agl 43.0.5 → 43.2.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 (216) hide show
  1. package/changelog.md +30 -0
  2. package/dist_serve/bundle.js +5996 -5280
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +30 -30
  5. package/dist_serve/bundle.js.third-party-notices.txt +30 -30
  6. package/dist_serve/third-party-notices.md +1 -1
  7. package/dist_ts/00_commitinfo_data.js +1 -1
  8. package/dist_ts/aglapi/aglapisurface.document.js +805 -10
  9. package/dist_ts/aglapi/interfaces.d.ts +13 -0
  10. package/dist_ts/aglapi/interfaces.js +4 -1
  11. package/dist_ts/classes.authmodels.js +17 -4
  12. package/dist_ts/classes.authstore.js +16 -2
  13. package/dist_ts/classes.claudeharness.d.ts +14 -5
  14. package/dist_ts/classes.claudeharness.js +62 -2
  15. package/dist_ts/classes.cli.d.ts +4 -2
  16. package/dist_ts/classes.cli.js +6 -3
  17. package/dist_ts/classes.codexclientadapter.d.ts +7 -5
  18. package/dist_ts/classes.codexclientadapter.js +38 -3
  19. package/dist_ts/classes.controller.d.ts +19 -2
  20. package/dist_ts/classes.controller.js +234 -27
  21. package/dist_ts/classes.controllermanagement.d.ts +14 -4
  22. package/dist_ts/classes.controllermanagement.js +20 -2
  23. package/dist_ts/classes.gatewayclient.d.ts +115 -0
  24. package/dist_ts/classes.gatewayclient.js +336 -0
  25. package/dist_ts/classes.gatewayclientstore.d.ts +97 -0
  26. package/dist_ts/classes.gatewayclientstore.js +261 -0
  27. package/dist_ts/classes.inferencegateway.d.ts +8 -5
  28. package/dist_ts/classes.inferencegateway.js +62 -19
  29. package/dist_ts/classes.inferencerouter.d.ts +9 -0
  30. package/dist_ts/classes.inferencerouter.js +11 -1
  31. package/dist_ts/classes.inferenceservice.d.ts +9 -0
  32. package/dist_ts/classes.inferenceservice.js +27 -1
  33. package/dist_ts/classes.inferencespend.d.ts +9 -3
  34. package/dist_ts/classes.inferencespend.js +44 -16
  35. package/dist_ts/classes.mcpclient.d.ts +9 -4
  36. package/dist_ts/classes.mcpclient.js +24 -2
  37. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -1
  38. package/dist_ts/classes.mcpcontrollerhost.js +13 -1
  39. package/dist_ts/classes.mcptools.d.ts +3 -3
  40. package/dist_ts/classes.mcptools.js +42 -4
  41. package/dist_ts/classes.mcpvalidation.js +7 -1
  42. package/dist_ts/classes.opencodeclient.js +3 -1
  43. package/dist_ts/classes.proxycontrol.d.ts +33 -11
  44. package/dist_ts/classes.proxycontrol.js +12 -3
  45. package/dist_ts/classes.proxycontrolclient.d.ts +23 -5
  46. package/dist_ts/classes.proxycontrolclient.js +42 -6
  47. package/dist_ts/classes.proxydaemon.d.ts +8 -6
  48. package/dist_ts/classes.proxydaemon.js +42 -21
  49. package/dist_ts/classes.proxyleaseholder.d.ts +12 -4
  50. package/dist_ts/classes.proxyleaseholder.js +39 -9
  51. package/dist_ts/classes.proxymonitor.d.ts +7 -0
  52. package/dist_ts/classes.proxymonitor.js +13 -1
  53. package/dist_ts/classes.proxystore.d.ts +4 -3
  54. package/dist_ts/classes.proxystore.js +17 -7
  55. package/dist_ts/classes.sessionfeed.d.ts +1 -1
  56. package/dist_ts/classes.trustedproxysecrets.d.ts +2 -0
  57. package/dist_ts/classes.trustedproxysecrets.js +5 -1
  58. package/dist_ts/classes.validation.d.ts +7 -0
  59. package/dist_ts/classes.validation.js +49 -2
  60. package/dist_ts/driver/functions.drivertools.js +2 -2
  61. package/dist_ts/fleet/classes.codexworkers.d.ts +4 -11
  62. package/dist_ts/fleet/classes.codexworkers.js +6 -3
  63. package/dist_ts/fleet/classes.workers.d.ts +25 -13
  64. package/dist_ts/fleet/classes.workers.js +105 -9
  65. package/dist_ts/fleet/functions.workervalidation.d.ts +26 -1
  66. package/dist_ts/fleet/functions.workervalidation.js +40 -11
  67. package/dist_ts/fleet/interfaces.workers.d.ts +17 -11
  68. package/dist_ts/fleet/interfaces.workers.js +10 -1
  69. package/dist_ts/functions.confinedrelay.d.ts +21 -0
  70. package/dist_ts/functions.confinedrelay.js +65 -0
  71. package/dist_ts/functions.controllermanagementsurface.d.ts +4 -0
  72. package/dist_ts/functions.controllermanagementsurface.js +15 -1
  73. package/dist_ts/functions.deviceapi.d.ts +4 -2
  74. package/dist_ts/functions.deviceapi.js +20 -2
  75. package/dist_ts/functions.elicitation.d.ts +49 -0
  76. package/dist_ts/functions.elicitation.js +418 -0
  77. package/dist_ts/functions.gatewaycli.d.ts +24 -0
  78. package/dist_ts/functions.gatewaycli.js +395 -0
  79. package/dist_ts/functions.gatewayroute.d.ts +135 -0
  80. package/dist_ts/functions.gatewayroute.js +366 -0
  81. package/dist_ts/functions.inferencecli.d.ts +3 -3
  82. package/dist_ts/functions.inferencecli.js +62 -10
  83. package/dist_ts/functions.inferencecliarguments.d.ts +9 -2
  84. package/dist_ts/functions.inferencecliarguments.js +59 -10
  85. package/dist_ts/functions.inferencelaunch.d.ts +35 -7
  86. package/dist_ts/functions.inferencelaunch.js +143 -16
  87. package/dist_ts/functions.mcpfleetworkertools.d.ts +63 -70
  88. package/dist_ts/functions.mcpfleetworkertools.js +32 -4
  89. package/dist_ts/functions.proxycapacity.d.ts +50 -0
  90. package/dist_ts/functions.proxycapacity.js +142 -0
  91. package/dist_ts/functions.proxycapacitycli.d.ts +30 -0
  92. package/dist_ts/functions.proxycapacitycli.js +65 -0
  93. package/dist_ts/functions.proxycontract.d.ts +21 -4
  94. package/dist_ts/functions.proxycontract.js +12 -5
  95. package/dist_ts/functions.proxyharnessconfig.d.ts +7 -0
  96. package/dist_ts/functions.proxyharnessconfig.js +11 -1
  97. package/dist_ts/functions.remotecli.d.ts +30 -3
  98. package/dist_ts/functions.remotecli.js +44 -18
  99. package/dist_ts/interfaces.auth.d.ts +25 -4
  100. package/dist_ts/interfaces.auth.js +8 -1
  101. package/dist_ts/plugins.d.ts +2 -0
  102. package/dist_ts/plugins.js +4 -1
  103. package/dist_ts_authswitch/authority-placement.js +3 -17
  104. package/dist_ts_authswitch/authority-usagelimit.d.ts +29 -0
  105. package/dist_ts_authswitch/authority-usagelimit.js +66 -2
  106. package/dist_ts_authswitch/authority-usagewindows.d.ts +6 -0
  107. package/dist_ts_authswitch/authority-usagewindows.js +15 -1
  108. package/dist_ts_interfaces/devices.d.ts +133 -3
  109. package/dist_ts_interfaces/devices.js +3 -2
  110. package/dist_ts_interfaces/elicitations.d.ts +125 -0
  111. package/dist_ts_interfaces/elicitations.js +7 -0
  112. package/dist_ts_interfaces/fleetworkers.d.ts +119 -5
  113. package/dist_ts_interfaces/fleetworkers.js +14 -2
  114. package/dist_ts_interfaces/gateway.d.ts +151 -0
  115. package/dist_ts_interfaces/gateway.js +66 -0
  116. package/dist_ts_interfaces/index.d.ts +3 -0
  117. package/dist_ts_interfaces/index.js +4 -1
  118. package/dist_ts_interfaces/interfaces.d.ts +3 -1
  119. package/dist_ts_interfaces/interfaces.js +2 -2
  120. package/dist_ts_interfaces/management.d.ts +4 -4
  121. package/dist_ts_interfaces/management.js +3 -2
  122. package/dist_ts_interfaces/mcprequests.d.ts +18 -2
  123. package/dist_ts_interfaces/mcprequests.js +3 -1
  124. package/dist_ts_interfaces/nativesessions.d.ts +14 -0
  125. package/dist_ts_interfaces/proxycapacity.d.ts +99 -0
  126. package/dist_ts_interfaces/proxycapacity.js +74 -0
  127. package/dist_ts_interfaces/requests.d.ts +3 -3
  128. package/dist_ts_interfaces/requests.fleetworkers.js +2 -2
  129. package/dist_ts_interfaces/requests.js +1 -1
  130. package/dist_ts_interfaces/requests.promptreply.d.ts +18 -0
  131. package/dist_ts_interfaces/sessionfeed.d.ts +3 -2
  132. package/dist_ts_interfaces/sessionfeed.js +1 -1
  133. package/package.json +5 -4
  134. package/readme.md +267 -26
  135. package/third-party-notices.md +1 -1
  136. package/ts/00_commitinfo_data.ts +1 -1
  137. package/ts/aglapi/aglapisurface.document.ts +804 -9
  138. package/ts/aglapi/interfaces.ts +3 -0
  139. package/ts/classes.authmodels.ts +22 -3
  140. package/ts/classes.authstore.ts +15 -1
  141. package/ts/classes.claudeharness.ts +80 -9
  142. package/ts/classes.cli.ts +7 -3
  143. package/ts/classes.codexclientadapter.ts +41 -5
  144. package/ts/classes.controller.ts +276 -32
  145. package/ts/classes.controllermanagement.ts +40 -7
  146. package/ts/classes.gatewayclient.ts +401 -0
  147. package/ts/classes.gatewayclientstore.ts +272 -0
  148. package/ts/classes.inferencegateway.ts +69 -23
  149. package/ts/classes.inferencerouter.ts +12 -0
  150. package/ts/classes.inferenceservice.ts +27 -0
  151. package/ts/classes.inferencespend.ts +46 -13
  152. package/ts/classes.mcpclient.ts +26 -4
  153. package/ts/classes.mcpcontrollerhost.ts +17 -0
  154. package/ts/classes.mcptools.ts +47 -5
  155. package/ts/classes.mcpvalidation.ts +5 -0
  156. package/ts/classes.opencodeclient.ts +2 -0
  157. package/ts/classes.proxycontrol.ts +43 -13
  158. package/ts/classes.proxycontrolclient.ts +39 -6
  159. package/ts/classes.proxydaemon.ts +57 -27
  160. package/ts/classes.proxyleaseholder.ts +43 -11
  161. package/ts/classes.proxymonitor.ts +12 -0
  162. package/ts/classes.proxystore.ts +21 -8
  163. package/ts/classes.sessionfeed.ts +1 -1
  164. package/ts/classes.trustedproxysecrets.ts +5 -0
  165. package/ts/classes.validation.ts +52 -0
  166. package/ts/driver/functions.drivertools.ts +1 -1
  167. package/ts/fleet/classes.codexworkers.ts +8 -6
  168. package/ts/fleet/classes.workers.ts +101 -17
  169. package/ts/fleet/functions.workervalidation.ts +35 -9
  170. package/ts/fleet/interfaces.workers.ts +11 -4
  171. package/ts/functions.confinedrelay.ts +65 -0
  172. package/ts/functions.controllermanagementsurface.ts +15 -0
  173. package/ts/functions.deviceapi.ts +24 -1
  174. package/ts/functions.elicitation.ts +443 -0
  175. package/ts/functions.gatewaycli.ts +436 -0
  176. package/ts/functions.gatewayroute.ts +429 -0
  177. package/ts/functions.inferencecli.ts +62 -13
  178. package/ts/functions.inferencecliarguments.ts +56 -9
  179. package/ts/functions.inferencelaunch.ts +143 -16
  180. package/ts/functions.mcpfleetworkertools.ts +34 -4
  181. package/ts/functions.proxycapacity.ts +191 -0
  182. package/ts/functions.proxycapacitycli.ts +104 -0
  183. package/ts/functions.proxycontract.ts +17 -4
  184. package/ts/functions.proxyharnessconfig.ts +11 -0
  185. package/ts/functions.remotecli.ts +56 -20
  186. package/ts/interfaces.auth.ts +29 -4
  187. package/ts/plugins.ts +5 -0
  188. package/ts_authswitch/authority-placement.ts +2 -15
  189. package/ts_authswitch/authority-usagelimit.ts +84 -1
  190. package/ts_authswitch/authority-usagewindows.ts +13 -0
  191. package/ts_interfaces/devices.schema.json +476 -2
  192. package/ts_interfaces/devices.ts +146 -2
  193. package/ts_interfaces/elicitations.ts +148 -0
  194. package/ts_interfaces/fleetworkers.ts +96 -4
  195. package/ts_interfaces/gateway.ts +242 -0
  196. package/ts_interfaces/index.ts +3 -0
  197. package/ts_interfaces/interfaces.ts +3 -1
  198. package/ts_interfaces/management.ts +6 -4
  199. package/ts_interfaces/mcprequests.ts +19 -0
  200. package/ts_interfaces/nativesessions.ts +16 -0
  201. package/ts_interfaces/proxycapacity.ts +162 -0
  202. package/ts_interfaces/requests.fleetworkers.ts +1 -1
  203. package/ts_interfaces/requests.promptreply.ts +22 -0
  204. package/ts_interfaces/requests.ts +4 -0
  205. package/ts_interfaces/sessionfeed.ts +3 -2
  206. package/ts_web/00_commitinfo_data.ts +1 -1
  207. package/ts_web/classes.browserpresentation.ts +13 -5
  208. package/ts_web/classes.elicitationcards.ts +106 -0
  209. package/ts_web/classes.nativesessionstate.ts +38 -1
  210. package/ts_web/elements.accounts.ts +40 -113
  211. package/ts_web/elements.configurationpane.ts +24 -37
  212. package/ts_web/elements.devices.ts +4 -17
  213. package/ts_web/elements.fleetworker.ts +27 -2
  214. package/ts_web/elements.flexlimitstrip.ts +21 -70
  215. package/ts_web/elements.harnesscontrollerapp.ts +159 -186
  216. package/ts_web/functions.sessionchat.ts +5 -0
