@phnx-labs/agents-cli 1.23.45 → 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.
Files changed (43) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +28 -2
  3. package/dist/commands/accounts.js +58 -1
  4. package/dist/commands/exec.js +5 -2
  5. package/dist/commands/view.js +11 -6
  6. package/dist/lib/account-catalog.d.ts +2 -0
  7. package/dist/lib/account-catalog.js +5 -2
  8. package/dist/lib/account-registry.d.ts +2 -0
  9. package/dist/lib/account-registry.js +34 -0
  10. package/dist/lib/accounting/account-pool-collect.d.ts +2 -0
  11. package/dist/lib/accounting/account-pool-collect.js +10 -4
  12. package/dist/lib/accounting/account-pool.d.ts +1 -0
  13. package/dist/lib/accounting/account-pool.js +4 -1
  14. package/dist/lib/accounting/advise-notify.d.ts +7 -0
  15. package/dist/lib/accounting/advise-notify.js +37 -0
  16. package/dist/lib/accounting/advise.d.ts +67 -0
  17. package/dist/lib/accounting/advise.js +237 -0
  18. package/dist/lib/accounting/rotate.d.ts +1 -0
  19. package/dist/lib/accounting/rotate.js +8 -3
  20. package/dist/lib/accounting/usage-history.d.ts +24 -0
  21. package/dist/lib/accounting/usage-history.js +97 -0
  22. package/dist/lib/accounting/usage-sync.d.ts +6 -2
  23. package/dist/lib/accounting/usage-sync.js +18 -3
  24. package/dist/lib/accounting/usage.js +7 -0
  25. package/dist/lib/agent-spec/agents.d.ts +1 -0
  26. package/dist/lib/agent-spec/agents.js +10 -2
  27. package/dist/lib/claude-statusline.d.ts +16 -1
  28. package/dist/lib/claude-statusline.js +45 -7
  29. package/dist/lib/daemon/usage-sync-service.js +9 -0
  30. package/dist/lib/device-config.d.ts +1 -1
  31. package/dist/lib/device-config.js +2 -2
  32. package/dist/lib/fleet-shared-state.d.ts +5 -0
  33. package/dist/lib/fleet-shared-state.js +7 -0
  34. package/dist/lib/github/open-prs.js +2 -1
  35. package/dist/lib/github/project-prs.js +1 -11
  36. package/dist/lib/github/rest.d.ts +1 -0
  37. package/dist/lib/github/rest.js +1 -1
  38. package/dist/lib/helper-versions.js +1 -1
  39. package/dist/lib/rush-api.js +1 -1
  40. package/dist/lib/session/glance-files.js +1 -1
  41. package/dist/lib/session/remote/watch.js +2 -2
  42. package/dist/lib/types.d.ts +1 -0
  43. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.46
4
+
5
+ - **`agents accounts usage [harness]` shows how many subscription accounts you actually need.**
6
+ It prints each named account's highest weekly-limit percent per calendar week (last 4 weeks
7
+ by default, `--weeks`), this week's reading projected to the full week, and the summed
8
+ demand in account-weeks, then recommends a count: keep `ceil(peak demand ÷ 0.8)` accounts
9
+ (`--target`), plus one if any account hit its weekly limit. With readings for every active
10
+ account in 3 of the last 4 weeks it names the least-used accounts to pause (never the default
11
+ account), or paused accounts to resume; on thinner history it gives the count only. `--json`
12
+ carries the same table and advice for the menu bar. The history comes from a new weekly-peak
13
+ ledger (`usage-history.json`) fed by every usage cache writer (headed poll, status line, peer
14
+ sync), and every box, worker included, now publishes its ledger on the 15-minute usage-sync
15
+ exchange, so the status-line readings from sessions on workers reach the headed box for the
16
+ first time. Source: `cli/src/lib/accounting/usage-history.ts`, `cli/src/lib/accounting/advise.ts`,
17
+ `cli/src/lib/accounting/usage-sync.ts`, `cli/src/commands/accounts.ts`.
18
+ - **`agents accounts pause <harness>#<name>` / `resume`.** A paused account stays registered with
19
+ its credentials but balanced and available rotation never pick it; `agents run <harness>#<name>`
20
+ and resuming its sessions still work. `accounts list` marks it `paused` and stops suggesting a
21
+ repair for it. The flag lives on the fleet-wide account row in `agents.yaml`.
22
+ - **The headed daemon tells you when the advice changes.** On the usage-sync tick it sends one owner
23
+ notification per harness when a high-confidence recommendation to pause, resume or add accounts
24
+ changes, deduplicated per week so two headed boxes never both send it. Source:
25
+ `cli/src/lib/accounting/advise-notify.ts`, `cli/src/lib/daemon/usage-sync-service.ts`.
26
+
27
+ - **Agent version views show the installed release first.** Resource details and section headings no longer report the historical installation label as the installed release. Diagnostics and detail summaries identify a differing stable name as `(installation: <label>)`; homes, selectors, and JSON fields keep their existing meanings. Source: `cli/src/commands/view.ts`.
28
+
29
+ - **AGI Menu 1.20.0: the Accounts tab.** The `menubar` helper floor rises to 1.20.0, so an installed CLI
30
+ fetches the AGI Menu with the Accounts tab (weekly usage per named account, the keep/pause verdict
31
+ from `agents accounts usage`, and Pause/Resume). Source: `cli/src/lib/helper-versions.ts`.
32
+
33
+ - **A setup-token session no longer credits its rate limits to the login whose home it runs in.**
34
+ `agents run claude --strategy balanced` on a box whose native login was at 100% kept
35
+ picking that login. A session launched with a provider account (`--account <setup-token>`,
36
+ or balanced picking it) runs inside the native login's version home, and the Claude status
37
+ line read the account from that home, so it wrote the token account's headroom (session 31%,
38
+ week 3%) over the poll's 100%/56% under the native login's usage key. Each write made the
39
+ limited login look healthy again until the next poll, and the run died with "You've hit
40
+ your session limit". The status line now resolves the account from `AGENTS_RUN_ACCOUNT_ID`:
41
+ a provider account's limits land under its own key (`claude:name=<account>`), a native
42
+ login keeps its identity, and an id that matches neither writes nothing. Balanced and
43
+ available rotation read that key, so a limited token account is excluded like a limited
44
+ login instead of being a permanently blind pick; a balanced provider pick now also passes
45
+ its account id to the session, and the pick banner names the provider account (`balanced
46
+ picked turing-token · claude@2.1.260`) instead of only the harness version. Source: `cli/src/lib/claude-statusline.ts`,
47
+ `cli/src/lib/accounting/account-pool-collect.ts`, `cli/src/lib/accounting/account-pool.ts`,
48
+ `cli/src/commands/exec.ts`.
49
+
3
50
  ## 1.23.45
