agl 43.6.0 → 43.8.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 (166) hide show
  1. package/changelog.md +27 -0
  2. package/dist_serve/bundle.js +1801 -1783
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/interfaces.d.ts +35 -0
  6. package/dist_ts/aglapi/interfaces.js +9 -1
  7. package/dist_ts/classes.accountsactions.d.ts +3 -1
  8. package/dist_ts/classes.accountsactions.js +17 -1
  9. package/dist_ts/classes.apnsclient.d.ts +97 -0
  10. package/dist_ts/classes.apnsclient.js +363 -0
  11. package/dist_ts/classes.authmodels.js +19 -6
  12. package/dist_ts/classes.authstore.js +15 -2
  13. package/dist_ts/classes.cli.js +8 -1
  14. package/dist_ts/classes.controller.d.ts +33 -6
  15. package/dist_ts/classes.controller.js +254 -12
  16. package/dist_ts/classes.controllerdevices.d.ts +35 -7
  17. package/dist_ts/classes.controllerdevices.js +86 -13
  18. package/dist_ts/classes.controllerpush.d.ts +111 -0
  19. package/dist_ts/classes.controllerpush.js +299 -0
  20. package/dist_ts/classes.fcmclient.d.ts +78 -0
  21. package/dist_ts/classes.fcmclient.js +278 -0
  22. package/dist_ts/classes.inbox.d.ts +10 -2
  23. package/dist_ts/classes.inbox.js +9 -2
  24. package/dist_ts/classes.inferencerouter.d.ts +21 -3
  25. package/dist_ts/classes.inferencerouter.js +40 -17
  26. package/dist_ts/classes.inferenceservice.js +2 -2
  27. package/dist_ts/classes.mcpclient.d.ts +5 -0
  28. package/dist_ts/classes.mcpclient.js +18 -6
  29. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
  30. package/dist_ts/classes.mcpcontrollerhost.js +19 -1
  31. package/dist_ts/classes.mcpvalidation.js +4 -1
  32. package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
  33. package/dist_ts/classes.mcpworkercaller.js +26 -4
  34. package/dist_ts/classes.pushdelivery.d.ts +115 -0
  35. package/dist_ts/classes.pushdelivery.js +311 -0
  36. package/dist_ts/classes.pushhandover.d.ts +46 -0
  37. package/dist_ts/classes.pushhandover.js +131 -0
  38. package/dist_ts/classes.pushregistrations.d.ts +96 -0
  39. package/dist_ts/classes.pushregistrations.js +263 -0
  40. package/dist_ts/classes.pushsettings.d.ts +125 -0
  41. package/dist_ts/classes.pushsettings.js +377 -0
  42. package/dist_ts/classes.workercallers.d.ts +73 -2
  43. package/dist_ts/classes.workercallers.js +354 -43
  44. package/dist_ts/driver/classes.directreports.d.ts +5 -0
  45. package/dist_ts/driver/classes.directreports.js +3 -2
  46. package/dist_ts/fleet/classes.workerlaunches.d.ts +6 -4
  47. package/dist_ts/fleet/classes.workerlaunches.js +10 -9
  48. package/dist_ts/fleet/classes.workers.d.ts +12 -2
  49. package/dist_ts/fleet/classes.workers.js +82 -2
  50. package/dist_ts/functions.deviceapi.d.ts +23 -3
  51. package/dist_ts/functions.deviceapi.js +41 -3
  52. package/dist_ts/functions.inferencecli.js +2 -1
  53. package/dist_ts/functions.pushcli.d.ts +43 -0
  54. package/dist_ts/functions.pushcli.js +201 -0
  55. package/dist_ts/functions.pushcredentials.d.ts +53 -0
  56. package/dist_ts/functions.pushcredentials.js +111 -0
  57. package/dist_ts/functions.pushwire.d.ts +8 -0
  58. package/dist_ts/functions.pushwire.js +83 -0
  59. package/dist_ts/functions.remotecli.d.ts +2 -2
  60. package/dist_ts/functions.remotecli.js +4 -4
  61. package/dist_ts/functions.workercallervalidation.js +3 -2
  62. package/dist_ts/functions.workerprocessproof.d.ts +12 -0
  63. package/dist_ts/functions.workerprocessproof.js +32 -1
  64. package/dist_ts/interfaces.auth.d.ts +27 -3
  65. package/dist_ts/interfaces.auth.js +10 -1
  66. package/dist_ts/interfaces.lifecycle.d.ts +7 -1
  67. package/dist_ts/interfaces.push.d.ts +69 -0
  68. package/dist_ts/interfaces.push.js +25 -0
  69. package/dist_ts/plugins.d.ts +5 -2
  70. package/dist_ts/plugins.js +7 -3
  71. package/dist_ts_authswitch/authority-contract.d.ts +26 -0
  72. package/dist_ts_authswitch/authority-contract.js +1 -1
  73. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  74. package/dist_ts_authswitch/authority-overview.js +10 -4
  75. package/dist_ts_authswitch/authority-placement.d.ts +16 -9
  76. package/dist_ts_authswitch/authority-placement.js +10 -7
  77. package/dist_ts_authswitch/authority-priority.d.ts +20 -0
  78. package/dist_ts_authswitch/authority-priority.js +21 -0
  79. package/dist_ts_authswitch/classes.authoritybroker.d.ts +7 -0
  80. package/dist_ts_authswitch/classes.authoritybroker.js +26 -2
  81. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  82. package/dist_ts_authswitch/classes.authoritycli.js +43 -3
  83. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  84. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  85. package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
  86. package/dist_ts_authswitch/classes.authoritydatabase.d.ts +6 -0
  87. package/dist_ts_authswitch/classes.authoritydatabase.js +13 -2
  88. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  89. package/dist_ts_authswitch/classes.authoritymodels.js +17 -8
  90. package/dist_ts_interfaces/devices.d.ts +178 -2
  91. package/dist_ts_interfaces/devices.js +24 -2
  92. package/dist_ts_interfaces/index.d.ts +1 -0
  93. package/dist_ts_interfaces/index.js +2 -1
  94. package/dist_ts_interfaces/mcprequests.d.ts +3 -2
  95. package/dist_ts_interfaces/mcprequests.js +3 -1
  96. package/dist_ts_interfaces/push.d.ts +166 -0
  97. package/dist_ts_interfaces/push.js +24 -0
  98. package/dist_ts_interfaces/requests.accounts.d.ts +19 -0
  99. package/dist_ts_interfaces/requests.accounts.js +1 -1
  100. package/dist_ts_interfaces/requests.d.ts +2 -2
  101. package/dist_ts_interfaces/requests.js +1 -1
  102. package/dist_ts_interfaces/workercallers.d.ts +43 -3
  103. package/docs/authswitch.md +25 -0
  104. package/package.json +1 -1
  105. package/readme.md +93 -16
  106. package/ts/00_commitinfo_data.ts +1 -1
  107. package/ts/aglapi/interfaces.ts +8 -0
  108. package/ts/classes.accountsactions.ts +25 -0
  109. package/ts/classes.apnsclient.ts +389 -0
  110. package/ts/classes.authmodels.ts +21 -5
  111. package/ts/classes.authstore.ts +14 -1
  112. package/ts/classes.cli.ts +7 -0
  113. package/ts/classes.controller.ts +277 -10
  114. package/ts/classes.controllerdevices.ts +94 -12
  115. package/ts/classes.controllerpush.ts +351 -0
  116. package/ts/classes.fcmclient.ts +292 -0
  117. package/ts/classes.inbox.ts +13 -2
  118. package/ts/classes.inferencerouter.ts +61 -16
  119. package/ts/classes.inferenceservice.ts +1 -1
  120. package/ts/classes.mcpclient.ts +20 -5
  121. package/ts/classes.mcpcontrollerhost.ts +20 -0
  122. package/ts/classes.mcpvalidation.ts +2 -0
  123. package/ts/classes.mcpworkercaller.ts +24 -2
  124. package/ts/classes.pushdelivery.ts +378 -0
  125. package/ts/classes.pushhandover.ts +98 -0
  126. package/ts/classes.pushregistrations.ts +244 -0
  127. package/ts/classes.pushsettings.ts +428 -0
  128. package/ts/classes.workercallers.ts +329 -37
  129. package/ts/driver/classes.directreports.ts +7 -1
  130. package/ts/fleet/classes.workerlaunches.ts +9 -7
  131. package/ts/fleet/classes.workers.ts +65 -2
  132. package/ts/functions.deviceapi.ts +52 -2
  133. package/ts/functions.inferencecli.ts +1 -0
  134. package/ts/functions.pushcli.ts +212 -0
  135. package/ts/functions.pushcredentials.ts +129 -0
  136. package/ts/functions.pushwire.ts +106 -0
  137. package/ts/functions.remotecli.ts +3 -2
  138. package/ts/functions.workercallervalidation.ts +2 -1
  139. package/ts/functions.workerprocessproof.ts +34 -0
  140. package/ts/interfaces.auth.ts +27 -3
  141. package/ts/interfaces.lifecycle.ts +7 -1
  142. package/ts/interfaces.push.ts +78 -0
  143. package/ts/plugins.ts +6 -1
  144. package/ts_authswitch/authority-contract.ts +21 -0
  145. package/ts_authswitch/authority-overview.ts +19 -5
  146. package/ts_authswitch/authority-placement.ts +18 -10
  147. package/ts_authswitch/authority-priority.ts +25 -0
  148. package/ts_authswitch/classes.authoritybroker.ts +26 -1
  149. package/ts_authswitch/classes.authoritycli.ts +48 -2
  150. package/ts_authswitch/classes.authorityclient.ts +14 -4
  151. package/ts_authswitch/classes.authoritydaemon.ts +8 -1
  152. package/ts_authswitch/classes.authoritydatabase.ts +11 -1
  153. package/ts_authswitch/classes.authoritymodels.ts +17 -6
  154. package/ts_authswitch/readme.md +1 -1
  155. package/ts_interfaces/devices.schema.json +327 -0
  156. package/ts_interfaces/devices.ts +206 -1
  157. package/ts_interfaces/index.ts +1 -0
  158. package/ts_interfaces/mcprequests.ts +3 -0
  159. package/ts_interfaces/push.ts +162 -0
  160. package/ts_interfaces/requests.accounts.ts +17 -0
  161. package/ts_interfaces/requests.ts +2 -0
  162. package/ts_interfaces/workercallers.ts +34 -2
  163. package/ts_web/00_commitinfo_data.ts +1 -1
  164. package/ts_web/accounts.plugins.ts +4 -2
  165. package/ts_web/classes.accountsreadmodel.ts +36 -2
  166. package/ts_web/elements.accounts.ts +48 -0