@@ -0,0 +1,104 @@
1
+ import type {
2
+ IProxyCapacityAnswer,
3
+ IProxyCapacityMember,
4
+ IProxyCapacityPool,
5
+ IProxyCapacityRequest,
6
+ TProxyCapacityProvider,
7
+ TProxyCapacityWaitReason,
8
+ } from '../ts_interfaces/proxycapacity.js';
9
+ import { proxyCapacityPlans } from './functions.proxycapacity.js';
10
+
11
+ /** `agl proxy capacity` exits 0 when every pool it reports is open, 2 when one waits or `--wait` ran out; a failure exits 1. */
12
+ export const proxyCapacityExitOpen = 0;
13
+ export const proxyCapacityExitWait = 2;
14
+
15
+ /** How long `--wait` pauses at most before it asks again. */
16
+ const longestPauseMs = 60_000;
17
+
18
+ const poolNames: Record<TProxyCapacityProvider, string> = { anthropic: 'Claude', openai: 'ChatGPT' };
19
+
20
+ const waitReasons: Record<TProxyCapacityWaitReason, string> = {
21
+ room: 'too little room',
22
+ 'provider-429': 'a provider 429 on a member within five minutes',
23
+ 'quiet-unobserved': 'the proxy has watched its pools for provider 429s for less than five minutes',
24
+ };
25
+
26
+ const percent = (valueArg: number): string => `${Math.round(valueArg * 10) / 10}%`;
27
+
28
+ /** The plans a pool counts, in words (`proxyCapacityPlans`). */
29
+ const countedPlans = (providerArg: TProxyCapacityProvider): string => {
30
+ const rule = proxyCapacityPlans[providerArg];
31
+ return `${rule.counts === 'only' ? 'plan' : 'every plan but'} ${rule.plans.join(', ')}`;
32
+ };
33
+
34
+ const memberText = (memberArg: IProxyCapacityMember): string => {
35
+ const binding = memberArg.binding;
36
+ return ` account ${memberArg.accountId.slice(0, 12)} (${memberArg.plan}): ${memberArg.state}, adds ${percent(memberArg.headroom)}`
37
+ + `${binding === null ? '' : `, bound by its ${binding.name} window (${percent(binding.usedPercent)} used`
38
+ + `${binding.estimated ? ', est.' : ''}${binding.resetAt === null ? '' : `, resets ${binding.resetAt}`})`}`
39
+ + `${memberArg.growsAt === null ? '; no growth foreseen' : `; grows at ${memberArg.growsAt} to ${percent(memberArg.growsTo!)}`}`
40
+ + `${memberArg.recheckAt === null ? '' : `; its usage is read again at ${memberArg.recheckAt}`}`;
41
+ };
42
+
43
+ const poolText = (poolArg: IProxyCapacityPool, observedSinceArg: string): string[] => {
44
+ const verdict = poolArg.verdict;
45
+ const verdictText = verdict.state === 'open' ? 'open'
46
+ : verdict.until === null ? `wait (${waitReasons[verdict.reason]}; no moment foreseen when it suffices)`
47
+ : `wait ${verdict.seconds} s, until ${verdict.until} (${waitReasons[verdict.reason]})`;
48
+ return [
49
+ `${poolNames[poolArg.provider]} pool (${poolArg.provider}): ${verdictText}; room ${percent(poolArg.room)}, `
50
+ + `minimum ${poolArg.minHeadroom}%; last provider 429 on a member: ${poolArg.last429At ?? `none since ${observedSinceArg}`}`,
51
+ ...poolArg.members.length ? poolArg.members.map(memberText)
52
+ : [` no account counts (${countedPlans(poolArg.provider)}, a subscription sign-in that has not lapsed)`],
53
+ ];
54
+ };
55
+
56
+ /** The answer as `agl proxy capacity` prints it: per pool its verdict, room and newest 429, then each counted account. */
57
+ export const formatProxyCapacity = (answerArg: IProxyCapacityAnswer): string =>
58
+ [`As of ${answerArg.at}:`, ...answerArg.pools.flatMap((poolArg) => poolText(poolArg, answerArg.observedSince))].join('\n') + '\n';
59
+
60
+ export interface IProxyCapacityCliOptions {
61
+ request: IProxyCapacityRequest;
62
+ json: boolean;
63
+ /** Ask again until every pool asked is open; `--wait` names one pool. */
64
+ wait: boolean;
65
+ /** How long `--wait` waits at most; unbounded when absent. */
66
+ maxSeconds?: number;
67
+ }
68
+
69
+ /** What the command reads and writes, so a test runs it without a proxy or a clock. */
70
+ export interface IProxyCapacityCliIo {
71
+ ask: (requestArg: IProxyCapacityRequest, signalArg: AbortSignal) => Promise<IProxyCapacityAnswer>;
72
+ now: () => number;
73
+ sleep: (msArg: number, signalArg: AbortSignal) => Promise<void>;
74
+ /** Standard output: the answer. */
75
+ write: (textArg: string) => void;
76
+ /** Standard error: what `--wait` waits for between its questions. */
77
+ note: (textArg: string) => void;
78
+ }
79
+
80
+ /**
81
+ * `agl proxy capacity`: asks the proxy, prints its answer (text or `--json`) and resolves to the exit status. With
82
+ * `--wait` it asks again after the pool's `seconds`, at most a minute and never past `--max-seconds`, until the pool is
83
+ * open or that time ran out, and prints the last answer. A failure (no proxy, an older one, a refusal) rejects.
84
+ */
85
+ export const runProxyCapacity = async (optionsArg: IProxyCapacityCliOptions, ioArg: IProxyCapacityCliIo,
86
+ signalArg: AbortSignal): Promise<number> => {
87
+ const deadline = optionsArg.maxSeconds === undefined ? Infinity : ioArg.now() + optionsArg.maxSeconds * 1000;
88
+ for (;;) {
89
+ const answer = await ioArg.ask(optionsArg.request, signalArg);
90
+ const open = answer.pools.every((poolArg) => poolArg.verdict.state === 'open');
91
+ const remaining = deadline - ioArg.now();
92
+ if (!optionsArg.wait || open || remaining <= 0) {
93
+ ioArg.write(optionsArg.json ? JSON.stringify(answer) + '\n' : formatProxyCapacity(answer));
94
+ return open ? proxyCapacityExitOpen : proxyCapacityExitWait;
95
+ }
96
+ // `--wait` names one pool, which waits: the pause is its seconds, at most a minute and never past `--max-seconds`.
97
+ const [waiting] = answer.pools.flatMap((poolArg) => poolArg.verdict.state === 'wait'
98
+ ? [{ provider: poolArg.provider, verdict: poolArg.verdict }] : []);
99
+ const pause = Math.min((waiting.verdict.seconds ?? 60) * 1000, longestPauseMs, remaining);
100
+ ioArg.note(`AGL proxy capacity: the ${poolNames[waiting.provider]} pool waits (${waitReasons[waiting.verdict.reason]}); `
101
+ + `asking again in ${Math.ceil(pause / 1000)} s.\n`);
102
+ await ioArg.sleep(pause, signalArg);
103
+ }
104
+ };
@@ -35,13 +35,26 @@ export const aglProxyUnitName = 'agl-proxy.service';
35
35
  export const aglProxyDefaultPort = 4100;
