claude_profile 1.4.1

Claude Code account credential management and token status
Documentation
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Shared types for the `.usage` command module.
//!
//! All enums, structs, and their `impl` blocks live here so other submodules
//! can import them without circular dependencies.

use claude_quota::OauthUsageData;

// ── Sort and prefer strategies ─────────────────────────────────────────────────

#[ derive( Copy, Clone, PartialEq, Eq, Debug ) ]
pub( crate ) enum SortStrategy { Name, Renew, Renews }

impl SortStrategy
{
  pub( crate ) fn parse( s : &str ) -> Result< Self, String >
  {
    match s
    {
      "name"   => Ok( Self::Name ),
      "renew"  => Ok( Self::Renew ),
      "renews" => Ok( Self::Renews ),
      _        => Err( format!(
        "invalid sort:: value {s:?}: valid values are `name`, `renew`, `renews`",
      ) ),
    }
  }

  /// Context-sensitive default `desc` direction for each strategy.
  ///
  /// All strategies default to ascending (`false`).
  pub( crate ) fn default_desc( self ) -> bool
  {
    match self { Self::Name | Self::Renew | Self::Renews => false }
  }
}

#[ derive( Copy, Clone, PartialEq, Eq, Debug ) ]
pub( crate ) enum PreferStrategy { Any, Opus, Sonnet }

impl PreferStrategy
{
  pub( crate ) fn parse( s : &str ) -> Result< Self, String >
  {
    match s
    {
      "any"    => Ok( Self::Any ),
      "opus"   => Ok( Self::Opus ),
      "sonnet" => Ok( Self::Sonnet ),
      _        => Err( format!(
        "invalid prefer:: value {s:?}: valid values are `any`, `opus`, `sonnet`",
      ) ),
    }
  }
}

/// Column visibility state for the `.usage` quota table.
///
/// `flag` (first col) and `account` (name) are structural and always visible.
/// All other columns follow the default set; `cols::` modifiers toggle each one.
#[ derive( Debug ) ]
#[ allow( clippy::struct_excessive_bools ) ]
pub( crate ) struct ColsVisibility
{
  /// `●` composite status emoji column (default ON).
  pub( crate ) status       : bool,
  /// `Expires` token TTL column (default ON).
  pub( crate ) expires      : bool,
  /// `Sub` subscription label column (default OFF).
  pub( crate ) sub          : bool,
  /// `~Renews` next billing date column (default ON).
  pub( crate ) renews       : bool,
  /// `5h Left` session quota remaining (default ON).
  pub( crate ) h5_left      : bool,
  /// `5h Reset` session reset countdown (default ON).
  pub( crate ) h5_reset     : bool,
  /// `7d Left` weekly quota remaining (default ON).
  pub( crate ) d7_left      : bool,
  /// `7d(Son)` Sonnet-only weekly quota remaining (default ON).
  pub( crate ) d7_son       : bool,
  /// `7d Reset` weekly reset countdown (default ON).
  pub( crate ) d7_reset     : bool,
  /// `7d Son Reset` Sonnet weekly reset countdown (default OFF).
  pub( crate ) d7_son_reset : bool,
  /// `Host` machine label column (default OFF).
  pub( crate ) host         : bool,
  /// `Role` user-defined role tag column (default OFF).
  pub( crate ) role         : bool,
  /// `Owner` account owner identity column (default ON).
  pub( crate ) owner        : bool,
  /// `→ Next` soonest upcoming event column (default ON).
  pub( crate ) next         : bool,
}

impl ColsVisibility
{
  pub( crate ) fn default_set() -> Self
  {
    Self
    {
      status       : true,
      expires      : true,
      sub          : false,
      renews       : true,
      h5_left      : true,
      h5_reset     : true,
      d7_left      : true,
      d7_son       : true,
      d7_reset     : true,
      d7_son_reset : false,
      host         : false,
      role         : false,
      owner        : true,
      next         : true,
    }
  }