@@ -95,12 +95,13 @@ const maximumSecretInputBytes = 4_096;
95
95
 
96
96
  /**
97
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.
98
+ * returns it trimmed; nothing of it is echoed or kept past the read. `maximumBytesArg` bounds it (4 KiB by default).
99
99
  */
100
100
  export const readStandardInputSecret = async (
101
101
  inputArg: NodeJS.ReadableStream & { isTTY?: boolean },
102
102
  refusalArg: string,
103
103
  whatArg: string,
104
+ maximumBytesArg = maximumSecretInputBytes,
104
105
  ): Promise<string> => {
105
106
  if (inputArg.isTTY) throw new Error(refusalArg);
106
107
  const chunks: Buffer[] = [];
@@ -110,7 +111,7 @@ export const readStandardInputSecret = async (
110
111
  const buffer = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk as Uint8Array);
111
112
  chunks.push(buffer);
112
113
  bytes += buffer.byteLength;
113
- if (bytes > maximumSecretInputBytes) throw new Error(`The standard input is longer than ${whatArg}.`);
114
+ if (bytes > maximumBytesArg) throw new Error(`The standard input is longer than ${whatArg}.`);
114
115
  }
115
116
  return Buffer.concat(chunks).toString('utf8').trim();
116
117
  } finally {
@@ -9,7 +9,8 @@ export const assertWorkerCallerEnrollment = (valueArg: unknown): TWorkerCallerEn
9
9
  throw new Error('Invalid worker enrollment request.');
10
10
  }