36
36
 
37
37
  /**
38
- * Confined runs (`agl proxy confined run`): Claude Code in a container that reaches the proxy only through the confined
39
- * listener, a Unix socket alone in its directory, which the run mounts read-only at `aglProxyConfinedMountPoint`. Their
40
- * sessions are those of the client `aglProxyConfinedClient`, and Claude Code names `aglProxyConfinedOrigin` as its
41
- * endpoint's origin, whose host the socket makes irrelevant.
38
+ * Confined runs (`agl proxy confined run`): Claude Code or Codex in a container that reaches the proxy only through the
39
+ * confined listener, a Unix socket alone in its directory, which the run mounts read-only at `aglProxyConfinedMountPoint`.
40
+ * Claude Code's sessions are those of the client `aglProxyConfinedClient`, and it names `aglProxyConfinedOrigin` as its
41
+ * endpoint's origin, whose host the socket makes irrelevant. Codex's are those of `aglProxyConfinedCodexClient`; it reaches
42
+ * the socket through AGL's relay (`aglProxyRelaySource`), mounted read-only at `aglProxyRelayMountPoint`.
42
43
  */
43
44
  export const aglProxyConfinedClient = 'confined';
45
+ export const aglProxyConfinedCodexClient = 'confined-codex';
44
46
  export const aglProxyConfinedOrigin = 'http://localhost';