  pub( crate ) fn apply_modifier( &mut self, modifier : &str ) -> Result< (), String >
  {
    let ( show, id ) = if let Some( rest ) = modifier.strip_prefix( '+' )
    {
      ( true, rest )
    }
    else if let Some( rest ) = modifier.strip_prefix( '-' )
    {
      ( false, rest )
    }
    else
    {
      return Err( format!( "cols:: modifier {modifier:?} must start with `+` or `-`" ) );
    };
    match id
    {
      "status"       => self.status       = show,
      "expires"      => self.expires      = show,
      "sub"          => self.sub          = show,
      "renews"       => self.renews       = show,
      "5h_left"      => self.h5_left      = show,
      "5h_reset"     => self.h5_reset     = show,
      "7d_left"      => self.d7_left      = show,
      "7d_son"       => self.d7_son       = show,
      "7d_reset"     => self.d7_reset     = show,
      "7d_son_reset" => self.d7_son_reset = show,
      "host"         => self.host         = show,
      "role"         => self.role         = show,
      "owner"        => self.owner        = show,
      "next"         => self.next         = show,
      _              => return Err( format!(
        "cols:: unknown column {id:?}: valid IDs are `status`, `expires`, `sub`, `renews`, `5h_left`, `5h_reset`, `7d_left`, `7d_son`, `7d_reset`, `7d_son_reset`, `host`, `role`, `owner`, `next`",
      ) ),
    }
    Ok( () )
  }

  pub( crate ) fn parse( s : &str ) -> Result< Self, String >
  {
    let mut vis = Self::default_set();
    for modifier in s.split( ',' ).map( str::trim ).filter( |m| !m.is_empty() )
    {
      vis.apply_modifier( modifier )?;
    }
    Ok( vis )
  }
}

// ── Per-account quota result ───────────────────────────────────────────────────

/// Per-account quota fetch result, bundling identity, state flags, and the raw usage data.
#[ allow( clippy::struct_excessive_bools ) ]
pub( crate ) struct AccountQuota
{
  pub( crate ) name                  : String,
  /// Live-token match: `accessToken` in `~/.claude/.credentials.json` equals this account's stored token.
  pub( crate ) is_current            : bool,
  /// Active-marker match: per-machine active marker file in the credential store names this account.
  pub( crate ) is_active             : bool,
  /// Another machine's `_active_*` file names this account.
  pub( crate ) is_occupied_elsewhere : bool,
  pub( crate ) expires_at_ms         : u64,
  /// `Ok` = live quota fetched; `Err` = reason string (expired, network, etc.).
  pub( crate ) result                : Result< OauthUsageData, String >,
  /// Billing state from `GET /api/oauth/account`; `None` if the fetch failed.
  pub( crate ) account               : Option< claude_quota::OauthAccountData >,
  /// Machine label from `{name}.json`; empty when absent.
  pub( crate ) host                  : String,
  /// User-defined role tag from `{name}.json`; empty when absent.
  pub( crate ) role                  : String,
  /// Override billing renewal date from `{name}.json`; `None` when not set.
  pub( crate ) renewal_at            : Option< String >,
  /// `true` when result was loaded from cache (fetch failed, fallback used).
  pub( crate ) cached                : bool,
  /// Seconds since last successful fetch; present only when `cached == true`.
  pub( crate ) cache_age_secs        : Option< u64 >,
  /// `true` when `owner` in `{name}.json` is empty or matches `current_identity()`.
  /// `false` for accounts owned by a different machine — G1–G7 enforcement gates apply.
  pub( crate ) is_owned              : bool,
  /// Raw owner identity string from `{name}.json`; empty when unset.
  pub( crate ) owner                 : String,
}

// ── Command handler ────────────────────────────────────────────────────────────

