agl 43.1.0 → 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 (123) hide show
  1. package/changelog.md +12 -0
  2. package/dist_serve/bundle.js +5329 -5116
  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_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +325 -1
  8. package/dist_ts/aglapi/interfaces.d.ts +3 -0
  9. package/dist_ts/aglapi/interfaces.js +2 -1
  10. package/dist_ts/classes.authmodels.js +17 -4
  11. package/dist_ts/classes.authstore.js +16 -2
  12. package/dist_ts/classes.cli.d.ts +4 -2
  13. package/dist_ts/classes.cli.js +6 -3
  14. package/dist_ts/classes.controller.d.ts +10 -0
  15. package/dist_ts/classes.controller.js +119 -4
  16. package/dist_ts/classes.controllermanagement.d.ts +14 -4
  17. package/dist_ts/classes.controllermanagement.js +20 -2
  18. package/dist_ts/classes.gatewayclient.d.ts +115 -0
  19. package/dist_ts/classes.gatewayclient.js +336 -0
  20. package/dist_ts/classes.gatewayclientstore.d.ts +97 -0
  21. package/dist_ts/classes.gatewayclientstore.js +261 -0
  22. package/dist_ts/classes.inferencerouter.d.ts +9 -0
  23. package/dist_ts/classes.inferencerouter.js +11 -1
  24. package/dist_ts/classes.inferenceservice.d.ts +9 -0
  25. package/dist_ts/classes.inferenceservice.js +27 -1
  26. package/dist_ts/classes.mcpclient.d.ts +4 -1
  27. package/dist_ts/classes.mcpclient.js +19 -1
  28. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -1
  29. package/dist_ts/classes.mcpcontrollerhost.js +9 -1
  30. package/dist_ts/classes.mcptools.d.ts +3 -3
  31. package/dist_ts/classes.mcptools.js +26 -1
  32. package/dist_ts/classes.mcpvalidation.js +7 -1
  33. package/dist_ts/classes.proxycontrol.d.ts +11 -0
  34. package/dist_ts/classes.proxycontrol.js +7 -1
  35. package/dist_ts/classes.proxycontrolclient.d.ts +17 -0
  36. package/dist_ts/classes.proxycontrolclient.js +35 -1
  37. package/dist_ts/classes.proxydaemon.js +8 -1
  38. package/dist_ts/classes.proxymonitor.d.ts +7 -0
  39. package/dist_ts/classes.proxymonitor.js +13 -1
  40. package/dist_ts/classes.trustedproxysecrets.d.ts +2 -0
  41. package/dist_ts/classes.trustedproxysecrets.js +5 -1
  42. package/dist_ts/functions.controllermanagementsurface.d.ts +4 -0
  43. package/dist_ts/functions.controllermanagementsurface.js +15 -1
  44. package/dist_ts/functions.gatewaycli.d.ts +24 -0
  45. package/dist_ts/functions.gatewaycli.js +395 -0
  46. package/dist_ts/functions.gatewayroute.d.ts +135 -0
  47. package/dist_ts/functions.gatewayroute.js +366 -0
  48. package/dist_ts/functions.inferencecli.js +30 -1
  49. package/dist_ts/functions.inferencecliarguments.d.ts +8 -2
  50. package/dist_ts/functions.inferencecliarguments.js +31 -3
  51. package/dist_ts/functions.proxycapacity.d.ts +50 -0
  52. package/dist_ts/functions.proxycapacity.js +142 -0
  53. package/dist_ts/functions.proxycapacitycli.d.ts +30 -0
  54. package/dist_ts/functions.proxycapacitycli.js +65 -0
  55. package/dist_ts/functions.remotecli.d.ts +30 -3
  56. package/dist_ts/functions.remotecli.js +44 -18
  57. package/dist_ts/interfaces.auth.d.ts +25 -4
  58. package/dist_ts/interfaces.auth.js +7 -1
  59. package/dist_ts/plugins.d.ts +2 -0
  60. package/dist_ts/plugins.js +4 -1
  61. package/dist_ts_authswitch/authority-placement.js +3 -17
  62. package/dist_ts_authswitch/authority-usagelimit.d.ts +29 -0
  63. package/dist_ts_authswitch/authority-usagelimit.js +66 -2
  64. package/dist_ts_authswitch/authority-usagewindows.d.ts +6 -0
  65. package/dist_ts_authswitch/authority-usagewindows.js +15 -1
  66. package/dist_ts_interfaces/gateway.d.ts +151 -0
  67. package/dist_ts_interfaces/gateway.js +66 -0
  68. package/dist_ts_interfaces/index.d.ts +2 -0
  69. package/dist_ts_interfaces/index.js +3 -1
  70. package/dist_ts_interfaces/management.d.ts +4 -4
  71. package/dist_ts_interfaces/management.js +3 -2
  72. package/dist_ts_interfaces/mcprequests.d.ts +14 -2
  73. package/dist_ts_interfaces/mcprequests.js +2 -1
  74. package/dist_ts_interfaces/proxycapacity.d.ts +99 -0
  75. package/dist_ts_interfaces/proxycapacity.js +74 -0
  76. package/package.json +4 -3
  77. package/readme.md +79 -5
  78. package/ts/00_commitinfo_data.ts +1 -1
  79. package/ts/aglapi/aglapisurface.document.ts +324 -0
  80. package/ts/aglapi/interfaces.ts +1 -0
  81. package/ts/classes.authmodels.ts +22 -3
  82. package/ts/classes.authstore.ts +15 -1
  83. package/ts/classes.cli.ts +7 -3
  84. package/ts/classes.controller.ts +134 -3
  85. package/ts/classes.controllermanagement.ts +40 -7
  86. package/ts/classes.gatewayclient.ts +401 -0
  87. package/ts/classes.gatewayclientstore.ts +272 -0
  88. package/ts/classes.inferencerouter.ts +12 -0
  89. package/ts/classes.inferenceservice.ts +27 -0
  90. package/ts/classes.mcpclient.ts +18 -0
  91. package/ts/classes.mcpcontrollerhost.ts +13 -0
  92. package/ts/classes.mcptools.ts +30 -2
  93. package/ts/classes.mcpvalidation.ts +5 -0
  94. package/ts/classes.proxycontrol.ts +16 -0
  95. package/ts/classes.proxycontrolclient.ts +30 -0
  96. package/ts/classes.proxydaemon.ts +8 -0
  97. package/ts/classes.proxymonitor.ts +12 -0
  98. package/ts/classes.trustedproxysecrets.ts +5 -0
  99. package/ts/functions.controllermanagementsurface.ts +15 -0
  100. package/ts/functions.gatewaycli.ts +436 -0
  101. package/ts/functions.gatewayroute.ts +429 -0
  102. package/ts/functions.inferencecli.ts +24 -0
  103. package/ts/functions.inferencecliarguments.ts +30 -4
  104. package/ts/functions.proxycapacity.ts +191 -0
  105. package/ts/functions.proxycapacitycli.ts +104 -0
  106. package/ts/functions.remotecli.ts +56 -20
  107. package/ts/interfaces.auth.ts +28 -4
  108. package/ts/plugins.ts +5 -0
  109. package/ts_authswitch/authority-placement.ts +2 -15
  110. package/ts_authswitch/authority-usagelimit.ts +84 -1
  111. package/ts_authswitch/authority-usagewindows.ts +13 -0
  112. package/ts_interfaces/gateway.ts +242 -0
  113. package/ts_interfaces/index.ts +2 -0
  114. package/ts_interfaces/management.ts +6 -4
  115. package/ts_interfaces/mcprequests.ts +18 -0
  116. package/ts_interfaces/proxycapacity.ts +162 -0
  117. package/ts_web/00_commitinfo_data.ts +1 -1
  118. package/ts_web/classes.browserpresentation.ts +13 -5
  119. package/ts_web/elements.accounts.ts +40 -113
  120. package/ts_web/elements.configurationpane.ts +24 -37
  121. package/ts_web/elements.devices.ts +4 -17
  122. package/ts_web/elements.flexlimitstrip.ts +21 -70
  123. package/ts_web/elements.harnesscontrollerapp.ts +91 -185