11
11
  const keys = Object.hasOwn(valueArg, 'launchId') ? ['bridgePid', 'launchId', 'launchGeneration']
12
- : Object.hasOwn(valueArg, 'challenge') ? ['bridgePid', 'challenge', 'nativeThreadId'] : ['bridgePid', 'nativeThreadId'];
12
+ : Object.hasOwn(valueArg, 'challenge') ? ['bridgePid', 'challenge', 'nativeThreadId']
13
+ : Object.hasOwn(valueArg, 'nativeThreadId') ? ['bridgePid', 'nativeThreadId'] : ['bridgePid'];
13
14
  if (Object.keys(valueArg).length !== keys.length || keys.some(key => !Object.hasOwn(valueArg, key))) {
14
15
  throw new Error('Invalid worker enrollment request.');
15
16
  }
@@ -3,6 +3,8 @@ import type { IConfigurationMcpStdioServer, IFleetClaudeProcess } from '../ts_in
3
3
  import { resolveControllerTerminalAgentExecutable } from './functions.terminalagents.js';
4
4
 
5
5
  export class WorkerCallerProofError extends Error {}
6
+ /** A proof refused because the process changed while it was read: unlike the other refusals, it may pass at the next read. */
7
+ export class WorkerProcessChangedError extends WorkerCallerProofError {}
6
8
 