/// Parsed `.usage` parameters extracted from a `VerifiedCommand`.
#[ derive( Debug ) ]
#[ allow( clippy::struct_excessive_bools ) ]
pub( crate ) struct UsageParams
{
  /// 1 = auto-refresh expired tokens (default); 0 = show errors as-is.
  pub( crate ) refresh           : i64,
  /// 1 = continuous live-monitor loop; 0 = single fetch (default).
  pub( crate ) live              : i64,
  /// Seconds between live-loop cycles (default 30; only validated when live=1).
  pub( crate ) interval          : u64,
  /// Max random seconds added to each cycle (default 0; only validated when live=1).
  pub( crate ) jitter            : u64,
  /// true = emit `[trace]` diagnostic lines to stderr.
  pub( crate ) trace             : bool,
  /// Row ordering strategy for the text table.
  pub( crate ) sort              : SortStrategy,
  /// Sort direction override; `None` = use strategy's context-sensitive default.
  pub( crate ) desc              : Option< bool >,
  /// Weekly quota column selector for strategies that reference weekly availability.
  pub( crate ) prefer            : PreferStrategy,
  /// Column visibility modifiers applied to the text table.
  pub( crate ) cols              : ColsVisibility,
  /// 1 = activate idle 5h session windows via subprocess (default); 0 = off.
  pub( crate ) touch             : i64,
  /// Subprocess model selection (default: `auto`).
  pub( crate ) imodel            : SubprocessModel,
  /// Subprocess effort level (default: `auto`).
  pub( crate ) effort            : SubprocessEffort,
  // ── Row filtering (TSK-223) ────────────────────────────────────────────────
  /// Max rows to display; 0 = show all.
  pub( crate ) count             : u64,
  /// Skip first N rows from the filtered result before display.
  pub( crate ) offset            : u64,
  /// When true, show only the per-machine active account row.
  pub( crate ) only_active       : bool,
  /// When true, show only the row selected as the recommended next account.
  pub( crate ) only_next         : bool,
  /// Minimum 5h quota percentage (0–100); rows below threshold are hidden.
  pub( crate ) min_5h            : u8,
  /// Minimum 7d quota percentage (0–100); rows below threshold are hidden.
  pub( crate ) min_7d            : u8,
  /// When true, hide 🔴 rows (invalid/expired token).
  pub( crate ) only_valid        : bool,
  /// When true, hide 🟡 and 🔴 rows; show only 🟢 rows.
  pub( crate ) exclude_exhausted : bool,
  // ── Format / extraction (TSK-224) ─────────────────────────────────────────
  /// Output format for the result set.
  pub( crate ) format    : UsageOutputFormat,
  /// When `Some`, extract this field's value from the first row as bare string.
  pub( crate ) get       : Option< GetField >,
  /// When true, replace percentage columns with absolute token counts (no-op when API data absent).
  pub( crate ) abs       : bool,
  /// When true, strip emoji and ANSI sequences from the output.
  pub( crate ) no_color  : bool,
  /// When `Some`, write this value to `set_session_model` instead of running `apply_model_override`.
  /// String is the raw user-provided value (e.g., `"opus"`, `"default"`); resolve at use site.
  pub( crate ) set_model : Option< String >,
  // ── Rotation (Feature 038) ─────────────────────────────────────────────────
  /// When true, switch to the `→` winner after rendering the quota table.
  pub( crate ) rotate    : bool,
  /// When true, bypass the G5 ownership gate on the rotate path (and G8 on unclaim).
  pub( crate ) force     : bool,
  // ── Sessions table (Plan 022) ──────────────────────────────────────────────
  /// Controls sessions table visibility: `None` = auto (shown when >1 `_active_*` marker),
  /// `Some(true)` = force on, `Some(false)` = suppress.
  pub( crate ) who       : Option< bool >,
  // ── Token conservation (TSK-314) ──────────────────────────────────────────
  /// When true, restrict all fetch/refresh/touch operations to the current+owned account.
  /// All other accounts use approximated historical data from the quota cache.
  pub( crate ) solo      : bool,
}

// ── Output format ─────────────────────────────────────────────────────────────

/// Output format for the `.usage` command.
#[ derive( Copy, Clone, PartialEq, Eq, Debug ) ]
pub( crate ) enum UsageOutputFormat
{
  /// Human-readable table (default).
  Text,
  /// Machine-readable JSON array.
  Json,
  /// Tab-separated values, plain-text status labels (`ok`/`warn`/`err`).
  Tsv,
  /// Same layout as `Text` with no emoji or ANSI sequences.
  Plain,
  /// Bare value extraction; outputs one field for the first row only.
  Value,
}

// ── GetField ──────────────────────────────────────────────────────────────────

/// Field selector for `get::` single-value extraction.
#[ derive( Copy, Clone, PartialEq, Eq, Debug ) ]
pub( crate ) enum GetField
{
  FiveHourLeft,
  FiveHourReset,
  SevenDayLeft,
  SevenDaySon,
  SevenDayReset,
  Expires,
  Renews,
  Sub,
  Status,
  Account,
  Host,
  Role,
  NextEventType,
  NextEventSecs,
}

