agl 43.1.0 → 43.3.0

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 (259) hide show
  1. package/changelog.md +32 -0
  2. package/dist_serve/bundle.js +5950 -5530
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +31 -31
  5. package/dist_serve/bundle.js.third-party-notices.txt +31 -31
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +521 -17
  8. package/dist_ts/aglapi/interfaces.d.ts +3 -0
  9. package/dist_ts/aglapi/interfaces.js +2 -1
  10. package/dist_ts/classes.accountsactions.d.ts +3 -1
  11. package/dist_ts/classes.accountsactions.js +21 -3
  12. package/dist_ts/classes.authmodels.js +17 -4
  13. package/dist_ts/classes.authstore.js +16 -2
  14. package/dist_ts/classes.claudeharness.d.ts +16 -0
  15. package/dist_ts/classes.claudeharness.js +24 -2
  16. package/dist_ts/classes.cli.d.ts +4 -2
  17. package/dist_ts/classes.cli.js +6 -3
  18. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  19. package/dist_ts/classes.codexclientadapter.js +14 -2
  20. package/dist_ts/classes.controller.d.ts +175 -11
  21. package/dist_ts/classes.controller.js +1213 -173
  22. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  23. package/dist_ts/classes.controllerdevices.js +6 -1
  24. package/dist_ts/classes.controllermanagement.d.ts +14 -4
  25. package/dist_ts/classes.controllermanagement.js +20 -2
  26. package/dist_ts/classes.gatewayclient.d.ts +115 -0
  27. package/dist_ts/classes.gatewayclient.js +336 -0
  28. package/dist_ts/classes.gatewayclientstore.d.ts +97 -0
  29. package/dist_ts/classes.gatewayclientstore.js +261 -0
  30. package/dist_ts/classes.inbox.d.ts +72 -0
  31. package/dist_ts/classes.inbox.js +231 -0
  32. package/dist_ts/classes.inferencerouter.d.ts +19 -0
  33. package/dist_ts/classes.inferencerouter.js +15 -3
  34. package/dist_ts/classes.inferenceservice.d.ts +9 -0
  35. package/dist_ts/classes.inferenceservice.js +28 -2
  36. package/dist_ts/classes.mcpclient.d.ts +4 -1
  37. package/dist_ts/classes.mcpclient.js +42 -6
  38. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -1
  39. package/dist_ts/classes.mcpcontrollerhost.js +11 -1
  40. package/dist_ts/classes.mcptools.d.ts +3 -3
  41. package/dist_ts/classes.mcptools.js +38 -8
  42. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  43. package/dist_ts/classes.mcpvalidation.js +38 -2
  44. package/dist_ts/classes.nativesessions.d.ts +17 -4
  45. package/dist_ts/classes.nativesessions.js +41 -9
  46. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  47. package/dist_ts/classes.opencodeclient.js +47 -3
  48. package/dist_ts/classes.proxycontrol.d.ts +11 -0
  49. package/dist_ts/classes.proxycontrol.js +7 -1
  50. package/dist_ts/classes.proxycontrolclient.d.ts +17 -0
  51. package/dist_ts/classes.proxycontrolclient.js +35 -1
  52. package/dist_ts/classes.proxydaemon.js +8 -1
  53. package/dist_ts/classes.proxymonitor.d.ts +7 -0
  54. package/dist_ts/classes.proxymonitor.js +13 -1
  55. package/dist_ts/classes.publishedset.d.ts +38 -0
  56. package/dist_ts/classes.publishedset.js +50 -0
  57. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  58. package/dist_ts/classes.sessionfeed.js +18 -26
  59. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  60. package/dist_ts/classes.systemmetricssampler.js +15 -3
  61. package/dist_ts/classes.ticketstore.d.ts +50 -3
  62. package/dist_ts/classes.ticketstore.js +45 -8
  63. package/dist_ts/classes.trustedproxysecrets.d.ts +2 -0
  64. package/dist_ts/classes.trustedproxysecrets.js +5 -1
  65. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  66. package/dist_ts/driver/classes.directreports.js +25 -6
  67. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  68. package/dist_ts/driver/classes.driverservice.js +50 -16
  69. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  70. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  71. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  72. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  73. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  74. package/dist_ts/fleet/classes.workercommand.js +15 -4
  75. package/dist_ts/fleet/classes.workers.d.ts +5 -1
  76. package/dist_ts/fleet/classes.workers.js +8 -2
  77. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  78. package/dist_ts/fleet/functions.workervalidation.js +2 -2
  79. package/dist_ts/fleet/interfaces.workers.d.ts +21 -3
  80. package/dist_ts/fleet/interfaces.workers.js +1 -1
  81. package/dist_ts/functions.agentmessage.d.ts +3 -0
  82. package/dist_ts/functions.agentmessage.js +4 -1
  83. package/dist_ts/functions.controllermanagementsurface.d.ts +4 -0
  84. package/dist_ts/functions.controllermanagementsurface.js +15 -1
  85. package/dist_ts/functions.deviceapi.d.ts +151 -4
  86. package/dist_ts/functions.deviceapi.js +893 -38
  87. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  88. package/dist_ts/functions.fleetworkercli.js +11 -8
  89. package/dist_ts/functions.gatewaycli.d.ts +24 -0
  90. package/dist_ts/functions.gatewaycli.js +395 -0
  91. package/dist_ts/functions.gatewayroute.d.ts +135 -0
  92. package/dist_ts/functions.gatewayroute.js +366 -0
  93. package/dist_ts/functions.inferencecli.js +32 -1
  94. package/dist_ts/functions.inferencecliarguments.d.ts +8 -2
  95. package/dist_ts/functions.inferencecliarguments.js +31 -3
  96. package/dist_ts/functions.mcpfleetworkertools.js +2 -2
  97. package/dist_ts/functions.proxycapacity.d.ts +50 -0
  98. package/dist_ts/functions.proxycapacity.js +142 -0
  99. package/dist_ts/functions.proxycapacitycli.d.ts +30 -0
  100. package/dist_ts/functions.proxycapacitycli.js +65 -0
  101. package/dist_ts/functions.remotecli.d.ts +30 -3
  102. package/dist_ts/functions.remotecli.js +44 -18
  103. package/dist_ts/functions.ticketvalidation.js +11 -2
  104. package/dist_ts/interfaces.auth.d.ts +25 -4
  105. package/dist_ts/interfaces.auth.js +15 -1
  106. package/dist_ts/plugins.d.ts +5 -1
  107. package/dist_ts/plugins.js +10 -2
  108. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  109. package/dist_ts_authswitch/authority-contract.js +1 -1
  110. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  111. package/dist_ts_authswitch/authority-overview.js +17 -6
  112. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  113. package/dist_ts_authswitch/authority-placement.js +19 -26
  114. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  115. package/dist_ts_authswitch/authority-renewal.js +56 -0
  116. package/dist_ts_authswitch/authority-usagelimit.d.ts +29 -0
  117. package/dist_ts_authswitch/authority-usagelimit.js +66 -2
  118. package/dist_ts_authswitch/authority-usagewindows.d.ts +6 -0
  119. package/dist_ts_authswitch/authority-usagewindows.js +15 -1
  120. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  121. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  122. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  123. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  124. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  125. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  126. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  127. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  128. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  129. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  130. package/dist_ts_interfaces/devices.d.ts +1012 -5
  131. package/dist_ts_interfaces/devices.js +68 -2
  132. package/dist_ts_interfaces/fleetworkers.d.ts +5 -3
  133. package/dist_ts_interfaces/gateway.d.ts +151 -0
  134. package/dist_ts_interfaces/gateway.js +66 -0
  135. package/dist_ts_interfaces/inbox.d.ts +234 -0
  136. package/dist_ts_interfaces/inbox.js +101 -0
  137. package/dist_ts_interfaces/index.d.ts +3 -0
  138. package/dist_ts_interfaces/index.js +4 -1
  139. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  140. package/dist_ts_interfaces/interfaces.js +4 -2
  141. package/dist_ts_interfaces/management.d.ts +4 -4
  142. package/dist_ts_interfaces/management.js +3 -2
  143. package/dist_ts_interfaces/mcprequests.d.ts +48 -6
  144. package/dist_ts_interfaces/mcprequests.js +12 -1
  145. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  146. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  147. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  148. package/dist_ts_interfaces/plugins.d.ts +2 -1
  149. package/dist_ts_interfaces/plugins.js +4 -2
  150. package/dist_ts_interfaces/proxycapacity.d.ts +99 -0
  151. package/dist_ts_interfaces/proxycapacity.js +74 -0
  152. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  153. package/dist_ts_interfaces/requests.accounts.js +3 -1
  154. package/dist_ts_interfaces/requests.d.ts +3 -2
  155. package/dist_ts_interfaces/requests.js +1 -1
  156. package/docs/authswitch.md +20 -1
  157. package/package.json +6 -5
  158. package/readme.md +191 -31
  159. package/ts/00_commitinfo_data.ts +1 -1
  160. package/ts/aglapi/aglapisurface.document.ts +520 -16
  161. package/ts/aglapi/interfaces.ts +1 -0
  162. package/ts/classes.accountsactions.ts +30 -3
  163. package/ts/classes.authmodels.ts +22 -3
  164. package/ts/classes.authstore.ts +15 -1
  165. package/ts/classes.claudeharness.ts +27 -1
  166. package/ts/classes.cli.ts +7 -3
  167. package/ts/classes.codexclientadapter.ts +14 -1
  168. package/ts/classes.controller.ts +1428 -249
  169. package/ts/classes.controllerdevices.ts +6 -0
  170. package/ts/classes.controllermanagement.ts +40 -7
  171. package/ts/classes.gatewayclient.ts +401 -0
  172. package/ts/classes.gatewayclientstore.ts +272 -0
  173. package/ts/classes.inbox.ts +239 -0
  174. package/ts/classes.inferencerouter.ts +27 -2
  175. package/ts/classes.inferenceservice.ts +28 -1
  176. package/ts/classes.mcpclient.ts +42 -3
  177. package/ts/classes.mcpcontrollerhost.ts +15 -0
  178. package/ts/classes.mcptools.ts +42 -9
  179. package/ts/classes.mcpvalidation.ts +32 -1
  180. package/ts/classes.nativesessions.ts +50 -12
  181. package/ts/classes.opencodeclient.ts +55 -4
  182. package/ts/classes.proxycontrol.ts +16 -0
  183. package/ts/classes.proxycontrolclient.ts +30 -0
  184. package/ts/classes.proxydaemon.ts +8 -0
  185. package/ts/classes.proxymonitor.ts +12 -0
  186. package/ts/classes.publishedset.ts +56 -0
  187. package/ts/classes.sessionfeed.ts +17 -20
  188. package/ts/classes.systemmetricssampler.ts +13 -2
  189. package/ts/classes.ticketstore.ts +73 -12
  190. package/ts/classes.trustedproxysecrets.ts +5 -0
  191. package/ts/driver/classes.directreports.ts +25 -6
  192. package/ts/driver/classes.driverservice.ts +75 -14
  193. package/ts/fleet/classes.claudeworkers.ts +112 -39
  194. package/ts/fleet/classes.codexworkers.ts +21 -6
  195. package/ts/fleet/classes.workercommand.ts +14 -4
  196. package/ts/fleet/classes.workers.ts +9 -2
  197. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  198. package/ts/fleet/functions.workervalidation.ts +1 -1
  199. package/ts/fleet/interfaces.workers.ts +20 -5
  200. package/ts/functions.agentmessage.ts +3 -0
  201. package/ts/functions.controllermanagementsurface.ts +15 -0
  202. package/ts/functions.deviceapi.ts +1071 -34
  203. package/ts/functions.fleetworkercli.ts +10 -7
  204. package/ts/functions.gatewaycli.ts +436 -0
  205. package/ts/functions.gatewayroute.ts +429 -0
  206. package/ts/functions.inferencecli.ts +26 -0
  207. package/ts/functions.inferencecliarguments.ts +30 -4
  208. package/ts/functions.mcpfleetworkertools.ts +1 -1
  209. package/ts/functions.proxycapacity.ts +191 -0
  210. package/ts/functions.proxycapacitycli.ts +104 -0
  211. package/ts/functions.remotecli.ts +56 -20
  212. package/ts/functions.ticketvalidation.ts +11 -1
  213. package/ts/interfaces.auth.ts +36 -4
  214. package/ts/plugins.ts +12 -0
  215. package/ts_authswitch/authority-contract.ts +20 -0
  216. package/ts_authswitch/authority-overview.ts +28 -6
  217. package/ts_authswitch/authority-placement.ts +27 -32
  218. package/ts_authswitch/authority-renewal.ts +64 -0
  219. package/ts_authswitch/authority-usagelimit.ts +84 -1
  220. package/ts_authswitch/authority-usagewindows.ts +13 -0
  221. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  222. package/ts_authswitch/classes.authoritycli.ts +49 -2
  223. package/ts_authswitch/classes.authorityclient.ts +14 -4
  224. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  225. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  226. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  227. package/ts_authswitch/native-contracts.md +21 -0
  228. package/ts_authswitch/readme.md +1 -1
  229. package/ts_interfaces/devices.schema.json +3573 -603
  230. package/ts_interfaces/devices.ts +1093 -4
  231. package/ts_interfaces/fleetworkers.ts +5 -3
  232. package/ts_interfaces/gateway.ts +242 -0
  233. package/ts_interfaces/inbox.ts +287 -0
  234. package/ts_interfaces/index.ts +3 -0
  235. package/ts_interfaces/interfaces.ts +9 -2
  236. package/ts_interfaces/management.ts +6 -4
  237. package/ts_interfaces/mcprequests.ts +61 -4
  238. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  239. package/ts_interfaces/nativesessions.ts +17 -3
  240. package/ts_interfaces/plugins.ts +3 -1
  241. package/ts_interfaces/proxycapacity.ts +162 -0
  242. package/ts_interfaces/requests.accounts.ts +20 -0
  243. package/ts_interfaces/requests.ts +4 -0
  244. package/ts_web/00_commitinfo_data.ts +1 -1
  245. package/ts_web/accounts.plugins.ts +4 -2
  246. package/ts_web/classes.accountsreadmodel.ts +33 -0
  247. package/ts_web/classes.browserpresentation.ts +19 -6
  248. package/ts_web/classes.inboxfeed.ts +329 -0
  249. package/ts_web/classes.nativesessionstate.ts +9 -23
  250. package/ts_web/elements.accounts.ts +121 -113
  251. package/ts_web/elements.configurationpane.ts +24 -37
  252. package/ts_web/elements.deployments.ts +66 -2
  253. package/ts_web/elements.devices.ts +4 -17
  254. package/ts_web/elements.flexlimitstrip.ts +21 -70
  255. package/ts_web/elements.harnesscontrollerapp.ts +198 -222
  256. package/ts_web/elements.inbox.ts +808 -0
  257. package/ts_web/functions.inbox.ts +95 -0
  258. package/ts_web/functions.sessioncards.ts +40 -0
  259. package/ts_web/plugins.ts +2 -0