@@ -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`;
@@ -147,6 +147,12 @@ export const controllerAuditEventTypes = [
147
147
  'remote.set',
148
148
  'remote.unset',
149
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',
150
156
  // Paired devices (AGL-824): the owner makes a pairing code and revokes a device; a device pairs and authenticates.
151
157
  'device.pairing.begin',
152
158
  'device.pair',
@@ -273,21 +279,39 @@ export interface IControllerAuditRemoteMove {
273
279
  target: IControllerAuditRemoteEndpoint;
274
280
  }
275
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
+
276
296
  /**
277
297
  * 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.
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.
279
300
  */
280
301
  export interface IControllerAuditEventDetails {
281
302
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
282
303
  remoteMove?: IControllerAuditRemoteMove;
304
+ /** `remote.gateway.*` only: the gateway route the command acted on. */
305
+ gateway?: IControllerAuditGateway;
283
306
  [key: string]: unknown;
284
307
  }
285
308
 
286
309
  /** What this release records in an audit event's `details`. */
287
- export interface IRecordAuditEventDetails {
310
+ export type IRecordAuditEventDetails =
288
311
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
289
- remoteMove: IControllerAuditRemoteMove;
290
- }
312
+ | { remoteMove: IControllerAuditRemoteMove }
313
+ /** `remote.gateway.*` only: the gateway route the command acted on. */
314
+ | { gateway: IControllerAuditGateway };
291
315
 
292
316
  /**
293
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
  });