45
47
  export const aglProxyConfinedMountPoint = '/run/agl-proxy';
46
48
  /** A confined run's id: the first 12 hex characters of its credential's SHA-256 digest. */
47
49
  export const aglProxyConfinedIdPattern = /^[a-f0-9]{12}$/;
50
+
51
+ /** The harness a confined run serves: Claude Code (on the Claude or the ChatGPT pool) or Codex (on the ChatGPT pool). */
52
+ export type TAglProxyConfinedHarness = 'claude' | 'codex';
53
+ /** What a confined run is asked for: Claude Code on either pool, or Codex on the ChatGPT pool. */
54
+ export type TAglProxyConfinedRun = { harness: 'claude'; provider: TInferenceProvider } | { harness: 'codex'; provider: 'openai' };
55
+
56
+ /** Where a Codex run's container finds AGL's relay, read-only, and the relay's file there. */
57
+ export const aglProxyRelayMountPoint = '/run/agl-proxy-relay';
58
+ export const aglProxyRelayFile = 'agl-relay.mjs';
59
+ /** The loopback port the relay listens on inside the container unless `AGL_PROXY_RELAY_PORT` names another. */
60
+ export const aglProxyRelayDefaultPort = 4100;
@@ -53,6 +53,17 @@ export const claudeRoutingVariables: readonly string[] = ['ANTHROPIC_API_KEY', '
53
53
  'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY', 'CLAUDE_CODE_USE_ANTHROPIC_AWS', 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',
54
54
  'CLAUDE_CODE_USE_MANTLE', 'CLAUDE_CODE_USE_GATEWAY', 'ANTHROPIC_UNIX_SOCKET'];