7
9
  export const isWorkerCallerProofRefusal = (errorArg: unknown): boolean => (
8
10
  errorArg instanceof WorkerCallerProofError
@@ -213,6 +215,38 @@ export const verifyClaudeWorkerProcess = async (
213
215
  return snapshot;
214
216
  };
215
217
 
218
+ /**
219
+ * The process `processArg` (PID and start), proved to run an installed Claude Code release: its executable is a
220
+ * regular file of the controller's user in the directory of `releaseArg`, the release `claude` resolves to now, and is
221
+ * the very file the process runs. Claude Code installs every release as a file of its own there (`versions/<release>`)
222
+ * and moves its launcher to the newest, while a running job keeps the release it started on; a release file that was
223
+ * removed or replaced since the process started is refused. A local read of the process and two file stats: the
224
+ * controller proves it before it asks the fleet's inventory which job the process runs.
225
+ */
226
+ export const verifyClaudeReleaseProcess = async (
227
+ processArg: Pick<IFleetClaudeProcess, 'pid' | 'startTicks'>,
228
+ releaseArg: string,
229
+ ): Promise<IWorkerProcessSnapshot> => {
230
+ if (!/^\d+$/u.test(processArg.startTicks) || !plugins.path.isAbsolute(releaseArg)) {
231
+ throw new WorkerCallerProofError('Invalid Claude launch observation.');
232
+ }
233
+ const snapshot = await readWorkerProcessSnapshot(processArg.pid);
234
+ if (snapshot.startTicks !== processArg.startTicks || !plugins.path.isAbsolute(snapshot.executable)
235
+ || plugins.path.dirname(snapshot.executable) !== plugins.path.dirname(releaseArg)) {
236
+ throw new WorkerCallerProofError('The Claude process does not run an installed Claude Code release.');
237
+ }
238
+ const [installed, running] = await Promise.all([plugins.fs.promises.lstat(snapshot.executable, { bigint: true }),
239
+ plugins.fs.promises.stat(`/proc/${processArg.pid}/exe`, { bigint: true })]);
240
+ if (!installed.isFile() || installed.uid !== BigInt(process.getuid?.() ?? -1)
241
+ || installed.dev !== running.dev || installed.ino !== running.ino) {
242
+ throw new WorkerCallerProofError('The Claude process does not run an installed Claude Code release.');
243
+ }
244
+ if (!workerSnapshotsEqual(snapshot, await readWorkerProcessSnapshot(processArg.pid))) {
245
+ throw new WorkerProcessChangedError('The Claude launch observation no longer matches its process.');
246
+ }
247
+ return snapshot;
248
+ };
249
+
216
250
  export const readWorkerUnixSocketOwner = async (socketPathArg: string): Promise<IWorkerProcessSnapshot> => {
217
251
  const table = await plugins.fs.promises.readFile('/proc/net/unix', 'utf8');
218
252
  const rows = table.split('\n').slice(1).map(line => line.trim().split(/\s+/u))
@@ -85,6 +85,7 @@ export const controllerAuditEventTypes = [
85
85
  'accounts.spendlimit',
86
86
  'accounts.claudecode',
87
87
  'accounts.renewal',
88
+ 'accounts.priority',
88
89
  'accounts.remove',
89
90
  'accounts.add',
90
91
  'accounts.reauth',
@@ -166,6 +167,14 @@ export const controllerAuditEventTypes = [
166
167
  'device.pair',
167
168
  'device.auth',
168
169
  'device.revoke',
170
+ // The host's push settings (AGL-1639): `agl push` against the running controller, as the local owner; what a change
171
+ // sets rides in `details.push`, never a key.
172
+ 'push.apns.set',
173
+ 'push.apns.unset',
174
+ 'push.fcm.set',
175
+ 'push.fcm.unset',
176
+ 'push.previews',
177
+ 'push.test',
169
178
  ] as const;
170
179
  export type TControllerAuditEventType = (typeof controllerAuditEventTypes)[number];
171
180
  export type TControllerAuditOutcome = 'attempted' | 'succeeded' | 'denied' | 'failed';
@@ -301,16 +310,29 @@ export interface IControllerAuditGateway {
301
310
  rotate?: boolean;
302
311
  }
303
312
 
313
+ /**
314
+ * What a `push.*` event records of the change (AGL-1639), never a key or a token: `push.apns.set` the key id, team id
315
+ * and topic, `push.fcm.set` the Firebase project and the service account's address, `push.previews` the setting,
316
+ * `push.test` how many devices it went to and how many got it.
317
+ */
318
+ export type IControllerAuditPush =
319
+ | { keyId: string; teamId: string; topic: string }
320
+ | { projectId: string; clientEmail: string }
321
+ | { previews: boolean }
322
+ | { devices: number; delivered: number };
323
+
304
324
  /**
305
325
  * What an audit event records beyond its envelope (bounded plain JSON). This release records `remoteMove` on
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.
326
+ * `remote.set` and `remote.unset`, `gateway` on `remote.gateway.*` and `push` on `push.apns.set`, `push.fcm.set` and
327
+ * `push.previews`; any other key is a later release's, kept and pruned as it wrote it.
308
328
  */
309
329
  export interface IControllerAuditEventDetails {
310
330
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
311
331
  remoteMove?: IControllerAuditRemoteMove;
312
332
  /** `remote.gateway.*` only: the gateway route the command acted on. */
313
333
  gateway?: IControllerAuditGateway;
334
+ /** `push.apns.set`, `push.fcm.set`, `push.previews` and `push.test` only: what the change set or sent. */
335
+ push?: IControllerAuditPush;
314
336
  [key: string]: unknown;
315
337
  }
316
338
 
@@ -319,7 +341,9 @@ export type IRecordAuditEventDetails =
319
341
  /** `remote.set` and `remote.unset` only: where the move goes from and to. */
320
342
  | { remoteMove: IControllerAuditRemoteMove }
321
343
  /** `remote.gateway.*` only: the gateway route the command acted on. */
322
- | { gateway: IControllerAuditGateway };
344
+ | { gateway: IControllerAuditGateway }
345
+ /** `push.apns.set`, `push.fcm.set`, `push.previews` and `push.test` only: what the change set or sent. */
346
+ | { push: IControllerAuditPush };
323
347
 
324
348
  /**
325
349
  * A stored audit event. The audit log is shared with later releases, so a stored `type` is any audit type, also one
@@ -3,6 +3,7 @@ import type { IAuthoritySocketPaths } from './classes.authorityclient.js';
3
3
  import type { IControllerRuntimeOverrides } from './interfaces.config.js';
4
4
  import type * as plugins from './plugins.js';
5
5
  import type { ITpmSecretCodec } from './classes.tpmsecretcodec.js';
6
+ import type { IPushEndpoints } from './interfaces.push.js';
6
7
 
7
8
  export interface IControllerStartOptions {
8
9
  processMode: TControllerProcessMode;
@@ -25,8 +26,13 @@ export interface IControllerStartOptions {
25
26
  codexAppServerScope?: plugins.authswitch.ICodexAppServerScopeOptions;
26
27
  /** Operator-provided first-start setup code; a random code is minted when absent. */
27
28
  setupCode?: string;
28
- /** Seals the trusted-proxy secret in TLS-proxy mode; TPM2 (`TpmSecretCodec`) when absent. For tests. */
29
+ /**
30
+ * Seals the trusted-proxy secret in TLS-proxy mode, the gateway credential and the push keys; TPM2 (`TpmSecretCodec`)
31
+ * when absent. For tests.
32
+ */
29
33
  trustedProxySecretCodec?: ITpmSecretCodec;
34
+ /** Where the push senders connect; Apple's and Google's hosts when absent. For tests: production never sets it. */
35
+ pushEndpoints?: IPushEndpoints;
30
36
  /** Private upgrade transaction token received over parent IPC. */
31
37
  upgradeToken?: string;
32
38
  upgradeGlobalRoot?: string;
@@ -0,0 +1,78 @@
1
+ import type { TDevicePushData, TDevicePushEnvironment, TDevicePushFailureReason } from '../ts_interfaces/devices.js';
2
+
3
+ /**
4
+ * What the APNs and FCM senders share (AGL-1639): the hosts they talk to, pinned here and nowhere configurable, and
5
+ * what one send came to.
6
+ */
7
+
8
+ /** Apple's push service: one host per environment of a device token. */
9
+ export const apnsHosts = { production: 'api.push.apple.com', sandbox: 'api.sandbox.push.apple.com' } as const satisfies Record<TDevicePushEnvironment, string>;
10
+ export type TApnsHost = (typeof apnsHosts)[TDevicePushEnvironment];
11
+
12
+ /** Google's token endpoint and Firebase Cloud Messaging; a service account file's `token_uri` is never asked. */
13
+ export const googleHosts = { token: 'oauth2.googleapis.com', fcm: 'fcm.googleapis.com' } as const;
14
+ export type TGoogleHost = (typeof googleHosts)[keyof typeof googleHosts];
15
+
16
+ /** Where an HTTPS request to a pinned Google host goes. */
17
+ export interface IPushHttpEndpoint {
18
+ protocol: 'https:' | 'http:';
19
+ hostname: string;
20
+ port: number;
21
+ }
22
+
23
+ /**
24
+ * Where the senders' connections go. Production code never sets it: the senders connect to the pinned hosts on 443
25
+ * with TLS. A test hands its own fake servers' addresses here, and the requests still name the pinned hosts.
26
+ */
27
+ export interface IPushEndpoints {
28
+ /** The authority URL an HTTP/2 session to an APNs host connects to. */
29
+ apns(hostArg: TApnsHost): string;
30
+ /** Where a request to a Google host connects. */
31
+ google(hostArg: TGoogleHost): IPushHttpEndpoint;
32
+ }
33
+
34
+ export const pushServiceEndpoints: IPushEndpoints = {
35
+ apns: (hostArg) => `https://${hostArg}:443`,
36
+ google: (hostArg) => ({ protocol: 'https:', hostname: hostArg, port: 443 }),
37
+ };
38
+
39
+ /** A device's registration as a sender needs it: the push token, and for APNs the token's environment. */
40
+ export interface IPushSendTarget {
41
+ token: string;
42
+ environment?: TDevicePushEnvironment;
43
+ }
44
+
45
+ /**
46
+ * What one send came to: `delivered`; `unregistered`, the push service says the token is gone (the registration is
47
+ * deleted if it still holds that token); or why it did not go out (`TDevicePushFailureReason`), with the push service's
48
+ * own code when it named one (never its message) and how long it asked the host to wait. `clockSkewMs` is set when the
49
+ * refusal came while the service's clock and the host's were apart (`googleTokenClockSkewLimitMs`): the service's `Date`
50
+ * minus the host's clock, so a positive value is a host clock behind.
51
+ */
52
+ export type TPushSendResult =
53
+ | { outcome: 'delivered' }
54
+ | { outcome: 'unregistered'; vendorReason?: string }
55
+ | { outcome: TDevicePushFailureReason; vendorReason?: string; retryAfterMs?: number; clockSkewMs?: number };
56
+
57
+ /** One send to a push service, for the delivery service. */
58
+ export interface IPushSender {
59
+ send(targetArg: IPushSendTarget, payloadArg: TDevicePushData, expiresAtArg: number, signalArg: AbortSignal): Promise<TPushSendResult>;
60
+ /** Ends every connection; a send still running ends as `unreachable`. */
61
+ close(): Promise<void>;
62
+ }
63
+
64
+ /** How long one request to a push service may take, from connecting to the last byte of its answer. */
65
+ export const pushRequestTimeoutMs = 15_000;
66
+
67
+ /** A push service's code as the host keeps it: an identifier of letters, digits and `_`, never its message. */
68
+ export const isPushVendorReason = (valueArg: unknown): valueArg is string => (
69
+ typeof valueArg === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(valueArg)
70
+ );
71
+
72
+ /** A `Retry-After` header in milliseconds: seconds, or an HTTP date; at most a day. */
73
+ export const retryAfterMs = (valueArg: string | string[] | undefined, nowArg: number): number | undefined => {
74
+ const value = Array.isArray(valueArg) ? valueArg[0] : valueArg;
75
+ if (value === undefined) return undefined;
76
+ const seconds = /^\d{1,6}$/u.test(value.trim()) ? Number(value.trim()) * 1000 : Date.parse(value) - nowArg;
77
+ return Number.isFinite(seconds) && seconds >= 0 ? Math.min(seconds, 24 * 60 * 60 * 1000) : undefined;
78
+ };
package/ts/plugins.ts CHANGED
@@ -5,6 +5,8 @@ import * as nodeConsole from 'node:console';
5
5
  import * as crypto from 'node:crypto';
6
6
  import * as fs from 'node:fs';
7
7
  import * as http from 'node:http';
8
+ import * as http2 from 'node:http2';
9
+ import * as https from 'node:https';
8
10
  import { createRequire } from 'node:module';
9
11
  import * as net from 'node:net';
10
12
  import * as os from 'node:os';
@@ -14,7 +16,7 @@ import * as url from 'node:url';
14
16
  import * as util from 'node:util';
15
17
  import * as timersPromises from 'node:timers/promises';
16
18
 
17
- export { asyncHooks, childProcess, nodeConsole, createRequire, crypto, fs, http, net, os, path, stream, url, util, timersPromises };
19
+ export { asyncHooks, childProcess, nodeConsole, createRequire, crypto, fs, http, http2, https, net, os, path, stream, url, util, timersPromises };
18
20
 
19
21
  // foss.global modules
20
22
  import * as docker from '@apiclient.xyz/docker';
@@ -68,6 +70,8 @@ import * as authswitchSpend from '../ts_authswitch/authority-spend.js';
68
70
  import * as authswitchSubscription from '../ts_authswitch/authority-subscription.js';
69
71
  // A Claude sign-in's monthly renewal as its owner set it: the rule, the next renewal, which placement and the status share.
70
72
  import * as authswitchRenewal from '../ts_authswitch/authority-renewal.js';
73
+ // An account's priority as its owner set it: whether it holds now, the one rule placement and every view judge it by.
74
+ import * as authswitchPriority from '../ts_authswitch/authority-priority.js';
71
75
  // The login an account's usage is read with (`authSwitchUsageLogin`), the rule `authswitch list` and a device's API key
72
76
  // counts share. The package root already loads this module through its CLI, so the value import adds none.
73
77
  import * as authswitchOverview from '../ts_authswitch/authority-overview.js';
@@ -93,6 +97,7 @@ export {
93
97
  authswitchSpend,
94
98
  authswitchSubscription,
95
99
  authswitchRenewal,
100
+ authswitchPriority,
96
101
  authswitchOverview,
97
102
  flexharness,
98
103
  browserRuntime,
@@ -279,6 +279,15 @@ export interface IAuthSwitchAccount {
279
279
  * lapse date ignores it. Whether the windows reset at a renewal is not known. See `authority-placement.ts`.
280
280
  */
281
281
  renewsAt: string | null;
282
+ /**
283
+ * When the owner's priority on the account ends (AGL-1809), ISO 8601 UTC, 24 hours after it was set
284
+ * (`authSwitchPriorityMs` of `authority-priority.ts`); `null` when the owner set none or turned it off. Until then, AGL's
285
+ * inference proxy places a new session on the account before any account of its pool without one, as long as it takes
286
+ * the request; several accounts can hold it at once. It ends by itself: one whose moment passed is none, so a reader
287
+ * judges it against its own clock (`authSwitchPriorityActive`) rather than by whether it is set. Any account can hold
288
+ * one.
289
+ */
290
+ priorityUntil: string | null;
282
291
  /**
283
292
  * An API key account's spend limit per calendar month in UTC, in micro-dollars (`isAuthSwitchSpendLimitMicroUsd`);
284
293
  * `null` for none, and always for an account on a sign-in. The limit counts what AGL's inference proxy relayed on the
@@ -1544,6 +1553,18 @@ export interface IReq_AuthSwitchSetAccountRenewal extends ITypedRequest {
1544
1553
  response: { account: IAuthSwitchAccount };
1545
1554
  }
1546
1555
 
1556
+ /**
1557
+ * Gives an account the owner's priority for 24 hours from now (`priority: true`; again on an account that holds it starts
1558
+ * the 24 hours again), or ends it (`false`): see `IAuthSwitchAccount.priorityUntil`. The end is the authority's clock
1559
+ * plus `authSwitchPriorityMs`, never the caller's. `expectedRevision` is the revision the caller read, so a change of an
1560
+ * account that changed meanwhile is refused as `account_changed`.
1561
+ */
1562
+ export interface IReq_AuthSwitchSetAccountPriority extends ITypedRequest {
1563
+ method: 'authswitch.authority.priority';
1564
+ request: { accountId: string; expectedRevision: number; priority: boolean };
1565
+ response: { account: IAuthSwitchAccount };
1566
+ }
1567
+
1547
1568
  /**
1548
1569
  * One binding by the id `bind` returned, credential-free, or `null` when this authority holds no binding by
1549
1570
  * that id. A backend checks that its binding still stands without reading the whole snapshot.
@@ -12,6 +12,7 @@ import { authSwitchUsageLimit, authSwitchUsageLimitText, type IAuthSwitchUsageLi
12
12
  type TAuthSwitchLimitState } from './authority-usagelimit.js';
13
13
  import { authSwitchPlacement, type IAuthSwitchPlacement, type TAuthSwitchAccountLifecycle } from './authority-placement.js';
14
14
  import { authSwitchRenewal, type IAuthSwitchRenewal } from './authority-renewal.js';
15
+ import { authSwitchPriorityUntil } from './authority-priority.js';
15
16
  import { authSwitchSubscriptionFacts, type IAuthSwitchSubscriptionFact } from './authority-subscription.js';
16
17
  import type { IAuthSwitchPaymentProblem } from './classes.authorityusage.js';
17
18
  import { plainText } from './formatting.js';
@@ -60,6 +61,12 @@ export interface IAuthSwitchAccountOverview {
60
61
  * without one. Placement ignores it while the account has a lapse date.
61
62
  */
62
63
  renewal: IAuthSwitchRenewal | null;
64
+ /**
65
+ * When the owner's priority on the account ends, while it holds at the list's time (`IAuthSwitchAccount.priorityUntil`,
66
+ * AGL-1809); null without one or once it ended. Until then the AGL proxy places new sessions on it before any account of
67
+ * its pool without one, as long as it takes them.
68
+ */
69
+ priorityUntil: string | null;
63
70
  /**
64
71
  * How the AGL proxy treats the account for a new session, by the rule of `authority-placement.ts`: its score in
65
72
  * percent per hour (null without a counted window) and whether it is a last resort or never placed on.
@@ -102,6 +109,8 @@ export interface IAuthSwitchLimitRow {
102
109
  lifecycle: TAuthSwitchAccountLifecycle;
103
110
  /** The account's next monthly renewal as its owner set it, or null without one (`IAuthSwitchAccountOverview.renewal`). */
104
111
  renewal: IAuthSwitchRenewal | null;
112
+ /** When the owner's priority on the account ends while it holds, or null (`IAuthSwitchAccountOverview.priorityUntil`). */
113
+ priorityUntil: string | null;
105
114
  /** The account's placement score in percent per hour (`IAuthSwitchPlacement.score`), on each of its rows. */
106
115
  placementScore: number | null;
107
116
  placementEligibility: IAuthSwitchPlacement['eligibility'];
@@ -177,6 +186,7 @@ export const readAuthSwitchAccountOverview = async (snapshotArg: IAuthSwitchSnap
177
186
  lifecycle: authSwitchPlacement(null, accountArg.maxUsagePercent, accountArg.lapsesAt, accountArg.renewsAt, nowArg,
178
187
  accountArg.reserveLiftUntil).lifecycle,
179
188
  renewal: authSwitchRenewal(accountArg.renewsAt, nowArg),
189
+ priorityUntil: authSwitchPriorityUntil(accountArg.priorityUntil, nowArg),
180
190
  };
181
191
  const placement = (readingArg: IAuthSwitchUsageSnapshot['reading']): IAuthSwitchPlacement =>
182
192
  authSwitchPlacement(readingArg, accountArg.maxUsagePercent, accountArg.lapsesAt, accountArg.renewsAt, nowArg,
@@ -232,7 +242,7 @@ export const authSwitchLimitList = (overviewArg: IAuthSwitchAccountOverviewList)
232
242
  plan: accountArg.plan, usageState: accountArg.usage?.state ?? null, problem: accountArg.problem,
233
243
  maxUsagePercent: accountArg.maxUsagePercent, accountState: accountArg.limit?.state ?? null,
234
244
  lapsesAt: accountArg.lapsesAt, lifecycle: accountArg.lifecycle, renewal: accountArg.renewal,
235
- placementScore: accountArg.placement.score,
245
+ priorityUntil: accountArg.priorityUntil, placementScore: accountArg.placement.score,
236
246
  placementEligibility: accountArg.placement.eligibility };
237
247
  if (accountArg.windows.length === 0) {
238
248
  return [{ ...base, limit: null, windowSeconds: null, usedPercent: null, estimatedUsedPercent: null, resetAt: null,
@@ -308,13 +318,16 @@ const limitLines = (maxUsagePercentArg: number | null, limitArg: IAuthSwitchUsag
308
318
 
309
319
  /**
310
320
  * The lifecycle and placement of an account as lines of its cell: nothing for an active account with its score, a
311
- * canceled one with its lapse, a lapsed one as never placed on; and the renewal its owner set, unless it lapsed.
321
+ * canceled one with its lapse, a lapsed one as never placed on; and the priority and renewal its owner set, unless it
322
+ * lapsed. The priority's end is in local time: `priority until 14:05 (set by the owner)`, with its date on another day.
312
323
  */
313
- const placementLines = (accountArg: Pick<IAuthSwitchLimitRow, 'lifecycle' | 'lapsesAt' | 'renewal' | 'placementScore'
314
- | 'placementEligibility'>, nowArg: number): string[] => [
324
+ const placementLines = (accountArg: Pick<IAuthSwitchLimitRow, 'lifecycle' | 'lapsesAt' | 'renewal' | 'priorityUntil'
325
+ | 'placementScore' | 'placementEligibility'>, nowArg: number): string[] => [
315
326
  ...accountArg.lifecycle === 'lapsed' ? ['lapsed · never placed on']
316
327
  : accountArg.lifecycle === 'canceled' && accountArg.lapsesAt !== null
317
328
  ? [`canceled · lapses in ${compactUntil(accountArg.lapsesAt, nowArg)}`] : [],
329
+ ...accountArg.lifecycle === 'lapsed' || accountArg.priorityUntil === null ? []
330
+ : [`priority until ${asOfTime(accountArg.priorityUntil, nowArg)} (set by the owner)`],
318
331
  ...accountArg.lifecycle === 'lapsed' || accountArg.renewal === null ? []
319
332
  : [renewalLine(accountArg.renewal, accountArg.lifecycle, nowArg)],
320
333
  ...accountArg.lifecycle === 'lapsed' ? []
@@ -344,7 +357,8 @@ const accountCell = (accountArg: IAuthSwitchAccountOverview, nowArg: number): st
344
357
  ...accountArg.paymentProblem === null ? [] : [`payment problem since ${asOfTime(accountArg.paymentProblem.at, nowArg)}`],
345
358
  ...limitLines(accountArg.maxUsagePercent, accountArg.limit, nowArg),
346
359
  ...placementLines({ lifecycle: accountArg.lifecycle, lapsesAt: accountArg.lapsesAt, renewal: accountArg.renewal,
347
- placementScore: accountArg.placement.score, placementEligibility: accountArg.placement.eligibility }, nowArg),
360
+ priorityUntil: accountArg.priorityUntil, placementScore: accountArg.placement.score,
361
+ placementEligibility: accountArg.placement.eligibility }, nowArg),
348
362
  ...accountArg.loginHealth === null ? ['no login']
349
363
  : accountArg.loginHealth === 'ready' ? []
350
364
  : [`login ${accountArg.loginHealth}`,
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Where a new session goes: an account's lifecycle against its lapse date, and how much of its usage it can spend per
3
- * hour before that usage resets, the account lapses or it renews. The inference proxy places new sessions by it, and the
4
- * authswitch command line and `agl proxy status` show it; an existing session keeps its account for the prompt cache and
5
- * is never placed again by it.
3
+ * hour before that usage resets, the account lapses or it renews, after its owner's priority. The inference proxy places
4
+ * new sessions by it, and the authswitch command line and `agl proxy status` show it; an existing session keeps its
5
+ * account for the prompt cache and is never placed again by it.
6
6
  *
7
7
  * Besides types, the module imports only the limit rule of `authority-usagelimit.ts`, the window reader it uses, the
8
8
  * spend month of `authority-spend.ts` and the renewal of `authority-renewal.ts`, whose own imports carry nothing to a
@@ -86,25 +86,33 @@ export const authSwitchPlacement = (readingArg: TAuthSwitchUsageReading | null,
86
86
  return { lifecycle, eligibility, score: scores.length ? Math.min(...scores) : null };
87
87
  };
88
88
 
89
- /** An account as placement ranks it: its score, whether it is a last resort, and its headroom below its threshold. */
89
+ /**
90
+ * An account as placement ranks it: whether its owner's priority holds now (`authSwitchPriorityActive` of
91
+ * `authority-priority.ts`, judged at the moment of placing), its score, whether it is a last resort, and its headroom
92
+ * below its threshold.
93
+ */
90
94
  export interface IAuthSwitchPlacementRank {
91
95
  id: string;
96
+ priority: boolean;
92
97
  score: number | null;
93
98
  lastResort: boolean;
94
99
  headroom: number;
95
100
  }
96
101
 
97
102
  /**
98
- * The order a new session is placed in: an account that lapses within `lapseHorizonMs` only after every other one;
99
- * then by the account's score shared among the requests it serves now -- `score / (1 + in flight)`, so new sessions
100
- * spread over the accounts in proportion to what each can spend per hour, and usage that resets, lapses or meets a
101
- * renewal soon is spent first -- then by headroom and id. An account without a counted window comes after every scored
102
- * one, the least busy of them first.
103
+ * The order a new session is placed in: an account with its owner's priority (AGL-1809) before every account without
104
+ * one, then by the rest of the order among each of the two. An account that lapses within `lapseHorizonMs` only after
105
+ * every other one; then by the account's score shared among the requests it serves now -- `score / (1 + in flight)`, so
106
+ * new sessions spread over the accounts in proportion to what each can spend per hour, and usage that resets, lapses or
107
+ * meets a renewal soon is spent first -- then by headroom and id. An account without a counted window comes after every
108
+ * scored one, the least busy of them first. The order ranks only accounts that take the request: one at its limit or
109
+ * reserve, resting after a 429, lapsed or without the model is never ranked, whatever its priority.
103
110
  */
104
111
  export const authSwitchPlacementOrder = (inFlightArg: (accountIdArg: string) => number) => (
105
112
  left: IAuthSwitchPlacementRank,
106
113
  right: IAuthSwitchPlacementRank,
107
- ): number => Number(left.lastResort) - Number(right.lastResort)
114
+ ): number => Number(right.priority) - Number(left.priority)
115
+ || Number(left.lastResort) - Number(right.lastResort)
108
116
  || Number(left.score === null) - Number(right.score === null)
109
117
  || (left.score !== null && right.score !== null
110
118
  ? right.score / (1 + inFlightArg(right.id)) - left.score / (1 + inFlightArg(left.id))
@@ -0,0 +1,25 @@
1
+ /**
2
+ * An account's priority (AGL-1809), as its owner sets it: for 24 hours from when it was set, or until the owner turns it
3
+ * off, AGL's inference proxy places a new session on a priority account of its pool before any other account, as long as
4
+ * one takes the request (`authSwitchPlacementOrder`). Several accounts can hold it at once; among them the placement
5
+ * order decides as it always does. A session already running stays on its account.
6
+ *
7
+ * The account holds the moment its priority ends (`IAuthSwitchAccount.priorityUntil`), and every reader judges it against
8
+ * its own clock, so it ends by itself with nothing running at its end: one that ended reads as none.
9
+ *
10
+ * The module imports nothing, so it bundles for a browser as it is.
11
+ */
12
+
13
+ /** How long a priority holds once its owner sets it: 24 hours. Setting it again starts the 24 hours again. */
14
+ export const authSwitchPriorityMs = 86_400_000;
15
+
16
+ /**
17
+ * Whether an account's priority holds at `nowArg` (epoch milliseconds): strictly before the moment it ends
18
+ * (`priorityUntilArg`, `IAuthSwitchAccount.priorityUntil`). One that ended is none.
19
+ */
20
+ export const authSwitchPriorityActive = (priorityUntilArg: string | null | undefined, nowArg: number): boolean =>
21
+ typeof priorityUntilArg === 'string' && Date.parse(priorityUntilArg) > nowArg;
22
+
23
+ /** When an account's priority ends while it holds at `nowArg`, ISO 8601 UTC as stored; `null` without one or once it ended. */
24
+ export const authSwitchPriorityUntil = (priorityUntilArg: string | null, nowArg: number): string | null =>
25
+ authSwitchPriorityActive(priorityUntilArg, nowArg) ? priorityUntilArg : null;
@@ -11,6 +11,7 @@ import { authSwitchApiKeyOtherProvider, authSwitchApiKeyProviderNames, authSwitc
11
11
  type TAuthSwitchApiKeyVerdict, type TAuthSwitchApiKeyVerifier } from './authority-apikeys.js';
12
12
  import { isAuthSwitchSpendLimitMicroUsd } from './authority-spend.js';
13
13
  import { isAuthSwitchRenewsAt } from './authority-renewal.js';
14
+ import { authSwitchPriorityMs } from './authority-priority.js';
14
15
  import { AuthSwitchAuthorityDatabase, authorityBindPurpose, authSwitchBindPurposes, type TAuthSwitchBindPurpose,
15
16
  type TStoredNativeHome } from './classes.authoritydatabase.js';
16
17
  import { authorityApiKeyProvider, type IStoredAuthorityAccount, type IStoredAuthorityBinding,
@@ -157,7 +158,8 @@ const notOnApiKey = 'An API key account has no usage windows to keep a reserve o
157
158
  const publicAccount = (account: IStoredAuthorityAccount): IAuthSwitchAccount => ({
158
159
  id: account.id, providerId: account.providerId, label: account.label, email: account.email,
159
160
  plan: account.plan, organizationId: account.workspaceId, maxUsagePercent: account.maxUsagePercent, reserveLiftUntil: account.reserveLiftUntil,
160
- lapsesAt: account.lapsesAt, renewsAt: account.renewsAt ?? null, spendLimitMicroUsd: account.spendLimitMicroUsd,
161
+ lapsesAt: account.lapsesAt, renewsAt: account.renewsAt ?? null, priorityUntil: account.priorityUntil ?? null,
162
+ spendLimitMicroUsd: account.spendLimitMicroUsd,
161
163
  keyHint: account.keyHint, claudeCode: account.claudeCode,
162
164
  removed: account.removed, revision: account.revision, statusObservedAt: account.statusObservedAt,
163
165
  });
@@ -974,6 +976,29 @@ export class AuthSwitchAuthorityBroker {
974
976
  return publicAccount(updated.account);
975
977
  }
976
978
 
979
+ /**
980
+ * Gives an account the owner's priority until 24 hours from now on the authority's clock (`authSwitchPriorityMs`), or
981
+ * ends it, as `setAccountRenewal` sets a renewal. Any account can hold one, and giving it to one that holds it starts the
982
+ * 24 hours again. The stored record carries `priorityUntil` only while it is set: ending it removes the member, and the
983
+ * first write of the account after it ended drops it (`AuthSwitchAuthorityDatabase.persistAccount`).
984
+ */
985
+ public async setAccountPriority(accountId: string, expectedRevision: number,
986
+ priority: boolean): Promise<IAuthSwitchAccount> {
987
+ if (!isId(accountId) || !validRevision(expectedRevision) || typeof priority !== 'boolean') {
988
+ throw new Error('Invalid account change.');
989
+ }
990
+ const updateId = plugins.crypto.randomUUID();
991
+ const updated = await this.database.changeAccount(updateId, accountId, account => {
992
+ if (!account || account.removed || account.revision !== expectedRevision) throw new AuthSwitchRefusal('account_changed', 'Account changed; refresh before editing.');
993
+ const now = this.now();
994
+ const { priorityUntil: _previous, ...rest } = account;
995
+ return { ...rest, ...(priority ? { priorityUntil: new Date(now + authSwitchPriorityMs).toISOString() } : {}),
996
+ revision: account.revision + 1, updateId, statusObservedAt: new Date(now).toISOString() };
997
+ });
998
+ this.publish();
999
+ return publicAccount(updated.account);
1000
+ }
1001
+
977
1002
  /** Refuses a removal that would not go ahead, changing nothing; `removeAccount` refuses the same. */
978
1003
  public async assertAccountRemovable(accountId: string, expectedRevision: number): Promise<void> {
979
1004
  if (!isId(accountId) || !validRevision(expectedRevision)) throw new Error('Invalid account change.');