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
@@ -0,0 +1,191 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { IInferenceAccountStatus } from './classes.inferencerouter.js';
3
+ import {
4
+ proxyCapacityQuietMs,
5
+ type IProxyCapacityMember,
6
+ type IProxyCapacityPool,
7
+ type IProxyCapacityWindow,
8
+ type TProxyCapacityProvider,
9
+ type TProxyCapacityVerdict,
10
+ type TProxyCapacityWaitReason,
11
+ } from '../ts_interfaces/proxycapacity.js';
12
+
13
+ /**
14
+ * Which plans a pool counts, by the plan name its member's held reading states: `only` the plans listed, or every plan
15
+ * `except` them. A Claude account counts on Max alone (Anthropic's `organization_type` `claude_max`, both Max tiers;
16
+ * Claude Code reads the tier apart, from `rate_limit_tier`), a ChatGPT account on every plan but Free.
17
+ */
18
+ export interface IProxyCapacityPlanRule {
19
+ counts: 'only' | 'except';
20
+ plans: readonly string[];
21
+ }
22
+
23
+ export const proxyCapacityPlans: Readonly<Record<TProxyCapacityProvider, IProxyCapacityPlanRule>> = {
24
+ anthropic: { counts: 'only', plans: ['max'] },
25
+ openai: { counts: 'except', plans: ['free'] },
26
+ };
27
+
28
+ /** Whether a pool counts an account of the plan `planArg` names. */
29
+ export const proxyCapacityPlanCounts = (providerArg: TProxyCapacityProvider, planArg: string): boolean => {
30
+ const rule = proxyCapacityPlans[providerArg];
31
+ return rule.plans.includes(planArg) === (rule.counts === 'only');
32
+ };
33
+
34
+ /** The plan a held reading of the pool's kind states, whatever its age; `null` without one. */
35
+ export const proxyCapacityHeldPlan = (providerArg: TProxyCapacityProvider,
36
+ usageArg: plugins.authswitchAuthority.IAuthSwitchUsageSnapshot | undefined): string | null => {
37
+ const reading = usageArg?.reading;
38
+ if (providerArg === 'anthropic') return reading?.kind === 'anthropic' ? reading.status.plan?.name || null : null;
39
+ return reading?.kind === 'openai' ? reading.rateLimits.plan || null : null;
40
+ };
41
+
42
+ /** One account of the proxy as the capacity judges it. */
43
+ export interface IProxyCapacityAccount {
44
+ /** As `InferenceRouter.accountStatus` judged it. */
45
+ status: IInferenceAccountStatus;
46
+ /** The usage reading the status judged it on, or `undefined` while none is held. */
47
+ usage: plugins.authswitchAuthority.IAuthSwitchUsageSnapshot | undefined;
48
+ /** The newest provider 429 on it the proxy saw (epoch milliseconds), or `null`; and until when it rests after one (0: it does not). */
49
+ quota: { lastAt: number | null; restUntil: number };
50
+ }
51
+
52
+ export interface IProxyCapacityOptions {
53
+ /** The room the pool needs: a non-negative integer, in headroom percent summed over its members. */
54
+ minHeadroom: number;
55
+ /** Since when the proxy observes provider 429s (epoch milliseconds): its start. */
56
+ observedSince: number;
57
+ /** Epoch milliseconds. */
58
+ now: number;
59
+ }
60
+
61
+ /** A member's headroom over time: what it adds now, and each later moment that changes, with what it adds from then on. */
62
+ interface IMemberProjection {
63
+ member: IProxyCapacityMember;
64
+ now: number;
65
+ steps: Array<{ at: number; headroom: number }>;
66
+ }
67
+
68
+ /** What a projection adds to the room at `atArg`, no earlier than now. */
69
+ const headroomAt = (projectionArg: IMemberProjection, atArg: number): number => {
70
+ let headroom = projectionArg.now;
71
+ for (const step of projectionArg.steps) {
72
+ if (step.at > atArg) break;
73
+ headroom = step.headroom;
74
+ }
75
+ return headroom;
76
+ };
77
+
78
+ const iso = (atArg: number): string => new Date(atArg).toISOString();
79
+
80
+ const capacityWindow = (windowArg: plugins.authswitchUsageWindows.IAuthSwitchUsageWindow): IProxyCapacityWindow => ({
81
+ name: plugins.authswitchUsageWindows.authSwitchUsageWindowName(windowArg).slice(0, 128),
82
+ durationSeconds: windowArg.durationSeconds,
83
+ usedPercent: plugins.authswitchUsageWindows.authSwitchUsageWindowPercent(windowArg),
84
+ estimated: windowArg.estimatedUsedPercent !== null,
85
+ resetAt: windowArg.resetAt,
86
+ });
87
+
88
+ /**
89
+ * One member's projection. An account that takes work adds its headroom (`authSwitchHeadroomGrowth`) and grows as its
90
+ * windows reset. One that does not adds 0 until it takes work again -- a provider 429's rest ends (`cooling`), or the
91
+ * windows and provider refusal its limit is held by lift (`reserved`, `exhausted`: the limit's reset, never before the
92
+ * rest of a 429) -- and from then on what its windows leave it. One the proxy cannot judge (`unavailable`: a stale
93
+ * reading, a sign-in, model list or payment problem), or whose reading counts no window, adds 0 with no growth
94
+ * foreseen. A canceled account adds nothing from its lapse on.
95
+ */
96
+ const projectMember = (accountArg: IProxyCapacityAccount, planArg: string, nowArg: number): IMemberProjection => {
97
+ const { status, usage, quota } = accountArg;
98
+ const base = { accountId: status.id, plan: planArg, state: status.state };
99
+ const recheckAt = status.unavailable?.reason === 'usage_unread' ? status.unavailable.retryAt ?? null : null;
100
+ if (status.state === 'unavailable' || status.headroom === null || !usage?.reading) {
101
+ return { now: 0, steps: [], member: { ...base, headroom: 0, binding: null, growsAt: null, growsTo: null, recheckAt } };
102
+ }
103
+ const growth = plugins.authswitchUsageLimit.authSwitchHeadroomGrowth(usage.reading, status.maxUsagePercent, nowArg,
104
+ status.reserveLiftUntil);
105
+ if (growth.headroom === null) {
106
+ return { now: 0, steps: [], member: { ...base, headroom: 0, binding: null, growsAt: null, growsTo: null, recheckAt } };
107
+ }
108
+ const windowsHeadroomAt = (atArg: number): number => {
109
+ let headroom = growth.headroom!;
110
+ for (const step of growth.steps) {
111
+ if (step.at > atArg) break;
112
+ headroom = step.headroom;
113
+ }
114
+ return headroom;
115
+ };
116
+ // When it takes work again: now, a known moment ahead, or never as far as the reading says.
117
+ const statedReset = status.resetAt === null ? Number.NaN : Date.parse(status.resetAt);
118
+ const returns = status.state === 'available' ? -Infinity
119
+ : status.state === 'cooling' ? statedReset
120
+ : Math.max(statedReset, quota.restUntil);
121
+ const takesWorkFrom = status.state === 'available' ? -Infinity
122
+ : Number.isFinite(returns) && returns > nowArg ? returns : Infinity;
123
+ const lapses = status.lifecycle === 'canceled' && status.lapsesAt !== null ? Date.parse(status.lapsesAt) : Infinity;
124
+ const adds = (atArg: number): number => atArg >= takesWorkFrom && atArg < lapses ? windowsHeadroomAt(atArg) : 0;
125
+ const moments = [...new Set([...growth.steps.map((stepArg) => stepArg.at), takesWorkFrom, lapses])]
126
+ .filter((atArg) => Number.isFinite(atArg) && atArg > nowArg)
127
+ .sort((left, right) => left - right);
128
+ const current = adds(nowArg);
129
+ const steps: Array<{ at: number; headroom: number }> = [];
130
+ let previous = current;
131
+ for (const at of moments) {
132
+ const headroom = adds(at);
133
+ if (headroom !== previous) steps.push({ at, headroom });
134
+ previous = headroom;
135
+ }
136
+ let before = current;
137
+ const grows = steps.find((stepArg) => {
138
+ const grew = stepArg.headroom > before;
139
+ before = stepArg.headroom;
140
+ return grew;
141
+ });
142
+ return { now: current, steps, member: { ...base, headroom: current,
143
+ binding: growth.binding ? capacityWindow(growth.binding) : null,
144
+ growsAt: grows ? iso(grows.at) : null, growsTo: grows ? grows.headroom : null, recheckAt } };
145
+ };
146
+
147
+ /**
148
+ * A pool's room for new work (AGL-1097). Its members are the pool's subscription sign-ins that have not lapsed and whose
149
+ * held reading states a plan the pool counts (`proxyCapacityPlans`), stale or not; API keys never count. The room is
150
+ * the headroom its members add now (see `projectMember`), summed.
151
+ *
152
+ * The pool is open when the room reaches `minHeadroom` and it is quiet: no provider 429 on a member within
153
+ * `proxyCapacityQuietMs`, which the proxy can say only once it has observed that long. Otherwise it waits until the
154
+ * first moment the members' readings foresee the room at the minimum once it is quiet (`room`), or until it is quiet when
155
+ * the room is there by then (`provider-429`, or `quiet-unobserved` while the proxy has not observed long enough); with
156
+ * no such moment foreseen, without an end (`until` and `seconds` `null`). Each projected moment is the earliest the room
157
+ * can be there, as no reading foresees the usage spent meanwhile.
158
+ */
159
+ export const proxyPoolCapacity = (providerArg: TProxyCapacityProvider, accountsArg: readonly IProxyCapacityAccount[],
160
+ optionsArg: IProxyCapacityOptions): IProxyCapacityPool => {
161
+ const { now, minHeadroom, observedSince } = optionsArg;
162
+ const counted = accountsArg.flatMap((accountArg) => {
163
+ const { status } = accountArg;
164
+ if (status.provider !== providerArg || status.credential !== 'subscription' || status.lifecycle === 'lapsed') return [];
165
+ const plan = proxyCapacityHeldPlan(providerArg, accountArg.usage);
166
+ return plan !== null && proxyCapacityPlanCounts(providerArg, plan) ? [{ account: accountArg, plan }] : [];
167
+ }).sort((left, right) => left.account.status.id.localeCompare(right.account.status.id));
168
+ const projections = counted.map(({ account, plan }) => projectMember(account, plan, now));
169
+ const roomAt = (atArg: number): number => projections.reduce((sumArg, projectionArg) => sumArg + headroomAt(projectionArg, atArg), 0);
170
+ const room = roomAt(now);
171
+ const lastQuota = counted.reduce<number | null>((latestArg, { account }) => account.quota.lastAt === null ? latestArg
172
+ : Math.max(latestArg ?? -Infinity, account.quota.lastAt), null);
173
+ // When the pool is quiet, and why it is not before.
174
+ const quiet: Array<{ until: number; reason: TProxyCapacityWaitReason }> = [
175
+ ...(lastQuota !== null ? [{ until: lastQuota + proxyCapacityQuietMs, reason: 'provider-429' as const }] : []),
176
+ { until: observedSince + proxyCapacityQuietMs, reason: 'quiet-unobserved' as const },
177
+ ].filter((entryArg) => entryArg.until > now).sort((left, right) => right.until - left.until);
178
+ const quietFrom = quiet[0]?.until ?? now;
179
+ let verdict: TProxyCapacityVerdict;
180
+ if (!quiet.length && room >= minHeadroom) verdict = { state: 'open' };
181
+ else {
182
+ const moments = [...new Set(projections.flatMap((projectionArg) => projectionArg.steps.map((stepArg) => stepArg.at)))]
183
+ .filter((atArg) => atArg > quietFrom).sort((left, right) => left - right);
184
+ const enough = roomAt(quietFrom) >= minHeadroom ? quietFrom : moments.find((atArg) => roomAt(atArg) >= minHeadroom);
185
+ verdict = enough === undefined ? { state: 'wait', reason: 'room', until: null, seconds: null }
186
+ : { state: 'wait', reason: enough > quietFrom || !quiet.length ? 'room' : quiet[0].reason, until: iso(enough),
187
+ seconds: Math.max(1, Math.ceil((enough - now) / 1000)) };
188
+ }
189
+ return { provider: providerArg, minHeadroom, room, members: projections.map((projectionArg) => projectionArg.member),
190
+ last429At: lastQuota === null ? null : iso(lastQuota), verdict };
191
+ };
@@ -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
+ };
@@ -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`;
@@ -68,6 +68,16 @@ const referenceContent = plugins.z.array(plugins.z.discriminatedUnion('type', [
68
68
  plugins.z.object({ type: plugins.z.literal('text'), text: text(64 * 1024) }).strict(),
69
69
  plugins.z.object({ type: plugins.z.literal('reference'), id: identifier, label: text(200).min(1) }).strict(),
70
70
  ])).min(1).max(100).refine((valueArg) => JSON.stringify(valueArg).length <= 64 * 1024);
71
+ /**
72
+ * A comment's body: text, which the store keeps as one text part, or parts. Either is held to what a stored comment
73
+ * holds (`referenceContent`, at most 64 KiB as JSON), so text the store cannot keep is refused as input, never at the
74
+ * write.
75
+ */
76
+ const commentBody = plugins.z.union([
77
+ text(64 * 1024).min(1).refine((valueArg) => JSON.stringify([{ type: 'text', text: valueArg }]).length <= 64 * 1024,
78
+ 'A comment holds at most 64 KiB, counted as the store keeps it.'),
79
+ referenceContent,
80
+ ]);
71
81
  const optionId = plugins.z.string().regex(/^[1-9][0-9]*$/u);
72
82
  const questionOption = plugins.z.object({ label: text(200).trim().min(1), description: text(1000).optional() }).strict();
73
83
  const filters = plugins.z.object({ mine: plugins.z.boolean().optional(), project: identifier.optional(),
@@ -93,7 +103,7 @@ export const ticketInputSchemas = {
93
103
  attachments: plugins.z.array(attachment).max(100).optional() }).strict(),
94
104
  update: plugins.z.object({ ticketId, expectedRevision: plugins.z.number().int().nonnegative(), changes }).strict(),
95
105
  move: plugins.z.object({ ticketId, columnId: plugins.z.enum(ticketColumns), beforeTicketId: ticketId.optional() }).strict(),
96
- comment: plugins.z.object({ ticketId, body: plugins.z.union([text(64 * 1024).min(1), referenceContent]) }).strict(),
106
+ comment: plugins.z.object({ ticketId, body: commentBody }).strict(),
97
107
  link: plugins.z.object({ ticketId, link }).strict(),
98
108
  // A link is removed exactly as it is held, fleet release links (repo, sha) included.
99
109
  unlink: plugins.z.object({ ticketId, link: storedLink }).strict(),
@@ -61,6 +61,13 @@ export const controllerAuditEventTypes = [
61
61
  'permission.reply',
62
62
  'question.reply',
63
63
  'elicitation.reply',
64
+ // The owner answers a ticket question, from the browser or a paired device (AGL-1635); the envelope alone.
65
+ 'ticket.answer',
66
+ // The owner comments on, asks on or moves a ticket, from the browser's board or a paired device (AGL-1637); the
67
+ // envelope alone, which 41.1.0 and later read as unknown types.
68
+ 'ticket.comment',
69
+ 'ticket.ask',
70
+ 'ticket.move',
64
71
  'project.list',
65
72
  'project.create',
66
73
  'project.remove',
@@ -77,6 +84,7 @@ export const controllerAuditEventTypes = [
77
84
  'accounts.apikey.add',
78
85
  'accounts.spendlimit',
79
86
  'accounts.claudecode',
87
+ 'accounts.renewal',
80
88
  'accounts.remove',
81
89
  'accounts.add',
82
90
  'accounts.reauth',
@@ -147,6 +155,12 @@ export const controllerAuditEventTypes = [
147
155
  'remote.set',
148
156
  'remote.unset',
149
157
  'remote.secret.import',
158
+ // The controller's own gateway route (AGL-828): `agl remote gateway enrol|remove` against a stopped controller, and
159
+ // `agl remote gateway sync` over the running controller's loopback management endpoint.
160
+ 'remote.gateway.enrol',
161
+ 'remote.gateway.sync',
162
+ 'remote.gateway.remove',
163
+ 'remote.gateway.abandon',
150
164
  // Paired devices (AGL-824): the owner makes a pairing code and revokes a device; a device pairs and authenticates.
151
165
  'device.pairing.begin',
152
166
  'device.pair',
@@ -273,21 +287,39 @@ export interface IControllerAuditRemoteMove {
273
287
  target: IControllerAuditRemoteEndpoint;
274
288
  }
275
289
 
290
+ /** The gateway route an `agl remote gateway` command acted on, as its audit events record it; never a credential. */
291
+ export interface IControllerAuditGateway {
292
+ gatewayUrl: string;
293
+ gatewayClientId: string;
294
+ appId: string;
295
+ hostname: string;
296
+ targetHost: string;
297
+ targetPort: number;
298
+ /** The key the gateway files the route under (`custom:<client>:<app>:<hostname>`). */
299
+ routeKey: string;
300
+ /** `remote.gateway.sync` only: whether the trusted-proxy secret was rotated first. */
301
+ rotate?: boolean;
302
+ }
303
+
276
304
  /**
277
305
  * What an audit event records beyond its envelope (bounded plain JSON). This release records `remoteMove` on
278
- * `remote.set` and `remote.unset`; any other key is a later release's, kept and pruned as it wrote it.
306
+ * `remote.set` and `remote.unset` and `gateway` on `remote.gateway.*`; any other key is a later release's, kept and
307
+ * pruned as it wrote it.
279
308
  */
280
309
  export interface IControllerAuditEventDetails {
281
310
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
282
311
  remoteMove?: IControllerAuditRemoteMove;
312
+ /** `remote.gateway.*` only: the gateway route the command acted on. */
313
+ gateway?: IControllerAuditGateway;
283
314
  [key: string]: unknown;
284
315
  }
285
316
 
286
317
  /** What this release records in an audit event's `details`. */
287
- export interface IRecordAuditEventDetails {
318
+ export type IRecordAuditEventDetails =
288
319
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
289
- remoteMove: IControllerAuditRemoteMove;
290
- }
320
+ | { remoteMove: IControllerAuditRemoteMove }
321
+ /** `remote.gateway.*` only: the gateway route the command acted on. */
322
+ | { gateway: IControllerAuditGateway };
291
323
 
292
324
  /**
293
325
  * 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
@@ -66,6 +66,11 @@ import * as authswitchClaudeNative from '../ts_authswitch/classes.claudenative.j
66
66
  import * as authswitchSpend from '../ts_authswitch/authority-spend.js';
67
67
  // Whether a held payment problem still holds an account, the one rule the authority and the proxy share.
68
68
  import * as authswitchSubscription from '../ts_authswitch/authority-subscription.js';
69
+ // A Claude sign-in's monthly renewal as its owner set it: the rule, the next renewal, which placement and the status share.
70
+ import * as authswitchRenewal from '../ts_authswitch/authority-renewal.js';
71
+ // The login an account's usage is read with (`authSwitchUsageLogin`), the rule `authswitch list` and a device's API key
72
+ // counts share. The package root already loads this module through its CLI, so the value import adds none.
73
+ import * as authswitchOverview from '../ts_authswitch/authority-overview.js';
69
74
  import * as crossharness from '@modelprofile.com/mcp-crossharness';
70
75
  import * as mcpSystem from '@modelprofile.com/mcp-system';
71
76
  import * as flexharnessMigration from '@modelprofile.com/flexharness/migration';
@@ -87,6 +92,8 @@ export {
87
92
  authswitchClaudeNative,
88
93
  authswitchSpend,
89
94
  authswitchSubscription,
95
+ authswitchRenewal,
96
+ authswitchOverview,
90
97
  flexharness,
91
98
  browserRuntime,
92
99
  smartbrowser,
@@ -130,6 +137,11 @@ import * as objectstorageEngine from '@lossless.org/objectstorage';
130
137
 
131
138
  export { nosqldb, nosqldbEngine, objectstorage, objectstorageEngine };
132
139
 
140
+ // @serve.zone modules: the gateway (dcrouter) contracts AGL's own gateway client speaks (AGL-828).
141
+ import * as servezoneInterfaces from '@serve.zone/interfaces';
142
+
143
+ export { servezoneInterfaces };
144
+
133
145
  // third-party modules
134
146
  import * as claudeAgentSdk from '@anthropic-ai/claude-agent-sdk';
135
147
  import * as simplewebauthnServer from '@simplewebauthn/server';
@@ -271,6 +271,14 @@ export interface IAuthSwitchAccount {
271
271
  * request. Clearing the date makes it active again. See `authority-placement.ts`.
272
272
  */
273
273
  lapsesAt: string | null;
274
+ /**
275
+ * The anchor of a Claude sign-in's monthly renewal, as its owner set it (ISO 8601 UTC, `isAuthSwitchRenewsAt` of
276
+ * `authority-renewal.ts`); `null` when none is set, and always for any other account. Every renewal is a calendar
277
+ * month from the anchor (`authSwitchNextRenewal`); nothing derives it from a provider. Placement spends a window's
278
+ * usage by the next renewal when that comes before the window resets; it changes no lifecycle, and an account with a
279
+ * lapse date ignores it. Whether the windows reset at a renewal is not known. See `authority-placement.ts`.
280
+ */
281
+ renewsAt: string | null;
274
282
  /**
275
283
  * An API key account's spend limit per calendar month in UTC, in micro-dollars (`isAuthSwitchSpendLimitMicroUsd`);
276
284
  * `null` for none, and always for an account on a sign-in. The limit counts what AGL's inference proxy relayed on the
@@ -1524,6 +1532,18 @@ export interface IReq_AuthSwitchSetAccountLapse extends ITypedRequest {
1524
1532
  response: { account: IAuthSwitchAccount };
1525
1533
  }
1526
1534
 
1535
+ /**
1536
+ * Sets the anchor of a Claude sign-in's monthly renewal (`renewsAt`, see `isAuthSwitchRenewsAt`), or clears it with
1537
+ * `null`. A past anchor is valid: the next renewal is a whole number of months after it. `expectedRevision` is the
1538
+ * revision the caller read, so a change of an account that changed meanwhile is refused as `account_changed`; a value
1539
+ * that breaks the rule, or any account other than a Claude sign-in, is refused as `invalid_input`.
1540
+ */
1541
+ export interface IReq_AuthSwitchSetAccountRenewal extends ITypedRequest {
1542
+ method: 'authswitch.authority.renewal';
1543
+ request: { accountId: string; expectedRevision: number; renewsAt: string | null };
1544
+ response: { account: IAuthSwitchAccount };
1545
+ }
1546
+
1527
1547
  /**
1528
1548
  * One binding by the id `bind` returned, credential-free, or `null` when this authority holds no binding by
1529
1549
  * that id. A backend checks that its binding still stands without reading the whole snapshot.