4
51
 
5
52
  - **The Lead's own drafting turns no longer read as something you said.** When agents stop to ask, the Lead runs a turn on its own to draft their replies. History saved that turn's whole internal prompt ("[New asks] These agents in this project stopped …") as its `ask`, so the AGI extension's Lead tab drew it under "You" on every such turn. These turns are now saved with `trigger: "asks"` and an empty `ask`. Turns saved before this are read back the same way, and `agents lead history` prints "(on its own, for new asks)" for them. Source: `cli/src/lib/lead/store.ts` (`DRAFT_TURN_PREFIX`, `readHistory`), `cli/src/lib/lead/host.ts`.
package/README.md CHANGED
@@ -1182,6 +1182,10 @@ agents view claude # accounts and usage, one row per ident
1182
1182
  agents view claude --versions # legacy diagnostic: every retained installation and actual release
1183
1183
  ```
1184
1184
 
1185
+ Version diagnostics and resource details show the installed release first, with
1186
+ `(installation: <label>)` when the stable installation name differs. Resource
1187
+ section headings use the release; existing installation selectors stay valid.
1188
+
1185
1189
  `accounts add <harness> [name]` reuses the managed install, creates a HOME-shaped
1186
1190
  slot (no binary), drives the native login there, registers the fleet-wide row, and
1187
1191
  mints the worker credential (claude: `setup-token`; codex/grok/cursor/opencode:
@@ -1237,6 +1241,28 @@ The `connect` / `name` / `label` / `mint` / `attach` / `detach` / `switch` /
1237
1241
  `set-default` verbs are deleted; use `add` / `login` / `default` /
1238
1242
  `run <harness>#<name>` instead.
1239
1243
 
1244
+ ### How many accounts do you need?
1245
+
1246
+ ```bash
1247
+ agents accounts usage # claude: weekly peak per account, demand, keep/pause
1248
+ agents accounts usage codex --weeks 8 --json
1249
+ agents accounts pause claude#spare # out of rotation, still registered
1250
+ agents accounts resume claude#spare
1251
+ ```
1252
+
1253
+ `accounts usage` lists each named account's highest weekly-limit percent per
1254
+ calendar week, this week's reading projected to the full week, and the summed
1255
+ `demand` in account-weeks. Rotation spreads work over every account, so the useful
1256
+ answer is a count: keep `ceil(peak demand ÷ 0.8)` accounts (`--target` changes
1257
+ the 0.8), plus one if any account hit its limit. Once every active account has
1258
+ readings in 3 of the last 4 weeks it names the least-used accounts to pause,
1259
+ never the default; before that it gives the count only. Readings come from every
1260
+ box: the headed poll and the status line of interactive sessions on workers,
1261
+ carried home on the 15-minute usage-sync exchange. Accounts used only headless
1262
+ show no reading. The headed daemon sends one owner notification when that
1263
+ recommendation changes. `pause` keeps the credentials, so `resume` is instant if
1264
+ you re-subscribe; cancelling the subscription itself is done with the provider.
1265
+
1240
1266
  ---
1241
1267
 
1242
1268
  ## Secrets
