@phnx-labs/agents-cli 1.23.44 → 1.23.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.md +28 -2
- package/dist/commands/accounts.js +58 -1
- package/dist/commands/exec.js +5 -2
- package/dist/commands/lead.js +1 -1
- package/dist/commands/view.js +11 -6
- package/dist/lib/account-catalog.d.ts +2 -0
- package/dist/lib/account-catalog.js +5 -2
- package/dist/lib/account-registry.d.ts +2 -0
- package/dist/lib/account-registry.js +34 -0
- package/dist/lib/accounting/account-pool-collect.d.ts +2 -0
- package/dist/lib/accounting/account-pool-collect.js +10 -4
- package/dist/lib/accounting/account-pool.d.ts +1 -0
- package/dist/lib/accounting/account-pool.js +4 -1
- package/dist/lib/accounting/advise-notify.d.ts +7 -0
- package/dist/lib/accounting/advise-notify.js +37 -0
- package/dist/lib/accounting/advise.d.ts +67 -0
- package/dist/lib/accounting/advise.js +237 -0
- package/dist/lib/accounting/rotate.d.ts +1 -0
- package/dist/lib/accounting/rotate.js +8 -3
- package/dist/lib/accounting/usage-history.d.ts +24 -0
- package/dist/lib/accounting/usage-history.js +97 -0
- package/dist/lib/accounting/usage-sync.d.ts +6 -2
- package/dist/lib/accounting/usage-sync.js +18 -3
- package/dist/lib/accounting/usage.js +7 -0
- package/dist/lib/agent-spec/agents.d.ts +1 -0
- package/dist/lib/agent-spec/agents.js +10 -2
- package/dist/lib/claude-statusline.d.ts +16 -1
- package/dist/lib/claude-statusline.js +45 -7
- package/dist/lib/daemon/usage-sync-service.js +9 -0
- package/dist/lib/device-config.d.ts +1 -1
- package/dist/lib/device-config.js +2 -2
- package/dist/lib/fleet-shared-state.d.ts +5 -0
- package/dist/lib/fleet-shared-state.js +7 -0
- package/dist/lib/github/open-prs.js +2 -1
- package/dist/lib/github/project-prs.js +1 -11
- package/dist/lib/github/rest.d.ts +1 -0
- package/dist/lib/github/rest.js +1 -1
- package/dist/lib/helper-versions.js +1 -1
- package/dist/lib/lead/host.d.ts +1 -1
- package/dist/lib/lead/host.js +8 -7
- package/dist/lib/lead/store.d.ts +2 -0
- package/dist/lib/lead/store.js +3 -1
- package/dist/lib/rush-api.js +1 -1
- package/dist/lib/session/glance-files.js +1 -1
- package/dist/lib/session/remote/watch.js +2 -2
- package/dist/lib/types.d.ts +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { listNativeAccounts } from '../account-registry.js';
|
|
2
|
+
import { usageKeyForNativeIdentity } from '../agents.js';
|
|
3
|
+
import { readFleetSharedDeviceStates } from '../fleet-shared-state.js';
|
|
4
|
+
import { readMeta } from '../state.js';
|
|
5
|
+
import { getUsageHistoryPath, mergeUsagePeaks, parseUsagePeaks, readUsageHistory } from './usage-history.js';
|
|
6
|
+
export const DEFAULT_ADVISE_WEEKS = 4;
|
|
7
|
+
export const DEFAULT_ADVISE_TARGET = 0.8;
|
|
8
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
9
|
+
const WEEK_MS = 7 * DAY_MS;
|
|
10
|
+
export function weekStartUtc(ms) {
|
|
11
|
+
const d = new Date(ms);
|
|
12
|
+
const day = (d.getUTCDay() + 6) % 7;
|
|
13
|
+
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - day * DAY_MS;
|
|
14
|
+
}
|
|
15
|
+
function windowWeek(p) {
|
|
16
|
+
return weekStartUtc(Date.parse(p.resetsAt) - WEEK_MS);
|
|
17
|
+
}
|
|
18
|
+
function round2(n) {
|
|
19
|
+
return Math.round(n * 100) / 100;
|
|
20
|
+
}
|
|
21
|
+
export function adviseAccounts(accounts, peaks, options = {}) {
|
|
22
|
+
const now = options.now ?? new Date();
|
|
23
|
+
const weekCount = Math.max(1, Math.floor(options.weeks ?? DEFAULT_ADVISE_WEEKS));
|
|
24
|
+
const target = options.target ?? DEFAULT_ADVISE_TARGET;
|
|
25
|
+
if (!(target > 0 && target <= 1))
|
|
26
|
+
throw new Error(`target must be in (0, 1], got ${target}`);
|
|
27
|
+
const currentWeek = weekStartUtc(now.getTime());
|
|
28
|
+
const weekStarts = Array.from({ length: weekCount }, (_, i) => currentWeek - (weekCount - i) * WEEK_MS);
|
|
29
|
+
const weekIndex = new Map(weekStarts.map((w, i) => [w, i]));
|
|
30
|
+
const byKey = new Map();
|
|
31
|
+
for (const p of peaks) {
|
|
32
|
+
const list = byKey.get(p.key) ?? [];
|
|
33
|
+
list.push(p);
|
|
34
|
+
byKey.set(p.key, list);
|
|
35
|
+
}
|
|
36
|
+
const rows = accounts.map((account) => {
|
|
37
|
+
const weekly = weekStarts.map(() => null);
|
|
38
|
+
let thisWeek = null;
|
|
39
|
+
let pace = null;
|
|
40
|
+
let limitedWeeks = 0;
|
|
41
|
+
for (const p of byKey.get(account.usageKey) ?? []) {
|
|
42
|
+
if (p.peak >= 100)
|
|
43
|
+
limitedWeeks += 1;
|
|
44
|
+
if (Date.parse(p.resetsAt) > now.getTime()) {
|
|
45
|
+
thisWeek = Math.max(thisWeek ?? 0, p.peak);
|
|
46
|
+
const elapsed = Date.parse(p.lastSeen) - (Date.parse(p.resetsAt) - WEEK_MS);
|
|
47
|
+
if (elapsed >= DAY_MS)
|
|
48
|
+
pace = Math.max(pace ?? 0, Math.min(100, (p.peak * WEEK_MS) / elapsed));
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const idx = weekIndex.get(windowWeek(p));
|
|
52
|
+
if (idx !== undefined)
|
|
53
|
+
weekly[idx] = Math.max(weekly[idx] ?? 0, p.peak);
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
name: account.name,
|
|
57
|
+
id: account.id,
|
|
58
|
+
paused: account.paused,
|
|
59
|
+
isDefault: account.isDefault,
|
|
60
|
+
peaks: weekly.map((v) => (v === null ? null : Math.round(v))),
|
|
61
|
+
thisWeek: thisWeek === null ? null : Math.round(thisWeek),
|
|
62
|
+
pace: pace === null ? null : Math.round(pace),
|
|
63
|
+
limitedWeeks,
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
const firstOfKey = new Set();
|
|
67
|
+
const seenKeys = new Set();
|
|
68
|
+
accounts.forEach((a, i) => {
|
|
69
|
+
if (!seenKeys.has(a.usageKey)) {
|
|
70
|
+
seenKeys.add(a.usageKey);
|
|
71
|
+
firstOfKey.add(i);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
const counted = rows.filter((_, i) => firstOfKey.has(i));
|
|
75
|
+
const demand = weekStarts.map((_, i) => round2(counted.reduce((sum, r) => sum + (r.peaks[i] ?? 0), 0) / 100));
|
|
76
|
+
const weeksWithData = weekStarts.filter((_, i) => rows.some((r) => r.peaks[i] !== null)).length;
|
|
77
|
+
const current = (r) => r.pace ?? r.thisWeek;
|
|
78
|
+
const currentDemand = counted.some((r) => current(r) !== null)
|
|
79
|
+
? round2(counted.reduce((sum, r) => sum + (current(r) ?? 0), 0) / 100)
|
|
80
|
+
: null;
|
|
81
|
+
const candidates = [...(weeksWithData > 0 ? demand : []), ...(currentDemand === null ? [] : [currentDemand])];
|
|
82
|
+
const peakDemand = candidates.length > 0 ? Math.max(...candidates) : null;
|
|
83
|
+
const active = rows.filter((r) => !r.paused);
|
|
84
|
+
const paused = rows.filter((r) => r.paused);
|
|
85
|
+
const hasReading = (r) => r.peaks.some((v) => v !== null) || r.thisWeek !== null;
|
|
86
|
+
const measured = active.filter(hasReading).length;
|
|
87
|
+
const coverage = { measured, total: active.length };
|
|
88
|
+
const weeksLabel = weekStarts.map((w) => new Date(w).toISOString().slice(0, 10));
|
|
89
|
+
if (peakDemand === null) {
|
|
90
|
+
return {
|
|
91
|
+
weeks: weeksLabel, rows, demand, currentDemand, peakDemand, target, coverage,
|
|
92
|
+
advice: {
|
|
93
|
+
keep: active.length, pause: [], resume: [], add: 0, confidence: 'none',
|
|
94
|
+
reason: `No weekly usage recorded in the last ${weekCount} weeks yet; readings arrive as accounts run.`,
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const limited = rows.some((r) => r.limitedWeeks > 0);
|
|
99
|
+
let need = Math.max(1, Math.ceil(round2(peakDemand / target)));
|
|
100
|
+
if (limited && need <= active.length)
|
|
101
|
+
need = active.length + 1;
|
|
102
|
+
const sumPeaks = (r) => r.peaks.reduce((s, v) => s + (v ?? 0), current(r) ?? 0);
|
|
103
|
+
let pause = [];
|
|
104
|
+
let resume = [];
|
|
105
|
+
let add = 0;
|
|
106
|
+
if (need < active.length) {
|
|
107
|
+
pause = active
|
|
108
|
+
.filter((r) => !r.isDefault)
|
|
109
|
+
.sort((a, b) => sumPeaks(a) - sumPeaks(b) || a.name.localeCompare(b.name))
|
|
110
|
+
.slice(0, active.length - need)
|
|
111
|
+
.map((r) => r.name);
|
|
112
|
+
}
|
|
113
|
+
else if (need > active.length) {
|
|
114
|
+
const short = need - active.length;
|
|
115
|
+
resume = paused
|
|
116
|
+
.sort((a, b) => sumPeaks(b) - sumPeaks(a) || a.name.localeCompare(b.name))
|
|
117
|
+
.slice(0, short)
|
|
118
|
+
.map((r) => r.name);
|
|
119
|
+
add = short - resume.length;
|
|
120
|
+
}
|
|
121
|
+
const confidence = measured === active.length && weeksWithData >= Math.min(3, weekCount) ? 'high' : 'low';
|
|
122
|
+
if (confidence === 'low') {
|
|
123
|
+
pause = [];
|
|
124
|
+
resume = [];
|
|
125
|
+
}
|
|
126
|
+
const unmeasured = active.filter((r) => !hasReading(r)).map((r) => r.name);
|
|
127
|
+
const parts = [
|
|
128
|
+
`Peak weekly demand ${peakDemand.toFixed(2)} account-weeks ÷ ${Math.round(target * 100)}% target = ${need}.`,
|
|
129
|
+
];
|
|
130
|
+
if (limited)
|
|
131
|
+
parts.push('An account hit its weekly limit, so the count adds one.');
|
|
132
|
+
if (weeksWithData < weekCount)
|
|
133
|
+
parts.push(`Only ${weeksWithData} of ${weekCount} weeks have readings.`);
|
|
134
|
+
if (unmeasured.length > 0)
|
|
135
|
+
parts.push(`No reading for ${unmeasured.join(', ')} (idle, or used only headless).`);
|
|
136
|
+
if (confidence === 'low' && need !== active.length) {
|
|
137
|
+
parts.push(`Accounts to ${need < active.length ? 'pause' : 'resume'} are named once every active account has readings in ${Math.min(3, weekCount)} of the last ${weekCount} weeks.`);
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
weeks: weeksLabel, rows, demand, currentDemand, peakDemand, target, coverage,
|
|
141
|
+
advice: { keep: need, pause, resume, add, confidence, reason: parts.join(' ') },
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
export function collectAccountsAdvice(agent, options = {}) {
|
|
145
|
+
const meta = readMeta();
|
|
146
|
+
const defaultRef = meta.accounts?.defaults?.[agent];
|
|
147
|
+
const accounts = listNativeAccounts(meta)
|
|
148
|
+
.filter((a) => a.agent === agent)
|
|
149
|
+
.map((a) => ({
|
|
150
|
+
name: a.name,
|
|
151
|
+
id: a.id,
|
|
152
|
+
usageKey: usageKeyForNativeIdentity(agent, a.identityKey),
|
|
153
|
+
paused: !!a.pausedAt,
|
|
154
|
+
isDefault: defaultRef === a.name || defaultRef === a.id,
|
|
155
|
+
}))
|
|
156
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
157
|
+
const local = readUsageHistory(options.historyPath ?? getUsageHistoryPath());
|
|
158
|
+
const peers = readFleetSharedDeviceStates(options.userAgentsDir).states
|
|
159
|
+
.map((s) => parseUsagePeaks(s.usageHistory?.peaks));
|
|
160
|
+
return { harness: agent, ...adviseAccounts(accounts, mergeUsagePeaks(local, ...peers), options) };
|
|
161
|
+
}
|
|
162
|
+
function pct(v) {
|
|
163
|
+
return v === null ? '—' : `${v}%`;
|
|
164
|
+
}
|
|
165
|
+
export function renderAccountsAdvice(result) {
|
|
166
|
+
const { harness, weeks, rows, demand, coverage, advice } = result;
|
|
167
|
+
const lines = [];
|
|
168
|
+
const pausedCount = rows.filter((r) => r.paused).length;
|
|
169
|
+
lines.push(`${harness} · ${coverage.total} active${pausedCount ? `, ${pausedCount} paused` : ''} · last ${weeks.length} weeks · ${coverage.measured}/${coverage.total} measured`);
|
|
170
|
+
if (rows.length === 0) {
|
|
171
|
+
lines.push('', `No named ${harness} accounts. Add one: agents accounts add ${harness} <name>`);
|
|
172
|
+
return lines;
|
|
173
|
+
}
|
|
174
|
+
const nameW = Math.max(8, ...rows.map((r) => r.name.length + (r.paused ? 9 : 0)));
|
|
175
|
+
const cell = (s) => s.padStart(7);
|
|
176
|
+
const nowCell = (r) => r.thisWeek === null ? '—' : r.pace !== null && r.pace !== r.thisWeek ? `${r.thisWeek}→${r.pace}%` : `${r.thisWeek}%`;
|
|
177
|
+
const header = ' '.repeat(nameW + 2) + weeks.map((w) => cell(w.slice(5))).join('') + ' this week';
|
|
178
|
+
lines.push('', header);
|
|
179
|
+
for (const r of rows) {
|
|
180
|
+
const label = `${r.name}${r.paused ? ' (paused)' : ''}`.padEnd(nameW);
|
|
181
|
+
lines.push(` ${label}${r.peaks.map((v) => cell(pct(v))).join('')} ${nowCell(r)}`);
|
|
182
|
+
}
|
|
183
|
+
const nowDemand = result.currentDemand === null ? '—' : result.currentDemand.toFixed(2);
|
|
184
|
+
lines.push(` ${'demand'.padEnd(nameW)}${demand.map((d) => cell(d.toFixed(2))).join('')} ${nowDemand} account-weeks`);
|
|
185
|
+
lines.push(' this week: reading so far → projected to the full week');
|
|
186
|
+
lines.push('');
|
|
187
|
+
const { keep, pause, resume, add, confidence, reason } = advice;
|
|
188
|
+
if (confidence === 'none') {
|
|
189
|
+
lines.push(`No recommendation yet. ${reason}`);
|
|
190
|
+
return lines;
|
|
191
|
+
}
|
|
192
|
+
const verdict = confidence === 'low'
|
|
193
|
+
? `Need about ${keep} of ${coverage.total} accounts`
|
|
194
|
+
: pause.length > 0
|
|
195
|
+
? `Keep ${keep}, pause ${pause.length}: ${pause.join(', ')}`
|
|
196
|
+
: resume.length > 0 || add > 0
|
|
197
|
+
? `Need ${keep}: ${[resume.length ? `resume ${resume.join(', ')}` : '', add ? `add ${add}` : ''].filter(Boolean).join(', ')}`
|
|
198
|
+
: `Keep all ${keep}. The active accounts match demand.`;
|
|
199
|
+
lines.push(`${verdict}${confidence === 'low' ? ' (low confidence)' : ''}`);
|
|
200
|
+
lines.push(` ${reason}`);
|
|
201
|
+
if (pause.length > 0)
|
|
202
|
+
lines.push(` agents accounts pause ${pause.map((n) => `${harness}#${n}`).join(' ')}`);
|
|
203
|
+
if (resume.length > 0)
|
|
204
|
+
lines.push(` agents accounts resume ${resume.map((n) => `${harness}#${n}`).join(' ')}`);
|
|
205
|
+
return lines;
|
|
206
|
+
}
|
|
207
|
+
export function accountsAdviceNotification(result, lastNotified, now = new Date()) {
|
|
208
|
+
const { harness, advice, coverage, peakDemand } = result;
|
|
209
|
+
if (advice.confidence !== 'high')
|
|
210
|
+
return null;
|
|
211
|
+
if (advice.pause.length === 0 && advice.resume.length === 0 && advice.add === 0)
|
|
212
|
+
return null;
|
|
213
|
+
const fingerprint = [harness, advice.keep, [...advice.pause].sort().join(','), [...advice.resume].sort().join(','), advice.add].join('|');
|
|
214
|
+
if (fingerprint === lastNotified)
|
|
215
|
+
return null;
|
|
216
|
+
const week = new Date(weekStartUtc(now.getTime())).toISOString().slice(0, 10);
|
|
217
|
+
const demand = peakDemand === null ? '' : ` Peak weekly demand was ${peakDemand.toFixed(2)} account-weeks.`;
|
|
218
|
+
let title;
|
|
219
|
+
let action;
|
|
220
|
+
if (advice.pause.length > 0) {
|
|
221
|
+
title = `${harness}: ${advice.keep} of ${coverage.total} accounts cover your usage`;
|
|
222
|
+
action = `Pause ${advice.pause.join(', ')}: agents accounts pause ${advice.pause.map((n) => `${harness}#${n}`).join(' ')}`;
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
title = `${harness}: you need ${advice.keep} accounts, ${coverage.total} are active`;
|
|
226
|
+
action = [
|
|
227
|
+
advice.resume.length ? `Resume ${advice.resume.join(', ')}: agents accounts resume ${advice.resume.map((n) => `${harness}#${n}`).join(' ')}` : '',
|
|
228
|
+
advice.add ? `Add ${advice.add}: agents accounts add ${harness} <name>` : '',
|
|
229
|
+
].filter(Boolean).join('. ');
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
fingerprint,
|
|
233
|
+
title,
|
|
234
|
+
body: `${action}.${demand} Details: agents accounts usage ${harness}`,
|
|
235
|
+
dedupKey: `accounts-advice:${harness}:${week}:${advice.keep}`,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
@@ -8,7 +8,7 @@ import { resolveConfiguredModel } from '../models.js';
|
|
|
8
8
|
import { isTierToken, resolveTier } from '../model-tiers.js';
|
|
9
9
|
import { listInstalledVersions, getVersionHomePath, resolveVersion } from '../installations/versions.js';
|
|
10
10
|
import { resolveManagedInstallation } from '../installations/store.js';
|
|
11
|
-
import { listNativeAccounts } from '../account-registry.js';
|
|
11
|
+
import { listNativeAccounts, pausedNativeIdentityKeys } from '../account-registry.js';
|
|
12
12
|
import { resolveNativeSpawnHome } from '../exec-account-home.js';
|
|
13
13
|
import { getProjectRunConfigs } from '../run-config.js';
|
|
14
14
|
import { emit } from '../feed/events.js';
|
|
@@ -47,6 +47,8 @@ function isLaunchableSlotVerdict(verdict) {
|
|
|
47
47
|
return verdict !== null && LAUNCHABLE_SLOT_VERDICTS.has(verdict);
|
|
48
48
|
}
|
|
49
49
|
function isRotationEligible(candidate, nowMs = Date.now(), model) {
|
|
50
|
+
if (candidate.paused)
|
|
51
|
+
return false;
|
|
50
52
|
if (candidate.fromSlot && !isLaunchableSlotVerdict(candidate.authVerdict))
|
|
51
53
|
return false;
|
|
52
54
|
return readinessFromCandidate(candidate, nowMs, model).ready;
|
|
@@ -262,7 +264,7 @@ export function classifyHarnessCandidates(byHarness, nowMs = Date.now()) {
|
|
|
262
264
|
const counts = new Map();
|
|
263
265
|
for (const c of candidates) {
|
|
264
266
|
const readiness = readinessFromCandidate(c, nowMs);
|
|
265
|
-
const reason = readiness.ready ? 'ineligible' : readiness.reason;
|
|
267
|
+
const reason = c.paused ? 'paused' : readiness.ready ? 'ineligible' : readiness.reason;
|
|
266
268
|
counts.set(reason, (counts.get(reason) ?? 0) + 1);
|
|
267
269
|
}
|
|
268
270
|
summaries.push({
|
|
@@ -326,7 +328,7 @@ export function formatNoHealthyAccountError(agent, strategy, excluded, nowMs = D
|
|
|
326
328
|
? 'no installed versions'
|
|
327
329
|
: excluded.map((c) => {
|
|
328
330
|
const readiness = readinessFromCandidate(c, nowMs);
|
|
329
|
-
const reason = readiness.ready ? 'ineligible' : readiness.reason;
|
|
331
|
+
const reason = c.paused ? 'paused' : readiness.ready ? 'ineligible' : readiness.reason;
|
|
330
332
|
return `${c.version} (${reason})`;
|
|
331
333
|
}).join(', ');
|
|
332
334
|
const resetSummary = formatResetSummary(earliestResetAcross(excluded, nowMs));
|
|
@@ -368,6 +370,7 @@ export async function collectRunCandidates(agent) {
|
|
|
368
370
|
const authCache = readAuthHealthCache();
|
|
369
371
|
const localHost = machineId();
|
|
370
372
|
const meta = readMeta();
|
|
373
|
+
const pausedKeys = pausedNativeIdentityKeys(meta, agent);
|
|
371
374
|
const binaryLabel = resolveManagedInstallation(agent)?.label ?? versions[0];
|
|
372
375
|
const slotRows = [];
|
|
373
376
|
const slotDirs = new Set();
|
|
@@ -409,6 +412,7 @@ export async function collectRunCandidates(agent) {
|
|
|
409
412
|
nativeAccountId: account.id,
|
|
410
413
|
slotDir: home,
|
|
411
414
|
fromSlot: !!slot,
|
|
415
|
+
paused: !!account.pausedAt,
|
|
412
416
|
};
|
|
413
417
|
}));
|
|
414
418
|
for (const row of probed) {
|
|
@@ -440,6 +444,7 @@ export async function collectRunCandidates(agent) {
|
|
|
440
444
|
authVerdict,
|
|
441
445
|
authCheckedAt: authHealth?.checkedAt ?? null,
|
|
442
446
|
lastActive: info.lastActive,
|
|
447
|
+
paused: !!info.accountKey && pausedKeys.has(info.accountKey),
|
|
443
448
|
};
|
|
444
449
|
}));
|
|
445
450
|
const rows = [...slotRows, ...versionRows.filter((row) => row !== null)];
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface UsagePeak {
|
|
2
|
+
key: string;
|
|
3
|
+
resetsAt: string;
|
|
4
|
+
peak: number;
|
|
5
|
+
firstSeen: string;
|
|
6
|
+
lastSeen: string;
|
|
7
|
+
}
|
|
8
|
+
export interface UsageWindowSample {
|
|
9
|
+
key: string;
|
|
10
|
+
usedPercent: number;
|
|
11
|
+
resetsAt: Date | string | null;
|
|
12
|
+
}
|
|
13
|
+
export declare const USAGE_HISTORY_RETAIN_DAYS = 180;
|
|
14
|
+
export declare const USAGE_HISTORY_PUBLISH_DAYS = 90;
|
|
15
|
+
export declare const USAGE_HISTORY_FILE = "usage-history.json";
|
|
16
|
+
export declare function getUsageHistoryPath(): string;
|
|
17
|
+
export declare function usageHistoryPathFor(cachePath: string): string;
|
|
18
|
+
export declare function parseUsagePeaks(value: unknown): UsagePeak[];
|
|
19
|
+
export declare function readUsageHistory(historyPath?: string): UsagePeak[];
|
|
20
|
+
export declare function mergeUsagePeaks(...sets: ReadonlyArray<readonly UsagePeak[]>): UsagePeak[];
|
|
21
|
+
export declare function pruneUsagePeaks(peaks: readonly UsagePeak[], now: Date, days?: number): UsagePeak[];
|
|
22
|
+
export declare function peaksFromWindows(usageKey: string, windows: readonly UsageWindowSample[], seenAt: Date): UsagePeak[];
|
|
23
|
+
export declare function recordUsagePeaks(usageKey: string, windows: readonly UsageWindowSample[], seenAt?: Date, historyPath?: string): number;
|
|
24
|
+
export declare function usagePeaksForPublish(now?: Date, historyPath?: string): UsagePeak[];
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { atomicWriteFileSync, ensureLockTarget, withFileLock } from '../fs-atomic.js';
|
|
4
|
+
import { getCacheDir } from '../state.js';
|
|
5
|
+
export const USAGE_HISTORY_RETAIN_DAYS = 180;
|
|
6
|
+
export const USAGE_HISTORY_PUBLISH_DAYS = 90;
|
|
7
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
8
|
+
export const USAGE_HISTORY_FILE = 'usage-history.json';
|
|
9
|
+
export function getUsageHistoryPath() {
|
|
10
|
+
return path.join(getCacheDir(), USAGE_HISTORY_FILE);
|
|
11
|
+
}
|
|
12
|
+
export function usageHistoryPathFor(cachePath) {
|
|
13
|
+
return path.join(path.dirname(cachePath), USAGE_HISTORY_FILE);
|
|
14
|
+
}
|
|
15
|
+
function peakId(p) {
|
|
16
|
+
return `${p.key}\u0000${p.resetsAt}`;
|
|
17
|
+
}
|
|
18
|
+
function isUsagePeak(value) {
|
|
19
|
+
if (!value || typeof value !== 'object')
|
|
20
|
+
return false;
|
|
21
|
+
const v = value;
|
|
22
|
+
return typeof v.key === 'string' && v.key.length > 0
|
|
23
|
+
&& typeof v.resetsAt === 'string' && Number.isFinite(Date.parse(v.resetsAt))
|
|
24
|
+
&& typeof v.peak === 'number' && Number.isFinite(v.peak)
|
|
25
|
+
&& typeof v.firstSeen === 'string' && typeof v.lastSeen === 'string';
|
|
26
|
+
}
|
|
27
|
+
export function parseUsagePeaks(value) {
|
|
28
|
+
return Array.isArray(value) ? value.filter(isUsagePeak) : [];
|
|
29
|
+
}
|
|
30
|
+
export function readUsageHistory(historyPath = getUsageHistoryPath()) {
|
|
31
|
+
let raw;
|
|
32
|
+
try {
|
|
33
|
+
raw = fs.readFileSync(historyPath, 'utf-8');
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
if (err.code === 'ENOENT')
|
|
37
|
+
return [];
|
|
38
|
+
throw err;
|
|
39
|
+
}
|
|
40
|
+
if (!raw.trim())
|
|
41
|
+
return [];
|
|
42
|
+
const parsed = JSON.parse(raw);
|
|
43
|
+
return parseUsagePeaks(parsed?.peaks);
|
|
44
|
+
}
|
|
45
|
+
export function mergeUsagePeaks(...sets) {
|
|
46
|
+
const byId = new Map();
|
|
47
|
+
for (const set of sets) {
|
|
48
|
+
for (const p of set) {
|
|
49
|
+
const id = peakId(p);
|
|
50
|
+
const prior = byId.get(id);
|
|
51
|
+
if (!prior) {
|
|
52
|
+
byId.set(id, { ...p });
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
byId.set(id, {
|
|
56
|
+
key: p.key,
|
|
57
|
+
resetsAt: p.resetsAt,
|
|
58
|
+
peak: Math.max(prior.peak, p.peak),
|
|
59
|
+
firstSeen: prior.firstSeen < p.firstSeen ? prior.firstSeen : p.firstSeen,
|
|
60
|
+
lastSeen: prior.lastSeen > p.lastSeen ? prior.lastSeen : p.lastSeen,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return [...byId.values()].sort((a, b) => a.key.localeCompare(b.key) || a.resetsAt.localeCompare(b.resetsAt));
|
|
65
|
+
}
|
|
66
|
+
export function pruneUsagePeaks(peaks, now, days = USAGE_HISTORY_RETAIN_DAYS) {
|
|
67
|
+
const floor = now.getTime() - days * DAY_MS;
|
|
68
|
+
return peaks.filter((p) => Date.parse(p.resetsAt) >= floor);
|
|
69
|
+
}
|
|
70
|
+
export function peaksFromWindows(usageKey, windows, seenAt) {
|
|
71
|
+
const seen = seenAt.toISOString();
|
|
72
|
+
const out = [];
|
|
73
|
+
for (const w of windows) {
|
|
74
|
+
if (w.key !== 'week' || w.resetsAt == null || !Number.isFinite(w.usedPercent))
|
|
75
|
+
continue;
|
|
76
|
+
const resetsAt = new Date(w.resetsAt);
|
|
77
|
+
if (!Number.isFinite(resetsAt.getTime()))
|
|
78
|
+
continue;
|
|
79
|
+
out.push({ key: usageKey, resetsAt: resetsAt.toISOString(), peak: w.usedPercent, firstSeen: seen, lastSeen: seen });
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
export function recordUsagePeaks(usageKey, windows, seenAt = new Date(), historyPath = getUsageHistoryPath()) {
|
|
84
|
+
const incoming = peaksFromWindows(usageKey, windows, seenAt);
|
|
85
|
+
if (incoming.length === 0)
|
|
86
|
+
return 0;
|
|
87
|
+
ensureLockTarget(historyPath, '');
|
|
88
|
+
return withFileLock(historyPath, () => {
|
|
89
|
+
const merged = pruneUsagePeaks(mergeUsagePeaks(readUsageHistory(historyPath), incoming), seenAt);
|
|
90
|
+
fs.mkdirSync(path.dirname(historyPath), { recursive: true });
|
|
91
|
+
atomicWriteFileSync(historyPath, `${JSON.stringify({ v: 1, peaks: merged })}\n`, 'utf-8');
|
|
92
|
+
return incoming.length;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
export function usagePeaksForPublish(now = new Date(), historyPath = getUsageHistoryPath()) {
|
|
96
|
+
return pruneUsagePeaks(readUsageHistory(historyPath), now, USAGE_HISTORY_PUBLISH_DAYS);
|
|
97
|
+
}
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* its cache newest-wins and prints its own envelope back, which the headed box
|
|
10
10
|
* stores in `~/.agents/devices/<peer>/daemon-state.json` stamped `receivedAt`.
|
|
11
11
|
* Workers never initiate. A peer that times out is skipped this tick and never
|
|
12
|
-
* blocks another. Only usage rows, verdicts,
|
|
13
|
-
* never a credential (invariant 7: roles never cross).
|
|
12
|
+
* blocks another. Only usage rows, verdicts, session digests and weekly usage
|
|
13
|
+
* peaks move here — never a credential (invariant 7: roles never cross).
|
|
14
14
|
*
|
|
15
15
|
* This replaced a git exchange over the fleet-synced user repo: every daemon
|
|
16
16
|
* committed its own file each tick, so the shared store reached 1.1 GiB /
|
|
@@ -55,6 +55,10 @@ interface PublishUsageSnapshotResult {
|
|
|
55
55
|
export declare function publishUsageSnapshotToSharedStore(options?: PublishUsageSnapshotOptions): Promise<PublishUsageSnapshotResult>;
|
|
56
56
|
export interface PublishOwnFleetStateResult {
|
|
57
57
|
usage: PublishUsageSnapshotResult;
|
|
58
|
+
history: {
|
|
59
|
+
count: number;
|
|
60
|
+
error: string | null;
|
|
61
|
+
};
|
|
58
62
|
mirror: {
|
|
59
63
|
changed: boolean;
|
|
60
64
|
count: number;
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* its cache newest-wins and prints its own envelope back, which the headed box
|
|
10
10
|
* stores in `~/.agents/devices/<peer>/daemon-state.json` stamped `receivedAt`.
|
|
11
11
|
* Workers never initiate. A peer that times out is skipped this tick and never
|
|
12
|
-
* blocks another. Only usage rows, verdicts,
|
|
13
|
-
* never a credential (invariant 7: roles never cross).
|
|
12
|
+
* blocks another. Only usage rows, verdicts, session digests and weekly usage
|
|
13
|
+
* peaks move here — never a credential (invariant 7: roles never cross).
|
|
14
14
|
*
|
|
15
15
|
* This replaced a git exchange over the fleet-synced user repo: every daemon
|
|
16
16
|
* committed its own file each tick, so the shared store reached 1.1 GiB /
|
|
@@ -26,6 +26,7 @@ import { getUserAgentsDir } from '../state.js';
|
|
|
26
26
|
import { machineId, normalizeHost } from '../session/sync/config.js';
|
|
27
27
|
import { resolveDeviceProfile } from '../devices/resolve-profile.js';
|
|
28
28
|
import { exportClaudeUsageCacheRows, ingestPeerClaudeUsageRows, } from './usage.js';
|
|
29
|
+
import { getUsageHistoryPath, usageHistoryPathFor, usagePeaksForPublish } from './usage-history.js';
|
|
29
30
|
export const USAGE_SYNC_INTERVAL_MS = 15 * 60_000;
|
|
30
31
|
export const USAGE_PUBLISH_HEARTBEAT_MS = 10 * 60_000;
|
|
31
32
|
export const USAGE_EXCHANGE_PEER_TIMEOUT_MS = 20_000;
|
|
@@ -91,12 +92,26 @@ export async function publishUsageSnapshotToSharedStore(options = {}) {
|
|
|
91
92
|
}
|
|
92
93
|
return result;
|
|
93
94
|
}
|
|
95
|
+
async function publishOwnUsageHistory(options) {
|
|
96
|
+
try {
|
|
97
|
+
const historyPath = options.cachePath ? usageHistoryPathFor(options.cachePath) : getUsageHistoryPath();
|
|
98
|
+
const peaks = usagePeaksForPublish(new Date(), historyPath);
|
|
99
|
+
await updateFleetSharedDeviceStateAsync(options.device ?? machineId(), { usageHistory: { peaks } }, options.userAgentsDir ?? getUserAgentsDir());
|
|
100
|
+
return { count: peaks.length, error: null };
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
return { count: 0, error: err.message };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
94
106
|
// Peer exchange carries usage, auth verdict, and session digests only; credentials never cross device roles.
|
|
95
107
|
export async function publishOwnFleetState(options = {}) {
|
|
96
108
|
const errors = [];
|
|
97
109
|
const usage = await publishUsageSnapshotToSharedStore(options);
|
|
98
110
|
if (usage.error)
|
|
99
111
|
errors.push(`usage: ${usage.error}`);
|
|
112
|
+
const history = await publishOwnUsageHistory(options);
|
|
113
|
+
if (history.error)
|
|
114
|
+
errors.push(`usage-history: ${history.error}`);
|
|
100
115
|
let mirror = { changed: false, count: 0, error: null };
|
|
101
116
|
try {
|
|
102
117
|
const { publishSessionMirrorToSharedStore } = await import('../session/mirror.js');
|
|
@@ -126,7 +141,7 @@ export async function publishOwnFleetState(options = {}) {
|
|
|
126
141
|
catch (err) {
|
|
127
142
|
errors.push(`owner-notify: ${err.message}`);
|
|
128
143
|
}
|
|
129
|
-
return { usage, mirror, auth, errors };
|
|
144
|
+
return { usage, history, mirror, auth, errors };
|
|
130
145
|
}
|
|
131
146
|
// Workers never initiate or poll OAuth usage; only headed peers publish the usage rows they own.
|
|
132
147
|
export function buildFleetStatePayload(options = {}) {
|
|
@@ -16,6 +16,7 @@ import { mapBounded } from '../concurrency.js';
|
|
|
16
16
|
import { atomicWriteFileSync, ensureLockTarget, withFileLock, withFileLockAsync } from '../fs-atomic.js';
|
|
17
17
|
import { withRefreshLease } from '../refresh-coordinator.js';
|
|
18
18
|
import { padToWidth } from '../session/width.js';
|
|
19
|
+
import { recordUsagePeaks, usageHistoryPathFor } from './usage-history.js';
|
|
19
20
|
const execFileAsync = promisify(execFile);
|
|
20
21
|
const CLAUDE_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage';
|
|
21
22
|
const CLAUDE_OAUTH_BETA_HEADER = 'oauth-2025-04-20';
|
|
@@ -1184,6 +1185,7 @@ export function writeClaudeUsageCache(usageKey, snapshot, cachePath = getClaudeU
|
|
|
1184
1185
|
};
|
|
1185
1186
|
atomicWriteFileSync(cachePath, JSON.stringify(cache, null, 2), 'utf-8');
|
|
1186
1187
|
});
|
|
1188
|
+
recordUsagePeaks(usageKey, snapshot.windows, snapshot.capturedAt ?? new Date(), usageHistoryPathFor(cachePath));
|
|
1187
1189
|
}
|
|
1188
1190
|
catch {
|
|
1189
1191
|
}
|
|
@@ -1211,6 +1213,7 @@ export function mergeClaudeUsageCacheWindows(usageKey, snapshot, cachePath = get
|
|
|
1211
1213
|
};
|
|
1212
1214
|
atomicWriteFileSync(cachePath, JSON.stringify(cache, null, 2), 'utf-8');
|
|
1213
1215
|
});
|
|
1216
|
+
recordUsagePeaks(usageKey, snapshot.windows, snapshot.capturedAt ?? new Date(), usageHistoryPathFor(cachePath));
|
|
1214
1217
|
}
|
|
1215
1218
|
catch {
|
|
1216
1219
|
}
|
|
@@ -1255,6 +1258,10 @@ export async function ingestPeerClaudeUsageRows(rows, cachePath = getClaudeUsage
|
|
|
1255
1258
|
if (merged > 0)
|
|
1256
1259
|
writeClaudeUsageCacheFile(cache, cachePath);
|
|
1257
1260
|
});
|
|
1261
|
+
const historyPath = usageHistoryPathFor(cachePath);
|
|
1262
|
+
for (const [key, row] of incoming) {
|
|
1263
|
+
recordUsagePeaks(key, row.windows, new Date(row.capturedAt ?? Date.now()), historyPath);
|
|
1264
|
+
}
|
|
1258
1265
|
}
|
|
1259
1266
|
catch {
|
|
1260
1267
|
}
|
|
@@ -136,6 +136,7 @@ interface ClaudeHomeConfig {
|
|
|
136
136
|
config: Record<string, any>;
|
|
137
137
|
identity: ClaudeHomeIdentity;
|
|
138
138
|
}
|
|
139
|
+
export declare function usageKeyForNativeIdentity(agent: AgentId, identityKey: string): string;
|
|
139
140
|
export declare function readClaudeHomeConfig(base: string): ClaudeHomeConfig | null;
|
|
140
141
|
export declare function getAccountInfo(agentId: AgentId, home?: string): Promise<AccountInfo>;
|
|
141
142
|
export declare function resolveLastActive(agentId: AgentId, base: string, configPath?: string, cachePath?: string, now?: Date): Date | null;
|
|
@@ -1260,6 +1260,15 @@ export function isClaudeCredentialFileBlank(base, platform = process.platform) {
|
|
|
1260
1260
|
return false;
|
|
1261
1261
|
}
|
|
1262
1262
|
}
|
|
1263
|
+
// Usage is org-scoped; account routing is account+org scoped.
|
|
1264
|
+
function claudeUsageKey(organizationId) {
|
|
1265
|
+
return buildIdentityKey('claude', [['org', organizationId]]);
|
|
1266
|
+
}
|
|
1267
|
+
export function usageKeyForNativeIdentity(agent, identityKey) {
|
|
1268
|
+
if (agent !== 'claude')
|
|
1269
|
+
return identityKey;
|
|
1270
|
+
return claudeUsageKey(parseNativeIdentityKey('claude', identityKey)?.org ?? null) ?? identityKey;
|
|
1271
|
+
}
|
|
1263
1272
|
export function readClaudeHomeConfig(base) {
|
|
1264
1273
|
const configDirFile = path.join(base, '.claude', '.claude.json');
|
|
1265
1274
|
const homeLevelFile = path.join(base, '.claude.json');
|
|
@@ -1296,8 +1305,7 @@ export function readClaudeHomeConfig(base) {
|
|
|
1296
1305
|
organizationId,
|
|
1297
1306
|
organizationName: oa.organizationName ?? null,
|
|
1298
1307
|
organizationType: oa.organizationType ?? null,
|
|
1299
|
-
|
|
1300
|
-
usageKey: buildIdentityKey('claude', [['org', organizationId]]),
|
|
1308
|
+
usageKey: claudeUsageKey(organizationId),
|
|
1301
1309
|
accountKey: buildIdentityKey('claude', [
|
|
1302
1310
|
['account', accountId],
|
|
1303
1311
|
['org', organizationId],
|
|
@@ -23,7 +23,22 @@ interface ClaudeStatusLinePayload {
|
|
|
23
23
|
};
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
|
-
export declare
|
|
26
|
+
export declare const RUN_ACCOUNT_ID_ENV = "AGENTS_RUN_ACCOUNT_ID";
|
|
27
|
+
export interface StatusLineAccount {
|
|
28
|
+
usageKey: string | null;
|
|
29
|
+
accountId: string | null;
|
|
30
|
+
label: string;
|
|
31
|
+
}
|
|
32
|
+
export interface StatusLineAccountLookups {
|
|
33
|
+
nativeAccount?: (identity: ClaudeHomeIdentity | null) => NativeAccount | null;
|
|
34
|
+
nativeAccountById?: (id: string) => NativeAccount | null;
|
|
35
|
+
providerAccount?: (id: string) => {
|
|
36
|
+
id: string;
|
|
37
|
+
name: string;
|
|
38
|
+
} | null;
|
|
39
|
+
}
|
|
40
|
+
export declare function resolveStatusLineAccount(env: NodeJS.ProcessEnv, identity: ClaudeHomeIdentity | null, lookups?: StatusLineAccountLookups): StatusLineAccount;
|
|
41
|
+
export declare function ingestClaudeStatusLineUsage(payload: ClaudeStatusLinePayload, account: StatusLineAccount, versionHome?: string | null): boolean;
|
|
27
42
|
export declare function claudeHomeFromEnv(env: NodeJS.ProcessEnv): string;
|
|
28
43
|
export declare function readClaudeIdentity(claudeHome: string): ClaudeHomeIdentity | null;
|
|
29
44
|
export declare function resolveNativeAccount(identity: ClaudeHomeIdentity | null): NativeAccount | null;
|