impl GetField
{
  pub( crate ) fn parse( s : &str ) -> Result< Self, String >
  {
    match s
    {
      "5h_left"         => Ok( Self::FiveHourLeft ),
      "5h_reset"        => Ok( Self::FiveHourReset ),
      "7d_left"         => Ok( Self::SevenDayLeft ),
      "7d_son"          => Ok( Self::SevenDaySon ),
      "7d_reset"        => Ok( Self::SevenDayReset ),
      "expires"         => Ok( Self::Expires ),
      "renews"          => Ok( Self::Renews ),
      "sub"             => Ok( Self::Sub ),
      "status"          => Ok( Self::Status ),
      "account"         => Ok( Self::Account ),
      "host"            => Ok( Self::Host ),
      "role"            => Ok( Self::Role ),
      "next_event_type" => Ok( Self::NextEventType ),
      "next_event_secs" => Ok( Self::NextEventSecs ),
      _                 => Err( format!(
        "invalid get:: field {s:?}: valid IDs are \
`5h_left`, `5h_reset`, `7d_left`, `7d_son`, `7d_reset`, `expires`, `renews`, \
`sub`, `status`, `account`, `host`, `role`, `next_event_type`, `next_event_secs`",
      ) ),
    }
  }
}

// ── Subprocess model / effort enums ───────────────────────────────────────────

/// `imodel::` parameter value — determines how the subprocess model is selected.
#[ derive( Copy, Clone, PartialEq, Eq, Debug ) ]
pub( crate ) enum SubprocessModel { Auto, Sonnet, Opus, Keep, Haiku }

impl SubprocessModel
{
  pub( crate ) fn parse( s : &str ) -> Result< Self, String >
  {
    match s
    {
      "auto"   => Ok( Self::Auto ),
      "sonnet" => Ok( Self::Sonnet ),
      "opus"   => Ok( Self::Opus ),
      "keep"   => Ok( Self::Keep ),
      "haiku"  => Ok( Self::Haiku ),
      _ => Err( format!( "imodel:: must be one of: auto, sonnet, opus, keep, haiku; got {s:?}" ) ),
    }
  }
}

/// `effort::` parameter value — determines the `--effort` flag injected into subprocesses.
#[ derive( Copy, Clone, PartialEq, Eq, Debug ) ]
pub( crate ) enum SubprocessEffort { Auto, High, Max, Low, Normal }

impl SubprocessEffort
{
  pub( crate ) fn parse( s : &str ) -> Result< Self, String >
  {
    match s
    {
      "auto"   => Ok( Self::Auto ),
      "high"   => Ok( Self::High ),
      "max"    => Ok( Self::Max ),
      "low"    => Ok( Self::Low ),
      "normal" => Ok( Self::Normal ),
      _ => Err( format!( "effort:: must be one of: auto, high, max, low, normal; got {s:?}" ) ),
    }
  }
}

/// Map a model shorthand to its full model ID.
///
/// Returns `Some(Some(model_id))` for `opus`, `sonnet`, `haiku`;
/// `Some(None)` for `default` (removes the `model` key from `settings.json`);
/// `None` for unknown values.
///
/// Shared by `validate_set_model` (`.account.use` / `.usage` `set_model::` parameter)
/// and the `.model` command handler. The model-ID table lives here exactly once.
// `Option<Option<T>>` is intentional: tri-state (known model / remove key / unknown input).
#[ allow( clippy::option_option ) ]
pub( crate ) fn map_model_shorthand( s : &str ) -> Option< Option< &'static str > >
{
  match s
  {
    "opus"    => Some( Some( "claude-opus-4-6" ) ),
    "sonnet"  => Some( Some( "claude-sonnet-4-6" ) ),
    "haiku"   => Some( Some( "claude-haiku-4-5-20251001" ) ),
    "default" => Some( None ),
    _         => None,
  }
}

/// Validate a `set_model::` string and resolve to the model ID to write.
///
/// Returns `Ok(Some(model_id))` for `opus`, `sonnet`, `haiku`;
/// `Ok(None)` for `default` (removes the `model` key from `settings.json`);
/// `Err(message)` for unknown values.
pub( crate ) fn validate_set_model( s : &str ) -> Result< Option< &'static str >, String >
{
  map_model_shorthand( s )
    .ok_or_else( || format!( "set_model:: must be one of: opus, sonnet, haiku, default; got {s:?}" ) )
}