@phren/cli 0.3.35 → 0.3.37
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/account-choice.d.ts +82 -0
- package/dist/bridge/account-choice.js +173 -0
- package/dist/bridge/account-failover.d.ts +57 -0
- package/dist/bridge/account-failover.js +181 -0
- package/dist/bridge/account-usage.d.ts +2 -0
- package/dist/bridge/account-usage.js +17 -2
- package/dist/bridge/agent-hooks.d.ts +11 -1
- package/dist/bridge/agent-hooks.js +56 -19
- package/dist/bridge/changes.js +18 -9
- package/dist/bridge/dispatch-command.js +3 -1
- package/dist/bridge/dispatch-returns.d.ts +12 -0
- package/dist/bridge/dispatch-returns.js +37 -6
- package/dist/bridge/dispatch.d.ts +31 -3
- package/dist/bridge/dispatch.js +68 -10
- package/dist/bridge/hand-off.d.ts +23 -1
- package/dist/bridge/hand-off.js +36 -3
- package/dist/bridge/health.js +3 -1
- package/dist/bridge/host-key.d.ts +16 -0
- package/dist/bridge/host-key.js +35 -0
- package/dist/bridge/launch-brief.d.ts +5 -0
- package/dist/bridge/launch-brief.js +21 -0
- package/dist/bridge/link.js +11 -4
- package/dist/bridge/owner-inbox-sources.d.ts +5 -0
- package/dist/bridge/owner-inbox-sources.js +94 -0
- package/dist/bridge/owner-inbox-view.js +20 -1
- package/dist/bridge/owner-inbox.d.ts +7 -3
- package/dist/bridge/owner-inbox.js +113 -69
- package/dist/bridge/pair.js +3 -2
- package/dist/bridge/peers.js +4 -2
- package/dist/bridge/schedule-launch.js +5 -1
- package/dist/bridge/schedule-watch.d.ts +3 -0
- package/dist/bridge/schedule-watch.js +27 -1
- package/dist/bridge/server-launch.js +6 -2
- package/dist/bridge/server-routes.js +5 -1
- package/dist/bridge/server.js +9 -23
- package/dist/bridge/sudo.d.ts +36 -6
- package/dist/bridge/sudo.js +180 -37
- package/dist/bridge/usage.d.ts +4 -2
- package/dist/bridge/usage.js +4 -2
- package/dist/bridge/worker-reports.d.ts +8 -1
- package/dist/bridge/worker-reports.js +28 -7
- package/dist/bridge-hook.mjs +7120 -6298
- package/dist/clanker.d.ts +54 -0
- package/dist/clanker.js +188 -0
- package/dist/cli/config.js +56 -0
- package/dist/cli/hooks-output.d.ts +1 -1
- package/dist/cli/hooks-output.js +28 -21
- package/dist/cli/hooks.js +1 -1
- package/dist/cli/namespaces-skills.js +2 -2
- package/dist/cli/namespaces-tasks.js +46 -7
- package/dist/cli/session-start.js +12 -3
- package/dist/cli/session-stop.js +9 -0
- package/dist/cli/team.js +3 -0
- package/dist/cli-handlers.js +7 -0
- package/dist/cli-registry.js +1 -0
- package/dist/data/task-format.d.ts +5 -1
- package/dist/data/task-format.js +13 -5
- package/dist/index.js +82 -50
- package/dist/init/init-configure.d.ts +2 -0
- package/dist/init/init-configure.js +12 -0
- package/dist/init/init-uninstall.js +21 -2
- package/dist/init/init.d.ts +2 -0
- package/dist/init/init.js +11 -3
- package/dist/init/preferences.d.ts +12 -0
- package/dist/init/teardown.js +18 -4
- package/dist/link/doctor.js +2 -2
- package/dist/link/link.js +9 -0
- package/dist/link/refresh.d.ts +10 -0
- package/dist/link/refresh.js +34 -0
- package/dist/mcp/local-index.d.ts +20 -0
- package/dist/mcp/local-index.js +39 -1
- package/dist/modules/registry.js +1 -1
- package/dist/shared/index.d.ts +14 -0
- package/dist/shared/index.js +88 -74
- package/dist/shared/retrieval.js +1 -1
- package/dist/skill/files.js +40 -11
- package/dist/skill/registry.d.ts +6 -0
- package/dist/skill/registry.js +21 -5
- package/dist/task/lifecycle.js +3 -1
- package/dist/tools/dispatch.js +7 -4
- package/dist/tools/finding.js +20 -11
- package/dist/tools/graph.d.ts +2 -0
- package/dist/tools/graph.js +2 -0
- package/dist/tools/search.d.ts +2 -0
- package/dist/tools/search.js +88 -6
- package/dist/tools/tasks.js +45 -0
- package/dist/tools/types.d.ts +3 -1
- package/dist/tools/types.js +3 -2
- package/package.json +1 -1
package/dist/bridge/sudo.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
3
|
import { EventEmitter } from "node:events";
|
|
4
4
|
import { existsSync, readlinkSync } from "node:fs";
|
|
5
5
|
import { open, readdir, readFile, readlink, unlink } from "node:fs/promises";
|
|
6
6
|
import { request } from "node:http";
|
|
7
|
+
import { createConnection, createServer } from "node:net";
|
|
7
8
|
import path from "node:path";
|
|
8
9
|
import { promisify } from "node:util";
|
|
9
10
|
import { userInfo } from "node:os";
|
|
@@ -25,9 +26,13 @@ import { briefId } from "./launch-brief.js";
|
|
|
25
26
|
* running as root (euid 0, which no process of the owner's can fake), and the
|
|
26
27
|
* asker's stdout is a pipe no other process of the owner's reads. The
|
|
27
28
|
* connection is bound to that process too: on macOS its other end must be
|
|
28
|
-
* held by the asker alone
|
|
29
|
-
*
|
|
30
|
-
*
|
|
29
|
+
* held by the asker alone. On Linux, where no unprivileged process can see a
|
|
30
|
+
* socket's peer, askpass listens on a fresh abstract socket and names it in
|
|
31
|
+
* its request; the listener must be held by the asker alone, and the Hook
|
|
32
|
+
* hands the password to that listener (with a one-time nonce askpass chose),
|
|
33
|
+
* which prints it to its own stdout. So a connection that names another
|
|
34
|
+
* process's pid gets nothing. (sudo creates askpass's stdout pipe as root,
|
|
35
|
+
* 0600, so the Hook cannot open `/proc/<pid>/fd/1` there.) It reads
|
|
31
36
|
* that sudo's command line itself and pushes the request to the phone; `GET /v1/sudo` and the overview socket's `sudo` frame
|
|
32
37
|
* list it. `POST /v1/sudo/answer` writes the password into the held
|
|
33
38
|
* connection and forgets the request: the password is never logged, stored,
|
|
@@ -145,6 +150,33 @@ export async function readProcess(pid) {
|
|
|
145
150
|
return undefined;
|
|
146
151
|
}
|
|
147
152
|
}
|
|
153
|
+
/** Linux: whether any process of the owner's other than `exclude` holds a
|
|
154
|
+
* descriptor that links to `target` (`pipe:[n]`, `socket:[n]`). */
|
|
155
|
+
async function heldElsewhere(target, exclude) {
|
|
156
|
+
const holders = (await readdir("/proc")).map(Number).filter(holder => Number.isInteger(holder) && !exclude.includes(holder));
|
|
157
|
+
let next = 0, other = false;
|
|
158
|
+
// Busy machines can have thousands of descriptors. Bound the process
|
|
159
|
+
// concurrency while checking every visible descriptor of each holder.
|
|
160
|
+
await Promise.all(Array.from({ length: Math.min(16, holders.length) }, async () => {
|
|
161
|
+
while (!other && next < holders.length) {
|
|
162
|
+
const holder = holders[next++];
|
|
163
|
+
const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
|
|
164
|
+
// procfs links are kernel metadata, without disk I/O. Reading a
|
|
165
|
+
// holder's links directly avoids thousands of thread-pool jobs;
|
|
166
|
+
// the directory awaits above still yield between holders.
|
|
167
|
+
for (const fd of fds) {
|
|
168
|
+
try {
|
|
169
|
+
if (readlinkSync(`/proc/${holder}/fd/${fd}`) === target) {
|
|
170
|
+
other = true;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
catch { /* The descriptor closed or its process exited. */ }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}));
|
|
178
|
+
return other;
|
|
179
|
+
}
|
|
148
180
|
/** Whether `pid`'s stdout is a pipe that no process of the owner's other than
|
|
149
181
|
* `allowed` holds. sudo, running as root, is never visible here. */
|
|
150
182
|
export async function stdoutReaders(pid, allowed) {
|
|
@@ -153,30 +185,7 @@ export async function stdoutReaders(pid, allowed) {
|
|
|
153
185
|
const target = await readlink(`/proc/${pid}/fd/1`);
|
|
154
186
|
if (!/^pipe:\[\d+\]$/.test(target))
|
|
155
187
|
return "other";
|
|
156
|
-
|
|
157
|
-
.filter(holder => Number.isInteger(holder) && holder !== pid && !allowed.includes(holder));
|
|
158
|
-
let next = 0, other = false;
|
|
159
|
-
// Busy machines can have thousands of descriptors. Bound the process
|
|
160
|
-
// concurrency while checking every visible descriptor of each holder.
|
|
161
|
-
await Promise.all(Array.from({ length: Math.min(16, holders.length) }, async () => {
|
|
162
|
-
while (!other && next < holders.length) {
|
|
163
|
-
const holder = holders[next++];
|
|
164
|
-
const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
|
|
165
|
-
// procfs links are kernel metadata, without disk I/O. Reading a
|
|
166
|
-
// holder's links directly avoids thousands of thread-pool jobs;
|
|
167
|
-
// the directory awaits above still yield between holders.
|
|
168
|
-
for (const fd of fds) {
|
|
169
|
-
try {
|
|
170
|
-
if (readlinkSync(`/proc/${holder}/fd/${fd}`) === target) {
|
|
171
|
-
other = true;
|
|
172
|
-
break;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
catch { /* The descriptor closed or its process exited. */ }
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}));
|
|
179
|
-
return other ? "other" : "sudo";
|
|
188
|
+
return await heldElsewhere(target, [pid, ...allowed]) ? "other" : "sudo";
|
|
180
189
|
}
|
|
181
190
|
// macOS: each pipe end has its own address, and `n->` names the other end.
|
|
182
191
|
const own = await exec("lsof", ["-nP", "-a", "-p", String(pid), "-d", "1", "-F", "tdn"], { timeout: 5_000, maxBuffer: 65_536 });
|
|
@@ -227,8 +236,81 @@ export async function processStart(pid) {
|
|
|
227
236
|
const stat = await readFile(`/proc/${pid}/stat`, "utf8").catch(() => undefined);
|
|
228
237
|
return stat?.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
229
238
|
}
|
|
230
|
-
|
|
231
|
-
|
|
239
|
+
const DELIVERY_SOCKET = /^phren-askpass-[0-9a-f]{32}$/, DELIVERY_NONCE = /^[0-9a-f]{64}$/;
|
|
240
|
+
export function deliveryFrom(value) {
|
|
241
|
+
const item = object(value);
|
|
242
|
+
return typeof item.socket === "string" && DELIVERY_SOCKET.test(item.socket) && typeof item.nonce === "string" && DELIVERY_NONCE.test(item.nonce)
|
|
243
|
+
? { socket: item.socket, nonce: item.nonce } : undefined;
|
|
244
|
+
}
|
|
245
|
+
export function newDelivery() {
|
|
246
|
+
return { socket: `phren-askpass-${randomBytes(16).toString("hex")}`, nonce: randomBytes(32).toString("hex") };
|
|
247
|
+
}
|
|
248
|
+
/** Linux: the inode of the listening abstract socket `name`, from
|
|
249
|
+
* `/proc/net/unix` (`Num RefCount Protocol Flags Type St Inode Path`; a
|
|
250
|
+
* listener has `__SO_ACCEPTCON`, 0x10000, in Flags). */
|
|
251
|
+
export async function listeningInode(name, table = () => readFile("/proc/net/unix", "utf8")) {
|
|
252
|
+
const text = await table().catch(() => "");
|
|
253
|
+
const found = text.split("\n").slice(1).map(row => row.trim().split(/\s+/))
|
|
254
|
+
.filter(cols => cols.length >= 8 && cols[7] === `@${name}` && (Number.parseInt(cols[3], 16) & 0x10000) !== 0 && /^\d+$/.test(cols[6]));
|
|
255
|
+
return found.length === 1 ? found[0][6] : undefined;
|
|
256
|
+
}
|
|
257
|
+
/** Linux: whether the listening socket `inode` is held by `pid` and no other
|
|
258
|
+
* process of the owner's. */
|
|
259
|
+
export async function listenerHolders(pid, inode) {
|
|
260
|
+
try {
|
|
261
|
+
const target = `socket:[${inode}]`;
|
|
262
|
+
const own = await readdir(`/proc/${pid}/fd`);
|
|
263
|
+
if (!own.some(fd => { try {
|
|
264
|
+
return readlinkSync(`/proc/${pid}/fd/${fd}`) === target;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return false;
|
|
268
|
+
} }))
|
|
269
|
+
return "other";
|
|
270
|
+
return await heldElsewhere(target, [pid]) ? "other" : "asker";
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return "unknown";
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** Linux: the password handed to askpass's own listener, if askpass is still
|
|
277
|
+
* the process that was verified and its listener is still the one checked.
|
|
278
|
+
* The check runs after connecting: a name is bound to one listener at a time,
|
|
279
|
+
* so while the asker still holds that listener, this connection reached it. */
|
|
280
|
+
export async function deliverToListener(pid, start, delivery, inode, password, checks = {}) {
|
|
281
|
+
const gone = { status: 410, error: "askpass went away." };
|
|
282
|
+
const socket = (checks.connect ?? (target => createConnection({ path: target })))(`\0${delivery.socket}`);
|
|
283
|
+
try {
|
|
284
|
+
await new Promise((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); setTimeout(() => reject(new Error("connect timeout")), 3_000).unref(); });
|
|
285
|
+
if (await (checks.start ?? processStart)(pid) !== start)
|
|
286
|
+
return gone;
|
|
287
|
+
if (await (checks.inode ?? listeningInode)(delivery.socket) !== inode)
|
|
288
|
+
return gone;
|
|
289
|
+
if (await (checks.holders ?? listenerHolders)(pid, inode) !== "asker")
|
|
290
|
+
return gone;
|
|
291
|
+
const ack = new Promise(resolve => {
|
|
292
|
+
let text = "";
|
|
293
|
+
socket.on("data", chunk => { text += chunk.toString(); if (text.includes("\n"))
|
|
294
|
+
resolve(text.startsWith("ok\n")); if (text.length > 64)
|
|
295
|
+
resolve(false); });
|
|
296
|
+
socket.once("close", () => resolve(false));
|
|
297
|
+
socket.once("error", () => resolve(false));
|
|
298
|
+
setTimeout(() => resolve(false), 5_000).unref();
|
|
299
|
+
});
|
|
300
|
+
socket.write(`${delivery.nonce}\n${password}\n`);
|
|
301
|
+
return await ack ? { delivered: true } : gone;
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return gone;
|
|
305
|
+
}
|
|
306
|
+
finally {
|
|
307
|
+
socket.destroy();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/** Linux, an askpass that names no delivery socket (one from before it did):
|
|
311
|
+
* the password written into the asker's stdout, the pipe verified to reach
|
|
312
|
+
* sudo alone. Works only where that pipe is the owner's, not sudo's root-owned
|
|
313
|
+
* one. */
|
|
232
314
|
async function writeToAsker(pid, start, password) {
|
|
233
315
|
if (await processStart(pid) !== start)
|
|
234
316
|
return { status: 410, error: "askpass went away." };
|
|
@@ -282,19 +364,24 @@ function placeFrom(value) {
|
|
|
282
364
|
return Object.fromEntries(fields.map(key => [key, item[key]]));
|
|
283
365
|
}
|
|
284
366
|
/** The chain check against this Hook's own node, bundle and script. */
|
|
285
|
-
async function defaultVerify(pid, hookFd) {
|
|
367
|
+
async function defaultVerify(pid, hookFd, delivery) {
|
|
286
368
|
const linux = process.platform === "linux";
|
|
287
369
|
const running = process.argv[1] ? [path.resolve(process.argv[1])] : [];
|
|
288
370
|
const start = linux ? await processStart(pid) : undefined;
|
|
371
|
+
const inode = linux && delivery ? await listeningInode(delivery.socket) : undefined;
|
|
289
372
|
const result = await verifyAsker(pid, { processes: readProcess, stdout: stdoutReaders, node: process.execPath, script: askpassPath(),
|
|
290
373
|
bundles: [...new Set([path.join(bridgeRoot(), "current/bridge-hook.mjs"), ...running])],
|
|
291
|
-
// On Linux the password goes to the asker's
|
|
292
|
-
|
|
374
|
+
// On Linux the password goes to the asker's own listener (or, for an
|
|
375
|
+
// askpass that names none, its stdout), not this connection.
|
|
376
|
+
connection: linux
|
|
377
|
+
? async (asker) => !start ? "unknown" : !delivery ? "asker" : !inode ? "other" : listenerHolders(asker, inode)
|
|
378
|
+
: asker => connectionHolders(asker, hookFd),
|
|
293
379
|
// The real-Hook tests stand a copy of bash named sudo in for sudo, which cannot run as root.
|
|
294
380
|
unprivilegedSudo: process.env.NODE_ENV === "test" && process.env.PHREN_SUDO_TEST_PARENT === "1" });
|
|
295
381
|
if ("refused" in result)
|
|
296
382
|
return result;
|
|
297
|
-
return { sudo: result.sudo, sudoPid: result.sudoPid, deliver: linux ?
|
|
383
|
+
return { sudo: result.sudo, sudoPid: result.sudoPid, deliver: !linux ? async (password) => ({ password })
|
|
384
|
+
: delivery && inode ? password => deliverToListener(pid, start, delivery, inode, password) : password => writeToAsker(pid, start, password) };
|
|
298
385
|
}
|
|
299
386
|
export class SudoBroker {
|
|
300
387
|
options;
|
|
@@ -323,7 +410,7 @@ export class SudoBroker {
|
|
|
323
410
|
* an answer, a timeout, or `cancel` (the caller went away). */
|
|
324
411
|
async ask(body, respond, hookFd) {
|
|
325
412
|
const none = { cancel: () => { } };
|
|
326
|
-
const verified = await (this.options.verify ?? defaultVerify)(Number(body.pid), hookFd);
|
|
413
|
+
const verified = await (this.options.verify ?? defaultVerify)(Number(body.pid), hookFd, deliveryFrom(body.delivery));
|
|
327
414
|
if ("refused" in verified) {
|
|
328
415
|
respond({ status: 400, error: verified.refused });
|
|
329
416
|
return none;
|
|
@@ -487,8 +574,63 @@ export class SudoAnswerError extends Error {
|
|
|
487
574
|
export async function askpass(prompt, env = process.env) {
|
|
488
575
|
const place = await terminalPaneFromEnv(env).catch(() => undefined);
|
|
489
576
|
const dispatchId = env.PHREN_DISPATCH_ID && briefId.safeParse(env.PHREN_DISPATCH_ID).success ? env.PHREN_DISPATCH_ID : undefined;
|
|
577
|
+
// Linux: listen for the password before asking, so the Hook can check
|
|
578
|
+
// that this process alone holds the listener.
|
|
579
|
+
const listener = process.platform === "linux" ? await deliveryListener().catch(() => undefined) : undefined;
|
|
580
|
+
if (process.platform === "linux" && !listener) {
|
|
581
|
+
process.stderr.write("phren askpass: could not open its delivery socket.\n");
|
|
582
|
+
return 1;
|
|
583
|
+
}
|
|
584
|
+
try {
|
|
585
|
+
return await ask(prompt, place, dispatchId, listener);
|
|
586
|
+
}
|
|
587
|
+
finally {
|
|
588
|
+
listener?.close();
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
/** An abstract socket that takes one password from a connection that sends
|
|
592
|
+
* the nonce first, prints it to stdout, and acknowledges. Any other
|
|
593
|
+
* connection is dropped without an answer. */
|
|
594
|
+
function deliveryListener() {
|
|
595
|
+
const delivery = newDelivery(), expected = Buffer.from(delivery.nonce);
|
|
596
|
+
let printed = false;
|
|
597
|
+
const server = createServer(socket => {
|
|
598
|
+
let text = "";
|
|
599
|
+
socket.setTimeout(10_000, () => socket.destroy());
|
|
600
|
+
socket.on("error", () => { });
|
|
601
|
+
socket.on("data", chunk => {
|
|
602
|
+
if (printed) {
|
|
603
|
+
socket.destroy();
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
text += chunk.toString();
|
|
607
|
+
if (text.length > 2_200) {
|
|
608
|
+
socket.destroy();
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const lines = text.split("\n");
|
|
612
|
+
if (lines.length < 3)
|
|
613
|
+
return;
|
|
614
|
+
const nonce = Buffer.from(lines[0]);
|
|
615
|
+
if (nonce.length !== expected.length || !timingSafeEqual(nonce, expected) || !lines[1]) {
|
|
616
|
+
socket.destroy();
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
printed = true;
|
|
620
|
+
process.stdout.write(`${lines[1]}\n`);
|
|
621
|
+
text = "";
|
|
622
|
+
socket.end("ok\n");
|
|
623
|
+
server.close();
|
|
624
|
+
});
|
|
625
|
+
});
|
|
626
|
+
return new Promise((resolve, reject) => {
|
|
627
|
+
server.once("error", reject);
|
|
628
|
+
server.listen({ path: `\0${delivery.socket}` }, () => resolve({ delivery, printed: () => printed, close: () => server.close() }));
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
async function ask(prompt, place, dispatchId, listener) {
|
|
490
632
|
const data = JSON.stringify({ pid: process.pid, cwd: process.cwd(), ...(prompt ? { prompt: prompt.slice(0, 200) } : {}),
|
|
491
|
-
...(place ? { place } : {}), ...(dispatchId ? { dispatchId } : {}) });
|
|
633
|
+
...(place ? { place } : {}), ...(dispatchId ? { dispatchId } : {}), ...(listener ? { delivery: listener.delivery } : {}) });
|
|
492
634
|
const reply = await new Promise(resolve => {
|
|
493
635
|
const req = request({ socketPath: localSocket(), path: "/sudo", method: "POST", timeout: SUDO_HOLD_MS + 15_000,
|
|
494
636
|
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
|
|
@@ -510,7 +652,8 @@ export async function askpass(prompt, env = process.env) {
|
|
|
510
652
|
process.stdout.write(`${reply.body.password}\n`);
|
|
511
653
|
return 0;
|
|
512
654
|
}
|
|
513
|
-
// Linux: the Hook
|
|
655
|
+
// Linux: the Hook handed it to the listener, which printed it (or, an
|
|
656
|
+
// older Hook, wrote it into this process's stdout itself).
|
|
514
657
|
if (reply.status === 200 && reply.body.delivered === true)
|
|
515
658
|
return 0;
|
|
516
659
|
process.stderr.write(`phren askpass: ${typeof reply.body.error === "string" ? reply.body.error : "sudo was not approved."}\n`);
|
package/dist/bridge/usage.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
+
import { accountWindows } from "./account-choice.js";
|
|
2
3
|
import { type AccountRef, type ClaudeHome } from "./claude-accounts.js";
|
|
3
4
|
import { type Subscription } from "./subscription.js";
|
|
4
5
|
export type { Subscription } from "./subscription.js";
|
|
@@ -137,14 +138,15 @@ export declare function windowExhausted(window: UsageWindow, now: number): boole
|
|
|
137
138
|
/** Percent left on a window at `now`: none once its reset passed or with no percent, 0 while the service refuses requests. */
|
|
138
139
|
export declare function windowLeft(window: UsageWindow, now: number): number | undefined;
|
|
139
140
|
/** What a capacity probe says about room: each Codex and Claude account's least room left, and whether it has none
|
|
140
|
-
* (`exhausted`, with `until` the last reset that frees it).
|
|
141
|
+
* (`exhausted`, with `until` the last reset that frees it). Claude rows add their 5-hour and weekly rooms, which
|
|
142
|
+
* launch and failover rank accounts by (account-choice.ts). */
|
|
141
143
|
export declare function capacityRoom(accounts: readonly AccountUsage[], now: number): Array<{
|
|
142
144
|
source: string;
|
|
143
145
|
account?: string;
|
|
144
146
|
leftPercent?: number;
|
|
145
147
|
exhausted?: true;
|
|
146
148
|
until?: string;
|
|
147
|
-
}
|
|
149
|
+
} & ReturnType<typeof accountWindows>>;
|
|
148
150
|
/** A Claude report older than this says nothing about the account now. */
|
|
149
151
|
export declare const CLAUDE_REPORT_MAX_AGE_MS: number;
|
|
150
152
|
/**
|
package/dist/bridge/usage.js
CHANGED
|
@@ -11,6 +11,7 @@ import { stripTerminal } from "../terminal-text.js";
|
|
|
11
11
|
import { codexExecutable } from "./codex-binary.js";
|
|
12
12
|
import { readSpeechKey } from "./speech-key.js";
|
|
13
13
|
import { resolveSpeechRegion, SPEECH_REGIONS } from "./speech-voice.js";
|
|
14
|
+
import { accountWindows } from "./account-choice.js";
|
|
14
15
|
import { CODEX_ACCOUNT, claudeAccountSubscription, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
|
|
15
16
|
import { planName, subscriptionDate } from "./subscription.js";
|
|
16
17
|
const exec = promisify(execFile);
|
|
@@ -691,14 +692,15 @@ export function windowLeft(window, now) {
|
|
|
691
692
|
return typeof window.usedPercent === "number" ? Math.max(0, Math.min(100, Math.round(100 - window.usedPercent))) : undefined;
|
|
692
693
|
}
|
|
693
694
|
/** What a capacity probe says about room: each Codex and Claude account's least room left, and whether it has none
|
|
694
|
-
* (`exhausted`, with `until` the last reset that frees it).
|
|
695
|
+
* (`exhausted`, with `until` the last reset that frees it). Claude rows add their 5-hour and weekly rooms, which
|
|
696
|
+
* launch and failover rank accounts by (account-choice.ts). */
|
|
695
697
|
export function capacityRoom(accounts, now) {
|
|
696
698
|
return accounts.map(usage => {
|
|
697
699
|
const left = usage.windows.map(window => windowLeft(window, now)).filter((value) => value !== undefined);
|
|
698
700
|
const out = usage.windows.filter(window => windowExhausted(window, now));
|
|
699
701
|
const until = out.map(window => window.resetsAt).filter((value) => Boolean(value)).sort().at(-1);
|
|
700
702
|
return { source: usage.source, ...(usage.account?.id ? { account: usage.account.id } : {}), ...(left.length ? { leftPercent: Math.min(...left) } : {}),
|
|
701
|
-
...(out.length ? { exhausted: true, ...(until ? { until } : {}) } : {}) };
|
|
703
|
+
...(out.length ? { exhausted: true, ...(until ? { until } : {}) } : {}), ...(usage.source === "claude" ? accountWindows(usage, now) : {}) };
|
|
702
704
|
});
|
|
703
705
|
}
|
|
704
706
|
/** A Claude report older than this says nothing about the account now. */
|
|
@@ -3,7 +3,14 @@ import type { TurnRecord } from "./turn-records.js";
|
|
|
3
3
|
import { type Integrator, type PullRequest } from "./return-contract.js";
|
|
4
4
|
export { integratorSchema, prsSchema, pullRequestSchema } from "./return-contract.js";
|
|
5
5
|
/** The worker reports PR evidence to its own Hook, without direct messaging or
|
|
6
|
-
* GitHub comments. Bound to this terminal and submitted turn, not the next one.
|
|
6
|
+
* GitHub comments. Bound to this terminal and submitted turn, not the next one.
|
|
7
|
+
*
|
|
8
|
+
* The pane's turn record can miss that turn: a nested agent run in the
|
|
9
|
+
* worker's own pane (`claude -p` from its shell) inherits the pane's
|
|
10
|
+
* variables, and its hooks replace the record with its own conversation. A
|
|
11
|
+
* worker whose dispatch this Hook saw arrive in this pane and conversation
|
|
12
|
+
* still reports; the evidence binds to its current turn, the one the next
|
|
13
|
+
* Stop ends, and never to a prompt submitted after the report. */
|
|
7
14
|
export declare function reportWorker(input: unknown): Promise<Json>;
|
|
8
15
|
export declare function workerPrs(target: Target, record: TurnRecord): Promise<PullRequest[] | undefined>;
|
|
9
16
|
export declare function readIntegrator(): Promise<Integrator | undefined>;
|
|
@@ -6,15 +6,24 @@ import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema } from "./pro
|
|
|
6
6
|
import { paneIdentity, findPane, snapshot, validateTarget } from "./herdr.js";
|
|
7
7
|
import { originPaneSchema } from "./dispatch.js";
|
|
8
8
|
import { paneTurn } from "./dispatch-returns.js";
|
|
9
|
+
import { briefArrival, briefId } from "./launch-brief.js";
|
|
9
10
|
import { integratorSchema, prsSchema, reportText as text } from "./return-contract.js";
|
|
10
11
|
export { integratorSchema, prsSchema, pullRequestSchema } from "./return-contract.js";
|
|
11
|
-
|
|
12
|
+
// `promptSeq` is absent for a report bound by its dispatch instead of a recorded prompt (`reportWorker`).
|
|
13
|
+
const reportSchema = z.object({ target: targetSchema, terminal: text(200), promptSeq: z.number().int().optional(), prs: prsSchema, at: z.string().datetime() }).strict();
|
|
12
14
|
const key = (target) => createHash("sha256").update(JSON.stringify([target.server, target.workspace, target.tab, target.pane, target.source, target.session])).digest("hex");
|
|
13
15
|
const reportFile = (target) => path.join(bridgeRoot(), "worker-reports", `${key(target)}.json`);
|
|
14
16
|
/** The worker reports PR evidence to its own Hook, without direct messaging or
|
|
15
|
-
* GitHub comments. Bound to this terminal and submitted turn, not the next one.
|
|
17
|
+
* GitHub comments. Bound to this terminal and submitted turn, not the next one.
|
|
18
|
+
*
|
|
19
|
+
* The pane's turn record can miss that turn: a nested agent run in the
|
|
20
|
+
* worker's own pane (`claude -p` from its shell) inherits the pane's
|
|
21
|
+
* variables, and its hooks replace the record with its own conversation. A
|
|
22
|
+
* worker whose dispatch this Hook saw arrive in this pane and conversation
|
|
23
|
+
* still reports; the evidence binds to its current turn, the one the next
|
|
24
|
+
* Stop ends, and never to a prompt submitted after the report. */
|
|
16
25
|
export async function reportWorker(input) {
|
|
17
|
-
const data = z.object({ origin: originPaneSchema, prs: prsSchema }).strict().parse(input);
|
|
26
|
+
const data = z.object({ origin: originPaneSchema, prs: prsSchema, dispatch: briefId.optional() }).strict().parse(input);
|
|
18
27
|
const pane = findPane(await snapshot(data.origin.server), data.origin);
|
|
19
28
|
if (!pane)
|
|
20
29
|
throw new BridgeError(409, "The worker pane changed.");
|
|
@@ -22,18 +31,30 @@ export async function reportWorker(input) {
|
|
|
22
31
|
const target = targetSchema.parse({ ...data.origin, source: pane.agent, session });
|
|
23
32
|
await validateTarget(target, false, true);
|
|
24
33
|
const record = await paneTurn(target.server, pane, target.source);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
34
|
+
const promptSeq = record?.prompt && record.session === session && record.terminal === pane.terminal_id ? record.prompt.seq : undefined;
|
|
35
|
+
if (promptSeq === undefined && !(typeof pane.terminal_id === "string" && await arrivedHere(data.dispatch ?? (record && record.session === session ? record.dispatch : undefined), target)))
|
|
36
|
+
throw new BridgeError(409, "The Hook has not recorded this worker's submitted turn yet, and no dispatch it launched arrived in this pane.");
|
|
37
|
+
await atomicInPrivateDir(reportFile(target), reportSchema.parse({ target, terminal: pane.terminal_id, ...(promptSeq !== undefined ? { promptSeq } : {}), prs: data.prs, at: new Date().toISOString() }));
|
|
28
38
|
return { ok: true, target, prs: data.prs };
|
|
29
39
|
}
|
|
40
|
+
/** Whether this Hook launched dispatch `id` and its brief arrived in exactly this pane and conversation. */
|
|
41
|
+
async function arrivedHere(id, target) {
|
|
42
|
+
if (!id)
|
|
43
|
+
return false;
|
|
44
|
+
const arrival = await briefArrival(id);
|
|
45
|
+
return [arrival?.accepted, arrival?.started].some(event => event && key(event.target) === key(target));
|
|
46
|
+
}
|
|
30
47
|
export async function workerPrs(target, record) {
|
|
31
48
|
try {
|
|
32
49
|
const file = reportFile(target), info = await lstat(file);
|
|
33
50
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 131072)
|
|
34
51
|
return undefined;
|
|
35
52
|
const report = reportSchema.parse(JSON.parse(await readFile(file, "utf8")));
|
|
36
|
-
|
|
53
|
+
if (report.terminal !== record.terminal)
|
|
54
|
+
return undefined;
|
|
55
|
+
if (report.promptSeq !== undefined)
|
|
56
|
+
return report.promptSeq === record.prompt?.seq ? report.prs : undefined;
|
|
57
|
+
return !record.prompt || Date.parse(record.prompt.at) <= Date.parse(report.at) ? report.prs : undefined;
|
|
37
58
|
}
|
|
38
59
|
catch (error) {
|
|
39
60
|
if (error.code !== "ENOENT")
|