55
55
 
56
+ /**
57
+ * The variables that make Codex authenticate or route another way than through the proxy's provider, or read a home of
58
+ * its own choosing: an OpenAI or Codex key, token or login, an OpenAI endpoint, organization or project, workload
59
+ * identity federation, a remote or local model server, a CA bundle, and `CODEX_HOME`, which a confined run's container
60
+ * names itself.
61
+ */
62
+ export const codexRoutingVariables: readonly string[] = ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_ORGANIZATION',
63
+ 'OPENAI_PROJECT', 'OPENAI_IDENTITY_TOKEN_FILE', 'OPENAI_WORKLOAD_IDENTITY_CONTEXT', 'OPENAI_FEDERATION_RULE_ID',
64
+ 'CODEX_API_KEY', 'CODEX_ACCESS_TOKEN', 'CODEX_AUTH', 'CODEX_REMOTE_AUTH_TOKEN', 'CODEX_REMOTE_TOKEN', 'CODEX_HOME',
65
+ 'CODEX_CA_CERTIFICATE', 'CODEX_OSS_BASE_URL', 'CODEX_OSS_PORT'];
66
+
56
67
  /**
57
68
  * The variables a Claude Code settings file routed through the proxy may not set beside the proxy's: its endpoint and
58
69
  * routing, and a bearer token, which would take precedence over the `apiKeyHelper` that reads the proxy's credential.
@@ -16,11 +16,13 @@ import { configurationLocalCliActor } from './functions.configurationactor.js';
16
16
  import { preflightAGLHomeMigration } from './functions.controllerdataroot.js';
17
17
  import type { IControllerIssuerIdentity } from './interfaces.identity.js';
18
18
  import type { IControllerRuntimeConfig } from './interfaces.config.js';
19
- import type { IControllerAuditRemoteMove, TControllerAuditEventType } from './interfaces.auth.js';
19
+ import type { IRecordAuditEventDetails, TControllerAuditEventType } from './interfaces.auth.js';
20
+ import { controllerGatewayEnrolledHostnames } from './classes.gatewayclientstore.js';
20
21
 
21
22
  export const remoteCliHelp = `Usage: agl remote set --public-origin ORIGIN [--rp-id HOST] [--gateway-source ADDRESS]... [--port PORT]
22
23
  agl remote unset [--port PORT]
23
24
  agl remote secret import [--port PORT] < SECRET_FILE
25
+ agl remote gateway enrol|status|sync|remove [options] (agl remote gateway --help)
24
26
  Every command runs against a stopped controller (agl stop first) on the port it was initialized on (default 4097),
25
27
  as the local OS user, and is audited.
26
28
  set moves the port to the HTTPS public origin ORIGIN behind a TLS reverse proxy, with WebAuthn RP ID HOST (default:
@@ -29,9 +31,11 @@ reverse proxy on this host reaches the controller, which then listens on loopbac
29
31
  all of its data. When the origin or RP ID changes, its passkey is removed and every temporary password revoked: the
30
32
  next start prints a new setup code, to enroll a passkey at the new origin. When the origin changes, every paired
31
33
  device is removed as well (a device signs the origin it paired with). Run it again to change the gateway sources;
32
- the passkey and the devices then stay.
34
+ the passkey and the devices then stay. While the controller is enrolled with a gateway, set keeps the origin's
35
+ hostname: for another, run agl remote gateway remove, then agl remote set, then agl remote gateway enrol.
33
36
  unset moves the port back to http://localhost:PORT (RP ID localhost), removes the passkey and every paired device,
34
- revokes every temporary password and forgets the trusted-proxy secret.
37
+ revokes every temporary password and forgets the trusted-proxy secret. It is refused while the controller is enrolled
38
+ with a gateway: run agl remote gateway remove first.
35
39
  secret import reads a 32-byte base64url secret (43 characters) from standard input, never from a terminal, and makes
36
40
  it the controller's trusted-proxy secret, for a reverse proxy other than AGL's own gateway: that proxy injects it as
37
41
  X-Harness-Controller-Proxy-Secret. The secret is sealed with the TPM and never printed.
@@ -76,22 +80,29 @@ export const parseRemoteCliArguments = (argsArg: readonly string[]): TRemoteCliA
76
80
  };
77
81
 
78
82
  export interface IRemoteCliOptions {
79
- /** Seals the trusted-proxy secret; TPM2 when absent. For tests. */
83
+ /** Seals the trusted-proxy secret and the gateway credential; TPM2 when absent. For tests. */
80
84
  codec?: ITpmSecretCodec;
