@phren/cli 0.3.12 → 0.3.13
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-usage.d.ts +124 -0
- package/dist/bridge/account-usage.js +258 -0
- package/dist/bridge/agent-hooks.d.ts +3 -0
- package/dist/bridge/agent-hooks.js +20 -1
- package/dist/bridge/codex-hook-trust.d.ts +27 -0
- package/dist/bridge/codex-hook-trust.js +237 -0
- package/dist/bridge/command.js +3 -0
- package/dist/bridge/dispatch-command.js +9 -3
- package/dist/bridge/dispatch-returns.d.ts +5 -0
- package/dist/bridge/dispatch-returns.js +16 -6
- package/dist/bridge/dispatch.d.ts +25 -1
- package/dist/bridge/dispatch.js +35 -6
- package/dist/bridge/hand-off-queue.d.ts +74 -0
- package/dist/bridge/hand-off-queue.js +235 -0
- package/dist/bridge/hand-off.d.ts +12 -4
- package/dist/bridge/hand-off.js +27 -7
- package/dist/bridge/install.js +16 -2
- package/dist/bridge/pane-status.d.ts +12 -0
- package/dist/bridge/pane-status.js +50 -1
- package/dist/bridge/push.d.ts +6 -0
- package/dist/bridge/push.js +21 -0
- package/dist/bridge/schedule-launch.d.ts +1 -1
- package/dist/bridge/schedule-launch.js +5 -1
- package/dist/bridge/schedule-watch.d.ts +15 -1
- package/dist/bridge/schedule-watch.js +45 -10
- package/dist/bridge/server-launch.js +14 -4
- package/dist/bridge/server-overview.d.ts +8 -1
- package/dist/bridge/server-overview.js +12 -3
- package/dist/bridge/server-pane-routes.d.ts +1 -0
- package/dist/bridge/server-pane-routes.js +9 -7
- package/dist/bridge/server-routes.d.ts +4 -0
- package/dist/bridge/server-routes.js +57 -7
- package/dist/bridge/server.js +15 -2
- package/dist/bridge/session-activity.d.ts +24 -12
- package/dist/bridge/session-activity.js +36 -14
- package/dist/bridge/stalls.d.ts +22 -0
- package/dist/bridge/stalls.js +57 -0
- package/dist/bridge/sudo.d.ts +209 -0
- package/dist/bridge/sudo.js +501 -0
- package/dist/bridge/terminal-tmux.d.ts +12 -0
- package/dist/bridge/terminal-tmux.js +79 -4
- package/dist/bridge/transcript-claude.d.ts +4 -0
- package/dist/bridge/transcript-claude.js +131 -6
- package/dist/bridge/usage.d.ts +17 -0
- package/dist/bridge/usage.js +37 -3
- package/dist/bridge-hook.mjs +19448 -18102
- package/dist/cli-registry.js +7 -1
- package/dist/modules/registry.js +8 -8
- package/dist/tools/dispatch.js +17 -2
- package/package.json +1 -1
- package/starter/global/AGENTS.md +4 -0
- package/starter/global/skills/conductor/SKILL.md +34 -2
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { type NotLinkedComputer } from "./hand-off.js";
|
|
2
|
+
import { type HookPeer } from "./peers.js";
|
|
3
|
+
import { type Json } from "./protocol.js";
|
|
4
|
+
import { NEAR_LIMIT_LEFT, type AccountUsage, type UsageWindow } from "./usage.js";
|
|
5
|
+
export { NEAR_LIMIT_LEFT };
|
|
6
|
+
/**
|
|
7
|
+
* Every computer's agent usage merged by account, for a conductor choosing
|
|
8
|
+
* where to send work: `account_usage` and `phren dispatch usage`. Read like
|
|
9
|
+
* `live_sessions`: this Hook, then each linked Hook over its pinned pipe, with
|
|
10
|
+
* unreachable and unlinked computers listed apart.
|
|
11
|
+
*
|
|
12
|
+
* The merge follows the phone's cards: one account is one allowance whichever
|
|
13
|
+
* computers report it, so the freshest whole report stands. Claude and Codex
|
|
14
|
+
* rows merge by their account key; a Claude login with no identity
|
|
15
|
+
* (`claude:home:<id>`) stays per computer, since two unknown logins are not
|
|
16
|
+
* one account. A window whose reset time has passed says `reset` and has no
|
|
17
|
+
* percent, and a report older than STALE_AFTER_MS is flagged stale.
|
|
18
|
+
*
|
|
19
|
+
* `nearLimit` is information: the owner often wants quota used before it
|
|
20
|
+
* resets. Only `exhausted` (a window at 100% or refusing requests) rules an
|
|
21
|
+
* account out.
|
|
22
|
+
*/
|
|
23
|
+
/** A report older than this is flagged: the Hook reads each account at most once a minute. */
|
|
24
|
+
export declare const STALE_AFTER_MS: number;
|
|
25
|
+
export interface AccountWindow {
|
|
26
|
+
id: string;
|
|
27
|
+
name: string;
|
|
28
|
+
usedPercent?: number;
|
|
29
|
+
leftPercent?: number;
|
|
30
|
+
resetsAt?: string;
|
|
31
|
+
resetsIn?: string;
|
|
32
|
+
/** Reset since its report: the allowance is back, but no new percent is known. */
|
|
33
|
+
reset?: true;
|
|
34
|
+
/** The service is refusing requests on this window now. */
|
|
35
|
+
limited?: true;
|
|
36
|
+
/** At 100% or refused: no quota on this window until it resets. */
|
|
37
|
+
exhausted?: true;
|
|
38
|
+
usedUSD?: number;
|
|
39
|
+
limitUSD?: number;
|
|
40
|
+
}
|
|
41
|
+
export interface AccountUsageRow {
|
|
42
|
+
/** `source` or `source|key`, as the phone keys its cards. */
|
|
43
|
+
id: string;
|
|
44
|
+
harness: string;
|
|
45
|
+
name: string;
|
|
46
|
+
/** The login's email, else the account's label, when the Hook names one. */
|
|
47
|
+
account?: string;
|
|
48
|
+
windows: AccountWindow[];
|
|
49
|
+
/** Least room on any window with a percent; `limited` counts as 0. */
|
|
50
|
+
leftPercent?: number;
|
|
51
|
+
/** Under 20% left on some window. Information, not a reason to avoid the account. */
|
|
52
|
+
nearLimit: boolean;
|
|
53
|
+
/** A window is at 100% or refusing requests: never dispatch to it until `availableIn`. */
|
|
54
|
+
exhausted: boolean;
|
|
55
|
+
/** When the last exhausted window resets, as "3h 10m". */
|
|
56
|
+
availableIn?: string;
|
|
57
|
+
spend?: {
|
|
58
|
+
amountUSD: number;
|
|
59
|
+
period: string;
|
|
60
|
+
};
|
|
61
|
+
updatedAt?: string;
|
|
62
|
+
/** How old the standing report is, as "4m" or "2d 3h". */
|
|
63
|
+
age?: string;
|
|
64
|
+
stale: boolean;
|
|
65
|
+
/** The computer whose report stands. */
|
|
66
|
+
from?: string;
|
|
67
|
+
/** Where it is signed in, with the Claude account id dispatch takes there. */
|
|
68
|
+
computers: Array<{
|
|
69
|
+
name: string;
|
|
70
|
+
account?: string;
|
|
71
|
+
}>;
|
|
72
|
+
message?: string;
|
|
73
|
+
}
|
|
74
|
+
export interface AccountUsageView {
|
|
75
|
+
accounts: AccountUsageRow[];
|
|
76
|
+
/** Harnesses no computer reported numbers for, with what each Hook said. */
|
|
77
|
+
noData: Array<{
|
|
78
|
+
harness: string;
|
|
79
|
+
name: string;
|
|
80
|
+
computers: string[];
|
|
81
|
+
message?: string;
|
|
82
|
+
}>;
|
|
83
|
+
/** The computers that answered, this one first. */
|
|
84
|
+
computers: string[];
|
|
85
|
+
unreachable: Array<{
|
|
86
|
+
computer: string;
|
|
87
|
+
error: string;
|
|
88
|
+
code?: string;
|
|
89
|
+
}>;
|
|
90
|
+
/** Registered in the store but not linked in hooks.yaml: their usage is unknown, not zero. */
|
|
91
|
+
notLinked: NotLinkedComputer[];
|
|
92
|
+
enrolled: number;
|
|
93
|
+
peerError?: string;
|
|
94
|
+
}
|
|
95
|
+
export interface ComputerUsage {
|
|
96
|
+
computer: string;
|
|
97
|
+
accounts: AccountUsage[];
|
|
98
|
+
}
|
|
99
|
+
export declare function ageText(ms: number): string;
|
|
100
|
+
/** The phone's card key, except that a Claude login with no identity stays on its own computer. */
|
|
101
|
+
export declare function accountIdentity(usage: AccountUsage, computer: string): string;
|
|
102
|
+
/** Percent used and left, with a passed reset reported as reset rather than as its old percent. */
|
|
103
|
+
export declare function settleWindow(window: UsageWindow, now: number): AccountWindow;
|
|
104
|
+
/** Least room across an account's windows, undefined when none has a percent. */
|
|
105
|
+
export declare function roomLeft(windows: readonly AccountWindow[]): number | undefined;
|
|
106
|
+
/** One row per account across every computer's report. */
|
|
107
|
+
export declare function mergeAccountUsage(reports: readonly ComputerUsage[], now?: number): Pick<AccountUsageView, "accounts" | "noData">;
|
|
108
|
+
export interface ReadAccountUsageOptions {
|
|
109
|
+
/** This computer's Hook; tests pass the fixture's socket. */
|
|
110
|
+
hook?: (route: string) => Promise<Json>;
|
|
111
|
+
peers?: () => Promise<{
|
|
112
|
+
peers: HookPeer[];
|
|
113
|
+
peerError?: string;
|
|
114
|
+
}>;
|
|
115
|
+
peer?: (peer: HookPeer, route: string) => Promise<Json>;
|
|
116
|
+
store?: string | null;
|
|
117
|
+
now?: number;
|
|
118
|
+
}
|
|
119
|
+
/** This Hook's usage and every linked Hook's, merged by account. */
|
|
120
|
+
export declare function readAccountUsage(options?: ReadAccountUsageOptions): Promise<AccountUsageView>;
|
|
121
|
+
/** The one-line answer a conductor reads first: how many, and which accounts are tight or stale. */
|
|
122
|
+
export declare function usageSummary(view: AccountUsageView): string;
|
|
123
|
+
/** `phren dispatch usage` without --json. */
|
|
124
|
+
export declare function formatAccountUsage(view: AccountUsageView): string;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { findPhrenPath } from "../phren-paths.js";
|
|
2
|
+
import { HARNESS_NAMES, resetsIn, USAGE_SOURCES } from "../computers/read.js";
|
|
3
|
+
import { hookRequest } from "./client.js";
|
|
4
|
+
import { notLinkedFrom } from "./hand-off.js";
|
|
5
|
+
import { optionalHookPeers, peerRequest } from "./peers.js";
|
|
6
|
+
import { errorCode, object } from "./protocol.js";
|
|
7
|
+
import { NEAR_LIMIT_LEFT, windowExhausted, windowLeft } from "./usage.js";
|
|
8
|
+
export { NEAR_LIMIT_LEFT };
|
|
9
|
+
/**
|
|
10
|
+
* Every computer's agent usage merged by account, for a conductor choosing
|
|
11
|
+
* where to send work: `account_usage` and `phren dispatch usage`. Read like
|
|
12
|
+
* `live_sessions`: this Hook, then each linked Hook over its pinned pipe, with
|
|
13
|
+
* unreachable and unlinked computers listed apart.
|
|
14
|
+
*
|
|
15
|
+
* The merge follows the phone's cards: one account is one allowance whichever
|
|
16
|
+
* computers report it, so the freshest whole report stands. Claude and Codex
|
|
17
|
+
* rows merge by their account key; a Claude login with no identity
|
|
18
|
+
* (`claude:home:<id>`) stays per computer, since two unknown logins are not
|
|
19
|
+
* one account. A window whose reset time has passed says `reset` and has no
|
|
20
|
+
* percent, and a report older than STALE_AFTER_MS is flagged stale.
|
|
21
|
+
*
|
|
22
|
+
* `nearLimit` is information: the owner often wants quota used before it
|
|
23
|
+
* resets. Only `exhausted` (a window at 100% or refusing requests) rules an
|
|
24
|
+
* account out.
|
|
25
|
+
*/
|
|
26
|
+
/** A report older than this is flagged: the Hook reads each account at most once a minute. */
|
|
27
|
+
export const STALE_AFTER_MS = 15 * 60_000;
|
|
28
|
+
/** ElevenLabs is left out: every read of it spends a request against its key's quota. */
|
|
29
|
+
const SOURCES = USAGE_SOURCES.join(",");
|
|
30
|
+
const USAGE_ROUTE = `/v1/usage?${new URLSearchParams({ sources: SOURCES, goPlan: "1", accounts: "all" })}`;
|
|
31
|
+
const date = (value) => value ? Date.parse(value) : NaN;
|
|
32
|
+
const hasData = (usage) => usage.windows.length > 0 || Boolean(usage.spend);
|
|
33
|
+
const newer = (a, b) => (date(b.usage.updatedAt) || 0) > (date(a.usage.updatedAt) || 0) ? b : a;
|
|
34
|
+
export function ageText(ms) {
|
|
35
|
+
const minutes = Math.max(0, Math.round(ms / 60_000));
|
|
36
|
+
const days = Math.floor(minutes / 1440), hours = Math.floor(minutes % 1440 / 60);
|
|
37
|
+
return days ? `${days}d ${hours}h` : hours ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
|
|
38
|
+
}
|
|
39
|
+
/** The phone's card key, except that a Claude login with no identity stays on its own computer. */
|
|
40
|
+
export function accountIdentity(usage, computer) {
|
|
41
|
+
const key = usage.account?.key;
|
|
42
|
+
if (!key || key === usage.source)
|
|
43
|
+
return usage.source;
|
|
44
|
+
return key.startsWith(`${usage.source}:home:`) ? `${usage.source}|${key}@${computer}` : `${usage.source}|${key}`;
|
|
45
|
+
}
|
|
46
|
+
/** Percent used and left, with a passed reset reported as reset rather than as its old percent. */
|
|
47
|
+
export function settleWindow(window, now) {
|
|
48
|
+
const out = { id: window.id, name: window.name };
|
|
49
|
+
const resetAt = date(window.resetsAt);
|
|
50
|
+
const reset = window.reset === true || Number.isFinite(resetAt) && resetAt <= now;
|
|
51
|
+
const left = windowLeft(window, now);
|
|
52
|
+
if (reset)
|
|
53
|
+
out.reset = true;
|
|
54
|
+
else if (typeof window.usedPercent === "number")
|
|
55
|
+
out.usedPercent = window.usedPercent;
|
|
56
|
+
if (left !== undefined)
|
|
57
|
+
out.leftPercent = left;
|
|
58
|
+
if (window.resetsAt && !reset) {
|
|
59
|
+
out.resetsAt = window.resetsAt;
|
|
60
|
+
const until = resetsIn(window.resetsAt, now);
|
|
61
|
+
if (until)
|
|
62
|
+
out.resetsIn = until;
|
|
63
|
+
}
|
|
64
|
+
if (window.limited && !reset)
|
|
65
|
+
out.limited = true;
|
|
66
|
+
if (windowExhausted(window, now))
|
|
67
|
+
out.exhausted = true;
|
|
68
|
+
if (window.usedUSD !== undefined)
|
|
69
|
+
out.usedUSD = window.usedUSD;
|
|
70
|
+
if (window.limitUSD !== undefined)
|
|
71
|
+
out.limitUSD = window.limitUSD;
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
/** Least room across an account's windows, undefined when none has a percent. */
|
|
75
|
+
export function roomLeft(windows) {
|
|
76
|
+
const known = windows.map(w => w.leftPercent).filter((value) => value !== undefined);
|
|
77
|
+
return known.length ? Math.min(...known) : undefined;
|
|
78
|
+
}
|
|
79
|
+
function accountName(usage) {
|
|
80
|
+
const named = usage.accountName;
|
|
81
|
+
const label = usage.account?.label;
|
|
82
|
+
return usage.account?.email ?? (typeof named === "string" && named ? named : undefined)
|
|
83
|
+
?? (label && label.toLowerCase() !== (HARNESS_NAMES[usage.source] ?? usage.source).toLowerCase() ? label : undefined);
|
|
84
|
+
}
|
|
85
|
+
/** One row per account across every computer's report. */
|
|
86
|
+
export function mergeAccountUsage(reports, now = Date.now()) {
|
|
87
|
+
const groups = new Map();
|
|
88
|
+
for (const report of reports)
|
|
89
|
+
for (const usage of report.accounts) {
|
|
90
|
+
const id = accountIdentity(usage, report.computer);
|
|
91
|
+
groups.set(id, [...groups.get(id) ?? [], { computer: report.computer, usage }]);
|
|
92
|
+
}
|
|
93
|
+
const accounts = [];
|
|
94
|
+
const empty = new Map();
|
|
95
|
+
for (const [id, group] of groups) {
|
|
96
|
+
const reporting = group.filter(item => hasData(item.usage));
|
|
97
|
+
if (!reporting.length) {
|
|
98
|
+
const entry = empty.get(group[0].usage.source) ?? { computers: [], messages: [] };
|
|
99
|
+
for (const item of group) {
|
|
100
|
+
if (!entry.computers.includes(item.computer))
|
|
101
|
+
entry.computers.push(item.computer);
|
|
102
|
+
if (item.usage.message && !entry.messages.includes(item.usage.message))
|
|
103
|
+
entry.messages.push(item.usage.message);
|
|
104
|
+
}
|
|
105
|
+
empty.set(group[0].usage.source, entry);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const source = group[0].usage.source;
|
|
109
|
+
// One allowance: the freshest report with windows stands whole, never mixed with another read.
|
|
110
|
+
const withWindows = reporting.filter(item => item.usage.windows.length);
|
|
111
|
+
const standing = (withWindows.length ? withWindows : reporting).reduce(newer);
|
|
112
|
+
const windows = standing.usage.windows.map(window => settleWindow(window, now));
|
|
113
|
+
const spend = mergedSpend(source, reporting);
|
|
114
|
+
const updated = date(standing.usage.updatedAt);
|
|
115
|
+
const leftPercent = roomLeft(windows);
|
|
116
|
+
const exhausted = windows.filter(w => w.exhausted);
|
|
117
|
+
const availableAt = exhausted.map(w => w.resetsAt).filter((value) => Boolean(value)).sort().at(-1);
|
|
118
|
+
const availableIn = availableAt ? resetsIn(availableAt, now) : undefined;
|
|
119
|
+
const name = accountName(standing.usage);
|
|
120
|
+
const computers = reporting.map(item => ({ name: item.computer, ...(source === "claude" && item.usage.account?.id ? { account: item.usage.account.id } : {}) }))
|
|
121
|
+
.filter((item, index, list) => list.findIndex(other => other.name === item.name && other.account === item.account) === index);
|
|
122
|
+
accounts.push({
|
|
123
|
+
id, harness: source, name: HARNESS_NAMES[source] ?? source, ...(name ? { account: name } : {}), windows,
|
|
124
|
+
...(leftPercent !== undefined ? { leftPercent } : {}),
|
|
125
|
+
nearLimit: windows.some(w => w.limited) || leftPercent !== undefined && leftPercent < NEAR_LIMIT_LEFT,
|
|
126
|
+
exhausted: exhausted.length > 0, ...(availableIn ? { availableIn } : {}),
|
|
127
|
+
...(spend ? { spend } : {}),
|
|
128
|
+
...(standing.usage.updatedAt ? { updatedAt: standing.usage.updatedAt } : {}),
|
|
129
|
+
...(Number.isFinite(updated) ? { age: ageText(now - updated) } : {}),
|
|
130
|
+
stale: !Number.isFinite(updated) || now - updated > STALE_AFTER_MS || windows.some(w => w.reset),
|
|
131
|
+
from: standing.computer, computers,
|
|
132
|
+
...(standing.usage.message ? { message: standing.usage.message } : {}),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const order = (source) => { const at = USAGE_SOURCES.indexOf(source); return at < 0 ? USAGE_SOURCES.length : at; };
|
|
136
|
+
accounts.sort((a, b) => order(a.harness) - order(b.harness) || (a.account ?? "").localeCompare(b.account ?? "") || a.id.localeCompare(b.id));
|
|
137
|
+
const noData = [...empty].filter(([source]) => !accounts.some(row => row.harness === source))
|
|
138
|
+
.map(([source, entry]) => ({ harness: source, name: HARNESS_NAMES[source] ?? source, computers: entry.computers, ...(entry.messages[0] ? { message: entry.messages[0] } : {}) }))
|
|
139
|
+
.sort((a, b) => order(a.harness) - order(b.harness));
|
|
140
|
+
return { accounts, noData };
|
|
141
|
+
}
|
|
142
|
+
/** OpenCode's ledgers are per computer and add up; OpenRouter is one key seen from several, counted once per key. */
|
|
143
|
+
function mergedSpend(source, reporting) {
|
|
144
|
+
const spends = reporting.filter(item => item.usage.spend);
|
|
145
|
+
if (!spends.length)
|
|
146
|
+
return undefined;
|
|
147
|
+
const round = (value) => Math.round(value * 100) / 100;
|
|
148
|
+
if (source === "opencode" || source === "opencode-go") {
|
|
149
|
+
return { amountUSD: round(spends.reduce((sum, item) => sum + item.usage.spend.amountUSD, 0)), period: spends[0].usage.spend.period };
|
|
150
|
+
}
|
|
151
|
+
if (source === "openrouter") {
|
|
152
|
+
const byKey = new Map();
|
|
153
|
+
for (const item of spends) {
|
|
154
|
+
const key = item.usage.accountId ?? `computer:${item.computer}`;
|
|
155
|
+
const seen = byKey.get(key);
|
|
156
|
+
byKey.set(key, seen ? newer(seen, item) : item);
|
|
157
|
+
}
|
|
158
|
+
return { amountUSD: round([...byKey.values()].reduce((sum, item) => sum + item.usage.spend.amountUSD, 0)), period: spends[0].usage.spend.period };
|
|
159
|
+
}
|
|
160
|
+
return spends.reduce(newer).usage.spend;
|
|
161
|
+
}
|
|
162
|
+
/** This Hook's usage and every linked Hook's, merged by account. */
|
|
163
|
+
export async function readAccountUsage(options = {}) {
|
|
164
|
+
const hook = options.hook ?? (route => hookRequest(route, undefined, undefined, 30_000));
|
|
165
|
+
const ask = options.peer ?? ((peer, route) => peerRequest(peer, route, undefined, 20_000));
|
|
166
|
+
const [health, local, linked] = await Promise.all([hook("/v1/health"), hook(USAGE_ROUTE), (options.peers ?? optionalHookPeers)()]);
|
|
167
|
+
const here = typeof object(health.computer).name === "string" ? String(object(health.computer).name) : "this computer";
|
|
168
|
+
const reports = [{ computer: here, accounts: accountsOf(local) }];
|
|
169
|
+
const unreachable = [];
|
|
170
|
+
const peerNames = new Map();
|
|
171
|
+
await Promise.all(linked.peers.map(async (peer) => {
|
|
172
|
+
try {
|
|
173
|
+
const [usage, peerHealth] = await Promise.all([ask(peer, USAGE_ROUTE), ask(peer, "/v1/health").catch(() => ({}))]);
|
|
174
|
+
reports.push({ computer: peer.name, accounts: accountsOf(usage) });
|
|
175
|
+
const computer = object(object(peerHealth).computer);
|
|
176
|
+
peerNames.set(peer.name, [computer.name, ...(Array.isArray(computer.aliases) ? computer.aliases : [])].filter((name) => typeof name === "string"));
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
const code = errorCode(error);
|
|
180
|
+
unreachable.push({ computer: peer.name, error: error instanceof Error ? error.message.slice(0, 300) : "Unreachable.", ...(code ? { code } : {}) });
|
|
181
|
+
}
|
|
182
|
+
}));
|
|
183
|
+
// Peers answer in any order; this computer first, then by name, so the standing report never depends on timing.
|
|
184
|
+
reports.sort((a, b) => a.computer === here ? -1 : b.computer === here ? 1 : a.computer.localeCompare(b.computer));
|
|
185
|
+
unreachable.sort((a, b) => a.computer.localeCompare(b.computer));
|
|
186
|
+
const store = options.store !== undefined ? options.store : findPhrenPath();
|
|
187
|
+
const notLinked = notLinkedFrom(store, here, linked.peers.map(peer => ({ name: peer.name, address: peer.address, names: peerNames.get(peer.name) })));
|
|
188
|
+
return { ...mergeAccountUsage(reports, options.now ?? Date.now()), computers: reports.map(report => report.computer), unreachable, notLinked,
|
|
189
|
+
enrolled: linked.peers.length, ...(linked.peerError ? { peerError: linked.peerError } : {}) };
|
|
190
|
+
}
|
|
191
|
+
function accountsOf(answer) {
|
|
192
|
+
return Array.isArray(answer.accounts) ? answer.accounts.filter((item) => {
|
|
193
|
+
const row = object(item);
|
|
194
|
+
return typeof row.source === "string" && Array.isArray(row.windows);
|
|
195
|
+
}) : [];
|
|
196
|
+
}
|
|
197
|
+
const ago = (age) => age === "0m" ? "just now" : `${age} ago`;
|
|
198
|
+
const title = (row) => row.account ? `${row.name} · ${row.account}` : row.name;
|
|
199
|
+
/** The one-line answer a conductor reads first: how many, and which accounts are tight or stale. */
|
|
200
|
+
export function usageSummary(view) {
|
|
201
|
+
const parts = [`${view.accounts.length} account${view.accounts.length === 1 ? "" : "s"} across ${view.computers.length} computer${view.computers.length === 1 ? "" : "s"}.`];
|
|
202
|
+
const out = view.accounts.filter(row => row.exhausted);
|
|
203
|
+
if (out.length)
|
|
204
|
+
parts.push(`Out of quota, do not dispatch to: ${out.map(row => `${title(row)}${row.availableIn ? ` (back in ${row.availableIn})` : ""}`).join("; ")}.`);
|
|
205
|
+
const near = view.accounts.filter(row => row.nearLimit && !row.exhausted);
|
|
206
|
+
if (near.length)
|
|
207
|
+
parts.push(`Low but usable: ${near.map(row => `${title(row)} (${row.leftPercent ?? 0}% left${tightest(row)?.resetsIn ? `, resets in ${tightest(row).resetsIn}` : ""})`).join("; ")}.`);
|
|
208
|
+
const limitedRows = view.accounts.filter(row => row.leftPercent !== undefined || row.exhausted);
|
|
209
|
+
if (limitedRows.length && limitedRows.every(row => row.exhausted))
|
|
210
|
+
parts.push("Every account with limits is out of quota: tell the owner before dispatching.");
|
|
211
|
+
const stale = view.accounts.filter(row => row.stale);
|
|
212
|
+
if (stale.length)
|
|
213
|
+
parts.push(`Stale: ${stale.map(row => `${title(row)} (${row.windows.some(w => w.reset) ? "a window reset since its report" : `reported ${row.age ? ago(row.age) : "at an unknown time"}`})`).join("; ")}.`);
|
|
214
|
+
if (view.unreachable.length)
|
|
215
|
+
parts.push(`Unreachable: ${view.unreachable.map(item => item.computer).join(", ")}.`);
|
|
216
|
+
if (view.notLinked.length)
|
|
217
|
+
parts.push(`Not linked, so not checked: ${view.notLinked.map(item => item.name).join(", ")}.`);
|
|
218
|
+
return parts.join(" ");
|
|
219
|
+
}
|
|
220
|
+
function tightest(row) {
|
|
221
|
+
return row.windows.filter(w => w.leftPercent !== undefined).sort((a, b) => a.leftPercent - b.leftPercent)[0];
|
|
222
|
+
}
|
|
223
|
+
/** `phren dispatch usage` without --json. */
|
|
224
|
+
export function formatAccountUsage(view) {
|
|
225
|
+
const lines = [`Usage by account from ${view.computers.join(", ")}`];
|
|
226
|
+
for (const row of view.accounts) {
|
|
227
|
+
const where = row.computers.map(c => c.account && c.account !== "default" ? `${c.name} (${c.account})` : c.name).join(", ");
|
|
228
|
+
const flags = [row.exhausted ? `out of quota${row.availableIn ? `, back in ${row.availableIn}` : ""}` : row.nearLimit ? `low, ${row.leftPercent ?? 0}% left` : row.leftPercent !== undefined ? `${row.leftPercent}% left` : "",
|
|
229
|
+
row.stale ? `stale${row.age ? `, reported ${ago(row.age)}` : ""}` : row.age ? ago(row.age) : ""].filter(Boolean).join("; ");
|
|
230
|
+
lines.push(`${title(row)} on ${where}${flags ? ` (${flags})` : ""}`);
|
|
231
|
+
for (const w of row.windows) {
|
|
232
|
+
const used = w.reset ? "reset, no new report" : w.usedPercent !== undefined ? `${w.usedPercent}% used` : w.usedUSD !== undefined ? `$${w.usedUSD.toFixed(2)}${w.limitUSD !== undefined ? ` of $${w.limitUSD.toFixed(2)}` : ""}` : "";
|
|
233
|
+
lines.push(` ${w.name.padEnd(30)} ${used.padEnd(22)}${w.limited ? "limited now " : ""}${w.resetsIn ? `resets in ${w.resetsIn}` : ""}`.trimEnd());
|
|
234
|
+
}
|
|
235
|
+
if (row.spend)
|
|
236
|
+
lines.push(` spend ${row.spend.period.replace(/_/g, " ").padEnd(24)} $${row.spend.amountUSD.toFixed(2)}`);
|
|
237
|
+
if (row.message)
|
|
238
|
+
lines.push(` ${row.message}`);
|
|
239
|
+
}
|
|
240
|
+
if (view.noData.length) {
|
|
241
|
+
lines.push("No numbers reported");
|
|
242
|
+
for (const item of view.noData)
|
|
243
|
+
lines.push(` ${item.name} (${item.computers.join(", ")})${item.message ? `: ${item.message}` : ""}`);
|
|
244
|
+
}
|
|
245
|
+
if (view.unreachable.length) {
|
|
246
|
+
lines.push("Unreachable");
|
|
247
|
+
for (const item of view.unreachable)
|
|
248
|
+
lines.push(` ${item.computer}: ${item.error}`);
|
|
249
|
+
}
|
|
250
|
+
if (view.notLinked.length) {
|
|
251
|
+
lines.push("Not linked, so not checked");
|
|
252
|
+
for (const item of view.notLinked)
|
|
253
|
+
lines.push(` ${item.name}${item.aliases?.length ? ` (also ${item.aliases.join(", ")})` : ""}`);
|
|
254
|
+
}
|
|
255
|
+
if (view.peerError)
|
|
256
|
+
lines.push(`Linked computers skipped: ${view.peerError}`);
|
|
257
|
+
return lines.join("\n");
|
|
258
|
+
}
|
|
@@ -6,6 +6,7 @@ import { type RequestKind } from "./approval-summary.js";
|
|
|
6
6
|
import { type DialogAnswer, type DialogQuestion } from "./claude-question-dialog.js";
|
|
7
7
|
import { type TerminalChoice } from "./terminal-choice.js";
|
|
8
8
|
import { ApprovalWatchLeases } from "./agent-hook-stores.js";
|
|
9
|
+
import { SudoBroker } from "./sudo.js";
|
|
9
10
|
import type { AppServerRequestId, PendingServerRequest } from "./codex-app-server.js";
|
|
10
11
|
import { PaneServerWatcher, type PaneAsks } from "./opencode-panes.js";
|
|
11
12
|
import type { PaneClient, PaneServerEntry } from "./opencode-pane-server.js";
|
|
@@ -158,6 +159,8 @@ export declare class AgentHooks {
|
|
|
158
159
|
/** The name the phone paired with (macOS Computer Name), for approval alerts;
|
|
159
160
|
* the short host name until that lookup answers. */
|
|
160
161
|
private computerName;
|
|
162
|
+
/** sudo -A requests from askpass, answered from the phone (sudo.ts). */
|
|
163
|
+
readonly sudo: SudoBroker;
|
|
161
164
|
constructor(push?: ApprovalPushService, modules?: ModuleSnapshot | undefined);
|
|
162
165
|
private approvalsDirectory;
|
|
163
166
|
private scheduleOpencodeSweep;
|
|
@@ -30,7 +30,8 @@ import { notePaneTranscript, paneAccountKey } from "./pane-accounts.js";
|
|
|
30
30
|
import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
|
|
31
31
|
import { noteTurn as recordTurn } from "./turn-records.js";
|
|
32
32
|
import { countTick } from "./metrics.js";
|
|
33
|
-
import { briefId, briefIdInPrompt, DISPATCH_ID_ENV, recordBriefArrival } from "./launch-brief.js";
|
|
33
|
+
import { briefId, briefIdInPrompt, briefLabel, DISPATCH_ID_ENV, recordBriefArrival } from "./launch-brief.js";
|
|
34
|
+
import { SudoBroker } from "./sudo.js";
|
|
34
35
|
import { CODEX_SERVER_ENV, codexServerId, codexServers } from "./codex-servers.js";
|
|
35
36
|
import { paneClient, paneKey, PaneServerWatcher, rootSession, servedPane } from "./opencode-panes.js";
|
|
36
37
|
export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./terminal-choice.js";
|
|
@@ -194,10 +195,23 @@ export class AgentHooks {
|
|
|
194
195
|
/** The name the phone paired with (macOS Computer Name), for approval alerts;
|
|
195
196
|
* the short host name until that lookup answers. */
|
|
196
197
|
computerName = hostname().replace(/\.local$/i, "").split(".")[0] || "Computer";
|
|
198
|
+
/** sudo -A requests from askpass, answered from the phone (sudo.ts). */
|
|
199
|
+
sudo;
|
|
197
200
|
constructor(push = new ApprovalPushService(), modules) {
|
|
198
201
|
this.push = push;
|
|
199
202
|
this.modules = modules;
|
|
200
203
|
void computerDisplayName().then(name => { this.computerName = name; }, () => { });
|
|
204
|
+
this.sudo = new SudoBroker({ computer: () => this.computerName, push, label: briefLabel,
|
|
205
|
+
describe: async (place) => {
|
|
206
|
+
const s = await snapshot(place.server);
|
|
207
|
+
const pane = findPane(s, place);
|
|
208
|
+
if (!pane)
|
|
209
|
+
return undefined;
|
|
210
|
+
const tab = objects(s.tabs).find(item => item.tab_id === place.tab && item.workspace_id === place.workspace);
|
|
211
|
+
const workspace = objects(s.workspaces).find(item => item.workspace_id === place.workspace);
|
|
212
|
+
const label = [tab?.label, workspace?.label].find(value => typeof value === "string" && value.trim());
|
|
213
|
+
return { ...(typeof pane.agent === "string" ? { source: pane.agent } : {}), ...(label ? { label } : {}) };
|
|
214
|
+
} });
|
|
201
215
|
}
|
|
202
216
|
approvalsDirectory() { return path.join(phrenStoreRoot(), ".runtime", "approvals"); }
|
|
203
217
|
scheduleOpencodeSweep() {
|
|
@@ -1575,6 +1589,10 @@ export class AgentHooks {
|
|
|
1575
1589
|
this.server = createServer(async (req, res) => {
|
|
1576
1590
|
res.setHeader("Content-Type", "application/json");
|
|
1577
1591
|
try {
|
|
1592
|
+
if (req.method === "POST" && req.url === "/sudo") {
|
|
1593
|
+
await this.sudo.handle(req, res);
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1578
1596
|
if (req.method !== "POST" || req.url !== "/hook")
|
|
1579
1597
|
throw new Error("Invalid callback");
|
|
1580
1598
|
let size = 0;
|
|
@@ -1801,6 +1819,7 @@ export class AgentHooks {
|
|
|
1801
1819
|
}
|
|
1802
1820
|
close() {
|
|
1803
1821
|
this.closed = true;
|
|
1822
|
+
this.sudo.close();
|
|
1804
1823
|
void this.changes.close().catch(() => { });
|
|
1805
1824
|
for (const pending of this.pending.values()) {
|
|
1806
1825
|
clearTimeout(pending.timer);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** `SessionStart` to `session_start`, the event name in Codex's trust keys. */
|
|
2
|
+
export declare function codexEventName(event: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Codex's `hook_hash` for one handler in one group (codex-rs hooks
|
|
5
|
+
* discovery + config fingerprint): sha256 of the canonical JSON of
|
|
6
|
+
* `{ event_name, matcher?, hooks: [handler] }`, where the handler always
|
|
7
|
+
* carries `timeout` (default 600, at least 1) and `async` (default false).
|
|
8
|
+
*/
|
|
9
|
+
export declare function codexHookHash(event: string, group: Record<string, unknown>, handler: Record<string, unknown>): string;
|
|
10
|
+
/**
|
|
11
|
+
* The config text with trust carried forward to Phren's handlers in
|
|
12
|
+
* `hooks` (the hooks.json text as it is now), or undefined when nothing
|
|
13
|
+
* changes. `before` is hooks.json as it stood before this install rewrote
|
|
14
|
+
* it, when there was a rewrite. `hooksPaths` are the names Codex may key
|
|
15
|
+
* this hooks.json by; the first is used for a new key.
|
|
16
|
+
*/
|
|
17
|
+
export declare function codexHookTrustText(config: string, hooks: string, program: string, hooksPaths: string[], before?: string): {
|
|
18
|
+
text: string;
|
|
19
|
+
carried: string[];
|
|
20
|
+
} | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Carries the owner's Codex trust forward to Phren's handlers in
|
|
23
|
+
* `$CODEX_HOME/hooks.json`. Runs after every install, update, rollback and
|
|
24
|
+
* module reconcile, whether or not hooks.json changed, so a computer an
|
|
25
|
+
* earlier install left untrusted is repaired too. Never throws.
|
|
26
|
+
*/
|
|
27
|
+
export declare function carryCodexHookTrust(program: string, before?: string, env?: NodeJS.ProcessEnv): Promise<string[]>;
|