@@ -1274,7 +1300,7 @@ Merge order: profile env < `--secrets` < `--env K=V`. A missing keychain item ab
1274
1300
  Secrets are provided by the standalone [`@phnx-labs/secrets-cli`](https://github.com/phnx-labs/secrets-cli)
1275
1301
  engine (`agents setup secrets` installs it if missing). Its `push`/`pull`
1276
1302
  verbs move a bundle between machines by encrypting it and round-tripping it
1277
- through `api.prix.dev` — no copy-paste, no `.env` files emailed to yourself:
1303
+ through `api.phoenix.so` — no copy-paste, no `.env` files emailed to yourself:
1278
1304
 
1279
1305
  ```bash
1280
1306
  # On laptop:
@@ -1542,7 +1568,7 @@ secrets add my-keys API_KEY # Prompts for value, stores in the keychai
1542
1568
  ```
1543
1569
 
1544
1570
  Move a bundle to another machine with `secrets push`/`secrets pull` (encrypted
1545
- round trip through `api.prix.dev`). See [Secrets](#secrets) for full usage.
1571
+ round trip through `api.phoenix.so`). See [Secrets](#secrets) for full usage.
1546
1572
 
1547
1573
  ### Summary
1548
1574
 
@@ -7,6 +7,7 @@ import { ALL_AGENT_IDS, resolveAgentName } from '../lib/agents.js';
7
7
  import { getGlobalDefault, listInstalledVersions } from '../lib/installations/versions.js';
8
8
  import { assertNativeAccountNameable } from '../lib/account-capabilities.js';
9
9
  import { collectRunCandidates } from '../lib/accounting/rotate.js';
10
+ import { collectAccountsAdvice, DEFAULT_ADVISE_TARGET, DEFAULT_ADVISE_WEEKS, renderAccountsAdvice } from '../lib/accounting/advise.js';
10
11
  import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
11
12
  import { buildSwitchAccountChoices, formatAccountLimits, pickSwitchAccount } from './run-account-picker.js';
12
13
  import { assertCredentialTransportHostPinned, resolveHostSshTarget } from '../lib/hosts/credential-transport.js';
@@ -20,7 +21,7 @@ import { ensureAdoptedDefaultRepoint } from '../lib/exec-account-home.js';
20
21
  import { acquireAuthOperationLock } from '../lib/accounts/auth-operation-lock.js';
21
22
  import { isSecretsClientError, pushBundleToHost, readAndResolveBundleEnv, readBundle } from '../lib/secrets-client.js';
22
23
  import { getAccountProvider, listAccountProviders, providerAuthenticatesHarness } from '../lib/account-provider-registry.js';
23
- import { accountBindings, addAccount, assertUnambiguousNativeAccount, findAccount, findUnifiedAccount, inspectAccount, listNativeAccounts, nativeAccountHome, parseAccountSelector, readAccountRegistry, removeAccount, renameAccount, setAccountSecret } from '../lib/account-registry.js';
24
+ import { accountBindings, addAccount, assertUnambiguousNativeAccount, findAccount, findUnifiedAccount, inspectAccount, listNativeAccounts, nativeAccountHome, parseAccountSelector, readAccountRegistry, removeAccount, renameAccount, setAccountSecret, setNativeAccountPaused } from '../lib/account-registry.js';
24
25
  function addSupportedList() {
25
26
  return supportedAddHarnesses().join(', ');
26
27
  }
@@ -319,6 +320,62 @@ agents accounts list --json
319
320
  agents accounts list --fleet`,
320
321
  notes: 'One row per account per harness: the account name, its usage bars (`*` stale), then nothing at all when the account is healthy. A state worth acting on trails the row — `rate-limited` (the usage snapshot via `deriveUsageStatusFromSnapshot`/`applyUsageHonesty`, never a probe 429), `expired`/`revoked`/`missing`, partial fleet coverage (`usable on 3 of 5 boxes`), then the exact repair command. `live`, `unverified`, `ready` and `per-device` are the ordinary cases and print nothing. For the identity behind an account use `agents accounts view <name>`; for per-device state use `--fleet`; for everything use `--json`. Reserved credential stores are not listed here; `secrets` is the place those show.',
321
322
  });
323
+ const usageCmd = accounts.command('usage [harness]')
324
+ .description('Weekly usage per account across the fleet, and how many accounts you need (keep / pause)')
325
+ .option('--weeks <n>', `Complete weeks to look back over (default ${DEFAULT_ADVISE_WEEKS})`)
326
+ .option('--target <fraction>', `Highest share of each account's weekly limit to plan for (default ${DEFAULT_ADVISE_TARGET})`)
327
+ .option('--json', 'Machine-readable history and recommendation')
328
+ .action(async (harnessRaw, o, command) => {
329
+ await runAccountsAction(command, () => {
330
+ const agent = harnessRaw ? resolveAgentName(harnessRaw) : 'claude';
331
+ if (!agent)
332
+ throw new Error(`Unknown harness '${harnessRaw}'. Known: ${ALL_AGENT_IDS.join(', ')}`);
333
+ const weeks = o.weeks === undefined ? undefined : Number(o.weeks);
334
+ if (weeks !== undefined && !(Number.isInteger(weeks) && weeks >= 1 && weeks <= 26))
335
+ throw new Error('--weeks must be a whole number from 1 to 26.');
336
+ const target = o.target === undefined ? undefined : Number(o.target);
337
+ if (target !== undefined && !(target > 0 && target <= 1))
338
+ throw new Error('--target must be a fraction above 0 and at most 1, e.g. 0.8.');
339
+ const result = collectAccountsAdvice(agent, { weeks, target });
340
+ if (o.json || command.optsWithGlobals().json) {
341
+ console.log(JSON.stringify(result, null, 2));
342
+ return;
343
+ }
344
+ for (const line of renderAccountsAdvice(result))
345
+ console.log(line);
346
+ });
347
+ });
348
+ setHelpSections(usageCmd, {
349
+ examples: `agents accounts usage
350
+ agents accounts usage claude --weeks 8
351
+ agents accounts usage codex --json
352
+ agents accounts pause claude#spare
353
+ agents accounts resume claude#spare`,
354
+ notes: 'Each cell is the highest weekly-limit percent an account reached in the weekly window that started that calendar week (UTC). Readings come from every box: the headed poll, and the status line of every interactive session on any worker, carried home on the 15-minute usage-sync exchange. `demand` is the column sum in account-weeks. The recommendation keeps ceil(peak demand ÷ target) accounts, adds one if any account hit its limit, never pauses the default account, and pauses the least-used ones first. Accounts used only headless never show a reading, so they read as idle. Pausing does not cancel a subscription; do that with the provider.',
355
+ });
356
+ const pauseCmd = accounts.command('pause <account>')
357
+ .description('Take an account out of automatic rotation without removing it (<harness>#<name>)')
358
+ .action(async (selector, _o, command) => {
359
+ await runAccountsAction(command, () => {
360
+ const account = setNativeAccountPaused(selector, true);
361
+ console.log(chalk.green(`Paused ${account.agent}#${account.name}.`));
362
+ console.log(chalk.gray(` Balanced and available rotation skip it; agents run ${account.agent}#${account.name} still runs it. Undo: agents accounts resume ${account.agent}#${account.name}`));
363
+ });
364
+ });
365
+ setHelpSections(pauseCmd, {
366
+ examples: `agents accounts usage claude
367
+ agents accounts pause claude#spare
368
+ agents accounts resume claude#spare`,
369
+ notes: 'Use it when you cancel or stop paying for a seat: the account stays registered with its credentials, so `resume` is instant if you subscribe again. The pause is fleet-wide (it lives on the account row in agents.yaml).',
370
+ });
371
+ accounts.command('resume <account>')
372
+ .description('Put a paused account back into automatic rotation (<harness>#<name>)')
373
+ .action(async (selector, _o, command) => {
374
+ await runAccountsAction(command, () => {
375
+ const account = setNativeAccountPaused(selector, false);
376
+ console.log(chalk.green(`Resumed ${account.agent}#${account.name}.`));
377
+ });
378
+ });
322
379
  const addCmd = accounts.command('add <target> [name]')
323
380
  .description('Add an account. Harness form: add <harness> [name] runs the native login in a fresh credential slot and provisions workers. Provider form: add <name> --provider <p> --auth <t> stores a durable credential.')
324
381
  .option('--api-key <key>', 'Worker credential for api-key harnesses (codex/grok/cursor/opencode); prompted when omitted')
@@ -132,7 +132,8 @@ function writeRunStage(text, opts) {
132
132
  }
133
133
  function formatRotationBanner(result, verb = 'balanced') {
134
134
  const { picked, healthy, excluded } = result;
135
- const label = picked.email ? `${picked.email} · ${picked.agent}@${picked.version}` : `${picked.agent}@${picked.version}`;
135
+ const who = picked.email || picked.accountLabel;
136
+ const label = who ? `${who} · ${picked.agent}@${picked.version}` : `${picked.agent}@${picked.version}`;
136
137
  const ratio = `${healthy.length} of ${healthy.length + excluded.length} healthy`;
137
138
  const caveat = result.usageUnverified ? ', usage unverified — no recent usage reading' : '';
138
139
  return `[agents] ${verb} picked ${label} (${ratio}${caveat})`;
@@ -2142,8 +2143,10 @@ ${formatModeSupportTable().split('\n').map((line) => ` ${line}`).join('\n
2142
2143
  if (pickedProviderAccount) {
2143
2144
  try {
2144
2145
  const picked = resolveSpawnAccount(pickedProviderAccount, agent, resolved.version, readMeta(), { useDefault: false });
2145
- if (picked?.kind === 'provider')
2146
+ if (picked?.kind === 'provider') {
2146
2147
  accountEnv = picked.env;
2148
+ spawnAccount = picked;
2149
+ }
2147
2150
  }
2148
2151
  catch (err) {
2149
2152
  console.error(chalk.red(err.message));
@@ -24,7 +24,7 @@ import { getAgentsDir, getEffectivePromptcutsPath, readMergedPromptcuts, readMet
24
24
  import { findNativeAccountByIdentity } from '../lib/account-registry.js';
25
25
  import { ACCOUNT_LISTING_LEGEND, loadAccountCatalog, renderAccountRows, secretsUnavailableNote } from '../lib/account-catalog.js';
26
26
  import { addSupported } from '../lib/accounts/add.js';
27
- import { readInstallation } from '../lib/installations/store.js';
27
+ import { installedReleaseFor, readInstallation } from '../lib/installations/store.js';
28
28
  import { isAutoUpdateEnabledForAgent } from '../lib/installations/update-policy.js';
29
29
  import { selectUpdateStrategy } from '../lib/installations/strategies.js';
30
30
  import { composeRulesFromState } from '../lib/rules/compose.js';
@@ -72,6 +72,9 @@ export function joinViewColumns(cols) {
72
72
  end--;
73
73
  return cols.slice(0, end).join(' ');
74
74
  }
75
+ function installedVersionLabel(label, release) {
76
+ return release === label ? release : `${release} (installation: ${label})`;
77
+ }
75
78
  function harnessVersionLabel(harness, globalDefault) {
76
79
  const version = harness.hostVersion ?? globalDefault;
77
80
  if (version) {
@@ -336,10 +339,10 @@ async function showInstalledVersions(filterAgentId, viewOpts) {
336
339
  if (live)
337
340
  liveVersionByAgent.set(agentId, live);
338
341
  }));
339
- const displayVersion = (agentId, dirVersion) => liveVersionByAgent.get(agentId) ?? readInstallation(agentId, dirVersion)?.releaseVersion ?? dirVersion;
342
+ const displayVersion = (agentId, dirVersion) => liveVersionByAgent.get(agentId) ?? installedReleaseFor(agentId, dirVersion);
340
343
  const versionRowLabel = (agentId, version, globalDefault) => {
341
344
  const release = displayVersion(agentId, version);
342
- const shown = release === version ? version : `${version} → ${release}`;
345
+ const shown = installedVersionLabel(version, release);
343
346
  if (version === globalDefault)
344
347
  return `${shown} (default)`;
345
348
  if (isVersionIsolated(agentId, version)) {
@@ -458,7 +461,7 @@ async function showInstalledVersions(filterAgentId, viewOpts) {
458
461
  const isolated = !isDefault && isVersionIsolated(agentId, version);
459
462
  const isolatedTag = getIsolatedDefault(agentId) === version ? ' (isolated default)' : ' (isolated)';
460
463
  const release = displayVersion(agentId, version);
461
- const shown = release === version ? version : `${version} → ${release}`;
464
+ const shown = installedVersionLabel(version, release);
462
465
  const base = versionRowLabel(agentId, version, globalDefault);
463
466
  const tagPad = ' '.repeat(maxVerLabel - base.length);
464
467
  const label = isDefault
@@ -678,6 +681,8 @@ async function showAgentResources(agentId, requestedVersion, filter) {
678
681
  }
679
682
  }
680
683
  const home = getVersionHomePath(agentId, version);
684
+ const release = (isGlobalBinaryAgent(agentId) ? await getLiveVersion(agentId) : null)
685
+ ?? installedReleaseFor(agentId, version);
681
686
  const { hasGitRepo, commands: commandsSync, skills: skillsSync, hooks: hooksSync, memory: memorySync } = await loadResourceSyncData();
682
687
  const resources = getAgentResources(agentId, {
683
688
  cwd,
@@ -688,7 +693,7 @@ async function showAgentResources(agentId, requestedVersion, filter) {
688
693
  const agentData = {
689
694
  agentId,
690
695
  agentName: agentLabel(agentId),
691
- version,
696
+ version: release,
692
697
  commands: resources.commands.map(r => ({
693
698
  ...r,
694
699
  syncState: r.scope === 'project' ? undefined : resolveResourceSyncState(agentId, r.name, 'commands', commandsSync),
@@ -768,7 +773,7 @@ async function showAgentResources(agentId, requestedVersion, filter) {
768
773
  }, { allowInteractiveLogin: usageAllowInteractiveLogin() });
769
774
  const accountLabel = accountColumnLabel(accountInfo);
770
775
  const emailStr = accountLabel ? chalk.cyan(` ${accountLabel}`) : '';
771
- const status = chalk.green(version);
776
+ const status = chalk.green(installedVersionLabel(version, release));
772
777
  const configuredModel = resolveConfiguredModel(agentId, version);
773
778
  const modelStr = configuredModel ? chalk.yellow(` ${configuredModel.model}`) : '';
774
779
  const usageStr = formatUsageSummary(usageInfo.snapshot?.plan ?? accountInfo.plan, null);
@@ -67,6 +67,7 @@ export interface NativeAccountCatalogRow {
67
67
  token: string;
68
68
  lastAuth: string;
69
69
  fix: string | null;
70
+ paused?: boolean;
70
71
  }
71
72
  export interface AccountDeviceVerdict {
72
73
  device: string;
@@ -116,6 +117,7 @@ export interface AccountListEntryJson {
116
117
  token: string;
117
118
  lastAuth: string;
118
119
  fix: string | null;
120
+ paused?: boolean;
119
121
  }
120
122
  interface AccountListJson {
121
123
  version: 2;
@@ -157,7 +157,8 @@ export function buildNativeCatalog(rows, meta, globalDefault = getGlobalDefault)
157
157
  usageError: null,
158
158
  token: 'no token',
159
159
  lastAuth: 'not used on this box yet',
160
- fix: fixFor({
160
+ paused: !!account?.pausedAt,
161
+ fix: account?.pausedAt ? null : fixFor({
161
162
  agent: group.agent,
162
163
  verdict: signedIn ? 'no_evidence' : 'missing',
163
164
  name: account?.name,
@@ -288,7 +289,7 @@ export async function loadAccountCatalog() {
288
289
  const credentialDir = slot?.slotDir ?? (localHome ? getVersionHomePath(row.agent, localHome.label) : null);
289
290
  row.token = readTokenFact(row.agent, credentialDir);
290
291
  row.lastAuth = formatAuthFact(cached ?? null);
291
- row.fix = fixFor({
292
+ row.fix = row.paused ? null : fixFor({
292
293
  agent: row.agent,
293
294
  verdict: row.verdict,
294
295
  name: row.name,
@@ -355,6 +356,7 @@ export function accountListJson(native, providers = [], harness) {
355
356
  token: row.token,
356
357
  lastAuth: row.lastAuth,
357
358
  fix: row.fix,
359
+ ...(row.paused ? { paused: true } : {}),
358
360
  })),
359
361
  ...providers.flatMap((row) => providerJsonEntries(row, harness)),
360
362
  ],
@@ -416,6 +418,7 @@ function nativeLine(row, localDevice, maxWindows) {
416
418
  return {
417
419
  name: row.name ?? row.identityLabel,
418
420
  notes: [
421
+ row.paused ? chalk.yellow('paused') : null,
419
422
  chalk.gray(row.token),
420
423
  authFactNote(row.lastAuth),
421
424
  row.verdict === 'missing' ? chalk.red('signed out') : null,
@@ -65,6 +65,8 @@ interface AddAccountOptions {
65
65
  export declare function addAccount(name: string, provider: string, auth: AccountAuthKind, secret: string, base?: string, opts?: AddAccountOptions): CredentialAccount;
66
66
  export declare function setAccountSecret(name: string, secret: string, base?: string): void;
67
67
  export declare function renameAccount(oldSelector: string, newName: string, base?: string): void;
68
+ export declare function setNativeAccountPaused(selector: string, paused: boolean, now?: Date): NativeAccount;
69
+ export declare function pausedNativeIdentityKeys(meta: Pick<Meta, 'accounts' | 'deviceAccounts'>, agent: AgentId): Set<string>;
68
70
  export declare function removeAccount(selector: string, base?: string): void;
69
71
  export declare function inspectAccount(name: string, base?: string): CredentialAccount & {
70
72
  secretPresent: boolean;
@@ -455,6 +455,40 @@ export function renameAccount(oldSelector, newName, base = getUserAgentsDir()) {
455
455
  renameBundleSync(account.name, newName);
456
456
  renameProfileConsumers(account.name, newName, base);
457
457
  }
458
+ export function setNativeAccountPaused(selector, paused, now = new Date()) {
459
+ const meta = readMeta();
460
+ const parsed = parseAccountSelector(selector);
461
+ const rows = nativeRowsForNameOrId(meta, parsed.name, parsed.agent);
462
+ if (rows.length === 0) {
463
+ const where = parsed.agent ? `${parsed.agent} account` : 'account';
464
+ throw new Error(`Unknown ${where} '${parsed.name}'. Pause applies to named harness logins (agents accounts list).`);
465
+ }
466
+ const rowScope = rows[0].scope;
467
+ const pausedAt = paused ? now.toISOString() : undefined;
468
+ const apply = (row) => {
469
+ const { pausedAt: _prior, ...rest } = row;
470
+ return pausedAt ? { ...rest, pausedAt } : rest;
471
+ };
472
+ updateMeta(current => {
473
+ if (rowScope === 'device') {
474
+ const native = { ...current.deviceAccounts?.native };
475
+ for (const row of rows)
476
+ native[row.id] = apply(native[row.id]);
477
+ return { ...current, deviceAccounts: { ...current.deviceAccounts, native } };
478
+ }
479
+ const native = { ...current.accounts?.native };
480
+ for (const row of rows)
481
+ native[row.id] = apply(native[row.id]);
482
+ return { ...current, accounts: { ...current.accounts, native } };
483
+ });
484
+ const { kind: _kind, ...first } = rows[0];
485
+ return { ...apply(first), kind: 'native' };
486
+ }
487
+ export function pausedNativeIdentityKeys(meta, agent) {
488
+ return new Set(listNativeAccounts(meta)
489
+ .filter(account => account.agent === agent && account.pausedAt)
490
+ .map(account => account.identityKey));
491
+ }
458
492
  export function removeAccount(selector, base = getUserAgentsDir()) {
459
493
  const meta = readMeta();
460
494
  const parsed = parseAccountSelector(selector);
@@ -1,11 +1,13 @@
1
1
  import type { AgentId } from '../types.js';
2
2
  import { type RotateCandidate } from './rotate.js';
3
3
  import { type RegistryAccountRecord } from './account-pool.js';
4
+ import { type UsageSnapshot } from './usage.js';
4
5
  export declare function localRegistryRecords(agent: AgentId, includeKeyed?: boolean): Promise<RegistryAccountRecord[]>;
5
6
  export interface RunCandidateInputs {
6
7
  native: RotateCandidate[];
7
8
  records: RegistryAccountRecord[];
8
9
  runVersion: string | undefined;
10
+ usageSnapshotFor?: (usageKey: string) => UsageSnapshot | null;
9
11
  }
10
12
  export declare function foldRegistryCandidates(agent: AgentId, inputs: RunCandidateInputs, includeKeyed?: boolean): RotateCandidate[];
11
13
  export declare function collectRunCandidatesForRun(agent: AgentId, includeKeyed?: boolean): Promise<RotateCandidate[]>;
@@ -3,6 +3,7 @@ import { hasKeychainToken, isSecretsTransportError } from '../secrets-client.js'
3
3
  import { getGlobalDefault, listInstalledVersions } from '../installations/versions.js';
4
4
  import { collectRunCandidates } from './rotate.js';
5
5
  import { registryAccountServesHarness, registryPoolCandidates } from './account-pool.js';
6
+ import { readClaudeUsageCache } from './usage.js';
6
7
  export async function localRegistryRecords(agent, includeKeyed = false) {
7
8
  try {
8
9
  const accounts = Object.values(readAccountRegistry().accounts)
@@ -19,7 +20,7 @@ export async function localRegistryRecords(agent, includeKeyed = false) {
19
20
  }
20
21
  }
21
22
  export function foldRegistryCandidates(agent, inputs, includeKeyed = false) {
22
- const { native, records, runVersion } = inputs;
23
+ const { native, records, runVersion, usageSnapshotFor } = inputs;
23
24
  if (!runVersion)
24
25
  return native;
25
26
  const seen = new Set(native.filter((c) => c.accountKey).map((c) => c.accountKey));
@@ -31,9 +32,9 @@ export function foldRegistryCandidates(agent, inputs, includeKeyed = false) {
31
32
  accountKey: r.accountKey,
32
33
  accountLabel: r.name,
33
34
  email: null,
34
- usageKey: null,
35
+ usageKey: r.accountKey,
35
36
  usageStatus: null,
36
- usageSnapshot: null,
37
+ usageSnapshot: usageSnapshotFor?.(r.accountKey) ?? null,
37
38
  usageError: null,
38
39
  usageMinutesToLimit: null,
39
40
  plan: null,
@@ -51,5 +52,10 @@ export async function collectRunCandidatesForRun(agent, includeKeyed = false) {
51
52
  collectRunCandidates(agent),
52
53
  runVersion ? localRegistryRecords(agent, includeKeyed) : Promise.resolve([]),
53
54
  ]);
54
- return foldRegistryCandidates(agent, { native, records, runVersion }, includeKeyed);
55
+ return foldRegistryCandidates(agent, {
56
+ native,
57
+ records,
58
+ runVersion,
59
+ usageSnapshotFor: (usageKey) => readClaudeUsageCache(usageKey),
60
+ }, includeKeyed);
55
61
  }
@@ -17,5 +17,6 @@ interface RegistryAccountInput {
17
17
  secretPresent: boolean;
18
18
  }
19
19
  export declare function registryAccountServesHarness(record: Pick<RegistryAccountRecord, 'provider' | 'auth'>, agent: AgentId, includeKeyed?: boolean): boolean;
20
+ export declare function providerAccountUsageKey(agent: AgentId, name: string): string;
20
21
  export declare function registryPoolCandidates(records: RegistryAccountRecord[], agent: AgentId, includeKeyed?: boolean): RegistryAccountInput[];
21
22
  export {};
@@ -2,6 +2,9 @@ import { providerAuthenticatesHarness } from '../account-provider-registry.js';
2
2
  export function registryAccountServesHarness(record, agent, includeKeyed = false) {
3
3
  return (record.auth === 'setup-token' || includeKeyed) && providerAuthenticatesHarness(record.provider, record.auth, agent);
4
4
  }
5
+ export function providerAccountUsageKey(agent, name) {
6
+ return `${agent}:name=${name}`;
7
+ }
5
8
  export function registryPoolCandidates(records, agent, includeKeyed = false) {
6
9
  const out = [];
7
10
  for (const r of records) {
@@ -9,7 +12,7 @@ export function registryPoolCandidates(records, agent, includeKeyed = false) {
9
12
  continue;
10
13
  out.push({
11
14
  id: r.id,
12
- accountKey: `${agent}:name=${r.name}`,
15
+ accountKey: providerAccountUsageKey(agent, r.name),
13
16
  email: null,
14
17
  name: r.name,
15
18
  provider: r.provider,
@@ -0,0 +1,7 @@
1
+ import type { AgentId } from '../types.js';
2
+ export interface AdviceNotifyOutcome {
3
+ harness: AgentId;
4
+ title: string;
5
+ result: string;
6
+ }
7
+ export declare function notifyChangedAccountsAdvice(now?: Date, statePath?: string): Promise<AdviceNotifyOutcome[]>;
@@ -0,0 +1,37 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { listNativeAccounts } from '../account-registry.js';
4
+ import { atomicWriteFileSync } from '../fs-atomic.js';
5
+ import { getCacheDir, readMeta } from '../state.js';
6
+ import { accountsAdviceNotification, collectAccountsAdvice } from './advise.js';
7
+ const STATE_FILE = 'accounts-advice-notified.json';
8
+ function readNotified(statePath) {
9
+ try {
10
+ const parsed = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
11
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
12
+ }
13
+ catch (err) {
14
+ if (err.code === 'ENOENT')
15
+ return {};
16
+ throw err;
17
+ }
18
+ }
19
+ export async function notifyChangedAccountsAdvice(now = new Date(), statePath = path.join(getCacheDir(), STATE_FILE)) {
20
+ const harnesses = [...new Set(listNativeAccounts(readMeta()).map((a) => a.agent))].sort();
21
+ const notified = readNotified(statePath);
22
+ const outcomes = [];
23
+ for (const harness of harnesses) {
24
+ const note = accountsAdviceNotification(collectAccountsAdvice(harness, { now }), notified[harness] ?? null, now);
25
+ if (!note)
26
+ continue;
27
+ const { postOwnerNotification, describeOwnerResult } = await import('../owner-notify.js');
28
+ const sent = await postOwnerNotification({ event: 'message', title: note.title, body: note.body, dedupKey: note.dedupKey });
29
+ outcomes.push({ harness, title: note.title, result: describeOwnerResult(sent) });
30
+ if (sent.delivered.length === 0 && sent.queued.length === 0 && sent.suppressed !== 'duplicate')
31
+ continue;
32
+ notified[harness] = note.fingerprint;
33
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
34
+ atomicWriteFileSync(statePath, `${JSON.stringify(notified, null, 2)}\n`, 'utf-8');
35
+ }
36
+ return outcomes;
37
+ }
@@ -0,0 +1,67 @@
1
+ import type { AgentId } from '../types.js';
2
+ import { type UsagePeak } from './usage-history.js';
3
+ export interface AdviseAccountInput {
4
+ name: string;
5
+ id: string;
6
+ usageKey: string;
7
+ paused: boolean;
8
+ isDefault: boolean;
9
+ }
10
+ export interface AccountUsageRow {
11
+ name: string;
12
+ id: string;
13
+ paused: boolean;
14
+ isDefault: boolean;
15
+ peaks: Array<number | null>;
16
+ thisWeek: number | null;
17
+ pace: number | null;
18
+ limitedWeeks: number;
19
+ }
20
+ export type AdviceConfidence = 'high' | 'low' | 'none';
21
+ export interface AccountsAdvice {
22
+ weeks: string[];
23
+ rows: AccountUsageRow[];
24
+ demand: number[];
25
+ currentDemand: number | null;
26
+ peakDemand: number | null;
27
+ target: number;
28
+ coverage: {
29
+ measured: number;
30
+ total: number;
31
+ };
32
+ advice: {
33
+ keep: number;
34
+ pause: string[];
35
+ resume: string[];
36
+ add: number;
37
+ confidence: AdviceConfidence;
38
+ reason: string;
39
+ };
40
+ }
41
+ export interface AdviseOptions {
42
+ now?: Date;
43
+ weeks?: number;
44
+ target?: number;
45
+ }
46
+ export declare const DEFAULT_ADVISE_WEEKS = 4;
47
+ export declare const DEFAULT_ADVISE_TARGET = 0.8;
48
+ export declare function weekStartUtc(ms: number): number;
49
+ export declare function adviseAccounts(accounts: readonly AdviseAccountInput[], peaks: readonly UsagePeak[], options?: AdviseOptions): AccountsAdvice;
50
+ export interface CollectAdviceOptions extends AdviseOptions {
51
+ userAgentsDir?: string;
52
+ historyPath?: string;
53
+ }
54
+ export declare function collectAccountsAdvice(agent: AgentId, options?: CollectAdviceOptions): AccountsAdvice & {
55
+ harness: AgentId;
56
+ };
57
+ export declare function renderAccountsAdvice(result: AccountsAdvice & {
58
+ harness: string;
59
+ }): string[];
60
+ export declare function accountsAdviceNotification(result: AccountsAdvice & {
61
+ harness: string;
62
+ }, lastNotified: string | null, now?: Date): {
63
+ fingerprint: string;
64
+ title: string;
65
+ body: string;
66
+ dedupKey: string;
67
+ } | null;