@phren/cli 0.3.45 → 0.3.47
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.d.ts +7 -0
- package/dist/bridge/codex-auth-refresh.js +22 -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-write-policy.d.ts +13 -0
- package/dist/bridge/git-write-policy.js +39 -0
- 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 +7 -0
- package/dist/bridge/schedule-format.js +73 -2
- package/dist/bridge/schedule-problems.js +4 -0
- package/dist/bridge/schedule-update.d.ts +6 -0
- package/dist/bridge/schedule-update.js +63 -0
- package/dist/bridge/schedules.js +16 -4
- 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-pane-routes.d.ts +4 -2
- package/dist/bridge/server-pane-routes.js +8 -2
- package/dist/bridge/server-routes.js +14 -4
- 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 +1420 -553
- package/dist/cli/actions.js +4 -0
- 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/mcp/profile.js +23 -4
- package/dist/memory-ui-graph.runtime.js +1 -1
- package/dist/modules/registry.js +2 -2
- package/dist/sync/conflict-resolve.d.ts +1 -1
- package/dist/sync/conflict-resolve.js +91 -8
- package/dist/task/lifecycle.js +5 -3
- package/package.json +1 -1
package/dist/bridge-hook.mjs
CHANGED
|
@@ -386,10 +386,10 @@ function mergeDefs(...defs) {
|
|
|
386
386
|
function cloneDef(schema) {
|
|
387
387
|
return mergeDefs(schema._zod.def);
|
|
388
388
|
}
|
|
389
|
-
function getElementAtPath(obj3,
|
|
390
|
-
if (!
|
|
389
|
+
function getElementAtPath(obj3, path146) {
|
|
390
|
+
if (!path146)
|
|
391
391
|
return obj3;
|
|
392
|
-
return
|
|
392
|
+
return path146.reduce((acc, key4) => acc?.[key4], obj3);
|
|
393
393
|
}
|
|
394
394
|
function promiseAllObject(promisesObj) {
|
|
395
395
|
const keys2 = Object.keys(promisesObj);
|
|
@@ -648,11 +648,11 @@ function explicitlyAborted(x2, startIndex = 0) {
|
|
|
648
648
|
}
|
|
649
649
|
return false;
|
|
650
650
|
}
|
|
651
|
-
function prefixIssues(
|
|
651
|
+
function prefixIssues(path146, issues) {
|
|
652
652
|
return issues.map((iss) => {
|
|
653
653
|
var _a3;
|
|
654
654
|
(_a3 = iss).path ?? (_a3.path = []);
|
|
655
|
-
iss.path.unshift(
|
|
655
|
+
iss.path.unshift(path146);
|
|
656
656
|
return iss;
|
|
657
657
|
});
|
|
658
658
|
}
|
|
@@ -1173,16 +1173,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1173
1173
|
}
|
|
1174
1174
|
function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
1175
1175
|
const fieldErrors = { _errors: [] };
|
|
1176
|
-
const processError = (error63,
|
|
1176
|
+
const processError = (error63, path146 = []) => {
|
|
1177
1177
|
for (const issue2 of error63.issues) {
|
|
1178
1178
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1179
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1179
|
+
issue2.errors.map((issues) => processError({ issues }, [...path146, ...issue2.path]));
|
|
1180
1180
|
} else if (issue2.code === "invalid_key") {
|
|
1181
|
-
processError({ issues: issue2.issues }, [...
|
|
1181
|
+
processError({ issues: issue2.issues }, [...path146, ...issue2.path]);
|
|
1182
1182
|
} else if (issue2.code === "invalid_element") {
|
|
1183
|
-
processError({ issues: issue2.issues }, [...
|
|
1183
|
+
processError({ issues: issue2.issues }, [...path146, ...issue2.path]);
|
|
1184
1184
|
} else {
|
|
1185
|
-
const fullpath = [...
|
|
1185
|
+
const fullpath = [...path146, ...issue2.path];
|
|
1186
1186
|
if (fullpath.length === 0) {
|
|
1187
1187
|
fieldErrors._errors.push(mapper(issue2));
|
|
1188
1188
|
} else {
|
|
@@ -1221,17 +1221,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1221
1221
|
}
|
|
1222
1222
|
function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
1223
1223
|
const result = { errors: [] };
|
|
1224
|
-
const processError = (error63,
|
|
1224
|
+
const processError = (error63, path146 = []) => {
|
|
1225
1225
|
var _a3;
|
|
1226
1226
|
for (const issue2 of error63.issues) {
|
|
1227
1227
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1228
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1228
|
+
issue2.errors.map((issues) => processError({ issues }, [...path146, ...issue2.path]));
|
|
1229
1229
|
} else if (issue2.code === "invalid_key") {
|
|
1230
|
-
processError({ issues: issue2.issues }, [...
|
|
1230
|
+
processError({ issues: issue2.issues }, [...path146, ...issue2.path]);
|
|
1231
1231
|
} else if (issue2.code === "invalid_element") {
|
|
1232
|
-
processError({ issues: issue2.issues }, [...
|
|
1232
|
+
processError({ issues: issue2.issues }, [...path146, ...issue2.path]);
|
|
1233
1233
|
} else {
|
|
1234
|
-
const fullpath = [...
|
|
1234
|
+
const fullpath = [...path146, ...issue2.path];
|
|
1235
1235
|
if (fullpath.length === 0) {
|
|
1236
1236
|
result.errors.push(mapper(issue2));
|
|
1237
1237
|
continue;
|
|
@@ -1270,8 +1270,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1270
1270
|
}
|
|
1271
1271
|
function toDotPath(_path) {
|
|
1272
1272
|
const segs = [];
|
|
1273
|
-
const
|
|
1274
|
-
for (const seg of
|
|
1273
|
+
const path146 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
1274
|
+
for (const seg of path146) {
|
|
1275
1275
|
if (typeof seg === "number")
|
|
1276
1276
|
segs.push(`[${seg}]`);
|
|
1277
1277
|
else if (typeof seg === "symbol")
|
|
@@ -16755,8 +16755,8 @@ var init_json_schema_processors = __esm({
|
|
|
16755
16755
|
let minItems = def.items.length;
|
|
16756
16756
|
while (minItems > 0) {
|
|
16757
16757
|
const item = def.items[minItems - 1];
|
|
16758
|
-
const
|
|
16759
|
-
if (!
|
|
16758
|
+
const optional3 = ctx.io === "input" ? inputOptin(item) !== void 0 : item._zod.optout === "optional";
|
|
16759
|
+
if (!optional3)
|
|
16760
16760
|
break;
|
|
16761
16761
|
minItems--;
|
|
16762
16762
|
}
|
|
@@ -19267,13 +19267,13 @@ function resolveRef(ref, ctx) {
|
|
|
19267
19267
|
if (!ref.startsWith("#")) {
|
|
19268
19268
|
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
|
|
19269
19269
|
}
|
|
19270
|
-
const
|
|
19271
|
-
if (
|
|
19270
|
+
const path146 = ref.slice(1).split("/").filter(Boolean);
|
|
19271
|
+
if (path146.length === 0) {
|
|
19272
19272
|
return ctx.rootSchema;
|
|
19273
19273
|
}
|
|
19274
19274
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
19275
|
-
if (
|
|
19276
|
-
const key4 =
|
|
19275
|
+
if (path146[0] === defsKey) {
|
|
19276
|
+
const key4 = path146[1] === void 0 ? void 0 : decodeJSONPointerSegment(path146[1]);
|
|
19277
19277
|
if (!key4 || !ctx.defs[key4]) {
|
|
19278
19278
|
throw new Error(`Reference not found: ${ref}`);
|
|
19279
19279
|
}
|
|
@@ -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
|
}
|
|
@@ -29689,7 +29802,7 @@ var init_tab_activity = __esm({
|
|
|
29689
29802
|
await this.load();
|
|
29690
29803
|
const prefix = JSON.stringify(server) + ":";
|
|
29691
29804
|
const seen = /* @__PURE__ */ new Set(), times = /* @__PURE__ */ new Map();
|
|
29692
|
-
let
|
|
29805
|
+
let changed = false;
|
|
29693
29806
|
for (const tab of objects(snapshot2.tabs)) {
|
|
29694
29807
|
const tabKey = tabActivityKey(tab.workspace_id, tab.tab_id), key4 = prefix + tabKey;
|
|
29695
29808
|
seen.add(key4);
|
|
@@ -29699,17 +29812,17 @@ var init_tab_activity = __esm({
|
|
|
29699
29812
|
if (stamp2?.signature !== signature) {
|
|
29700
29813
|
stamp2 = { signature, lastChangedAt: at2 };
|
|
29701
29814
|
this.entries.set(key4, stamp2);
|
|
29702
|
-
|
|
29815
|
+
changed = true;
|
|
29703
29816
|
}
|
|
29704
29817
|
times.set(tabKey, stamp2.lastChangedAt);
|
|
29705
29818
|
}
|
|
29706
29819
|
for (const key4 of this.entries.keys()) {
|
|
29707
29820
|
if (key4.startsWith(prefix) && !seen.has(key4)) {
|
|
29708
29821
|
this.entries.delete(key4);
|
|
29709
|
-
|
|
29822
|
+
changed = true;
|
|
29710
29823
|
}
|
|
29711
29824
|
}
|
|
29712
|
-
this.dirty ||=
|
|
29825
|
+
this.dirty ||= changed;
|
|
29713
29826
|
await this.persist();
|
|
29714
29827
|
return times;
|
|
29715
29828
|
});
|
|
@@ -32179,7 +32292,7 @@ var require_websocket = __commonJS({
|
|
|
32179
32292
|
var http = __require("http");
|
|
32180
32293
|
var net2 = __require("net");
|
|
32181
32294
|
var tls = __require("tls");
|
|
32182
|
-
var { randomBytes:
|
|
32295
|
+
var { randomBytes: randomBytes11, createHash: createHash32 } = __require("crypto");
|
|
32183
32296
|
var { Duplex: Duplex2, Readable: Readable2 } = __require("stream");
|
|
32184
32297
|
var { URL: URL2 } = __require("url");
|
|
32185
32298
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -32730,7 +32843,7 @@ var require_websocket = __commonJS({
|
|
|
32730
32843
|
}
|
|
32731
32844
|
}
|
|
32732
32845
|
const defaultPort = isSecure ? 443 : 80;
|
|
32733
|
-
const key4 =
|
|
32846
|
+
const key4 = randomBytes11(16).toString("base64");
|
|
32734
32847
|
const request9 = isSecure ? https.request : http.request;
|
|
32735
32848
|
const protocolSet = /* @__PURE__ */ new Set();
|
|
32736
32849
|
let perMessageDeflate;
|
|
@@ -32860,7 +32973,7 @@ var require_websocket = __commonJS({
|
|
|
32860
32973
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
32861
32974
|
return;
|
|
32862
32975
|
}
|
|
32863
|
-
const digest2 =
|
|
32976
|
+
const digest2 = createHash32("sha1").update(key4 + GUID).digest("base64");
|
|
32864
32977
|
if (res.headers["sec-websocket-accept"] !== digest2) {
|
|
32865
32978
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
32866
32979
|
return;
|
|
@@ -33229,7 +33342,7 @@ var require_websocket_server = __commonJS({
|
|
|
33229
33342
|
var EventEmitter2 = __require("events");
|
|
33230
33343
|
var http = __require("http");
|
|
33231
33344
|
var { Duplex: Duplex2 } = __require("stream");
|
|
33232
|
-
var { createHash:
|
|
33345
|
+
var { createHash: createHash32 } = __require("crypto");
|
|
33233
33346
|
var extension2 = require_extension();
|
|
33234
33347
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
33235
33348
|
var subprotocol2 = require_subprotocol();
|
|
@@ -33536,7 +33649,7 @@ var require_websocket_server = __commonJS({
|
|
|
33536
33649
|
);
|
|
33537
33650
|
}
|
|
33538
33651
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
33539
|
-
const digest2 =
|
|
33652
|
+
const digest2 = createHash32("sha1").update(key4 + GUID).digest("base64");
|
|
33540
33653
|
const headers = [
|
|
33541
33654
|
"HTTP/1.1 101 Switching Protocols",
|
|
33542
33655
|
"Upgrade: websocket",
|
|
@@ -33694,6 +33807,8 @@ import path28 from "node:path";
|
|
|
33694
33807
|
async function spawnAppServer(options) {
|
|
33695
33808
|
const env = { ...options.replaceEnv ? {} : process.env, ...options.env ?? {}, ...options.codexHome ? { CODEX_HOME: options.codexHome } : {} };
|
|
33696
33809
|
const codexBin = options.codexBin ?? codexExecutable(env);
|
|
33810
|
+
const known2 = unixListenUnsupported.get(codexBin);
|
|
33811
|
+
if (known2) throw new AppServerUnsupportedError(known2);
|
|
33697
33812
|
await mkdir7(path28.dirname(options.socketPath), { recursive: true, mode: 448 });
|
|
33698
33813
|
await rm4(options.socketPath, { force: true });
|
|
33699
33814
|
const log2 = options.logFile ? await open8(options.logFile, "a", 384) : void 0;
|
|
@@ -33728,6 +33843,12 @@ async function spawnAppServer(options) {
|
|
|
33728
33843
|
while (true) {
|
|
33729
33844
|
if (failure2) throw new Error(`codex app-server could not start: ${failure2.message}`);
|
|
33730
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
|
+
}
|
|
33731
33852
|
throw new Error(`codex app-server exited before ${options.socketPath} was ready (${child.exitCode ?? child.signalCode})${await why()}`);
|
|
33732
33853
|
}
|
|
33733
33854
|
if (await socketAccepts(options.socketPath)) break;
|
|
@@ -33839,7 +33960,7 @@ function declineResult(method) {
|
|
|
33839
33960
|
return {};
|
|
33840
33961
|
}
|
|
33841
33962
|
}
|
|
33842
|
-
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;
|
|
33843
33964
|
var init_codex_app_server = __esm({
|
|
33844
33965
|
"src/bridge/codex-app-server.ts"() {
|
|
33845
33966
|
"use strict";
|
|
@@ -33860,6 +33981,9 @@ var init_codex_app_server = __esm({
|
|
|
33860
33981
|
code;
|
|
33861
33982
|
method;
|
|
33862
33983
|
};
|
|
33984
|
+
AppServerUnsupportedError = class extends Error {
|
|
33985
|
+
};
|
|
33986
|
+
unixListenUnsupported = /* @__PURE__ */ new Map();
|
|
33863
33987
|
AppServerConnection = class {
|
|
33864
33988
|
constructor(ws2) {
|
|
33865
33989
|
this.ws = ws2;
|
|
@@ -34742,8 +34866,15 @@ function claudeQuestionDialog(text5) {
|
|
|
34742
34866
|
}
|
|
34743
34867
|
async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
|
|
34744
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
|
+
} };
|
|
34745
34876
|
const sleep5 = io.sleep ?? ((ms2) => new Promise((resolve17) => setTimeout(resolve17, ms2)));
|
|
34746
|
-
const matches = (screen, index2) => screen?.kind === "question" && screen.title
|
|
34877
|
+
const matches = (screen, index2) => screen?.kind === "question" && sameTitle(screen.title, questions[index2].question);
|
|
34747
34878
|
const settle2 = async (check2, ms2 = 2e3) => {
|
|
34748
34879
|
for (let waited = 0; ; waited += 120) {
|
|
34749
34880
|
const value2 = check2(claudeQuestionDialog(await io.read()));
|
|
@@ -34757,8 +34888,8 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
34757
34888
|
if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
|
|
34758
34889
|
const reach = async (index2) => {
|
|
34759
34890
|
const screen = await settle2((value2) => value2);
|
|
34760
|
-
if (screen?.kind === "question" && screen.title
|
|
34761
|
-
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;
|
|
34762
34893
|
if (at2 < 0) throw changed("The terminal is showing a different question.");
|
|
34763
34894
|
if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number) await io.keys(["up"]);
|
|
34764
34895
|
await io.keys(Array(Math.abs(index2 - at2)).fill(index2 > at2 ? "right" : "left"));
|
|
@@ -34772,7 +34903,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
34772
34903
|
if (!question2) throw new BridgeError(400, "The answer names a question that was not asked.");
|
|
34773
34904
|
const typed = answer.text?.trim() ?? "";
|
|
34774
34905
|
let screen = await reach(index2);
|
|
34775
|
-
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))) {
|
|
34776
34907
|
throw changed("The terminal's options differ from the question being answered.");
|
|
34777
34908
|
}
|
|
34778
34909
|
if (!screen.multiSelect) {
|
|
@@ -34821,14 +34952,13 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
34821
34952
|
const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
|
|
34822
34953
|
if (review === "gone") return;
|
|
34823
34954
|
if (!review) throw changed("The terminal did not reach the review of the answers.");
|
|
34824
|
-
|
|
34825
|
-
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)) {
|
|
34826
34956
|
throw changed("Not every question has an answer in the terminal.");
|
|
34827
34957
|
}
|
|
34828
34958
|
await io.keys(["1"]);
|
|
34829
34959
|
if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
|
|
34830
34960
|
}
|
|
34831
|
-
var TAB_BAR, ROW, NEXT, normalize, GUTTER,
|
|
34961
|
+
var TAB_BAR, ROW, NEXT, normalize, sameTitle, sameLabel, GUTTER, refusal, typedKeys;
|
|
34832
34962
|
var init_claude_question_dialog = __esm({
|
|
34833
34963
|
"src/bridge/claude-question-dialog.ts"() {
|
|
34834
34964
|
"use strict";
|
|
@@ -34837,8 +34967,17 @@ var init_claude_question_dialog = __esm({
|
|
|
34837
34967
|
ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
|
|
34838
34968
|
NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
|
|
34839
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
|
+
};
|
|
34840
34979
|
GUTTER = /^(\s*)│(?: |$)/;
|
|
34841
|
-
|
|
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" });
|
|
34842
34981
|
typedKeys = (text5) => [...text5].map((character) => character === " " ? "space" : character);
|
|
34843
34982
|
}
|
|
34844
34983
|
});
|
|
@@ -36200,7 +36339,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, co
|
|
|
36200
36339
|
children: objects(s.tabs).filter((t) => t.workspace_id === w.workspace_id).map((t) => {
|
|
36201
36340
|
const panes2 = objects(s.panes).filter((p) => p.tab_id === t.tab_id && p.workspace_id === t.workspace_id);
|
|
36202
36341
|
const agent = panes2.find((p) => p.agent);
|
|
36203
|
-
const
|
|
36342
|
+
const changed = Math.max(0, ...panes2.map((p) => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
|
|
36204
36343
|
return {
|
|
36205
36344
|
id: t.tab_id,
|
|
36206
36345
|
label: t.label,
|
|
@@ -36210,7 +36349,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, co
|
|
|
36210
36349
|
agentStatus: t.agent_status,
|
|
36211
36350
|
cwd: agent?.foreground_cwd || agent?.cwd,
|
|
36212
36351
|
role: (conductorPane2 === void 0 ? isConductorName(paneAgentName(s, agent)) : !!agent && agent.pane_id === conductorPane2) ? "conductor" : void 0,
|
|
36213
|
-
changedSeq:
|
|
36352
|
+
changedSeq: changed || void 0,
|
|
36214
36353
|
lastChangedAt: lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id)),
|
|
36215
36354
|
approvalPending: panes2.some((p) => approvalPanes?.has(String(p.pane_id))) || void 0,
|
|
36216
36355
|
contextUsedPercent: agent && panes2.filter((p) => p.agent).length === 1 ? contextUsedPercent?.get(agent) : void 0,
|
|
@@ -37861,7 +38000,7 @@ var init_package_metadata = __esm({
|
|
|
37861
38000
|
__dirname = path37.dirname(fileURLToPath2(import.meta.url));
|
|
37862
38001
|
ROOT = path37.join(__dirname, "..");
|
|
37863
38002
|
PACKAGE_JSON_PATH = path37.join(ROOT, "package.json");
|
|
37864
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
38003
|
+
BUNDLED_VERSION = true ? "0.3.47" : "0.0.0";
|
|
37865
38004
|
PACKAGE_JSON = readPackageJson();
|
|
37866
38005
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
37867
38006
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -38836,7 +38975,7 @@ var init_registry = __esm({
|
|
|
38836
38975
|
init_package_metadata();
|
|
38837
38976
|
core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
|
|
38838
38977
|
full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
|
|
38839
|
-
routes = (method, paths) => paths.map((
|
|
38978
|
+
routes = (method, paths) => paths.map((path146) => ({ method, path: path146 }));
|
|
38840
38979
|
BUILTIN_MODULES = [
|
|
38841
38980
|
{
|
|
38842
38981
|
schemaVersion: 1,
|
|
@@ -39230,8 +39369,8 @@ var init_registry = __esm({
|
|
|
39230
39369
|
tools: [],
|
|
39231
39370
|
cliCommands: ["schedule"],
|
|
39232
39371
|
agentHooks: [],
|
|
39233
|
-
hookRoutes: routes("POST", ["/v1/schedules", "/v1/schedules/run", "/v1/schedules/history"]),
|
|
39234
|
-
capabilities: ["schedules", "scheduleProjects"],
|
|
39372
|
+
hookRoutes: routes("POST", ["/v1/schedules", "/v1/schedules/run", "/v1/schedules/history", "/v1/schedules/update"]),
|
|
39373
|
+
capabilities: ["schedules", "scheduleProjects", "scheduleUpdate"],
|
|
39235
39374
|
storeFiles: ["<project>/schedules.yaml", ".runtime/agent-fanouts/<run-id>/**"],
|
|
39236
39375
|
localFiles: ["<bridge>/schedule-runs.jsonl"],
|
|
39237
39376
|
phoneScreens: [{ screen: "SchedulesView", capability: "schedules" }],
|
|
@@ -40371,6 +40510,14 @@ function settleClaudeUsage(usage, now) {
|
|
|
40371
40510
|
const since = usage.updatedAt?.slice(0, 10);
|
|
40372
40511
|
return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
|
|
40373
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
|
+
}
|
|
40374
40521
|
function usageStatusLine(current2, program, remove) {
|
|
40375
40522
|
const prefix = `${quote2(process.execPath)} ${quote2(program)} usage-statusline `;
|
|
40376
40523
|
const command = object2(current2).command;
|
|
@@ -40417,7 +40564,7 @@ async function captureClaudeUsage(original) {
|
|
|
40417
40564
|
});
|
|
40418
40565
|
}
|
|
40419
40566
|
}
|
|
40420
|
-
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;
|
|
40421
40568
|
var init_usage = __esm({
|
|
40422
40569
|
"src/bridge/usage.ts"() {
|
|
40423
40570
|
"use strict";
|
|
@@ -40453,6 +40600,8 @@ var init_usage = __esm({
|
|
|
40453
40600
|
isCreditWindow = (window2) => window2.id.startsWith("credit:");
|
|
40454
40601
|
CLAUDE_REPORT_MAX_AGE_MS = 3 * 864e5;
|
|
40455
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.` });
|
|
40456
40605
|
AccountUsageReader = class {
|
|
40457
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)) {
|
|
40458
40607
|
this.readCodex = readCodex;
|
|
@@ -40496,7 +40645,7 @@ var init_usage = __esm({
|
|
|
40496
40645
|
/** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
|
|
40497
40646
|
async limits(allAccounts = true) {
|
|
40498
40647
|
if (!this.cached || this.now() - this.cached.at >= 6e4) {
|
|
40499
|
-
this.pending ??= this.readCodex().then((value2) => {
|
|
40648
|
+
this.pending ??= bounded(this.readCodex(), () => unanswered("codex", "Codex")).then((value2) => {
|
|
40500
40649
|
this.cached = { at: this.now(), value: value2 };
|
|
40501
40650
|
return value2;
|
|
40502
40651
|
}).finally(() => {
|
|
@@ -40509,7 +40658,7 @@ var init_usage = __esm({
|
|
|
40509
40658
|
const now = new Date(this.now());
|
|
40510
40659
|
const email3 = claudeAccountEmail(home);
|
|
40511
40660
|
const credits = claudeCredits(home.id);
|
|
40512
|
-
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;
|
|
40513
40662
|
const fallback2 = auth?.console ? "Console" : auth?.plan ? claudePlan({ subscriptionType: auth.plan }) : void 0;
|
|
40514
40663
|
const subscription2 = claudeAccountSubscription(home, now, fallback2);
|
|
40515
40664
|
const usage = settleClaudeUsage(await this.claude(home), this.now());
|
|
@@ -40529,10 +40678,10 @@ var init_usage = __esm({
|
|
|
40529
40678
|
if (!this.spendingPending.has(key4)) {
|
|
40530
40679
|
const pending = Promise.all([
|
|
40531
40680
|
this.openCode(at2),
|
|
40532
|
-
this.readOpenCodeGo(new Date(at2)),
|
|
40533
|
-
this.readOpenRouter(new Date(at2)),
|
|
40534
|
-
includeCopilot ? this.readCopilot(new Date(at2)) : Promise.resolve(void 0),
|
|
40535
|
-
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)
|
|
40536
40685
|
]).then(([openCode, openCodeGo, openRouter, copilot, elevenLabs2]) => [openCode, openCodeGo, ...openRouter ? [openRouter] : [], ...copilot ? [copilot] : [], ...elevenLabs2 ? [elevenLabs2] : []]).then((value2) => {
|
|
40537
40686
|
this.spendingCached.set(key4, { at: at2, value: value2 });
|
|
40538
40687
|
return value2;
|
|
@@ -40547,8 +40696,12 @@ var init_usage = __esm({
|
|
|
40547
40696
|
/** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
|
|
40548
40697
|
openCode(at2) {
|
|
40549
40698
|
if (this.openCodeCached && at2 - this.openCodeCached.at < OPENCODE_STATS_REUSE_MS) return Promise.resolve(this.openCodeCached.value);
|
|
40550
|
-
|
|
40551
|
-
|
|
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 };
|
|
40552
40705
|
return value2;
|
|
40553
40706
|
}).finally(() => {
|
|
40554
40707
|
this.openCodePending = void 0;
|
|
@@ -40564,7 +40717,7 @@ var init_usage = __esm({
|
|
|
40564
40717
|
const cached3 = this.claudeCached.get(home.dir);
|
|
40565
40718
|
if (!cached3 || this.now() - cached3.at >= 6e4) {
|
|
40566
40719
|
const at2 = this.now();
|
|
40567
|
-
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) => {
|
|
40568
40721
|
this.claudeCached.set(home.dir, { at: at2, value: value2 });
|
|
40569
40722
|
return value2;
|
|
40570
40723
|
}).catch(() => {
|
|
@@ -40643,9 +40796,9 @@ async function mergeMcpServers(file4, servers2) {
|
|
|
40643
40796
|
async function syncAccountMcpServers(env = process.env) {
|
|
40644
40797
|
const homes = claudeHomes(env);
|
|
40645
40798
|
const servers2 = await mcpServersOf(homes[0].configFile);
|
|
40646
|
-
const
|
|
40647
|
-
for (const home of homes.slice(1)) if (await mergeMcpServers(home.configFile, servers2))
|
|
40648
|
-
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;
|
|
40649
40802
|
}
|
|
40650
40803
|
async function addClaudeAccount(slug, opts = {}) {
|
|
40651
40804
|
const env = opts.env ?? process.env;
|
|
@@ -41398,7 +41551,7 @@ function keyOptions(line) {
|
|
|
41398
41551
|
return void 0;
|
|
41399
41552
|
}
|
|
41400
41553
|
function upgradeKeys(text5) {
|
|
41401
|
-
let
|
|
41554
|
+
let changed = 0;
|
|
41402
41555
|
const result = text5.split(/(?<=\n)/).map((line) => {
|
|
41403
41556
|
const parsed = keyOptions(line);
|
|
41404
41557
|
if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest)) return line;
|
|
@@ -41407,10 +41560,10 @@ function upgradeKeys(text5) {
|
|
|
41407
41560
|
const options = parsed.options.filter((option) => option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen=")).map((option) => old.test(option) ? forcedCommand : option);
|
|
41408
41561
|
if (!options.includes("pty")) options.splice(1, 0, "pty");
|
|
41409
41562
|
const next = options.join(",") + parsed.rest;
|
|
41410
|
-
if (next !== line)
|
|
41563
|
+
if (next !== line) changed++;
|
|
41411
41564
|
return next;
|
|
41412
41565
|
}).join("");
|
|
41413
|
-
return { text: result, changed
|
|
41566
|
+
return { text: result, changed };
|
|
41414
41567
|
}
|
|
41415
41568
|
async function extraLaunchAgentEnvironment(file4, read = async (f) => (await exec8("plutil", ["-convert", "json", "-o", "-", f])).stdout) {
|
|
41416
41569
|
let parsed;
|
|
@@ -42097,6 +42250,33 @@ async function hookPeers(root = bridgeRoot()) {
|
|
|
42097
42250
|
}
|
|
42098
42251
|
async function addHookPeer(input2, root = bridgeRoot()) {
|
|
42099
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) {
|
|
42100
42280
|
const existing = await hookPeers(root).catch((error62) => {
|
|
42101
42281
|
if (error62 instanceof BridgeError && error62.details?.hooksYaml === "missing") return [];
|
|
42102
42282
|
throw error62;
|
|
@@ -42242,12 +42422,13 @@ async function peerRequest(peer, route2, data, timeout) {
|
|
|
42242
42422
|
await rm8(temporary, { recursive: true, force: true });
|
|
42243
42423
|
}
|
|
42244
42424
|
}
|
|
42245
|
-
var peerSchema, lastPeerError;
|
|
42425
|
+
var peerSchema, hooksYamlQueues, HOOKS_YAML_LOCK_WAIT_MS, lastPeerError;
|
|
42246
42426
|
var init_peers = __esm({
|
|
42247
42427
|
"src/bridge/peers.ts"() {
|
|
42248
42428
|
"use strict";
|
|
42249
42429
|
init_js_yaml();
|
|
42250
42430
|
init_zod();
|
|
42431
|
+
init_locks();
|
|
42251
42432
|
init_logger();
|
|
42252
42433
|
init_client();
|
|
42253
42434
|
init_computers();
|
|
@@ -42260,6 +42441,8 @@ var init_peers = __esm({
|
|
|
42260
42441
|
hostKey: external_exports.string().transform(publicComputerKey),
|
|
42261
42442
|
server: serverName.default("default")
|
|
42262
42443
|
}).strict();
|
|
42444
|
+
hooksYamlQueues = /* @__PURE__ */ new Map();
|
|
42445
|
+
HOOKS_YAML_LOCK_WAIT_MS = 5e3;
|
|
42263
42446
|
}
|
|
42264
42447
|
});
|
|
42265
42448
|
|
|
@@ -42298,7 +42481,9 @@ var init_computer_names = __esm({
|
|
|
42298
42481
|
});
|
|
42299
42482
|
|
|
42300
42483
|
// src/bridge/schedule-format.ts
|
|
42484
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
42301
42485
|
import { readFile as readFile27 } from "node:fs/promises";
|
|
42486
|
+
import { mkdirSync as mkdirSync11, readFileSync as readFileSync25, renameSync as renameSync7, unlinkSync as unlinkSync4, writeFileSync as writeFileSync11 } from "node:fs";
|
|
42302
42487
|
import path56 from "node:path";
|
|
42303
42488
|
function validateLocalTimestamp(value2) {
|
|
42304
42489
|
localTimestamp.parse(value2);
|
|
@@ -42360,6 +42545,19 @@ async function readScheduleDocument(projectDir) {
|
|
|
42360
42545
|
if (error62.code === "ENOENT") return { document: { version: 1 }, schedules: [] };
|
|
42361
42546
|
throw error62;
|
|
42362
42547
|
}
|
|
42548
|
+
return parseScheduleDocument(text5);
|
|
42549
|
+
}
|
|
42550
|
+
function readScheduleDocumentSync(projectDir) {
|
|
42551
|
+
let text5;
|
|
42552
|
+
try {
|
|
42553
|
+
text5 = readFileSync25(schedulePath(projectDir), "utf8");
|
|
42554
|
+
} catch (error62) {
|
|
42555
|
+
if (error62.code === "ENOENT") return { document: { version: 1 }, schedules: [] };
|
|
42556
|
+
throw error62;
|
|
42557
|
+
}
|
|
42558
|
+
return parseScheduleDocument(text5);
|
|
42559
|
+
}
|
|
42560
|
+
function parseScheduleDocument(text5) {
|
|
42363
42561
|
const document = object2(load(text5, { schema: CORE_SCHEMA }));
|
|
42364
42562
|
if (document.version !== 1) throw new Error("schedules.yaml must have version: 1.");
|
|
42365
42563
|
if (!Array.isArray(document.schedules)) throw new Error("schedules.yaml must contain a schedules list.");
|
|
@@ -42368,11 +42566,49 @@ async function readScheduleDocument(projectDir) {
|
|
|
42368
42566
|
if (new Set(schedules.map((item) => item.id)).size !== schedules.length) throw new Error("Schedule IDs must be unique within a project.");
|
|
42369
42567
|
return { document, schedules };
|
|
42370
42568
|
}
|
|
42371
|
-
async function
|
|
42569
|
+
async function withScheduleLock(projectDir, work) {
|
|
42570
|
+
const file4 = path56.resolve(schedulePath(projectDir));
|
|
42571
|
+
const previous = scheduleQueues.get(file4) ?? Promise.resolve();
|
|
42572
|
+
const next = previous.catch(() => void 0).then(async () => {
|
|
42573
|
+
const deadline = Date.now() + SCHEDULE_LOCK_WAIT_MS;
|
|
42574
|
+
let release = tryFileLock(file4);
|
|
42575
|
+
while (!release) {
|
|
42576
|
+
if (Date.now() >= deadline) throw new Error("schedules.yaml is being changed elsewhere. Try again.");
|
|
42577
|
+
await new Promise((resolve17) => setTimeout(resolve17, 50));
|
|
42578
|
+
release = tryFileLock(file4);
|
|
42579
|
+
}
|
|
42580
|
+
try {
|
|
42581
|
+
const result = work();
|
|
42582
|
+
return result instanceof Promise ? await result : result;
|
|
42583
|
+
} finally {
|
|
42584
|
+
release();
|
|
42585
|
+
}
|
|
42586
|
+
});
|
|
42587
|
+
scheduleQueues.set(file4, next);
|
|
42588
|
+
try {
|
|
42589
|
+
return await next;
|
|
42590
|
+
} finally {
|
|
42591
|
+
if (scheduleQueues.get(file4) === next) scheduleQueues.delete(file4);
|
|
42592
|
+
}
|
|
42593
|
+
}
|
|
42594
|
+
function writeScheduleDocumentSync(projectDir, schedules, original = { version: 1 }) {
|
|
42595
|
+
const text5 = serializeScheduleDocument(schedules, original), file4 = schedulePath(projectDir);
|
|
42596
|
+
mkdirSync11(projectDir, { recursive: true, mode: 448 });
|
|
42597
|
+
const temporary = `${file4}.${randomBytes4(8).toString("hex")}.tmp`;
|
|
42598
|
+
try {
|
|
42599
|
+
writeFileSync11(temporary, text5, { mode: 384, flag: "wx" });
|
|
42600
|
+
renameSync7(temporary, file4);
|
|
42601
|
+
} finally {
|
|
42602
|
+
try {
|
|
42603
|
+
unlinkSync4(temporary);
|
|
42604
|
+
} catch {
|
|
42605
|
+
}
|
|
42606
|
+
}
|
|
42607
|
+
}
|
|
42608
|
+
function serializeScheduleDocument(schedules, original) {
|
|
42372
42609
|
if (schedules.length > MAX_SCHEDULES) throw new Error(`A project can have at most ${MAX_SCHEDULES} schedules.`);
|
|
42373
42610
|
schedules.forEach(parseSchedule);
|
|
42374
|
-
|
|
42375
|
-
await atomicInPrivateDir(schedulePath(projectDir), text5);
|
|
42611
|
+
return dump({ ...original, version: 1, schedules }, { lineWidth: 1e3, noRefs: true, sortKeys: false });
|
|
42376
42612
|
}
|
|
42377
42613
|
function canonicalComputer(value2) {
|
|
42378
42614
|
const normalized = value2.trim().toLowerCase();
|
|
@@ -42529,7 +42765,7 @@ async function writeScheduleRuns(file4, runs) {
|
|
|
42529
42765
|
function scheduleRunsFile() {
|
|
42530
42766
|
return path56.join(bridgeRoot(), "schedule-runs.jsonl");
|
|
42531
42767
|
}
|
|
42532
|
-
var SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_NOTIFY, WEEKDAYS, SCHEDULE_SESSIONS, SCHEDULE_RUN_STATUSES, scheduleId, plain, singleLine, scheduleName, timestamp2, localTimestamp, clockTime, schedulePath, runningStatuses, MAX_SCHEDULES, MAX_RUNS, REUSE_PANES;
|
|
42768
|
+
var SCHEDULE_EVERY, SCHEDULE_HARNESSES, SCHEDULE_NOTIFY, WEEKDAYS, SCHEDULE_SESSIONS, SCHEDULE_RUN_STATUSES, scheduleId, plain, singleLine, scheduleName, timestamp2, localTimestamp, clockTime, schedulePath, runningStatuses, MAX_SCHEDULES, MAX_RUNS, scheduleQueues, SCHEDULE_LOCK_WAIT_MS, REUSE_PANES;
|
|
42533
42769
|
var init_schedule_format = __esm({
|
|
42534
42770
|
"src/bridge/schedule-format.ts"() {
|
|
42535
42771
|
"use strict";
|
|
@@ -42537,6 +42773,7 @@ var init_schedule_format = __esm({
|
|
|
42537
42773
|
init_zod();
|
|
42538
42774
|
init_protocol();
|
|
42539
42775
|
init_utils_paths();
|
|
42776
|
+
init_locks();
|
|
42540
42777
|
init_claude_accounts();
|
|
42541
42778
|
SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
42542
42779
|
SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
|
|
@@ -42555,6 +42792,8 @@ var init_schedule_format = __esm({
|
|
|
42555
42792
|
runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
|
|
42556
42793
|
MAX_SCHEDULES = 64;
|
|
42557
42794
|
MAX_RUNS = 2e3;
|
|
42795
|
+
scheduleQueues = /* @__PURE__ */ new Map();
|
|
42796
|
+
SCHEDULE_LOCK_WAIT_MS = 5e3;
|
|
42558
42797
|
REUSE_PANES = 8;
|
|
42559
42798
|
}
|
|
42560
42799
|
});
|
|
@@ -42564,6 +42803,9 @@ import { stat as stat15 } from "node:fs/promises";
|
|
|
42564
42803
|
import path57 from "node:path";
|
|
42565
42804
|
async function scheduleProblems(schedule, project, options) {
|
|
42566
42805
|
const problems = [];
|
|
42806
|
+
if ((schedule.prompt.match(/[\p{L}\p{N}]/gu) ?? []).length < 3) {
|
|
42807
|
+
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.");
|
|
42808
|
+
}
|
|
42567
42809
|
const machines = listMachines(options.store);
|
|
42568
42810
|
if (!options.owned && machines.ok && !Object.keys(machines.data).some((name) => canonicalComputer(name) === canonicalComputer(schedule.computer))) {
|
|
42569
42811
|
problems.push(`Computer "${schedule.computer}" is not a machine in this store, so no Hook will run this schedule.`);
|
|
@@ -43052,10 +43294,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
43052
43294
|
for (const value2 of values.slice(0, 128)) {
|
|
43053
43295
|
if (state.count >= 128) break;
|
|
43054
43296
|
const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
43055
|
-
const
|
|
43297
|
+
const path146 = publicLabel(raw.path);
|
|
43056
43298
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
43057
43299
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
43058
|
-
if (!id2.success || !source.success || !
|
|
43300
|
+
if (!id2.success || !source.success || !path146 || !callId || !routed) continue;
|
|
43059
43301
|
const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
|
|
43060
43302
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
43061
43303
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -43068,7 +43310,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
43068
43310
|
projected.push({
|
|
43069
43311
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
43070
43312
|
provider: source.data,
|
|
43071
|
-
path:
|
|
43313
|
+
path: path146,
|
|
43072
43314
|
callId,
|
|
43073
43315
|
state: raw.failed === true ? "failed" : childState,
|
|
43074
43316
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -43840,7 +44082,7 @@ var init_conductor_group = __esm({
|
|
|
43840
44082
|
});
|
|
43841
44083
|
|
|
43842
44084
|
// src/bridge/conductor-role.ts
|
|
43843
|
-
import { lstatSync as lstatSync2, readFileSync as
|
|
44085
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync26 } from "node:fs";
|
|
43844
44086
|
import path60 from "node:path";
|
|
43845
44087
|
async function readRoleState() {
|
|
43846
44088
|
const file4 = roleFile();
|
|
@@ -43848,7 +44090,7 @@ async function readRoleState() {
|
|
|
43848
44090
|
let text5;
|
|
43849
44091
|
try {
|
|
43850
44092
|
const info = lstatSync2(file4);
|
|
43851
|
-
text5 = info.isFile() && info.size <= 65536 ?
|
|
44093
|
+
text5 = info.isFile() && info.size <= 65536 ? readFileSync26(file4, "utf8") : "";
|
|
43852
44094
|
} catch {
|
|
43853
44095
|
text5 = void 0;
|
|
43854
44096
|
}
|
|
@@ -44749,8 +44991,8 @@ async function readIntegrator() {
|
|
|
44749
44991
|
}
|
|
44750
44992
|
async function setIntegrator(input2) {
|
|
44751
44993
|
if (input2 === null) {
|
|
44752
|
-
const { rm:
|
|
44753
|
-
await
|
|
44994
|
+
const { rm: rm18 } = await import("node:fs/promises");
|
|
44995
|
+
await rm18(path62.join(bridgeRoot(), "integrator.json"), { force: true });
|
|
44754
44996
|
return { ok: true, integrator: null };
|
|
44755
44997
|
}
|
|
44756
44998
|
const data = integratorSchema.parse(input2);
|
|
@@ -44982,11 +45224,11 @@ function approvalSummary(value2) {
|
|
|
44982
45224
|
requestKind = "tool";
|
|
44983
45225
|
} else {
|
|
44984
45226
|
const patch = string4(input2.patch) ?? (typeof value2.input === "string" ? value2.input : void 0);
|
|
44985
|
-
const
|
|
45227
|
+
const changed = patch ? new Set([...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$|^diff --git a\/(.+?) b\/(.+)$/gm)].map((match) => match[1] ?? match[3])).size : 0;
|
|
44986
45228
|
const file4 = string4(input2.file_path) ?? string4(input2.filePath) ?? string4(input2.path);
|
|
44987
|
-
if (
|
|
45229
|
+
if (changed > 1) line = `Apply patch: ${changed} files`;
|
|
44988
45230
|
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)}`;
|
|
44989
|
-
else if (
|
|
45231
|
+
else if (changed === 1 && patch) {
|
|
44990
45232
|
const match = /^\*\*\* (Add|Update|Delete) File: (.+)$/m.exec(patch);
|
|
44991
45233
|
line = match ? `${match[1] === "Add" ? "Write" : "Edit"}: ${relativeFile(match[2], value2.cwd)}` : "Apply patch: 1 file";
|
|
44992
45234
|
}
|
|
@@ -46308,7 +46550,7 @@ function observeApproval(receipt, value2, now) {
|
|
|
46308
46550
|
function observeState(receipt, parsed, now) {
|
|
46309
46551
|
let seen = parsed;
|
|
46310
46552
|
const at2 = new Date(now).toISOString();
|
|
46311
|
-
let
|
|
46553
|
+
let changed = false;
|
|
46312
46554
|
if (seen.session && receipt.target && !("session" in receipt.target)) {
|
|
46313
46555
|
const full2 = targetSchema.safeParse({
|
|
46314
46556
|
server: receipt.target.server,
|
|
@@ -46320,7 +46562,7 @@ function observeState(receipt, parsed, now) {
|
|
|
46320
46562
|
});
|
|
46321
46563
|
if (full2.success) {
|
|
46322
46564
|
receipt.target = full2.data;
|
|
46323
|
-
|
|
46565
|
+
changed = true;
|
|
46324
46566
|
}
|
|
46325
46567
|
}
|
|
46326
46568
|
const carried = seen.state === "working" && receipt.worker && receipt.worker.state !== "working" ? 0 : receipt.worker?.background ?? 0;
|
|
@@ -46348,18 +46590,18 @@ function observeState(receipt, parsed, now) {
|
|
|
46348
46590
|
if (repeated) {
|
|
46349
46591
|
if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
|
|
46350
46592
|
receipt.worker.sawWorking = sawWorking;
|
|
46351
|
-
|
|
46593
|
+
changed = true;
|
|
46352
46594
|
}
|
|
46353
46595
|
if (receipt.worker && background > (receipt.worker.background ?? 0)) {
|
|
46354
46596
|
receipt.worker.background = background;
|
|
46355
|
-
|
|
46597
|
+
changed = true;
|
|
46356
46598
|
}
|
|
46357
46599
|
if (receipt.worker && receipt.worker.waitingSince !== waitingSince) {
|
|
46358
46600
|
if (waitingSince) receipt.worker.waitingSince = waitingSince;
|
|
46359
46601
|
else delete receipt.worker.waitingSince;
|
|
46360
|
-
|
|
46602
|
+
changed = true;
|
|
46361
46603
|
}
|
|
46362
|
-
return
|
|
46604
|
+
return changed;
|
|
46363
46605
|
}
|
|
46364
46606
|
receipt.worker = {
|
|
46365
46607
|
state: next,
|
|
@@ -46681,9 +46923,9 @@ var init_dispatch_returns = __esm({
|
|
|
46681
46923
|
const seen = await this.grantAnswered(receipt, workers[index2]);
|
|
46682
46924
|
let fresh;
|
|
46683
46925
|
const current2 = await updateReceipt(receipt.id, (value2) => {
|
|
46684
|
-
const before = value2.approval?.actionId,
|
|
46926
|
+
const before = value2.approval?.actionId, changed = observe(value2, seen, this.now());
|
|
46685
46927
|
if (value2.approval && value2.approval.actionId !== before) fresh = value2.approval;
|
|
46686
|
-
return
|
|
46928
|
+
return changed;
|
|
46687
46929
|
}).catch(() => void 0);
|
|
46688
46930
|
if (!fresh || !current2) continue;
|
|
46689
46931
|
const pushed = await Promise.resolve(this.onApproval?.(current2, fresh)).catch(() => void 0);
|
|
@@ -47365,7 +47607,7 @@ var init_schedules = __esm({
|
|
|
47365
47607
|
const projectDir = this.projectDirectory(projectName2), project = path68.basename(projectDir);
|
|
47366
47608
|
const file4 = await readScheduleDocument(projectDir), schedule = file4.schedules.find((item) => item.id === id2);
|
|
47367
47609
|
if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
|
|
47368
|
-
if (expectedUpdatedAt !== void 0 &&
|
|
47610
|
+
if (expectedUpdatedAt !== void 0 && expectedUpdatedAt !== schedule.updatedAt) {
|
|
47369
47611
|
throw new BridgeError(409, "This computer has a different schedule revision. Wait for store sync to finish, refresh the schedule, and try Run now again.");
|
|
47370
47612
|
}
|
|
47371
47613
|
if (!this.owns(schedule)) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
@@ -47405,9 +47647,21 @@ var init_schedules = __esm({
|
|
|
47405
47647
|
await writeScheduleRuns(this.runsFile, [...runs, ...children.map((child) => child.run)]);
|
|
47406
47648
|
for (const child of children) this.own.add(child.run.id);
|
|
47407
47649
|
if (schedule.every === "once" && schedule.enabled) {
|
|
47408
|
-
const schedules = file4.schedules.map((item) => item.id === id2 ? { ...item, enabled: false, updatedAt: startedAt2 } : item);
|
|
47409
47650
|
try {
|
|
47410
|
-
await
|
|
47651
|
+
await withScheduleLock(projectDir, () => {
|
|
47652
|
+
const current2 = readScheduleDocumentSync(projectDir);
|
|
47653
|
+
const schedules = current2.document.schedules ?? [];
|
|
47654
|
+
const index2 = schedules.findIndex((item) => item.id === id2);
|
|
47655
|
+
if (index2 < 0) return;
|
|
47656
|
+
const occurrence = schedules[index2];
|
|
47657
|
+
if (occurrence.every !== "once" || occurrence.once !== schedule.once || occurrence.updatedAt !== schedule.updatedAt) return;
|
|
47658
|
+
schedules[index2] = {
|
|
47659
|
+
...schedules[index2],
|
|
47660
|
+
enabled: false,
|
|
47661
|
+
updatedAt: new Date(Math.max(this.now().getTime(), Date.parse(schedules[index2].updatedAt) + 1)).toISOString()
|
|
47662
|
+
};
|
|
47663
|
+
writeScheduleDocumentSync(projectDir, schedules, current2.document);
|
|
47664
|
+
});
|
|
47411
47665
|
} catch (error62) {
|
|
47412
47666
|
this.log(`[schedule] Could not disable consumed once schedule ${project}/${id2}: ${String(error62)}`);
|
|
47413
47667
|
}
|
|
@@ -48735,10 +48989,12 @@ function unionTrailing(ourTrailing, theirTrailing) {
|
|
|
48735
48989
|
function significantLines(content) {
|
|
48736
48990
|
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())));
|
|
48737
48991
|
}
|
|
48738
|
-
function mergeFindings(ours, theirs) {
|
|
48739
|
-
const
|
|
48992
|
+
function mergeFindings(ours, theirs, base) {
|
|
48993
|
+
const removed = base === void 0 ? /* @__PURE__ */ new Map() : removedFindings(base, ours, theirs);
|
|
48994
|
+
const { text: text5, dedupedContinuations } = buildMergedFindings(ours, theirs, removed);
|
|
48995
|
+
const removedLines = new Set([...removed.values()].flatMap((block) => block.split("\n").map((line) => line.trim())));
|
|
48740
48996
|
const present2 = new Set(text5.split("\n").map((line) => line.trim()));
|
|
48741
|
-
const lost = [...significantLines(ours), ...significantLines(theirs)].filter((line) => !present2.has(line)).filter((line) => !dedupedContinuations.has(line));
|
|
48997
|
+
const lost = [...significantLines(ours), ...significantLines(theirs)].filter((line) => !present2.has(line)).filter((line) => !dedupedContinuations.has(line)).filter((line) => !removedLines.has(line));
|
|
48742
48998
|
if (lost.length > 0) {
|
|
48743
48999
|
throw new FindingsMergeLossError(
|
|
48744
49000
|
`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.`
|
|
@@ -48746,7 +49002,20 @@ function mergeFindings(ours, theirs) {
|
|
|
48746
49002
|
}
|
|
48747
49003
|
return text5;
|
|
48748
49004
|
}
|
|
48749
|
-
function
|
|
49005
|
+
function removedFindings(base, ours, theirs) {
|
|
49006
|
+
const blocks = (content) => {
|
|
49007
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
49008
|
+
for (const list of parseFindings(content).dates.values()) for (const block of list) byKey.set(findingBulletText(block), block);
|
|
49009
|
+
return byKey;
|
|
49010
|
+
};
|
|
49011
|
+
const [b, o, t] = [blocks(base), blocks(ours), blocks(theirs)];
|
|
49012
|
+
const removed = /* @__PURE__ */ new Map();
|
|
49013
|
+
for (const [key4, block] of b) {
|
|
49014
|
+
if (!o.has(key4) && t.get(key4) === block || !t.has(key4) && o.get(key4) === block) removed.set(key4, block);
|
|
49015
|
+
}
|
|
49016
|
+
return removed;
|
|
49017
|
+
}
|
|
49018
|
+
function buildMergedFindings(ours, theirs, removed = /* @__PURE__ */ new Map()) {
|
|
48750
49019
|
const ourSide = parseFindings(ours);
|
|
48751
49020
|
const theirSide = parseFindings(theirs);
|
|
48752
49021
|
const allDates = [.../* @__PURE__ */ new Set([...ourSide.dates.keys(), ...theirSide.dates.keys()])].sort().reverse();
|
|
@@ -48760,6 +49029,7 @@ function buildMergedFindings(ours, theirs) {
|
|
|
48760
49029
|
const merged = [];
|
|
48761
49030
|
for (const block of [...ourSide.dates.get(date5) ?? [], ...theirSide.dates.get(date5) ?? []]) {
|
|
48762
49031
|
const key4 = findingBulletText(block);
|
|
49032
|
+
if (removed.has(key4)) continue;
|
|
48763
49033
|
if (seen.has(key4)) {
|
|
48764
49034
|
for (const line of block.split("\n").slice(1)) {
|
|
48765
49035
|
const trimmed = line.trim();
|
|
@@ -49239,7 +49509,8 @@ var init_task_format = __esm({
|
|
|
49239
49509
|
// src/bridge/memory-store.ts
|
|
49240
49510
|
import { execFile as execFile16, spawn as spawn8 } from "node:child_process";
|
|
49241
49511
|
import { createHash as createHash21 } from "node:crypto";
|
|
49242
|
-
import {
|
|
49512
|
+
import { mkdirSync as mkdirSync17, readFileSync as readFileSync33, renameSync as renameSync10, unlinkSync as unlinkSync7, writeFileSync as writeFileSync15 } from "node:fs";
|
|
49513
|
+
import { lstat as lstat21, mkdir as mkdir21, realpath as realpath11 } from "node:fs/promises";
|
|
49243
49514
|
import path75 from "node:path";
|
|
49244
49515
|
import { promisify as promisify14 } from "node:util";
|
|
49245
49516
|
function serialized2(work) {
|
|
@@ -49416,12 +49687,21 @@ async function storeFile(store, relative5) {
|
|
|
49416
49687
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
49417
49688
|
return file4;
|
|
49418
49689
|
}
|
|
49419
|
-
|
|
49420
|
-
|
|
49690
|
+
function lockedStoreFile(file4, rel, work) {
|
|
49691
|
+
try {
|
|
49692
|
+
withFileLock(file4, work);
|
|
49693
|
+
} catch (error62) {
|
|
49694
|
+
if (error62 instanceof BridgeError || !/could not acquire lock/.test(String(error62?.message))) throw error62;
|
|
49695
|
+
throw new BridgeError(409, `${rel} is being written on this computer (its lock is held). Try again.`);
|
|
49696
|
+
}
|
|
49697
|
+
}
|
|
49698
|
+
function currentShaSync(file4) {
|
|
49699
|
+
try {
|
|
49700
|
+
return blobSha(readFileSync33(file4));
|
|
49701
|
+
} catch (error62) {
|
|
49421
49702
|
if (error62.code === "ENOENT") return null;
|
|
49422
49703
|
throw error62;
|
|
49423
|
-
}
|
|
49424
|
-
return content === null ? null : blobSha(content);
|
|
49704
|
+
}
|
|
49425
49705
|
}
|
|
49426
49706
|
function putStoreFile(store, data) {
|
|
49427
49707
|
const input2 = putSchema.parse(data);
|
|
@@ -49429,11 +49709,13 @@ function putStoreFile(store, data) {
|
|
|
49429
49709
|
if (content.length > MAX_FILE) throw new BridgeError(413, "This file is too large for the phone to write.");
|
|
49430
49710
|
return serialized2(async () => {
|
|
49431
49711
|
const file4 = await storeFile(store, input2.path);
|
|
49432
|
-
|
|
49433
|
-
|
|
49434
|
-
|
|
49435
|
-
|
|
49436
|
-
|
|
49712
|
+
lockedStoreFile(file4, input2.path, () => {
|
|
49713
|
+
if (currentShaSync(file4) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
49714
|
+
mkdirSync17(path75.dirname(file4), { recursive: true });
|
|
49715
|
+
const temporary = `${file4}.phren-${process.pid}-${Date.now()}`;
|
|
49716
|
+
writeFileSync15(temporary, content, { flag: "wx" });
|
|
49717
|
+
renameSync10(temporary, file4);
|
|
49718
|
+
});
|
|
49437
49719
|
return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
|
|
49438
49720
|
});
|
|
49439
49721
|
}
|
|
@@ -49441,8 +49723,10 @@ function deleteStoreFile(store, data) {
|
|
|
49441
49723
|
const input2 = deleteSchema.parse(data);
|
|
49442
49724
|
return serialized2(async () => {
|
|
49443
49725
|
const file4 = await storeFile(store, input2.path);
|
|
49444
|
-
|
|
49445
|
-
|
|
49726
|
+
lockedStoreFile(file4, input2.path, () => {
|
|
49727
|
+
if (currentShaSync(file4) !== input2.sha) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
49728
|
+
unlinkSync7(file4);
|
|
49729
|
+
});
|
|
49446
49730
|
return { ok: true };
|
|
49447
49731
|
});
|
|
49448
49732
|
}
|
|
@@ -49460,6 +49744,7 @@ var init_memory_store = __esm({
|
|
|
49460
49744
|
"src/bridge/memory-store.ts"() {
|
|
49461
49745
|
"use strict";
|
|
49462
49746
|
init_zod();
|
|
49747
|
+
init_locks();
|
|
49463
49748
|
init_protocol();
|
|
49464
49749
|
exec12 = promisify14(execFile16);
|
|
49465
49750
|
SHA = /^[0-9a-f]{40}$/;
|
|
@@ -49671,7 +49956,7 @@ var init_task_receipts = __esm({
|
|
|
49671
49956
|
// src/data/tasks.ts
|
|
49672
49957
|
import * as fs32 from "fs";
|
|
49673
49958
|
import * as path79 from "path";
|
|
49674
|
-
import { createHash as createHash22, randomBytes as
|
|
49959
|
+
import { createHash as createHash22, randomBytes as randomBytes5, randomUUID as randomUUID18 } from "crypto";
|
|
49675
49960
|
function formatClaim(claim2) {
|
|
49676
49961
|
return `Claimed: ${claim2.computer} ${claim2.at}${claim2.session ? ` session:${claim2.session}` : ""}`;
|
|
49677
49962
|
}
|
|
@@ -49784,7 +50069,7 @@ function parseContinuation(lines, idx) {
|
|
|
49784
50069
|
};
|
|
49785
50070
|
}
|
|
49786
50071
|
function newBid() {
|
|
49787
|
-
return
|
|
50072
|
+
return randomBytes5(4).toString("hex");
|
|
49788
50073
|
}
|
|
49789
50074
|
function stripBid(text5) {
|
|
49790
50075
|
const m = text5.match(METADATA_PATTERN);
|
|
@@ -50985,7 +51270,7 @@ function resolveDuplicateMatches(matches) {
|
|
|
50985
51270
|
const first = bulletContentKey(matches[0].line);
|
|
50986
51271
|
return matches.every(({ line }) => bulletContentKey(line) === first) ? matches[0] : null;
|
|
50987
51272
|
}
|
|
50988
|
-
function findMatchingFindingBullet(bulletLines, needle, match) {
|
|
51273
|
+
function findMatchingFindingBullet(bulletLines, needle, match, exactOnly = false) {
|
|
50989
51274
|
const fidNeedle = needle.replace(/^fid:/, "");
|
|
50990
51275
|
const fidMatch = /^[a-z0-9]{8}$/.test(fidNeedle) ? bulletLines.filter(({ line }) => new RegExp(`<!--\\s*fid:${fidNeedle}\\s*-->`).test(line)) : [];
|
|
50991
51276
|
const exactMatches = bulletLines.filter(
|
|
@@ -50999,6 +51284,14 @@ function findMatchingFindingBullet(bulletLines, needle, match) {
|
|
|
50999
51284
|
if (dup) return { kind: "found", idx: dup.i };
|
|
51000
51285
|
return { kind: "ambiguous", error: `"${match}" is ambiguous (${exactMatches.length} exact matches). Use a more specific phrase.` };
|
|
51001
51286
|
}
|
|
51287
|
+
if (exactOnly) {
|
|
51288
|
+
const bare = withoutTypeTag(needle);
|
|
51289
|
+
const tagged = bulletLines.filter(({ line }) => withoutTypeTag(normalizeFindingText(line)) === bare);
|
|
51290
|
+
if (tagged.length === 0) return { kind: "not_found" };
|
|
51291
|
+
const dup = tagged.length === 1 ? tagged[0] : resolveDuplicateMatches(tagged);
|
|
51292
|
+
if (dup) return { kind: "found", idx: dup.i };
|
|
51293
|
+
return { kind: "ambiguous", error: `"${match}" is ambiguous (${tagged.length} matches). Use a more specific phrase.` };
|
|
51294
|
+
}
|
|
51002
51295
|
if (partialMatches.length === 1) return { kind: "found", idx: partialMatches[0].i };
|
|
51003
51296
|
if (partialMatches.length > 1) {
|
|
51004
51297
|
const dup = resolveDuplicateMatches(partialMatches);
|
|
@@ -51116,7 +51409,7 @@ function parseFindingsContent(content, opts = {}) {
|
|
|
51116
51409
|
}
|
|
51117
51410
|
return items;
|
|
51118
51411
|
}
|
|
51119
|
-
function removeFinding(phrenPath, project, match) {
|
|
51412
|
+
function removeFinding(phrenPath, project, match, opts = {}) {
|
|
51120
51413
|
const ensured = ensureProject(phrenPath, project);
|
|
51121
51414
|
if (!ensured.ok) return forwardErr(ensured);
|
|
51122
51415
|
const findingsPath = path83.resolve(path83.join(ensured.data, FINDINGS_FILENAME));
|
|
@@ -51129,12 +51422,12 @@ function removeFinding(phrenPath, project, match) {
|
|
|
51129
51422
|
const lines = fs36.readFileSync(filePath, "utf8").split("\n");
|
|
51130
51423
|
const needle = normalizeFindingText(match);
|
|
51131
51424
|
const bulletLines = collectFindingBulletLines(lines);
|
|
51132
|
-
const activeMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => !archived), needle, match);
|
|
51425
|
+
const activeMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => !archived), needle, match, opts.exactOnly);
|
|
51133
51426
|
if (activeMatch.kind === "ambiguous") {
|
|
51134
51427
|
return phrenErr(activeMatch.error, PhrenError.AMBIGUOUS_MATCH);
|
|
51135
51428
|
}
|
|
51136
51429
|
if (activeMatch.kind === "not_found") {
|
|
51137
|
-
const archivedMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => archived), needle, match);
|
|
51430
|
+
const archivedMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => archived), needle, match, opts.exactOnly);
|
|
51138
51431
|
if (archivedMatch.kind === "ambiguous" || archivedMatch.kind === "found") {
|
|
51139
51432
|
return phrenErr(`Finding "${match}" is archived and read-only. Restore or re-add it before mutating history.`, PhrenError.VALIDATION_ERROR);
|
|
51140
51433
|
}
|
|
@@ -51190,6 +51483,7 @@ function editFinding(phrenPath, project, oldText, newText) {
|
|
|
51190
51483
|
return phrenOk(`Updated finding in ${project}`);
|
|
51191
51484
|
});
|
|
51192
51485
|
}
|
|
51486
|
+
var withoutTypeTag;
|
|
51193
51487
|
var init_access = __esm({
|
|
51194
51488
|
"src/data/access.ts"() {
|
|
51195
51489
|
"use strict";
|
|
@@ -51210,6 +51504,7 @@ var init_access = __esm({
|
|
|
51210
51504
|
init_governance();
|
|
51211
51505
|
init_filenames();
|
|
51212
51506
|
init_filenames();
|
|
51507
|
+
withoutTypeTag = (text5) => text5.replace(/^\[[a-z-]+\]\s*/i, "");
|
|
51213
51508
|
}
|
|
51214
51509
|
});
|
|
51215
51510
|
|
|
@@ -52016,6 +52311,7 @@ var init_summarize = __esm({
|
|
|
52016
52311
|
init_store_routing();
|
|
52017
52312
|
init_phren_paths();
|
|
52018
52313
|
init_utils();
|
|
52314
|
+
init_locks();
|
|
52019
52315
|
NOW_START = "<!-- phren:now:start -->";
|
|
52020
52316
|
NOW_END = "<!-- phren:now:end -->";
|
|
52021
52317
|
KNOWS_START = "<!-- phren:knows:start -->";
|
|
@@ -52214,6 +52510,19 @@ ${entry2.lines.join("\n")}` : void 0;
|
|
|
52214
52510
|
}
|
|
52215
52511
|
});
|
|
52216
52512
|
|
|
52513
|
+
// src/data/notes.ts
|
|
52514
|
+
var NOTE_HEADING_RE;
|
|
52515
|
+
var init_notes = __esm({
|
|
52516
|
+
"src/data/notes.ts"() {
|
|
52517
|
+
"use strict";
|
|
52518
|
+
init_shared();
|
|
52519
|
+
init_dedup();
|
|
52520
|
+
init_phren_paths();
|
|
52521
|
+
init_data_utils();
|
|
52522
|
+
NOTE_HEADING_RE = /^##\s+(\d{2}:\d{2}(?::\d{2})?)\s+<!--\s*nid:([a-f0-9]{8})\s*-->(?:\s+<!--\s*promoted\s*-->)?\s*$/i;
|
|
52523
|
+
}
|
|
52524
|
+
});
|
|
52525
|
+
|
|
52217
52526
|
// src/sync/conflict-resolve.ts
|
|
52218
52527
|
import { execFileSync as execFileSync5, spawnSync as spawnSync2 } from "child_process";
|
|
52219
52528
|
import * as crypto11 from "crypto";
|
|
@@ -52230,7 +52539,8 @@ function conflictStrategy(relFile) {
|
|
|
52230
52539
|
if (name === "summary.md") return "summary";
|
|
52231
52540
|
if (name === "review.md" || name === "truths.md") return "union";
|
|
52232
52541
|
if (file4 === ".config/maintenance-writer.json") return "theirs";
|
|
52233
|
-
if (/(^|\/)
|
|
52542
|
+
if (/(^|\/)notes\/[^/]+\.md$/i.test(file4)) return "notes";
|
|
52543
|
+
if (/(^|\/)journal\/[^/]+\.md$/i.test(file4)) return "union";
|
|
52234
52544
|
return null;
|
|
52235
52545
|
}
|
|
52236
52546
|
function git4(cwd, args) {
|
|
@@ -52286,6 +52596,51 @@ function unionText(base, ours, theirs) {
|
|
|
52286
52596
|
fs39.rmSync(dir, { recursive: true, force: true });
|
|
52287
52597
|
}
|
|
52288
52598
|
}
|
|
52599
|
+
function noteBlocks(content) {
|
|
52600
|
+
const lines = content.split("\n");
|
|
52601
|
+
const first = lines.findIndex((line) => NOTE_HEADING_RE.test(line));
|
|
52602
|
+
const notes = /* @__PURE__ */ new Map();
|
|
52603
|
+
if (first === -1) return { header: content.trimEnd(), notes };
|
|
52604
|
+
let id2 = "";
|
|
52605
|
+
let body2 = [];
|
|
52606
|
+
const flush = () => {
|
|
52607
|
+
if (id2) notes.set(id2, body2.join("\n").trimEnd());
|
|
52608
|
+
};
|
|
52609
|
+
for (const line of lines.slice(first)) {
|
|
52610
|
+
const m = NOTE_HEADING_RE.exec(line);
|
|
52611
|
+
if (!m) {
|
|
52612
|
+
body2.push(line);
|
|
52613
|
+
continue;
|
|
52614
|
+
}
|
|
52615
|
+
flush();
|
|
52616
|
+
if (notes.has(m[2])) return null;
|
|
52617
|
+
id2 = m[2];
|
|
52618
|
+
body2 = [line];
|
|
52619
|
+
}
|
|
52620
|
+
flush();
|
|
52621
|
+
return { header: lines.slice(0, first).join("\n").trimEnd(), notes };
|
|
52622
|
+
}
|
|
52623
|
+
function mergeNotes(base, ours, theirs) {
|
|
52624
|
+
const b = noteBlocks(base);
|
|
52625
|
+
if (!b) return null;
|
|
52626
|
+
const deleted = { header: b.header, notes: /* @__PURE__ */ new Map() };
|
|
52627
|
+
const [o, t] = [ours === null ? deleted : noteBlocks(ours), theirs === null ? deleted : noteBlocks(theirs)];
|
|
52628
|
+
if (!o || !t) return null;
|
|
52629
|
+
const header = mergeText(b.header, o.header, t.header);
|
|
52630
|
+
if (header === null) return null;
|
|
52631
|
+
const out = [];
|
|
52632
|
+
for (const id2 of /* @__PURE__ */ new Set([...o.notes.keys(), ...t.notes.keys()])) {
|
|
52633
|
+
const [was, mine, incoming] = [b.notes.get(id2), o.notes.get(id2), t.notes.get(id2)];
|
|
52634
|
+
let note;
|
|
52635
|
+
if (mine === incoming || incoming === was) note = mine;
|
|
52636
|
+
else if (mine === was) note = incoming;
|
|
52637
|
+
else if (mine === void 0 || incoming === void 0) note = mine ?? incoming;
|
|
52638
|
+
else return null;
|
|
52639
|
+
if (note !== void 0) out.push(note);
|
|
52640
|
+
}
|
|
52641
|
+
if (!out.length && (ours === null || theirs === null)) return DELETED_FILE;
|
|
52642
|
+
return [header, ...out].join("\n\n") + "\n";
|
|
52643
|
+
}
|
|
52289
52644
|
function mergeWithGeneratedBlock(base, ours, theirs, start, end, where, merge2 = unionText) {
|
|
52290
52645
|
const b = splitBlock(base, start, end);
|
|
52291
52646
|
const o = splitBlock(ours, start, end);
|
|
@@ -52312,7 +52667,7 @@ function resolveContent(strategy, base, ours, theirs) {
|
|
|
52312
52667
|
case "tasks":
|
|
52313
52668
|
return orUnion(() => mergeTasksByBid(base, ours, theirs), base, ours, theirs, dedupe);
|
|
52314
52669
|
case "findings":
|
|
52315
|
-
return orUnion(() => mergeFindings(ours, theirs), base, ours, theirs);
|
|
52670
|
+
return orUnion(() => mergeFindings(ours, theirs, base), base, ours, theirs);
|
|
52316
52671
|
// Archived tasks only accumulate: keep both sides, the incoming version of any duplicate.
|
|
52317
52672
|
case "archive":
|
|
52318
52673
|
return dedupe(orUnion(() => mergeTask(theirs, ours), base, ours, theirs));
|
|
@@ -52323,6 +52678,10 @@ function resolveContent(strategy, base, ours, theirs) {
|
|
|
52323
52678
|
// summarize pass fold in anything only this machine had.
|
|
52324
52679
|
case "summary":
|
|
52325
52680
|
return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom", mergeText) ?? theirs;
|
|
52681
|
+
case "notes": {
|
|
52682
|
+
const merged = mergeNotes(base, ours, theirs);
|
|
52683
|
+
return typeof merged === "string" ? merged : unionText(base, ours, theirs);
|
|
52684
|
+
}
|
|
52326
52685
|
case "union":
|
|
52327
52686
|
return unionText(base, ours, theirs);
|
|
52328
52687
|
case "theirs":
|
|
@@ -52354,7 +52713,13 @@ function resolveStoreConflicts(cwd) {
|
|
|
52354
52713
|
unresolved.push(relFile);
|
|
52355
52714
|
continue;
|
|
52356
52715
|
}
|
|
52357
|
-
const
|
|
52716
|
+
const notesMerge = strategy === "notes" && (ours === null || theirs === null) ? mergeNotes(base, ours, theirs) : null;
|
|
52717
|
+
if (notesMerge === DELETED_FILE) {
|
|
52718
|
+
git4(cwd, ["rm", "--quiet", "--force", "--ignore-unmatch", "--", relFile]);
|
|
52719
|
+
resolved.push(relFile);
|
|
52720
|
+
continue;
|
|
52721
|
+
}
|
|
52722
|
+
const merged = notesMerge ?? (ours === null ? theirs : theirs === null ? ours : resolveContent(strategy, base, ours, theirs));
|
|
52358
52723
|
if (merged === null) {
|
|
52359
52724
|
unresolved.push(relFile);
|
|
52360
52725
|
continue;
|
|
@@ -52372,7 +52737,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
52372
52737
|
}
|
|
52373
52738
|
return { resolved, unresolved };
|
|
52374
52739
|
}
|
|
52375
|
-
var dedupe;
|
|
52740
|
+
var DELETED_FILE, dedupe;
|
|
52376
52741
|
var init_conflict_resolve = __esm({
|
|
52377
52742
|
"src/sync/conflict-resolve.ts"() {
|
|
52378
52743
|
"use strict";
|
|
@@ -52383,6 +52748,8 @@ var init_conflict_resolve = __esm({
|
|
|
52383
52748
|
init_validate();
|
|
52384
52749
|
init_summarize();
|
|
52385
52750
|
init_task_merge();
|
|
52751
|
+
init_notes();
|
|
52752
|
+
DELETED_FILE = /* @__PURE__ */ Symbol("deleted");
|
|
52386
52753
|
dedupe = (content) => content === null ? null : dedupeTaskIds(content).content;
|
|
52387
52754
|
}
|
|
52388
52755
|
});
|
|
@@ -52817,7 +53184,7 @@ var init_store_sync = __esm({
|
|
|
52817
53184
|
|
|
52818
53185
|
// src/bridge/health.ts
|
|
52819
53186
|
import { execFile as execFile19, spawn as spawn9 } from "node:child_process";
|
|
52820
|
-
import { lstat as lstat22, readFile as
|
|
53187
|
+
import { lstat as lstat22, readFile as readFile35 } from "node:fs/promises";
|
|
52821
53188
|
import { homedir as homedir14, hostname as hostname7 } from "node:os";
|
|
52822
53189
|
import path89 from "node:path";
|
|
52823
53190
|
import { promisify as promisify17 } from "node:util";
|
|
@@ -52951,11 +53318,16 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
52951
53318
|
const owner2 = newest2.scheduleProject ?? newest2.project;
|
|
52952
53319
|
const matching = runs.filter((run4) => (run4.scheduleProject ?? run4.project) === owner2 && run4.scheduleId === newest2.scheduleId && (newest2.batchId ? run4.batchId === newest2.batchId : run4.id === newest2.id));
|
|
52953
53320
|
const last = latestScheduleBatch(matching).lastRun;
|
|
52954
|
-
let name;
|
|
53321
|
+
let name, paused = false;
|
|
52955
53322
|
const directory = getProjectDirs(store).find((dir) => path89.basename(dir).toLowerCase() === owner2.toLowerCase());
|
|
52956
|
-
if (directory)
|
|
53323
|
+
if (directory) {
|
|
53324
|
+
const found = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId);
|
|
53325
|
+
name = found?.name;
|
|
53326
|
+
paused = found?.enabled === false;
|
|
53327
|
+
}
|
|
52957
53328
|
return {
|
|
52958
53329
|
...name ? { name } : {},
|
|
53330
|
+
...paused ? { paused } : {},
|
|
52959
53331
|
project: owner2,
|
|
52960
53332
|
status: last.status,
|
|
52961
53333
|
...last.reason ? { reason: plainError(last.reason) } : {},
|
|
@@ -53013,7 +53385,7 @@ async function readCanary(root = bridgeRoot()) {
|
|
|
53013
53385
|
try {
|
|
53014
53386
|
const info = await lstat22(canaryFile(root));
|
|
53015
53387
|
if (!info.isFile() || info.size > 65536) return null;
|
|
53016
|
-
const value2 = JSON.parse(await
|
|
53388
|
+
const value2 = JSON.parse(await readFile35(canaryFile(root), "utf8"));
|
|
53017
53389
|
return value2 && value2.version === 1 && Array.isArray(value2.steps) ? value2 : null;
|
|
53018
53390
|
} catch {
|
|
53019
53391
|
return null;
|
|
@@ -53166,7 +53538,7 @@ var init_harnesses = __esm({
|
|
|
53166
53538
|
});
|
|
53167
53539
|
|
|
53168
53540
|
// src/bridge/account-choice.ts
|
|
53169
|
-
import { readFile as
|
|
53541
|
+
import { readFile as readFile36 } from "node:fs/promises";
|
|
53170
53542
|
import path91 from "node:path";
|
|
53171
53543
|
function windowRoom2(window2, now) {
|
|
53172
53544
|
if (!window2) return void 0;
|
|
@@ -53212,7 +53584,7 @@ function claudeRooms(inventory, usage, now) {
|
|
|
53212
53584
|
}
|
|
53213
53585
|
async function readAccountLimits(now = Date.now()) {
|
|
53214
53586
|
try {
|
|
53215
|
-
const parsed = ledgerSchema.parse(JSON.parse(await
|
|
53587
|
+
const parsed = ledgerSchema.parse(JSON.parse(await readFile36(limitsFile(), "utf8")));
|
|
53216
53588
|
return parsed.limits.filter((entry2) => Date.parse(entry2.until) > now);
|
|
53217
53589
|
} catch (error62) {
|
|
53218
53590
|
if (error62.code !== "ENOENT") logger.warn("accounts", `Could not read account-limits.json: ${error62 instanceof Error ? error62.message : String(error62)}`);
|
|
@@ -53306,7 +53678,7 @@ var init_account_choice = __esm({
|
|
|
53306
53678
|
|
|
53307
53679
|
// src/bridge/owner-inbox.ts
|
|
53308
53680
|
import { randomUUID as randomUUID21 } from "node:crypto";
|
|
53309
|
-
import { lstat as lstat23, mkdir as mkdir22, readFile as
|
|
53681
|
+
import { lstat as lstat23, mkdir as mkdir22, readFile as readFile37 } from "node:fs/promises";
|
|
53310
53682
|
import path92 from "node:path";
|
|
53311
53683
|
function sourceKey(row) {
|
|
53312
53684
|
const t = row.target;
|
|
@@ -53371,7 +53743,7 @@ var init_owner_inbox = __esm({
|
|
|
53371
53743
|
});
|
|
53372
53744
|
if (!info) return [];
|
|
53373
53745
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 4 * 1024 * 1024) throw new BridgeError(409, "The owner inbox cannot be read safely.");
|
|
53374
|
-
return external_exports.array(itemSchema).max(1e4).parse(JSON.parse(await
|
|
53746
|
+
return external_exports.array(itemSchema).max(1e4).parse(JSON.parse(await readFile37(this.file, "utf8")));
|
|
53375
53747
|
}
|
|
53376
53748
|
run(input2) {
|
|
53377
53749
|
const run4 = this.pending.then(async () => {
|
|
@@ -53386,7 +53758,7 @@ var init_owner_inbox = __esm({
|
|
|
53386
53758
|
}
|
|
53387
53759
|
try {
|
|
53388
53760
|
const rows2 = await this.read(), at2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
53389
|
-
let
|
|
53761
|
+
let changed = false;
|
|
53390
53762
|
if (data.action === "list") {
|
|
53391
53763
|
const observed = await this.sources();
|
|
53392
53764
|
const { sources, unavailableDispatches = [] } = Array.isArray(observed) ? { sources: observed } : observed;
|
|
@@ -53398,7 +53770,7 @@ var init_owner_inbox = __esm({
|
|
|
53398
53770
|
row.resolvedAt = at2;
|
|
53399
53771
|
row.updatedAt = at2;
|
|
53400
53772
|
row.resolution = reason2;
|
|
53401
|
-
|
|
53773
|
+
changed = true;
|
|
53402
53774
|
};
|
|
53403
53775
|
for (const row of rows2) {
|
|
53404
53776
|
if (row.kind === "manual") continue;
|
|
@@ -53409,7 +53781,7 @@ var init_owner_inbox = __esm({
|
|
|
53409
53781
|
if (row.live !== live) {
|
|
53410
53782
|
row.live = live;
|
|
53411
53783
|
row.updatedAt = at2;
|
|
53412
|
-
|
|
53784
|
+
changed = true;
|
|
53413
53785
|
}
|
|
53414
53786
|
if (!source) {
|
|
53415
53787
|
if (row.state === "open" && !unavailable) resolve17(row, "stale: source gone");
|
|
@@ -53422,14 +53794,14 @@ var init_owner_inbox = __esm({
|
|
|
53422
53794
|
retained.add(key4);
|
|
53423
53795
|
if (row.state === "open" && JSON.stringify({ ...row, ...source }) !== JSON.stringify(row)) {
|
|
53424
53796
|
Object.assign(row, source, { updatedAt: at2 });
|
|
53425
|
-
|
|
53797
|
+
changed = true;
|
|
53426
53798
|
}
|
|
53427
53799
|
}
|
|
53428
53800
|
for (const [key4, source] of active) {
|
|
53429
53801
|
if (retained.has(key4)) continue;
|
|
53430
53802
|
if (rows2.length >= 1e4) throw new BridgeError(409, "The owner inbox is full.");
|
|
53431
53803
|
rows2.push(itemSchema.parse({ ...source, id: randomUUID21(), state: "open", live: true, createdAt: at2, updatedAt: at2 }));
|
|
53432
|
-
|
|
53804
|
+
changed = true;
|
|
53433
53805
|
}
|
|
53434
53806
|
}
|
|
53435
53807
|
if (data.action === "add") {
|
|
@@ -53440,9 +53812,9 @@ var init_owner_inbox = __esm({
|
|
|
53440
53812
|
if (!prior) {
|
|
53441
53813
|
if (rows2.length >= 1e4) throw new BridgeError(409, "The owner inbox is full.");
|
|
53442
53814
|
rows2.push(item);
|
|
53443
|
-
|
|
53815
|
+
changed = true;
|
|
53444
53816
|
}
|
|
53445
|
-
if (
|
|
53817
|
+
if (changed) await atomicInPrivateDir(this.file, rows2);
|
|
53446
53818
|
return { ok: true, item: prior ?? item };
|
|
53447
53819
|
}
|
|
53448
53820
|
if (data.action === "resolve") {
|
|
@@ -53453,12 +53825,12 @@ var init_owner_inbox = __esm({
|
|
|
53453
53825
|
item.resolvedAt = at2;
|
|
53454
53826
|
item.updatedAt = at2;
|
|
53455
53827
|
item.resolution = data.resolution;
|
|
53456
|
-
|
|
53828
|
+
changed = true;
|
|
53457
53829
|
}
|
|
53458
|
-
if (
|
|
53830
|
+
if (changed) await atomicInPrivateDir(this.file, rows2);
|
|
53459
53831
|
return { ok: true, item };
|
|
53460
53832
|
}
|
|
53461
|
-
if (
|
|
53833
|
+
if (changed) await atomicInPrivateDir(this.file, rows2);
|
|
53462
53834
|
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)) };
|
|
53463
53835
|
} finally {
|
|
53464
53836
|
release();
|
|
@@ -53577,7 +53949,7 @@ var init_owner_inbox_sources = __esm({
|
|
|
53577
53949
|
|
|
53578
53950
|
// src/bridge/hand-off-queue.ts
|
|
53579
53951
|
import { createHash as createHash24, randomUUID as randomUUID22 } from "node:crypto";
|
|
53580
|
-
import { lstat as lstat24, open as open16, readFile as
|
|
53952
|
+
import { lstat as lstat24, open as open16, readFile as readFile38, readdir as readdir14, unlink as unlink5 } from "node:fs/promises";
|
|
53581
53953
|
import path93 from "node:path";
|
|
53582
53954
|
var queuedHandOffSchema, rowSchema, DAY3, HAND_OFF_RETENTION_MS, HAND_OFF_MAX_ROWS, settled2, samePane, HandOffQueue;
|
|
53583
53955
|
var init_hand_off_queue = __esm({
|
|
@@ -53649,7 +54021,7 @@ var init_hand_off_queue = __esm({
|
|
|
53649
54021
|
});
|
|
53650
54022
|
if (!info) return void 0;
|
|
53651
54023
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 1e5) throw new BridgeError(409, "The hand-off record cannot be read safely.");
|
|
53652
|
-
const row = rowSchema.parse(JSON.parse(await
|
|
54024
|
+
const row = rowSchema.parse(JSON.parse(await readFile38(file4, "utf8")));
|
|
53653
54025
|
if (row.state === "attempting") {
|
|
53654
54026
|
row.state = "uncertain";
|
|
53655
54027
|
row.error = "The Hook restarted before delivery was confirmed.";
|
|
@@ -53855,9 +54227,52 @@ var init_hand_off_queue = __esm({
|
|
|
53855
54227
|
}
|
|
53856
54228
|
});
|
|
53857
54229
|
|
|
54230
|
+
// src/bridge/git-write-policy.ts
|
|
54231
|
+
function clientIdentity(headers) {
|
|
54232
|
+
const clean5 = (value2) => (Array.isArray(value2) ? value2.join(", ") : value2 ?? "").replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 200);
|
|
54233
|
+
const client = clean5(headers["x-phren-client"]);
|
|
54234
|
+
const version2 = clean5(headers["x-phren-app-version"] || headers["x-phren-client-version"]);
|
|
54235
|
+
const agent = clean5(headers["user-agent"]);
|
|
54236
|
+
return [client, version2, agent].filter(Boolean).join(" / ") || "unknown client";
|
|
54237
|
+
}
|
|
54238
|
+
var EXPECTED_REPOSITORY_REQUIRED, WRITE_ROUTES, isGitWriteRoute, GitWriteDiagnostics;
|
|
54239
|
+
var init_git_write_policy = __esm({
|
|
54240
|
+
"src/bridge/git-write-policy.ts"() {
|
|
54241
|
+
"use strict";
|
|
54242
|
+
EXPECTED_REPOSITORY_REQUIRED = false;
|
|
54243
|
+
WRITE_ROUTES = new Set(["stage", "unstage", "discard", "commit", "push", "pr", "pr/merge", "host-token", "checkout", "fetch", "pull", "apply"].map((action) => `/v1/git/${action}`));
|
|
54244
|
+
isGitWriteRoute = (route2) => WRITE_ROUTES.has(route2);
|
|
54245
|
+
GitWriteDiagnostics = class {
|
|
54246
|
+
clients = /* @__PURE__ */ new Map();
|
|
54247
|
+
record(route2, headers) {
|
|
54248
|
+
let client = clientIdentity(headers);
|
|
54249
|
+
if (!this.clients.has(client) && this.clients.size >= 128) client = "other clients";
|
|
54250
|
+
let entry2 = this.clients.get(client);
|
|
54251
|
+
if (!entry2) {
|
|
54252
|
+
entry2 = { count: 0, routes: /* @__PURE__ */ new Set() };
|
|
54253
|
+
this.clients.set(client, entry2);
|
|
54254
|
+
}
|
|
54255
|
+
entry2.count++;
|
|
54256
|
+
if (!entry2.routes.has(route2)) {
|
|
54257
|
+
entry2.routes.add(route2);
|
|
54258
|
+
console.warn(`[phren-hook] ${route2}: git write without expectedRepository from ${client}; update the app before the compatibility window ends.`);
|
|
54259
|
+
}
|
|
54260
|
+
}
|
|
54261
|
+
snapshot() {
|
|
54262
|
+
return [...this.clients].map(([client, entry2]) => ({
|
|
54263
|
+
client,
|
|
54264
|
+
count: entry2.count,
|
|
54265
|
+
warning: `${entry2.count} git writes without expectedRepository from ${client}`
|
|
54266
|
+
}));
|
|
54267
|
+
}
|
|
54268
|
+
};
|
|
54269
|
+
}
|
|
54270
|
+
});
|
|
54271
|
+
|
|
53858
54272
|
// src/bridge/git-host-auth.ts
|
|
54273
|
+
import { createHash as createHash25 } from "node:crypto";
|
|
53859
54274
|
import { execFile as execFile20 } from "node:child_process";
|
|
53860
|
-
import { mkdir as mkdir23, readFile as
|
|
54275
|
+
import { mkdir as mkdir23, readFile as readFile39, stat as stat19 } from "node:fs/promises";
|
|
53861
54276
|
import path94 from "node:path";
|
|
53862
54277
|
import { promisify as promisify18 } from "node:util";
|
|
53863
54278
|
function gitHostsFile() {
|
|
@@ -53879,7 +54294,7 @@ async function readStore(file4 = gitHostsFile()) {
|
|
|
53879
54294
|
if (!info.isFile()) return null;
|
|
53880
54295
|
if (process.platform !== "win32" && ((info.mode & 63) !== 0 || process.getuid && info.uid !== process.getuid())) return "unsafe";
|
|
53881
54296
|
try {
|
|
53882
|
-
const parsed = JSON.parse(await
|
|
54297
|
+
const parsed = JSON.parse(await readFile39(file4, "utf8"));
|
|
53883
54298
|
const hosts = {};
|
|
53884
54299
|
if (parsed.hosts && typeof parsed.hosts === "object") {
|
|
53885
54300
|
for (const [domain2, raw] of Object.entries(parsed.hosts)) {
|
|
@@ -53904,6 +54319,7 @@ async function writeHostToken(domain2, kind, token, user, file4 = gitHostsFile()
|
|
|
53904
54319
|
else delete hosts[key4];
|
|
53905
54320
|
await mkdir23(path94.dirname(file4), { recursive: true, mode: 448 });
|
|
53906
54321
|
await atomic(file4, JSON.stringify({ hosts }, null, 2) + "\n", 384);
|
|
54322
|
+
invalidatePullsForDomain(key4);
|
|
53907
54323
|
}
|
|
53908
54324
|
function fromEnv(kind, domain2, env) {
|
|
53909
54325
|
if (kind === "gitlab") {
|
|
@@ -53941,10 +54357,49 @@ async function listHostTokens(file4 = gitHostsFile()) {
|
|
|
53941
54357
|
if (store === "unsafe") return "unsafe";
|
|
53942
54358
|
return Object.entries(store?.hosts ?? {}).map(([domain2, { kind, user, savedAt }]) => ({ domain: domain2, kind, ...user ? { user } : {}, ...savedAt ? { savedAt } : {} }));
|
|
53943
54359
|
}
|
|
54360
|
+
function ghHostBlock(hostsYml, domain2) {
|
|
54361
|
+
const want = domain2.trim().toLowerCase().replace(/\.$/, "");
|
|
54362
|
+
const out = [];
|
|
54363
|
+
let inside = false;
|
|
54364
|
+
for (const line of hostsYml.split(/\r?\n/)) {
|
|
54365
|
+
const top = /^(\S[^:]*):\s*$/.exec(line);
|
|
54366
|
+
if (top) {
|
|
54367
|
+
inside = top[1].trim().replace(/^["']|["']$/g, "").toLowerCase() === want;
|
|
54368
|
+
if (inside) out.push(line);
|
|
54369
|
+
continue;
|
|
54370
|
+
}
|
|
54371
|
+
if (inside && (line.startsWith(" ") || line.startsWith(" ") || line.trim() === "")) out.push(line);
|
|
54372
|
+
else if (line.trim()) inside = false;
|
|
54373
|
+
}
|
|
54374
|
+
return out.join("\n").trimEnd();
|
|
54375
|
+
}
|
|
54376
|
+
async function hostCredentialIdentity(host) {
|
|
54377
|
+
let state = null;
|
|
54378
|
+
if (host.kind === "github") {
|
|
54379
|
+
const dir = process.env.GH_CONFIG_DIR || path94.join(process.env.XDG_CONFIG_HOME || path94.join(homeDir(), ".config"), "gh");
|
|
54380
|
+
const hosts = await readFile39(path94.join(dir, "hosts.yml"), "utf8").catch(() => "");
|
|
54381
|
+
state = [
|
|
54382
|
+
process.env.GH_TOKEN,
|
|
54383
|
+
process.env.GITHUB_TOKEN,
|
|
54384
|
+
process.env.GH_ENTERPRISE_TOKEN,
|
|
54385
|
+
process.env.GITHUB_ENTERPRISE_TOKEN,
|
|
54386
|
+
ghHostBlock(hosts, host.domain ?? "github.com")
|
|
54387
|
+
];
|
|
54388
|
+
} else if (host.kind && host.domain) {
|
|
54389
|
+
const store = await readStore();
|
|
54390
|
+
state = [
|
|
54391
|
+
await resolveHostToken(host.kind, host.domain),
|
|
54392
|
+
store && store !== "unsafe" ? store.hosts[normalDomain(host.domain)] : store
|
|
54393
|
+
];
|
|
54394
|
+
}
|
|
54395
|
+
return createHash25("sha256").update(JSON.stringify(state)).digest("hex");
|
|
54396
|
+
}
|
|
53944
54397
|
var exec15;
|
|
53945
54398
|
var init_git_host_auth = __esm({
|
|
53946
54399
|
"src/bridge/git-host-auth.ts"() {
|
|
53947
54400
|
"use strict";
|
|
54401
|
+
init_home_paths();
|
|
54402
|
+
init_git();
|
|
53948
54403
|
init_protocol();
|
|
53949
54404
|
exec15 = promisify18(execFile20);
|
|
53950
54405
|
}
|
|
@@ -54017,18 +54472,21 @@ var init_git_host_http = __esm({
|
|
|
54017
54472
|
|
|
54018
54473
|
// src/bridge/git-publish.ts
|
|
54019
54474
|
import { spawn as spawn10 } from "node:child_process";
|
|
54020
|
-
function runCombined(command, args, cwd, timeout, extraEnv = {}) {
|
|
54475
|
+
function runCombined(command, args, cwd, timeout, extraEnv = {}, killGraceMs = KILL_GRACE_MS2) {
|
|
54021
54476
|
return new Promise((resolve17) => {
|
|
54022
54477
|
let output2 = "", truncated = false, timedOut = false, settled3 = false;
|
|
54478
|
+
let deadline;
|
|
54023
54479
|
const finish = (run4) => {
|
|
54024
|
-
if (
|
|
54025
|
-
|
|
54026
|
-
|
|
54027
|
-
|
|
54480
|
+
if (settled3) return;
|
|
54481
|
+
settled3 = true;
|
|
54482
|
+
clearTimeout(deadline);
|
|
54483
|
+
resolve17(run4);
|
|
54028
54484
|
};
|
|
54485
|
+
const group = process.platform !== "win32";
|
|
54029
54486
|
const child = spawn10(command, args, {
|
|
54030
54487
|
cwd,
|
|
54031
54488
|
stdio: ["ignore", "pipe", "pipe"],
|
|
54489
|
+
detached: group,
|
|
54032
54490
|
env: nonInteractiveGitEnv({ ...process.env, ...extraEnv, GIT_CONFIG_NOSYSTEM: "1", GIT_EDITOR: "true", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1" })
|
|
54033
54491
|
});
|
|
54034
54492
|
const append = (chunk) => {
|
|
@@ -54041,9 +54499,38 @@ function runCombined(command, args, cwd, timeout, extraEnv = {}) {
|
|
|
54041
54499
|
};
|
|
54042
54500
|
child.stdout.on("data", append);
|
|
54043
54501
|
child.stderr.on("data", append);
|
|
54502
|
+
const kill = (signal) => {
|
|
54503
|
+
try {
|
|
54504
|
+
if (group && child.pid) process.kill(-child.pid, signal);
|
|
54505
|
+
else child.kill(signal);
|
|
54506
|
+
} catch {
|
|
54507
|
+
child.kill(signal);
|
|
54508
|
+
}
|
|
54509
|
+
};
|
|
54510
|
+
const escalate = () => {
|
|
54511
|
+
if (!group || !child.pid) {
|
|
54512
|
+
child.kill("SIGKILL");
|
|
54513
|
+
return;
|
|
54514
|
+
}
|
|
54515
|
+
try {
|
|
54516
|
+
process.kill(-child.pid, 0);
|
|
54517
|
+
} catch {
|
|
54518
|
+
return;
|
|
54519
|
+
}
|
|
54520
|
+
try {
|
|
54521
|
+
process.kill(-child.pid, "SIGKILL");
|
|
54522
|
+
} catch {
|
|
54523
|
+
}
|
|
54524
|
+
};
|
|
54044
54525
|
const timer = setTimeout(() => {
|
|
54045
54526
|
timedOut = true;
|
|
54046
|
-
|
|
54527
|
+
kill("SIGTERM");
|
|
54528
|
+
setTimeout(escalate, killGraceMs).unref();
|
|
54529
|
+
deadline = setTimeout(() => {
|
|
54530
|
+
child.stdout.destroy();
|
|
54531
|
+
child.stderr.destroy();
|
|
54532
|
+
finish({ code: null, output: output2.trimEnd(), missing: false, timedOut: true });
|
|
54533
|
+
}, killGraceMs * 2);
|
|
54047
54534
|
}, timeout);
|
|
54048
54535
|
child.on("error", (error62) => {
|
|
54049
54536
|
clearTimeout(timer);
|
|
@@ -54123,7 +54610,11 @@ async function gitPullRequest(cwd, draft) {
|
|
|
54123
54610
|
const { reason: reason2, message } = unknownHost(host);
|
|
54124
54611
|
return { ok: false, reason: reason2, message, host };
|
|
54125
54612
|
}
|
|
54126
|
-
|
|
54613
|
+
try {
|
|
54614
|
+
return { ...await provider2.open(root, branch, draft === true, host), host };
|
|
54615
|
+
} finally {
|
|
54616
|
+
invalidatePulls(root);
|
|
54617
|
+
}
|
|
54127
54618
|
}
|
|
54128
54619
|
async function gitMergeRequest(cwd, data) {
|
|
54129
54620
|
const request9 = MergeBody.parse(data);
|
|
@@ -54135,7 +54626,11 @@ async function gitMergeRequest(cwd, data) {
|
|
|
54135
54626
|
const { reason: reason2, message } = unknownHost(host);
|
|
54136
54627
|
return { ok: false, reason: reason2, message, host };
|
|
54137
54628
|
}
|
|
54138
|
-
|
|
54629
|
+
try {
|
|
54630
|
+
return { ...await provider2.merge(root, request9, host), host };
|
|
54631
|
+
} finally {
|
|
54632
|
+
invalidatePulls(root);
|
|
54633
|
+
}
|
|
54139
54634
|
}
|
|
54140
54635
|
async function gitHostToken(cwd, data) {
|
|
54141
54636
|
const { token } = external_exports.object({ token: external_exports.string().max(4096) }).parse(data);
|
|
@@ -54162,7 +54657,7 @@ async function gitHostToken(cwd, data) {
|
|
|
54162
54657
|
throw error62;
|
|
54163
54658
|
}
|
|
54164
54659
|
}
|
|
54165
|
-
var MAX_OUTPUT, COMMIT_TIMEOUT_MS, PUSH_TIMEOUT_MS, MAX_MESSAGE, MergeBody;
|
|
54660
|
+
var MAX_OUTPUT, COMMIT_TIMEOUT_MS, PUSH_TIMEOUT_MS, MAX_MESSAGE, KILL_GRACE_MS2, MergeBody;
|
|
54166
54661
|
var init_git_publish = __esm({
|
|
54167
54662
|
"src/bridge/git-publish.ts"() {
|
|
54168
54663
|
"use strict";
|
|
@@ -54179,6 +54674,7 @@ var init_git_publish = __esm({
|
|
|
54179
54674
|
COMMIT_TIMEOUT_MS = 11e4;
|
|
54180
54675
|
PUSH_TIMEOUT_MS = 11e4;
|
|
54181
54676
|
MAX_MESSAGE = 2e4;
|
|
54677
|
+
KILL_GRACE_MS2 = 2e3;
|
|
54182
54678
|
MergeBody = external_exports.object({
|
|
54183
54679
|
number: external_exports.number().int().positive(),
|
|
54184
54680
|
method: external_exports.enum(["merge", "squash", "rebase"]).default("merge"),
|
|
@@ -54244,19 +54740,19 @@ function obj(value2) {
|
|
|
54244
54740
|
}
|
|
54245
54741
|
function projectPath(host) {
|
|
54246
54742
|
if (!host.webUrl || !host.domain) return null;
|
|
54247
|
-
const
|
|
54248
|
-
return
|
|
54743
|
+
const path146 = host.webUrl.replace(/^https?:\/\/[^/]+\//, "");
|
|
54744
|
+
return path146 || null;
|
|
54249
54745
|
}
|
|
54250
54746
|
async function context(root, host) {
|
|
54251
|
-
const
|
|
54252
|
-
if (!host.domain || !
|
|
54747
|
+
const path146 = projectPath(host);
|
|
54748
|
+
if (!host.domain || !path146) return { available: false, reason: "unknown-host", message: "This repository has no GitLab remote.", pulls: [], current: null };
|
|
54253
54749
|
const token = await resolveHostToken("gitlab", host.domain);
|
|
54254
54750
|
if (!token) return { available: false, reason: "auth", message: SIGN_IN(host.domain), pulls: [], current: null };
|
|
54255
54751
|
const base = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
|
|
54256
|
-
return { base, token: token.token, project: encodeURIComponent(
|
|
54752
|
+
return { base, token: token.token, project: encodeURIComponent(path146), domain: host.domain, account: { source: token.source, ...token.user ? { user: token.user } : {} } };
|
|
54257
54753
|
}
|
|
54258
|
-
function call(ctx,
|
|
54259
|
-
return hostJson(`${ctx.base}/projects/${ctx.project}${
|
|
54754
|
+
function call(ctx, path146, init = {}) {
|
|
54755
|
+
return hostJson(`${ctx.base}/projects/${ctx.project}${path146}`, { token: ctx.token, scheme: "private-token", ...init });
|
|
54260
54756
|
}
|
|
54261
54757
|
function listed(mr) {
|
|
54262
54758
|
const author = obj(mr.author);
|
|
@@ -54458,8 +54954,8 @@ async function context2(root, host) {
|
|
|
54458
54954
|
const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
|
|
54459
54955
|
return { api, web: api.replace(/\/api\/v1$/, ""), repo, token: token.token, domain: host.domain, account: { source: token.source, ...token.user ? { user: token.user } : {} } };
|
|
54460
54956
|
}
|
|
54461
|
-
function call2(ctx,
|
|
54462
|
-
return hostJson(`${ctx.api}/repos/${ctx.repo}${
|
|
54957
|
+
function call2(ctx, path146, init = {}) {
|
|
54958
|
+
return hostJson(`${ctx.api}/repos/${ctx.repo}${path146}`, { token: ctx.token, scheme: "bearer", ...init });
|
|
54463
54959
|
}
|
|
54464
54960
|
function sameRepository(ctx, pull) {
|
|
54465
54961
|
const head = obj2(pull.head_repository);
|
|
@@ -54695,8 +55191,8 @@ function parseRemoteUrl(url2) {
|
|
|
54695
55191
|
return null;
|
|
54696
55192
|
}
|
|
54697
55193
|
}
|
|
54698
|
-
function clean4(
|
|
54699
|
-
return
|
|
55194
|
+
function clean4(path146) {
|
|
55195
|
+
return path146.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "");
|
|
54700
55196
|
}
|
|
54701
55197
|
function kindFromDomain(domain2) {
|
|
54702
55198
|
if (domain2 === "github.com" || domain2.endsWith(".github.com") || domain2.endsWith(".ghe.com")) return "github";
|
|
@@ -54903,7 +55399,8 @@ var init_git_hosts = __esm({
|
|
|
54903
55399
|
});
|
|
54904
55400
|
|
|
54905
55401
|
// src/bridge/git.ts
|
|
54906
|
-
import { createHash as
|
|
55402
|
+
import { createHash as createHash26 } from "node:crypto";
|
|
55403
|
+
import { readFileSync as readFileSync43, realpathSync as realpathSync3 } from "node:fs";
|
|
54907
55404
|
import { lstat as lstat25, open as open17, readdir as readdir15, realpath as realpath12 } from "node:fs/promises";
|
|
54908
55405
|
import path95 from "node:path";
|
|
54909
55406
|
function statusLetter(code) {
|
|
@@ -55126,13 +55623,70 @@ async function gitBranches(cwd) {
|
|
|
55126
55623
|
}
|
|
55127
55624
|
return { current: current2, local, remote };
|
|
55128
55625
|
}
|
|
55129
|
-
|
|
55130
|
-
const
|
|
55131
|
-
const
|
|
55132
|
-
|
|
55626
|
+
function credentialIdentity(host, fresh = false) {
|
|
55627
|
+
const key4 = JSON.stringify([host.kind ?? null, (host.domain ?? "").toLowerCase()]);
|
|
55628
|
+
const hit = credentialReads.get(key4);
|
|
55629
|
+
if (host.kind !== "gitlab") return hostCredentialIdentity(host);
|
|
55630
|
+
if (!fresh && hit && Date.now() - hit.at < CREDENTIAL_TTL_MS) return hit.value;
|
|
55631
|
+
const value2 = hostCredentialIdentity(host).catch((error62) => {
|
|
55632
|
+
credentialReads.delete(key4);
|
|
55633
|
+
throw error62;
|
|
55634
|
+
});
|
|
55635
|
+
credentialReads.set(key4, { at: Date.now(), value: value2 });
|
|
55636
|
+
if (credentialReads.size > 64) credentialReads.delete(credentialReads.keys().next().value);
|
|
55637
|
+
return value2;
|
|
55638
|
+
}
|
|
55639
|
+
function repositoryId(root) {
|
|
55640
|
+
try {
|
|
55641
|
+
const dotGit = path95.join(root, ".git");
|
|
55642
|
+
let gitDir2 = dotGit;
|
|
55643
|
+
try {
|
|
55644
|
+
const link = /^gitdir:\s*(.+)$/m.exec(readFileSync43(dotGit, "utf8"));
|
|
55645
|
+
if (link) gitDir2 = path95.resolve(root, link[1].trim());
|
|
55646
|
+
} catch {
|
|
55647
|
+
}
|
|
55648
|
+
let common = gitDir2;
|
|
55649
|
+
try {
|
|
55650
|
+
common = path95.resolve(gitDir2, readFileSync43(path95.join(gitDir2, "commondir"), "utf8").trim());
|
|
55651
|
+
} catch {
|
|
55652
|
+
}
|
|
55653
|
+
return realpathSync3(common);
|
|
55654
|
+
} catch {
|
|
55655
|
+
return root;
|
|
55656
|
+
}
|
|
55657
|
+
}
|
|
55658
|
+
function invalidatePulls(root) {
|
|
55659
|
+
const prefix = repositoryId(root) + "\0";
|
|
55660
|
+
pullsCache.invalidate((key4) => key4.startsWith(prefix));
|
|
55661
|
+
}
|
|
55662
|
+
function invalidatePullsForDomain(domain2) {
|
|
55663
|
+
const normalized = domain2.trim().toLowerCase().replace(/\.$/, "");
|
|
55664
|
+
for (const key4 of credentialReads.keys()) if (JSON.parse(key4)[1] === normalized) credentialReads.delete(key4);
|
|
55665
|
+
pullsCache.invalidate((key4) => key4.split("\0")[1] === normalized);
|
|
55666
|
+
}
|
|
55667
|
+
async function gitPulls(cwd, retried = false) {
|
|
55668
|
+
const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
|
|
55669
|
+
const root2 = await repository2(cwd);
|
|
55670
|
+
const branch2 = (await git(root2, "branch", "--show-current").catch(() => "")).trim();
|
|
55671
|
+
return { root: root2, branch: branch2, host: await detectHost(root2, branch2) };
|
|
55672
|
+
});
|
|
55133
55673
|
const provider2 = providerFor(host);
|
|
55134
|
-
const
|
|
55135
|
-
|
|
55674
|
+
const credential = await credentialIdentity(host);
|
|
55675
|
+
const key4 = repositoryId(root) + "\0" + (host.domain ?? "").toLowerCase().replace(/\.$/, "") + "\0" + JSON.stringify([branch, host, credential]);
|
|
55676
|
+
try {
|
|
55677
|
+
return await pullsCache.get(key4, () => withoutGitReadDeadline(async () => {
|
|
55678
|
+
const list = provider2 ? await provider2.list(root, branch, host) : unknownHost(host);
|
|
55679
|
+
if (await credentialIdentity(host, true) !== credential) {
|
|
55680
|
+
pullsCache.invalidate((candidate) => candidate === key4);
|
|
55681
|
+
throw new CredentialsChanged();
|
|
55682
|
+
}
|
|
55683
|
+
return { ...list, branch: branch || null, host };
|
|
55684
|
+
}));
|
|
55685
|
+
} catch (error62) {
|
|
55686
|
+
if (!(error62 instanceof CredentialsChanged)) throw error62;
|
|
55687
|
+
if (!retried) return gitPulls(cwd, true);
|
|
55688
|
+
throw new BridgeError(409, "Forge credentials keep changing. Retry.");
|
|
55689
|
+
}
|
|
55136
55690
|
}
|
|
55137
55691
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
55138
55692
|
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.");
|
|
@@ -55163,13 +55717,14 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
55163
55717
|
}
|
|
55164
55718
|
function invalidateTree(root) {
|
|
55165
55719
|
treeCache.delete(root);
|
|
55720
|
+
invalidatePulls(root);
|
|
55166
55721
|
}
|
|
55167
55722
|
async function treeSnapshot(root, head) {
|
|
55168
55723
|
const [tracked, porcelain] = await Promise.all([
|
|
55169
55724
|
git(root, "ls-files", "-z"),
|
|
55170
55725
|
git(root, "status", "--porcelain=v1", "-z", "--untracked-files=all")
|
|
55171
55726
|
]);
|
|
55172
|
-
const
|
|
55727
|
+
const changed = /* @__PURE__ */ new Map();
|
|
55173
55728
|
const files = new Set(tracked.split("\0").filter(Boolean));
|
|
55174
55729
|
const tokens = porcelain.split("\0");
|
|
55175
55730
|
for (let i = 0; i < tokens.length; i++) {
|
|
@@ -55177,7 +55732,7 @@ async function treeSnapshot(root, head) {
|
|
|
55177
55732
|
if (!row) continue;
|
|
55178
55733
|
const xy = row.slice(0, 2), file4 = row.slice(3);
|
|
55179
55734
|
const letter = xy === "??" ? "?" : statusLetter(xy[1] !== " " ? xy[1] : xy[0]);
|
|
55180
|
-
|
|
55735
|
+
changed.set(file4, letter);
|
|
55181
55736
|
files.add(file4);
|
|
55182
55737
|
if (/[RC]/.test(xy)) i++;
|
|
55183
55738
|
}
|
|
@@ -55202,12 +55757,12 @@ async function treeSnapshot(root, head) {
|
|
|
55202
55757
|
}
|
|
55203
55758
|
if (directory) {
|
|
55204
55759
|
entry2.fileCount = (entry2.fileCount ?? 0) + 1;
|
|
55205
|
-
if (
|
|
55206
|
-
} else if (
|
|
55760
|
+
if (changed.has(file4)) entry2.status = "changed";
|
|
55761
|
+
} else if (changed.has(file4)) entry2.status = entry2.kind === "dir" ? "changed" : changed.get(file4);
|
|
55207
55762
|
parent = full2;
|
|
55208
55763
|
}
|
|
55209
55764
|
}
|
|
55210
|
-
const version2 =
|
|
55765
|
+
const version2 = createHash26("sha256").update(head).update(tracked).update(porcelain).digest("hex");
|
|
55211
55766
|
return { version: version2, levels: new Map([...levels].map(([directory, entries2]) => [
|
|
55212
55767
|
directory,
|
|
55213
55768
|
[...entries2.values()].sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "dir" ? -1 : 1)
|
|
@@ -55331,6 +55886,16 @@ async function gitDiscard(cwd, paths) {
|
|
|
55331
55886
|
treeCache.delete(root);
|
|
55332
55887
|
try {
|
|
55333
55888
|
const files = await repositoryPaths(root, paths);
|
|
55889
|
+
for (const file4 of files) {
|
|
55890
|
+
const info = await lstat25(path95.join(root, file4)).catch((error62) => {
|
|
55891
|
+
if (error62.code === "ENOENT") return void 0;
|
|
55892
|
+
throw error62;
|
|
55893
|
+
});
|
|
55894
|
+
const indexed = info ? "" : await git(root, "ls-files", "-z", "--", `:(literal)${file4}`);
|
|
55895
|
+
if (info?.isDirectory() || indexed.split("\0").some((entry2) => entry2.startsWith(`${file4}/`))) {
|
|
55896
|
+
throw new BridgeError(409, "Discard the files in this directory one at a time.");
|
|
55897
|
+
}
|
|
55898
|
+
}
|
|
55334
55899
|
const untracked = new Set((await git(root, "ls-files", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean));
|
|
55335
55900
|
for (const file4 of files) {
|
|
55336
55901
|
const literal2 = `:(literal)${file4}`;
|
|
@@ -55429,17 +55994,32 @@ async function readGitShow(cwd, sha) {
|
|
|
55429
55994
|
truncated
|
|
55430
55995
|
};
|
|
55431
55996
|
}
|
|
55432
|
-
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;
|
|
55997
|
+
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;
|
|
55433
55998
|
var init_git = __esm({
|
|
55434
55999
|
"src/bridge/git.ts"() {
|
|
55435
56000
|
"use strict";
|
|
55436
56001
|
init_protocol();
|
|
55437
56002
|
init_projects();
|
|
55438
56003
|
init_git_hosts();
|
|
56004
|
+
init_git_host_auth();
|
|
56005
|
+
init_lookup_cache();
|
|
55439
56006
|
init_git_hosts();
|
|
55440
56007
|
UNKNOWN_COUNTS = { additions: 0, deletions: 0, countsComplete: false };
|
|
55441
56008
|
NO_DIFF2 = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
|
|
55442
56009
|
MAX_STATUS_ROWS = 500;
|
|
56010
|
+
REVOKING = /* @__PURE__ */ new Set(["auth", "not-found"]);
|
|
56011
|
+
pullsCache = new LookupCache(
|
|
56012
|
+
3e4,
|
|
56013
|
+
3e5,
|
|
56014
|
+
64,
|
|
56015
|
+
(value2) => value2.available === true,
|
|
56016
|
+
45e3,
|
|
56017
|
+
(value2) => value2.available === false && REVOKING.has(String(value2.reason))
|
|
56018
|
+
);
|
|
56019
|
+
credentialReads = /* @__PURE__ */ new Map();
|
|
56020
|
+
CREDENTIAL_TTL_MS = 5e3;
|
|
56021
|
+
CredentialsChanged = class extends Error {
|
|
56022
|
+
};
|
|
55443
56023
|
treeCache = /* @__PURE__ */ new Map();
|
|
55444
56024
|
TREE_TTL_MS = 2e3;
|
|
55445
56025
|
MAX_IGNORED_ENTRIES = 1e3;
|
|
@@ -55451,12 +56031,12 @@ var init_git = __esm({
|
|
|
55451
56031
|
});
|
|
55452
56032
|
|
|
55453
56033
|
// src/bridge/git-worktrees.ts
|
|
55454
|
-
import { createHash as
|
|
56034
|
+
import { createHash as createHash27 } from "node:crypto";
|
|
55455
56035
|
import { realpath as realpath13, stat as stat20 } from "node:fs/promises";
|
|
55456
56036
|
import { homedir as homedir15 } from "node:os";
|
|
55457
56037
|
import path96 from "node:path";
|
|
55458
56038
|
function worktreeId(abs) {
|
|
55459
|
-
return
|
|
56039
|
+
return createHash27("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
|
|
55460
56040
|
}
|
|
55461
56041
|
async function listed3(root) {
|
|
55462
56042
|
const output2 = await git(root, "worktree", "list", "--porcelain", "-z");
|
|
@@ -55537,7 +56117,7 @@ async function readGitWorktrees(cwd, workers) {
|
|
|
55537
56117
|
behind = Number(counts[0]);
|
|
55538
56118
|
ahead = Number(counts[1]);
|
|
55539
56119
|
}
|
|
55540
|
-
const
|
|
56120
|
+
const changed = uncommitted(await git(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal"));
|
|
55541
56121
|
const worker = await workerFor(worktree.abs, workers, worktrees.map((item) => item.abs));
|
|
55542
56122
|
return {
|
|
55543
56123
|
id: worktreeId(worktree.abs),
|
|
@@ -55546,7 +56126,7 @@ async function readGitWorktrees(cwd, workers) {
|
|
|
55546
56126
|
head: worktree.head,
|
|
55547
56127
|
ahead,
|
|
55548
56128
|
behind,
|
|
55549
|
-
changed
|
|
56129
|
+
changed,
|
|
55550
56130
|
...worktree.abs === main2 ? { main: true } : {},
|
|
55551
56131
|
...worktree.locked ? { locked: true } : {},
|
|
55552
56132
|
...worker ? { worker: {
|
|
@@ -55695,7 +56275,7 @@ var init_git_sync = __esm({
|
|
|
55695
56275
|
});
|
|
55696
56276
|
|
|
55697
56277
|
// src/bridge/git-review.ts
|
|
55698
|
-
import { mkdtemp as mkdtemp5, rm as
|
|
56278
|
+
import { mkdtemp as mkdtemp5, rm as rm11, writeFile as writeFile6 } from "node:fs/promises";
|
|
55699
56279
|
import { tmpdir as tmpdir4 } from "node:os";
|
|
55700
56280
|
import path97 from "node:path";
|
|
55701
56281
|
async function repository4(cwd) {
|
|
@@ -55750,7 +56330,25 @@ function headerName(raw) {
|
|
|
55750
56330
|
function patchFiles(patch) {
|
|
55751
56331
|
const files = /* @__PURE__ */ new Set();
|
|
55752
56332
|
let hunks = 0;
|
|
56333
|
+
let oldLeft = 0, newLeft = 0;
|
|
55753
56334
|
for (const line of patch.split("\n")) {
|
|
56335
|
+
if (oldLeft > 0 || newLeft > 0) {
|
|
56336
|
+
if (line.startsWith("\\")) continue;
|
|
56337
|
+
if (line.startsWith("-")) oldLeft--;
|
|
56338
|
+
else if (line.startsWith("+")) newLeft--;
|
|
56339
|
+
else {
|
|
56340
|
+
oldLeft--;
|
|
56341
|
+
newLeft--;
|
|
56342
|
+
}
|
|
56343
|
+
continue;
|
|
56344
|
+
}
|
|
56345
|
+
const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
|
|
56346
|
+
if (hunk) {
|
|
56347
|
+
hunks++;
|
|
56348
|
+
oldLeft = hunk[1] === void 0 ? 1 : Number(hunk[1]);
|
|
56349
|
+
newLeft = hunk[2] === void 0 ? 1 : Number(hunk[2]);
|
|
56350
|
+
continue;
|
|
56351
|
+
}
|
|
55754
56352
|
if (/^(?:rename|copy) (?:from|to) |^(?:old|new|deleted file|new file) mode |^GIT binary patch|^Binary files /.test(line)) {
|
|
55755
56353
|
throw new BridgeError(400, "Only text hunks can be staged one at a time. Stage the whole file instead.");
|
|
55756
56354
|
}
|
|
@@ -55758,7 +56356,6 @@ function patchFiles(patch) {
|
|
|
55758
56356
|
const name = headerName(line.slice(4).replace(/\t.*$/, ""));
|
|
55759
56357
|
if (name) files.add(name);
|
|
55760
56358
|
}
|
|
55761
|
-
if (line.startsWith("@@ ")) hunks++;
|
|
55762
56359
|
}
|
|
55763
56360
|
if (!files.size || !hunks) throw new BridgeError(400, "This patch has no hunks.");
|
|
55764
56361
|
if (files.size > 1) throw new BridgeError(400, "Stage hunks of one file at a time.");
|
|
@@ -55773,7 +56370,7 @@ async function gitApply(cwd, rawPatch, reverse) {
|
|
|
55773
56370
|
const scratch = await mkdtemp5(path97.join(tmpdir4(), "phren-apply-"));
|
|
55774
56371
|
const patchFile = path97.join(scratch, "hunk.patch");
|
|
55775
56372
|
try {
|
|
55776
|
-
await
|
|
56373
|
+
await writeFile6(patchFile, rawPatch.endsWith("\n") ? rawPatch : rawPatch + "\n", { mode: 384 });
|
|
55777
56374
|
const args = ["apply", "--cached", "--whitespace=nowarn", ...reverse === true ? ["-R"] : [], "--", patchFile];
|
|
55778
56375
|
invalidateTree(root);
|
|
55779
56376
|
try {
|
|
@@ -55785,7 +56382,7 @@ async function gitApply(cwd, rawPatch, reverse) {
|
|
|
55785
56382
|
return { ok: true, path: file4, staged: reverse !== true };
|
|
55786
56383
|
} finally {
|
|
55787
56384
|
invalidateTree(root);
|
|
55788
|
-
await
|
|
56385
|
+
await rm11(scratch, { recursive: true, force: true });
|
|
55789
56386
|
}
|
|
55790
56387
|
}
|
|
55791
56388
|
function sessionChanges(root, history) {
|
|
@@ -55844,8 +56441,8 @@ var init_git_review = __esm({
|
|
|
55844
56441
|
// src/bridge/approval-rules.ts
|
|
55845
56442
|
import { execFile as execFile22 } from "node:child_process";
|
|
55846
56443
|
import { promisify as promisify20 } from "node:util";
|
|
55847
|
-
import { createHash as
|
|
55848
|
-
import { lstat as lstat26, mkdir as mkdir24, readFile as
|
|
56444
|
+
import { createHash as createHash28, createPublicKey, verify } from "node:crypto";
|
|
56445
|
+
import { lstat as lstat26, mkdir as mkdir24, readFile as readFile40, realpath as realpath14 } from "node:fs/promises";
|
|
55849
56446
|
import { hostname as hostname8 } from "node:os";
|
|
55850
56447
|
import path98 from "node:path";
|
|
55851
56448
|
async function git6(cwd, ...args) {
|
|
@@ -55856,7 +56453,7 @@ async function git6(cwd, ...args) {
|
|
|
55856
56453
|
})).stdout;
|
|
55857
56454
|
}
|
|
55858
56455
|
async function ownerKeys() {
|
|
55859
|
-
const keys2 = await
|
|
56456
|
+
const keys2 = await readFile40(path98.join(homeDir(), ".ssh", "authorized_keys"), "utf8");
|
|
55860
56457
|
const result = /* @__PURE__ */ new Set();
|
|
55861
56458
|
for (const line of keys2.split("\n")) {
|
|
55862
56459
|
const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-iphone\s*$/.exec(line);
|
|
@@ -55872,7 +56469,7 @@ function verified(envelope, keys2) {
|
|
|
55872
56469
|
const key4 = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
|
|
55873
56470
|
if (!verify(null, payload, key4, signature)) throw forbidden();
|
|
55874
56471
|
const operation = operationSchema.parse(JSON.parse(payload.toString("utf8")));
|
|
55875
|
-
return { operation, owner:
|
|
56472
|
+
return { operation, owner: createHash28("sha256").update(raw).digest("hex") };
|
|
55876
56473
|
}
|
|
55877
56474
|
async function privateJSON(file4, fallback2, max = 2097152) {
|
|
55878
56475
|
const info = await lstat26(file4).catch((error62) => {
|
|
@@ -55881,7 +56478,7 @@ async function privateJSON(file4, fallback2, max = 2097152) {
|
|
|
55881
56478
|
});
|
|
55882
56479
|
if (!info) return fallback2;
|
|
55883
56480
|
if (!info.isFile() || info.isSymbolicLink() || info.mode & 63 || info.size > max) throw new BridgeError(409, "Approval policy must be a private regular file.");
|
|
55884
|
-
return JSON.parse(await
|
|
56481
|
+
return JSON.parse(await readFile40(file4, "utf8"));
|
|
55885
56482
|
}
|
|
55886
56483
|
async function readPolicy(root) {
|
|
55887
56484
|
const policy = policySchema.parse(await privateJSON(policyPath(root), { operations: [] }));
|
|
@@ -55922,7 +56519,7 @@ async function locked(root, work) {
|
|
|
55922
56519
|
}
|
|
55923
56520
|
async function listApprovalRules(root = bridgeRoot(), pairedKey) {
|
|
55924
56521
|
try {
|
|
55925
|
-
const pairedOwner = pairedKey ?
|
|
56522
|
+
const pairedOwner = pairedKey ? createHash28("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : void 0;
|
|
55926
56523
|
return [...(await readPolicy(root)).rules.values()].map((rule2) => ({
|
|
55927
56524
|
...rule2,
|
|
55928
56525
|
signerFingerprint: "SHA256:" + Buffer.from(rule2.owner, "hex").toString("base64").replace(/=+$/, ""),
|
|
@@ -56040,7 +56637,7 @@ var init_approval_rules = __esm({
|
|
|
56040
56637
|
});
|
|
56041
56638
|
|
|
56042
56639
|
// src/bridge/conductor-context.ts
|
|
56043
|
-
import { readFile as
|
|
56640
|
+
import { readFile as readFile41 } from "node:fs/promises";
|
|
56044
56641
|
import path99 from "node:path";
|
|
56045
56642
|
async function conductorBrief() {
|
|
56046
56643
|
let source;
|
|
@@ -56051,7 +56648,7 @@ async function conductorBrief() {
|
|
|
56051
56648
|
path99.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
56052
56649
|
path99.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
56053
56650
|
]) {
|
|
56054
|
-
source = await
|
|
56651
|
+
source = await readFile41(candidate, "utf8").catch(() => void 0);
|
|
56055
56652
|
if (source !== void 0) break;
|
|
56056
56653
|
}
|
|
56057
56654
|
}
|
|
@@ -56064,7 +56661,7 @@ async function conductorBrief() {
|
|
|
56064
56661
|
async function ensureConductorBrief(brief) {
|
|
56065
56662
|
const file4 = path99.join(bridgeRoot(), "conductor", "brief.md");
|
|
56066
56663
|
const content = (brief ?? await conductorBrief()) + "\n";
|
|
56067
|
-
if (await
|
|
56664
|
+
if (await readFile41(file4, "utf8").catch(() => void 0) !== content) await atomicInPrivateDir(file4, content);
|
|
56068
56665
|
return file4;
|
|
56069
56666
|
}
|
|
56070
56667
|
async function conductorContext(target, snapshot2) {
|
|
@@ -56084,92 +56681,11 @@ var init_conductor_context = __esm({
|
|
|
56084
56681
|
}
|
|
56085
56682
|
});
|
|
56086
56683
|
|
|
56087
|
-
// src/bridge/codex-review-mode.ts
|
|
56088
|
-
import { open as open18 } from "node:fs/promises";
|
|
56089
|
-
import path100 from "node:path";
|
|
56090
|
-
async function codexAutoReview(transcriptPath2) {
|
|
56091
|
-
if (typeof transcriptPath2 !== "string" || !path100.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path100.basename(transcriptPath2))) return false;
|
|
56092
|
-
const file4 = await open18(transcriptPath2, "r").catch(() => void 0);
|
|
56093
|
-
if (!file4) return false;
|
|
56094
|
-
try {
|
|
56095
|
-
const size = (await file4.stat()).size;
|
|
56096
|
-
let end = size, carry = Buffer.alloc(0);
|
|
56097
|
-
while (end > 0 && size - end < SCAN_LIMIT) {
|
|
56098
|
-
const start = Math.max(0, end - CHUNK), buffer = Buffer.alloc(end - start);
|
|
56099
|
-
await file4.read(buffer, 0, buffer.length, start);
|
|
56100
|
-
const bytes = Buffer.concat([buffer, carry]);
|
|
56101
|
-
let lineEnd = bytes.length;
|
|
56102
|
-
for (let at2 = bytes.lastIndexOf(10, lineEnd - 1); at2 >= 0; at2 = bytes.lastIndexOf(10, lineEnd - 1)) {
|
|
56103
|
-
const settings2 = reviewSettings(bytes.subarray(at2 + 1, lineEnd).toString("utf8"));
|
|
56104
|
-
if (settings2) return autoReviewed(settings2);
|
|
56105
|
-
lineEnd = at2;
|
|
56106
|
-
if (at2 === 0) break;
|
|
56107
|
-
}
|
|
56108
|
-
carry = bytes.subarray(0, lineEnd);
|
|
56109
|
-
end = start;
|
|
56110
|
-
}
|
|
56111
|
-
const settings = end === 0 ? reviewSettings(carry.toString("utf8")) : void 0;
|
|
56112
|
-
return !!settings && autoReviewed(settings);
|
|
56113
|
-
} catch {
|
|
56114
|
-
return false;
|
|
56115
|
-
} finally {
|
|
56116
|
-
await file4.close().catch(() => {
|
|
56117
|
-
});
|
|
56118
|
-
}
|
|
56119
|
-
}
|
|
56120
|
-
function reviewSettings(line) {
|
|
56121
|
-
if (!line.includes('"approvals_reviewer"') || !(line.includes('"type":"turn_context"') || line.includes('"type":"thread_settings_applied"'))) return void 0;
|
|
56122
|
-
try {
|
|
56123
|
-
const entry2 = JSON.parse(line);
|
|
56124
|
-
const payload = entry2?.payload;
|
|
56125
|
-
const settings = entry2?.type === "turn_context" ? payload : entry2?.type === "event_msg" && payload?.type === "thread_settings_applied" ? payload.thread_settings : void 0;
|
|
56126
|
-
if (!settings || !("approvals_reviewer" in settings)) return void 0;
|
|
56127
|
-
return { reviewer: settings.approvals_reviewer, policy: settings.approval_policy };
|
|
56128
|
-
} catch {
|
|
56129
|
-
return void 0;
|
|
56130
|
-
}
|
|
56131
|
-
}
|
|
56132
|
-
function autoReviewed({ reviewer, policy }) {
|
|
56133
|
-
return reviewer === "auto_review" && (policy === "on-request" || !!policy && typeof policy === "object" && "granular" in policy);
|
|
56134
|
-
}
|
|
56135
|
-
var SCAN_LIMIT, CHUNK;
|
|
56136
|
-
var init_codex_review_mode = __esm({
|
|
56137
|
-
"src/bridge/codex-review-mode.ts"() {
|
|
56138
|
-
"use strict";
|
|
56139
|
-
SCAN_LIMIT = 64 * 1048576;
|
|
56140
|
-
CHUNK = 1048576;
|
|
56141
|
-
}
|
|
56142
|
-
});
|
|
56143
|
-
|
|
56144
|
-
// src/bridge/codex-thread-origin.ts
|
|
56145
|
-
import { open as open19 } from "node:fs/promises";
|
|
56146
|
-
import path101 from "node:path";
|
|
56147
|
-
async function codexForeignThread(transcriptPath2) {
|
|
56148
|
-
if (typeof transcriptPath2 !== "string" || !path101.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path101.basename(transcriptPath2))) return false;
|
|
56149
|
-
const file4 = await open19(transcriptPath2, "r").catch(() => void 0);
|
|
56150
|
-
if (!file4) return false;
|
|
56151
|
-
try {
|
|
56152
|
-
const buffer = Buffer.alloc(4096), { bytesRead } = await file4.read(buffer, 0, buffer.length, 0);
|
|
56153
|
-
return foreignMeta(buffer.subarray(0, bytesRead).toString("utf8"));
|
|
56154
|
-
} finally {
|
|
56155
|
-
await file4.close();
|
|
56156
|
-
}
|
|
56157
|
-
}
|
|
56158
|
-
function foreignMeta(head) {
|
|
56159
|
-
if (!head.includes('"session_meta"')) return false;
|
|
56160
|
-
return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
|
|
56161
|
-
}
|
|
56162
|
-
var init_codex_thread_origin = __esm({
|
|
56163
|
-
"src/bridge/codex-thread-origin.ts"() {
|
|
56164
|
-
"use strict";
|
|
56165
|
-
}
|
|
56166
|
-
});
|
|
56167
|
-
|
|
56168
56684
|
// src/bridge/push.ts
|
|
56169
|
-
import { createCipheriv, createHmac as createHmac3, createPrivateKey, randomBytes as
|
|
56170
|
-
import { readFile as
|
|
56685
|
+
import { createCipheriv, createHmac as createHmac3, createPrivateKey, randomBytes as randomBytes7, sign } from "node:crypto";
|
|
56686
|
+
import { readFile as readFile42, stat as stat21 } from "node:fs/promises";
|
|
56171
56687
|
import { connect as connect3 } from "node:http2";
|
|
56172
|
-
import
|
|
56688
|
+
import path100 from "node:path";
|
|
56173
56689
|
function scheduleCollapseId(kind, runId) {
|
|
56174
56690
|
return `${runId.slice(0, 63 - kind.length)}-${kind}`;
|
|
56175
56691
|
}
|
|
@@ -56238,7 +56754,7 @@ async function secureJSON(file4, schema) {
|
|
|
56238
56754
|
try {
|
|
56239
56755
|
const metadata = await stat21(file4);
|
|
56240
56756
|
if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
56241
|
-
return schema.parse(JSON.parse(await
|
|
56757
|
+
return schema.parse(JSON.parse(await readFile42(file4, "utf8")));
|
|
56242
56758
|
} catch {
|
|
56243
56759
|
return void 0;
|
|
56244
56760
|
}
|
|
@@ -56247,12 +56763,12 @@ async function secureFile(file4) {
|
|
|
56247
56763
|
try {
|
|
56248
56764
|
const metadata = await stat21(file4);
|
|
56249
56765
|
if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
56250
|
-
return await
|
|
56766
|
+
return await readFile42(file4, "utf8");
|
|
56251
56767
|
} catch {
|
|
56252
56768
|
return void 0;
|
|
56253
56769
|
}
|
|
56254
56770
|
}
|
|
56255
|
-
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG ||
|
|
56771
|
+
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path100.join(bridgeRoot(), "apns.json")) {
|
|
56256
56772
|
return [
|
|
56257
56773
|
"Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
|
|
56258
56774
|
"1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
|
|
@@ -56269,7 +56785,7 @@ function upsertPushDevice(devices, value2) {
|
|
|
56269
56785
|
const device = deviceSchema.parse(value2);
|
|
56270
56786
|
return [...devices.filter((item) => item.deviceID !== device.deviceID), device].slice(-16);
|
|
56271
56787
|
}
|
|
56272
|
-
function relayCiphertext(key4, payload, nonce =
|
|
56788
|
+
function relayCiphertext(key4, payload, nonce = randomBytes7(12)) {
|
|
56273
56789
|
const aps = payload.aps ?? {};
|
|
56274
56790
|
let body2 = aps.alert?.body ?? "";
|
|
56275
56791
|
for (; ; ) {
|
|
@@ -56405,13 +56921,13 @@ var init_push = __esm({
|
|
|
56405
56921
|
ApprovalPushService = class {
|
|
56406
56922
|
devices = [];
|
|
56407
56923
|
sender;
|
|
56408
|
-
devicesFile =
|
|
56924
|
+
devicesFile = path100.join(bridgeRoot(), "push-devices.json");
|
|
56409
56925
|
async start() {
|
|
56410
56926
|
this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
|
|
56411
|
-
const configFile = process.env.PHREN_APNS_CONFIG ||
|
|
56927
|
+
const configFile = process.env.PHREN_APNS_CONFIG || path100.join(bridgeRoot(), "apns.json");
|
|
56412
56928
|
const config4 = await secureJSON(configFile, configSchema2);
|
|
56413
56929
|
if (!config4) return;
|
|
56414
|
-
const keyPath =
|
|
56930
|
+
const keyPath = path100.isAbsolute(config4.privateKeyPath) ? config4.privateKeyPath : path100.resolve(path100.dirname(configFile), config4.privateKeyPath);
|
|
56415
56931
|
const key4 = await secureFile(keyPath);
|
|
56416
56932
|
if (key4) this.sender = new APNsSender(config4, key4);
|
|
56417
56933
|
}
|
|
@@ -56739,10 +57255,18 @@ async function scopedDispatch(scope, command, io) {
|
|
|
56739
57255
|
answered = true;
|
|
56740
57256
|
io.output.write(httpResponse(503, "Phren Hook is not running on this computer."));
|
|
56741
57257
|
});
|
|
56742
|
-
socket.
|
|
57258
|
+
socket.setTimeout(io.answerIdleMs ?? ANSWER_IDLE_MS, () => socket.destroy());
|
|
57259
|
+
const drop = () => socket.destroy();
|
|
57260
|
+
io.output.once("error", drop);
|
|
57261
|
+
io.output.once("close", drop);
|
|
57262
|
+
socket.on("close", () => {
|
|
57263
|
+
io.output.off("error", drop);
|
|
57264
|
+
io.output.off("close", drop);
|
|
57265
|
+
resolve17();
|
|
57266
|
+
});
|
|
56743
57267
|
});
|
|
56744
57268
|
}
|
|
56745
|
-
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;
|
|
57269
|
+
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;
|
|
56746
57270
|
var init_scoped_gateway = __esm({
|
|
56747
57271
|
"src/bridge/scoped-gateway.ts"() {
|
|
56748
57272
|
"use strict";
|
|
@@ -56755,6 +57279,7 @@ var init_scoped_gateway = __esm({
|
|
|
56755
57279
|
MAX_HEADER_LINE = 8192;
|
|
56756
57280
|
MAX_HEADERS = 32;
|
|
56757
57281
|
READ_TIMEOUT_MS = 1e4;
|
|
57282
|
+
ANSWER_IDLE_MS = 6e4;
|
|
56758
57283
|
PROJECT = PROJECT_NAME2.source.slice(1, -1);
|
|
56759
57284
|
one = (query, key4) => query.get(key4)?.length === 1 ? query.get(key4)[0] : void 0;
|
|
56760
57285
|
only = (query, keys2) => [...query.keys()].every((key4) => keys2.includes(key4));
|
|
@@ -56828,10 +57353,10 @@ var init_pair = __esm({
|
|
|
56828
57353
|
|
|
56829
57354
|
// src/bridge/opencode-permissions.ts
|
|
56830
57355
|
import { randomUUID as randomUUID23 } from "node:crypto";
|
|
56831
|
-
import { lstat as lstat27, mkdir as mkdir25, readFile as
|
|
56832
|
-
import
|
|
57356
|
+
import { lstat as lstat27, mkdir as mkdir25, readFile as readFile43, rename as rename6, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
|
|
57357
|
+
import path101 from "node:path";
|
|
56833
57358
|
function opencodeConfigPath(env = process.env, home = homeDir(env)) {
|
|
56834
|
-
return
|
|
57359
|
+
return path101.join(env.XDG_CONFIG_HOME || path101.join(home, ".config"), "opencode", "opencode.json");
|
|
56835
57360
|
}
|
|
56836
57361
|
function opencodeToolName(value2) {
|
|
56837
57362
|
if (typeof value2 !== "string") return void 0;
|
|
@@ -56841,7 +57366,7 @@ function opencodeToolName(value2) {
|
|
|
56841
57366
|
async function readConfig2(file4) {
|
|
56842
57367
|
let text5;
|
|
56843
57368
|
try {
|
|
56844
|
-
text5 = await
|
|
57369
|
+
text5 = await readFile43(file4, "utf8");
|
|
56845
57370
|
} catch (error62) {
|
|
56846
57371
|
if (error62.code === "ENOENT") return {};
|
|
56847
57372
|
throw new BridgeError(409, "Could not read ~/.config/opencode/opencode.json.");
|
|
@@ -56879,12 +57404,12 @@ async function allowOpencodeToolEverywhere(tool, file4 = opencodeConfigPath()) {
|
|
|
56879
57404
|
try {
|
|
56880
57405
|
const config4 = withAllowedTool(await readConfig2(file4), name);
|
|
56881
57406
|
const mode = (await lstat27(file4).catch(() => void 0))?.mode;
|
|
56882
|
-
await mkdir25(
|
|
57407
|
+
await mkdir25(path101.dirname(file4), { recursive: true, mode: 448 });
|
|
56883
57408
|
const temporary = `${file4}.${randomUUID23()}.tmp`;
|
|
56884
|
-
await
|
|
57409
|
+
await writeFile7(temporary, `${JSON.stringify(config4, null, 2)}
|
|
56885
57410
|
`, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
|
|
56886
57411
|
try {
|
|
56887
|
-
await
|
|
57412
|
+
await rename6(temporary, file4);
|
|
56888
57413
|
} finally {
|
|
56889
57414
|
await unlink6(temporary).catch(() => {
|
|
56890
57415
|
});
|
|
@@ -56904,29 +57429,37 @@ var init_opencode_permissions = __esm({
|
|
|
56904
57429
|
});
|
|
56905
57430
|
|
|
56906
57431
|
// src/bridge/prompt-deliveries.ts
|
|
56907
|
-
import { createHash as
|
|
56908
|
-
import { readFileSync as
|
|
56909
|
-
import { open as
|
|
57432
|
+
import { createHash as createHash29 } from "node:crypto";
|
|
57433
|
+
import { readFileSync as readFileSync44 } from "node:fs";
|
|
57434
|
+
import { open as open18 } from "node:fs/promises";
|
|
56910
57435
|
function promptKey(text5) {
|
|
56911
57436
|
return unwrapPastedContent(text5).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
|
|
56912
57437
|
}
|
|
56913
|
-
|
|
56914
|
-
const
|
|
57438
|
+
function matchingOffsets(buffer, start, record4) {
|
|
57439
|
+
const entries2 = [];
|
|
57440
|
+
const lines = buffer.toString("utf8").split("\n");
|
|
57441
|
+
let offset = start + buffer.length;
|
|
57442
|
+
for (let index2 = lines.length - 1; index2 >= 0; index2--) {
|
|
57443
|
+
const line = lines[index2];
|
|
57444
|
+
offset -= Buffer.byteLength(line) + (index2 < lines.length - 1 ? 1 : 0);
|
|
57445
|
+
let row;
|
|
57446
|
+
try {
|
|
57447
|
+
row = object2(JSON.parse(line));
|
|
57448
|
+
} catch {
|
|
57449
|
+
continue;
|
|
57450
|
+
}
|
|
57451
|
+
const stamp2 = Date.parse(String(row.timestamp ?? ""));
|
|
57452
|
+
if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) break;
|
|
57453
|
+
if (userTexts(row).some((text5) => promptHash(text5) === record4.hash)) entries2.push({ offset, hook: row.type === "user" });
|
|
57454
|
+
}
|
|
57455
|
+
return entries2;
|
|
57456
|
+
}
|
|
57457
|
+
async function transcriptEntries(record4) {
|
|
57458
|
+
const file4 = await open18(await transcriptPath(record4.source, record4.session), "r");
|
|
56915
57459
|
try {
|
|
56916
57460
|
const size = (await file4.stat()).size, start = Math.max(0, size - 524288), buffer = Buffer.alloc(size - start);
|
|
56917
57461
|
await file4.read(buffer, 0, buffer.length, start);
|
|
56918
|
-
|
|
56919
|
-
let row;
|
|
56920
|
-
try {
|
|
56921
|
-
row = object2(JSON.parse(line));
|
|
56922
|
-
} catch {
|
|
56923
|
-
continue;
|
|
56924
|
-
}
|
|
56925
|
-
const stamp2 = Date.parse(String(row.timestamp ?? ""));
|
|
56926
|
-
if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) break;
|
|
56927
|
-
for (const text5 of userTexts(row)) if (promptHash(text5) === record4.hash) return true;
|
|
56928
|
-
}
|
|
56929
|
-
return false;
|
|
57462
|
+
return matchingOffsets(buffer, start, record4);
|
|
56930
57463
|
} finally {
|
|
56931
57464
|
await file4.close();
|
|
56932
57465
|
}
|
|
@@ -56938,12 +57471,13 @@ function userTexts(row) {
|
|
|
56938
57471
|
else for (const block of objects(content)) if (typeof block.text === "string") texts.push(block.text);
|
|
56939
57472
|
};
|
|
56940
57473
|
if (row.type === "user" && !row.isMeta) blocks(object2(row.message).content);
|
|
57474
|
+
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);
|
|
56941
57475
|
const payload = object2(row.payload);
|
|
56942
57476
|
if (payload.type === "user_message" && typeof payload.message === "string") texts.push(payload.message);
|
|
56943
57477
|
if (payload.type === "message" && payload.role === "user") blocks(payload.content);
|
|
56944
57478
|
return texts;
|
|
56945
57479
|
}
|
|
56946
|
-
var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
|
|
57480
|
+
var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, LANDED_CHECK_MS, ENTRY_SLACK_MS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
|
|
56947
57481
|
var init_prompt_deliveries = __esm({
|
|
56948
57482
|
"src/bridge/prompt-deliveries.ts"() {
|
|
56949
57483
|
"use strict";
|
|
@@ -56953,8 +57487,10 @@ var init_prompt_deliveries = __esm({
|
|
|
56953
57487
|
DELIVERY_RETENTION_MS = 24 * 36e5;
|
|
56954
57488
|
DELIVERY_GIVE_UP_MS = 3e4;
|
|
56955
57489
|
MAX_RECORDS = 512;
|
|
57490
|
+
LANDED_CHECK_MS = 3e3;
|
|
57491
|
+
ENTRY_SLACK_MS = 5e3;
|
|
56956
57492
|
PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
|
|
56957
|
-
promptHash = (text5) =>
|
|
57493
|
+
promptHash = (text5) => createHash29("sha256").update(promptKey(text5)).digest("hex");
|
|
56958
57494
|
recordSchema2 = external_exports.object({
|
|
56959
57495
|
id: external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(),
|
|
56960
57496
|
hash: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
@@ -56967,16 +57503,18 @@ var init_prompt_deliveries = __esm({
|
|
|
56967
57503
|
reason: external_exports.string().max(500).optional(),
|
|
56968
57504
|
at: external_exports.number(),
|
|
56969
57505
|
settledAt: external_exports.number().optional(),
|
|
56970
|
-
stoppedAt: external_exports.number().optional()
|
|
57506
|
+
stoppedAt: external_exports.number().optional(),
|
|
57507
|
+
/** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
|
|
57508
|
+
entry: external_exports.number().optional()
|
|
56971
57509
|
}).strict();
|
|
56972
|
-
PromptDeliveries = class {
|
|
56973
|
-
constructor(file4, now = Date.now, landed =
|
|
57510
|
+
PromptDeliveries = class _PromptDeliveries {
|
|
57511
|
+
constructor(file4, now = Date.now, landed = transcriptEntries) {
|
|
56974
57512
|
this.file = file4;
|
|
56975
57513
|
this.now = now;
|
|
56976
57514
|
this.landed = landed;
|
|
56977
57515
|
if (!file4) return;
|
|
56978
57516
|
try {
|
|
56979
|
-
for (const row of objects(object2(JSON.parse(
|
|
57517
|
+
for (const row of objects(object2(JSON.parse(readFileSync44(file4, "utf8"))).records)) {
|
|
56980
57518
|
const parsed = recordSchema2.safeParse(row);
|
|
56981
57519
|
if (parsed.success) this.records.push({ ...parsed.data, state: parsed.data.state === "typed" ? "queued" : parsed.data.state });
|
|
56982
57520
|
}
|
|
@@ -56990,6 +57528,18 @@ var init_prompt_deliveries = __esm({
|
|
|
56990
57528
|
records = [];
|
|
56991
57529
|
waiters = /* @__PURE__ */ new Map();
|
|
56992
57530
|
writing = Promise.resolve();
|
|
57531
|
+
/** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
|
|
57532
|
+
hookPanes = /* @__PURE__ */ new Set();
|
|
57533
|
+
paneKey(target) {
|
|
57534
|
+
return [target.server, target.pane, target.source].join("|");
|
|
57535
|
+
}
|
|
57536
|
+
static open(record4) {
|
|
57537
|
+
return record4.state === "typed" || record4.state === "queued";
|
|
57538
|
+
}
|
|
57539
|
+
/** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
|
|
57540
|
+
static claimable(record4) {
|
|
57541
|
+
return _PromptDeliveries.open(record4) || record4.state === "failed" && !!record4.hookClaim;
|
|
57542
|
+
}
|
|
56993
57543
|
samePane(record4, target) {
|
|
56994
57544
|
return record4.server === target.server && record4.pane === target.pane && record4.source === target.source;
|
|
56995
57545
|
}
|
|
@@ -57003,7 +57553,7 @@ var init_prompt_deliveries = __esm({
|
|
|
57003
57553
|
}
|
|
57004
57554
|
save() {
|
|
57005
57555
|
if (!this.file) return;
|
|
57006
|
-
const rows2 = this.records.filter((record4) => record4.id).map(({ idleSince: _2, ...row }) => row);
|
|
57556
|
+
const rows2 = this.records.filter((record4) => record4.id || record4.entry !== void 0).map(({ idleSince: _2, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
|
|
57007
57557
|
const file4 = this.file;
|
|
57008
57558
|
this.writing = this.writing.then(() => atomicInPrivateDir(file4, { records: rows2 })).catch(() => void 0);
|
|
57009
57559
|
}
|
|
@@ -57126,14 +57676,14 @@ var init_prompt_deliveries = __esm({
|
|
|
57126
57676
|
* input still pending on the old one stays there, out of the pane's view.
|
|
57127
57677
|
* Fails loudly; a late UserPromptSubmit from the old thread still settles it. */
|
|
57128
57678
|
threadChanged(previous) {
|
|
57129
|
-
let
|
|
57679
|
+
let changed = false;
|
|
57130
57680
|
for (const record4 of this.records) if ((record4.state === "typed" || record4.state === "queued") && this.samePane(record4, previous) && record4.session === previous.session) {
|
|
57131
57681
|
record4.state = "failed";
|
|
57132
57682
|
record4.settledAt = this.now();
|
|
57133
|
-
|
|
57683
|
+
changed = true;
|
|
57134
57684
|
record4.reason = "The pane moved to another Codex conversation before the agent took the message.";
|
|
57135
57685
|
}
|
|
57136
|
-
if (
|
|
57686
|
+
if (changed) this.save();
|
|
57137
57687
|
}
|
|
57138
57688
|
/** False when `id` names another message: other words or another pane. */
|
|
57139
57689
|
sameMessage(id2, target, text5) {
|
|
@@ -57154,23 +57704,104 @@ var init_prompt_deliveries = __esm({
|
|
|
57154
57704
|
/** Conversation `target` just submitted `prompt`. Its own record wins, then
|
|
57155
57705
|
* the oldest open one in the same pane: the agent kept the text across a
|
|
57156
57706
|
* conversation change, and the conversation now in the pane is where it
|
|
57157
|
-
* went. A prompt nothing matches was typed locally. Never refused.
|
|
57158
|
-
|
|
57707
|
+
* went. A prompt nothing matches was typed locally. Never refused.
|
|
57708
|
+
* For Claude the transcript is consulted first and the submission claims
|
|
57709
|
+
* the earliest unclaimed user row with these words, through the same
|
|
57710
|
+
* `settle` and the same table of claimed entries the idle check uses: a
|
|
57711
|
+
* callback for a row already claimed (the idle check settled it, the hook
|
|
57712
|
+
* came late) settles nothing more. */
|
|
57713
|
+
async submitted(target, prompt) {
|
|
57159
57714
|
const hash2 = promptHash(prompt);
|
|
57160
|
-
|
|
57161
|
-
const
|
|
57715
|
+
this.hookPanes.add(this.paneKey(target));
|
|
57716
|
+
const pick3 = () => {
|
|
57717
|
+
const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target) && record5.state !== "delivered");
|
|
57718
|
+
return open30.find((entry3) => entry3.session === target.session) ?? open30[0];
|
|
57719
|
+
};
|
|
57720
|
+
let record4 = pick3();
|
|
57162
57721
|
if (!record4) return;
|
|
57722
|
+
let entry2;
|
|
57723
|
+
if (target.source === "claude") {
|
|
57724
|
+
let rows2;
|
|
57725
|
+
try {
|
|
57726
|
+
rows2 = (await this.landed({ source: target.source, session: target.session, hash: hash2, at: record4.at })).filter((row) => row.hook);
|
|
57727
|
+
} catch {
|
|
57728
|
+
rows2 = void 0;
|
|
57729
|
+
}
|
|
57730
|
+
record4 = pick3();
|
|
57731
|
+
if (!record4) return;
|
|
57732
|
+
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));
|
|
57733
|
+
if (!rows2 && !claimed.size) {
|
|
57734
|
+
this.settle(record4, void 0, target.session);
|
|
57735
|
+
this.save();
|
|
57736
|
+
return;
|
|
57737
|
+
}
|
|
57738
|
+
if (!rows2?.length) {
|
|
57739
|
+
record4.hookClaim = true;
|
|
57740
|
+
record4.session = target.session;
|
|
57741
|
+
return;
|
|
57742
|
+
}
|
|
57743
|
+
const free = rows2.filter((row) => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
|
|
57744
|
+
if (!free) return;
|
|
57745
|
+
entry2 = free.offset;
|
|
57746
|
+
}
|
|
57747
|
+
this.settle(record4, entry2, target.session);
|
|
57748
|
+
this.save();
|
|
57749
|
+
}
|
|
57750
|
+
/** Marks `record` delivered, with the transcript entry that settled it when known. */
|
|
57751
|
+
settle(record4, entry2, session) {
|
|
57163
57752
|
record4.state = "delivered";
|
|
57164
|
-
record4.session = target.session;
|
|
57165
57753
|
record4.settledAt = this.now();
|
|
57166
57754
|
delete record4.reason;
|
|
57167
|
-
|
|
57755
|
+
delete record4.hookClaim;
|
|
57756
|
+
delete record4.seenRow;
|
|
57757
|
+
if (session) record4.session = session;
|
|
57758
|
+
if (entry2 !== void 0) record4.entry = entry2;
|
|
57168
57759
|
this.release(record4, "delivered");
|
|
57169
57760
|
}
|
|
57761
|
+
/** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
|
|
57762
|
+
* An entry settles one message: the table of records' `entry` offsets (per conversation) is the only
|
|
57763
|
+
* state, so neither this path nor the hook's can settle two messages with one turn. A user row is a
|
|
57764
|
+
* turn start whose UserPromptSubmit hook settles the message itself, so while the agent works only a
|
|
57765
|
+
* mid-turn queue removal (no hook fires for it) settles from the transcript; once the agent is idle
|
|
57766
|
+
* (`working` false) a user row settles too, for a hook that never came. Of several identical open
|
|
57767
|
+
* messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
|
|
57768
|
+
async taken(record4, pass, working = false) {
|
|
57769
|
+
if (record4.source !== "claude") return (await this.landed(record4).catch(() => [])).length > 0;
|
|
57770
|
+
const same2 = (other) => other.hash === record4.hash && other.server === record4.server && other.pane === record4.pane && other.session === record4.session;
|
|
57771
|
+
const open30 = this.records.filter((other) => same2(other) && _PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
|
|
57772
|
+
if (open30[0] !== record4) return false;
|
|
57773
|
+
const key4 = [record4.hash, record4.server, record4.pane, record4.session, working].join("|");
|
|
57774
|
+
let free = pass.get(key4);
|
|
57775
|
+
if (!free) {
|
|
57776
|
+
const found = (await this.landed(record4).catch(() => [])).sort((a, b) => a.offset - b.offset);
|
|
57777
|
+
const used = new Set(this.records.filter((other) => same2(other) && other.entry !== void 0).map((other) => other.entry));
|
|
57778
|
+
let hooked = this.records.filter((other) => same2(other) && other.state === "delivered" && other.entry === void 0 && (other.settledAt ?? 0) >= record4.at - ENTRY_SLACK_MS).length;
|
|
57779
|
+
const unclaimed = found.filter((entry3) => !used.has(entry3.offset)).filter((entry3) => !(entry3.hook && hooked-- > 0));
|
|
57780
|
+
if (working) {
|
|
57781
|
+
const row = unclaimed.find((entry3) => entry3.hook);
|
|
57782
|
+
const hookless = !this.hookPanes.has(this.paneKey(record4));
|
|
57783
|
+
const own2 = row && (record4.hookClaim || hookless && record4.seenRow === row.offset);
|
|
57784
|
+
if (row && hookless && !own2) record4.seenRow = row.offset;
|
|
57785
|
+
free = unclaimed.filter((entry3) => !entry3.hook || own2 && entry3 === row);
|
|
57786
|
+
} else free = unclaimed;
|
|
57787
|
+
}
|
|
57788
|
+
if (!_PromptDeliveries.claimable(record4)) return false;
|
|
57789
|
+
const entry2 = free.shift();
|
|
57790
|
+
pass.set(key4, free);
|
|
57791
|
+
if (entry2 === void 0) return false;
|
|
57792
|
+
record4.entry = entry2.offset;
|
|
57793
|
+
return true;
|
|
57794
|
+
}
|
|
57170
57795
|
/** A turn in `target`'s pane ended: the agent now takes held input or never will. */
|
|
57171
57796
|
stopped(target) {
|
|
57172
57797
|
const at2 = this.now();
|
|
57173
|
-
|
|
57798
|
+
this.hookPanes.add(this.paneKey(target));
|
|
57799
|
+
let marked = false;
|
|
57800
|
+
for (const record4 of this.records) if (this.samePane(record4, target) && (record4.state === "typed" || record4.state === "queued") && record4.at < at2) {
|
|
57801
|
+
record4.stoppedAt = at2;
|
|
57802
|
+
marked = true;
|
|
57803
|
+
}
|
|
57804
|
+
if (marked) this.save();
|
|
57174
57805
|
}
|
|
57175
57806
|
/** Called on the Hook's activity tick with a server's panes. A message
|
|
57176
57807
|
* still held fails loudly when its pane closed, its agent restarted, or the
|
|
@@ -57178,53 +57809,126 @@ var init_prompt_deliveries = __esm({
|
|
|
57178
57809
|
* transcript shows it after all). */
|
|
57179
57810
|
async observe(server, panes2) {
|
|
57180
57811
|
const now = this.now();
|
|
57181
|
-
let
|
|
57812
|
+
let changed = false;
|
|
57813
|
+
const pass = /* @__PURE__ */ new Map();
|
|
57182
57814
|
for (const record4 of this.records) {
|
|
57183
|
-
if (record4.server !== server
|
|
57815
|
+
if (record4.server !== server) continue;
|
|
57816
|
+
if (record4.state === "failed" && record4.hookClaim) {
|
|
57817
|
+
if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
|
|
57818
|
+
record4.checkedAt = now;
|
|
57819
|
+
if (await this.taken(record4, pass, true)) {
|
|
57820
|
+
this.settle(record4);
|
|
57821
|
+
changed = true;
|
|
57822
|
+
}
|
|
57823
|
+
}
|
|
57824
|
+
continue;
|
|
57825
|
+
}
|
|
57826
|
+
if (record4.state !== "typed" && record4.state !== "queued") continue;
|
|
57184
57827
|
const pane = panes2.find((entry2) => entry2.pane_id === record4.pane);
|
|
57185
57828
|
if (!pane || record4.terminal && pane.terminal_id !== record4.terminal || pane.agent && pane.agent !== record4.source) {
|
|
57186
|
-
if (await this.
|
|
57187
|
-
record4
|
|
57188
|
-
|
|
57189
|
-
changed2 = true;
|
|
57190
|
-
this.release(record4, "delivered");
|
|
57829
|
+
if (await this.taken(record4, pass)) {
|
|
57830
|
+
this.settle(record4);
|
|
57831
|
+
changed = true;
|
|
57191
57832
|
continue;
|
|
57192
57833
|
}
|
|
57834
|
+
if (!_PromptDeliveries.open(record4)) continue;
|
|
57193
57835
|
record4.state = "failed";
|
|
57194
57836
|
record4.settledAt = now;
|
|
57195
|
-
|
|
57837
|
+
changed = true;
|
|
57196
57838
|
record4.reason = pane ? "The agent in this pane restarted before it took the message." : "The agent's pane closed before it took the message.";
|
|
57197
57839
|
continue;
|
|
57198
57840
|
}
|
|
57199
57841
|
if (!["idle", "done"].includes(String(pane.agent_status))) {
|
|
57200
57842
|
record4.idleSince = void 0;
|
|
57843
|
+
if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
|
|
57844
|
+
record4.checkedAt = now;
|
|
57845
|
+
if (await this.taken(record4, pass, true)) {
|
|
57846
|
+
this.settle(record4);
|
|
57847
|
+
changed = true;
|
|
57848
|
+
}
|
|
57849
|
+
}
|
|
57201
57850
|
continue;
|
|
57202
57851
|
}
|
|
57203
57852
|
record4.idleSince ??= now;
|
|
57204
57853
|
if (record4.stoppedAt === void 0 || now - Math.max(record4.idleSince, record4.stoppedAt) < DELIVERY_GIVE_UP_MS) continue;
|
|
57205
|
-
if (await this.
|
|
57206
|
-
record4
|
|
57207
|
-
|
|
57208
|
-
changed2 = true;
|
|
57209
|
-
this.release(record4, "delivered");
|
|
57854
|
+
if (await this.taken(record4, pass)) {
|
|
57855
|
+
this.settle(record4);
|
|
57856
|
+
changed = true;
|
|
57210
57857
|
continue;
|
|
57211
57858
|
}
|
|
57859
|
+
if (!_PromptDeliveries.open(record4)) continue;
|
|
57212
57860
|
record4.state = "failed";
|
|
57213
57861
|
record4.settledAt = now;
|
|
57214
|
-
|
|
57862
|
+
changed = true;
|
|
57215
57863
|
record4.reason = "The agent finished its turn without taking the message.";
|
|
57216
57864
|
}
|
|
57217
|
-
if (
|
|
57865
|
+
if (changed) this.save();
|
|
57218
57866
|
}
|
|
57219
57867
|
};
|
|
57220
57868
|
}
|
|
57221
57869
|
});
|
|
57222
57870
|
|
|
57871
|
+
// src/bridge/agent-hook-asks.ts
|
|
57872
|
+
function appServerApproval(request9) {
|
|
57873
|
+
const params = request9.params;
|
|
57874
|
+
const reason2 = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
|
|
57875
|
+
if (request9.method === "item/commandExecution/requestApproval") {
|
|
57876
|
+
return { tool: "Bash", input: {
|
|
57877
|
+
...typeof params.command === "string" ? { command: params.command } : {},
|
|
57878
|
+
...typeof params.cwd === "string" ? { cwd: params.cwd } : {},
|
|
57879
|
+
...reason2
|
|
57880
|
+
} };
|
|
57881
|
+
}
|
|
57882
|
+
if (request9.method === "item/fileChange/requestApproval") {
|
|
57883
|
+
const changes = objects(params.changes);
|
|
57884
|
+
const verb = (change) => object2(change.kind).type === "add" ? "Add" : object2(change.kind).type === "delete" ? "Delete" : "Update";
|
|
57885
|
+
const patch = changes.filter((change) => typeof change.path === "string").map((change) => `*** ${verb(change)} File: ${change.path}`).join("\n");
|
|
57886
|
+
return { tool: "apply_patch", input: { ...patch ? { patch } : {}, ...typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}, ...reason2 } };
|
|
57887
|
+
}
|
|
57888
|
+
if (request9.method === "item/permissions/requestApproval") return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason2 } };
|
|
57889
|
+
return void 0;
|
|
57890
|
+
}
|
|
57891
|
+
function appServerDecision(request9, allow) {
|
|
57892
|
+
if (request9.method === "item/permissions/requestApproval") return { permissions: allow ? object2(request9.params.permissions) : {}, scope: "turn" };
|
|
57893
|
+
return { decision: allow ? "accept" : "decline" };
|
|
57894
|
+
}
|
|
57895
|
+
function conductorCall(tool, input2) {
|
|
57896
|
+
const tail2 = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool.replace(/^mcp_phren_/, ""))?.[1];
|
|
57897
|
+
const fields2 = object2(input2);
|
|
57898
|
+
let action;
|
|
57899
|
+
if (tail2 === "dispatch") action = "dispatch";
|
|
57900
|
+
else if (tail2 === "hand_off") action = "hand_off";
|
|
57901
|
+
else if (tail2 === "phren_admin" && (fields2.action === "dispatch" || fields2.action === "hand_off")) action = fields2.action;
|
|
57902
|
+
if (!action) return void 0;
|
|
57903
|
+
const project = typeof fields2.project === "string" ? fields2.project : void 0;
|
|
57904
|
+
const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
|
|
57905
|
+
return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
|
|
57906
|
+
}
|
|
57907
|
+
function opencodePermissionReply(decision) {
|
|
57908
|
+
if (decision === "approve") return "once";
|
|
57909
|
+
if (decision === "deny") return "reject";
|
|
57910
|
+
if (decision === "allow-project" || decision === "allow-everywhere") return "always";
|
|
57911
|
+
return void 0;
|
|
57912
|
+
}
|
|
57913
|
+
var OPENCODE_APPROVAL_OPTIONS;
|
|
57914
|
+
var init_agent_hook_asks = __esm({
|
|
57915
|
+
"src/bridge/agent-hook-asks.ts"() {
|
|
57916
|
+
"use strict";
|
|
57917
|
+
init_protocol();
|
|
57918
|
+
OPENCODE_APPROVAL_OPTIONS = [
|
|
57919
|
+
{ label: "Allow once", decision: "approve" },
|
|
57920
|
+
{ label: "Allow for this project", decision: "allow-project" },
|
|
57921
|
+
{ label: "Allow everywhere", decision: "allow-everywhere" },
|
|
57922
|
+
{ label: "Deny", decision: "deny" }
|
|
57923
|
+
];
|
|
57924
|
+
}
|
|
57925
|
+
});
|
|
57926
|
+
|
|
57223
57927
|
// src/bridge/opencode-pane-server.ts
|
|
57224
57928
|
import * as crypto12 from "node:crypto";
|
|
57225
57929
|
import * as fs42 from "node:fs";
|
|
57226
57930
|
import * as net from "node:net";
|
|
57227
|
-
import * as
|
|
57931
|
+
import * as path102 from "node:path";
|
|
57228
57932
|
function safeSegment(value2) {
|
|
57229
57933
|
return typeof value2 === "string" && value2.length > 0 && value2 !== "." && value2 !== ".." && !/[/\\\u0000-\u001f\u007f]/.test(value2);
|
|
57230
57934
|
}
|
|
@@ -57242,7 +57946,7 @@ function alive(pid) {
|
|
|
57242
57946
|
}
|
|
57243
57947
|
}
|
|
57244
57948
|
function paneServerFile(dir, server, pane) {
|
|
57245
|
-
return
|
|
57949
|
+
return path102.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
|
|
57246
57950
|
}
|
|
57247
57951
|
function registerPaneServer(dir, entry2) {
|
|
57248
57952
|
if (!validEntry(entry2)) throw new Error("Invalid OpenCode pane server entry.");
|
|
@@ -57280,7 +57984,7 @@ function listPaneServers(dir) {
|
|
|
57280
57984
|
const entries2 = [];
|
|
57281
57985
|
for (const name of names.slice(0, 1024)) {
|
|
57282
57986
|
if (!name.endsWith(".json")) continue;
|
|
57283
|
-
const file4 =
|
|
57987
|
+
const file4 = path102.join(dir, name);
|
|
57284
57988
|
let parsed;
|
|
57285
57989
|
try {
|
|
57286
57990
|
const info = fs42.lstatSync(file4);
|
|
@@ -57492,10 +58196,10 @@ var init_opencode_pane_server = __esm({
|
|
|
57492
58196
|
|
|
57493
58197
|
// src/bridge/opencode-panes.ts
|
|
57494
58198
|
import { execFile as execFile24 } from "node:child_process";
|
|
57495
|
-
import
|
|
58199
|
+
import path103 from "node:path";
|
|
57496
58200
|
import { promisify as promisify22 } from "node:util";
|
|
57497
58201
|
function paneServersDir() {
|
|
57498
|
-
return
|
|
58202
|
+
return path103.join(bridgeRoot(), "opencode-panes");
|
|
57499
58203
|
}
|
|
57500
58204
|
function servedPane(server, pane) {
|
|
57501
58205
|
return readPaneServer(paneServersDir(), server, pane);
|
|
@@ -57729,69 +58433,99 @@ var init_opencode_panes = __esm({
|
|
|
57729
58433
|
}
|
|
57730
58434
|
});
|
|
57731
58435
|
|
|
57732
|
-
// src/bridge/
|
|
57733
|
-
import {
|
|
57734
|
-
import
|
|
57735
|
-
|
|
57736
|
-
|
|
57737
|
-
|
|
57738
|
-
|
|
57739
|
-
|
|
57740
|
-
|
|
57741
|
-
|
|
57742
|
-
|
|
57743
|
-
|
|
57744
|
-
|
|
57745
|
-
|
|
57746
|
-
|
|
57747
|
-
|
|
57748
|
-
|
|
58436
|
+
// src/bridge/codex-review-mode.ts
|
|
58437
|
+
import { open as open19 } from "node:fs/promises";
|
|
58438
|
+
import path104 from "node:path";
|
|
58439
|
+
async function codexAutoReview(transcriptPath2) {
|
|
58440
|
+
if (typeof transcriptPath2 !== "string" || !path104.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path104.basename(transcriptPath2))) return false;
|
|
58441
|
+
const file4 = await open19(transcriptPath2, "r").catch(() => void 0);
|
|
58442
|
+
if (!file4) return false;
|
|
58443
|
+
try {
|
|
58444
|
+
const size = (await file4.stat()).size;
|
|
58445
|
+
let end = size, carry = Buffer.alloc(0);
|
|
58446
|
+
while (end > 0 && size - end < SCAN_LIMIT) {
|
|
58447
|
+
const start = Math.max(0, end - CHUNK), buffer = Buffer.alloc(end - start);
|
|
58448
|
+
await file4.read(buffer, 0, buffer.length, start);
|
|
58449
|
+
const bytes = Buffer.concat([buffer, carry]);
|
|
58450
|
+
let lineEnd = bytes.length;
|
|
58451
|
+
for (let at2 = bytes.lastIndexOf(10, lineEnd - 1); at2 >= 0; at2 = bytes.lastIndexOf(10, lineEnd - 1)) {
|
|
58452
|
+
const settings2 = reviewSettings(bytes.subarray(at2 + 1, lineEnd).toString("utf8"));
|
|
58453
|
+
if (settings2) return autoReviewed(settings2);
|
|
58454
|
+
lineEnd = at2;
|
|
58455
|
+
if (at2 === 0) break;
|
|
58456
|
+
}
|
|
58457
|
+
carry = bytes.subarray(0, lineEnd);
|
|
58458
|
+
end = start;
|
|
58459
|
+
}
|
|
58460
|
+
const settings = end === 0 ? reviewSettings(carry.toString("utf8")) : void 0;
|
|
58461
|
+
return !!settings && autoReviewed(settings);
|
|
58462
|
+
} catch {
|
|
58463
|
+
return false;
|
|
58464
|
+
} finally {
|
|
58465
|
+
await file4.close().catch(() => {
|
|
58466
|
+
});
|
|
58467
|
+
}
|
|
57749
58468
|
}
|
|
57750
|
-
function
|
|
57751
|
-
|
|
57752
|
-
|
|
57753
|
-
|
|
57754
|
-
|
|
57755
|
-
|
|
57756
|
-
|
|
57757
|
-
|
|
57758
|
-
|
|
58469
|
+
function reviewSettings(line) {
|
|
58470
|
+
if (!line.includes('"approvals_reviewer"') || !(line.includes('"type":"turn_context"') || line.includes('"type":"thread_settings_applied"'))) return void 0;
|
|
58471
|
+
try {
|
|
58472
|
+
const entry2 = JSON.parse(line);
|
|
58473
|
+
const payload = entry2?.payload;
|
|
58474
|
+
const settings = entry2?.type === "turn_context" ? payload : entry2?.type === "event_msg" && payload?.type === "thread_settings_applied" ? payload.thread_settings : void 0;
|
|
58475
|
+
if (!settings || !("approvals_reviewer" in settings)) return void 0;
|
|
58476
|
+
return { reviewer: settings.approvals_reviewer, policy: settings.approval_policy };
|
|
58477
|
+
} catch {
|
|
58478
|
+
return void 0;
|
|
57759
58479
|
}
|
|
57760
|
-
|
|
57761
|
-
|
|
57762
|
-
|
|
57763
|
-
|
|
57764
|
-
|
|
58480
|
+
}
|
|
58481
|
+
function autoReviewed({ reviewer, policy }) {
|
|
58482
|
+
return reviewer === "auto_review" && (policy === "on-request" || !!policy && typeof policy === "object" && "granular" in policy);
|
|
58483
|
+
}
|
|
58484
|
+
var SCAN_LIMIT, CHUNK;
|
|
58485
|
+
var init_codex_review_mode = __esm({
|
|
58486
|
+
"src/bridge/codex-review-mode.ts"() {
|
|
58487
|
+
"use strict";
|
|
58488
|
+
SCAN_LIMIT = 64 * 1048576;
|
|
58489
|
+
CHUNK = 1048576;
|
|
57765
58490
|
}
|
|
57766
|
-
|
|
57767
|
-
|
|
58491
|
+
});
|
|
58492
|
+
|
|
58493
|
+
// src/bridge/thread-origin.ts
|
|
58494
|
+
import { open as open20 } from "node:fs/promises";
|
|
58495
|
+
import path105 from "node:path";
|
|
58496
|
+
async function codexForeignThread(transcriptPath2) {
|
|
58497
|
+
if (typeof transcriptPath2 !== "string" || !path105.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path105.basename(transcriptPath2))) return false;
|
|
58498
|
+
return foreignMeta(await readHead(transcriptPath2, 4096));
|
|
57768
58499
|
}
|
|
57769
|
-
function
|
|
57770
|
-
|
|
57771
|
-
|
|
58500
|
+
async function readHead(file4, bytes) {
|
|
58501
|
+
const handle = await open20(file4, "r").catch(() => void 0);
|
|
58502
|
+
if (!handle) return "";
|
|
58503
|
+
try {
|
|
58504
|
+
const buffer = Buffer.alloc(bytes), { bytesRead } = await handle.read(buffer, 0, bytes, 0);
|
|
58505
|
+
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
58506
|
+
} finally {
|
|
58507
|
+
await handle.close();
|
|
58508
|
+
}
|
|
57772
58509
|
}
|
|
57773
|
-
function
|
|
57774
|
-
|
|
57775
|
-
|
|
57776
|
-
let action;
|
|
57777
|
-
if (tail2 === "dispatch") action = "dispatch";
|
|
57778
|
-
else if (tail2 === "hand_off") action = "hand_off";
|
|
57779
|
-
else if (tail2 === "phren_admin" && (fields2.action === "dispatch" || fields2.action === "hand_off")) action = fields2.action;
|
|
57780
|
-
if (!action) return void 0;
|
|
57781
|
-
const project = typeof fields2.project === "string" ? fields2.project : void 0;
|
|
57782
|
-
const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
|
|
57783
|
-
return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
|
|
58510
|
+
function foreignMeta(head) {
|
|
58511
|
+
if (!head.includes('"session_meta"')) return false;
|
|
58512
|
+
return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
|
|
57784
58513
|
}
|
|
57785
|
-
function
|
|
57786
|
-
if (
|
|
57787
|
-
|
|
57788
|
-
if (decision === "allow-project" || decision === "allow-everywhere") return "always";
|
|
57789
|
-
return void 0;
|
|
58514
|
+
async function claudeHeadlessThread(transcriptPath2) {
|
|
58515
|
+
if (typeof transcriptPath2 !== "string" || !path105.isAbsolute(transcriptPath2) || !transcriptPath2.endsWith(".jsonl")) return false;
|
|
58516
|
+
return headlessEntrypoint(await readHead(transcriptPath2, 32768));
|
|
57790
58517
|
}
|
|
57791
|
-
function
|
|
57792
|
-
|
|
57793
|
-
return project ? { project } : {};
|
|
58518
|
+
function headlessEntrypoint(head) {
|
|
58519
|
+
return /"entrypoint"\s*:\s*"sdk-[a-z]+"/.test(head);
|
|
57794
58520
|
}
|
|
58521
|
+
var init_thread_origin = __esm({
|
|
58522
|
+
"src/bridge/thread-origin.ts"() {
|
|
58523
|
+
"use strict";
|
|
58524
|
+
}
|
|
58525
|
+
});
|
|
58526
|
+
|
|
58527
|
+
// src/bridge/agent-hook-callback.ts
|
|
58528
|
+
import { request as request6 } from "node:http";
|
|
57795
58529
|
function stopFacts(value2) {
|
|
57796
58530
|
const tasks = Array.isArray(value2.background_tasks) ? value2.background_tasks.filter((task2) => !["completed", "failed", "killed", "stopped"].includes(String(object2(task2).status))) : void 0;
|
|
57797
58531
|
return {
|
|
@@ -57811,6 +58545,7 @@ async function agentHook(source, elapsed = () => performance.now()) {
|
|
|
57811
58545
|
const value2 = object2(JSON.parse(input2));
|
|
57812
58546
|
if (value2.agent_id || value2.agentId || value2.isSidechain || value2.is_sidechain) return;
|
|
57813
58547
|
if (source === "codex" && await codexForeignThread(value2.transcript_path).catch(() => false)) return;
|
|
58548
|
+
if (source === "claude" && await claudeHeadlessThread(value2.transcript_path).catch(() => false)) return;
|
|
57814
58549
|
const target = targetSchema.parse({
|
|
57815
58550
|
server: place.server,
|
|
57816
58551
|
workspace: place.workspace,
|
|
@@ -57884,23 +58619,56 @@ async function forwardHook(source, target, event, value2, left3) {
|
|
|
57884
58619
|
req.end(data);
|
|
57885
58620
|
});
|
|
57886
58621
|
}
|
|
57887
|
-
var
|
|
58622
|
+
var init_agent_hook_callback = __esm({
|
|
58623
|
+
"src/bridge/agent-hook-callback.ts"() {
|
|
58624
|
+
"use strict";
|
|
58625
|
+
init_shared();
|
|
58626
|
+
init_runtime();
|
|
58627
|
+
init_protocol();
|
|
58628
|
+
init_hook_fast();
|
|
58629
|
+
init_codex_daemon();
|
|
58630
|
+
init_codex_review_mode();
|
|
58631
|
+
init_thread_origin();
|
|
58632
|
+
init_terminal();
|
|
58633
|
+
init_launch_brief();
|
|
58634
|
+
init_codex_servers();
|
|
58635
|
+
init_agent_hook_stores();
|
|
58636
|
+
}
|
|
58637
|
+
});
|
|
58638
|
+
|
|
58639
|
+
// src/bridge/agent-hooks.ts
|
|
58640
|
+
import { createServer as createServer3 } from "node:http";
|
|
58641
|
+
import { mkdir as mkdir26, readFile as readFile44, chmod as chmod4, unlink as unlink7, lstat as lstat28 } from "node:fs/promises";
|
|
58642
|
+
import { watch } from "node:fs";
|
|
58643
|
+
import path106 from "node:path";
|
|
58644
|
+
import { randomUUID as randomUUID24 } from "node:crypto";
|
|
58645
|
+
import { hostname as hostname10 } from "node:os";
|
|
58646
|
+
function watchHangUp(res) {
|
|
58647
|
+
let closed = res.destroyed || res.socket?.destroyed === true;
|
|
58648
|
+
const onClose = () => {
|
|
58649
|
+
if (!res.writableEnded) closed = true;
|
|
58650
|
+
};
|
|
58651
|
+
res.once("close", onClose);
|
|
58652
|
+
return () => {
|
|
58653
|
+
res.off("close", onClose);
|
|
58654
|
+
return closed || res.destroyed;
|
|
58655
|
+
};
|
|
58656
|
+
}
|
|
58657
|
+
function projectField(cwd) {
|
|
58658
|
+
const project = paneProject(cwd, phrenStoreRoot());
|
|
58659
|
+
return project ? { project } : {};
|
|
58660
|
+
}
|
|
58661
|
+
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;
|
|
57888
58662
|
var init_agent_hooks = __esm({
|
|
57889
58663
|
"src/bridge/agent-hooks.ts"() {
|
|
57890
58664
|
"use strict";
|
|
57891
58665
|
init_approval_rules();
|
|
57892
58666
|
init_conductor_role();
|
|
57893
58667
|
init_conductor_context();
|
|
57894
|
-
init_shared();
|
|
57895
58668
|
init_registry();
|
|
57896
|
-
init_runtime();
|
|
57897
58669
|
init_logger();
|
|
57898
58670
|
init_protocol();
|
|
57899
58671
|
init_herdr();
|
|
57900
|
-
init_hook_fast();
|
|
57901
|
-
init_codex_daemon();
|
|
57902
|
-
init_codex_review_mode();
|
|
57903
|
-
init_codex_thread_origin();
|
|
57904
58672
|
init_terminal();
|
|
57905
58673
|
init_pane_text();
|
|
57906
58674
|
init_changes();
|
|
@@ -57922,10 +58690,13 @@ var init_agent_hooks = __esm({
|
|
|
57922
58690
|
init_prompt_deliveries();
|
|
57923
58691
|
init_metrics();
|
|
57924
58692
|
init_launch_brief();
|
|
58693
|
+
init_agent_hook_asks();
|
|
57925
58694
|
init_sudo();
|
|
57926
58695
|
init_codex_servers();
|
|
57927
58696
|
init_opencode_panes();
|
|
57928
58697
|
init_terminal_choice();
|
|
58698
|
+
init_agent_hook_asks();
|
|
58699
|
+
init_agent_hook_callback();
|
|
57929
58700
|
init_agent_hook_stores();
|
|
57930
58701
|
APPROVAL_SWEEP_MS = 2e3;
|
|
57931
58702
|
OPENCODE_PANES_FRESH_MS = 15e3;
|
|
@@ -57934,18 +58705,13 @@ var init_agent_hooks = __esm({
|
|
|
57934
58705
|
const value2 = Number(process.env.PHREN_APPROVAL_HOLD_MS);
|
|
57935
58706
|
return Number.isFinite(value2) && value2 >= 50 && value2 <= 6e4 ? Math.floor(value2) : 55e3;
|
|
57936
58707
|
})();
|
|
58708
|
+
QUESTION_READ_LINES = 120;
|
|
57937
58709
|
DIALOG_READ_MS2 = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3e3);
|
|
57938
58710
|
DIALOG_PUSH_MS = 10 * 6e4;
|
|
57939
58711
|
FANOUT_SWEEP_MS = 5e3;
|
|
57940
58712
|
SERVED_ASK_MS = 60 * 6e4;
|
|
57941
58713
|
FANOUT_ARCHIVE_MS = 60 * 60 * 1e3;
|
|
57942
58714
|
DISPATCH_LEASE_MS = 45e3;
|
|
57943
|
-
OPENCODE_APPROVAL_OPTIONS = [
|
|
57944
|
-
{ label: "Allow once", decision: "approve" },
|
|
57945
|
-
{ label: "Allow for this project", decision: "allow-project" },
|
|
57946
|
-
{ label: "Allow everywhere", decision: "allow-everywhere" },
|
|
57947
|
-
{ label: "Deny", decision: "deny" }
|
|
57948
|
-
];
|
|
57949
58715
|
AgentHooks = class {
|
|
57950
58716
|
constructor(push = new ApprovalPushService(), modules, deliveriesFile) {
|
|
57951
58717
|
this.push = push;
|
|
@@ -58318,7 +59084,7 @@ var init_agent_hooks = __esm({
|
|
|
58318
59084
|
try {
|
|
58319
59085
|
const file4 = path106.join(root, folder, name), info = await lstat28(file4);
|
|
58320
59086
|
if (!info.isFile() || info.size > 65536) continue;
|
|
58321
|
-
value2 = object2(JSON.parse(await
|
|
59087
|
+
value2 = object2(JSON.parse(await readFile44(file4, "utf8")));
|
|
58322
59088
|
} catch {
|
|
58323
59089
|
continue;
|
|
58324
59090
|
}
|
|
@@ -58508,9 +59274,11 @@ var init_agent_hooks = __esm({
|
|
|
58508
59274
|
this.dialogReads.set(key4, now);
|
|
58509
59275
|
while (this.dialogReads.size > 128) this.dialogReads.delete(this.dialogReads.keys().next().value);
|
|
58510
59276
|
const text5 = await this.paneLines(target);
|
|
59277
|
+
const tall = target.source === "claude" && /Chat about this/.test(text5) && !claudeQuestionDialog(text5) ? await this.paneLines(target, true, QUESTION_READ_LINES).catch(() => "") : "";
|
|
59278
|
+
const asking = target.source === "claude" && !!(claudeQuestionDialog(text5) || tall && claudeQuestionDialog(tall));
|
|
58511
59279
|
this.passwords.set(key4, passwordLine(text5));
|
|
58512
59280
|
while (this.passwords.size > 128) this.passwords.delete(this.passwords.keys().next().value);
|
|
58513
|
-
if (
|
|
59281
|
+
if (asking) {
|
|
58514
59282
|
if (entry2 && !question2) this.terminalPrompts.delete(key4);
|
|
58515
59283
|
return;
|
|
58516
59284
|
}
|
|
@@ -58618,7 +59386,8 @@ var init_agent_hooks = __esm({
|
|
|
58618
59386
|
async answerClaudeQuestions(target, questions, answers, options = {}) {
|
|
58619
59387
|
const key4 = JSON.stringify(target);
|
|
58620
59388
|
await answerClaudeQuestionDialog({
|
|
58621
|
-
|
|
59389
|
+
// A tall question (long text, many options) pushes its tab bar out of 40 lines.
|
|
59390
|
+
read: () => this.paneLines(target, true, QUESTION_READ_LINES),
|
|
58622
59391
|
keys: async (keys2) => {
|
|
58623
59392
|
if (!keys2.length) return;
|
|
58624
59393
|
await validateTarget(target, false, true);
|
|
@@ -58684,8 +59453,8 @@ var init_agent_hooks = __esm({
|
|
|
58684
59453
|
return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: false, format: "ansi", timeoutMs: 2e3 });
|
|
58685
59454
|
}
|
|
58686
59455
|
/** Read what the pane draws, stripping ANSI unless placeholder styling is needed. */
|
|
58687
|
-
paneLines(target, stripAnsi = true) {
|
|
58688
|
-
return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines
|
|
59456
|
+
paneLines(target, stripAnsi = true, lines = 40) {
|
|
59457
|
+
return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines, stripAnsi, timeoutMs: 2e3 });
|
|
58689
59458
|
}
|
|
58690
59459
|
/** After the phone walks Codex's /permissions menu onto Full Access, the
|
|
58691
59460
|
* agent draws a second "Enable full access?" confirmation. Watch the pane's
|
|
@@ -59384,7 +60153,7 @@ ${await conductorBrief()}` : context3 } : {}));
|
|
|
59384
60153
|
}
|
|
59385
60154
|
if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body2.event))) this.stopCompacting(target);
|
|
59386
60155
|
if (body2.event === "UserPromptSubmit") {
|
|
59387
|
-
if (typeof body2.prompt === "string") this.deliveries.submitted(target, body2.prompt.slice(0, 65536));
|
|
60156
|
+
if (typeof body2.prompt === "string") await this.deliveries.submitted(target, body2.prompt.slice(0, 65536));
|
|
59388
60157
|
await this.recordTurn(target, pane, body2, dispatch2);
|
|
59389
60158
|
const context3 = this.modules?.has("conductor") === false ? void 0 : await conductorContext(target, s).catch(() => void 0);
|
|
59390
60159
|
res.end(JSON.stringify(context3 ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context3 } } : {}));
|
|
@@ -59588,7 +60357,7 @@ ${await conductorBrief()}` : context3 } : {}));
|
|
|
59588
60357
|
|
|
59589
60358
|
// src/bridge/models.ts
|
|
59590
60359
|
import { spawn as spawn11 } from "node:child_process";
|
|
59591
|
-
import { readdir as readdir16, readFile as
|
|
60360
|
+
import { readdir as readdir16, readFile as readFile45, stat as stat22 } from "node:fs/promises";
|
|
59592
60361
|
import { homedir as homedir17 } from "node:os";
|
|
59593
60362
|
import path107 from "node:path";
|
|
59594
60363
|
function readCodexModels(executable2 = codexExecutable()) {
|
|
@@ -59676,7 +60445,7 @@ async function readClaudeCatalog(configDir2 = claudeConfigDir(), installed) {
|
|
|
59676
60445
|
if (!newest2) return [];
|
|
59677
60446
|
let parsed;
|
|
59678
60447
|
try {
|
|
59679
|
-
parsed = JSON.parse(await
|
|
60448
|
+
parsed = JSON.parse(await readFile45(newest2.file, "utf8"));
|
|
59680
60449
|
} catch {
|
|
59681
60450
|
return [];
|
|
59682
60451
|
}
|
|
@@ -59775,7 +60544,7 @@ async function readOpenCodeModels(executable2 = "opencode", configDir2 = path107
|
|
|
59775
60544
|
let configured;
|
|
59776
60545
|
for (const file4 of ["opencode.json", "opencode.jsonc"]) {
|
|
59777
60546
|
try {
|
|
59778
|
-
const text5 = await
|
|
60547
|
+
const text5 = await readFile45(path107.join(configDir2, file4), "utf8");
|
|
59779
60548
|
const model = /"model"\s*:\s*"([^"]+)"/.exec(text5)?.[1];
|
|
59780
60549
|
if (model) {
|
|
59781
60550
|
configured = model.slice(0, 200);
|
|
@@ -60479,6 +61248,7 @@ function descendsFrom(pid, roots, parents) {
|
|
|
60479
61248
|
function attributeServers(input2) {
|
|
60480
61249
|
const result = [];
|
|
60481
61250
|
for (const server of input2.servers) {
|
|
61251
|
+
if (server.unverified) continue;
|
|
60482
61252
|
if (descendsFrom(server.pid, input2.ownRoots, input2.parents)) result.push({ ...server, source: "started" });
|
|
60483
61253
|
else if (input2.mentioned.has(server.port) && !descendsFrom(server.pid, input2.otherRoots, input2.parents)) {
|
|
60484
61254
|
result.push({ ...server, source: "mentioned" });
|
|
@@ -60565,7 +61335,7 @@ var init_session_servers = __esm({
|
|
|
60565
61335
|
});
|
|
60566
61336
|
|
|
60567
61337
|
// src/bridge/uploads.ts
|
|
60568
|
-
import { mkdir as mkdir27, readdir as readdir17, lstat as lstat29, realpath as realpath15, readFile as
|
|
61338
|
+
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";
|
|
60569
61339
|
import path108 from "node:path";
|
|
60570
61340
|
import { randomUUID as randomUUID26 } from "node:crypto";
|
|
60571
61341
|
function imageBytes(bytes) {
|
|
@@ -60595,7 +61365,7 @@ async function saveUpload(session, name, bytes) {
|
|
|
60595
61365
|
const folder = path108.join(root, session);
|
|
60596
61366
|
await mkdir27(folder, { recursive: true, mode: 448 });
|
|
60597
61367
|
saved = path108.join(folder, `${randomUUID26()}-${name}`);
|
|
60598
|
-
await
|
|
61368
|
+
await writeFile8(saved, bytes, { flag: "wx", mode: 384 });
|
|
60599
61369
|
});
|
|
60600
61370
|
uploadQueue = task2;
|
|
60601
61371
|
await task2;
|
|
@@ -60630,7 +61400,7 @@ async function uploadImage(requested) {
|
|
|
60630
61400
|
const metadata = await stat24(file4);
|
|
60631
61401
|
if (!metadata.isFile()) throw missing;
|
|
60632
61402
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
60633
|
-
const bytes = await
|
|
61403
|
+
const bytes = await readFile46(file4);
|
|
60634
61404
|
if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
60635
61405
|
if (!imageBytes(bytes)) throw missing;
|
|
60636
61406
|
return bytes;
|
|
@@ -60767,9 +61537,9 @@ var init_file_range = __esm({
|
|
|
60767
61537
|
});
|
|
60768
61538
|
|
|
60769
61539
|
// src/bridge/file-write.ts
|
|
60770
|
-
import { randomBytes as
|
|
61540
|
+
import { randomBytes as randomBytes9 } from "node:crypto";
|
|
60771
61541
|
import { constants as constants4 } from "node:fs";
|
|
60772
|
-
import { lstat as lstat31, open as open23, realpath as realpath17, rename as
|
|
61542
|
+
import { lstat as lstat31, open as open23, realpath as realpath17, rename as rename7, rm as rm12 } from "node:fs/promises";
|
|
60773
61543
|
import path110 from "node:path";
|
|
60774
61544
|
async function serialized3(key4, work) {
|
|
60775
61545
|
const previous = fileLocks.get(key4) ?? Promise.resolve();
|
|
@@ -60782,7 +61552,8 @@ async function serialized3(key4, work) {
|
|
|
60782
61552
|
}
|
|
60783
61553
|
}
|
|
60784
61554
|
async function writeRepoFile(root, requested, content, expectedVersion) {
|
|
60785
|
-
const
|
|
61555
|
+
const name = typeof requested === "string" ? path110.posix.normalize(requested) : requested;
|
|
61556
|
+
const key4 = `${await realpath17(root).catch(() => root)}\0${name}`;
|
|
60786
61557
|
return serialized3(key4, () => writeRepoFileNow(root, requested, content, expectedVersion));
|
|
60787
61558
|
}
|
|
60788
61559
|
async function writeRepoFileNow(root, requested, content, expectedVersion) {
|
|
@@ -60829,7 +61600,7 @@ async function writeRepoFileNow(root, requested, content, expectedVersion) {
|
|
|
60829
61600
|
}
|
|
60830
61601
|
if (!existing) throw new BridgeError(409, "The file is gone. It changed since you opened it.", { code: "file-changed" });
|
|
60831
61602
|
if (fileVersion(existing) !== expectedVersion) throw new BridgeError(409, "The file changed since you opened it.", { code: "file-changed" });
|
|
60832
|
-
const temporary = path110.join(directory, `.${parts[parts.length - 1]}.phren-${
|
|
61603
|
+
const temporary = path110.join(directory, `.${parts[parts.length - 1]}.phren-${randomBytes9(6).toString("hex")}.tmp`);
|
|
60833
61604
|
try {
|
|
60834
61605
|
const handle = await open23(temporary, constants4.O_WRONLY | constants4.O_CREAT | constants4.O_EXCL | constants4.O_NOFOLLOW, existing.mode & 511);
|
|
60835
61606
|
try {
|
|
@@ -60842,9 +61613,9 @@ async function writeRepoFileNow(root, requested, content, expectedVersion) {
|
|
|
60842
61613
|
if (!current2 || current2.isSymbolicLink() || fileVersion(current2) !== expectedVersion) {
|
|
60843
61614
|
throw new BridgeError(409, "The file changed since you opened it.", { code: "file-changed" });
|
|
60844
61615
|
}
|
|
60845
|
-
await
|
|
61616
|
+
await rename7(temporary, file4);
|
|
60846
61617
|
} finally {
|
|
60847
|
-
await
|
|
61618
|
+
await rm12(temporary, { force: true });
|
|
60848
61619
|
}
|
|
60849
61620
|
const saved = await lstat31(file4);
|
|
60850
61621
|
return { path: requested, version: fileVersion(saved), size: saved.size, created: false };
|
|
@@ -61148,7 +61919,11 @@ function deliveryReply(agentHooks, id2, target, text5) {
|
|
|
61148
61919
|
...status.reason ? { reason: status.reason } : {}
|
|
61149
61920
|
};
|
|
61150
61921
|
}
|
|
61151
|
-
async function paneRoute(ctx, url2, data, response) {
|
|
61922
|
+
async function paneRoute(ctx, url2, data, response, headers = {}) {
|
|
61923
|
+
if (isGitWriteRoute(url2.pathname) && data.expectedRepository === void 0) {
|
|
61924
|
+
ctx.gitWrites?.record(url2.pathname, headers);
|
|
61925
|
+
if (EXPECTED_REPOSITORY_REQUIRED) throw new BridgeError(400, "This app is too old to change Git safely. Update it.", { code: "expected-repository-required" });
|
|
61926
|
+
}
|
|
61152
61927
|
if (["/v1/diff", "/v1/git/status", "/v1/git/worktrees"].includes(url2.pathname)) {
|
|
61153
61928
|
return withGitReadDeadline(() => paneRouteOnce(ctx, url2, data, response, () => {
|
|
61154
61929
|
}));
|
|
@@ -61431,7 +62206,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
61431
62206
|
}));
|
|
61432
62207
|
} else if (url2.pathname.startsWith("/v1/git/")) {
|
|
61433
62208
|
let cwd = await gitRepository(pane, target, data.child, data.worktree);
|
|
61434
|
-
if (
|
|
62209
|
+
if (isGitWriteRoute(url2.pathname) && data.expectedRepository !== void 0) {
|
|
61435
62210
|
const expected = external_exports.string().min(1).max(4096).refine((value2) => path111.isAbsolute(value2) && !value2.includes("\0"), "Expected an absolute repository path.").parse(data.expectedRepository);
|
|
61436
62211
|
const root = await gitRoot(cwd);
|
|
61437
62212
|
if (root !== expected) throw new BridgeError(409, "This pane's checkout changed. Refresh Changes before writing.", { code: "git-checkout-changed" });
|
|
@@ -61484,6 +62259,7 @@ var ANSWER_KEYS, HERDR_KEYS, questionText, claudeQuestionBody, secretText, promp
|
|
|
61484
62259
|
var init_server_pane_routes = __esm({
|
|
61485
62260
|
"src/bridge/server-pane-routes.ts"() {
|
|
61486
62261
|
"use strict";
|
|
62262
|
+
init_git_write_policy();
|
|
61487
62263
|
init_zod();
|
|
61488
62264
|
init_git();
|
|
61489
62265
|
init_fanouts();
|
|
@@ -61826,7 +62602,7 @@ __export(launcher_exports, {
|
|
|
61826
62602
|
writeManifest: () => writeManifest2
|
|
61827
62603
|
});
|
|
61828
62604
|
import { spawn as spawn12, execFileSync as execFileSync6 } from "node:child_process";
|
|
61829
|
-
import { randomBytes as
|
|
62605
|
+
import { randomBytes as randomBytes10 } from "node:crypto";
|
|
61830
62606
|
import * as fs44 from "node:fs";
|
|
61831
62607
|
import * as path114 from "node:path";
|
|
61832
62608
|
function jobsRoot(store) {
|
|
@@ -61882,7 +62658,7 @@ function createJob(options, env = process.env, nearest = nearestAgent) {
|
|
|
61882
62658
|
if (!options.label.trim() || options.label.length > 200) throw new Error("Choose a label of 1 to 200 characters.");
|
|
61883
62659
|
const worktree = fs44.realpathSync(options.worktree);
|
|
61884
62660
|
if (!fs44.statSync(worktree).isDirectory()) throw new Error("Choose a worktree directory.");
|
|
61885
|
-
const id2 = `${options.provider}-${
|
|
62661
|
+
const id2 = `${options.provider}-${randomBytes10(12).toString("hex")}`;
|
|
61886
62662
|
const root = jobsRoot(options.store), job = path114.join(root, id2);
|
|
61887
62663
|
fs44.mkdirSync(job, { recursive: true, mode: 448 });
|
|
61888
62664
|
fs44.chmodSync(root, 448);
|
|
@@ -61915,7 +62691,7 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
61915
62691
|
const { job, manifest } = reservation, adapter = adapters[options.provider];
|
|
61916
62692
|
console.log(job);
|
|
61917
62693
|
const out = fs44.openSync(path114.join(job, manifest.eventLog), "a"), err = fs44.openSync(path114.join(job, "stderr.log"), "a");
|
|
61918
|
-
const password =
|
|
62694
|
+
const password = randomBytes10(24).toString("hex");
|
|
61919
62695
|
const child = spawn12("nice", ["-n", "15", adapter.command, ...adapter.argv({ ...options, job })], {
|
|
61920
62696
|
cwd: manifest.worktree,
|
|
61921
62697
|
env: {
|
|
@@ -62006,8 +62782,8 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
62006
62782
|
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
|
|
62007
62783
|
fs44.closeSync(out);
|
|
62008
62784
|
fs44.closeSync(err);
|
|
62009
|
-
const blockedFile = path114.join(job, "blocked.json"),
|
|
62010
|
-
if (
|
|
62785
|
+
const blockedFile = path114.join(job, "blocked.json"), refusal2 = refused2 ?? stderrRefusal(stderr);
|
|
62786
|
+
if (refusal2 && !fs44.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal2, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
62011
62787
|
const blocked = fs44.existsSync(blockedFile);
|
|
62012
62788
|
if (blocked) console.error(`blocked: ${fs44.readFileSync(blockedFile, "utf8").slice(0, 4e3)}`);
|
|
62013
62789
|
fs44.writeFileSync(path114.join(job, "exit.txt"), `${exitCode}
|
|
@@ -62038,7 +62814,7 @@ var init_launcher = __esm({
|
|
|
62038
62814
|
|
|
62039
62815
|
// src/bridge/fanout-messages.ts
|
|
62040
62816
|
import { randomUUID as randomUUID27 } from "node:crypto";
|
|
62041
|
-
import { appendFile as appendFile2, lstat as lstat32, mkdir as mkdir28, readdir as readdir18, readFile as
|
|
62817
|
+
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";
|
|
62042
62818
|
import path115 from "node:path";
|
|
62043
62819
|
var fanoutMessageSchema, receiptSchema2, FanoutMessages;
|
|
62044
62820
|
var init_fanout_messages = __esm({
|
|
@@ -62092,7 +62868,7 @@ var init_fanout_messages = __esm({
|
|
|
62092
62868
|
if (!(await lstat32(directory)).isDirectory() || await realpath18(directory) !== directory) continue;
|
|
62093
62869
|
const file4 = path115.join(directory, "manifest.json"), info = await lstat32(file4);
|
|
62094
62870
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) continue;
|
|
62095
|
-
const manifest = manifestSchema.parse(JSON.parse(await
|
|
62871
|
+
const manifest = manifestSchema.parse(JSON.parse(await readFile47(file4, "utf8")));
|
|
62096
62872
|
if (manifest.id === name) jobs.push({ directory, manifest });
|
|
62097
62873
|
} catch {
|
|
62098
62874
|
}
|
|
@@ -62156,7 +62932,7 @@ var init_fanout_messages = __esm({
|
|
|
62156
62932
|
const file4 = path115.join(directory, name), info2 = await lstat32(file4);
|
|
62157
62933
|
if (!info2.isFile() || info2.isSymbolicLink() || info2.size > 262144) continue;
|
|
62158
62934
|
try {
|
|
62159
|
-
rows2.push({ file: file4, message: receiptSchema2.parse(JSON.parse(await
|
|
62935
|
+
rows2.push({ file: file4, message: receiptSchema2.parse(JSON.parse(await readFile47(file4, "utf8"))) });
|
|
62160
62936
|
} catch {
|
|
62161
62937
|
}
|
|
62162
62938
|
}
|
|
@@ -62202,17 +62978,17 @@ var init_fanout_messages = __esm({
|
|
|
62202
62978
|
if (await realpath18(round) !== round) throw new BridgeError(400, "Invalid worker round directory.");
|
|
62203
62979
|
const roundDir = path115.join(round, next.message.id);
|
|
62204
62980
|
await mkdir28(roundDir, { mode: 448 });
|
|
62205
|
-
await
|
|
62981
|
+
await writeFile9(path115.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
|
|
62206
62982
|
for (const name of ["stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
|
|
62207
|
-
await
|
|
62983
|
+
await rename8(path115.join(fresh.directory, name), path115.join(roundDir, `previous-${name}`)).catch((error62) => {
|
|
62208
62984
|
if (error62.code !== "ENOENT") throw error62;
|
|
62209
62985
|
});
|
|
62210
62986
|
}
|
|
62211
|
-
await
|
|
62987
|
+
await writeFile9(path115.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
|
|
62212
62988
|
const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
|
|
62213
62989
|
const message = { ...next.message, status: "running" };
|
|
62214
62990
|
await atomic(next.file, JSON.stringify(message));
|
|
62215
|
-
await
|
|
62991
|
+
await rename8(next.file, sentFile);
|
|
62216
62992
|
pending = { file: sentFile, message };
|
|
62217
62993
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
62218
62994
|
const manifest = {
|
|
@@ -62252,20 +63028,20 @@ var init_fanout_messages = __esm({
|
|
|
62252
63028
|
await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
|
|
62253
63029
|
await atomic(path115.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
62254
63030
|
}).finally(async () => {
|
|
62255
|
-
await
|
|
63031
|
+
await rm13(lock, { recursive: true, force: true });
|
|
62256
63032
|
}).catch(() => {
|
|
62257
63033
|
});
|
|
62258
63034
|
} catch (error62) {
|
|
62259
63035
|
if (!pending) throw error62;
|
|
62260
63036
|
await atomic(pending.file, JSON.stringify({ ...pending.message, status: "failed" }));
|
|
62261
|
-
if (pending.file.endsWith(".queued.json")) await
|
|
63037
|
+
if (pending.file.endsWith(".queued.json")) await rename8(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
|
|
62262
63038
|
if (started) await atomic(path115.join(job.directory, "manifest.json"), JSON.stringify({
|
|
62263
63039
|
...started,
|
|
62264
63040
|
status: "failed",
|
|
62265
63041
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
62266
63042
|
}));
|
|
62267
63043
|
} finally {
|
|
62268
|
-
if (!launched) await
|
|
63044
|
+
if (!launched) await rm13(lock, { recursive: true, force: true });
|
|
62269
63045
|
}
|
|
62270
63046
|
}
|
|
62271
63047
|
};
|
|
@@ -62695,8 +63471,8 @@ function relayLiveSpeech(client, query, options = {}) {
|
|
|
62695
63471
|
params.set("auto_mode", "true");
|
|
62696
63472
|
params.set("inactivity_timeout", "180");
|
|
62697
63473
|
}
|
|
62698
|
-
const
|
|
62699
|
-
const socket = connect5(`${origin}${
|
|
63474
|
+
const path146 = endpoint === "dialogue" ? "/v1/text-to-dialogue/stream-input" : `/v1/text-to-speech/${encodeURIComponent(voice)}/stream-input`;
|
|
63475
|
+
const socket = connect5(`${origin}${path146}?${params}`, key4);
|
|
62700
63476
|
upstream = socket;
|
|
62701
63477
|
const current2 = () => upstream === socket && !closed;
|
|
62702
63478
|
let voiced = false, firstAudio;
|
|
@@ -63053,7 +63829,7 @@ var init_speech_transcribe = __esm({
|
|
|
63053
63829
|
});
|
|
63054
63830
|
|
|
63055
63831
|
// src/bridge/activity.ts
|
|
63056
|
-
import { appendFile as appendFile3, mkdir as mkdir29, readFile as
|
|
63832
|
+
import { appendFile as appendFile3, mkdir as mkdir29, readFile as readFile48, rename as rename9, stat as stat25 } from "node:fs/promises";
|
|
63057
63833
|
import path116 from "node:path";
|
|
63058
63834
|
var ActivityJournal;
|
|
63059
63835
|
var init_activity2 = __esm({
|
|
@@ -63088,14 +63864,14 @@ var init_activity2 = __esm({
|
|
|
63088
63864
|
if (!changes.length) return;
|
|
63089
63865
|
const root = bridgeRoot(), file4 = path116.join(root, "activity.jsonl");
|
|
63090
63866
|
await mkdir29(root, { recursive: true, mode: 448 });
|
|
63091
|
-
if ((await stat25(file4).catch(() => null))?.size && (await stat25(file4)).size > 2097152) await
|
|
63867
|
+
if ((await stat25(file4).catch(() => null))?.size && (await stat25(file4)).size > 2097152) await rename9(file4, file4 + ".previous");
|
|
63092
63868
|
await appendFile3(file4, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
|
|
63093
63869
|
if (this.previous.size > 4096) this.previous.clear();
|
|
63094
63870
|
});
|
|
63095
63871
|
return this.pending;
|
|
63096
63872
|
}
|
|
63097
63873
|
async recent() {
|
|
63098
|
-
const text5 = await
|
|
63874
|
+
const text5 = await readFile48(path116.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
|
|
63099
63875
|
return text5.trim().split("\n").slice(-500).flatMap((line) => {
|
|
63100
63876
|
try {
|
|
63101
63877
|
return [JSON.parse(line)];
|
|
@@ -63229,7 +64005,7 @@ var init_code_package = __esm({
|
|
|
63229
64005
|
});
|
|
63230
64006
|
|
|
63231
64007
|
// src/bridge/code-routes.ts
|
|
63232
|
-
import { rm as
|
|
64008
|
+
import { rm as rm14 } from "node:fs/promises";
|
|
63233
64009
|
import * as fs46 from "node:fs";
|
|
63234
64010
|
import * as path118 from "node:path";
|
|
63235
64011
|
async function requireCodePackage(store) {
|
|
@@ -63254,7 +64030,7 @@ async function resolveCodeStore(base, value2, write = false) {
|
|
|
63254
64030
|
function noIndex(project) {
|
|
63255
64031
|
return new BridgeError(404, `No code index for "${project}" on this computer. Build one with: phren code index ${project}`);
|
|
63256
64032
|
}
|
|
63257
|
-
function
|
|
64033
|
+
function readHead2(root) {
|
|
63258
64034
|
try {
|
|
63259
64035
|
const dotGit = path118.join(root, ".git");
|
|
63260
64036
|
const gitDirectory2 = fs46.statSync(dotGit).isDirectory() ? dotGit : (() => {
|
|
@@ -63492,7 +64268,7 @@ var init_code_routes = __esm({
|
|
|
63492
64268
|
const project = projectSchema.parse(projectValue ?? "");
|
|
63493
64269
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
63494
64270
|
const file4 = codeDatabasePath(this.store, project);
|
|
63495
|
-
await Promise.all([file4, `${file4}-journal`, `${file4}-wal`, `${file4}-shm`].map((
|
|
64271
|
+
await Promise.all([file4, `${file4}-journal`, `${file4}-wal`, `${file4}-shm`].map((path146) => rm14(path146, { force: true })));
|
|
63496
64272
|
return { project, disabled: true };
|
|
63497
64273
|
}
|
|
63498
64274
|
async reindex(projectValue) {
|
|
@@ -63584,7 +64360,7 @@ var init_code_routes = __esm({
|
|
|
63584
64360
|
for (const root of new Set(files.map((file4) => file4.root))) {
|
|
63585
64361
|
const project = projects.find((entry2) => entry2.root === root);
|
|
63586
64362
|
if (!project) continue;
|
|
63587
|
-
const head =
|
|
64363
|
+
const head = readHead2(root);
|
|
63588
64364
|
const previous = this.heads.get(root);
|
|
63589
64365
|
if (head !== void 0) this.heads.set(root, head);
|
|
63590
64366
|
this.schedule(project.project, previous !== void 0 && head !== void 0 && previous !== head);
|
|
@@ -63780,8 +64556,8 @@ var init_context2 = __esm({
|
|
|
63780
64556
|
|
|
63781
64557
|
// src/bridge/questions.ts
|
|
63782
64558
|
import { execFile as execFile26 } from "node:child_process";
|
|
63783
|
-
import { createHash as
|
|
63784
|
-
import { mkdir as mkdir30, open as open25, stat as stat26, readFile as
|
|
64559
|
+
import { createHash as createHash30 } from "node:crypto";
|
|
64560
|
+
import { mkdir as mkdir30, open as open25, stat as stat26, readFile as readFile49, writeFile as writeFile10 } from "node:fs/promises";
|
|
63785
64561
|
import path119 from "node:path";
|
|
63786
64562
|
import { promisify as promisify24 } from "node:util";
|
|
63787
64563
|
function asyncQuestion(raw, id2) {
|
|
@@ -64023,8 +64799,8 @@ ${attachedFiles(paths)}` : answer;
|
|
|
64023
64799
|
this.snapshots.set(target.session, { at: Date.now(), stamp: stamp2, pending });
|
|
64024
64800
|
}
|
|
64025
64801
|
return Promise.all((pending ?? []).map(async (p) => {
|
|
64026
|
-
const key4 =
|
|
64027
|
-
const submitted = await
|
|
64802
|
+
const key4 = createHash30("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
|
|
64803
|
+
const submitted = await readFile49(path119.join(bridgeRoot(), "question-replies", key4), "utf8").then((value2) => value2 === "submitted").catch(() => false);
|
|
64028
64804
|
return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
|
|
64029
64805
|
})).then((prompts) => prompts.filter((p) => !p.submitted));
|
|
64030
64806
|
}
|
|
@@ -64059,7 +64835,7 @@ ${attachedFiles(paths)}` : answer;
|
|
|
64059
64835
|
if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
64060
64836
|
const directory = path119.join(bridgeRoot(), "question-replies");
|
|
64061
64837
|
await mkdir30(directory, { recursive: true, mode: 448 });
|
|
64062
|
-
const key4 =
|
|
64838
|
+
const key4 = createHash30("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
|
|
64063
64839
|
const receiptPath = path119.join(directory, key4);
|
|
64064
64840
|
const receipt = await open25(receiptPath, "wx", 384).catch((error62) => {
|
|
64065
64841
|
if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
@@ -64069,7 +64845,7 @@ ${attachedFiles(paths)}` : answer;
|
|
|
64069
64845
|
try {
|
|
64070
64846
|
if (entry2) await this.served.steer(entry2, reply, extra);
|
|
64071
64847
|
else await exec21(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
|
|
64072
|
-
await
|
|
64848
|
+
await writeFile10(receiptPath, "submitted", { mode: 384 });
|
|
64073
64849
|
} catch {
|
|
64074
64850
|
throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
|
|
64075
64851
|
}
|
|
@@ -64296,7 +65072,7 @@ var init_settings_switch = __esm({
|
|
|
64296
65072
|
if (pane.agent_status === "working") throw new BridgeError(409, "The agent started working during the settings change. The result is unconfirmed; check the terminal.");
|
|
64297
65073
|
};
|
|
64298
65074
|
const screenMode = async () => claudeFooterMode(await this.hooks.paneLines(target));
|
|
64299
|
-
const
|
|
65075
|
+
const changed = async (from, wait) => {
|
|
64300
65076
|
const deadline = Date.now() + wait;
|
|
64301
65077
|
do {
|
|
64302
65078
|
await new Promise((resolve17) => setTimeout(resolve17, 150));
|
|
@@ -64348,7 +65124,7 @@ var init_settings_switch = __esm({
|
|
|
64348
65124
|
if (change.plan === true) {
|
|
64349
65125
|
if (started !== "plan") {
|
|
64350
65126
|
await slash("/plan");
|
|
64351
|
-
mode = await
|
|
65127
|
+
mode = await changed(started, this.wait);
|
|
64352
65128
|
if (mode !== "plan") throw new BridgeError(409, "Claude did not enter plan mode. Open terminal to check.");
|
|
64353
65129
|
}
|
|
64354
65130
|
} else if (change.permissionMode || change.plan === false) {
|
|
@@ -64358,7 +65134,7 @@ var init_settings_switch = __esm({
|
|
|
64358
65134
|
if (presses >= MAX_PRESSES || presses > 0 && mode === started) throw new BridgeError(422, "Claude doesn't offer that mode in this session.");
|
|
64359
65135
|
await validate2();
|
|
64360
65136
|
await terminalProvider().sendKeys(target.server, target.pane, ["shift+tab"]);
|
|
64361
|
-
mode = await
|
|
65137
|
+
mode = await changed(mode, this.wait);
|
|
64362
65138
|
}
|
|
64363
65139
|
}
|
|
64364
65140
|
const phone = mode ? CLAUDE_MODES[mode] : void 0;
|
|
@@ -64374,7 +65150,7 @@ var init_settings_switch = __esm({
|
|
|
64374
65150
|
});
|
|
64375
65151
|
|
|
64376
65152
|
// src/bridge/job-registry.ts
|
|
64377
|
-
import { readFileSync as
|
|
65153
|
+
import { readFileSync as readFileSync50 } from "node:fs";
|
|
64378
65154
|
import path120 from "node:path";
|
|
64379
65155
|
function jobKey(job) {
|
|
64380
65156
|
if (job.pane) return `pane:${paneKey3(job.pane)}`;
|
|
@@ -64515,7 +65291,7 @@ var init_job_registry = __esm({
|
|
|
64515
65291
|
now;
|
|
64516
65292
|
async list() {
|
|
64517
65293
|
try {
|
|
64518
|
-
const parsed = stateSchema2.safeParse(JSON.parse(
|
|
65294
|
+
const parsed = stateSchema2.safeParse(JSON.parse(readFileSync50(this.file, "utf8")));
|
|
64519
65295
|
return parsed.success ? parsed.data.jobs : [];
|
|
64520
65296
|
} catch {
|
|
64521
65297
|
return [];
|
|
@@ -64574,7 +65350,7 @@ var init_job_registry = __esm({
|
|
|
64574
65350
|
|
|
64575
65351
|
// src/bridge/resources.ts
|
|
64576
65352
|
import { execFile as execFile27 } from "node:child_process";
|
|
64577
|
-
import { readdir as readdir19, readFile as
|
|
65353
|
+
import { readdir as readdir19, readFile as readFile50, statfs } from "node:fs/promises";
|
|
64578
65354
|
import { cpus, loadavg, totalmem, uptime } from "node:os";
|
|
64579
65355
|
import path121 from "node:path";
|
|
64580
65356
|
import { promisify as promisify25 } from "node:util";
|
|
@@ -64609,12 +65385,12 @@ function computerHardware(platform = process.platform) {
|
|
|
64609
65385
|
return { ...found, ...base };
|
|
64610
65386
|
}
|
|
64611
65387
|
if (platform === "linux") {
|
|
64612
|
-
const dmi = (name) =>
|
|
65388
|
+
const dmi = (name) => readFile50(`/sys/devices/virtual/dmi/id/${name}`, "utf8").catch(() => void 0);
|
|
64613
65389
|
const [vendor, product, version2, cpuinfo] = await Promise.all([
|
|
64614
65390
|
dmi("sys_vendor"),
|
|
64615
65391
|
dmi("product_name"),
|
|
64616
65392
|
dmi("product_version"),
|
|
64617
|
-
|
|
65393
|
+
readFile50("/proc/cpuinfo", "utf8").catch(() => "")
|
|
64618
65394
|
]);
|
|
64619
65395
|
const model = linuxModel(vendor, product, version2), chip = linuxChip(cpuinfo);
|
|
64620
65396
|
return { ...model ? { model } : {}, ...chip ? { chip } : {}, ...base };
|
|
@@ -64833,7 +65609,7 @@ async function linuxBattery() {
|
|
|
64833
65609
|
const names = await readdir19(root).catch(() => []);
|
|
64834
65610
|
const battery = names.find((name) => /^BAT/.test(name));
|
|
64835
65611
|
if (!battery) return void 0;
|
|
64836
|
-
const read = (name, field) =>
|
|
65612
|
+
const read = (name, field) => readFile50(path121.join(root, name, field), "utf8").then((text5) => text5.trim()).catch(() => "");
|
|
64837
65613
|
const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
|
|
64838
65614
|
const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
|
|
64839
65615
|
const percent = Number(capacity2);
|
|
@@ -64903,7 +65679,7 @@ async function collectResources(deps2) {
|
|
|
64903
65679
|
const platform = deps2.platform;
|
|
64904
65680
|
const registry2 = deps2.jobs ?? new JobRegistry();
|
|
64905
65681
|
const [memory, disk, battery, rows2, registered, hardware] = await Promise.all([
|
|
64906
|
-
platform === "darwin" ? darwinMemory() : platform === "linux" ?
|
|
65682
|
+
platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile50("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
|
|
64907
65683
|
statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
|
|
64908
65684
|
platform === "darwin" ? run3("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
|
|
64909
65685
|
deps2.processes().catch(() => []),
|
|
@@ -64984,7 +65760,7 @@ var init_resources = __esm({
|
|
|
64984
65760
|
});
|
|
64985
65761
|
|
|
64986
65762
|
// src/bridge/canary.ts
|
|
64987
|
-
import { lstat as lstat33, mkdtemp as mkdtemp6, realpath as realpath19, rm as
|
|
65763
|
+
import { lstat as lstat33, mkdtemp as mkdtemp6, realpath as realpath19, rm as rm15 } from "node:fs/promises";
|
|
64988
65764
|
import { hostname as hostname11, tmpdir as tmpdir5 } from "node:os";
|
|
64989
65765
|
import path122 from "node:path";
|
|
64990
65766
|
function reason(error62) {
|
|
@@ -65031,7 +65807,7 @@ async function conductorStep(options, server) {
|
|
|
65031
65807
|
failure2 = reason(error62);
|
|
65032
65808
|
} finally {
|
|
65033
65809
|
const cleanup = await closeCanaryWorkspaces(server, before, created);
|
|
65034
|
-
await
|
|
65810
|
+
await rm15(folder, { recursive: true, force: true }).catch(() => {
|
|
65035
65811
|
});
|
|
65036
65812
|
if (cleanup) failure2 = failure2 ? `${failure2}; ${cleanup}` : cleanup;
|
|
65037
65813
|
}
|
|
@@ -65143,7 +65919,7 @@ var init_canary = __esm({
|
|
|
65143
65919
|
|
|
65144
65920
|
// src/bridge/launch-worktree.ts
|
|
65145
65921
|
import { execFile as execFile28 } from "node:child_process";
|
|
65146
|
-
import { mkdir as mkdir31, realpath as realpath20, rm as
|
|
65922
|
+
import { mkdir as mkdir31, realpath as realpath20, rm as rm16, stat as stat28 } from "node:fs/promises";
|
|
65147
65923
|
import path123 from "node:path";
|
|
65148
65924
|
import { promisify as promisify26 } from "node:util";
|
|
65149
65925
|
async function git7(cwd, ...args) {
|
|
@@ -65189,7 +65965,7 @@ async function createLaunchWorktree(cwd, request9) {
|
|
|
65189
65965
|
path: abs,
|
|
65190
65966
|
branch,
|
|
65191
65967
|
async discard() {
|
|
65192
|
-
await git7(root, "worktree", "remove", "--force", abs).catch(() =>
|
|
65968
|
+
await git7(root, "worktree", "remove", "--force", abs).catch(() => rm16(abs, { recursive: true, force: true }));
|
|
65193
65969
|
await git7(root, "worktree", "prune").catch(() => void 0);
|
|
65194
65970
|
await git7(root, "branch", "-D", branch).catch(() => void 0);
|
|
65195
65971
|
}
|
|
@@ -65211,7 +65987,7 @@ var init_launch_worktree = __esm({
|
|
|
65211
65987
|
});
|
|
65212
65988
|
|
|
65213
65989
|
// src/bridge/server-launch.ts
|
|
65214
|
-
import { mkdir as mkdir32, mkdtemp as mkdtemp7, readFile as
|
|
65990
|
+
import { mkdir as mkdir32, mkdtemp as mkdtemp7, readFile as readFile51, realpath as realpath21, rmdir as rmdir2 } from "node:fs/promises";
|
|
65215
65991
|
import path124 from "node:path";
|
|
65216
65992
|
function effortArgs(kind, effort) {
|
|
65217
65993
|
if (kind === "claude") return ["--effort", effort];
|
|
@@ -65231,7 +66007,7 @@ async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
|
|
|
65231
66007
|
return [...mode === "chat" ? ["--mode", "chat"] : [], ...resume ? ["--session", resume] : []];
|
|
65232
66008
|
}
|
|
65233
66009
|
async function sessionUsedTools(session, store = phrenStoreRoot()) {
|
|
65234
|
-
const raw = await
|
|
66010
|
+
const raw = await readFile51(path124.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
|
|
65235
66011
|
const withTools = (message) => {
|
|
65236
66012
|
const content = message?.content;
|
|
65237
66013
|
return Array.isArray(content) && content.some((block) => ["tool_use", "tool_result"].includes(String(block?.type)));
|
|
@@ -65273,7 +66049,7 @@ mode: primary
|
|
|
65273
66049
|
${brief}
|
|
65274
66050
|
`;
|
|
65275
66051
|
await mkdir32(directory, { recursive: true, mode: 448 });
|
|
65276
|
-
if (await
|
|
66052
|
+
if (await readFile51(file4, "utf8").catch(() => void 0) !== definition) await atomic(file4, definition, 420);
|
|
65277
66053
|
return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
|
|
65278
66054
|
}
|
|
65279
66055
|
if (kind === "phren") return [...PHREN_AGENT_ARGS, ...model ? phrenModelArgs(model) : [], "--append-system-prompt-file", briefFile, ...effortArgs(kind, effort)];
|
|
@@ -65501,7 +66277,9 @@ async function startSession(server, data, options) {
|
|
|
65501
66277
|
startThread: !!brief,
|
|
65502
66278
|
...permissionMode ? { remoteArgs: codexModeFlags(permissionMode) } : {}
|
|
65503
66279
|
}).catch((error62) => {
|
|
65504
|
-
|
|
66280
|
+
const note = `Codex app-server unavailable, typing instead: ${error62 instanceof Error ? error62.message : String(error62)}`;
|
|
66281
|
+
if (error62 instanceof AppServerUnsupportedError) logger.debug("launch", note);
|
|
66282
|
+
else logger.warn("launch", note);
|
|
65505
66283
|
return void 0;
|
|
65506
66284
|
}) : void 0;
|
|
65507
66285
|
const appServer = structuredLaunch?.entry;
|
|
@@ -66780,8 +67558,8 @@ var init_session_git = __esm({
|
|
|
66780
67558
|
// src/bridge/enroll.ts
|
|
66781
67559
|
import { execFile as execFile29 } from "node:child_process";
|
|
66782
67560
|
import { promisify as promisify27 } from "node:util";
|
|
66783
|
-
import { realpathSync as
|
|
66784
|
-
import { readdir as readdir20, readFile as
|
|
67561
|
+
import { realpathSync as realpathSync6 } from "node:fs";
|
|
67562
|
+
import { readdir as readdir20, readFile as readFile52, stat as stat30, mkdir as mkdir33 } from "node:fs/promises";
|
|
66785
67563
|
import { homedir as homedir19 } from "node:os";
|
|
66786
67564
|
import path130 from "node:path";
|
|
66787
67565
|
function repoName(url2) {
|
|
@@ -66810,7 +67588,7 @@ async function registeredSources(env) {
|
|
|
66810
67588
|
const source = readProjectConfig(store, project).sourcePath;
|
|
66811
67589
|
if (typeof source === "string" && source) {
|
|
66812
67590
|
try {
|
|
66813
|
-
paths.add(
|
|
67591
|
+
paths.add(realpathSync6.native(path130.resolve(source)));
|
|
66814
67592
|
} catch {
|
|
66815
67593
|
}
|
|
66816
67594
|
}
|
|
@@ -66825,7 +67603,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
66825
67603
|
let dir = path130.resolve(directory);
|
|
66826
67604
|
try {
|
|
66827
67605
|
if (!(await stat30(dir)).isDirectory()) return;
|
|
66828
|
-
dir =
|
|
67606
|
+
dir = realpathSync6.native(dir);
|
|
66829
67607
|
} catch {
|
|
66830
67608
|
return;
|
|
66831
67609
|
}
|
|
@@ -66869,7 +67647,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
66869
67647
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
66870
67648
|
}
|
|
66871
67649
|
try {
|
|
66872
|
-
const session = JSON.parse(await
|
|
67650
|
+
const session = JSON.parse(await readFile52(path130.join(herdrRoot(), "session.json"), "utf8"));
|
|
66873
67651
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
66874
67652
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
66875
67653
|
if (!path130.isAbsolute(directory)) continue;
|
|
@@ -66954,7 +67732,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
66954
67732
|
const raw = input2.directory;
|
|
66955
67733
|
if (raw.length > 4096 || raw.includes("\0") || !path130.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
66956
67734
|
try {
|
|
66957
|
-
directory =
|
|
67735
|
+
directory = realpathSync6.native(raw);
|
|
66958
67736
|
if (!(await stat30(directory)).isDirectory()) throw new Error();
|
|
66959
67737
|
} catch {
|
|
66960
67738
|
throw new BridgeError(404, "That folder is not on this computer.");
|
|
@@ -72169,10 +72947,10 @@ var init_project_git = __esm({
|
|
|
72169
72947
|
|
|
72170
72948
|
// src/bridge/simulators.ts
|
|
72171
72949
|
import { execFile as execFile30 } from "node:child_process";
|
|
72172
|
-
import { chmod as chmod5, mkdir as mkdir34, readFile as
|
|
72950
|
+
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";
|
|
72173
72951
|
import { tmpdir as tmpdir6 } from "node:os";
|
|
72174
72952
|
import path137 from "node:path";
|
|
72175
|
-
import { createHash as
|
|
72953
|
+
import { createHash as createHash31, randomUUID as randomUUID29 } from "node:crypto";
|
|
72176
72954
|
import { promisify as promisify28 } from "node:util";
|
|
72177
72955
|
async function bootedSimulators() {
|
|
72178
72956
|
if (process.platform !== "darwin") return [];
|
|
@@ -72200,7 +72978,7 @@ async function simulatorScreenshot(udid) {
|
|
|
72200
72978
|
const file4 = path137.join(tmpdir6(), `phren-sim-${randomUUID29()}.png`);
|
|
72201
72979
|
try {
|
|
72202
72980
|
await exec25("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file4], { timeout: 15e3 });
|
|
72203
|
-
return await
|
|
72981
|
+
return await readFile53(file4);
|
|
72204
72982
|
} catch (error62) {
|
|
72205
72983
|
if (error62 instanceof BridgeError) throw error62;
|
|
72206
72984
|
throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
|
|
@@ -72308,23 +73086,23 @@ case "type":
|
|
|
72308
73086
|
}
|
|
72309
73087
|
default: fail(2, "unknown command \\(command)")
|
|
72310
73088
|
}
|
|
72311
|
-
` : await
|
|
72312
|
-
const digest2 =
|
|
72313
|
-
const saved = await
|
|
73089
|
+
` : await readFile53(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
73090
|
+
const digest2 = createHash31("sha256").update(code).digest("hex");
|
|
73091
|
+
const saved = await readFile53(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
72314
73092
|
if (await stat31(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
72315
73093
|
await mkdir34(dir, { recursive: true, mode: 448 });
|
|
72316
73094
|
const temporary = path137.join(dir, `simtap.${randomUUID29()}`), source = temporary + ".swift";
|
|
72317
73095
|
const sidecar = temporary + ".sha256";
|
|
72318
73096
|
try {
|
|
72319
|
-
await
|
|
73097
|
+
await writeFile11(source, code, { mode: 384, flag: "wx" });
|
|
72320
73098
|
await exec25("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
|
|
72321
73099
|
throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
|
|
72322
73100
|
});
|
|
72323
73101
|
await chmod5(temporary, 448);
|
|
72324
|
-
const binarySha =
|
|
72325
|
-
await
|
|
72326
|
-
await
|
|
72327
|
-
await
|
|
73102
|
+
const binarySha = createHash31("sha256").update(await readFile53(temporary)).digest("hex");
|
|
73103
|
+
await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
|
|
73104
|
+
await rename10(temporary, binary);
|
|
73105
|
+
await rename10(sidecar, binary + ".sha256");
|
|
72328
73106
|
} finally {
|
|
72329
73107
|
await Promise.all([source, temporary, sidecar].map((file4) => unlink9(file4).catch(() => void 0)));
|
|
72330
73108
|
}
|
|
@@ -72338,8 +73116,8 @@ function simtap(name, ...args) {
|
|
|
72338
73116
|
}
|
|
72339
73117
|
async function verifiedHelper() {
|
|
72340
73118
|
const binary = await helper();
|
|
72341
|
-
const saved = await
|
|
72342
|
-
const binarySha =
|
|
73119
|
+
const saved = await readFile53(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
73120
|
+
const binarySha = createHash31("sha256").update(await readFile53(binary)).digest("hex");
|
|
72343
73121
|
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
|
|
72344
73122
|
return binary;
|
|
72345
73123
|
}
|
|
@@ -72632,9 +73410,80 @@ var init_steps = __esm({
|
|
|
72632
73410
|
}
|
|
72633
73411
|
});
|
|
72634
73412
|
|
|
73413
|
+
// src/bridge/schedule-update.ts
|
|
73414
|
+
import path139 from "node:path";
|
|
73415
|
+
async function updateScheduleRoute(store, body2) {
|
|
73416
|
+
let input2;
|
|
73417
|
+
try {
|
|
73418
|
+
input2 = updateSchema.parse(body2);
|
|
73419
|
+
} catch (error62) {
|
|
73420
|
+
throw new BridgeError(400, error62 instanceof Error ? error62.message : "Invalid schedule update.");
|
|
73421
|
+
}
|
|
73422
|
+
const directory = getProjectDirs(store).find((dir) => path139.basename(dir).toLowerCase() === input2.project.toLowerCase());
|
|
73423
|
+
if (!directory) throw new BridgeError(404, `Unknown project "${input2.project}".`);
|
|
73424
|
+
return withScheduleLock(directory, () => {
|
|
73425
|
+
const file4 = readScheduleDocumentSync(directory);
|
|
73426
|
+
const schedules = file4.document.schedules ?? [];
|
|
73427
|
+
const index2 = schedules.findIndex((schedule) => schedule.id === input2.id);
|
|
73428
|
+
if (index2 < 0) throw new BridgeError(404, `Schedule "${input2.id}" was not found in ${input2.project}.`);
|
|
73429
|
+
const current2 = schedules[index2];
|
|
73430
|
+
if (current2.updatedAt !== input2.expectedUpdatedAt) {
|
|
73431
|
+
throw new BridgeError(409, "This schedule changed. Refresh it and try again.", { schedule: current2 });
|
|
73432
|
+
}
|
|
73433
|
+
const updated = { ...current2 };
|
|
73434
|
+
for (const [key4, value2] of Object.entries(input2.changes)) {
|
|
73435
|
+
if (value2 === null) delete updated[key4];
|
|
73436
|
+
else updated[key4] = value2;
|
|
73437
|
+
}
|
|
73438
|
+
try {
|
|
73439
|
+
parseSchedule(updated);
|
|
73440
|
+
} catch (error62) {
|
|
73441
|
+
throw new BridgeError(400, error62 instanceof Error ? error62.message : "Invalid schedule.");
|
|
73442
|
+
}
|
|
73443
|
+
updated.updatedAt = new Date(Math.max(Date.now(), Date.parse(current2.updatedAt) + 1)).toISOString();
|
|
73444
|
+
schedules[index2] = updated;
|
|
73445
|
+
writeScheduleDocumentSync(directory, schedules, file4.document);
|
|
73446
|
+
return { ok: true, schedule: updated };
|
|
73447
|
+
});
|
|
73448
|
+
}
|
|
73449
|
+
var optional2, updateSchema;
|
|
73450
|
+
var init_schedule_update = __esm({
|
|
73451
|
+
"src/bridge/schedule-update.ts"() {
|
|
73452
|
+
"use strict";
|
|
73453
|
+
init_zod();
|
|
73454
|
+
init_shared();
|
|
73455
|
+
init_protocol();
|
|
73456
|
+
init_schedule_format();
|
|
73457
|
+
optional2 = (schema) => schema.nullable().optional();
|
|
73458
|
+
updateSchema = external_exports.object({
|
|
73459
|
+
project: external_exports.string().min(1).max(200),
|
|
73460
|
+
id: external_exports.string().regex(/^[a-f0-9]{8}$/),
|
|
73461
|
+
expectedUpdatedAt: external_exports.string().datetime({ offset: true }),
|
|
73462
|
+
changes: external_exports.object({
|
|
73463
|
+
name: external_exports.string().optional(),
|
|
73464
|
+
prompt: external_exports.string().optional(),
|
|
73465
|
+
enabled: external_exports.boolean().optional(),
|
|
73466
|
+
computer: external_exports.string().optional(),
|
|
73467
|
+
harness: external_exports.enum(SCHEDULE_HARNESSES).optional(),
|
|
73468
|
+
every: external_exports.enum(SCHEDULE_EVERY).optional(),
|
|
73469
|
+
model: optional2(external_exports.string()),
|
|
73470
|
+
account: optional2(external_exports.string()),
|
|
73471
|
+
notify: optional2(external_exports.array(external_exports.enum(SCHEDULE_NOTIFY))),
|
|
73472
|
+
projects: optional2(external_exports.array(external_exports.string())),
|
|
73473
|
+
session: optional2(external_exports.enum(SCHEDULE_SESSIONS)),
|
|
73474
|
+
at: optional2(external_exports.string()),
|
|
73475
|
+
days: optional2(external_exports.array(external_exports.enum(WEEKDAYS))),
|
|
73476
|
+
interval: optional2(external_exports.string()),
|
|
73477
|
+
once: optional2(external_exports.string()),
|
|
73478
|
+
cron: optional2(external_exports.string())
|
|
73479
|
+
}).strict()
|
|
73480
|
+
}).strict();
|
|
73481
|
+
}
|
|
73482
|
+
});
|
|
73483
|
+
|
|
72635
73484
|
// src/bridge/session-rename.ts
|
|
72636
73485
|
import { open as open28 } from "node:fs/promises";
|
|
72637
|
-
import
|
|
73486
|
+
import path140 from "node:path";
|
|
72638
73487
|
function lastCustomTitle(text5) {
|
|
72639
73488
|
for (const line of text5.split("\n").reverse()) {
|
|
72640
73489
|
if (!line.includes('"custom-title"')) continue;
|
|
@@ -72784,7 +73633,7 @@ var init_session_rename = __esm({
|
|
|
72784
73633
|
return text5 === void 0 ? void 0 : lastCustomTitle(text5);
|
|
72785
73634
|
},
|
|
72786
73635
|
async codexIndexTitle(thread) {
|
|
72787
|
-
const text5 = await tail(
|
|
73636
|
+
const text5 = await tail(path140.join(codexHome(), "session_index.jsonl"));
|
|
72788
73637
|
return text5 === void 0 ? void 0 : lastIndexedName(text5, thread);
|
|
72789
73638
|
},
|
|
72790
73639
|
sleep: (ms2) => new Promise((resolve17) => setTimeout(resolve17, ms2)),
|
|
@@ -72795,9 +73644,9 @@ var init_session_rename = __esm({
|
|
|
72795
73644
|
|
|
72796
73645
|
// src/bridge/link.ts
|
|
72797
73646
|
import { execFile as execFile31 } from "node:child_process";
|
|
72798
|
-
import { readFile as
|
|
73647
|
+
import { readFile as readFile54 } from "node:fs/promises";
|
|
72799
73648
|
import { homedir as homedir21, hostname as hostname12, userInfo as userInfo5 } from "node:os";
|
|
72800
|
-
import
|
|
73649
|
+
import path141 from "node:path";
|
|
72801
73650
|
import { promisify as promisify29 } from "node:util";
|
|
72802
73651
|
function sshConfigHosts(text5) {
|
|
72803
73652
|
const hosts = [];
|
|
@@ -72840,11 +73689,11 @@ async function probe2(host) {
|
|
|
72840
73689
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
72841
73690
|
}
|
|
72842
73691
|
async function discoverComputers(options = {}) {
|
|
72843
|
-
const config4 = options.sshConfig ?? await
|
|
73692
|
+
const config4 = options.sshConfig ?? await readFile54(path141.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
|
|
72844
73693
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
72845
73694
|
const machines = store ? listMachines(store) : void 0;
|
|
72846
73695
|
const { peers } = await optionalHookPeers();
|
|
72847
|
-
const own2 = (await
|
|
73696
|
+
const own2 = (await readFile54(path141.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
72848
73697
|
const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
72849
73698
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config4), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
|
|
72850
73699
|
const [found, peerIds] = await Promise.all([
|
|
@@ -72866,7 +73715,7 @@ function slugName(value2) {
|
|
|
72866
73715
|
async function linkComputer(host, options = {}) {
|
|
72867
73716
|
const remote = await probe2(host);
|
|
72868
73717
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
72869
|
-
const own2 = (await
|
|
73718
|
+
const own2 = (await readFile54(path141.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
72870
73719
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
72871
73720
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
72872
73721
|
const as2 = computerName.parse(options.as ?? slugName(hostname12()));
|
|
@@ -73047,7 +73896,7 @@ var init_mux_wire = __esm({
|
|
|
73047
73896
|
});
|
|
73048
73897
|
|
|
73049
73898
|
// src/bridge/server-routes.ts
|
|
73050
|
-
import
|
|
73899
|
+
import path142 from "node:path";
|
|
73051
73900
|
async function childActivity(source, session) {
|
|
73052
73901
|
const key4 = `${source}\0${session}`, now = Date.now(), cached3 = childActivityCache.get(key4);
|
|
73053
73902
|
if (cached3 && (cached3.pending || now - cached3.at < CHILD_ACTIVITY_CACHE_MS)) return cached3.result;
|
|
@@ -73069,7 +73918,10 @@ function capabilitiesForModules(snapshot2) {
|
|
|
73069
73918
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
73070
73919
|
for (const name of ["memory", "tasks", "hook", "git", "schedules"]) if (snapshot2.has(name)) result[name] = true;
|
|
73071
73920
|
if (snapshot2.has("hook")) result.approvalRules = { version: 2, effects: ["always-ask", "deny"], harnesses: ["claude"], events: ["PermissionRequest"], tools: ["Bash"], inputField: "command", conductorTools: false, mcpTools: false, preExecution: false };
|
|
73072
|
-
if (snapshot2.has("schedules"))
|
|
73921
|
+
if (snapshot2.has("schedules")) {
|
|
73922
|
+
result.scheduleProjects = true;
|
|
73923
|
+
result.scheduleUpdate = true;
|
|
73924
|
+
}
|
|
73073
73925
|
if (snapshot2.has("tasks")) {
|
|
73074
73926
|
result.taskDependencies = true;
|
|
73075
73927
|
result.taskWriterSafety = true;
|
|
@@ -73259,6 +74111,8 @@ function createRouteHandler(ctx) {
|
|
|
73259
74111
|
} = ctx;
|
|
73260
74112
|
const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
|
|
73261
74113
|
const readWorkspaces = workspacesReader(ctx);
|
|
74114
|
+
const gitWrites = new GitWriteDiagnostics();
|
|
74115
|
+
const paneContext = { ...ctx, gitWrites };
|
|
73262
74116
|
return async (request9, response) => {
|
|
73263
74117
|
response.setHeader("X-Phren-Protocol", String(PROTOCOL));
|
|
73264
74118
|
response.setHeader("Cache-Control", "no-store");
|
|
@@ -73300,13 +74154,16 @@ function createRouteHandler(ctx) {
|
|
|
73300
74154
|
result = hookMetrics.snapshot();
|
|
73301
74155
|
break;
|
|
73302
74156
|
case "/v1/health/details":
|
|
73303
|
-
result =
|
|
73304
|
-
|
|
73305
|
-
|
|
73306
|
-
|
|
73307
|
-
|
|
73308
|
-
|
|
73309
|
-
|
|
74157
|
+
result = {
|
|
74158
|
+
...await healthDetails({
|
|
74159
|
+
hookVersion: version2,
|
|
74160
|
+
computerId: computerID2,
|
|
74161
|
+
store: scheduleStore,
|
|
74162
|
+
scheduler: scheduler ? { running: true, lastTickAt: scheduler.lastTickAt } : void 0,
|
|
74163
|
+
push: agentHooks.push.status
|
|
74164
|
+
}),
|
|
74165
|
+
gitWrites: gitWrites.snapshot()
|
|
74166
|
+
};
|
|
73310
74167
|
break;
|
|
73311
74168
|
case "/v1/health/peers": {
|
|
73312
74169
|
const caller = external_exports.object({ name: external_exports.string().max(253).optional(), hostKey: external_exports.string().max(512).optional() }).parse({ name: url2.searchParams.get("name") ?? void 0, hostKey: url2.searchParams.get("hostKey") ?? void 0 });
|
|
@@ -73446,7 +74303,7 @@ function createRouteHandler(ctx) {
|
|
|
73446
74303
|
case "/v1/files/range": {
|
|
73447
74304
|
let root;
|
|
73448
74305
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
73449
|
-
root =
|
|
74306
|
+
root = path142.join(bridgeRoot(), "uploads");
|
|
73450
74307
|
} else if (url2.searchParams.has("session")) {
|
|
73451
74308
|
const target = targetFromURL(url2), pane = await validateTarget(target);
|
|
73452
74309
|
const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -73704,6 +74561,8 @@ function createRouteHandler(ctx) {
|
|
|
73704
74561
|
}).parse(data);
|
|
73705
74562
|
const runs = await scheduler.launchNow(input2.project, input2.id, false, input2.expectedUpdatedAt);
|
|
73706
74563
|
result = { ok: runs.every((run4) => run4.status !== "failed"), run: runs[0], runs };
|
|
74564
|
+
} else if (url2.pathname === "/v1/schedules/update") {
|
|
74565
|
+
result = await updateScheduleRoute(scheduleStore, data);
|
|
73707
74566
|
} else if (url2.pathname === "/v1/schedules/history") {
|
|
73708
74567
|
const input2 = external_exports.object({
|
|
73709
74568
|
project: external_exports.string().min(1).max(200).optional(),
|
|
@@ -73812,7 +74671,7 @@ function createRouteHandler(ctx) {
|
|
|
73812
74671
|
{ ...data, cwd: await launchDirectory(data.cwd ?? homeDir(), await journal.recent(), locatedDirectories) }
|
|
73813
74672
|
)) : await workspaceAction(selectedServer(url2), operation, data);
|
|
73814
74673
|
} else {
|
|
73815
|
-
result = await paneRoute(
|
|
74674
|
+
result = await paneRoute(paneContext, url2, data, response, request9.headers);
|
|
73816
74675
|
}
|
|
73817
74676
|
}
|
|
73818
74677
|
} else if (request9.method === "DELETE") {
|
|
@@ -73884,6 +74743,7 @@ var init_server_routes = __esm({
|
|
|
73884
74743
|
init_uploads();
|
|
73885
74744
|
init_steps();
|
|
73886
74745
|
init_usage();
|
|
74746
|
+
init_schedule_update();
|
|
73887
74747
|
init_schedule_watch();
|
|
73888
74748
|
init_health();
|
|
73889
74749
|
init_shared();
|
|
@@ -73894,6 +74754,7 @@ var init_server_routes = __esm({
|
|
|
73894
74754
|
init_conductor_sets();
|
|
73895
74755
|
init_conductor_role();
|
|
73896
74756
|
init_metrics();
|
|
74757
|
+
init_git_write_policy();
|
|
73897
74758
|
init_speech();
|
|
73898
74759
|
init_speech_key();
|
|
73899
74760
|
init_speech_voice();
|
|
@@ -74753,11 +75614,11 @@ var init_server_overview = __esm({
|
|
|
74753
75614
|
});
|
|
74754
75615
|
|
|
74755
75616
|
// src/bridge/codex-auth-refresh.ts
|
|
74756
|
-
import { readFile as
|
|
74757
|
-
import
|
|
74758
|
-
async function lastCodexRefresh(file4 =
|
|
75617
|
+
import { readFile as readFile55 } from "node:fs/promises";
|
|
75618
|
+
import path143 from "node:path";
|
|
75619
|
+
async function lastCodexRefresh(file4 = path143.join(codexHome(), "auth.json")) {
|
|
74759
75620
|
try {
|
|
74760
|
-
const auth = object2(JSON.parse(await
|
|
75621
|
+
const auth = object2(JSON.parse(await readFile55(file4, "utf8")));
|
|
74761
75622
|
if (!object2(auth.tokens).refresh_token) return void 0;
|
|
74762
75623
|
const at2 = Date.parse(String(auth.last_refresh ?? ""));
|
|
74763
75624
|
return Number.isFinite(at2) ? at2 : 0;
|
|
@@ -74768,14 +75629,16 @@ async function lastCodexRefresh(file4 = path142.join(codexHome(), "auth.json"))
|
|
|
74768
75629
|
function codexAuthRefreshEnabled(env = process.env) {
|
|
74769
75630
|
return !/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_AUTH_REFRESH ?? "");
|
|
74770
75631
|
}
|
|
74771
|
-
var REFRESH_AFTER_MS, CodexAuthKeeper;
|
|
75632
|
+
var REFRESH_AFTER_MS, CODEX_SIGNIN_STALE_MS, CodexAuthKeeper;
|
|
74772
75633
|
var init_codex_auth_refresh = __esm({
|
|
74773
75634
|
"src/bridge/codex-auth-refresh.ts"() {
|
|
74774
75635
|
"use strict";
|
|
74775
75636
|
init_home_paths();
|
|
74776
75637
|
init_logger();
|
|
75638
|
+
init_codex_app_server();
|
|
74777
75639
|
init_protocol();
|
|
74778
75640
|
REFRESH_AFTER_MS = 6 * 864e5;
|
|
75641
|
+
CODEX_SIGNIN_STALE_MS = 9 * 864e5;
|
|
74779
75642
|
CodexAuthKeeper = class {
|
|
74780
75643
|
constructor(refresher, file4, now = () => Date.now()) {
|
|
74781
75644
|
this.refresher = refresher;
|
|
@@ -74798,6 +75661,10 @@ var init_codex_auth_refresh = __esm({
|
|
|
74798
75661
|
try {
|
|
74799
75662
|
await this.refresher.refreshAuth();
|
|
74800
75663
|
} catch (error62) {
|
|
75664
|
+
if (error62 instanceof AppServerUnsupportedError) {
|
|
75665
|
+
logger.debug("codex-auth", `Sign-in refresh skipped: ${error62.message}`);
|
|
75666
|
+
return false;
|
|
75667
|
+
}
|
|
74801
75668
|
logger.warn("codex-auth", `Could not refresh the Codex sign-in ahead of its workers: ${error62 instanceof Error ? error62.message : String(error62)}`);
|
|
74802
75669
|
return false;
|
|
74803
75670
|
}
|
|
@@ -74813,11 +75680,11 @@ var init_codex_auth_refresh = __esm({
|
|
|
74813
75680
|
|
|
74814
75681
|
// src/bridge/server.ts
|
|
74815
75682
|
import { randomUUID as randomUUID30 } from "node:crypto";
|
|
74816
|
-
import { chmod as chmod6, lstat as lstat36, mkdir as mkdir35, readFile as
|
|
74817
|
-
import { readFileSync as
|
|
75683
|
+
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";
|
|
75684
|
+
import { readFileSync as readFileSync58 } from "node:fs";
|
|
74818
75685
|
import { createServer as createServer4 } from "node:http";
|
|
74819
75686
|
import { cpus as cpus2, hostname as hostname13, loadavg as loadavg2 } from "node:os";
|
|
74820
|
-
import
|
|
75687
|
+
import path144 from "node:path";
|
|
74821
75688
|
async function serve(version2, options = {}) {
|
|
74822
75689
|
process.umask(63);
|
|
74823
75690
|
const modules = activateModules(defaultPhrenPath(), void 0, true);
|
|
@@ -74827,12 +75694,12 @@ async function serve(version2, options = {}) {
|
|
|
74827
75694
|
await mkdir35(root, { recursive: true, mode: 448 });
|
|
74828
75695
|
await chmod6(root, 448);
|
|
74829
75696
|
let computerID2;
|
|
74830
|
-
const identityFile =
|
|
75697
|
+
const identityFile = path144.join(root, "computer-id");
|
|
74831
75698
|
try {
|
|
74832
|
-
computerID2 = (await
|
|
75699
|
+
computerID2 = (await readFile56(identityFile, "utf8")).trim();
|
|
74833
75700
|
} catch {
|
|
74834
75701
|
computerID2 = randomUUID30();
|
|
74835
|
-
await
|
|
75702
|
+
await writeFile12(identityFile, computerID2, { flag: "wx", mode: 384 });
|
|
74836
75703
|
}
|
|
74837
75704
|
const launches = new LaunchLimiter();
|
|
74838
75705
|
const dispatches = modules.has("conductor") ? new DispatchService({
|
|
@@ -74846,7 +75713,7 @@ async function serve(version2, options = {}) {
|
|
|
74846
75713
|
}) : void 0;
|
|
74847
75714
|
const locatedDirectories = /* @__PURE__ */ new Set();
|
|
74848
75715
|
const journal = new ActivityJournal();
|
|
74849
|
-
const agentHooks = new AgentHooks(void 0, modules,
|
|
75716
|
+
const agentHooks = new AgentHooks(void 0, modules, path144.join(bridgeRoot(), "deliveries.json"));
|
|
74850
75717
|
const returns = dispatches ? new DispatchReturns({
|
|
74851
75718
|
// Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
|
|
74852
75719
|
failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input2, origin, continues) => dispatches.dispatch(input2, origin, continues) }),
|
|
@@ -74954,7 +75821,7 @@ async function serve(version2, options = {}) {
|
|
|
74954
75821
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
74955
75822
|
function gatewayTiming() {
|
|
74956
75823
|
try {
|
|
74957
|
-
const parsed = JSON.parse(
|
|
75824
|
+
const parsed = JSON.parse(readFileSync58(path144.join(root, "gateway.json"), "utf8"));
|
|
74958
75825
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
74959
75826
|
} catch {
|
|
74960
75827
|
}
|
|
@@ -75000,7 +75867,7 @@ async function serve(version2, options = {}) {
|
|
|
75000
75867
|
}
|
|
75001
75868
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
75002
75869
|
};
|
|
75003
|
-
if (modules.has("git")) await
|
|
75870
|
+
if (modules.has("git")) await rm17(path144.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
75004
75871
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
|
|
75005
75872
|
const { stream } = streams;
|
|
75006
75873
|
const overview = overviewStream({
|
|
@@ -75266,24 +76133,24 @@ __export(device_enroll_exports, {
|
|
|
75266
76133
|
enrollDevice: () => enrollDevice,
|
|
75267
76134
|
runEnrollDevice: () => runEnrollDevice
|
|
75268
76135
|
});
|
|
75269
|
-
import { readFile as
|
|
76136
|
+
import { readFile as readFile57 } from "node:fs/promises";
|
|
75270
76137
|
import { homedir as homedir22, userInfo as userInfo6 } from "node:os";
|
|
75271
|
-
import
|
|
76138
|
+
import path145 from "node:path";
|
|
75272
76139
|
async function enrollDevice(input2, options) {
|
|
75273
76140
|
try {
|
|
75274
76141
|
const publicKey = publicComputerKey(input2);
|
|
75275
76142
|
const comment = options.device === "android" ? "phren-android" : "phren-iphone";
|
|
75276
76143
|
const line = `restrict,pty,${forcedCommand} ${publicKey} ${comment}`;
|
|
75277
76144
|
const encoded = publicKey.split(" ")[1];
|
|
75278
|
-
const file4 =
|
|
75279
|
-
const before = await
|
|
76145
|
+
const file4 = path145.join(options.sshDirectory ?? path145.join(homedir22(), ".ssh"), "authorized_keys");
|
|
76146
|
+
const before = await readFile57(file4, "utf8").catch(() => "");
|
|
75280
76147
|
await appendAuthorizedKey(
|
|
75281
76148
|
line,
|
|
75282
76149
|
(existing) => existing.split(/\s+/).includes(encoded),
|
|
75283
76150
|
"This phone key is already authorized with different options.",
|
|
75284
76151
|
options.sshDirectory
|
|
75285
76152
|
);
|
|
75286
|
-
const id2 = await
|
|
76153
|
+
const id2 = await readFile57(path145.join(options.root ?? bridgeRoot(), "computer-id"), "utf8").then((value2) => value2.trim() || null).catch(() => null);
|
|
75287
76154
|
return {
|
|
75288
76155
|
v: 1,
|
|
75289
76156
|
ok: true,
|
|
@@ -75334,13 +76201,13 @@ __export(command_exports, {
|
|
|
75334
76201
|
approvalPushCheck: () => approvalPushCheck,
|
|
75335
76202
|
runBridge: () => runBridge
|
|
75336
76203
|
});
|
|
75337
|
-
import { readFile as
|
|
76204
|
+
import { readFile as readFile58 } from "node:fs/promises";
|
|
75338
76205
|
async function runBridge(args, version2) {
|
|
75339
76206
|
switch (args[0]) {
|
|
75340
76207
|
case "enroll-computer": {
|
|
75341
76208
|
if (args.length === 2) console.log(await enrollComputer(args[1]));
|
|
75342
76209
|
else if (args.length === 4 && args[2] === "--accept") {
|
|
75343
|
-
await acceptComputer(args[1], await
|
|
76210
|
+
await acceptComputer(args[1], await readFile58(args[3], "utf8"));
|
|
75344
76211
|
console.log(`Enrolled ${args[1]} for Phren Hook.`);
|
|
75345
76212
|
} else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
|
|
75346
76213
|
break;
|
|
@@ -75515,7 +76382,7 @@ async function runBridge(args, version2) {
|
|
|
75515
76382
|
break;
|
|
75516
76383
|
}
|
|
75517
76384
|
const readModels = async (source) => {
|
|
75518
|
-
const rows2 = JSON.parse(await
|
|
76385
|
+
const rows2 = JSON.parse(await readFile58(fixture, "utf8"));
|
|
75519
76386
|
return Array.isArray(rows2[source]) ? rows2[source] : [];
|
|
75520
76387
|
};
|
|
75521
76388
|
const emptyUsage = (source) => ({ source, windows: [] });
|
|
@@ -75672,7 +76539,7 @@ async function main() {
|
|
|
75672
76539
|
return askpass2(args[1]);
|
|
75673
76540
|
}
|
|
75674
76541
|
const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
|
|
75675
|
-
return runBridge2(args, "0.3.
|
|
76542
|
+
return runBridge2(args, "0.3.47");
|
|
75676
76543
|
}
|
|
75677
76544
|
main().then((code) => {
|
|
75678
76545
|
process.exitCode = code;
|