81
- /** Where `secret import` reads the secret; this process's standard input when absent. */
85
+ /** Where `secret import` and `gateway enrol` read their secret; this process's standard input when absent. */
82
86
  input?: NodeJS.ReadableStream & { isTTY?: boolean };
83
87
  /** Where the outcome is written; standard output when absent. */
84
88
  write?: (textArg: string) => void;
89
+ /** Waits before each retried gateway confirmation of `gateway enrol`; 1 s and 3 s when absent. For tests. */
90
+ finalizeRetryDelaysMs?: readonly number[];
85
91
  }
86
92
 
87
- /** A trusted-proxy secret file is a few dozen bytes; anything past this is not one. */
93
+ /** A secret on standard input is a few dozen bytes; anything past this is not one. */
88
94
  const maximumSecretInputBytes = 4_096;
89
95
 
90
- const readSecretInput = async (inputArg: NodeJS.ReadableStream & { isTTY?: boolean }): Promise<string> => {
91
- if (inputArg.isTTY) {
92
- throw new Error('agl remote secret import reads the secret from a pipe or a file, never from a terminal: '
93
- + 'run it as `agl remote secret import --port <port> < SECRET_FILE`.');
94
- }
96
+ /**
97
+ * Reads a secret from standard input, a pipe or a file, never a terminal (`refusalArg` names the right way), and
98
+ * returns it trimmed; nothing of it is echoed or kept past the read.
99
+ */
100
+ export const readStandardInputSecret = async (
101
+ inputArg: NodeJS.ReadableStream & { isTTY?: boolean },
102
+ refusalArg: string,
103
+ whatArg: string,
104
+ ): Promise<string> => {
105
+ if (inputArg.isTTY) throw new Error(refusalArg);
95
106
  const chunks: Buffer[] = [];
96
107
  let bytes = 0;
97
108
  try {
@@ -99,7 +110,7 @@ const readSecretInput = async (inputArg: NodeJS.ReadableStream & { isTTY?: boole
99
110
  const buffer = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk as Uint8Array);
100
111
  chunks.push(buffer);
101
112
  bytes += buffer.byteLength;
102
- if (bytes > maximumSecretInputBytes) throw new Error('The standard input is longer than a trusted-proxy secret.');
113
+ if (bytes > maximumSecretInputBytes) throw new Error(`The standard input is longer than ${whatArg}.`);
103
114
  }
104
115
  return Buffer.concat(chunks).toString('utf8').trim();
105
116
  } finally {
@@ -107,6 +118,13 @@ const readSecretInput = async (inputArg: NodeJS.ReadableStream & { isTTY?: boole
107
118
  }
108
119
  };
109
120
 
121
+ const readSecretInput = (inputArg: NodeJS.ReadableStream & { isTTY?: boolean }): Promise<string> => readStandardInputSecret(
122
+ inputArg,
123
+ 'agl remote secret import reads the secret from a pipe or a file, never from a terminal: '
124
+ + 'run it as `agl remote secret import --port <port> < SECRET_FILE`.',
125
+ 'a trusted-proxy secret',
126
+ );
127
+
110
128
  /**
111
129
  * Holds the controller's port on loopback while a command changes its stopped configuration: a controller still
112
130
  * listening there (on loopback or every interface) is found, and one starting meanwhile cannot listen until the
@@ -137,7 +155,7 @@ const releasePort = (serverArg: plugins.net.Server): Promise<void> => new Promis
137
155
  serverArg.close(() => resolve());
138
156
  });
139
157
 
140
- interface IStoppedController {
158
+ export interface IStoppedController {
141
159
  authStore: SmartDataAuthStore;
142
160
  issuer: IControllerIssuerIdentity;
143
161
  /** `controller:<port>`. */
@@ -146,7 +164,7 @@ interface IStoppedController {
146
164
  }
147
165
 
148
166
  /** Runs `actionArg` on the stored configuration of a stopped, initialized controller, under start admission. */
149
- const withStoppedController = async <T>(
167
+ export const withStoppedController = async <T>(
150
168
  portArg: number,
151
169
  actionArg: (controllerArg: IStoppedController) => Promise<T>,
152
170
  ): Promise<T> => {
@@ -174,16 +192,16 @@ const withStoppedController = async <T>(
174
192
 
175
193
  /**
176
194
  * Records `typeArg` as attempted, runs the change, and records its outcome, attributed to this OS user and process;
177
- * a move records on every event where it goes from and to (`details.remoteMove`).
195
+ * every event records `detailsArg` (a move where it goes from and to, a gateway command its route).
178
196
  */
179
- const audited = async <T>(
197
+ export const audited = async <T>(
180
198
  authStoreArg: SmartDataAuthStore,
181
199
  typeArg: TControllerAuditEventType,
182
200
  actionArg: () => Promise<T>,
183
- remoteMoveArg?: IControllerAuditRemoteMove,
201
+ detailsArg?: IRecordAuditEventDetails,
184
202
  ): Promise<T> => {
185
203
  const localCli = await configurationLocalCliActor();
186
- const detail = { localCli, ...(remoteMoveArg === undefined ? {} : { details: { remoteMove: remoteMoveArg } }) };
204
+ const detail = { localCli, ...(detailsArg === undefined ? {} : { details: detailsArg }) };
187
205
  await authStoreArg.recordAuditEvent({ type: typeArg, outcome: 'attempted', ...detail });
188
206
  let result: T;
189
207
  try {
@@ -228,6 +246,11 @@ const moveOutcome = (
228
246
 
229
247
  export const runRemoteCli = async (argsArg: string[], optionsArg: IRemoteCliOptions = {}): Promise<void> => {
230
248
  const write = optionsArg.write ?? ((textArg: string) => { process.stdout.write(textArg); });
249
+ if (argsArg[0] === 'gateway') {
250
+ const { runGatewayCli } = await import('./functions.gatewaycli.js');
251
+ await runGatewayCli(argsArg.slice(1), optionsArg);
252
+ return;
253
+ }
231
254
  if (argsArg.includes('--help') || argsArg.includes('-h')) { write(remoteCliHelp); return; }
232
255
  const parsed = parseRemoteCliArguments(argsArg);
233
256
  if (parsed.action === 'secret-import') {
@@ -250,19 +273,32 @@ export const runRemoteCli = async (argsArg: string[], optionsArg: IRemoteCliOpti
250
273
  return;
251
274
  }
252
275
  write(await withStoppedController(parsed.port, async (controllerArg) => {
276
+ // The gateway's route serves the origin this would drop: it goes first, with its DNS record.
277
+ const enrolledHostnames = await controllerGatewayEnrolledHostnames(controllerArg.controllerId);
278
+ if (parsed.action === 'unset' && enrolledHostnames.length > 0) {
279
+ throw new Error(`${controllerArg.controllerId} is enrolled with a gateway: run \`agl remote gateway remove --port `
280
+ + `${parsed.port}\` first, which deletes its route there.`);
281
+ }
253
282
  const target = resolveMovedRuntimeConfig(controllerArg.config, parsed.action === 'set'
254
283
  ? { publicOrigin: parsed.publicOrigin, ...(parsed.rpId === undefined ? {} : { rpId: parsed.rpId }), gatewaySources: parsed.gatewaySources }
255
284
  : 'local');
285
+ // Its route serves one hostname: a move to another goes through removing the enrolment and enrolling again.
286
+ const targetHostname = new URL(target.publicOrigin).hostname;
287
+ if (parsed.action === 'set' && enrolledHostnames.some((hostnameArg) => hostnameArg !== targetHostname)) {
288
+ throw new Error(`${controllerArg.controllerId} is enrolled with a gateway for ${enrolledHostnames.join(' and ')}, `
289
+ + `which ${target.publicOrigin} does not keep: run \`agl remote gateway remove --port ${parsed.port}\`, then `
290
+ + `\`agl remote set\`, then \`agl remote gateway enrol --port ${parsed.port}\`.`);
291
+ }
256
292
  const type = parsed.action === 'set' ? 'remote.set' as const : 'remote.unset' as const;
257
293
  const moved = await audited(controllerArg.authStore, type, async () => {
258
294
  const result = await controllerArg.authStore.moveRuntimeConfig(target);
259
295
  // Local mode takes no trusted-proxy secret, and moving back behind a proxy generates a new one.
260
296
  if (parsed.action === 'unset') await removeControllerTrustedProxySecret(controllerArg.controllerId);
261
297
  return result;
262
- }, {
298
+ }, { remoteMove: {
263
299
  previous: { publicOrigin: controllerArg.config.publicOrigin, rpId: controllerArg.config.rpId },
264
300
  target: { publicOrigin: target.publicOrigin, rpId: target.rpId },
265
- });
301
+ } });
266
302
  return moved.changed
267
303
  ? moveOutcome(controllerArg.controllerId, moved.previous, target, moved.enrollmentReset, moved.devicesRemoved)
268
304
  : `${controllerArg.controllerId} already serves ${describeConfig(target)}; nothing changed.\n`;
@@ -60,6 +60,7 @@ export const controllerAuditEventTypes = [
60
60
  'slash.execute',
61
61
  'permission.reply',
62
62
  'question.reply',
63
+ 'elicitation.reply',
63
64
  'project.list',
64
65
  'project.create',
65
66
  'project.remove',
@@ -146,6 +147,12 @@ export const controllerAuditEventTypes = [
146
147
  'remote.set',
147
148
  'remote.unset',
148
149
  'remote.secret.import',
150
+ // The controller's own gateway route (AGL-828): `agl remote gateway enrol|remove` against a stopped controller, and
151
+ // `agl remote gateway sync` over the running controller's loopback management endpoint.
152
+ 'remote.gateway.enrol',
153
+ 'remote.gateway.sync',
154
+ 'remote.gateway.remove',
155
+ 'remote.gateway.abandon',
149
156
  // Paired devices (AGL-824): the owner makes a pairing code and revokes a device; a device pairs and authenticates.
150
157
  'device.pairing.begin',
151
158
  'device.pair',
@@ -272,21 +279,39 @@ export interface IControllerAuditRemoteMove {
272
279
  target: IControllerAuditRemoteEndpoint;
273
280
  }
274
281
 
282
+ /** The gateway route an `agl remote gateway` command acted on, as its audit events record it; never a credential. */
283
+ export interface IControllerAuditGateway {
284
+ gatewayUrl: string;
285
+ gatewayClientId: string;
286
+ appId: string;
287
+ hostname: string;
288
+ targetHost: string;
289
+ targetPort: number;
290
+ /** The key the gateway files the route under (`custom:<client>:<app>:<hostname>`). */
291
+ routeKey: string;
292
+ /** `remote.gateway.sync` only: whether the trusted-proxy secret was rotated first. */
293
+ rotate?: boolean;
294
+ }
295
+
275
296
  /**
276
297
  * What an audit event records beyond its envelope (bounded plain JSON). This release records `remoteMove` on
277
- * `remote.set` and `remote.unset`; any other key is a later release's, kept and pruned as it wrote it.
298
+ * `remote.set` and `remote.unset` and `gateway` on `remote.gateway.*`; any other key is a later release's, kept and
299
+ * pruned as it wrote it.
278
300
  */
279
301
  export interface IControllerAuditEventDetails {
280
302
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
281
303
  remoteMove?: IControllerAuditRemoteMove;
304
+ /** `remote.gateway.*` only: the gateway route the command acted on. */
305
+ gateway?: IControllerAuditGateway;
282
306
  [key: string]: unknown;
283
307
  }
284
308
 
285
309
  /** What this release records in an audit event's `details`. */
286
- export interface IRecordAuditEventDetails {
310
+ export type IRecordAuditEventDetails =
287
311
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
288
- remoteMove: IControllerAuditRemoteMove;
289
- }
312
+ | { remoteMove: IControllerAuditRemoteMove }
313
+ /** `remote.gateway.*` only: the gateway route the command acted on. */
314
+ | { gateway: IControllerAuditGateway };
290
315
 
291
316
  /**
292
317
  * A stored audit event. The audit log is shared with later releases, so a stored `type` is any audit type, also one
package/ts/plugins.ts CHANGED
@@ -130,6 +130,11 @@ import * as objectstorageEngine from '@lossless.org/objectstorage';
130
130
 
131
131
  export { nosqldb, nosqldbEngine, objectstorage, objectstorageEngine };
132
132
 
133
+ // @serve.zone modules: the gateway (dcrouter) contracts AGL's own gateway client speaks (AGL-828).
134
+ import * as servezoneInterfaces from '@serve.zone/interfaces';
135
+
136
+ export { servezoneInterfaces };
137
+
133
138
  // third-party modules
134
139
  import * as claudeAgentSdk from '@anthropic-ai/claude-agent-sdk';
135
140
  import * as simplewebauthnServer from '@simplewebauthn/server';
@@ -10,7 +10,7 @@
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
15
 
16
16
  /**
@@ -46,19 +46,6 @@ export interface IAuthSwitchPlacement {
46
46
  export const authSwitchAccountLifecycle = (lapsesAtArg: string | null, nowArg: number): TAuthSwitchAccountLifecycle =>
47
47
  lapsesAtArg === null ? 'active' : Date.parse(lapsesAtArg) <= nowArg ? 'lapsed' : 'canceled';
48
48
 
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
49
  /**
63
50
  * Where an account stands for a new session at `nowArg`, from its usage reading (`null` when none is held), its usage
64
51
  * threshold and its lapse date.
@@ -84,7 +71,7 @@ export const authSwitchPlacement = (readingArg: TAuthSwitchUsageReading | null,
84
71
  const spendMonthEnded = readingArg?.kind === 'spend' && authSwitchSpendMonthEnded(readingArg.spend, nowArg);
85
72
  const scores = windows.map((windowArg) => {
86
73
  const headroom = spendMonthEnded ? threshold : Math.max(0, threshold - authSwitchUsageWindowPercent(windowArg));
87
- const resetAt = spendMonthEnded ? Date.parse(authSwitchSpendPeriod(nowArg).end) : windowResetAt(windowArg, nowArg);
74
+ const resetAt = spendMonthEnded ? Date.parse(authSwitchSpendPeriod(nowArg).end) : authSwitchUsageWindowResetAt(windowArg, nowArg);
88
75
  const deadline = Math.min(resetAt, lapsesAt);
89
76
  return headroom / (Math.max(deadline - nowArg, minimumDeadlineMs) / 3_600_000);
90
77
  });
@@ -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)}`;