@@ -11,6 +11,7 @@ import { authSwitchUsageProblemText, authSwitchUsageWindowName, authSwitchUsageW
11
11
  import { authSwitchUsageLimit, authSwitchUsageLimitText, type IAuthSwitchUsageLimit,
12
12
  type TAuthSwitchLimitState } from './authority-usagelimit.js';
13
13
  import { authSwitchPlacement, type IAuthSwitchPlacement, type TAuthSwitchAccountLifecycle } from './authority-placement.js';
14
+ import { authSwitchRenewal, type IAuthSwitchRenewal } from './authority-renewal.js';
14
15
  import { authSwitchSubscriptionFacts, type IAuthSwitchSubscriptionFact } from './authority-subscription.js';
15
16
  import type { IAuthSwitchPaymentProblem } from './classes.authorityusage.js';
16
17
  import { plainText } from './formatting.js';
@@ -54,6 +55,11 @@ export interface IAuthSwitchAccountOverview {
54
55
  /** When the account's subscription ends, or null while it renews (`IAuthSwitchAccount.lapsesAt`). */
55
56
  lapsesAt: string | null;
56
57
  lifecycle: TAuthSwitchAccountLifecycle;
58
+ /**
59
+ * The account's next monthly renewal as its owner set it (`IAuthSwitchAccount.renewsAt` rolled forward), or null
60
+ * without one. Placement ignores it while the account has a lapse date.
61
+ */
62
+ renewal: IAuthSwitchRenewal | null;
57
63
  /**
58
64
  * How the AGL proxy treats the account for a new session, by the rule of `authority-placement.ts`: its score in
59
65
  * percent per hour (null without a counted window) and whether it is a last resort or never placed on.
@@ -94,6 +100,8 @@ export interface IAuthSwitchLimitRow {
94
100
  /** When the account's subscription ends, or null while it renews. */
95
101
  lapsesAt: string | null;
96
102
  lifecycle: TAuthSwitchAccountLifecycle;
103
+ /** The account's next monthly renewal as its owner set it, or null without one (`IAuthSwitchAccountOverview.renewal`). */
104
+ renewal: IAuthSwitchRenewal | null;
97
105
  /** The account's placement score in percent per hour (`IAuthSwitchPlacement.score`), on each of its rows. */
98
106
  placementScore: number | null;
99
107
  placementEligibility: IAuthSwitchPlacement['eligibility'];
@@ -166,10 +174,13 @@ export const readAuthSwitchAccountOverview = async (snapshotArg: IAuthSwitchSnap
166
174
  plan: accountArg.plan, usedBy: accountUses(snapshotArg, accountArg.id), usageLoginId: login?.id ?? null,
167
175
  loginHealth: login?.health ?? null, loginProblem: login?.problem ?? null,
168
176
  maxUsagePercent: accountArg.maxUsagePercent, lapsesAt: accountArg.lapsesAt,
169
- lifecycle: authSwitchPlacement(null, accountArg.maxUsagePercent, accountArg.lapsesAt, nowArg, accountArg.reserveLiftUntil).lifecycle,
177
+ lifecycle: authSwitchPlacement(null, accountArg.maxUsagePercent, accountArg.lapsesAt, accountArg.renewsAt, nowArg,
178
+ accountArg.reserveLiftUntil).lifecycle,
179
+ renewal: authSwitchRenewal(accountArg.renewsAt, nowArg),
170
180
  };
171
181
  const placement = (readingArg: IAuthSwitchUsageSnapshot['reading']): IAuthSwitchPlacement =>
172
- authSwitchPlacement(readingArg, accountArg.maxUsagePercent, accountArg.lapsesAt, nowArg, accountArg.reserveLiftUntil);
182
+ authSwitchPlacement(readingArg, accountArg.maxUsagePercent, accountArg.lapsesAt, accountArg.renewsAt, nowArg,
183
+ accountArg.reserveLiftUntil);
173
184
  if (login === null) {
174
185
  return { ...base, usage: null, windows: [], problem: 'The account has no login to read its usage with.',
175
186
  subscription: [], paymentProblem: null, limit: null, placement: placement(null) };
@@ -220,7 +231,8 @@ export const authSwitchLimitList = (overviewArg: IAuthSwitchAccountOverviewList)
220
231
  const base = { accountId: accountArg.accountId, providerId: accountArg.providerId, account: identity(accountArg),
221
232
  plan: accountArg.plan, usageState: accountArg.usage?.state ?? null, problem: accountArg.problem,
222
233
  maxUsagePercent: accountArg.maxUsagePercent, accountState: accountArg.limit?.state ?? null,
223
- lapsesAt: accountArg.lapsesAt, lifecycle: accountArg.lifecycle, placementScore: accountArg.placement.score,
234
+ lapsesAt: accountArg.lapsesAt, lifecycle: accountArg.lifecycle, renewal: accountArg.renewal,
235
+ placementScore: accountArg.placement.score,
224
236
  placementEligibility: accountArg.placement.eligibility };
225
237
  if (accountArg.windows.length === 0) {
226
238
  return [{ ...base, limit: null, windowSeconds: null, usedPercent: null, estimatedUsedPercent: null, resetAt: null,
@@ -296,18 +308,28 @@ const limitLines = (maxUsagePercentArg: number | null, limitArg: IAuthSwitchUsag
296
308
 
297
309
  /**
298
310
  * The lifecycle and placement of an account as lines of its cell: nothing for an active account with its score, a
299
- * canceled one with its lapse, a lapsed one as never placed on.
311
+ * canceled one with its lapse, a lapsed one as never placed on; and the renewal its owner set, unless it lapsed.
300
312
  */
301
- const placementLines = (accountArg: Pick<IAuthSwitchLimitRow, 'lifecycle' | 'lapsesAt' | 'placementScore'
313
+ const placementLines = (accountArg: Pick<IAuthSwitchLimitRow, 'lifecycle' | 'lapsesAt' | 'renewal' | 'placementScore'
302
314
  | 'placementEligibility'>, nowArg: number): string[] => [
303
315
  ...accountArg.lifecycle === 'lapsed' ? ['lapsed · never placed on']
304
316
  : accountArg.lifecycle === 'canceled' && accountArg.lapsesAt !== null
305
317
  ? [`canceled · lapses in ${compactUntil(accountArg.lapsesAt, nowArg)}`] : [],
318
+ ...accountArg.lifecycle === 'lapsed' || accountArg.renewal === null ? []
319
+ : [renewalLine(accountArg.renewal, accountArg.lifecycle, nowArg)],
306
320
  ...accountArg.lifecycle === 'lapsed' ? []
307
321
  : [`placement ${placementScoreText(accountArg.placementScore)}${accountArg.placementEligibility === 'last_resort'
308
322
  ? ' · last resort' : ''}`],
309
323
  ];
310
324
 
325
+ /**
326
+ * The renewal line of an account cell: `renews in 9d 4h (set by the owner)`. A canceled account does not renew, so
327
+ * placement ignores it then, and the line says so.
328
+ */
329
+ const renewalLine = (renewalArg: IAuthSwitchRenewal, lifecycleArg: TAuthSwitchAccountLifecycle, nowArg: number): string =>
330
+ `renews in ${compactUntil(renewalArg.at, nowArg)} (set by the owner${lifecycleArg === 'canceled'
331
+ ? ', ignored while it lapses' : ''})`;
332
+
311
333
  /** A placement score as a cell shows it: percent per hour, or `unscored` without a counted window. */
312
334
  const placementScoreText = (scoreArg: number | null): string => scoreArg === null ? 'unscored'
313
335
  : `${scoreArg < 10 ? scoreArg.toFixed(2) : Math.round(scoreArg)}%/h`;
@@ -321,7 +343,7 @@ const accountCell = (accountArg: IAuthSwitchAccountOverview, nowArg: number): st
321
343
  plainText(accountArg.plan === null ? 'plan not reported' : `${accountArg.plan} plan`),
322
344
  ...accountArg.paymentProblem === null ? [] : [`payment problem since ${asOfTime(accountArg.paymentProblem.at, nowArg)}`],
323
345
  ...limitLines(accountArg.maxUsagePercent, accountArg.limit, nowArg),
324
- ...placementLines({ lifecycle: accountArg.lifecycle, lapsesAt: accountArg.lapsesAt,
346
+ ...placementLines({ lifecycle: accountArg.lifecycle, lapsesAt: accountArg.lapsesAt, renewal: accountArg.renewal,
325
347
  placementScore: accountArg.placement.score, placementEligibility: accountArg.placement.eligibility }, nowArg),
326
348
  ...accountArg.loginHealth === null ? ['no login']
327
349
  : accountArg.loginHealth === 'ready' ? []
@@ -1,17 +1,18 @@
1
1
  /**
2
2
  * Where a new session goes: an account's lifecycle against its lapse date, and how much of its usage it can spend per
3
- * hour before that usage resets or the account lapses. The inference proxy places new sessions by it, and the authswitch
4
- * command line and `agl proxy status` show it; an existing session keeps its account for the prompt cache and is never
5
- * placed again by it.
3
+ * hour before that usage resets, the account lapses or it renews. The inference proxy places new sessions by it, and the
4
+ * authswitch command line and `agl proxy status` show it; an existing session keeps its account for the prompt cache and
5
+ * is never placed again by it.
6
6
  *
7
- * Besides types, the module imports only the limit rule of `authority-usagelimit.ts`, the window reader it uses and the
8
- * spend month of `authority-spend.ts`, whose own imports carry nothing to a page, so it bundles for a browser with
9
- * nothing behind it.
7
+ * Besides types, the module imports only the limit rule of `authority-usagelimit.ts`, the window reader it uses, the
8
+ * spend month of `authority-spend.ts` and the renewal of `authority-renewal.ts`, whose own imports carry nothing to a
9
+ * page, so it bundles for a browser with nothing behind it.
10
10
  */
11
11
  import type { TAuthSwitchUsageReading } from './classes.authorityusage.js';
12
12
  import { authSwitchCountedWindows, authSwitchEffectiveMaxUsage } from './authority-usagelimit.js';
13
- import { authSwitchUsageWindowPercent, type IAuthSwitchUsageWindow } from './authority-usagewindows.js';
13
+ import { authSwitchUsageWindowPercent, authSwitchUsageWindowResetAt } from './authority-usagewindows.js';
14
14
  import { authSwitchSpendMonthEnded, authSwitchSpendPeriod } from './authority-spend.js';
15
+ import { authSwitchNextRenewal } from './authority-renewal.js';
15
16
 
16
17
  /**
17
18
  * `active`: the account has no lapse date. `canceled`: its subscription ends at `lapsesAt`, which is still ahead.
@@ -36,8 +37,8 @@ export interface IAuthSwitchPlacement {
36
37
  eligibility: TAuthSwitchPlacementEligibility;
37
38
  /**
38
39
  * The percent of its usage the account can spend per hour and still stay within every counted window before that
39
- * window resets or the account lapses, whichever comes first; the smallest over its counted windows. `null` when the
40
- * reading counts no window.
40
+ * window resets, the account lapses or it renews, whichever comes first; the smallest over its counted windows.
41
+ * `null` when the reading counts no window.
41
42
  */
42
43
  score: number | null;
43
44
  }
@@ -46,37 +47,31 @@ export interface IAuthSwitchPlacement {
46
47
  export const authSwitchAccountLifecycle = (lapsesAtArg: string | null, nowArg: number): TAuthSwitchAccountLifecycle =>
47
48
  lapsesAtArg === null ? 'active' : Date.parse(lapsesAtArg) <= nowArg ? 'lapsed' : 'canceled';
48
49
 
49
- /**
50
- * When a window's current period ends, after `nowArg`: its stated reset; a reset that passed and was not read again yet
51
- * moved forward by whole window lengths, as the provider starts each period; `nowArg` plus the window's length when
52
- * the reading names no reset.
53
- */
54
- const windowResetAt = (windowArg: IAuthSwitchUsageWindow, nowArg: number): number => {
55
- const lengthMs = windowArg.durationSeconds * 1000;
56
- const stated = windowArg.resetAt === null ? Number.NaN : Date.parse(windowArg.resetAt);
57
- if (!Number.isFinite(stated)) return nowArg + (lengthMs > 0 ? lengthMs : 0);
58
- if (stated > nowArg || !(lengthMs > 0)) return stated;
59
- return stated + (Math.floor((nowArg - stated) / lengthMs) + 1) * lengthMs;
60
- };
61
-
62
50
  /**
63
51
  * Where an account stands for a new session at `nowArg`, from its usage reading (`null` when none is held), its usage
64
- * threshold and its lapse date.
52
+ * threshold, its lapse date and its renewal anchor (`IAuthSwitchAccount.renewsAt`, `null` when its owner set none).
65
53
  *
66
54
  * The score is taken over the windows the account's limit counts (`authSwitchCountedWindows`). Per window it is the
67
55
  * headroom left below the threshold -- the percent the limit decides by, the estimate between reads where present --
68
- * divided by the hours until the window's deadline: its reset, or the account's lapse when that comes first, and at
69
- * least an hour. Usage that resets soon, or is lost when the account lapses, is worth more now than usage that stays for
70
- * days; placing by it uses that first and spares the accounts that reset later.
56
+ * divided by the hours until the window's deadline: the earliest of its reset, the account's lapse and its next renewal
57
+ * (`authSwitchNextRenewal` from `nowArg`), and at least an hour. Usage that resets soon, or is lost when the account
58
+ * lapses, is worth more now than usage that stays for days; placing by it uses that first and spares the accounts that
59
+ * reset later. Usage a window still holds at the renewal counts the same way, as spent by the renewal. Whether a
60
+ * provider's windows reset at a renewal is not known: the renewal is a scoring deadline only, and eligibility, lifecycle
61
+ * and capacity never read it. An account with a lapse date ignores its renewal, since a canceled subscription does not
62
+ * renew.
71
63
  *
72
64
  * An API key's spend reading whose month ended (`authSwitchSpendMonthEnded`, as `authSwitchUsageLimit` judges it) says
73
65
  * nothing about the current month, which starts with nothing spent: its window counts as 0% used, with the end of the
74
66
  * current month (`authSwitchSpendPeriod`) as its reset.
75
67
  */
76
68
  export const authSwitchPlacement = (readingArg: TAuthSwitchUsageReading | null, maxUsagePercentArg: number | null,
77
- lapsesAtArg: string | null, nowArg: number, reserveLiftUntilArg: string | null = null): IAuthSwitchPlacement => {
69
+ lapsesAtArg: string | null, renewalAnchorArg: string | null, nowArg: number,
70
+ reserveLiftUntilArg: string | null = null): IAuthSwitchPlacement => {
78
71
  const lifecycle = authSwitchAccountLifecycle(lapsesAtArg, nowArg);
79
72
  const lapsesAt = lapsesAtArg === null ? Infinity : Date.parse(lapsesAtArg);
73
+ const renewsAt = lapsesAtArg !== null || renewalAnchorArg === null ? Infinity
74
+ : authSwitchNextRenewal(renewalAnchorArg, nowArg);
80
75
  const eligibility: TAuthSwitchPlacementEligibility = lifecycle === 'lapsed' ? 'never'
81
76
  : lapsesAt - nowArg <= lapseHorizonMs ? 'last_resort' : 'normal';
82
77
  const threshold = authSwitchEffectiveMaxUsage(maxUsagePercentArg, reserveLiftUntilArg, nowArg) ?? 100;
@@ -84,8 +79,8 @@ export const authSwitchPlacement = (readingArg: TAuthSwitchUsageReading | null,
84
79
  const spendMonthEnded = readingArg?.kind === 'spend' && authSwitchSpendMonthEnded(readingArg.spend, nowArg);
85
80
  const scores = windows.map((windowArg) => {
86
81
  const headroom = spendMonthEnded ? threshold : Math.max(0, threshold - authSwitchUsageWindowPercent(windowArg));
87
- const resetAt = spendMonthEnded ? Date.parse(authSwitchSpendPeriod(nowArg).end) : windowResetAt(windowArg, nowArg);
88
- const deadline = Math.min(resetAt, lapsesAt);
82
+ const resetAt = spendMonthEnded ? Date.parse(authSwitchSpendPeriod(nowArg).end) : authSwitchUsageWindowResetAt(windowArg, nowArg);
83
+ const deadline = Math.min(resetAt, lapsesAt, renewsAt);
89
84
  return headroom / (Math.max(deadline - nowArg, minimumDeadlineMs) / 3_600_000);
90
85
  });
91
86
  return { lifecycle, eligibility, score: scores.length ? Math.min(...scores) : null };
@@ -102,9 +97,9 @@ export interface IAuthSwitchPlacementRank {
102
97
  /**
103
98
  * The order a new session is placed in: an account that lapses within `lapseHorizonMs` only after every other one;
104
99
  * then by the account's score shared among the requests it serves now -- `score / (1 + in flight)`, so new sessions
105
- * spread over the accounts in proportion to what each can spend per hour, and usage that resets or lapses soon is
106
- * spent first -- then by headroom and id. An account without a counted window comes after every scored one, the least
107
- * busy of them first.
100
+ * spread over the accounts in proportion to what each can spend per hour, and usage that resets, lapses or meets a
101
+ * renewal soon is spent first -- then by headroom and id. An account without a counted window comes after every scored
102
+ * one, the least busy of them first.
108
103
  */
109
104
  export const authSwitchPlacementOrder = (inFlightArg: (accountIdArg: string) => number) => (
110
105
  left: IAuthSwitchPlacementRank,
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A Claude sign-in's monthly renewal (AGL-1644), as its owner set it: the anchor is one date and time the subscription
3
+ * renewed or renews (`IAuthSwitchAccount.renewsAt`), and every renewal is a calendar month from it. AGL derives no
4
+ * renewal from anything a provider states; the owner sets the anchor, and nothing else does.
5
+ *
6
+ * Whether a provider's usage windows reset at the renewal is not known. Placement uses the renewal only as a deadline
7
+ * (`authority-placement.ts`): usage still held at the renewal counts as spent by then.
8
+ *
9
+ * The module imports nothing, so it bundles for a browser as it is.
10
+ */
11
+
12
+ /**
13
+ * The renewal anchor rule, the one the authority applies to `authswitch.authority.renewal`: a date-time `Date.parse`
14
+ * reads, in any year from 2000 to 9999, as the lapse date rule (`isAuthSwitchLapsesAt`). A past anchor is valid: the
15
+ * next renewal is a whole number of months after it. A consumer validates with this rather than restating it; the
16
+ * authority stores the anchor as its ISO 8601 UTC form and answers any other value with the `invalid_input` refusal.
17
+ */
18
+ export const isAuthSwitchRenewsAt = (value: unknown): value is string => {
19
+ if (typeof value !== 'string' || value.length > 64) return false;
20
+ const at = Date.parse(value);
21
+ return Number.isFinite(at) && at >= Date.UTC(2000, 0, 1) && at < Date.UTC(10000, 0, 1);
22
+ };
23
+
24
+ /** The renewal `monthsArg` months after the anchor: the anchor's UTC day clamped to that month, at the anchor's UTC time. */
25
+ const renewalAfter = (anchor: Date, monthsArg: number): number => {
26
+ const year = anchor.getUTCFullYear();
27
+ const month = anchor.getUTCMonth() + monthsArg;
28
+ // Day 0 of the following month is the last day of this one; `Date.UTC` carries a month past December into the year.
29
+ const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
30
+ const timeOfDay = anchor.getTime() - Date.UTC(year, anchor.getUTCMonth(), anchor.getUTCDate());
31
+ return Date.UTC(year, month, Math.min(anchor.getUTCDate(), lastDay)) + timeOfDay;
32
+ };
33
+
34
+ /**
35
+ * The first monthly renewal strictly after `nowArg` (epoch milliseconds), as epoch milliseconds, from the anchor
36
+ * `anchorArg` (`isAuthSwitchRenewsAt`). An anchor still ahead is itself the next renewal. Every renewal is computed from
37
+ * the anchor, never from the renewal before it: the anchor's UTC day, clamped to the month's last day, at the anchor's
38
+ * UTC time, so an anchor on January 31st renews on February 28th (29th in a leap year) and again on March 31st.
39
+ * Throws for an anchor the rule refuses or a `nowArg` that is not a finite number.
40
+ */
41
+ export const authSwitchNextRenewal = (anchorArg: string, nowArg: number): number => {
42
+ if (!isAuthSwitchRenewsAt(anchorArg) || !Number.isFinite(nowArg)) throw new Error('Invalid renewal anchor or time.');
43
+ const anchor = new Date(Date.parse(anchorArg));
44
+ if (anchor.getTime() > nowArg) return anchor.getTime();
45
+ const now = new Date(nowArg);
46
+ // The whole months between the two, less one, lie at or before now; count up from there.
47
+ let months = Math.max(0, (now.getUTCFullYear() - anchor.getUTCFullYear()) * 12
48
+ + now.getUTCMonth() - anchor.getUTCMonth() - 1);
49
+ while (renewalAfter(anchor, months) <= nowArg) months += 1;
50
+ return renewalAfter(anchor, months);
51
+ };
52
+
53
+ /** An account's next renewal as the account lists and `agl proxy status` show it; `source` says who set it. */
54
+ export interface IAuthSwitchRenewal {
55
+ /** The next renewal, ISO 8601 UTC (`authSwitchNextRenewal`). */
56
+ at: string;
57
+ /** `manual`: the owner set the anchor. AGL derives no renewal, so there is no other source. */
58
+ source: 'manual';
59
+ }
60
+
61
+ /** The next renewal of an account with the anchor `renewsAtArg` at `nowArg`, or `null` without an anchor. */
62
+ export const authSwitchRenewal = (renewsAtArg: string | null, nowArg: number): IAuthSwitchRenewal | null =>
63
+ renewsAtArg === null ? null
64
+ : { at: new Date(authSwitchNextRenewal(renewsAtArg, nowArg)).toISOString(), source: 'manual' };
@@ -6,7 +6,7 @@
6
6
  * `authority-spend.ts`, whose own imports carry nothing to a page, so it bundles for a browser with nothing behind it.
7
7
  */
8
8
  import type { TAuthSwitchProviderUsageReading, TAuthSwitchUsageReading } from './classes.authorityusage.js';
9
- import { authSwitchUsageWindowName, authSwitchUsageWindowPercent, authSwitchUsageWindows,
9
+ import { authSwitchUsageWindowName, authSwitchUsageWindowPercent, authSwitchUsageWindowResetAt, authSwitchUsageWindows,
10
10
  type IAuthSwitchUsageWindow } from './authority-usagewindows.js';
11
11
  import { authSwitchSpendExhausted, authSwitchSpendMonthEnded } from './authority-spend.js';
12
12
 
@@ -167,6 +167,89 @@ export const authSwitchUsageLimit = (readingArg: TAuthSwitchUsageReading, maxUsa
167
167
  }
168
168
  };
169
169
 
170
+ /** One moment an account's headroom is projected to change (epoch milliseconds), and its headroom from then on. */
171
+ export interface IAuthSwitchHeadroomStep {
172
+ at: number;
173
+ headroom: number;
174
+ }
175
+
176
+ /** How an account's headroom stands and is projected to change, from its reading alone (see `authSwitchHeadroomGrowth`). */
177
+ export interface IAuthSwitchHeadroomGrowth {
178
+ /** The headroom now, as `authSwitchUsageLimit` states it; `null` when the reading counts no window. */
179
+ headroom: number | null;
180
+ /**
181
+ * The counted window the headroom is bound by: of the windows at the headroom, the one whose period ends last (one
182
+ * whose end the reading does not state last of all), since the headroom grows only once each of them started a new
183
+ * period; `null` without a counted window.
184
+ */
185
+ binding: IAuthSwitchUsageWindow | null;
186
+ /** The moments the headroom changes, in order, each with the headroom from then on; empty when none is foreseen. */
187
+ steps: IAuthSwitchHeadroomStep[];
188
+ }
189
+
190
+ /**
191
+ * When an account's headroom (`authSwitchUsageLimit`) changes, as far as its reading foresees it at `nowArg`: each
192
+ * counted window starts a new period at its reset (`authSwitchUsageWindowResetAt`, a stated reset that passed moved on by
193
+ * whole lengths), from then on with nothing used, and an active reserve lift ends at its expiry, which brings the
194
+ * threshold back to `maxUsagePercentArg`. The headroom is the least of the windows' at every moment, so it grows only
195
+ * once every window at the least has reset: a binding 5-hour window lifts it at its own reset, long before a weekly
196
+ * window that is not binding. A window whose reading names no reset holds its headroom for as long as the projection
197
+ * runs. Usage spent meanwhile is not foreseen, so each step is the most the headroom can be then. An API key's month
198
+ * leaves all of its limit at the month's end. Pure, and bundles for a browser as the rest of the module does.
199
+ */
200
+ export const authSwitchHeadroomGrowth = (readingArg: TAuthSwitchUsageReading, maxUsagePercentArg: number | null,
201
+ nowArg: number, reserveLiftUntilArg: string | null = null): IAuthSwitchHeadroomGrowth => {
202
+ const limit = authSwitchUsageLimit(readingArg, maxUsagePercentArg, nowArg, reserveLiftUntilArg);
203
+ switch (readingArg.kind) {
204
+ case 'openai':
205
+ case 'anthropic': {
206
+ const windows = authSwitchCountedWindows(readingArg, maxUsagePercentArg);
207
+ if (limit.headroom === null || !windows.length) return { headroom: limit.headroom, binding: null, steps: [] };
208
+ // The end of each window's current period, `Infinity` where the reading does not state it.
209
+ const ends = windows.map((windowArg) => {
210
+ if (windowArg.resetAt === null) return Infinity;
211
+ const end = authSwitchUsageWindowResetAt(windowArg, nowArg);
212
+ return end > nowArg ? end : Infinity;
213
+ });
214
+ const thresholdAt = (atArg: number): number =>
215
+ authSwitchEffectiveMaxUsage(maxUsagePercentArg, reserveLiftUntilArg, atArg) ?? 100;
216
+ const headroomAt = (atArg: number): number => {
217
+ const threshold = thresholdAt(atArg);
218
+ return Math.min(...windows.map((windowArg, indexArg) => ends[indexArg] <= atArg ? threshold
219
+ : Math.max(0, threshold - authSwitchUsageWindowPercent(windowArg))));
220
+ };
221
+ const liftEnd = maxUsagePercentArg !== null && authSwitchReserveLiftActive(reserveLiftUntilArg, nowArg)
222
+ ? [Date.parse(reserveLiftUntilArg!)] : [];
223
+ const moments = [...new Set([...ends.filter((endArg) => Number.isFinite(endArg)), ...liftEnd])].sort((left, right) => left - right);
224
+ const steps: IAuthSwitchHeadroomStep[] = [];
225
+ let previous = limit.headroom;
226
+ for (const at of moments) {
227
+ const headroom = headroomAt(at);
228
+ if (headroom !== previous) steps.push({ at, headroom });
229
+ previous = headroom;
230
+ }
231
+ const threshold = thresholdAt(nowArg);
232
+ const binding = windows
233
+ .map((windowArg, indexArg) => ({ window: windowArg, end: ends[indexArg],
234
+ headroom: Math.max(0, threshold - authSwitchUsageWindowPercent(windowArg)) }))
235
+ .filter((entryArg) => entryArg.headroom === limit.headroom)
236
+ .sort((left, right) => right.end - left.end)[0]?.window ?? null;
237
+ return { headroom: limit.headroom, binding, steps };
238
+ }
239
+ case 'spend': {
240
+ const window = authSwitchUsageWindows(readingArg)[0];
241
+ if (limit.headroom === null || !window) return { headroom: limit.headroom, binding: null, steps: [] };
242
+ const end = Date.parse(readingArg.spend.resetAt);
243
+ return { headroom: limit.headroom, binding: window,
244
+ steps: limit.headroom < 100 && end > nowArg ? [{ at: end, headroom: 100 }] : [] };
245
+ }
246
+ default: {
247
+ const unhandledReading: never = readingArg;
248
+ return unhandledReading;
249
+ }
250
+ }
251
+ };
252
+
170
253
  const windowNames = (windowsArg: readonly IAuthSwitchUsageWindow[]): string => {
171
254
  const names = [...new Set(windowsArg.map(authSwitchUsageWindowName))];
172
255
  return names.length < 2 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
@@ -106,6 +106,19 @@ export const authSwitchUsageWindows = (readingArg: TAuthSwitchUsageReading | nul
106
106
  export const authSwitchUsageWindowPercent = (windowArg: IAuthSwitchUsageWindow): number =>
107
107
  windowArg.estimatedUsedPercent ?? windowArg.usedPercent;
108
108
 
109
+ /**
110
+ * When a window's current period ends, after `nowArg` (epoch milliseconds): its stated reset; a reset that passed and was
111
+ * not read again yet moved forward by whole window lengths, as the provider starts each period; `nowArg` plus the
112
+ * window's length when the reading names no reset.
113
+ */
114
+ export const authSwitchUsageWindowResetAt = (windowArg: IAuthSwitchUsageWindow, nowArg: number): number => {
115
+ const lengthMs = windowArg.durationSeconds * 1000;
116
+ const stated = windowArg.resetAt === null ? Number.NaN : Date.parse(windowArg.resetAt);
117
+ if (!Number.isFinite(stated)) return nowArg + (lengthMs > 0 ? lengthMs : 0);
118
+ if (stated > nowArg || !(lengthMs > 0)) return stated;
119
+ return stated + (Math.floor((nowArg - stated) / lengthMs) + 1) * lengthMs;
120
+ };
121
+
109
122
  /** A window's name: Claude's own, or a ChatGPT window's length after the name of the extra limit it belongs to. */
110
123
  export const authSwitchUsageWindowName = (windowArg: IAuthSwitchUsageWindow): string => windowArg.label
111
124
  ?? `${windowArg.limitName === null ? '' : `${windowArg.limitName} `}${usageWindowPeriod(windowArg.durationSeconds)}`;
@@ -10,6 +10,7 @@ import { AuthSwitchRefusal, authSwitchKeyHint, isAuthSwitchReserveLiftHours, isA
10
10
  import { authSwitchApiKeyOtherProvider, authSwitchApiKeyProviderNames, authSwitchApiKeyVerifier,
11
11
  type TAuthSwitchApiKeyVerdict, type TAuthSwitchApiKeyVerifier } from './authority-apikeys.js';
12
12
  import { isAuthSwitchSpendLimitMicroUsd } from './authority-spend.js';
13
+ import { isAuthSwitchRenewsAt } from './authority-renewal.js';
13
14
  import { AuthSwitchAuthorityDatabase, authorityBindPurpose, authSwitchBindPurposes, type TAuthSwitchBindPurpose,
14
15
  type TStoredNativeHome } from './classes.authoritydatabase.js';
15
16
  import { authorityApiKeyProvider, type IStoredAuthorityAccount, type IStoredAuthorityBinding,
@@ -156,7 +157,8 @@ const notOnApiKey = 'An API key account has no usage windows to keep a reserve o
156
157
  const publicAccount = (account: IStoredAuthorityAccount): IAuthSwitchAccount => ({
157
158
  id: account.id, providerId: account.providerId, label: account.label, email: account.email,
158
159
  plan: account.plan, organizationId: account.workspaceId, maxUsagePercent: account.maxUsagePercent, reserveLiftUntil: account.reserveLiftUntil,
159
- lapsesAt: account.lapsesAt, spendLimitMicroUsd: account.spendLimitMicroUsd, keyHint: account.keyHint, claudeCode: account.claudeCode,
160
+ lapsesAt: account.lapsesAt, renewsAt: account.renewsAt ?? null, spendLimitMicroUsd: account.spendLimitMicroUsd,
161
+ keyHint: account.keyHint, claudeCode: account.claudeCode,
160
162
  removed: account.removed, revision: account.revision, statusObservedAt: account.statusObservedAt,
161
163
  });
162
164
 
@@ -941,6 +943,37 @@ export class AuthSwitchAuthorityBroker {
941
943
  return publicAccount(updated.account);
942
944
  }
943
945
 
946
+ /**
947
+ * Sets or clears the anchor of a Claude sign-in's monthly renewal, as `setAccountLapse` sets its lapse date. The
948
+ * anchor is stored in its ISO 8601 UTC form; a past one is kept as given, since every renewal is a whole number of
949
+ * months after it. Only an account on a Claude sign-in has one; any other account is refused as `invalid_input`.
950
+ * The stored record carries `renewsAt` only while it is set: clearing removes the member, so an account that never
951
+ * had one is the record an earlier accounts service reads.
952
+ */
953
+ public async setAccountRenewal(accountId: string, expectedRevision: number,
954
+ renewsAt: string | null): Promise<IAuthSwitchAccount> {
955
+ if (!isId(accountId) || !validRevision(expectedRevision)) throw new Error('Invalid account change.');
956
+ if (renewsAt !== null && !isAuthSwitchRenewsAt(renewsAt)) {
957
+ // Spelled out like the lapse rule: an owner-facing instruction carries no bare number.
958
+ throw new AuthSwitchRefusal('invalid_input', 'An account\'s renewal is a date and time written year first, '
959
+ + 'as an ISO date is. Choose another value, or clear it.');
960
+ }
961
+ const stored = renewsAt === null ? null : new Date(Date.parse(renewsAt)).toISOString();
962
+ const updateId = plugins.crypto.randomUUID();
963
+ const updated = await this.database.changeAccount(updateId, accountId, account => {
964
+ if (!account || account.removed || account.revision !== expectedRevision) throw new AuthSwitchRefusal('account_changed', 'Account changed; refresh before editing.');
965
+ if (account.providerId !== 'anthropic' || isApiKeyAccount(account)) {
966
+ throw new AuthSwitchRefusal('invalid_input', 'Only an account on a Claude sign-in has a monthly renewal to '
967
+ + 'set.');
968
+ }
969
+ const { renewsAt: _previous, ...rest } = account;
970
+ return { ...rest, ...(stored === null ? {} : { renewsAt: stored }), revision: account.revision + 1, updateId,
971
+ statusObservedAt: new Date(this.now()).toISOString() };
972
+ });
973
+ this.publish();
974
+ return publicAccount(updated.account);
975
+ }
976
+
944
977
  /** Refuses a removal that would not go ahead, changing nothing; `removeAccount` refuses the same. */
945
978
  public async assertAccountRemovable(accountId: string, expectedRevision: number): Promise<void> {
946
979
  if (!isId(accountId) || !validRevision(expectedRevision)) throw new Error('Invalid account change.');
@@ -19,6 +19,7 @@ import { authSwitchApiKeyPaymentProblemText, authSwitchPaymentProblemText,
19
19
  authSwitchRecheckOutcomeText } from './authority-subscription.js';
20
20
  import { localDateTime } from './timetext.js';
21
21
  import { authSwitchAccountLifecycle, lapseHorizonMs } from './authority-placement.js';
22
+ import { authSwitchRenewal, isAuthSwitchRenewsAt } from './authority-renewal.js';
22
23
  import { authSwitchPackageIdentity, authSwitchRelease } from './packageidentity.js';
23
24
  import { describeOomScoreAdjust } from './serviceoom.js';
24
25
  import * as plugins from './plugins.js';
@@ -59,6 +60,7 @@ export interface IAuthSwitchAuthorityCliClient {
59
60
  setAccountMaxUsage(accountId: string, expectedRevision: number,
60
61
  maxUsagePercent: number | null): Promise<IAuthSwitchAccount>;
61
62
  setAccountLapse(accountId: string, expectedRevision: number, lapsesAt: string | null): Promise<IAuthSwitchAccount>;
63
+ setAccountRenewal(accountId: string, expectedRevision: number, renewsAt: string | null): Promise<IAuthSwitchAccount>;
62
64
  setAccountSpendLimit(accountId: string, expectedRevision: number,
63
65
  spendLimitMicroUsd: number | null): Promise<IAuthSwitchAccount>;
64
66
  setAccountClaudeCode(accountId: string, expectedRevision: number, claudeCode: boolean): Promise<IAuthSwitchAccount>;
@@ -102,6 +104,7 @@ type TAuthorityCliCommand =
102
104
  | { kind: 'remove'; accountId: string; revoke: boolean; json: boolean }
103
105
  | { kind: 'setMaxUsage'; accountId: string; maxUsagePercent: number | null; json: boolean }
104
106
  | { kind: 'setLapse'; accountId: string; lapsesAt: string | null; json: boolean }
107
+ | { kind: 'setRenewal'; accountId: string; renewsAt: string | null; json: boolean }
105
108
  | { kind: 'setSpendLimit'; accountId: string; spendLimitMicroUsd: number | null; json: boolean }
106
109
  | { kind: 'setClaudeCode'; accountId: string; claudeCode: boolean; json: boolean }
107
110
  | { kind: 'get'; operationId: string; json: boolean }
@@ -120,7 +123,7 @@ class AuthorityCliFailure extends Error {
120
123
  }
121
124
  }
122
125
 
123
- const usage = 'Usage: authswitch --help | authswitch --version [--json] | authswitch list [--json] | authswitch limits [--json] | authswitch account list [--json] | authswitch account add openai|claude [--json] | authswitch account add anthropic-api-key|openai-api-key [--label <label>] [--spend-limit <dollars>] [--json] | authswitch account use codex <account-id> [--json] | authswitch account release codex <account-id> [--end-running-turns] [--json] | authswitch account release claude <account-id> [--end-native-sessions] [--json] | authswitch account repair claude [--json] | authswitch account reauth <account-id> <login-id> [--json] | authswitch account recheck <account-id> [--json] | authswitch account remove <account-id> [--revoke] [--json] | authswitch account set <account-id> --max-usage <percent>|--clear|--lapses-at <date-time>|--clear-lapse|--spend-limit <dollars>|--clear-spend-limit [--json] | authswitch account operation get|cancel|resume <operation-id> [--json] | authswitch account preuse <account-id> <login-id>|--all [--prompt <text>] [--model <id>] [--json] | authswitch account preuse operation get|cancel|resume <operation-id> [--json] | authswitch authority doctor [--json] | authswitch authority import inventory [--json] | authswitch authority import status [--json] | authswitch authority import submit <source-id> --digest <source-digest> [--json] | authswitch authority service install|status|enable|start|stop | authswitch authority daemon';
126
+ const usage = 'Usage: authswitch --help | authswitch --version [--json] | authswitch list [--json] | authswitch limits [--json] | authswitch account list [--json] | authswitch account add openai|claude [--json] | authswitch account add anthropic-api-key|openai-api-key [--label <label>] [--spend-limit <dollars>] [--json] | authswitch account use codex <account-id> [--json] | authswitch account release codex <account-id> [--end-running-turns] [--json] | authswitch account release claude <account-id> [--end-native-sessions] [--json] | authswitch account repair claude [--json] | authswitch account reauth <account-id> <login-id> [--json] | authswitch account recheck <account-id> [--json] | authswitch account remove <account-id> [--revoke] [--json] | authswitch account set <account-id> --max-usage <percent>|--clear|--lapses-at <date-time>|--clear-lapse|--renews-at <date-time>|--clear-renewal|--spend-limit <dollars>|--clear-spend-limit [--json] | authswitch account operation get|cancel|resume <operation-id> [--json] | authswitch account preuse <account-id> <login-id>|--all [--prompt <text>] [--model <id>] [--json] | authswitch account preuse operation get|cancel|resume <operation-id> [--json] | authswitch authority doctor [--json] | authswitch authority import inventory [--json] | authswitch authority import status [--json] | authswitch authority import submit <source-id> --digest <source-digest> [--json] | authswitch authority service install|status|enable|start|stop | authswitch authority daemon';
124
127
 
125
128
  /** Every command, one per line, with what it does; `authswitch --help` prints it. */
126
129
  const help = (): string => `authswitch ${authSwitchRelease.version}
@@ -173,6 +176,11 @@ Usage
173
176
  new sessions on it only as a last resort in its last day,
174
177
  and from then on routes nothing to it and moves its
175
178
  sessions; --clear-lapse makes it active again
179
+ authswitch account set <account-id> --renews-at <date-time>|--clear-renewal [--json]
180
+ a Claude sign-in renews monthly from that date and time
181
+ (a past one too): the AGL proxy spends first the usage a
182
+ window would still hold at the next renewal;
183
+ --clear-renewal removes it
176
184
  authswitch account set <account-id> --spend-limit <dollars>|--clear-spend-limit [--json]
177
185
  an API key's monthly spend limit (calendar month, UTC) on
178
186
  what AGL's proxy relayed on it: at the limit the proxy places
@@ -385,6 +393,12 @@ const parse = (argv: readonly string[]): TAuthorityCliCommand | null => {
385
393
  if (options.length === 2 && options[0] === '--lapses-at' && isAuthSwitchLapsesAt(options[1])) {
386
394
  return { kind: 'setLapse', accountId: argv[2], lapsesAt: options[1], json };
387
395
  }
396
+ if (options.length === 1 && options[0] === '--clear-renewal') {
397
+ return { kind: 'setRenewal', accountId: argv[2], renewsAt: null, json };
398
+ }
399
+ if (options.length === 2 && options[0] === '--renews-at' && isAuthSwitchRenewsAt(options[1])) {
400
+ return { kind: 'setRenewal', accountId: argv[2], renewsAt: options[1], json };
401
+ }
388
402
  if (options.length === 1 && options[0] === '--clear-spend-limit') {
389
403
  return { kind: 'setSpendLimit', accountId: argv[2], spendLimitMicroUsd: null, json };
390
404
  }
@@ -519,6 +533,10 @@ class ScopedAuthorityCliClient implements IAuthSwitchAuthorityCliClient {
519
533
  return this.client.setAccountLapse(accountId, expectedRevision, lapsesAt, this.controller.signal);
520
534
  }
521
535
 
536
+ public setAccountRenewal(accountId: string, expectedRevision: number, renewsAt: string | null): Promise<IAuthSwitchAccount> {
537
+ return this.client.setAccountRenewal(accountId, expectedRevision, renewsAt, this.controller.signal);
538
+ }
539
+
522
540
  public addApiKey(providerId: TAuthSwitchApiKeyProvider, apiKey: string,
523
541
  options: { label?: string; spendLimitMicroUsd?: number }): Promise<IReq_AuthSwitchAddApiKey['response']> {
524
542
  return this.client.addApiKey(providerId, apiKey, options, this.controller.signal);
@@ -623,6 +641,20 @@ const lapseText = (account: IAuthSwitchAccount, nowArg: number): string => {
623
641
  const renderLapse = (account: IAuthSwitchAccount, nowArg: number): string =>
624
642
  `Account ${safe(account.email ?? account.label)} (${safe(account.id)}): ${lapseText(account, nowArg)}.\n`;
625
643
 
644
+ /**
645
+ * An account's renewal in words, as `account set --renews-at` and `account list` state it: the next renewal, rolled
646
+ * forward from the anchor the owner set. Empty for an account without one.
647
+ */
648
+ const renewalText = (account: IAuthSwitchAccount, nowArg: number): string => {
649
+ const renewal = authSwitchRenewal(account.renewsAt, nowArg);
650
+ return renewal === null ? '' : `renews ${safe(renewal.at)} (set by the owner)`;
651
+ };
652
+
653
+ const renderRenewal = (account: IAuthSwitchAccount, nowArg: number): string =>
654
+ `Account ${safe(account.email ?? account.label)} (${safe(account.id)}): `
655
+ + (account.renewsAt === null ? 'no renewal set.\n'
656
+ : `${renewalText(account, nowArg)}; usage it would still hold then is used first.\n`);
657
+
626
658
  /** A re-check as `account recheck` states it: how the read went, and whether the account is still held. */
627
659
  const renderRecheck = (account: IAuthSwitchAccount, recheck: IAuthSwitchUsageRecheck): string =>
628
660
  `Account ${safe(account.email ?? account.label)} (${safe(account.id)}): ${authSwitchRecheckOutcomeText(recheck.outcome)}\n`
@@ -677,7 +709,8 @@ const renderList = (snapshot: IAuthSwitchSnapshot, nowArg: number): string => {
677
709
  lines.push(`${safe(identity)} [${safe(account.providerId)}]`,
678
710
  ` account ${safe(account.id)}; organization ${account.organizationId === undefined ? 'not published'
679
711
  : safe(account.organizationId)}; plan ${safe(account.plan)}; max usage ${account.maxUsagePercent === null ? 'not set'
680
- : `${account.maxUsagePercent}%`}; ${lapseText(account, nowArg)}; ${account.removed ? 'removed' : 'registered'}; `
712
+ : `${account.maxUsagePercent}%`}; ${lapseText(account, nowArg)}; `
713
+ + `${account.renewsAt === null ? '' : `${renewalText(account, nowArg)}; `}${account.removed ? 'removed' : 'registered'}; `
681
714
  + `stored ${safe(account.statusObservedAt)}`);
682
715
  const logins = snapshot.logins.filter(login => login.accountId === account.id);
683
716
  if (logins.length === 0) lines.push(' logins: none');
@@ -1497,6 +1530,20 @@ export const runAuthSwitchAuthorityCli = async (argv: readonly string[],
1497
1530
  await writeOutput(command.json ? JSON.stringify({ account: changed }) + '\n' : renderLapse(changed, now()));
1498
1531
  return 0;
1499
1532
  }
1533
+ if (command.kind === 'setRenewal') {
1534
+ const account = (await activeClient.snapshotAll()).accounts.find(item => item.id === command.accountId && !item.removed);
1535
+ if (!account) {
1536
+ await writeDiagnostic('No authority account has this id. Run `authswitch account list` for the ids.\n');
1537
+ return 1;
1538
+ }
1539
+ const changed = await activeClient.setAccountRenewal(account.id, account.revision, command.renewsAt);
1540
+ if (changed.id !== account.id || (command.renewsAt === null ? changed.renewsAt !== null
1541
+ : changed.renewsAt === null || Date.parse(changed.renewsAt) !== Date.parse(command.renewsAt))) {
1542
+ throw new AuthorityCliFailure('response');
1543
+ }
1544
+ await writeOutput(command.json ? JSON.stringify({ account: changed }) + '\n' : renderRenewal(changed, now()));
1545
+ return 0;
1546
+ }
1500
1547
  if (command.kind === 'setSpendLimit') {
1501
1548
  const account = (await activeClient.snapshotAll()).accounts.find(item => item.id === command.accountId && !item.removed);
1502
1549
  if (!account) {
@@ -7,7 +7,7 @@ import type {
7
7
  IReq_AuthSwitchClaudeHostLogin, IReq_AuthSwitchEvents, IReq_AuthSwitchReleaseClaudeNative,
8
8
  IReq_AuthSwitchClaudeNativeReleaseOperation, IReq_AuthSwitchRepairClaudeHost,
9
9
  IReq_AuthSwitchGetBinding, IReq_AuthSwitchGetOperation, IReq_AuthSwitchListOperations,
10
- IReq_AuthSwitchRemoveAccount, IReq_AuthSwitchRenameAccount, IReq_AuthSwitchSetAccountLapse, IReq_AuthSwitchSetAccountMaxUsage, IReq_AuthSwitchLiftAccountReserve,
10
+ IReq_AuthSwitchRemoveAccount, IReq_AuthSwitchRenameAccount, IReq_AuthSwitchSetAccountLapse, IReq_AuthSwitchSetAccountRenewal, IReq_AuthSwitchSetAccountMaxUsage, IReq_AuthSwitchLiftAccountReserve,
11
11
  IReq_AuthSwitchCancelPreuse, IReq_AuthSwitchGetPreuse, IReq_AuthSwitchSnapshot,
12
12
  IReq_AuthSwitchStartPreuse, IReq_AuthSwitchUsage, IReq_AuthSwitchObserveUsage, IReq_AuthSwitchReportPaymentProblem,
13
13
  IReq_AuthSwitchRecordSpend, IAuthSwitchSpendAnswer, TAuthSwitchPaymentProblemCause, TAuthSwitchApiKeyProvider,
@@ -122,8 +122,8 @@ export class AuthSwitchDaemonOutdatedError extends Error {
122
122
  * A snapshot page carries every member of this release's contract. `schemaVersion` is not bumped for an
123
123
  * additive member; version 3 adds the gateway runtime, every account states its `maxUsagePercent` from 38.3.0
124
124
  * on, its `lapsesAt` from 38.4.0 on, its `reserveLiftUntil` with reserve lifts, its `spendLimitMicroUsd` and
125
- * `keyHint` with API keys of both providers, and its `claudeCode` from AGL-1146 on. Consumers still check their
126
- * supported version.
125
+ * `keyHint` with API keys of both providers, its `claudeCode` from AGL-1146 on, and its `renewsAt` from AGL-1644 on.
126
+ * Consumers still check their supported version.
127
127
  */
128
128
  const assertCurrentSnapshot = (snapshot: IAuthSwitchSnapshot): IAuthSwitchSnapshot => {
129
129
  const page: Partial<IAuthSwitchSnapshot> = snapshot;
@@ -134,7 +134,8 @@ const assertCurrentSnapshot = (snapshot: IAuthSwitchSnapshot): IAuthSwitchSnapsh
134
134
  || (account as Partial<IAuthSwitchAccount>).reserveLiftUntil === undefined
135
135
  || (account as Partial<IAuthSwitchAccount>).spendLimitMicroUsd === undefined
136
136
  || (account as Partial<IAuthSwitchAccount>).keyHint === undefined
137
- || (account as Partial<IAuthSwitchAccount>).claudeCode === undefined)) {
137
+ || (account as Partial<IAuthSwitchAccount>).claudeCode === undefined
138
+ || (account as Partial<IAuthSwitchAccount>).renewsAt === undefined)) {
138
139
  throw new AuthSwitchDaemonOutdatedError();
139
140
  }
140
141
  return snapshot;
@@ -553,6 +554,15 @@ export class AuthSwitchClient {
553
554
  return (await this.request<IReq_AuthSwitchSetAccountLapse>('authswitch.authority.lapse',
554
555
  { accountId, expectedRevision, lapsesAt }, 35_000, false, signal)).account;
555
556
  }
557
+ /**
558
+ * Sets the anchor of a Claude sign-in's monthly renewal, or clears it with `null` (see
559
+ * `IReq_AuthSwitchSetAccountRenewal`).
560
+ */
561
+ public async setAccountRenewal(accountId: string, expectedRevision: number, renewsAt: string | null,
562
+ signal?: AbortSignal): Promise<IReq_AuthSwitchSetAccountRenewal['response']['account']> {
563
+ return (await this.request<IReq_AuthSwitchSetAccountRenewal>('authswitch.authority.renewal',
564
+ { accountId, expectedRevision, renewsAt }, 35_000, false, signal)).account;
565
+ }
556
566
  /**
557
567
  * Removes an account; `revoke: true` also revokes its ChatGPT sign-in at OpenAI (see
558
568
  * `IReq_AuthSwitchRemoveAccount`). An older daemon refuses `revoke` as an invalid request before it changes