tokenmaxx 0.0.0-alpha.0 → 0.0.3

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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +523 -519
  3. package/package.json +64 -59
package/dist/index.js CHANGED
@@ -1,13 +1,17 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
3
  var __defProp = Object.defineProperty;
4
+ var __returnValue = (v) => v;
5
+ function __exportSetter(name, newValue) {
6
+ this[name] = __returnValue.bind(null, newValue);
7
+ }
4
8
  var __export = (target, all) => {
5
9
  for (var name in all)
6
10
  __defProp(target, name, {
7
11
  get: all[name],
8
12
  enumerable: true,
9
13
  configurable: true,
10
- set: (newValue) => all[name] = () => newValue
14
+ set: __exportSetter.bind(all, name)
11
15
  });
12
16
  };
13
17
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
@@ -11245,7 +11249,7 @@ function finalize(ctx, schema) {
11245
11249
  result.$schema = "http://json-schema.org/draft-07/schema#";
11246
11250
  } else if (ctx.target === "draft-04") {
11247
11251
  result.$schema = "http://json-schema.org/draft-04/schema#";
11248
- } else if (ctx.target === "openapi-3.0") {} else {}
11252
+ } else if (ctx.target === "openapi-3.0") {}
11249
11253
  if (ctx.external?.uri) {
11250
11254
  const id = ctx.external.registry.get(schema)?.id;
11251
11255
  if (!id)
@@ -11506,7 +11510,7 @@ var formatMap, stringProcessor = (schema, ctx, _json, _params) => {
11506
11510
  if (val === undefined) {
11507
11511
  if (ctx.unrepresentable === "throw") {
11508
11512
  throw new Error("Literal `undefined` cannot be represented in JSON Schema");
11509
- } else {}
11513
+ }
11510
11514
  } else if (typeof val === "bigint") {
11511
11515
  if (ctx.unrepresentable === "throw") {
11512
11516
  throw new Error("BigInt literals cannot be represented in JSON Schema");
@@ -12213,21 +12217,21 @@ __export(exports_core2, {
12213
12217
  $ZodAny: () => $ZodAny
12214
12218
  });
12215
12219
  var init_core2 = __esm(() => {
12220
+ init_util();
12221
+ init_regexes();
12222
+ init_locales();
12223
+ init_json_schema_processors();
12224
+ init_json_schema_generator();
12225
+ init_json_schema();
12216
12226
  init_core();
12217
12227
  init_parse();
12218
12228
  init_errors();
12219
12229
  init_schemas();
12220
12230
  init_checks();
12221
12231
  init_versions();
12222
- init_util();
12223
- init_regexes();
12224
- init_locales();
12225
12232
  init_registries();
12226
12233
  init_api();
12227
12234
  init_to_json_schema();
12228
- init_json_schema_processors();
12229
- init_json_schema_generator();
12230
- init_json_schema();
12231
12235
  });
12232
12236
 
12233
12237
  // node_modules/zod/v4/classic/checks.js
@@ -14614,11 +14618,6 @@ __export(exports_external, {
14614
14618
  });
14615
14619
  var init_external = __esm(() => {
14616
14620
  init_core2();
14617
- init_schemas2();
14618
- init_checks2();
14619
- init_errors2();
14620
- init_parse2();
14621
- init_compat();
14622
14621
  init_core2();
14623
14622
  init_en();
14624
14623
  init_core2();
@@ -14628,6 +14627,11 @@ var init_external = __esm(() => {
14628
14627
  init_iso();
14629
14628
  init_iso();
14630
14629
  init_coerce();
14630
+ init_schemas2();
14631
+ init_checks2();
14632
+ init_errors2();
14633
+ init_parse2();
14634
+ init_compat();
14631
14635
  config(en_default());
14632
14636
  });
14633
14637
 
@@ -14679,28 +14683,28 @@ var init_domain = __esm(() => {
14679
14683
  "disabled"
14680
14684
  ]);
14681
14685
  AccountFieldsSchema = exports_external.object({
14686
+ createdAt: exports_external.iso.datetime(),
14687
+ enabled: exports_external.boolean(),
14688
+ externalAccountId: exports_external.string().trim().min(1).nullable(),
14689
+ health: HealthStateSchema,
14682
14690
  id: exports_external.uuid(),
14683
- label: AccountEmailSchema,
14684
14691
  identity: AccountEmailSchema,
14685
- externalAccountId: exports_external.string().trim().min(1).nullable(),
14692
+ label: AccountEmailSchema,
14686
14693
  plan: exports_external.string().trim().min(1).nullish(),
14687
- health: HealthStateSchema,
14688
- enabled: exports_external.boolean(),
14689
- createdAt: exports_external.iso.datetime(),
14690
14694
  updatedAt: exports_external.iso.datetime()
14691
14695
  });
14692
14696
  AccountSchema = exports_external.discriminatedUnion("provider", [
14693
14697
  AccountFieldsSchema.extend({
14694
- provider: exports_external.literal("openai"),
14695
14698
  externalUserId: exports_external.string().trim().min(1).nullable().default(null),
14696
- secretReference: exports_external.string().trim().min(1),
14697
- profilePath: exports_external.null()
14699
+ profilePath: exports_external.null(),
14700
+ provider: exports_external.literal("openai"),
14701
+ secretReference: exports_external.string().trim().min(1)
14698
14702
  }).strict(),
14699
14703
  AccountFieldsSchema.extend({
14700
- provider: exports_external.literal("anthropic"),
14701
14704
  externalUserId: exports_external.null().default(null),
14702
- secretReference: exports_external.null(),
14703
- profilePath: exports_external.string().trim().min(1)
14705
+ profilePath: exports_external.string().trim().min(1),
14706
+ provider: exports_external.literal("anthropic"),
14707
+ secretReference: exports_external.null()
14704
14708
  }).strict()
14705
14709
  ]).refine((account) => account.label === account.identity, {
14706
14710
  message: "Account label must equal its authenticated email identity",
@@ -14708,16 +14712,16 @@ var init_domain = __esm(() => {
14708
14712
  });
14709
14713
  UsageWindowSchema = exports_external.object({
14710
14714
  id: exports_external.string().trim().min(1),
14715
+ kind: exports_external.enum(["hard", "soft", "spend"]),
14711
14716
  label: exports_external.string().trim().min(1),
14712
- usedPercent: exports_external.number().min(0).max(100),
14713
14717
  resetAt: exports_external.iso.datetime().nullable(),
14714
- kind: exports_external.enum(["hard", "soft", "spend"])
14718
+ usedPercent: exports_external.number().min(0).max(100)
14715
14719
  }).strict();
14716
14720
  UsageSnapshotFieldsSchema = exports_external.object({
14717
14721
  accountId: exports_external.uuid(),
14722
+ hardLimitReached: exports_external.boolean(),
14718
14723
  observedAt: exports_external.iso.datetime(),
14719
- windows: exports_external.array(UsageWindowSchema),
14720
- hardLimitReached: exports_external.boolean()
14724
+ windows: exports_external.array(UsageWindowSchema)
14721
14725
  });
14722
14726
  UsageSnapshotSchema = exports_external.discriminatedUnion("provider", [
14723
14727
  UsageSnapshotFieldsSchema.extend({
@@ -14731,23 +14735,23 @@ var init_domain = __esm(() => {
14731
14735
  ]);
14732
14736
  AuthorizationStateSchema = exports_external.enum(["notConfirmed", "confirmed"]);
14733
14737
  AutomationPolicySchema = exports_external.object({
14734
- provider: ProviderIdSchema,
14738
+ authorization: AuthorizationStateSchema.default("notConfirmed"),
14735
14739
  enabled: exports_external.boolean(),
14736
- thresholdPercent: exports_external.number().min(1).max(100).default(95),
14737
14740
  hysteresisPercent: exports_external.number().min(0).max(25).default(5),
14738
- minimumDwellMilliseconds: exports_external.number().int().min(0).default(300000),
14739
14741
  maximumSnapshotAgeMilliseconds: exports_external.number().int().positive().default(120000),
14740
- authorization: AuthorizationStateSchema.default("notConfirmed")
14742
+ minimumDwellMilliseconds: exports_external.number().int().min(0).default(300000),
14743
+ provider: ProviderIdSchema,
14744
+ thresholdPercent: exports_external.number().min(1).max(100).default(95)
14741
14745
  }).strict().refine((policy) => policy.hysteresisPercent < policy.thresholdPercent, {
14742
14746
  message: "hysteresisPercent must be lower than thresholdPercent",
14743
14747
  path: ["hysteresisPercent"]
14744
14748
  });
14745
14749
  ProviderStateSchema = exports_external.object({
14746
- provider: ProviderIdSchema,
14747
14750
  activeAccountId: exports_external.uuid().nullable(),
14748
14751
  generation: exports_external.number().int().nonnegative(),
14749
- switchedAt: exports_external.iso.datetime().nullable(),
14750
- policy: AutomationPolicySchema
14752
+ policy: AutomationPolicySchema,
14753
+ provider: ProviderIdSchema,
14754
+ switchedAt: exports_external.iso.datetime().nullable()
14751
14755
  }).strict().refine((state) => state.provider === state.policy.provider, {
14752
14756
  message: "Provider state and automation policy must target the same provider",
14753
14757
  path: ["policy", "provider"]
@@ -14763,28 +14767,28 @@ var init_domain = __esm(() => {
14763
14767
  "failed"
14764
14768
  ]);
14765
14769
  SwitchRecordSchema = exports_external.object({
14770
+ createdAt: exports_external.iso.datetime(),
14771
+ generation: exports_external.number().int().positive(),
14766
14772
  id: exports_external.uuid(),
14773
+ message: exports_external.string().nullable(),
14774
+ phase: SwitchPhaseSchema,
14767
14775
  provider: ProviderIdSchema,
14776
+ reason: exports_external.string().trim().min(1),
14768
14777
  sourceAccountId: exports_external.uuid().nullable(),
14769
14778
  targetAccountId: exports_external.uuid(),
14770
- phase: SwitchPhaseSchema,
14771
- reason: exports_external.string().trim().min(1),
14772
- generation: exports_external.number().int().positive(),
14773
- message: exports_external.string().nullable(),
14774
- createdAt: exports_external.iso.datetime(),
14775
14779
  updatedAt: exports_external.iso.datetime()
14776
14780
  }).strict();
14777
14781
  DashboardSnapshotSchema = exports_external.object({
14778
14782
  accounts: exports_external.array(AccountSchema),
14779
- usage: exports_external.array(UsageSnapshotSchema),
14780
14783
  providers: exports_external.array(ProviderStateSchema),
14781
- sampledAt: exports_external.iso.datetime()
14784
+ sampledAt: exports_external.iso.datetime(),
14785
+ usage: exports_external.array(UsageSnapshotSchema)
14782
14786
  }).strict();
14783
14787
  UsageHistoryPointSchema = exports_external.object({ at: exports_external.number().int().nonnegative(), usedPercent: exports_external.number().min(0).max(100) }).strict();
14784
14788
  UsageHistorySchema = exports_external.object({
14785
- windowId: exports_external.string().min(1),
14786
14789
  label: exports_external.string().min(1),
14787
- points: exports_external.array(UsageHistoryPointSchema)
14790
+ points: exports_external.array(UsageHistoryPointSchema),
14791
+ windowId: exports_external.string().min(1)
14788
14792
  }).strict();
14789
14793
  TIMEFRAMES = [
14790
14794
  { key: "1h", label: "1h", ms: 3600000 },
@@ -14794,30 +14798,30 @@ var init_domain = __esm(() => {
14794
14798
  { key: "31d", label: "31d", ms: 31 * 24 * 3600000 }
14795
14799
  ];
14796
14800
  TokenEventSchema = exports_external.object({
14797
- at: exports_external.number().int().nonnegative(),
14798
- provider: ProviderIdSchema,
14799
14801
  accountId: exports_external.uuid().nullable(),
14800
- model: exports_external.string().min(1).nullable(),
14802
+ at: exports_external.number().int().nonnegative(),
14801
14803
  inputTokens: exports_external.number().int().nonnegative(),
14802
- outputTokens: exports_external.number().int().nonnegative()
14804
+ model: exports_external.string().min(1).nullable(),
14805
+ outputTokens: exports_external.number().int().nonnegative(),
14806
+ provider: ProviderIdSchema
14803
14807
  }).strict();
14804
- TokenProviderTotalSchema = exports_external.object({ tokens: exports_external.number().nonnegative(), costUsd: exports_external.number().nonnegative() }).strict();
14808
+ TokenProviderTotalSchema = exports_external.object({ costUsd: exports_external.number().nonnegative(), tokens: exports_external.number().nonnegative() }).strict();
14805
14809
  TokenTimeframeSchema = exports_external.object({
14806
- key: exports_external.string(),
14807
- buckets: exports_external.array(exports_external.number().nonnegative()),
14808
14810
  bucketMs: exports_external.number().positive(),
14809
- totalTokens: exports_external.number().nonnegative(),
14810
- totalInput: exports_external.number().nonnegative(),
14811
- totalOutput: exports_external.number().nonnegative(),
14811
+ buckets: exports_external.array(exports_external.number().nonnegative()),
14812
+ byProvider: exports_external.object({ anthropic: TokenProviderTotalSchema, openai: TokenProviderTotalSchema }).strict(),
14812
14813
  costUsd: exports_external.number().nonnegative(),
14814
+ key: exports_external.string(),
14813
14815
  peakPerHour: exports_external.number().nonnegative(),
14814
14816
  topModel: exports_external.string().nullable(),
14815
- byProvider: exports_external.object({ openai: TokenProviderTotalSchema, anthropic: TokenProviderTotalSchema }).strict()
14817
+ totalInput: exports_external.number().nonnegative(),
14818
+ totalOutput: exports_external.number().nonnegative(),
14819
+ totalTokens: exports_external.number().nonnegative()
14816
14820
  }).strict();
14817
14821
  TokenAnalyticsSchema = exports_external.object({ timeframes: exports_external.array(TokenTimeframeSchema) }).strict();
14818
14822
  AnalyticsSnapshotSchema = exports_external.object({
14819
- snapshot: DashboardSnapshotSchema,
14820
14823
  history: exports_external.array(exports_external.object({ accountId: exports_external.uuid(), windows: exports_external.array(UsageHistorySchema) }).strict()),
14824
+ snapshot: DashboardSnapshotSchema,
14821
14825
  tokens: TokenAnalyticsSchema.nullish()
14822
14826
  }).strict();
14823
14827
  });
@@ -14832,7 +14836,7 @@ function writeResponse(socket, response) {
14832
14836
  async function dispatch(manager, method, params) {
14833
14837
  switch (method) {
14834
14838
  case "manager/ping":
14835
- return { ready: true, processId: process.pid };
14839
+ return { processId: process.pid, ready: true };
14836
14840
  case "dashboard/read":
14837
14841
  return manager.dashboard();
14838
14842
  case "usage/refresh":
@@ -14888,16 +14892,16 @@ async function startManagerServer(input) {
14888
14892
  decoded = JSON.parse(line);
14889
14893
  } catch {
14890
14894
  writeResponse(socket, {
14891
- id: 0,
14892
- error: { code: "INVALID_JSON", message: "Request is not valid JSON" }
14895
+ error: { code: "INVALID_JSON", message: "Request is not valid JSON" },
14896
+ id: 0
14893
14897
  });
14894
14898
  return;
14895
14899
  }
14896
14900
  const parsed = RpcRequestSchema.safeParse(decoded);
14897
14901
  if (!parsed.success) {
14898
14902
  writeResponse(socket, {
14899
- id: 0,
14900
- error: { code: "INVALID_REQUEST", message: exports_external.prettifyError(parsed.error) }
14903
+ error: { code: "INVALID_REQUEST", message: exports_external.prettifyError(parsed.error) },
14904
+ id: 0
14901
14905
  });
14902
14906
  return;
14903
14907
  }
@@ -14911,11 +14915,11 @@ async function startManagerServer(input) {
14911
14915
  writeResponse(socket, { id: parsed.data.id, result });
14912
14916
  } catch (error51) {
14913
14917
  writeResponse(socket, {
14914
- id: parsed.data.id,
14915
14918
  error: {
14916
14919
  code: error51 instanceof ApplicationError ? error51.code : "INTERNAL_ERROR",
14917
14920
  message: errorMessage(error51)
14918
- }
14921
+ },
14922
+ id: parsed.data.id
14919
14923
  });
14920
14924
  }
14921
14925
  })();
@@ -14975,59 +14979,59 @@ async function managerRequest(input) {
14975
14979
  }
14976
14980
  async function managerAvailable(socketPath) {
14977
14981
  return managerRequest({
14978
- socketPath,
14979
14982
  method: "manager/ping",
14980
- schema: exports_external.object({ ready: exports_external.literal(true), processId: exports_external.number().int().positive() }),
14983
+ schema: exports_external.object({ processId: exports_external.number().int().positive(), ready: exports_external.literal(true) }),
14984
+ socketPath,
14981
14985
  timeoutMilliseconds: 500
14982
14986
  }).then(() => true).catch(() => false);
14983
14987
  }
14984
14988
  function readDashboard(socketPath) {
14985
14989
  return managerRequest({
14986
- socketPath,
14987
14990
  method: "dashboard/read",
14988
14991
  schema: DashboardSnapshotSchema,
14992
+ socketPath,
14989
14993
  timeoutMilliseconds: 15000
14990
14994
  });
14991
14995
  }
14992
14996
  function readAnalytics(socketPath) {
14993
14997
  return managerRequest({
14994
- socketPath,
14995
14998
  method: "dashboard/analytics",
14996
14999
  schema: AnalyticsSnapshotSchema,
15000
+ socketPath,
14997
15001
  timeoutMilliseconds: 15000
14998
15002
  });
14999
15003
  }
15000
15004
  function refreshUsage(socketPath) {
15001
15005
  return managerRequest({
15002
- socketPath,
15003
15006
  method: "usage/refresh",
15004
15007
  schema: DashboardSnapshotSchema,
15008
+ socketPath,
15005
15009
  timeoutMilliseconds: 60000
15006
15010
  });
15007
15011
  }
15008
15012
  function requestSwitch(socketPath, provider, targetAccountId) {
15009
15013
  return managerRequest({
15010
- socketPath,
15011
15014
  method: "provider/switch",
15012
- params: { provider, targetAccountId, reason: "manual" },
15015
+ params: { provider, reason: "manual", targetAccountId },
15013
15016
  schema: DashboardSnapshotSchema,
15017
+ socketPath,
15014
15018
  timeoutMilliseconds: 30000
15015
15019
  });
15016
15020
  }
15017
15021
  function readProxyPort(socketPath) {
15018
15022
  return managerRequest({
15019
- socketPath,
15020
15023
  method: "proxy/port",
15021
15024
  schema: exports_external.object({ port: exports_external.number().int().positive() }),
15025
+ socketPath,
15022
15026
  timeoutMilliseconds: 15000
15023
15027
  }).then((result) => result.port);
15024
15028
  }
15025
15029
  function requestPolicy(socketPath, input) {
15026
15030
  return managerRequest({
15027
- socketPath,
15028
15031
  method: "policy/set",
15029
15032
  params: input,
15030
15033
  schema: exports_external.unknown(),
15034
+ socketPath,
15031
15035
  timeoutMilliseconds: 15000
15032
15036
  }).then(() => {
15033
15037
  return;
@@ -15035,10 +15039,10 @@ function requestPolicy(socketPath, input) {
15035
15039
  }
15036
15040
  function requestAccountSave(socketPath, account, removePrevious) {
15037
15041
  return managerRequest({
15038
- socketPath,
15039
15042
  method: "account/save",
15040
15043
  params: { account, removePrevious },
15041
15044
  schema: exports_external.object({ saved: exports_external.literal(true) }),
15045
+ socketPath,
15042
15046
  timeoutMilliseconds: 15000
15043
15047
  }).then(() => {
15044
15048
  return;
@@ -15055,26 +15059,26 @@ var init_ipc = __esm(() => {
15055
15059
  params: exports_external.unknown().optional()
15056
15060
  }).strict();
15057
15061
  RpcResponseSchema = exports_external.object({
15062
+ error: exports_external.object({ code: exports_external.string(), message: exports_external.string() }).strict().optional(),
15058
15063
  id: exports_external.literal(1),
15059
- result: exports_external.unknown().optional(),
15060
- error: exports_external.object({ code: exports_external.string(), message: exports_external.string() }).strict().optional()
15064
+ result: exports_external.unknown().optional()
15061
15065
  }).strict().refine((response) => response.result === undefined !== (response.error === undefined), {
15062
15066
  message: "Manager response must contain exactly one result or error"
15063
15067
  });
15064
15068
  SwitchParamsSchema = exports_external.object({
15065
15069
  provider: ProviderIdSchema,
15066
- targetAccountId: exports_external.uuid(),
15067
- reason: exports_external.string().min(1).optional()
15070
+ reason: exports_external.string().min(1).optional(),
15071
+ targetAccountId: exports_external.uuid()
15068
15072
  }).strict();
15069
15073
  PolicyParamsSchema = exports_external.object({
15070
- provider: ProviderIdSchema,
15074
+ authorizationConfirmed: exports_external.boolean().optional(),
15071
15075
  enabled: exports_external.boolean(),
15072
- thresholdPercent: exports_external.number().min(1).max(100).optional(),
15073
- authorizationConfirmed: exports_external.boolean().optional()
15076
+ provider: ProviderIdSchema,
15077
+ thresholdPercent: exports_external.number().min(1).max(100).optional()
15074
15078
  }).strict();
15075
15079
  ReplaceCredentialParamsSchema = exports_external.object({
15076
15080
  account: AccountSchema,
15077
- removePrevious: exports_external.object({ secretReference: exports_external.string().nullable(), profilePath: exports_external.string().nullable() }).strict()
15081
+ removePrevious: exports_external.object({ profilePath: exports_external.string().nullable(), secretReference: exports_external.string().nullable() }).strict()
15078
15082
  }).strict();
15079
15083
  });
15080
15084
 
@@ -15247,17 +15251,17 @@ function healthBadge(theme, account) {
15247
15251
  case "refreshing":
15248
15252
  return null;
15249
15253
  case "loginExpiring":
15250
- return { text: "\u26A0 expiring", color: theme.warn };
15254
+ return { color: theme.warn, text: "\u26A0 expiring" };
15251
15255
  case "scopeMissing":
15252
- return { text: "\u26A0 scope", color: theme.warn };
15256
+ return { color: theme.warn, text: "\u26A0 scope" };
15253
15257
  case "reauthenticationRequired":
15254
- return { text: "\u26A0 login", color: theme.bad };
15258
+ return { color: theme.bad, text: "\u26A0 login" };
15255
15259
  case "temporarilyUnreachable":
15256
- return { text: "\xB7 offline", color: theme.warn };
15260
+ return { color: theme.warn, text: "\xB7 offline" };
15257
15261
  case "usageRateLimited":
15258
- return { text: "\xB7 limited", color: theme.warn };
15262
+ return { color: theme.warn, text: "\xB7 limited" };
15259
15263
  case "disabled":
15260
- return { text: "\xB7 off", color: theme.dim };
15264
+ return { color: theme.dim, text: "\xB7 off" };
15261
15265
  }
15262
15266
  }
15263
15267
  function shortWindow(label) {
@@ -15315,30 +15319,30 @@ var darkTheme, lightTheme, themes, brailleDots;
15315
15319
  var init_format = __esm(() => {
15316
15320
  init_domain();
15317
15321
  darkTheme = {
15318
- fg: "#e6e6e6",
15319
- dim: "#8b93a1",
15320
- faint: "#4b515c",
15321
15322
  accent: "#5ab0ff",
15323
+ bad: "#ff5f6e",
15322
15324
  bg: "#0b0d10",
15323
- panel: "#0f1216",
15324
- selected: "#1b2330",
15325
15325
  border: "#2a3038",
15326
+ dim: "#8b93a1",
15327
+ faint: "#4b515c",
15328
+ fg: "#e6e6e6",
15326
15329
  good: "#3ad07a",
15327
- warn: "#f0a83a",
15328
- bad: "#ff5f6e"
15330
+ panel: "#0f1216",
15331
+ selected: "#1b2330",
15332
+ warn: "#f0a83a"
15329
15333
  };
15330
15334
  lightTheme = {
15331
- fg: "#1c2430",
15332
- dim: "#5a6472",
15333
- faint: "#aab2bd",
15334
15335
  accent: "#0b62d6",
15336
+ bad: "#d23b48",
15335
15337
  bg: "#fbfcfe",
15336
- panel: "#f2f4f8",
15337
- selected: "#e3e9f2",
15338
15338
  border: "#c7cedb",
15339
+ dim: "#5a6472",
15340
+ faint: "#aab2bd",
15341
+ fg: "#1c2430",
15339
15342
  good: "#1f9d57",
15340
- warn: "#b9770f",
15341
- bad: "#d23b48"
15343
+ panel: "#f2f4f8",
15344
+ selected: "#e3e9f2",
15345
+ warn: "#b9770f"
15342
15346
  };
15343
15347
  themes = { dark: darkTheme, light: lightTheme };
15344
15348
  brailleDots = [
@@ -15370,19 +15374,19 @@ function buildTokens(scale) {
15370
15374
  const bucketMs = timeframe.ms / 120;
15371
15375
  const peakBucket = buckets.reduce((max, value) => Math.max(max, value), 0);
15372
15376
  return {
15373
- key: timeframe.key,
15374
- buckets,
15375
15377
  bucketMs,
15376
- totalTokens,
15377
- totalInput,
15378
- totalOutput: totalTokens - totalInput,
15378
+ buckets,
15379
+ byProvider: {
15380
+ anthropic: { costUsd: claudeCost, tokens: claudeTokens },
15381
+ openai: { costUsd: codexCost, tokens: codexTokens }
15382
+ },
15379
15383
  costUsd: codexCost + claudeCost,
15384
+ key: timeframe.key,
15380
15385
  peakPerHour: Math.round(peakBucket * (3600000 / bucketMs)),
15381
15386
  topModel: totalTokens === 0 ? null : "claude-opus-4-8",
15382
- byProvider: {
15383
- openai: { tokens: codexTokens, costUsd: codexCost },
15384
- anthropic: { tokens: claudeTokens, costUsd: claudeCost }
15385
- }
15387
+ totalInput,
15388
+ totalOutput: totalTokens - totalInput,
15389
+ totalTokens
15386
15390
  };
15387
15391
  });
15388
15392
  return { timeframes };
@@ -15404,10 +15408,10 @@ function valueAt(spec, at, now) {
15404
15408
  function toWindow2(spec, now) {
15405
15409
  return {
15406
15410
  id: spec.id,
15411
+ kind: "hard",
15407
15412
  label: spec.label,
15408
- usedPercent: Math.round(valueAt(spec, now, now)),
15409
15413
  resetAt: new Date(now + (1 - spec.nowFrac) * spec.period).toISOString(),
15410
- kind: "hard"
15414
+ usedPercent: Math.round(valueAt(spec, now, now))
15411
15415
  };
15412
15416
  }
15413
15417
  function toHistory(spec, now) {
@@ -15420,76 +15424,76 @@ function toHistory(spec, now) {
15420
15424
  for (let at = fine;at <= now; at += 10 * MINUTE) {
15421
15425
  points.push({ at, usedPercent: Math.round(valueAt(spec, at, now)) });
15422
15426
  }
15423
- return { windowId: spec.id, label: spec.label, points };
15427
+ return { label: spec.label, points, windowId: spec.id };
15424
15428
  }
15425
15429
  function account(seed, now) {
15426
15430
  const base = {
15431
+ createdAt: new Date(now - 34 * DAY).toISOString(),
15432
+ enabled: true,
15433
+ externalAccountId: `acct_${seed.n.toString().padStart(4, "0")}`,
15434
+ health: seed.health ?? "ready",
15427
15435
  id: uuid3(seed.n),
15428
- label: seed.email,
15429
15436
  identity: seed.email,
15430
- externalAccountId: `acct_${seed.n.toString().padStart(4, "0")}`,
15437
+ label: seed.email,
15431
15438
  plan: seed.plan,
15432
- health: seed.health ?? "ready",
15433
- enabled: true,
15434
- createdAt: new Date(now - 34 * DAY).toISOString(),
15435
15439
  updatedAt: new Date(now - 40 * MINUTE).toISOString()
15436
15440
  };
15437
15441
  return seed.provider === "openai" ? {
15438
15442
  ...base,
15439
- provider: "openai",
15440
15443
  externalUserId: `user_${seed.n}`,
15441
- secretReference: `codex:${base.externalAccountId}`,
15442
- profilePath: null
15444
+ profilePath: null,
15445
+ provider: "openai",
15446
+ secretReference: `codex:${base.externalAccountId}`
15443
15447
  } : {
15444
15448
  ...base,
15445
- provider: "anthropic",
15446
15449
  externalUserId: null,
15447
- secretReference: null,
15448
- profilePath: `/tmp/tokenmaxx/claude/${seed.n}`
15450
+ profilePath: `/tmp/tokenmaxx/claude/${seed.n}`,
15451
+ provider: "anthropic",
15452
+ secretReference: null
15449
15453
  };
15450
15454
  }
15451
15455
  function usage(seed, now) {
15452
15456
  const windows = (seed.windows ?? []).map((spec) => toWindow2(spec, now));
15453
15457
  const base = {
15454
15458
  accountId: uuid3(seed.n),
15459
+ hardLimitReached: windows.some((window) => window.usedPercent >= 100),
15455
15460
  observedAt: new Date(now - 40 * MINUTE).toISOString(),
15456
- windows,
15457
- hardLimitReached: windows.some((window) => window.usedPercent >= 100)
15461
+ windows
15458
15462
  };
15459
15463
  return seed.provider === "openai" ? { ...base, provider: "openai", source: "codexUsageEndpoint" } : { ...base, provider: "anthropic", source: "claudeUsageEndpoint" };
15460
15464
  }
15461
15465
  function policy(provider, enabled, thresholdPercent = 95) {
15462
15466
  return {
15463
- provider,
15467
+ authorization: enabled ? "confirmed" : "notConfirmed",
15464
15468
  enabled,
15465
- thresholdPercent,
15466
15469
  hysteresisPercent: 5,
15467
- minimumDwellMilliseconds: 300000,
15468
15470
  maximumSnapshotAgeMilliseconds: 120000,
15469
- authorization: enabled ? "confirmed" : "notConfirmed"
15471
+ minimumDwellMilliseconds: 300000,
15472
+ provider,
15473
+ thresholdPercent
15470
15474
  };
15471
15475
  }
15472
15476
  function providerState(seed, now) {
15473
15477
  return {
15474
- provider: seed.provider,
15475
15478
  activeAccountId: seed.activeN === null ? null : uuid3(seed.activeN),
15476
15479
  generation: seed.generation,
15477
- switchedAt: seed.switchedMinutesAgo === null ? null : new Date(now - seed.switchedMinutesAgo * MINUTE).toISOString(),
15478
- policy: policy(seed.provider, seed.auto, seed.threshold)
15480
+ policy: policy(seed.provider, seed.auto, seed.threshold),
15481
+ provider: seed.provider,
15482
+ switchedAt: seed.switchedMinutesAgo === null ? null : new Date(now - seed.switchedMinutesAgo * MINUTE).toISOString()
15479
15483
  };
15480
15484
  }
15481
15485
  function assemble(now, accounts, providers, tokenScale = 1) {
15482
15486
  return AnalyticsSnapshotSchema.parse({
15483
- snapshot: {
15484
- accounts: accounts.map((seed) => account(seed, now)),
15485
- usage: accounts.map((seed) => usage(seed, now)),
15486
- providers: providers.map((seed) => providerState(seed, now)),
15487
- sampledAt: new Date(now - 40 * MINUTE).toISOString()
15488
- },
15489
15487
  history: accounts.map((seed) => ({
15490
15488
  accountId: uuid3(seed.n),
15491
15489
  windows: (seed.windows ?? []).map((spec) => toHistory(spec, now))
15492
15490
  })),
15491
+ snapshot: {
15492
+ accounts: accounts.map((seed) => account(seed, now)),
15493
+ providers: providers.map((seed) => providerState(seed, now)),
15494
+ sampledAt: new Date(now - 40 * MINUTE).toISOString(),
15495
+ usage: accounts.map((seed) => usage(seed, now))
15496
+ },
15493
15497
  tokens: buildTokens(tokenScale)
15494
15498
  });
15495
15499
  }
@@ -15501,139 +15505,139 @@ function buildScenario(name, now = FIXTURE_NOW) {
15501
15505
  return builder(now);
15502
15506
  }
15503
15507
  var MINUTE = 60000, HOUR = 3600000, DAY, FIXTURE_NOW, fiveHour = (peak, nowFrac, seed) => ({
15508
+ fillFrac: 0.92,
15504
15509
  id: "five-hour",
15505
15510
  label: "5 hour",
15506
- period: 5 * HOUR,
15507
- peak,
15508
15511
  nowFrac,
15509
- fillFrac: 0.92,
15510
- wobble: 4,
15511
- seed
15512
+ peak,
15513
+ period: 5 * HOUR,
15514
+ seed,
15515
+ wobble: 4
15512
15516
  }), weekly = (peak, nowFrac, seed) => ({
15517
+ fillFrac: 1,
15513
15518
  id: "weekly",
15514
15519
  label: "7 day \xB7 all models",
15515
- period: 7 * DAY,
15516
- peak,
15517
15520
  nowFrac,
15518
- fillFrac: 1,
15519
- wobble: 2,
15520
- seed
15521
+ peak,
15522
+ period: 7 * DAY,
15523
+ seed,
15524
+ wobble: 2
15521
15525
  }), fable = (peak, nowFrac, seed) => ({
15526
+ fillFrac: 1,
15522
15527
  id: "weekly_scoped:fable",
15523
15528
  label: "7 day \xB7 Fable",
15524
- period: 7 * DAY,
15525
- peak,
15526
15529
  nowFrac,
15527
- fillFrac: 1,
15528
- wobble: 3,
15529
- seed
15530
+ peak,
15531
+ period: 7 * DAY,
15532
+ seed,
15533
+ wobble: 3
15530
15534
  }), claudeSession = (peak, nowFrac, seed) => ({
15531
15535
  ...fiveHour(peak, nowFrac, seed),
15532
15536
  label: "5h session"
15533
15537
  }), cruising = (now) => assemble(now, [
15534
15538
  {
15535
- n: 1,
15536
- provider: "openai",
15537
15539
  email: "dexter@rubriclabs.com",
15540
+ n: 1,
15538
15541
  plan: "pro",
15542
+ provider: "openai",
15539
15543
  windows: [fiveHour(58, 0.62, 11), weekly(44, 0.63, 21)]
15540
15544
  },
15541
15545
  {
15542
- n: 2,
15543
- provider: "openai",
15544
15546
  email: "ship@rubriclabs.com",
15547
+ n: 2,
15545
15548
  plan: "pro",
15549
+ provider: "openai",
15546
15550
  windows: [fiveHour(21, 0.3, 12), weekly(33, 0.61, 22)]
15547
15551
  },
15548
15552
  {
15549
- n: 3,
15550
- provider: "anthropic",
15551
15553
  email: "dexter@rubriclabs.com",
15554
+ n: 3,
15552
15555
  plan: "claude_max_20x",
15556
+ provider: "anthropic",
15553
15557
  windows: [claudeSession(47, 0.55, 31), weekly(29, 0.5, 41), fable(38, 0.44, 51)]
15554
15558
  },
15555
15559
  {
15556
- n: 4,
15557
- provider: "anthropic",
15558
15560
  email: "research@rubriclabs.com",
15561
+ n: 4,
15559
15562
  plan: "claude_max_5x",
15563
+ provider: "anthropic",
15560
15564
  windows: [claudeSession(18, 0.24, 32), weekly(22, 0.4, 42), fable(12, 0.2, 52)]
15561
15565
  }
15562
15566
  ], [
15563
- { provider: "openai", activeN: 1, generation: 4, switchedMinutesAgo: 96, auto: true },
15564
- { provider: "anthropic", activeN: 3, generation: 2, switchedMinutesAgo: 210, auto: true }
15567
+ { activeN: 1, auto: true, generation: 4, provider: "openai", switchedMinutesAgo: 96 },
15568
+ { activeN: 3, auto: true, generation: 2, provider: "anthropic", switchedMinutesAgo: 210 }
15565
15569
  ]), oneHot = (now) => assemble(now, [
15566
15570
  {
15567
- n: 1,
15568
- provider: "openai",
15569
15571
  email: "dexter@rubriclabs.com",
15572
+ n: 1,
15570
15573
  plan: "pro",
15574
+ provider: "openai",
15571
15575
  windows: [fiveHour(99, 0.87, 11), weekly(72, 0.7, 21)]
15572
15576
  },
15573
15577
  {
15574
- n: 2,
15575
- provider: "openai",
15576
15578
  email: "ship@rubriclabs.com",
15579
+ n: 2,
15577
15580
  plan: "pro",
15581
+ provider: "openai",
15578
15582
  windows: [fiveHour(23, 0.28, 12), weekly(41, 0.6, 22)]
15579
15583
  },
15580
15584
  {
15581
- n: 3,
15582
- provider: "anthropic",
15583
15585
  email: "dexter@rubriclabs.com",
15586
+ n: 3,
15584
15587
  plan: "claude_max_20x",
15588
+ provider: "anthropic",
15585
15589
  windows: [claudeSession(63, 0.6, 31), weekly(48, 0.62, 41), fable(97, 0.9, 51)]
15586
15590
  },
15587
15591
  {
15588
- n: 4,
15589
- provider: "anthropic",
15590
15592
  email: "research@rubriclabs.com",
15593
+ n: 4,
15591
15594
  plan: "claude_max_5x",
15595
+ provider: "anthropic",
15592
15596
  windows: [claudeSession(31, 0.35, 32), weekly(27, 0.45, 42), fable(19, 0.3, 52)]
15593
15597
  }
15594
15598
  ], [
15595
- { provider: "openai", activeN: 1, generation: 7, switchedMinutesAgo: 288, auto: true },
15596
- { provider: "anthropic", activeN: 3, generation: 3, switchedMinutesAgo: 420, auto: true }
15599
+ { activeN: 1, auto: true, generation: 7, provider: "openai", switchedMinutesAgo: 288 },
15600
+ { activeN: 3, auto: true, generation: 3, provider: "anthropic", switchedMinutesAgo: 420 }
15597
15601
  ]), rotated = (now) => assemble(now, [
15598
15602
  {
15599
- n: 2,
15600
- provider: "openai",
15601
15603
  email: "ship@rubriclabs.com",
15604
+ n: 2,
15602
15605
  plan: "pro",
15606
+ provider: "openai",
15603
15607
  windows: [fiveHour(19, 0.22, 12), weekly(38, 0.58, 22)]
15604
15608
  },
15605
15609
  {
15606
- n: 1,
15607
- provider: "openai",
15608
15610
  email: "dexter@rubriclabs.com",
15611
+ n: 1,
15609
15612
  plan: "pro",
15613
+ provider: "openai",
15610
15614
  windows: [fiveHour(96, 0.95, 11), weekly(74, 0.72, 21)]
15611
15615
  },
15612
15616
  {
15613
- n: 3,
15614
- provider: "anthropic",
15615
15617
  email: "dexter@rubriclabs.com",
15618
+ n: 3,
15616
15619
  plan: "claude_max_20x",
15620
+ provider: "anthropic",
15617
15621
  windows: [claudeSession(44, 0.5, 31), weekly(46, 0.6, 41), fable(52, 0.55, 51)]
15618
15622
  },
15619
15623
  {
15620
- n: 4,
15621
- provider: "anthropic",
15622
15624
  email: "research@rubriclabs.com",
15625
+ n: 4,
15623
15626
  plan: "claude_max_5x",
15627
+ provider: "anthropic",
15624
15628
  windows: [claudeSession(16, 0.2, 32), weekly(24, 0.42, 42), fable(14, 0.24, 52)]
15625
15629
  }
15626
15630
  ], [
15627
- { provider: "openai", activeN: 2, generation: 8, switchedMinutesAgo: 2, auto: true },
15628
- { provider: "anthropic", activeN: 3, generation: 3, switchedMinutesAgo: 420, auto: true }
15631
+ { activeN: 2, auto: true, generation: 8, provider: "openai", switchedMinutesAgo: 2 },
15632
+ { activeN: 3, auto: true, generation: 3, provider: "anthropic", switchedMinutesAgo: 420 }
15629
15633
  ]), onboarding = (now) => assemble(now, [], [
15630
- { provider: "openai", activeN: null, generation: 0, switchedMinutesAgo: null, auto: false },
15634
+ { activeN: null, auto: false, generation: 0, provider: "openai", switchedMinutesAgo: null },
15631
15635
  {
15632
- provider: "anthropic",
15633
15636
  activeN: null,
15637
+ auto: false,
15634
15638
  generation: 0,
15635
- switchedMinutesAgo: null,
15636
- auto: false
15639
+ provider: "anthropic",
15640
+ switchedMinutesAgo: null
15637
15641
  }
15638
15642
  ], 0), scenarios, SCENARIO_NAMES;
15639
15643
  var init_fixtures = __esm(() => {
@@ -15642,7 +15646,7 @@ var init_fixtures = __esm(() => {
15642
15646
  init_format();
15643
15647
  DAY = 24 * HOUR;
15644
15648
  FIXTURE_NOW = Date.parse("2026-07-15T16:42:00.000Z");
15645
- scenarios = { cruising, oneHot, rotated, onboarding };
15649
+ scenarios = { cruising, onboarding, oneHot, rotated };
15646
15650
  SCENARIO_NAMES = Object.keys(scenarios);
15647
15651
  });
15648
15652
 
@@ -15677,7 +15681,7 @@ function orderedRows(snapshot) {
15677
15681
  return active !== 0 ? active : left.label.localeCompare(right.label);
15678
15682
  });
15679
15683
  for (const account2 of accounts) {
15680
- rows.push({ provider, accountId: account2.id });
15684
+ rows.push({ accountId: account2.id, provider });
15681
15685
  }
15682
15686
  }
15683
15687
  return rows;
@@ -15689,9 +15693,9 @@ function accountLine(ctx, account2, windows, isActive, isSelected) {
15689
15693
  const children = [
15690
15694
  Text({ content: ` ${marker} `, fg: rgb(markerColor) }),
15691
15695
  Text({
15696
+ attributes: isActive ? 1 : 0,
15692
15697
  content: pad2(account2.label, labelWidth - 2),
15693
- fg: rgb(isActive || isSelected ? ctx.theme.fg : ctx.theme.dim),
15694
- attributes: isActive ? 1 : 0
15698
+ fg: rgb(isActive || isSelected ? ctx.theme.fg : ctx.theme.dim)
15695
15699
  }),
15696
15700
  Text({ content: badge === null ? " " : " *", fg: rgb(badge?.color ?? ctx.theme.dim) })
15697
15701
  ];
@@ -15705,31 +15709,31 @@ function accountLine(ctx, account2, windows, isActive, isSelected) {
15705
15709
  }));
15706
15710
  }
15707
15711
  return Box({
15712
+ backgroundColor: isSelected ? rgb(ctx.theme.selected) : rgb(ctx.theme.bg),
15708
15713
  flexDirection: "row",
15709
- width: "100%",
15710
- backgroundColor: isSelected ? rgb(ctx.theme.selected) : rgb(ctx.theme.bg)
15714
+ width: "100%"
15711
15715
  }, ...children);
15712
15716
  }
15713
15717
  function accountDetail(ctx, account2, windows) {
15714
15718
  const indent = " ".repeat(5);
15715
15719
  const plan = planLabel(account2.plan);
15716
15720
  const lines = [
15717
- Box({ flexDirection: "row", backgroundColor: rgb(ctx.theme.selected) }, Text({ content: `${indent}${providerShort[account2.provider]}`, fg: rgb(ctx.theme.dim) }), Text({
15721
+ Box({ backgroundColor: rgb(ctx.theme.selected), flexDirection: "row" }, Text({ content: `${indent}${providerShort[account2.provider]}`, fg: rgb(ctx.theme.dim) }), Text({
15722
+ attributes: plan === null ? 0 : 1,
15718
15723
  content: plan === null ? " \xB7 plan \u2014" : ` \xB7 ${plan}`,
15719
- fg: rgb(plan === null ? ctx.theme.dim : ctx.theme.accent),
15720
- attributes: plan === null ? 0 : 1
15724
+ fg: rgb(plan === null ? ctx.theme.dim : ctx.theme.accent)
15721
15725
  }))
15722
15726
  ];
15723
15727
  const hard = hardWindows(windows);
15724
15728
  if (hard.length === 0) {
15725
- lines.push(Box({ flexDirection: "row", backgroundColor: rgb(ctx.theme.selected) }, Text({
15729
+ lines.push(Box({ backgroundColor: rgb(ctx.theme.selected), flexDirection: "row" }, Text({
15726
15730
  content: `${indent}${account2.health === "ready" ? "waiting for usage\u2026" : "usage unavailable"}`,
15727
15731
  fg: rgb(ctx.theme.dim)
15728
15732
  })));
15729
15733
  }
15730
15734
  for (const window of hard) {
15731
15735
  const reset = resetCountdown(window.resetAt, ctx.now);
15732
- lines.push(Box({ flexDirection: "row", backgroundColor: rgb(ctx.theme.selected) }, Text({ content: `${indent}${pad2(window.label, 16)} `, fg: rgb(ctx.theme.dim) }), Text({
15736
+ lines.push(Box({ backgroundColor: rgb(ctx.theme.selected), flexDirection: "row" }, Text({ content: `${indent}${pad2(window.label, 16)} `, fg: rgb(ctx.theme.dim) }), Text({
15733
15737
  content: `${meter(window.usedPercent, 8)} ${percentLabel(window.usedPercent)}`,
15734
15738
  fg: rgb(pressureColor(ctx.theme, window.usedPercent))
15735
15739
  }), Text({
@@ -15739,12 +15743,12 @@ function accountDetail(ctx, account2, windows) {
15739
15743
  }
15740
15744
  const shortId = account2.externalAccountId?.slice(0, 8) ?? "\u2014";
15741
15745
  const added = account2.createdAt.slice(0, 10);
15742
- lines.push(Box({ flexDirection: "row", backgroundColor: rgb(ctx.theme.selected) }, Text({ content: `${indent}account ${shortId} \xB7 added ${added}`, fg: rgb(ctx.theme.faint) })));
15746
+ lines.push(Box({ backgroundColor: rgb(ctx.theme.selected), flexDirection: "row" }, Text({ content: `${indent}account ${shortId} \xB7 added ${added}`, fg: rgb(ctx.theme.faint) })));
15743
15747
  return lines;
15744
15748
  }
15745
15749
  function providerPanel(ctx, snapshot, provider, rows, selected, expanded) {
15746
15750
  const state = snapshot.providers.find((s) => s.provider === provider);
15747
- const providerRows = rows.map((row, index) => ({ row, index })).filter((entry) => entry.row.provider === provider);
15751
+ const providerRows = rows.map((row, index) => ({ index, row })).filter((entry) => entry.row.provider === provider);
15748
15752
  const lines = providerRows.length === 0 ? [
15749
15753
  Box({ flexDirection: "row", width: "100%" }, Text({
15750
15754
  content: ` no accounts \u2014 tokenmaxx login ${providerCli[provider]}`,
@@ -15762,14 +15766,14 @@ function providerPanel(ctx, snapshot, provider, rows, selected, expanded) {
15762
15766
  });
15763
15767
  const auto = state?.policy.enabled ? `\u27F3 auto ${state.policy.thresholdPercent}%` : "auto off";
15764
15768
  return Box({
15765
- flexDirection: "column",
15766
- width: "100%",
15767
- flexShrink: 0,
15768
15769
  border: true,
15769
- borderStyle: "rounded",
15770
15770
  borderColor: rgb(ctx.theme.border),
15771
+ borderStyle: "rounded",
15772
+ flexDirection: "column",
15773
+ flexShrink: 0,
15771
15774
  title: ` ${providerTitles[provider]} ${auto} `,
15772
- titleColor: rgb(state?.policy.enabled ? ctx.theme.good : ctx.theme.dim)
15775
+ titleColor: rgb(state?.policy.enabled ? ctx.theme.good : ctx.theme.dim),
15776
+ width: "100%"
15773
15777
  }, ...lines);
15774
15778
  }
15775
15779
  function legend(ctx, snapshot) {
@@ -15785,10 +15789,10 @@ function legend(ctx, snapshot) {
15785
15789
  }
15786
15790
  function pill(ctx, label, active) {
15787
15791
  return Text({
15788
- content: ` ${label} `,
15789
- fg: rgb(active ? ctx.theme.bg : ctx.theme.dim),
15792
+ attributes: active ? 1 : 0,
15790
15793
  bg: rgb(active ? ctx.theme.accent : ctx.theme.bg),
15791
- attributes: active ? 1 : 0
15794
+ content: ` ${label} `,
15795
+ fg: rgb(active ? ctx.theme.bg : ctx.theme.dim)
15792
15796
  });
15793
15797
  }
15794
15798
  function tabBar(ctx, tab) {
@@ -15799,7 +15803,7 @@ function timeframeBar(ctx, timeframe) {
15799
15803
  ...index === 0 ? [] : [Text({ content: " ", fg: rgb(ctx.theme.faint) })],
15800
15804
  pill(ctx, option.label, option.key === timeframe.key)
15801
15805
  ]);
15802
- return Box({ flexDirection: "row", width: "100%", paddingLeft: 1 }, Text({ content: "range ", fg: rgb(ctx.theme.dim) }), ...cells);
15806
+ return Box({ flexDirection: "row", paddingLeft: 1, width: "100%" }, Text({ content: "range ", fg: rgb(ctx.theme.dim) }), ...cells);
15803
15807
  }
15804
15808
  function throughputCard(ctx, tokens, timeframe, height, width) {
15805
15809
  const body = [];
@@ -15822,10 +15826,10 @@ function throughputCard(ctx, tokens, timeframe, height, width) {
15822
15826
  fg: rgb(ctx.theme.faint)
15823
15827
  }), Text({ content: "now", fg: rgb(ctx.theme.faint) })));
15824
15828
  body.push(Box({ flexDirection: "row", paddingLeft: 1 }, Text({ content: "\u03A3 ", fg: rgb(ctx.theme.dim) }), Text({
15829
+ attributes: 1,
15825
15830
  content: `${compactNumber(tokens.totalTokens)} tokens`,
15826
- fg: rgb(ctx.theme.fg),
15827
- attributes: 1
15828
- }), Text({ content: " \u2248 ", fg: rgb(ctx.theme.dim) }), Text({ content: compactUsd(tokens.costUsd), fg: rgb(ctx.theme.good), attributes: 1 }), Text({ content: " peak ", fg: rgb(ctx.theme.dim) }), Text({ content: `${compactNumber(tokens.peakPerHour)}/h`, fg: rgb(ctx.theme.accent) }), Text({
15831
+ fg: rgb(ctx.theme.fg)
15832
+ }), Text({ content: " \u2248 ", fg: rgb(ctx.theme.dim) }), Text({ attributes: 1, content: compactUsd(tokens.costUsd), fg: rgb(ctx.theme.good) }), Text({ content: " peak ", fg: rgb(ctx.theme.dim) }), Text({ content: `${compactNumber(tokens.peakPerHour)}/h`, fg: rgb(ctx.theme.accent) }), Text({
15829
15833
  content: tokens.topModel === null ? "" : ` top ${tokens.topModel}`,
15830
15834
  fg: rgb(ctx.theme.faint)
15831
15835
  })));
@@ -15841,14 +15845,14 @@ function throughputCard(ctx, tokens, timeframe, height, width) {
15841
15845
  })));
15842
15846
  }
15843
15847
  return Box({
15844
- flexDirection: "column",
15845
- width: "100%",
15846
- flexGrow: 1,
15847
15848
  border: true,
15848
- borderStyle: "rounded",
15849
15849
  borderColor: rgb(ctx.theme.border),
15850
+ borderStyle: "rounded",
15851
+ flexDirection: "column",
15852
+ flexGrow: 1,
15850
15853
  title: " Token throughput \xB7 all accounts \xB7 both providers ",
15851
- titleColor: rgb(ctx.theme.dim)
15854
+ titleColor: rgb(ctx.theme.dim),
15855
+ width: "100%"
15852
15856
  }, ...body);
15853
15857
  }
15854
15858
  function analyticsBody(ctx, analytics, timeframe) {
@@ -15874,26 +15878,26 @@ function view(ctx, analytics, rows, state) {
15874
15878
  const refreshed = freshestMillis === 0 ? "\u2014" : `${relativeAge(freshestMillis, ctx.now)} ago`;
15875
15879
  const timeframe = TIMEFRAMES[state.timeframeIndex] ?? fallbackTimeframe;
15876
15880
  const footer = state.tab === "accounts" ? "\u2191\u2193 select \xB7 space details \xB7 \u23CE switch \xB7 a auto \xB7 tab analytics \xB7 r refresh" : "\u2190\u2192 range \xB7 tab accounts \xB7 r refresh";
15877
- const header = Box({ flexDirection: "row" }, Text({ content: "tokenmaxx", fg: rgb(ctx.theme.accent), attributes: 1 }), Text({ content: ` ${clock}`, fg: rgb(ctx.theme.dim) }), Text({ content: ` \u21BB ${refreshed} \xB7 active 60s / idle 5m`, fg: rgb(ctx.theme.faint) }), ...state.note === "" ? [] : [Text({ content: ` ${state.note}`, fg: rgb(ctx.theme.warn) })]);
15881
+ const header = Box({ flexDirection: "row" }, Text({ attributes: 1, content: "tokenmaxx", fg: rgb(ctx.theme.accent) }), Text({ content: ` ${clock}`, fg: rgb(ctx.theme.dim) }), Text({ content: ` \u21BB ${refreshed} \xB7 active 60s / idle 5m`, fg: rgb(ctx.theme.faint) }), ...state.note === "" ? [] : [Text({ content: ` ${state.note}`, fg: rgb(ctx.theme.warn) })]);
15878
15882
  const children = [header];
15879
15883
  if (!state.installed) {
15880
- children.push(Box({ width: "100%", backgroundColor: rgb(ctx.theme.warn) }, Text({
15881
- content: " native routing is off \u2014 run tokenmaxx install to route codex & claude",
15882
- fg: rgb(ctx.theme.bg),
15884
+ children.push(Box({ backgroundColor: rgb(ctx.theme.warn), width: "100%" }, Text({
15885
+ attributes: 1,
15883
15886
  bg: rgb(ctx.theme.warn),
15884
- attributes: 1
15887
+ content: " native routing is off \u2014 run tokenmaxx install to route codex & claude",
15888
+ fg: rgb(ctx.theme.bg)
15885
15889
  })));
15886
15890
  }
15887
15891
  children.push(tabBar(ctx, state.tab));
15888
15892
  children.push(...state.tab === "accounts" ? accountsBody(ctx, analytics.snapshot, rows, state.selected, state.expanded) : analyticsBody(ctx, analytics, timeframe));
15889
15893
  children.push(Text({ content: footer, fg: rgb(ctx.theme.dim) }));
15890
15894
  return Box({
15895
+ backgroundColor: rgb(ctx.theme.bg),
15891
15896
  flexDirection: "column",
15892
- width: "100%",
15897
+ gap: 1,
15893
15898
  height: "100%",
15894
15899
  padding: 1,
15895
- gap: 1,
15896
- backgroundColor: rgb(ctx.theme.bg)
15900
+ width: "100%"
15897
15901
  }, ...children);
15898
15902
  }
15899
15903
  async function runTuiDashboard(socketPath, options) {
@@ -15905,12 +15909,12 @@ async function runTuiDashboard(socketPath, options) {
15905
15909
  let analytics = options.fixture ?? await readAnalytics(socketPath);
15906
15910
  let rows = orderedRows(analytics.snapshot);
15907
15911
  const state = {
15908
- tab: "accounts",
15909
- selected: 0,
15910
15912
  expanded: false,
15911
- timeframeIndex: 2,
15912
15913
  installed: options.installed,
15913
- note: ""
15914
+ note: "",
15915
+ selected: 0,
15916
+ tab: "accounts",
15917
+ timeframeIndex: 2
15914
15918
  };
15915
15919
  let busy = false;
15916
15920
  const clampSelection = () => {
@@ -15920,7 +15924,7 @@ async function runTuiDashboard(socketPath, options) {
15920
15924
  clampSelection();
15921
15925
  let next;
15922
15926
  try {
15923
- next = view({ theme: currentTheme(), now: options.now ?? Date.now() }, analytics, rows, state);
15927
+ next = view({ now: options.now ?? Date.now(), theme: currentTheme() }, analytics, rows, state);
15924
15928
  } catch {
15925
15929
  return;
15926
15930
  }
@@ -15979,10 +15983,10 @@ async function runTuiDashboard(socketPath, options) {
15979
15983
  const enable = !(providerState2?.policy.enabled ?? false);
15980
15984
  withBusy(`auto-rotate ${providerCli[row.provider]} ${enable ? "on" : "off"}\u2026`, async () => {
15981
15985
  await requestPolicy(socketPath, {
15982
- provider: row.provider,
15986
+ authorizationConfirmed: enable,
15983
15987
  enabled: enable,
15984
- thresholdPercent: 95,
15985
- authorizationConfirmed: enable
15988
+ provider: row.provider,
15989
+ thresholdPercent: 95
15986
15990
  });
15987
15991
  analytics = await readAnalytics(socketPath);
15988
15992
  });
@@ -16050,11 +16054,11 @@ var init_dashboard = __esm(() => {
16050
16054
  init_format();
16051
16055
  colorCache = new Map;
16052
16056
  providerTitles = {
16053
- openai: "OpenAI \xB7 Codex",
16054
- anthropic: "Anthropic \xB7 Claude Code"
16057
+ anthropic: "Anthropic \xB7 Claude Code",
16058
+ openai: "OpenAI \xB7 Codex"
16055
16059
  };
16056
- providerShort = { openai: "Codex", anthropic: "Claude Code" };
16057
- providerCli = { openai: "codex", anthropic: "claude" };
16060
+ providerShort = { anthropic: "Claude Code", openai: "Codex" };
16061
+ providerCli = { anthropic: "claude", openai: "codex" };
16058
16062
  providerOrder = ["openai", "anthropic"];
16059
16063
  fallbackTimeframe = TIMEFRAMES[2];
16060
16064
  });
@@ -16078,13 +16082,13 @@ import { chmod, mkdir } from "fs/promises";
16078
16082
  import { homedir } from "os";
16079
16083
  import { join, resolve } from "path";
16080
16084
  var ApplicationPathsSchema = exports_external.object({
16081
- root: exports_external.string().min(1),
16085
+ claudeProfiles: exports_external.string().min(1),
16082
16086
  database: exports_external.string().min(1),
16083
- runtime: exports_external.string().min(1),
16084
- managerSocket: exports_external.string().min(1),
16085
16087
  managerLock: exports_external.string().min(1),
16086
- claudeProfiles: exports_external.string().min(1),
16087
- proxyPort: exports_external.number().int().positive()
16088
+ managerSocket: exports_external.string().min(1),
16089
+ proxyPort: exports_external.number().int().positive(),
16090
+ root: exports_external.string().min(1),
16091
+ runtime: exports_external.string().min(1)
16088
16092
  });
16089
16093
  var defaultProxyPort = 8459;
16090
16094
  function applicationPaths(environment = process.env) {
@@ -16092,18 +16096,18 @@ function applicationPaths(environment = process.env) {
16092
16096
  const runtime = join(root, "runtime");
16093
16097
  const proxyPort = Number(environment.TOKENMAXX_PROXY_PORT ?? environment.TOKMAX_PROXY_PORT ?? defaultProxyPort);
16094
16098
  return ApplicationPathsSchema.parse({
16095
- root,
16099
+ claudeProfiles: join(root, "profiles", "claude"),
16096
16100
  database: join(root, "state.sqlite"),
16097
- runtime,
16098
- managerSocket: join(runtime, "manager.sock"),
16099
16101
  managerLock: join(runtime, "manager.lock"),
16100
- claudeProfiles: join(root, "profiles", "claude"),
16101
- proxyPort: Number.isFinite(proxyPort) ? proxyPort : defaultProxyPort
16102
+ managerSocket: join(runtime, "manager.sock"),
16103
+ proxyPort: Number.isFinite(proxyPort) ? proxyPort : defaultProxyPort,
16104
+ root,
16105
+ runtime
16102
16106
  });
16103
16107
  }
16104
16108
  async function ensureApplicationPaths(paths) {
16105
16109
  const directories = [paths.root, paths.runtime, paths.claudeProfiles];
16106
- await Promise.all(directories.map((directory) => mkdir(directory, { recursive: true, mode: 448 })));
16110
+ await Promise.all(directories.map((directory) => mkdir(directory, { mode: 448, recursive: true })));
16107
16111
  await Promise.all(directories.map((directory) => chmod(directory, 448)));
16108
16112
  }
16109
16113
  function proxyBaseUrl(paths, provider) {
@@ -16200,8 +16204,8 @@ async function installClaudeConfig(paths) {
16200
16204
  }
16201
16205
  settings.env = {
16202
16206
  ...settings.env,
16203
- ANTHROPIC_BASE_URL: proxyBaseUrl(paths, "anthropic"),
16204
- ANTHROPIC_AUTH_TOKEN: dummyAuthToken
16207
+ ANTHROPIC_AUTH_TOKEN: dummyAuthToken,
16208
+ ANTHROPIC_BASE_URL: proxyBaseUrl(paths, "anthropic")
16205
16209
  };
16206
16210
  await mkdir2(dirname(path), { recursive: true });
16207
16211
  await writeFile(path, `${JSON.stringify(settings, null, 2)}
@@ -16247,9 +16251,9 @@ init_zod();
16247
16251
  init_errors3();
16248
16252
  import { open, readFile as readFile2, rm } from "fs/promises";
16249
16253
  var DaemonLockSchema = exports_external.object({
16254
+ createdAt: exports_external.iso.datetime(),
16250
16255
  ownerId: exports_external.uuid(),
16251
- processId: exports_external.number().int().positive(),
16252
- createdAt: exports_external.iso.datetime()
16256
+ processId: exports_external.number().int().positive()
16253
16257
  }).strict();
16254
16258
  function isAlreadyExists(error51) {
16255
16259
  return error51 instanceof Error && "code" in error51 && Reflect.get(error51, "code") === "EEXIST";
@@ -16271,9 +16275,9 @@ async function readLock(lockPath) {
16271
16275
  }
16272
16276
  async function ownedLock(lockPath, fileHandle) {
16273
16277
  const owner = DaemonLockSchema.parse({
16278
+ createdAt: new Date().toISOString(),
16274
16279
  ownerId: crypto.randomUUID(),
16275
- processId: process.pid,
16276
- createdAt: new Date().toISOString()
16280
+ processId: process.pid
16277
16281
  });
16278
16282
  await fileHandle.writeFile(JSON.stringify(owner), "utf8");
16279
16283
  await fileHandle.sync();
@@ -16334,12 +16338,12 @@ import { userInfo } from "os";
16334
16338
  import { join as join3, normalize, resolve as resolve2 } from "path";
16335
16339
  var ClaudeOauthSchema = exports_external.object({
16336
16340
  accessToken: exports_external.string().min(1),
16337
- refreshToken: exports_external.string().min(1),
16338
16341
  expiresAt: exports_external.number().nonnegative(),
16342
+ rateLimitTier: exports_external.string().optional(),
16343
+ refreshToken: exports_external.string().min(1),
16339
16344
  refreshTokenExpiresAt: exports_external.number().nonnegative().optional(),
16340
16345
  scopes: exports_external.union([exports_external.array(exports_external.string()), exports_external.string()]).optional(),
16341
- subscriptionType: exports_external.string().optional(),
16342
- rateLimitTier: exports_external.string().optional()
16346
+ subscriptionType: exports_external.string().optional()
16343
16347
  }).passthrough();
16344
16348
  function claudePlanTier(credential) {
16345
16349
  const tier = credential.rateLimitTier?.trim();
@@ -16351,18 +16355,18 @@ function claudePlanTier(credential) {
16351
16355
  }
16352
16356
  var ClaudeCredentialPayloadSchema = exports_external.object({ claudeAiOauth: ClaudeOauthSchema }).passthrough();
16353
16357
  var ClaudeAuthStatusSchema = exports_external.object({
16354
- loggedIn: exports_external.boolean(),
16355
16358
  authMethod: exports_external.string().optional(),
16356
16359
  email: exports_external.string().email().optional(),
16360
+ loggedIn: exports_external.boolean(),
16357
16361
  subscriptionType: exports_external.string().optional()
16358
16362
  }).passthrough();
16359
16363
  var ClaudeProfileSchema = exports_external.object({
16360
16364
  account: exports_external.object({
16361
- uuid: exports_external.string().min(1),
16362
- email_address: exports_external.string().email().optional()
16365
+ email_address: exports_external.string().email().optional(),
16366
+ uuid: exports_external.string().min(1)
16363
16367
  }).passthrough().optional(),
16364
- uuid: exports_external.string().min(1).optional(),
16365
- email_address: exports_external.string().email().optional()
16368
+ email_address: exports_external.string().email().optional(),
16369
+ uuid: exports_external.string().min(1).optional()
16366
16370
  }).passthrough();
16367
16371
  function currentUser() {
16368
16372
  return process.env.USER ?? userInfo().username;
@@ -16387,20 +16391,12 @@ function decodeSecurityOutput(output) {
16387
16391
  }
16388
16392
  function defaultClaudeCommandRunner() {
16389
16393
  return {
16390
- async interactive(command, environment) {
16391
- return Bun.spawn([...command], {
16392
- env: { ...process.env, ...environment },
16393
- stdin: "inherit",
16394
- stdout: "inherit",
16395
- stderr: "inherit"
16396
- }).exited;
16397
- },
16398
16394
  async captured(command, environment) {
16399
16395
  const processHandle = Bun.spawn([...command], {
16400
16396
  env: { ...process.env, ...environment },
16397
+ stderr: "pipe",
16401
16398
  stdin: "ignore",
16402
- stdout: "pipe",
16403
- stderr: "pipe"
16399
+ stdout: "pipe"
16404
16400
  });
16405
16401
  const timeout = setTimeout(() => processHandle.kill("SIGTERM"), 30000);
16406
16402
  const [exitCode, stdout, stderr] = await Promise.all([
@@ -16409,7 +16405,15 @@ function defaultClaudeCommandRunner() {
16409
16405
  new Response(processHandle.stderr).text()
16410
16406
  ]);
16411
16407
  clearTimeout(timeout);
16412
- return { exitCode, stdout, stderr };
16408
+ return { exitCode, stderr, stdout };
16409
+ },
16410
+ async interactive(command, environment) {
16411
+ return Bun.spawn([...command], {
16412
+ env: { ...process.env, ...environment },
16413
+ stderr: "inherit",
16414
+ stdin: "inherit",
16415
+ stdout: "inherit"
16416
+ }).exited;
16413
16417
  }
16414
16418
  };
16415
16419
  }
@@ -16480,7 +16484,7 @@ async function registerClaudeAccount(input) {
16480
16484
  const id = crypto.randomUUID();
16481
16485
  const profilePath = canonicalClaudeProfilePath(join3(input.paths.claudeProfiles, id));
16482
16486
  const runner = input.runner ?? defaultClaudeCommandRunner();
16483
- await mkdir3(profilePath, { recursive: true, mode: 448 });
16487
+ await mkdir3(profilePath, { mode: 448, recursive: true });
16484
16488
  let registered = false;
16485
16489
  try {
16486
16490
  const command = ["claude", "auth", "login", "--claudeai"];
@@ -16510,18 +16514,18 @@ async function registerClaudeAccount(input) {
16510
16514
  }
16511
16515
  const now = new Date().toISOString();
16512
16516
  const account = {
16513
- id,
16514
- provider: "anthropic",
16515
- label: email3.data,
16516
- identity: email3.data,
16517
+ createdAt: now,
16518
+ enabled: true,
16517
16519
  externalAccountId: profile.accountId,
16518
16520
  externalUserId: null,
16521
+ health: credential.expiresAt <= Date.now() ? "refreshDue" : "ready",
16522
+ id,
16523
+ identity: email3.data,
16524
+ label: email3.data,
16519
16525
  plan: claudePlanTier(credential),
16520
- secretReference: null,
16521
16526
  profilePath,
16522
- health: credential.expiresAt <= Date.now() ? "refreshDue" : "ready",
16523
- enabled: true,
16524
- createdAt: now,
16527
+ provider: "anthropic",
16528
+ secretReference: null,
16525
16529
  updatedAt: now
16526
16530
  };
16527
16531
  registered = true;
@@ -16535,7 +16539,7 @@ async function registerClaudeAccount(input) {
16535
16539
  async function removeClaudeProfile(profilePath, runner = defaultClaudeCommandRunner()) {
16536
16540
  const service = claudeKeychainService(profilePath);
16537
16541
  const result = await runner.captured(["security", "delete-generic-password", "-a", currentUser(), "-s", service], {});
16538
- await rm3(profilePath, { recursive: true, force: true });
16542
+ await rm3(profilePath, { force: true, recursive: true });
16539
16543
  if (result.exitCode !== 0 && result.exitCode !== 44) {
16540
16544
  throw new ApplicationError("KEYCHAIN_DELETE_FAILED", result.stderr.trim() || `Could not remove Claude Keychain service ${service}`);
16541
16545
  }
@@ -16556,17 +16560,17 @@ async function refreshClaudeProfile(input) {
16556
16560
  const credential = await reader.read(input.profilePath);
16557
16561
  await projectClaudeCredential({
16558
16562
  credential,
16559
- targetProfilePath: input.profilePath,
16560
- runner
16563
+ runner,
16564
+ targetProfilePath: input.profilePath
16561
16565
  });
16562
16566
  return reader.read(input.profilePath);
16563
16567
  }
16564
16568
  async function projectClaudeCredential(input) {
16565
16569
  const runner = input.runner ?? defaultClaudeCommandRunner();
16566
16570
  const result = await runner.captured(["claude", "auth", "login", "--claudeai"], {
16567
- CLAUDE_CONFIG_DIR: input.targetProfilePath,
16568
16571
  CLAUDE_CODE_OAUTH_REFRESH_TOKEN: input.credential.refreshToken,
16569
- CLAUDE_CODE_OAUTH_SCOPES: serializedScopes(input.credential.scopes)
16572
+ CLAUDE_CODE_OAUTH_SCOPES: serializedScopes(input.credential.scopes),
16573
+ CLAUDE_CONFIG_DIR: input.targetProfilePath
16570
16574
  });
16571
16575
  if (result.exitCode !== 0) {
16572
16576
  throw new ApplicationError("REAUTHENTICATION_REQUIRED", result.stderr.trim() || `Claude profile refresh exited with ${result.exitCode}`);
@@ -16590,35 +16594,35 @@ function requireProvider(account, provider) {
16590
16594
  init_zod();
16591
16595
  init_errors3();
16592
16596
  var UsageWindowSchema2 = exports_external.object({
16593
- utilization: exports_external.number().min(0),
16594
- resets_at: exports_external.union([exports_external.string(), exports_external.number()]).nullish(),
16595
16597
  limit_dollars: exports_external.number().nonnegative().nullish(),
16598
+ remaining_dollars: exports_external.number().nonnegative().nullish(),
16599
+ resets_at: exports_external.union([exports_external.string(), exports_external.number()]).nullish(),
16596
16600
  used_dollars: exports_external.number().nonnegative().nullish(),
16597
- remaining_dollars: exports_external.number().nonnegative().nullish()
16601
+ utilization: exports_external.number().min(0)
16598
16602
  }).passthrough();
16599
16603
  var LimitScopeSchema = exports_external.object({
16600
- model: exports_external.object({ id: exports_external.string().nullish(), display_name: exports_external.string().nullish() }).passthrough().nullish(),
16604
+ model: exports_external.object({ display_name: exports_external.string().nullish(), id: exports_external.string().nullish() }).passthrough().nullish(),
16601
16605
  surface: exports_external.union([
16602
16606
  exports_external.string(),
16603
- exports_external.object({ id: exports_external.string().nullish(), display_name: exports_external.string().nullish() }).passthrough()
16607
+ exports_external.object({ display_name: exports_external.string().nullish(), id: exports_external.string().nullish() }).passthrough()
16604
16608
  ]).nullish()
16605
16609
  }).passthrough();
16606
16610
  var LimitSchema = exports_external.object({
16607
- kind: exports_external.string().min(1),
16608
16611
  group: exports_external.string().nullish(),
16612
+ is_active: exports_external.boolean().nullish(),
16613
+ kind: exports_external.string().min(1),
16609
16614
  percent: exports_external.number().min(0),
16610
- severity: exports_external.string().nullish(),
16611
16615
  resets_at: exports_external.union([exports_external.string(), exports_external.number()]).nullish(),
16612
16616
  scope: LimitScopeSchema.nullish(),
16613
- is_active: exports_external.boolean().nullish()
16617
+ severity: exports_external.string().nullish()
16614
16618
  }).passthrough();
16615
16619
  var ClaudeUsageResponseSchema = exports_external.object({
16616
- limits: exports_external.array(LimitSchema).nullish(),
16617
16620
  five_hour: UsageWindowSchema2.nullish(),
16621
+ limits: exports_external.array(LimitSchema).nullish(),
16618
16622
  seven_day: UsageWindowSchema2.nullish(),
16623
+ seven_day_oauth_apps: UsageWindowSchema2.nullish(),
16619
16624
  seven_day_opus: UsageWindowSchema2.nullish(),
16620
- seven_day_sonnet: UsageWindowSchema2.nullish(),
16621
- seven_day_oauth_apps: UsageWindowSchema2.nullish()
16625
+ seven_day_sonnet: UsageWindowSchema2.nullish()
16622
16626
  }).passthrough();
16623
16627
  function resetTimestamp(value) {
16624
16628
  if (value == null) {
@@ -16634,10 +16638,10 @@ function normalizePercent(utilization) {
16634
16638
  function normalizeWindow(id, label, source) {
16635
16639
  return {
16636
16640
  id,
16641
+ kind: id.includes("oauth_apps") || id.includes("extra_usage") || source.limit_dollars != null ? "spend" : "hard",
16637
16642
  label,
16638
- usedPercent: normalizePercent(source.utilization),
16639
16643
  resetAt: resetTimestamp(source.resets_at),
16640
- kind: id.includes("oauth_apps") || id.includes("extra_usage") || source.limit_dollars != null ? "spend" : "hard"
16644
+ usedPercent: normalizePercent(source.utilization)
16641
16645
  };
16642
16646
  }
16643
16647
  function limitScopeName(limit) {
@@ -16655,10 +16659,10 @@ function limitWindow(limit) {
16655
16659
  const fallbackLabel = limit.kind.split("_").filter((part) => part.length > 0).map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
16656
16660
  return {
16657
16661
  id: scopeName === null ? limit.kind : `${limit.kind}:${scopeName.toLowerCase()}`,
16662
+ kind: "hard",
16658
16663
  label: labels[limit.kind] ?? (scopeName === null ? fallbackLabel : `${fallbackLabel} \xB7 ${scopeName}`),
16659
- usedPercent: Math.min(100, limit.percent),
16660
16664
  resetAt: resetTimestamp(limit.resets_at),
16661
- kind: "hard"
16665
+ usedPercent: Math.min(100, limit.percent)
16662
16666
  };
16663
16667
  }
16664
16668
  var exhaustedSeverities = new Set(["exceeded", "blocked", "at_limit"]);
@@ -16666,8 +16670,8 @@ async function fetchClaudeUsage(input) {
16666
16670
  const response = await (input.fetchImplementation ?? fetch)("https://api.anthropic.com/api/oauth/usage", {
16667
16671
  headers: {
16668
16672
  Authorization: `Bearer ${input.accessToken}`,
16669
- "Content-Type": "application/json",
16670
- "anthropic-beta": "oauth-2025-04-20"
16673
+ "anthropic-beta": "oauth-2025-04-20",
16674
+ "Content-Type": "application/json"
16671
16675
  },
16672
16676
  signal: AbortSignal.timeout(1e4)
16673
16677
  });
@@ -16710,11 +16714,11 @@ async function fetchClaudeUsage(input) {
16710
16714
  }
16711
16715
  return {
16712
16716
  accountId: input.accountId,
16713
- provider: "anthropic",
16717
+ hardLimitReached: windows.some((window) => window.kind === "hard" && window.usedPercent >= 100) || limits.some((limit) => limit.severity != null && exhaustedSeverities.has(limit.severity.toLowerCase())),
16714
16718
  observedAt: new Date().toISOString(),
16719
+ provider: "anthropic",
16715
16720
  source: "claudeUsageEndpoint",
16716
- windows,
16717
- hardLimitReached: windows.some((window) => window.kind === "hard" && window.usedPercent >= 100) || limits.some((limit) => limit.severity != null && exhaustedSeverities.has(limit.severity.toLowerCase()))
16721
+ windows
16718
16722
  };
16719
16723
  }
16720
16724
 
@@ -16757,7 +16761,7 @@ class AnthropicProviderAdapter {
16757
16761
  const reader = defaultClaudeCredentialReader();
16758
16762
  let credential = await reader.read(profilePath);
16759
16763
  if (credential.expiresAt <= this.#dependencies.now().getTime() + 300000) {
16760
- credential = await refreshClaudeProfile({ profilePath, credentialReader: reader });
16764
+ credential = await refreshClaudeProfile({ credentialReader: reader, profilePath });
16761
16765
  }
16762
16766
  if (!scopesPermitUsage(credential.scopes)) {
16763
16767
  throw new ApplicationError("SCOPE_MISSING", "Claude credential does not include the user:profile scope required for usage");
@@ -16778,23 +16782,23 @@ class AnthropicProviderAdapter {
16778
16782
  if (!(error51 instanceof ApplicationError) || error51.code !== "REAUTHENTICATION_REQUIRED") {
16779
16783
  throw error51;
16780
16784
  }
16781
- credential = await refreshClaudeProfile({ profilePath, credentialReader: reader });
16785
+ credential = await refreshClaudeProfile({ credentialReader: reader, profilePath });
16782
16786
  return verifyIdentity();
16783
16787
  });
16784
16788
  assertIdentity(anthropicAccount, profile.accountId);
16785
16789
  const usage = await fetchClaudeUsage({
16786
- accountId: anthropicAccount.id,
16787
16790
  accessToken: credential.accessToken,
16791
+ accountId: anthropicAccount.id,
16788
16792
  fetchImplementation: this.#dependencies.fetchImplementation
16789
16793
  }).catch(async (error51) => {
16790
16794
  if (!(error51 instanceof ApplicationError) || error51.code !== "ACCESS_TOKEN_REJECTED") {
16791
16795
  throw error51;
16792
16796
  }
16793
- credential = await refreshClaudeProfile({ profilePath, credentialReader: reader });
16797
+ credential = await refreshClaudeProfile({ credentialReader: reader, profilePath });
16794
16798
  profile = await verifyIdentity();
16795
16799
  return fetchClaudeUsage({
16796
- accountId: anthropicAccount.id,
16797
16800
  accessToken: credential.accessToken,
16801
+ accountId: anthropicAccount.id,
16798
16802
  fetchImplementation: this.#dependencies.fetchImplementation
16799
16803
  });
16800
16804
  });
@@ -16803,10 +16807,10 @@ class AnthropicProviderAdapter {
16803
16807
  return {
16804
16808
  account: {
16805
16809
  ...anthropicAccount,
16806
- plan: claudePlanTier(credential) ?? anthropicAccount.plan ?? null,
16807
- label: email3.success ? email3.data : anthropicAccount.label,
16808
- identity: email3.success ? email3.data : anthropicAccount.identity,
16809
16810
  health: health(credential.refreshTokenExpiresAt, this.#dependencies.now()),
16811
+ identity: email3.success ? email3.data : anthropicAccount.identity,
16812
+ label: email3.success ? email3.data : anthropicAccount.label,
16813
+ plan: claudePlanTier(credential) ?? anthropicAccount.plan ?? null,
16810
16814
  updatedAt: this.#dependencies.now().toISOString()
16811
16815
  },
16812
16816
  usage
@@ -16828,33 +16832,33 @@ import { join as join4 } from "path";
16828
16832
  var openAiClientId = "app_EMoamEEZ73f0CkXaXp7hrann";
16829
16833
  var refreshEndpoint = "https://auth.openai.com/oauth/token";
16830
16834
  var CodexTokensSchema = exports_external.object({
16831
- id_token: exports_external.string().min(1),
16832
16835
  access_token: exports_external.string().min(1),
16833
- refresh_token: exports_external.string().min(1),
16834
- account_id: exports_external.string().min(1).optional()
16836
+ account_id: exports_external.string().min(1).optional(),
16837
+ id_token: exports_external.string().min(1),
16838
+ refresh_token: exports_external.string().min(1)
16835
16839
  }).passthrough();
16836
16840
  var CodexAuthSchema = exports_external.object({
16837
16841
  auth_mode: exports_external.string().optional(),
16838
- tokens: CodexTokensSchema,
16839
- last_refresh: exports_external.string().optional()
16842
+ last_refresh: exports_external.string().optional(),
16843
+ tokens: CodexTokensSchema
16840
16844
  }).passthrough();
16841
16845
  var JwtClaimsSchema = exports_external.object({
16842
- exp: exports_external.number().optional(),
16843
- sub: exports_external.string().optional(),
16844
- email: exports_external.string().email().optional(),
16845
16846
  chatgpt_account_id: exports_external.string().optional(),
16846
16847
  chatgpt_user_id: exports_external.string().optional(),
16848
+ email: exports_external.string().email().optional(),
16849
+ exp: exports_external.number().optional(),
16847
16850
  "https://api.openai.com/auth": exports_external.object({
16848
16851
  chatgpt_account_id: exports_external.string().optional(),
16849
- chatgpt_user_id: exports_external.string().optional(),
16850
16852
  chatgpt_plan_type: exports_external.string().optional(),
16853
+ chatgpt_user_id: exports_external.string().optional(),
16851
16854
  user_id: exports_external.string().optional()
16852
- }).passthrough().optional()
16855
+ }).passthrough().optional(),
16856
+ sub: exports_external.string().optional()
16853
16857
  }).passthrough();
16854
16858
  var RefreshResponseSchema = exports_external.object({
16855
16859
  access_token: exports_external.string().min(1),
16856
- refresh_token: exports_external.string().min(1).optional(),
16857
- id_token: exports_external.string().min(1).optional()
16860
+ id_token: exports_external.string().min(1).optional(),
16861
+ refresh_token: exports_external.string().min(1).optional()
16858
16862
  }).passthrough();
16859
16863
  var refreshLocks = new Map;
16860
16864
  function base64UrlJson(segment) {
@@ -16885,27 +16889,27 @@ function codexIdentity(auth) {
16885
16889
  }
16886
16890
  const expiresAt = accessClaims.exp === undefined ? null : new Date(accessClaims.exp * 1000).toISOString();
16887
16891
  return {
16892
+ accessExpiresAt: expiresAt,
16888
16893
  accountId,
16889
- userId: claims.chatgpt_user_id ?? namespaced?.chatgpt_user_id ?? namespaced?.user_id ?? claims.sub ?? null,
16890
16894
  email: claims.email ?? accessClaims.email ?? null,
16891
16895
  plan: namespaced?.chatgpt_plan_type ?? null,
16892
- accessExpiresAt: expiresAt
16896
+ userId: claims.chatgpt_user_id ?? namespaced?.chatgpt_user_id ?? namespaced?.user_id ?? claims.sub ?? null
16893
16897
  };
16894
16898
  }
16895
16899
  function defaultCodexLoginDependencies() {
16896
16900
  return {
16901
+ createTemporaryDirectory: (prefix) => mkdtemp(join4(tmpdir(), prefix)),
16902
+ read: (path) => readFile4(path, "utf8"),
16903
+ remove: (path) => rm4(path, { force: true, recursive: true }),
16897
16904
  async run(command, environment) {
16898
16905
  const child = Bun.spawn([...command], {
16899
16906
  env: { ...process.env, ...environment },
16907
+ stderr: "inherit",
16900
16908
  stdin: "inherit",
16901
- stdout: "inherit",
16902
- stderr: "inherit"
16909
+ stdout: "inherit"
16903
16910
  });
16904
16911
  return child.exited;
16905
- },
16906
- createTemporaryDirectory: (prefix) => mkdtemp(join4(tmpdir(), prefix)),
16907
- read: (path) => readFile4(path, "utf8"),
16908
- remove: (path) => rm4(path, { recursive: true, force: true })
16912
+ }
16909
16913
  };
16910
16914
  }
16911
16915
  async function registerCodexAccount(input) {
@@ -16930,18 +16934,18 @@ async function registerCodexAccount(input) {
16930
16934
  await input.vault.write(secretReference, JSON.stringify(auth));
16931
16935
  const now = new Date().toISOString();
16932
16936
  return {
16933
- id,
16934
- provider: "openai",
16935
- label: email3.data,
16936
- identity: email3.data,
16937
+ createdAt: now,
16938
+ enabled: true,
16937
16939
  externalAccountId: identity.accountId,
16938
16940
  externalUserId: identity.userId,
16941
+ health: "ready",
16942
+ id,
16943
+ identity: email3.data,
16944
+ label: email3.data,
16939
16945
  plan: identity.plan,
16940
- secretReference,
16941
16946
  profilePath: null,
16942
- health: "ready",
16943
- enabled: true,
16944
- createdAt: now,
16947
+ provider: "openai",
16948
+ secretReference,
16945
16949
  updatedAt: now
16946
16950
  };
16947
16951
  } finally {
@@ -16977,13 +16981,13 @@ async function refreshCodexCredential(input) {
16977
16981
  return exclusive(input.reference, async () => {
16978
16982
  const current = await readCodexCredential(input.vault, input.reference);
16979
16983
  const response = await (input.fetchImplementation ?? fetch)(refreshEndpoint, {
16980
- method: "POST",
16981
- headers: { "Content-Type": "application/json" },
16982
16984
  body: JSON.stringify({
16983
16985
  client_id: openAiClientId,
16984
16986
  grant_type: "refresh_token",
16985
16987
  refresh_token: current.tokens.refresh_token
16986
16988
  }),
16989
+ headers: { "Content-Type": "application/json" },
16990
+ method: "POST",
16987
16991
  signal: AbortSignal.timeout(7000)
16988
16992
  });
16989
16993
  if (response.status === 400 || response.status === 401) {
@@ -16995,13 +16999,13 @@ async function refreshCodexCredential(input) {
16995
16999
  const refreshed = RefreshResponseSchema.parse(await response.json());
16996
17000
  const updated = CodexAuthSchema.parse({
16997
17001
  ...current,
17002
+ last_refresh: new Date().toISOString(),
16998
17003
  tokens: {
16999
17004
  ...current.tokens,
17000
17005
  access_token: refreshed.access_token,
17001
- refresh_token: refreshed.refresh_token ?? current.tokens.refresh_token,
17002
- id_token: refreshed.id_token ?? current.tokens.id_token
17003
- },
17004
- last_refresh: new Date().toISOString()
17006
+ id_token: refreshed.id_token ?? current.tokens.id_token,
17007
+ refresh_token: refreshed.refresh_token ?? current.tokens.refresh_token
17008
+ }
17005
17009
  });
17006
17010
  const priorIdentity = codexIdentity(current);
17007
17011
  const updatedIdentity = codexIdentity(updated);
@@ -17019,9 +17023,9 @@ init_errors3();
17019
17023
  var usageEndpoint = "https://chatgpt.com/backend-api/wham/usage";
17020
17024
  var sampleCount = 3;
17021
17025
  var WindowSchema = exports_external.object({
17022
- used_percent: exports_external.number().min(0).max(100),
17023
17026
  limit_window_seconds: exports_external.number().nonnegative().optional(),
17024
- reset_at: exports_external.number().nonnegative().optional()
17027
+ reset_at: exports_external.number().nonnegative().optional(),
17028
+ used_percent: exports_external.number().min(0).max(100)
17025
17029
  }).passthrough();
17026
17030
  var LimitDetailsSchema = exports_external.object({
17027
17031
  allowed: exports_external.boolean().optional(),
@@ -17035,8 +17039,8 @@ var AdditionalLimitSchema = exports_external.object({
17035
17039
  rate_limit: LimitDetailsSchema.nullish()
17036
17040
  }).passthrough();
17037
17041
  var UsageResponseSchema = exports_external.object({
17038
- rate_limit: LimitDetailsSchema.nullish(),
17039
17042
  additional_rate_limits: exports_external.array(AdditionalLimitSchema).nullish(),
17043
+ rate_limit: LimitDetailsSchema.nullish(),
17040
17044
  rate_limit_reached_type: exports_external.unknown().nullish()
17041
17045
  }).passthrough();
17042
17046
  function durationLabel(seconds, fallback) {
@@ -17057,10 +17061,10 @@ function toWindow(id, scope, fallback, window) {
17057
17061
  const duration3 = durationLabel(window.limit_window_seconds, fallback);
17058
17062
  return {
17059
17063
  id,
17064
+ kind: "hard",
17060
17065
  label: scope === "Codex" ? duration3 : `${scope} \xB7 ${duration3}`,
17061
- usedPercent: window.used_percent,
17062
17066
  resetAt: window.reset_at === undefined ? null : new Date(window.reset_at * 1000).toISOString(),
17063
- kind: "hard"
17067
+ usedPercent: window.used_percent
17064
17068
  };
17065
17069
  }
17066
17070
  function appendLimitWindows(windows, prefix, label, details) {
@@ -17100,11 +17104,11 @@ function normalizeResponse(accountId, body) {
17100
17104
  }
17101
17105
  return {
17102
17106
  accountId,
17103
- provider: "openai",
17107
+ hardLimitReached: body.rate_limit?.limit_reached === true || body.rate_limit?.allowed === false || body.rate_limit_reached_type != null || (body.additional_rate_limits ?? []).some((additional) => additional.rate_limit?.limit_reached === true || additional.rate_limit?.allowed === false),
17104
17108
  observedAt: new Date().toISOString(),
17109
+ provider: "openai",
17105
17110
  source: "codexUsageEndpoint",
17106
- windows,
17107
- hardLimitReached: body.rate_limit?.limit_reached === true || body.rate_limit?.allowed === false || body.rate_limit_reached_type != null || (body.additional_rate_limits ?? []).some((additional) => additional.rate_limit?.limit_reached === true || additional.rate_limit?.allowed === false)
17111
+ windows
17108
17112
  };
17109
17113
  }
17110
17114
  function conservativeSnapshot(accountId, bodies) {
@@ -17124,9 +17128,9 @@ function conservativeSnapshot(accountId, bodies) {
17124
17128
  }
17125
17129
  return {
17126
17130
  ...head,
17131
+ hardLimitReached: snapshots.some((snapshot) => snapshot.hardLimitReached),
17127
17132
  observedAt: new Date().toISOString(),
17128
- windows: [...windows.values()],
17129
- hardLimitReached: snapshots.some((snapshot) => snapshot.hardLimitReached)
17133
+ windows: [...windows.values()]
17130
17134
  };
17131
17135
  }
17132
17136
  async function fetchUsageResponse(input) {
@@ -17152,7 +17156,7 @@ async function fetchUsageResponse(input) {
17152
17156
  async function fetchCodexUsage(input) {
17153
17157
  const identity = codexIdentity(input.credential);
17154
17158
  const fetchImplementation = input.fetchImplementation ?? fetch;
17155
- const bodies = await Promise.all(Array.from({ length: sampleCount }, () => fetchUsageResponse({ identity, credential: input.credential, fetchImplementation })));
17159
+ const bodies = await Promise.all(Array.from({ length: sampleCount }, () => fetchUsageResponse({ credential: input.credential, fetchImplementation, identity })));
17156
17160
  return conservativeSnapshot(input.accountId, bodies);
17157
17161
  }
17158
17162
 
@@ -17187,9 +17191,9 @@ class OpenAiProviderAdapter {
17187
17191
  throw error51;
17188
17192
  }
17189
17193
  credential = await refreshCodexCredential({
17194
+ fetchImplementation: this.#dependencies.fetchImplementation,
17190
17195
  reference: openAiAccount.secretReference,
17191
- vault: this.#vault,
17192
- fetchImplementation: this.#dependencies.fetchImplementation
17196
+ vault: this.#vault
17193
17197
  });
17194
17198
  identity = codexIdentity(credential);
17195
17199
  return fetchCodexUsage({
@@ -17204,10 +17208,10 @@ class OpenAiProviderAdapter {
17204
17208
  ...openAiAccount,
17205
17209
  externalAccountId: identity.accountId,
17206
17210
  externalUserId: identity.userId,
17207
- plan: identity.plan ?? openAiAccount.plan ?? null,
17208
- label: email3.success ? email3.data : openAiAccount.label,
17209
- identity: email3.success ? email3.data : openAiAccount.identity,
17210
17211
  health: "ready",
17212
+ identity: email3.success ? email3.data : openAiAccount.identity,
17213
+ label: email3.success ? email3.data : openAiAccount.label,
17214
+ plan: identity.plan ?? openAiAccount.plan ?? null,
17211
17215
  updatedAt: this.#dependencies.now().toISOString()
17212
17216
  },
17213
17217
  usage
@@ -17255,6 +17259,18 @@ function createUsageObserver(provider, contentType, onUsage) {
17255
17259
  }
17256
17260
  };
17257
17261
  return {
17262
+ finish() {
17263
+ if (!isSse && jsonBuffer.length > 0) {
17264
+ consume(jsonBuffer);
17265
+ }
17266
+ if (saw && input + output > 0) {
17267
+ onUsage({
17268
+ inputTokens: input,
17269
+ model: model && model.length > 0 ? model : null,
17270
+ outputTokens: output
17271
+ });
17272
+ }
17273
+ },
17258
17274
  push(chunk) {
17259
17275
  const text = decoder.decode(chunk, { stream: true });
17260
17276
  if (isSse) {
@@ -17276,32 +17292,20 @@ function createUsageObserver(provider, contentType, onUsage) {
17276
17292
  } else if (jsonBuffer.length < maxJson) {
17277
17293
  jsonBuffer += text;
17278
17294
  }
17279
- },
17280
- finish() {
17281
- if (!isSse && jsonBuffer.length > 0) {
17282
- consume(jsonBuffer);
17283
- }
17284
- if (saw && input + output > 0) {
17285
- onUsage({
17286
- model: model && model.length > 0 ? model : null,
17287
- inputTokens: input,
17288
- outputTokens: output
17289
- });
17290
- }
17291
17295
  }
17292
17296
  };
17293
17297
  }
17294
17298
  function observeStream(body, observer) {
17295
17299
  return body.pipeThrough(new TransformStream({
17296
- transform(chunk, controller) {
17297
- controller.enqueue(chunk);
17300
+ flush() {
17298
17301
  try {
17299
- observer.push(chunk);
17302
+ observer.finish();
17300
17303
  } catch {}
17301
17304
  },
17302
- flush() {
17305
+ transform(chunk, controller) {
17306
+ controller.enqueue(chunk);
17303
17307
  try {
17304
- observer.finish();
17308
+ observer.push(chunk);
17305
17309
  } catch {}
17306
17310
  }
17307
17311
  }));
@@ -17347,9 +17351,9 @@ function passThrough(response) {
17347
17351
  headers.delete(header);
17348
17352
  }
17349
17353
  return new Response(response.body, {
17354
+ headers,
17350
17355
  status: response.status,
17351
- statusText: response.statusText,
17352
- headers
17356
+ statusText: response.statusText
17353
17357
  });
17354
17358
  }
17355
17359
  function createProxyHandler(options) {
@@ -17364,9 +17368,9 @@ function createProxyHandler(options) {
17364
17368
  }
17365
17369
  const body = request.method === "GET" || request.method === "HEAD" ? undefined : await request.arrayBuffer();
17366
17370
  const send = (injection2) => doFetch(`${injection2.baseUrl.replace(/\/$/, "")}${route.rest}${url2.search}`, {
17367
- method: request.method,
17368
- headers: forwardHeaders(request.headers, injection2),
17369
17371
  body,
17372
+ headers: forwardHeaders(request.headers, injection2),
17373
+ method: request.method,
17370
17374
  redirect: "manual",
17371
17375
  signal: request.signal
17372
17376
  });
@@ -17406,15 +17410,15 @@ function createProxyHandler(options) {
17406
17410
  if (options.record !== undefined && response.ok && forwarded.body !== null) {
17407
17411
  const observer = createUsageObserver(route.provider, response.headers.get("content-type") ?? "", (usage) => options.record?.({
17408
17412
  at: Date.now(),
17409
- provider: route.provider,
17410
- model: usage.model,
17411
17413
  inputTokens: usage.inputTokens,
17412
- outputTokens: usage.outputTokens
17414
+ model: usage.model,
17415
+ outputTokens: usage.outputTokens,
17416
+ provider: route.provider
17413
17417
  }));
17414
17418
  return new Response(observeStream(forwarded.body, observer), {
17419
+ headers: forwarded.headers,
17415
17420
  status: forwarded.status,
17416
- statusText: forwarded.statusText,
17417
- headers: forwarded.headers
17421
+ statusText: forwarded.statusText
17418
17422
  });
17419
17423
  }
17420
17424
  return forwarded;
@@ -17424,10 +17428,10 @@ function createProxyHandler(options) {
17424
17428
  function startProxy(options) {
17425
17429
  const handler = createProxyHandler(options);
17426
17430
  const server = Bun.serve({
17431
+ fetch: (request) => handler.handle(request),
17427
17432
  hostname: "127.0.0.1",
17428
- port: options.port ?? 0,
17429
17433
  idleTimeout: 0,
17430
- fetch: (request) => handler.handle(request)
17434
+ port: options.port ?? 0
17431
17435
  });
17432
17436
  const port = server.port;
17433
17437
  if (port === undefined) {
@@ -17469,9 +17473,9 @@ function createRuntimeCredentialSource(dependencies) {
17469
17473
  const stale = expiry !== null && expiry - now() <= refreshMarginMilliseconds;
17470
17474
  if (forceRefresh || stale) {
17471
17475
  auth = await refreshCodexCredential({
17476
+ fetchImplementation,
17472
17477
  reference: account.secretReference,
17473
- vault: dependencies.vault,
17474
- fetchImplementation
17478
+ vault: dependencies.vault
17475
17479
  });
17476
17480
  }
17477
17481
  return {
@@ -17491,14 +17495,14 @@ function createRuntimeCredentialSource(dependencies) {
17491
17495
  const stale = credential.expiresAt - now() <= refreshMarginMilliseconds;
17492
17496
  if (forceRefresh || stale) {
17493
17497
  credential = await refreshClaudeProfile({
17494
- profilePath: account.profilePath,
17495
- credentialReader: reader
17498
+ credentialReader: reader,
17499
+ profilePath: account.profilePath
17496
17500
  });
17497
17501
  }
17498
17502
  return {
17503
+ appendHeaders: { "anthropic-beta": "oauth-2025-04-20" },
17499
17504
  baseUrl: upstreamFor("anthropic"),
17500
17505
  headers: { authorization: `Bearer ${credential.accessToken}` },
17501
- appendHeaders: { "anthropic-beta": "oauth-2025-04-20" },
17502
17506
  stripHeaders: ["x-api-key"]
17503
17507
  };
17504
17508
  }
@@ -17515,10 +17519,10 @@ function createRuntimeCredentialSource(dependencies) {
17515
17519
  }
17516
17520
  }
17517
17521
  return {
17518
- resolve: (provider) => injectionFor(provider, false),
17519
17522
  refresh: async (provider) => {
17520
17523
  await injectionFor(provider, true);
17521
- }
17524
+ },
17525
+ resolve: (provider) => injectionFor(provider, false)
17522
17526
  };
17523
17527
  }
17524
17528
 
@@ -17527,15 +17531,14 @@ init_zod();
17527
17531
  init_domain();
17528
17532
  var RotationDecisionSchema = exports_external.discriminatedUnion("rotate", [
17529
17533
  exports_external.object({
17534
+ reason: exports_external.enum(["threshold", "hardLimit"]),
17530
17535
  rotate: exports_external.literal(true),
17531
17536
  sourceAccountId: exports_external.uuid(),
17532
- targetAccountId: exports_external.uuid(),
17533
17537
  sourcePressure: exports_external.number().min(0).max(100),
17534
- targetPressure: exports_external.number().min(0).max(100),
17535
- reason: exports_external.enum(["threshold", "hardLimit"])
17538
+ targetAccountId: exports_external.uuid(),
17539
+ targetPressure: exports_external.number().min(0).max(100)
17536
17540
  }),
17537
17541
  exports_external.object({
17538
- rotate: exports_external.literal(false),
17539
17542
  reason: exports_external.enum([
17540
17543
  "disabled",
17541
17544
  "authorizationRequired",
@@ -17545,7 +17548,8 @@ var RotationDecisionSchema = exports_external.discriminatedUnion("rotate", [
17545
17548
  "belowThreshold",
17546
17549
  "minimumDwell",
17547
17550
  "noEligibleCandidate"
17548
- ])
17551
+ ]),
17552
+ rotate: exports_external.literal(false)
17549
17553
  })
17550
17554
  ]);
17551
17555
  function hardPressure(snapshot) {
@@ -17569,13 +17573,13 @@ function eligibleHealth(account) {
17569
17573
  function selectRotation(input) {
17570
17574
  const { policy } = input.state;
17571
17575
  if (!policy.enabled) {
17572
- return { rotate: false, reason: "disabled" };
17576
+ return { reason: "disabled", rotate: false };
17573
17577
  }
17574
17578
  if (policy.authorization !== "confirmed") {
17575
- return { rotate: false, reason: "authorizationRequired" };
17579
+ return { reason: "authorizationRequired", rotate: false };
17576
17580
  }
17577
17581
  if (input.state.activeAccountId === null) {
17578
- return { rotate: false, reason: "noActiveAccount" };
17582
+ return { reason: "noActiveAccount", rotate: false };
17579
17583
  }
17580
17584
  const snapshotByAccount = new Map(input.usage.map((snapshot) => {
17581
17585
  const parsed = UsageSnapshotSchema.parse(snapshot);
@@ -17583,22 +17587,22 @@ function selectRotation(input) {
17583
17587
  }));
17584
17588
  const activeSnapshot = snapshotByAccount.get(input.state.activeAccountId);
17585
17589
  if (activeSnapshot === undefined) {
17586
- return { rotate: false, reason: "activeUsageUnknown" };
17590
+ return { reason: "activeUsageUnknown", rotate: false };
17587
17591
  }
17588
17592
  if (!isFresh(activeSnapshot, input.now, policy.maximumSnapshotAgeMilliseconds)) {
17589
- return { rotate: false, reason: "activeUsageStale" };
17593
+ return { reason: "activeUsageStale", rotate: false };
17590
17594
  }
17591
17595
  const activePressure = hardPressure(activeSnapshot);
17592
17596
  if (activePressure === null) {
17593
- return { rotate: false, reason: "activeUsageUnknown" };
17597
+ return { reason: "activeUsageUnknown", rotate: false };
17594
17598
  }
17595
17599
  if (!activeSnapshot.hardLimitReached && activePressure < policy.thresholdPercent) {
17596
- return { rotate: false, reason: "belowThreshold" };
17600
+ return { reason: "belowThreshold", rotate: false };
17597
17601
  }
17598
17602
  if (input.state.switchedAt !== null) {
17599
17603
  const dwell = input.now.getTime() - Date.parse(input.state.switchedAt);
17600
17604
  if (dwell < policy.minimumDwellMilliseconds) {
17601
- return { rotate: false, reason: "minimumDwell" };
17605
+ return { reason: "minimumDwell", rotate: false };
17602
17606
  }
17603
17607
  }
17604
17608
  const targetCeiling = policy.thresholdPercent - policy.hysteresisPercent;
@@ -17615,15 +17619,15 @@ function selectRotation(input) {
17615
17619
  }).sort((left, right) => left.pressure - right.pressure || left.account.id.localeCompare(right.account.id));
17616
17620
  const target = candidates[0];
17617
17621
  if (target === undefined) {
17618
- return { rotate: false, reason: "noEligibleCandidate" };
17622
+ return { reason: "noEligibleCandidate", rotate: false };
17619
17623
  }
17620
17624
  return {
17625
+ reason: activeSnapshot.hardLimitReached ? "hardLimit" : "threshold",
17621
17626
  rotate: true,
17622
17627
  sourceAccountId: input.state.activeAccountId,
17623
- targetAccountId: target.account.id,
17624
17628
  sourcePressure: activePressure,
17625
- targetPressure: target.pressure,
17626
- reason: activeSnapshot.hardLimitReached ? "hardLimit" : "threshold"
17629
+ targetAccountId: target.account.id,
17630
+ targetPressure: target.pressure
17627
17631
  };
17628
17632
  }
17629
17633
 
@@ -17633,8 +17637,8 @@ function priceTokenTimeframe(aggregate) {
17633
17637
  let totalOutput = 0;
17634
17638
  let costTotal = 0;
17635
17639
  const byProvider = {
17636
- openai: { tokens: 0, costUsd: 0 },
17637
- anthropic: { tokens: 0, costUsd: 0 }
17640
+ anthropic: { costUsd: 0, tokens: 0 },
17641
+ openai: { costUsd: 0, tokens: 0 }
17638
17642
  };
17639
17643
  let top = null;
17640
17644
  for (const entry of aggregate.byModel) {
@@ -17652,16 +17656,16 @@ function priceTokenTimeframe(aggregate) {
17652
17656
  }
17653
17657
  const peakBucket = aggregate.buckets.reduce((max, value) => Math.max(max, value), 0);
17654
17658
  return {
17655
- key: aggregate.key,
17656
- buckets: aggregate.buckets,
17657
17659
  bucketMs: aggregate.bucketMs,
17658
- totalTokens: totalInput + totalOutput,
17659
- totalInput,
17660
- totalOutput,
17660
+ buckets: aggregate.buckets,
17661
+ byProvider,
17661
17662
  costUsd: costTotal,
17663
+ key: aggregate.key,
17662
17664
  peakPerHour: peakBucket * (3600000 / aggregate.bucketMs),
17663
17665
  topModel: top?.model ?? null,
17664
- byProvider
17666
+ totalInput,
17667
+ totalOutput,
17668
+ totalTokens: totalInput + totalOutput
17665
17669
  };
17666
17670
  }
17667
17671
  var defaultDependencies = {
@@ -17706,11 +17710,11 @@ class AccountManager {
17706
17710
  this.#vault = input.vault;
17707
17711
  this.#dependencies = { ...defaultDependencies, ...input.dependencies };
17708
17712
  this.#adapters = input.adapters ?? {
17713
+ anthropic: new AnthropicProviderAdapter({ dependencies: this.#dependencies }),
17709
17714
  openai: new OpenAiProviderAdapter({
17710
- vault: input.vault,
17711
- dependencies: this.#dependencies
17712
- }),
17713
- anthropic: new AnthropicProviderAdapter({ dependencies: this.#dependencies })
17715
+ dependencies: this.#dependencies,
17716
+ vault: input.vault
17717
+ })
17714
17718
  };
17715
17719
  if (this.#adapters.openai.provider !== "openai" || this.#adapters.anthropic.provider !== "anthropic") {
17716
17720
  throw new ApplicationError("PROVIDER_MISMATCH", "Injected provider adapters do not match their registry keys");
@@ -17722,12 +17726,11 @@ class AccountManager {
17722
17726
  async start() {
17723
17727
  this.#stopping = false;
17724
17728
  const source = createRuntimeCredentialSource({
17729
+ fetchImplementation: this.#dependencies.fetchImplementation,
17725
17730
  store: { activeAccount: (provider) => this.activeAccount(provider) },
17726
- vault: this.#vault,
17727
- fetchImplementation: this.#dependencies.fetchImplementation
17731
+ vault: this.#vault
17728
17732
  });
17729
17733
  this.#proxy = startProxy({
17730
- source,
17731
17734
  port: this.#paths.proxyPort,
17732
17735
  record: (event) => {
17733
17736
  try {
@@ -17736,7 +17739,8 @@ class AccountManager {
17736
17739
  accountId: this.activeAccount(event.provider)?.id ?? null
17737
17740
  });
17738
17741
  } catch {}
17739
- }
17742
+ },
17743
+ source
17740
17744
  });
17741
17745
  this.refreshAll().catch(() => {
17742
17746
  return;
@@ -17769,11 +17773,11 @@ class AccountManager {
17769
17773
  const snapshot = this.#store.dashboard();
17770
17774
  const nowMillis = this.#dependencies.now().getTime();
17771
17775
  return {
17772
- snapshot,
17773
17776
  history: snapshot.accounts.map((account) => ({
17774
17777
  accountId: account.id,
17775
17778
  windows: this.#store.usageHistory(account.id)
17776
17779
  })),
17780
+ snapshot,
17777
17781
  tokens: {
17778
17782
  timeframes: this.#store.tokenAnalytics(nowMillis, TIMEFRAMES).map(priceTokenTimeframe)
17779
17783
  }
@@ -17801,10 +17805,10 @@ class AccountManager {
17801
17805
  if (state.activeAccountId === null) {
17802
17806
  this.commitActivation({
17803
17807
  provider: input.account.provider,
17804
- state,
17808
+ reason: "first-account",
17805
17809
  sourceAccountId: null,
17806
- target: input.account,
17807
- reason: "first-account"
17810
+ state,
17811
+ target: input.account
17808
17812
  });
17809
17813
  }
17810
17814
  });
@@ -17813,9 +17817,9 @@ class AccountManager {
17813
17817
  const current = this.#store.findProviderState(input.provider).policy;
17814
17818
  const policy = AutomationPolicySchema.parse({
17815
17819
  ...current,
17820
+ authorization: input.authorizationConfirmed ? "confirmed" : current.authorization,
17816
17821
  enabled: input.enabled,
17817
- thresholdPercent: input.thresholdPercent ?? current.thresholdPercent,
17818
- authorization: input.authorizationConfirmed ? "confirmed" : current.authorization
17822
+ thresholdPercent: input.thresholdPercent ?? current.thresholdPercent
17819
17823
  });
17820
17824
  if (policy.enabled && policy.authorization !== "confirmed") {
17821
17825
  throw new ApplicationError("AUTHORIZATION_REQUIRED", "Automatic rotation requires explicit confirmation that your provider authorizes this use");
@@ -17854,10 +17858,10 @@ class AccountManager {
17854
17858
  }
17855
17859
  this.commitActivation({
17856
17860
  provider,
17857
- state,
17861
+ reason,
17858
17862
  sourceAccountId: state.activeAccountId,
17859
- target,
17860
- reason
17863
+ state,
17864
+ target
17861
17865
  });
17862
17866
  });
17863
17867
  }
@@ -17907,9 +17911,9 @@ class AccountManager {
17907
17911
  const state = this.#store.findProviderState(provider);
17908
17912
  const decision = selectRotation({
17909
17913
  accounts: this.#store.listAccounts(provider),
17910
- usage: this.#store.listUsage(),
17914
+ now: this.#dependencies.now(),
17911
17915
  state,
17912
- now: this.#dependencies.now()
17916
+ usage: this.#store.listUsage()
17913
17917
  });
17914
17918
  if (decision.rotate) {
17915
17919
  await this.performSwitchForAutomation(provider, decision.targetAccountId, decision.reason);
@@ -17923,24 +17927,24 @@ class AccountManager {
17923
17927
  }
17924
17928
  this.commitActivation({
17925
17929
  provider,
17926
- state,
17930
+ reason: `automatic:${reason}`,
17927
17931
  sourceAccountId: state.activeAccountId,
17928
- target,
17929
- reason: `automatic:${reason}`
17932
+ state,
17933
+ target
17930
17934
  });
17931
17935
  }
17932
17936
  commitActivation(input) {
17933
17937
  const now = this.#dependencies.now().toISOString();
17934
17938
  this.#store.commitSwitch(SwitchRecordSchema.parse({
17939
+ createdAt: now,
17940
+ generation: input.state.generation + 1,
17935
17941
  id: crypto.randomUUID(),
17942
+ message: null,
17943
+ phase: "committed",
17936
17944
  provider: input.provider,
17945
+ reason: input.reason,
17937
17946
  sourceAccountId: input.sourceAccountId,
17938
17947
  targetAccountId: input.target.id,
17939
- phase: "committed",
17940
- reason: input.reason,
17941
- generation: input.state.generation + 1,
17942
- message: null,
17943
- createdAt: now,
17944
17948
  updatedAt: now
17945
17949
  }), {
17946
17950
  ...input.state,
@@ -17981,23 +17985,23 @@ class AccountManager {
17981
17985
  init_zod();
17982
17986
  var CommandResultSchema = exports_external.object({
17983
17987
  exitCode: exports_external.number().int(),
17984
- stdout: exports_external.string(),
17985
- stderr: exports_external.string()
17988
+ stderr: exports_external.string(),
17989
+ stdout: exports_external.string()
17986
17990
  });
17987
17991
  async function runCommand(command, options = {}) {
17988
17992
  const processHandle = Bun.spawn([...command], {
17989
17993
  cwd: options.cwd,
17990
17994
  env: { ...process.env, ...options.environment },
17995
+ stderr: options.stderr ?? "pipe",
17991
17996
  stdin: options.stdin ?? "ignore",
17992
- stdout: options.stdout ?? "pipe",
17993
- stderr: options.stderr ?? "pipe"
17997
+ stdout: options.stdout ?? "pipe"
17994
17998
  });
17995
17999
  const [exitCode, stdout, stderr] = await Promise.all([
17996
18000
  processHandle.exited,
17997
18001
  options.stdout === "inherit" ? Promise.resolve("") : new Response(processHandle.stdout).text(),
17998
18002
  options.stderr === "inherit" ? Promise.resolve("") : new Response(processHandle.stderr).text()
17999
18003
  ]);
18000
- return CommandResultSchema.parse({ exitCode, stdout, stderr });
18004
+ return CommandResultSchema.parse({ exitCode, stderr, stdout });
18001
18005
  }
18002
18006
 
18003
18007
  // src/providers/codex/keychain.ts
@@ -18012,9 +18016,9 @@ function defaultKeychainCommandRunner() {
18012
18016
  return {
18013
18017
  async run(command, stdinText) {
18014
18018
  const processHandle = Bun.spawn([...command], {
18019
+ stderr: "pipe",
18015
18020
  stdin: "pipe",
18016
- stdout: "pipe",
18017
- stderr: "pipe"
18021
+ stdout: "pipe"
18018
18022
  });
18019
18023
  if (stdinText !== undefined) {
18020
18024
  processHandle.stdin.write(stdinText);
@@ -18025,7 +18029,7 @@ function defaultKeychainCommandRunner() {
18025
18029
  new Response(processHandle.stdout).text(),
18026
18030
  new Response(processHandle.stderr).text()
18027
18031
  ]);
18028
- return { exitCode, stdout, stderr };
18032
+ return { exitCode, stderr, stdout };
18029
18033
  }
18030
18034
  };
18031
18035
  }
@@ -18120,6 +18124,11 @@ function createMacOsKeychainVault(service = defaultService, runner = defaultKeyc
18120
18124
  }
18121
18125
  return Buffer.from(chunks.join(""), "base64").toString("utf8");
18122
18126
  },
18127
+ async remove(reference) {
18128
+ requireSafeIdentifier("reference", reference);
18129
+ await deleteItem(reference);
18130
+ await deleteChunksFrom(reference, 0);
18131
+ },
18123
18132
  async write(reference, value) {
18124
18133
  requireSafeIdentifier("reference", reference);
18125
18134
  const encoded = Buffer.from(value, "utf8").toString("base64");
@@ -18137,11 +18146,6 @@ function createMacOsKeychainVault(service = defaultService, runner = defaultKeyc
18137
18146
  }
18138
18147
  await writeItem(reference, Buffer.from(`${manifestPrefix}${chunkCount}`, "utf8").toString("base64"));
18139
18148
  await deleteChunksFrom(reference, chunkCount);
18140
- },
18141
- async remove(reference) {
18142
- requireSafeIdentifier("reference", reference);
18143
- await deleteItem(reference);
18144
- await deleteChunksFrom(reference, 0);
18145
18149
  }
18146
18150
  };
18147
18151
  }
@@ -18178,19 +18182,19 @@ function serialize(value) {
18178
18182
  }
18179
18183
  function initialProviderState(provider) {
18180
18184
  return ProviderStateSchema.parse({
18181
- provider,
18182
18185
  activeAccountId: null,
18183
18186
  generation: 0,
18184
- switchedAt: null,
18185
18187
  policy: {
18186
- provider,
18188
+ authorization: "notConfirmed",
18187
18189
  enabled: false,
18188
- thresholdPercent: 95,
18189
18190
  hysteresisPercent: 5,
18190
- minimumDwellMilliseconds: 300000,
18191
18191
  maximumSnapshotAgeMilliseconds: 120000,
18192
- authorization: "notConfirmed"
18193
- }
18192
+ minimumDwellMilliseconds: 300000,
18193
+ provider,
18194
+ thresholdPercent: 95
18195
+ },
18196
+ provider,
18197
+ switchedAt: null
18194
18198
  });
18195
18199
  }
18196
18200
  function migrate(database) {
@@ -18375,9 +18379,9 @@ function createStateStore(databasePath) {
18375
18379
  }
18376
18380
  function usageHistory(accountId) {
18377
18381
  return database.query("SELECT window_id, label, points FROM usage_history WHERE account_id = ? ORDER BY window_id").all(accountId).map((row) => ({
18378
- windowId: row.window_id,
18379
18382
  label: row.label,
18380
- points: UsageHistoryPointSchema.array().parse(JSON.parse(row.points))
18383
+ points: UsageHistoryPointSchema.array().parse(JSON.parse(row.points)),
18384
+ windowId: row.window_id
18381
18385
  }));
18382
18386
  }
18383
18387
  function listProviderStates() {
@@ -18429,9 +18433,9 @@ function createStateStore(databasePath) {
18429
18433
  function dashboard() {
18430
18434
  return database.transaction(() => DashboardSnapshotSchema.parse({
18431
18435
  accounts: listAccounts(),
18432
- usage: listUsage(),
18433
18436
  providers: listProviderStates(),
18434
- sampledAt: new Date().toISOString()
18437
+ sampledAt: new Date().toISOString(),
18438
+ usage: listUsage()
18435
18439
  }))();
18436
18440
  }
18437
18441
  function recordTokenEvent(event) {
@@ -18451,46 +18455,46 @@ function createStateStore(databasePath) {
18451
18455
  buckets[index] = (buckets[index] ?? 0) + row.tokens;
18452
18456
  }
18453
18457
  const byModel = modelQuery.all(start, nowMillis).map((row) => ({
18454
- model: row.model ?? "unknown",
18455
- provider: row.provider,
18456
18458
  input: row.input,
18457
- output: row.output
18459
+ model: row.model ?? "unknown",
18460
+ output: row.output,
18461
+ provider: row.provider
18458
18462
  }));
18459
- return { key, bucketMs, buckets, byModel };
18463
+ return { bucketMs, buckets, byModel, key };
18460
18464
  });
18461
18465
  }
18462
18466
  return {
18463
18467
  close: () => database.close(),
18464
- recordTokenEvent,
18465
- tokenAnalytics,
18466
- listAccounts,
18468
+ commitSwitch,
18469
+ dashboard,
18467
18470
  findAccount,
18468
- saveAccount,
18469
- removeAccount,
18470
- listUsage,
18471
+ findProviderState,
18471
18472
  findUsage,
18472
- saveUsage,
18473
+ listAccounts,
18473
18474
  listProviderStates,
18474
- findProviderState,
18475
- saveProviderState,
18476
- saveAutomationPolicy,
18477
18475
  listSwitchRecords,
18476
+ listUsage,
18477
+ recordTokenEvent,
18478
+ removeAccount,
18479
+ saveAccount,
18480
+ saveAutomationPolicy,
18481
+ saveProviderState,
18478
18482
  saveSwitchRecord,
18479
- commitSwitch,
18480
- usageHistory,
18481
- dashboard
18483
+ saveUsage,
18484
+ tokenAnalytics,
18485
+ usageHistory
18482
18486
  };
18483
18487
  }
18484
18488
 
18485
18489
  // src/ui.ts
18486
18490
  var ansi = {
18487
- reset: "\x1B[0m",
18488
18491
  bold: "\x1B[1m",
18492
+ cyan: "\x1B[36m",
18489
18493
  dim: "\x1B[2m",
18490
- red: "\x1B[31m",
18491
18494
  green: "\x1B[32m",
18492
- yellow: "\x1B[33m",
18493
- cyan: "\x1B[36m"
18495
+ red: "\x1B[31m",
18496
+ reset: "\x1B[0m",
18497
+ yellow: "\x1B[33m"
18494
18498
  };
18495
18499
  function createPainter(enabled) {
18496
18500
  return (value, ...codes) => enabled && codes.length > 0 ? `${codes.map((code) => ansi[code]).join("")}${value}${ansi.reset}` : value;
@@ -18784,8 +18788,8 @@ async function runDaemon(context) {
18784
18788
  });
18785
18789
  const server = await startManagerServer({
18786
18790
  manager,
18787
- socketPath: context.paths.managerSocket,
18788
- onStop: () => requestStop?.()
18791
+ onStop: () => requestStop?.(),
18792
+ socketPath: context.paths.managerSocket
18789
18793
  });
18790
18794
  const signalHandler = () => requestStop?.();
18791
18795
  process.once("SIGINT", signalHandler);
@@ -18803,7 +18807,7 @@ async function startDaemon(context) {
18803
18807
  if (await managerAvailable(context.paths.managerSocket)) {
18804
18808
  return;
18805
18809
  }
18806
- await mkdir4(context.paths.runtime, { recursive: true, mode: 448 });
18810
+ await mkdir4(context.paths.runtime, { mode: 448, recursive: true });
18807
18811
  const entrypoint = process.argv[1];
18808
18812
  if (entrypoint === undefined) {
18809
18813
  throw new ApplicationError("ENTRYPOINT_MISSING", "Cannot locate the CLI entrypoint");
@@ -18839,9 +18843,9 @@ async function startDaemon(context) {
18839
18843
  }
18840
18844
  async function stopDaemon(context) {
18841
18845
  await managerRequest({
18842
- socketPath: context.paths.managerSocket,
18843
18846
  method: "manager/stop",
18844
18847
  schema: EmptyResultSchema,
18848
+ socketPath: context.paths.managerSocket,
18845
18849
  timeoutMilliseconds: 1000
18846
18850
  });
18847
18851
  const deadline = Date.now() + 15000;
@@ -18881,14 +18885,14 @@ async function login(context, providerArgument) {
18881
18885
  const existing = context.store.listAccounts(provider).find((candidate) => candidate.externalAccountId !== null && candidate.externalAccountId === authenticated.externalAccountId);
18882
18886
  const account2 = existing === undefined ? authenticated : {
18883
18887
  ...authenticated,
18884
- id: existing.id,
18888
+ createdAt: existing.createdAt,
18885
18889
  enabled: existing.enabled,
18886
- createdAt: existing.createdAt
18890
+ id: existing.id
18887
18891
  };
18888
18892
  try {
18889
18893
  await requestAccountSave(context.paths.managerSocket, account2, {
18890
- secretReference: existing?.secretReference ?? null,
18891
- profilePath: existing?.profilePath ?? null
18894
+ profilePath: existing?.profilePath ?? null,
18895
+ secretReference: existing?.secretReference ?? null
18892
18896
  });
18893
18897
  } catch (error51) {
18894
18898
  await removeUnstoredAccount(authenticated);
@@ -18915,16 +18919,16 @@ function resolveAccount(store, provider, reference) {
18915
18919
  return account2;
18916
18920
  }
18917
18921
  var healthText = {
18918
- unchecked: "checking",
18922
+ disabled: "disabled",
18923
+ loginExpiring: "login expiring soon",
18919
18924
  ready: "ready",
18925
+ reauthenticationRequired: "login required \u2014 tokenmaxx login",
18920
18926
  refreshDue: "refreshing",
18921
18927
  refreshing: "refreshing",
18922
- loginExpiring: "login expiring soon",
18923
18928
  scopeMissing: "missing a scope",
18924
- reauthenticationRequired: "login required \u2014 tokenmaxx login",
18925
18929
  temporarilyUnreachable: "provider unreachable",
18926
- usageRateLimited: "rate-limited",
18927
- disabled: "disabled"
18930
+ unchecked: "checking",
18931
+ usageRateLimited: "rate-limited"
18928
18932
  };
18929
18933
  function listAccounts(context) {
18930
18934
  const states = new Map(context.store.listProviderStates().map((state) => [state.provider, state]));
@@ -18985,15 +18989,15 @@ async function configureAutomation(context, arguments_) {
18985
18989
  let effectiveThreshold = thresholdPercent ?? 95;
18986
18990
  for (const provider of providers) {
18987
18991
  const state = await managerRequest({
18988
- socketPath: context.paths.managerSocket,
18989
18992
  method: "policy/set",
18990
18993
  params: {
18991
- provider,
18994
+ authorizationConfirmed: mode === "on",
18992
18995
  enabled: mode === "on",
18993
- thresholdPercent,
18994
- authorizationConfirmed: mode === "on"
18996
+ provider,
18997
+ thresholdPercent
18995
18998
  },
18996
- schema: exports_external.object({ policy: exports_external.object({ thresholdPercent: exports_external.number() }) })
18999
+ schema: exports_external.object({ policy: exports_external.object({ thresholdPercent: exports_external.number() }) }),
19000
+ socketPath: context.paths.managerSocket
18997
19001
  });
18998
19002
  effectiveThreshold = state.policy.thresholdPercent;
18999
19003
  }
@@ -19081,8 +19085,8 @@ async function runCli(rawArguments) {
19081
19085
  ]);
19082
19086
  const now = process.env.TOKENMAXX_NOW ? Number(process.env.TOKENMAXX_NOW) : FIXTURE_NOW2;
19083
19087
  await runTuiDashboard2(context.paths.managerSocket, {
19084
- installed: process.env.TOKENMAXX_INSTALLED !== "false",
19085
19088
  fixture: buildScenario2(fixtureName, now),
19089
+ installed: process.env.TOKENMAXX_INSTALLED !== "false",
19086
19090
  now
19087
19091
  });
19088
19092
  context.store.close();
@@ -19117,9 +19121,9 @@ async function runCli(rawArguments) {
19117
19121
  case "refresh":
19118
19122
  await ensureDaemon(context);
19119
19123
  await managerRequest({
19120
- socketPath: context.paths.managerSocket,
19121
19124
  method: "usage/refresh",
19122
19125
  schema: exports_external.unknown(),
19126
+ socketPath: context.paths.managerSocket,
19123
19127
  timeoutMilliseconds: 60000
19124
19128
  });
19125
19129
  process.stdout.write(`Re-probed usage for every account.