# Code coverage report for src/agent/accounts/usage.ts

# All files / src/agent/accounts usage.ts

4.27% Statements 5/117
0% Branches 0/90
0% Functions 0/9
4.46% Lines 5/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375

    18x

    18x
    18x
    18x
    18x

     import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
    import { join, dirname } from 'node:path';
    import type { Account } from '../../db/schema.js';
    import type { AgentInfo } from '../types.js';
    import type { AccountCredentialManager } from '../credentials/types.js';
    import { createModuleLogger } from '../../logger/index.js';
    import { getAccountConfigDir } from './paths.js';
    import { setupAccountConfigDir } from './setup.js';

    const log = createModuleLogger('account-usage');

    const USAGE_API_URL = 'https://api.anthropic.com/api/oauth/usage';
    const TOKEN_REFRESH_URL = 'https://console.anthropic.com/v1/oauth/token';
    const OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
    const TOKEN_REFRESH_BUFFER_MS = 300_000; // 5 minutes

    export interface OAuthCredentials {
      accessToken: string;
      refreshToken: string | null;
      expiresAt: number | null; // ms epoch, null for setup tokens
      subscriptionType: string | null;
      rateLimitTier: string | null;
    }

    export interface UsageTier {
      utilization: number;
      resets_at: string | null;
    }

    export interface AccountUsage {
      five_hour: UsageTier | null;
      seven_day: UsageTier | null;
      seven_day_sonnet: UsageTier | null;
      seven_day_opus: UsageTier | null;
      extra_usage: {
        is_enabled: boolean;
        monthly_limit: number | null;
        used_credits: number | null;
        utilization: number | null;
      } | null;
    }

    export interface AccountHealthResult {
      id: string;
      email: string;
      provider: string;
      credentialsValid: boolean;
      tokenValid: boolean;
      tokenExpiresAt: string | null;
      subscriptionType: string | null;
      error: string | null;
      usage: AccountUsage | null;
      isExhausted: boolean;
      exhaustedUntil: string | null;
      lastUsedAt: string | null;
      agentCount: number;
      activeAgentCount: number;
    }

    function readCredentials(configDir: string): OAuthCredentials | null {
      try {
        const credPath = join(configDir, '.credentials.json');
        if (!existsSync(credPath)) return null;
        const raw = readFileSync(credPath, 'utf-8');
        const parsed = JSON.parse(raw);
        const oauth = parsed.claudeAiOauth;
        if (!oauth || !oauth.accessToken) return null;
        return {
          accessToken: oauth.accessToken,
          refreshToken: oauth.refreshToken ?? null,
          expiresAt: oauth.expiresAt ?? null,
          subscriptionType: oauth.subscriptionType ?? null,
          rateLimitTier: oauth.rateLimitTier ?? null,
        };
      } catch {
        return null;
      }
    }

    function isTokenExpired(credentials: OAuthCredentials): boolean {
      if (!credentials.expiresAt) return false; // Setup tokens without expiry are treated as non-expired
      return credentials.expiresAt < Date.now() + TOKEN_REFRESH_BUFFER_MS;
    }

    /**
     * Write credentials back to the config directory.
     * Matches ccswitch's update_credentials_with_token() behavior.
     */
    function writeCredentials(
      configDir: string,
      accessToken: string,
      refreshToken: string,
      expiresIn: number,
    ): void {
      const credPath = join(configDir, '.credentials.json');

      // Read existing credentials to preserve other fields
      let existing: Record<string, unknown> = {};
      try {
        if (existsSync(credPath)) {
          existing = JSON.parse(readFileSync(credPath, 'utf-8'));
        }
      } catch {
        // Start fresh if can't read
      }

      // Calculate expiry in milliseconds (matching ccswitch behavior)
      const nowMs = Date.now();
      const expiresAt = nowMs + (expiresIn * 1000);

      // Update claudeAiOauth section
      const claudeAiOauth = (existing.claudeAiOauth as Record<string, unknown>) ?? {};
      claudeAiOauth.accessToken = accessToken;
      claudeAiOauth.refreshToken = refreshToken;
      claudeAiOauth.expiresAt = expiresAt;
      existing.claudeAiOauth = claudeAiOauth;

      // Ensure directory exists
      mkdirSync(dirname(credPath), { recursive: true });

      // Write back (compact JSON for consistency with ccswitch)
      writeFileSync(credPath, JSON.stringify(existing));
      log.debug({ configDir }, 'credentials written after token refresh');
    }

    async function refreshToken(
      refreshTokenStr: string,
    ): Promise<{ accessToken: string; refreshToken: string; expiresIn: number } | null> {
      try {
        const response = await fetch(TOKEN_REFRESH_URL, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            grant_type: 'refresh_token',
            refresh_token: refreshTokenStr,
            client_id: OAUTH_CLIENT_ID,
            scope: 'user:inference user:profile',
          }),
        });
        if (!response.ok) return null;
        const data = await response.json();
        return {
          accessToken: data.access_token,
          refreshToken: data.refresh_token,
          expiresIn: data.expires_in,
        };
      } catch {
        return null;
      }
    }

    type FetchUsageResult =
      | { ok: true; usage: AccountUsage }
      | { ok: false; status: number; statusText: string }
      | { ok: false; status: 0; statusText: string };

    async function fetchUsage(accessToken: string): Promise<FetchUsageResult> {
      try {
        const response = await fetch(USAGE_API_URL, {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${accessToken}`,
            'anthropic-beta': 'oauth-2025-04-20',
            'Content-Type': 'application/json',
          },
        });
        if (!response.ok) {
          return { ok: false, status: response.status, statusText: response.statusText };
        }
        const data = await response.json();
        return {
          ok: true,
          usage: {
            five_hour: data.five_hour ?? null,
            seven_day: data.seven_day ?? null,
            seven_day_sonnet: data.seven_day_sonnet ?? null,
            seven_day_opus: data.seven_day_opus ?? null,
            extra_usage: data.extra_usage ?? null,
          },
        };
      } catch (err) {
        return { ok: false, status: 0, statusText: err instanceof Error ? err.message : 'Network error' };
      }
    }

    export async function checkAccountHealth(
      account: Account,
      agents: AgentInfo[],
      credentialManager?: AccountCredentialManager,
      workspaceRoot?: string,
    ): Promise<AccountHealthResult> {
      const configDir = workspaceRoot ? getAccountConfigDir(workspaceRoot, account.id) : null;

      const accountAgents = agents.filter((a) => a.accountId === account.id);
      const activeAgents = accountAgents.filter(
        (a) => a.status === 'running' || a.status === 'waiting_for_input',
      );

      const base: AccountHealthResult = {
        id: account.id,
        email: account.email,
        provider: account.provider,
        credentialsValid: false,
        tokenValid: false,
        tokenExpiresAt: null,
        subscriptionType: null,
        error: null,
        usage: null,
        isExhausted: account.isExhausted,
        exhaustedUntil: account.exhaustedUntil?.toISOString() ?? null,
        lastUsedAt: account.lastUsedAt?.toISOString() ?? null,
        agentCount: accountAgents.length,
        activeAgentCount: activeAgents.length,
      };

      if (!configDir) {
        return { ...base, error: 'Cannot derive config dir: workspaceRoot not provided' };
      }

      // Ensure DB credentials are written to disk so file-based checks can find them
      if (account.configJson && account.credentials) {
        try {
          setupAccountConfigDir(configDir, {
            configJson: JSON.parse(account.configJson),
            credentials: account.credentials,
          });
        } catch (err) {
          log.warn({ accountId: account.id, err: err instanceof Error ? err.message : String(err) }, 'failed to sync DB credentials to disk');
        }
      }

      try {
        // Use credential manager if provided, otherwise fall back to direct functions
        let accessToken: string;
        let currentExpiresAt: number | null;
        let subscriptionType: string | null = null;

        if (credentialManager) {
          const result = await credentialManager.ensureValid(configDir, account.id);
          if (!result.valid || !result.credentials) {
            return {
              ...base,
              credentialsValid: result.credentials !== null,
              error: result.error ?? 'Credentials validation failed',
            };
          }
          accessToken = result.credentials.accessToken;
          currentExpiresAt = result.credentials.expiresAt;
          subscriptionType = result.credentials.subscriptionType;
        } else {
          // Legacy path: direct function calls
          const credentials = readCredentials(configDir);
          if (!credentials) {
            return {
              ...base,
              error: 'Credentials file not found or unreadable',
            };
          }

          accessToken = credentials.accessToken;
          currentExpiresAt = credentials.expiresAt;
          subscriptionType = credentials.subscriptionType;

          if (isTokenExpired(credentials)) {
            if (!credentials.refreshToken) {
              log.warn({ accountId: account.id }, 'setup token expired, no refresh token');
              return {
                ...base,
                credentialsValid: true,
                error: 'Setup token expired, no refresh token available',
              };
            }
            log.info({ accountId: account.id, email: account.email }, 'token expired, refreshing');
            const refreshed = await refreshToken(credentials.refreshToken);
            if (!refreshed) {
              log.warn({ accountId: account.id }, 'token refresh failed');
              return {
                ...base,
                credentialsValid: true,
                error: 'Token expired and refresh failed',
              };
            }
            accessToken = refreshed.accessToken;

            // Persist the refreshed credentials back to disk
            const newRefreshToken = refreshed.refreshToken || credentials.refreshToken;
            writeCredentials(configDir, accessToken, newRefreshToken, refreshed.expiresIn);
            currentExpiresAt = Date.now() + (refreshed.expiresIn * 1000);
            log.info({ accountId: account.id, expiresIn: refreshed.expiresIn }, 'token refreshed and persisted');
          }
        }

        const isSetupToken = !currentExpiresAt;
        const usageResult = await fetchUsage(accessToken);

        if (!usageResult.ok) {
          const statusDetail = usageResult.status > 0
            ? `HTTP ${usageResult.status} ${usageResult.statusText}`
            : usageResult.statusText;

          if (isSetupToken) {
            // Setup tokens often can't query the usage API — not a hard error
            return {
              ...base,
              credentialsValid: true,
              tokenValid: true,
              tokenExpiresAt: null,
              subscriptionType,
              error: `Usage API unavailable for setup token (${statusDetail}). Run \`claude\` with this account to complete OAuth setup.`,
            };
          }

          return {
            ...base,
            credentialsValid: true,
            error: `Usage API request failed: ${statusDetail}`,
          };
        }

        return {
          ...base,
          credentialsValid: true,
          tokenValid: true,
          tokenExpiresAt: currentExpiresAt ? new Date(currentExpiresAt).toISOString() : null,
          subscriptionType,
          usage: usageResult.usage,
        };
      } catch (err) {
        return {
          ...base,
          error: err instanceof Error ? err.message : String(err),
        };
      }
    }

    /**
     * Ensure account credentials are valid and refreshed if needed.
     * Call this before spawning an agent to ensure the credentials file
     * has fresh tokens that the agent subprocess can use.
     *
     * Returns true if credentials are valid (or were successfully refreshed).
     * Returns false if credentials are missing or refresh failed.
     *
     * @deprecated Use AccountCredentialManager.ensureValid() instead for event emission support.
     */
    export async function ensureAccountCredentials(configDir: string): Promise<boolean> {
      const credentials = readCredentials(configDir);
      if (!credentials) {
        log.warn({ configDir }, 'no credentials found');
        return false;
      }

      if (!isTokenExpired(credentials)) {
        log.debug({ configDir }, 'credentials valid, no refresh needed');
        return true;
      }

      if (!credentials.refreshToken) {
        log.error({ configDir }, 'setup token expired, no refresh token available');
        return false;
      }

      log.info({ configDir }, 'credentials expired, refreshing before spawn');
      const refreshed = await refreshToken(credentials.refreshToken);
      if (!refreshed) {
        log.error({ configDir }, 'failed to refresh credentials');
        return false;
      }

      const newRefreshToken = refreshed.refreshToken || credentials.refreshToken;
      writeCredentials(configDir, refreshed.accessToken, newRefreshToken, refreshed.expiresIn);
      log.info({ configDir, expiresIn: refreshed.expiresIn }, 'credentials refreshed before spawn');
      return true;
    }