agl 43.2.0 → 43.3.1

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 (213) hide show
  1. package/changelog.md +29 -0
  2. package/dist_serve/bundle.js +2845 -2638
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +1 -1
  5. package/dist_serve/bundle.js.third-party-notices.txt +1 -1
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +197 -17
  8. package/dist_ts/classes.accountsactions.d.ts +3 -1
  9. package/dist_ts/classes.accountsactions.js +21 -3
  10. package/dist_ts/classes.authstore.d.ts +7 -0
  11. package/dist_ts/classes.authstore.js +9 -1
  12. package/dist_ts/classes.claudeharness.d.ts +29 -2
  13. package/dist_ts/classes.claudeharness.js +35 -6
  14. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  15. package/dist_ts/classes.codexclientadapter.js +14 -2
  16. package/dist_ts/classes.controller.d.ts +187 -12
  17. package/dist_ts/classes.controller.js +1208 -186
  18. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  19. package/dist_ts/classes.controllerdevices.js +6 -1
  20. package/dist_ts/classes.inbox.d.ts +72 -0
  21. package/dist_ts/classes.inbox.js +231 -0
  22. package/dist_ts/classes.inferencerouter.d.ts +10 -0
  23. package/dist_ts/classes.inferencerouter.js +5 -3
  24. package/dist_ts/classes.inferenceservice.js +2 -2
  25. package/dist_ts/classes.mcpclient.d.ts +1 -1
  26. package/dist_ts/classes.mcpclient.js +24 -6
  27. package/dist_ts/classes.mcpcontrollerhost.js +6 -1
  28. package/dist_ts/classes.mcptools.js +18 -8
  29. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  30. package/dist_ts/classes.mcpvalidation.js +32 -2
  31. package/dist_ts/classes.nativesessions.d.ts +29 -4
  32. package/dist_ts/classes.nativesessions.js +41 -9
  33. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  34. package/dist_ts/classes.opencodeclient.js +47 -3
  35. package/dist_ts/classes.publishedset.d.ts +38 -0
  36. package/dist_ts/classes.publishedset.js +50 -0
  37. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  38. package/dist_ts/classes.sessionfeed.js +18 -26
  39. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  40. package/dist_ts/classes.systemmetricssampler.js +15 -3
  41. package/dist_ts/classes.ticketstore.d.ts +50 -3
  42. package/dist_ts/classes.ticketstore.js +45 -8
  43. package/dist_ts/classes.workercallers.js +4 -2
  44. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  45. package/dist_ts/driver/classes.directreports.js +42 -23
  46. package/dist_ts/driver/classes.directreportstore.d.ts +8 -1
  47. package/dist_ts/driver/classes.directreportstore.js +20 -10
  48. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  49. package/dist_ts/driver/classes.driverservice.js +50 -16
  50. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  51. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  52. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  53. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  54. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  55. package/dist_ts/fleet/classes.workercommand.js +15 -4
  56. package/dist_ts/fleet/classes.workers.d.ts +21 -1
  57. package/dist_ts/fleet/classes.workers.js +80 -40
  58. package/dist_ts/fleet/classes.workerstore.js +14 -8
  59. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  60. package/dist_ts/fleet/functions.workervalidation.js +11 -4
  61. package/dist_ts/fleet/interfaces.workers.d.ts +27 -5
  62. package/dist_ts/fleet/interfaces.workers.js +8 -4
  63. package/dist_ts/functions.agentmessage.d.ts +3 -0
  64. package/dist_ts/functions.agentmessage.js +4 -1
  65. package/dist_ts/functions.deviceapi.d.ts +198 -4
  66. package/dist_ts/functions.deviceapi.js +1060 -38
  67. package/dist_ts/functions.exactpersistence.d.ts +3 -0
  68. package/dist_ts/functions.exactpersistence.js +4 -0
  69. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  70. package/dist_ts/functions.fleetworkercli.js +11 -8
  71. package/dist_ts/functions.inferencecli.js +3 -1
  72. package/dist_ts/functions.mcpfleetworkertools.js +3 -3
  73. package/dist_ts/functions.ticketactor.d.ts +17 -1
  74. package/dist_ts/functions.ticketactor.js +55 -15
  75. package/dist_ts/functions.ticketvalidation.js +11 -2
  76. package/dist_ts/interfaces.auth.d.ts +1 -1
  77. package/dist_ts/interfaces.auth.js +9 -1
  78. package/dist_ts/plugins.d.ts +3 -1
  79. package/dist_ts/plugins.js +7 -2
  80. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  81. package/dist_ts_authswitch/authority-contract.js +1 -1
  82. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  83. package/dist_ts_authswitch/authority-overview.js +17 -6
  84. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  85. package/dist_ts_authswitch/authority-placement.js +17 -10
  86. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  87. package/dist_ts_authswitch/authority-renewal.js +56 -0
  88. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  89. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  90. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  91. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  92. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  93. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  94. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  95. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  96. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  97. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  98. package/dist_ts_interfaces/devices.d.ts +1027 -7
  99. package/dist_ts_interfaces/devices.js +68 -2
  100. package/dist_ts_interfaces/fleetworkers.d.ts +37 -10
  101. package/dist_ts_interfaces/fleetworkers.js +19 -8
  102. package/dist_ts_interfaces/inbox.d.ts +234 -0
  103. package/dist_ts_interfaces/inbox.js +101 -0
  104. package/dist_ts_interfaces/index.d.ts +1 -0
  105. package/dist_ts_interfaces/index.js +2 -1
  106. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  107. package/dist_ts_interfaces/interfaces.js +4 -2
  108. package/dist_ts_interfaces/mcprequests.d.ts +34 -4
  109. package/dist_ts_interfaces/mcprequests.js +11 -1
  110. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  111. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  112. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  113. package/dist_ts_interfaces/plugins.d.ts +2 -1
  114. package/dist_ts_interfaces/plugins.js +4 -2
  115. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  116. package/dist_ts_interfaces/requests.accounts.js +3 -1
  117. package/dist_ts_interfaces/requests.d.ts +3 -2
  118. package/dist_ts_interfaces/requests.js +1 -1
  119. package/dist_ts_interfaces/workercallers.d.ts +2 -0
  120. package/dist_ts_migration/classes.documentmigrationrunner.d.ts +14 -0
  121. package/dist_ts_migration/classes.documentmigrationrunner.js +20 -1
  122. package/dist_ts_migration/index.d.ts +1 -0
  123. package/dist_ts_migration/index.js +2 -1
  124. package/dist_ts_migration/v43_ticketactornames.d.ts +32 -0
  125. package/dist_ts_migration/v43_ticketactornames.js +236 -0
  126. package/docs/authswitch.md +20 -1
  127. package/package.json +3 -3
  128. package/readme.md +144 -27
  129. package/ts/00_commitinfo_data.ts +1 -1
  130. package/ts/aglapi/aglapisurface.document.ts +196 -16
  131. package/ts/classes.accountsactions.ts +30 -3
  132. package/ts/classes.authstore.ts +10 -0
  133. package/ts/classes.claudeharness.ts +45 -5
  134. package/ts/classes.codexclientadapter.ts +14 -1
  135. package/ts/classes.controller.ts +1412 -262
  136. package/ts/classes.controllerdevices.ts +6 -0
  137. package/ts/classes.inbox.ts +239 -0
  138. package/ts/classes.inferencerouter.ts +15 -2
  139. package/ts/classes.inferenceservice.ts +1 -1
  140. package/ts/classes.mcpclient.ts +24 -3
  141. package/ts/classes.mcpcontrollerhost.ts +5 -0
  142. package/ts/classes.mcptools.ts +17 -7
  143. package/ts/classes.mcpvalidation.ts +27 -1
  144. package/ts/classes.nativesessions.ts +63 -12
  145. package/ts/classes.opencodeclient.ts +55 -4
  146. package/ts/classes.publishedset.ts +56 -0
  147. package/ts/classes.sessionfeed.ts +17 -20
  148. package/ts/classes.systemmetricssampler.ts +13 -2
  149. package/ts/classes.ticketstore.ts +73 -12
  150. package/ts/classes.workercallers.ts +3 -1
  151. package/ts/driver/classes.directreports.ts +42 -23
  152. package/ts/driver/classes.directreportstore.ts +20 -9
  153. package/ts/driver/classes.driverservice.ts +75 -14
  154. package/ts/fleet/classes.claudeworkers.ts +112 -39
  155. package/ts/fleet/classes.codexworkers.ts +21 -6
  156. package/ts/fleet/classes.workercommand.ts +14 -4
  157. package/ts/fleet/classes.workers.ts +75 -41
  158. package/ts/fleet/classes.workerstore.ts +11 -7
  159. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  160. package/ts/fleet/functions.workervalidation.ts +8 -3
  161. package/ts/fleet/interfaces.workers.ts +26 -7
  162. package/ts/functions.agentmessage.ts +3 -0
  163. package/ts/functions.deviceapi.ts +1292 -34
  164. package/ts/functions.exactpersistence.ts +5 -0
  165. package/ts/functions.fleetworkercli.ts +10 -7
  166. package/ts/functions.inferencecli.ts +2 -0
  167. package/ts/functions.mcpfleetworkertools.ts +2 -2
  168. package/ts/functions.ticketactor.ts +58 -14
  169. package/ts/functions.ticketvalidation.ts +11 -1
  170. package/ts/interfaces.auth.ts +8 -0
  171. package/ts/plugins.ts +7 -0
  172. package/ts_authswitch/authority-contract.ts +20 -0
  173. package/ts_authswitch/authority-overview.ts +28 -6
  174. package/ts_authswitch/authority-placement.ts +25 -17
  175. package/ts_authswitch/authority-renewal.ts +64 -0
  176. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  177. package/ts_authswitch/classes.authoritycli.ts +49 -2
  178. package/ts_authswitch/classes.authorityclient.ts +14 -4
  179. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  180. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  181. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  182. package/ts_authswitch/native-contracts.md +21 -0
  183. package/ts_authswitch/readme.md +1 -1
  184. package/ts_interfaces/devices.schema.json +3576 -603
  185. package/ts_interfaces/devices.ts +1111 -6
  186. package/ts_interfaces/fleetworkers.ts +38 -10
  187. package/ts_interfaces/inbox.ts +287 -0
  188. package/ts_interfaces/index.ts +1 -0
  189. package/ts_interfaces/interfaces.ts +9 -2
  190. package/ts_interfaces/mcprequests.ts +43 -4
  191. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  192. package/ts_interfaces/nativesessions.ts +17 -3
  193. package/ts_interfaces/plugins.ts +3 -1
  194. package/ts_interfaces/requests.accounts.ts +20 -0
  195. package/ts_interfaces/requests.ts +4 -0
  196. package/ts_interfaces/workercallers.ts +2 -0
  197. package/ts_migration/classes.documentmigrationrunner.ts +21 -0
  198. package/ts_migration/index.ts +1 -0
  199. package/ts_migration/v43_ticketactornames.ts +225 -0
  200. package/ts_web/00_commitinfo_data.ts +1 -1
  201. package/ts_web/accounts.plugins.ts +4 -2
  202. package/ts_web/classes.accountsreadmodel.ts +33 -0
  203. package/ts_web/classes.browserpresentation.ts +10 -5
  204. package/ts_web/classes.inboxfeed.ts +329 -0
  205. package/ts_web/classes.nativesessionstate.ts +9 -23
  206. package/ts_web/elements.accounts.ts +81 -0
  207. package/ts_web/elements.deployments.ts +66 -2
  208. package/ts_web/elements.fleetworker.ts +4 -2
  209. package/ts_web/elements.harnesscontrollerapp.ts +107 -37
  210. package/ts_web/elements.inbox.ts +808 -0
  211. package/ts_web/functions.inbox.ts +95 -0
  212. package/ts_web/functions.sessioncards.ts +40 -0
  213. package/ts_web/plugins.ts +2 -0
@@ -0,0 +1,5 @@
1
+ import * as plugins from './plugins.js';
2
+
3
+ /** Whether an error is the persistence client's exact-write error of this code (`SmartdataExactPersistenceError`). */
4
+ export const exactError = (errorArg: unknown, codeArg: plugins.nosqldb.TExactPersistenceErrorCode): boolean =>
5
+ errorArg instanceof plugins.nosqldb.SmartdataExactPersistenceError && errorArg.code === codeArg;
@@ -39,12 +39,15 @@ every --probe-interval seconds (default 60); each writes its state first and the
39
39
  Steer and message reach a live worker through a relay and resume a reaped or stopped one with its saved options.
40
40
  Message addresses one worker by its name or by its native session id (a unique prefix of at least 8 characters).
41
41
  Without --ticket it steers the worker on its own ticket; a --ticket the worker is not on, and a worker on no ticket, are refused.
42
- native-message wakes a settled (done, blocked or stopped) Claude Code background job that no fleet worker binds, named by
43
- its session id or a unique prefix of at least 8 characters, through Claude Code itself, as the browser's native session
44
- send does. The text arrives behind the session_message attribution header with the --sender label and the local owner
45
- capability, never as the job's user. A running, failed or held job, a fleet worker's session and a project conversation
46
- are refused with their reason. A native wake holds no dispatch fence, writes no ticket comment and does not observe the
47
- woken turn; the receipt names the command that adopts the job. It takes no --ticket.
42
+ native-message reaches a Claude Code background job that no fleet worker binds, named by its session id or a unique
43
+ prefix of at least 8 characters, through Claude Code itself, as the browser's native session send does: a settled (done,
44
+ blocked or stopped) job is woken with it, a running one takes it in its inbox through Claude Code's own SendMessage
45
+ (accepted and queued, not yet read). The text arrives behind the session_message attribution header with the --sender
46
+ label and the local owner capability, never as the job's user. A running job without a session name of its own (none,
47
+ or one another running session shares), a failed or held job, a fleet worker's session and a project conversation are
48
+ refused with their reason. It holds no dispatch fence, writes no ticket comment and does not observe the turn that reads
49
+ it; the receipt says whether it was a native wake or a native inbox and names the command that adopts the job. It takes
50
+ no --ticket.
48
51
  Adopt registers a native session as it is. --relaunch-file resumes a settled Claude Code session under the fleet with the
49
52
  file's prompt, so the worker calls AGL with a verified identity; a background job continues as a copy under a new
50
53
  session id. The adopt refuses while the session still runs: its owner stops it first, the adopt never does.
@@ -95,7 +98,7 @@ export const resolveFleetWorkerTarget = (workers: IFleetWorker[], target: string
95
98
  const file = /^[\w@%+=:,./-]+$/u.test(messageFile) ? messageFile : `'${messageFile.replaceAll('\'', '\'\\\'\'')}'`;
96
99
  throw new Error(`No fleet worker is named ${target} or bound to that native session; message does not reach a session outside the fleet. `
97
100
  + (/^[0-9a-fA-F][0-9a-fA-F-]{7,35}$/u.test(target)
98
- ? `If ${target} is a settled Claude Code background job no fleet worker binds, wake it with an attributed message: `
101
+ ? `If ${target} is a Claude Code background job no fleet worker binds, reach it with an attributed message: `
99
102
  + `agl fleet worker native-message ${target} --message-file ${file} --sender LABEL (no dispatch fence, no ticket comment, the turn is not observed), `
100
103
  + 'or adopt it first.'
101
104
  : 'Adopt the session first.'));
@@ -44,6 +44,8 @@ const placementText = (accountArg: NonNullable<TReportedProxyStatus['accounts']>
44
44
  if (accountArg.lifecycle === undefined) return '';
45
45
  if (accountArg.lifecycle === 'lapsed') return `; lapsed ${accountArg.lapsesAt}, never routed to again`;
46
46
  return `${accountArg.lifecycle === 'canceled' ? `; canceled, lapses ${accountArg.lapsesAt}` : ''}`
47
+ + `${accountArg.renewal ? `; renews ${accountArg.renewal.at} (set by the owner`
48
+ + `${accountArg.lifecycle === 'canceled' ? ', ignored while it lapses' : ''})` : ''}`
47
49
  + `; placement ${scoreText(accountArg.placementScore ?? null)}`
48
50
  + `${accountArg.placementRank === null || accountArg.placementRank === undefined ? ', takes no new session now'
49
51
  : `, rank ${accountArg.placementRank}`}${accountArg.lastResort ? ' (last resort: lapses within a day)' : ''}`;
@@ -16,8 +16,8 @@ const descriptions: Record<TFleetWorkerAction, string> = {
16
16
  list: 'List this owner\'s fleet workers as summaries, newest first, in pages of limit (1-100, default 50): identity, ticket, state, native id, cwd, the native status, newest turn outcome and native wait last observed, and fence flags (an unresolved dispatch with its action and since, a lost or reconfirmed dispatch, a recorded error). total, fenced and failed (recorded errors and failed turn outcomes) count the whole filtered set, so a page never hides a fence. Continue with nextCursor and the same filter (archived, ticketKey, state, harness); a cursor of another filter or one after a worker no longer held as it was is refused. view full returns every full record unpaged; fleet_worker_get returns one worker whole.',
17
17
  get: 'Read one of this owner\'s fleet workers, archived ones included, by name or id: its full record (dispatch fence, lost, reconfirmed and re-bind resolutions with their attribution and proof, error) and the native status, turn outcome and start, native wait and excerpt the controller last observed.',
18
18
  status: 'Read a fleet operation job (the handle a fleet_worker_* action returns), not a host job. Jobs are transient; bindings and unresolved dispatches survive restart. Inspect unknown native outcomes before retrying.',
19
- 'job-wait': 'Wait until a fleet operation job (the handle a fleet_worker_* action returns, not a host job) succeeds or fails, or timeoutMs (at most 240000) passes; timedOut tells which. Waiting, a timeout or an abandoned wait never cancels the job. A job the controller no longer holds (jobs end with a controller restart or eviction) is JOB_UNAVAILABLE, not failed: read the worker with fleet_worker_get.',
20
- 'native-message': 'Wake a settled (done, blocked or stopped) Claude Code background job that no fleet worker binds with an attributed message, through Claude Code itself (`claude --bg --resume <id> <text>`), as the browser\'s native session send does. nativeId is the full session id or a unique prefix of at least 8 characters; an ambiguous prefix is refused. A running, failed or held job, a fleet worker\'s session and a project conversation are refused with their reason. The message arrives behind the same attribution header as session_message, naming the sender label and the local owner capability, never as the job\'s user. A native wake holds no dispatch fence, writes no ticket comment and does not observe the woken turn; the receipt names the command that adopts the job as a fleet worker. Returns a job handle; an unknown outcome is never retried.',
19
+ 'job-wait': 'Wait until a fleet operation job (the handle a fleet_worker_* action returns, not a host job) succeeds or fails, or timeoutMs (at most 240000) passes; timedOut tells which. Waiting, a timeout or an abandoned wait never cancels the job. A job the controller no longer holds (jobs end with a controller restart or eviction) is JOB_UNAVAILABLE, not failed: read the worker with fleet_worker_get. A failed job\'s errorOutcome is refused when nothing reached a native session, unknown when it may have (a steer may have been delivered): never repeat an unknown one before reading the worker.',
20
+ 'native-message': 'Reach a Claude Code background job that no fleet worker binds with an attributed message, through Claude Code itself, as the browser\'s native session send does: a settled (done, blocked or stopped) job is woken with it (`claude --bg --resume <id> <text>`), a running one takes it in its inbox through Claude Code\'s own SendMessage, accepted and queued there, not yet read. nativeId is the full session id or a unique prefix of at least 8 characters; an ambiguous prefix is refused. A running job without a session name of its own (none, or one another running session shares), a failed or held job, a fleet worker\'s session and a project conversation are refused with their reason. The message arrives behind the same attribution header as session_message, naming the sender label and the local owner capability, never as the job\'s user. It holds no dispatch fence, writes no ticket comment and does not observe the turn that reads it; the receipt (delivery native-wake or native-inbox) names the command that adopts the job as a fleet worker. Returns a job handle; an unknown outcome is never retried.',
21
21
  watch: 'Read the one bounded fleet event stream: worker turn endings, reports during turns, reaped Claude worker observations, release outcomes, and host load. Continue with the returned epoch/cursor; reset explicitly signals restart or retained-history gaps.',
22
22
  };
23
23
  /** The tools' own inputs where they differ from the private request's: MCP `fleet_worker_list` lists summaries unless told otherwise. */
@@ -1,20 +1,64 @@
1
- import type { IControllerMcpCaller } from '../ts_interfaces/mcprequests.js';
1
+ import type { TControllerSessionHarnessId } from '../ts_interfaces/interfaces.js';
2
+ import type { IControllerMcpCaller, TControllerMcpSubject } from '../ts_interfaces/mcprequests.js';
2
3
  import { ticketErrorMessages, type ITicketActor } from '../ts_interfaces/tickets.js';
3
4
  import { TicketError } from './classes.ticketstore.js';
4
5
 
5
- export const ticketActorFromCaller = (callerArg: IControllerMcpCaller): ITicketActor => {
6
- const subject = callerArg.subject;
7
- if (subject.kind === 'anonymous') throw new TicketError('ticket_identity_required', ticketErrorMessages.ticket_identity_required);
8
- if (subject.kind === 'worker_launch') return { id: subject.sessionIdentityId,
9
- name: subject.ticketSessionId, sessionId: subject.ticketSessionId, kind: subject.harnessId, role: 'worker' };
10
- if (subject.kind === 'session') {
11
- const sessionId = `${subject.sessionId.harnessId}:${subject.sessionId.nativeId}`;
12
- return { id: subject.sessionIdentityId, name: sessionId, sessionId,
13
- kind: subject.sessionId.harnessId === 'codex' ? 'codex' : 'worker', role: 'worker' };
6
+ /**
7
+ * What a ticket calls a session no direct report or fleet worker names: its harness's label, never its session id. A
8
+ * new harness does not compile until it has one.
9
+ */
10
+ export const ticketSessionLabels: Readonly<Record<TControllerSessionHarnessId, string>> = {
11
+ claude: 'Claude Code session',
12
+ codex: 'Codex session',
13
+ opencode: 'OpenCode session',
14
+ flex: 'Flex session',
15
+ };
16
+ /** What a ticket calls the OpenCode runtime's caller: one server per controller, never one session (AGL-1686). */
17
+ export const ticketOpenCodeRuntimeName = 'OpenCode';
18
+
19
+ /** The native session an MCP caller acts in, as tickets name it (`harness:nativeId`); none for a caller without one. */
20
+ export const ticketCallerSessionId = (callerArg: IControllerMcpCaller): string | undefined => {
21
+ const subject: TControllerMcpSubject = callerArg.subject;
22
+ switch (subject.kind) {
23
+ case 'worker_launch': return subject.ticketSessionId;
24
+ case 'session': return `${subject.sessionId.harnessId}:${subject.sessionId.nativeId}`;
25
+ case 'terminal': return subject.agentSessionId === undefined ? undefined : `claude:${subject.agentSessionId}`;
26
+ case 'runtime':
27
+ case 'anonymous': return undefined;
28
+ default: {
29
+ const exhaustive: never = subject;
30
+ throw new Error(`Unknown MCP caller subject ${(exhaustive as { kind: string }).kind}.`);
31
+ }
14
32
  }
15
- if (subject.kind === 'terminal' && subject.agentSessionId) {
16
- const sessionId = `claude:${subject.agentSessionId}`;
17
- return { id: sessionId, name: sessionId, sessionId, kind: 'claude', role: 'worker' };
33
+ };
34
+
35
+ /**
36
+ * The actor a ticket records for an MCP caller. It is named by its role, never by a session id (AGL-1686): the active
37
+ * direct report whose session the caller acts in (`reportNameArg`, which the caller resolves once through
38
+ * `DirectReports.reportOf` with `ticketCallerSessionId`), else the fleet worker's name, else its harness's label; the
39
+ * OpenCode runtime is "OpenCode". `id` and `sessionId` identify the actor; the name is display only.
40
+ */
41
+ export const ticketActorFromCaller = (callerArg: IControllerMcpCaller, reportNameArg?: string): ITicketActor => {
42
+ const subject: TControllerMcpSubject = callerArg.subject;
43
+ switch (subject.kind) {
44
+ case 'anonymous': throw new TicketError('ticket_identity_required', ticketErrorMessages.ticket_identity_required);
45
+ case 'worker_launch': return { id: subject.sessionIdentityId, name: reportNameArg ?? subject.workerName,
46
+ sessionId: subject.ticketSessionId, kind: subject.harnessId, role: 'worker' };
47
+ case 'session': {
48
+ const sessionId = `${subject.sessionId.harnessId}:${subject.sessionId.nativeId}`;
49
+ return { id: subject.sessionIdentityId, name: reportNameArg ?? ticketSessionLabels[subject.sessionId.harnessId], sessionId,
50
+ kind: subject.sessionId.harnessId === 'codex' ? 'codex' : 'worker', role: 'worker' };
51
+ }
52
+ case 'terminal': {
53
+ // A terminal without an agent session acts in no session.
54
+ if (subject.agentSessionId === undefined) return { id: callerArg.auditPeerId, name: 'terminal', kind: 'worker', role: 'worker' };
55
+ const sessionId = `claude:${subject.agentSessionId}`;
56
+ return { id: sessionId, name: reportNameArg ?? ticketSessionLabels.claude, sessionId, kind: 'claude', role: 'worker' };
57
+ }
58
+ case 'runtime': return { id: callerArg.auditPeerId, name: ticketOpenCodeRuntimeName, kind: 'worker', role: 'worker' };
59
+ default: {
60
+ const exhaustive: never = subject;
61
+ throw new Error(`Unknown MCP caller subject ${(exhaustive as { kind: string }).kind}.`);
62
+ }
18
63
  }
19
- return { id: callerArg.auditPeerId, name: subject.kind, kind: 'worker', role: 'worker' };
20
64
  };
@@ -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',
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,
@@ -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.
@@ -11,6 +11,7 @@ import { authSwitchUsageProblemText, authSwitchUsageWindowName, authSwitchUsageW
11
11
  import { authSwitchUsageLimit, authSwitchUsageLimitText, type IAuthSwitchUsageLimit,
12
12
  type TAuthSwitchLimitState } from './authority-usagelimit.js';
13
13
  import { authSwitchPlacement, type IAuthSwitchPlacement, type TAuthSwitchAccountLifecycle } from './authority-placement.js';
14
+ import { authSwitchRenewal, type IAuthSwitchRenewal } from './authority-renewal.js';
14
15
  import { authSwitchSubscriptionFacts, type IAuthSwitchSubscriptionFact } from './authority-subscription.js';
15
16
  import type { IAuthSwitchPaymentProblem } from './classes.authorityusage.js';
16
17
  import { plainText } from './formatting.js';
@@ -54,6 +55,11 @@ export interface IAuthSwitchAccountOverview {
54
55
  /** When the account's subscription ends, or null while it renews (`IAuthSwitchAccount.lapsesAt`). */
55
56
  lapsesAt: string | null;
56
57
  lifecycle: TAuthSwitchAccountLifecycle;
58
+ /**
59
+ * The account's next monthly renewal as its owner set it (`IAuthSwitchAccount.renewsAt` rolled forward), or null
60
+ * without one. Placement ignores it while the account has a lapse date.
61
+ */
62
+ renewal: IAuthSwitchRenewal | null;
57
63
  /**
58
64
  * How the AGL proxy treats the account for a new session, by the rule of `authority-placement.ts`: its score in
59
65
  * percent per hour (null without a counted window) and whether it is a last resort or never placed on.
@@ -94,6 +100,8 @@ export interface IAuthSwitchLimitRow {
94
100
  /** When the account's subscription ends, or null while it renews. */
95
101
  lapsesAt: string | null;
96
102
  lifecycle: TAuthSwitchAccountLifecycle;
103
+ /** The account's next monthly renewal as its owner set it, or null without one (`IAuthSwitchAccountOverview.renewal`). */
104
+ renewal: IAuthSwitchRenewal | null;
97
105
  /** The account's placement score in percent per hour (`IAuthSwitchPlacement.score`), on each of its rows. */
98
106
  placementScore: number | null;
99
107
  placementEligibility: IAuthSwitchPlacement['eligibility'];
@@ -166,10 +174,13 @@ export const readAuthSwitchAccountOverview = async (snapshotArg: IAuthSwitchSnap
166
174
  plan: accountArg.plan, usedBy: accountUses(snapshotArg, accountArg.id), usageLoginId: login?.id ?? null,
167
175
  loginHealth: login?.health ?? null, loginProblem: login?.problem ?? null,
168
176
  maxUsagePercent: accountArg.maxUsagePercent, lapsesAt: accountArg.lapsesAt,
169
- lifecycle: authSwitchPlacement(null, accountArg.maxUsagePercent, accountArg.lapsesAt, nowArg, accountArg.reserveLiftUntil).lifecycle,
177
+ lifecycle: authSwitchPlacement(null, accountArg.maxUsagePercent, accountArg.lapsesAt, accountArg.renewsAt, nowArg,
178
+ accountArg.reserveLiftUntil).lifecycle,
179
+ renewal: authSwitchRenewal(accountArg.renewsAt, nowArg),
170
180
  };
171
181
  const placement = (readingArg: IAuthSwitchUsageSnapshot['reading']): IAuthSwitchPlacement =>
172
- authSwitchPlacement(readingArg, accountArg.maxUsagePercent, accountArg.lapsesAt, nowArg, accountArg.reserveLiftUntil);
182
+ authSwitchPlacement(readingArg, accountArg.maxUsagePercent, accountArg.lapsesAt, accountArg.renewsAt, nowArg,
183
+ accountArg.reserveLiftUntil);
173
184
  if (login === null) {
174
185
  return { ...base, usage: null, windows: [], problem: 'The account has no login to read its usage with.',
175
186
  subscription: [], paymentProblem: null, limit: null, placement: placement(null) };
@@ -220,7 +231,8 @@ export const authSwitchLimitList = (overviewArg: IAuthSwitchAccountOverviewList)
220
231
  const base = { accountId: accountArg.accountId, providerId: accountArg.providerId, account: identity(accountArg),
221
232
  plan: accountArg.plan, usageState: accountArg.usage?.state ?? null, problem: accountArg.problem,
222
233
  maxUsagePercent: accountArg.maxUsagePercent, accountState: accountArg.limit?.state ?? null,
223
- lapsesAt: accountArg.lapsesAt, lifecycle: accountArg.lifecycle, placementScore: accountArg.placement.score,
234
+ lapsesAt: accountArg.lapsesAt, lifecycle: accountArg.lifecycle, renewal: accountArg.renewal,
235
+ placementScore: accountArg.placement.score,
224
236
  placementEligibility: accountArg.placement.eligibility };
225
237
  if (accountArg.windows.length === 0) {
226
238
  return [{ ...base, limit: null, windowSeconds: null, usedPercent: null, estimatedUsedPercent: null, resetAt: null,
@@ -296,18 +308,28 @@ const limitLines = (maxUsagePercentArg: number | null, limitArg: IAuthSwitchUsag
296
308
 
297
309
  /**
298
310
  * The lifecycle and placement of an account as lines of its cell: nothing for an active account with its score, a
299
- * canceled one with its lapse, a lapsed one as never placed on.
311
+ * canceled one with its lapse, a lapsed one as never placed on; and the renewal its owner set, unless it lapsed.
300
312
  */
301
- const placementLines = (accountArg: Pick<IAuthSwitchLimitRow, 'lifecycle' | 'lapsesAt' | 'placementScore'
313
+ const placementLines = (accountArg: Pick<IAuthSwitchLimitRow, 'lifecycle' | 'lapsesAt' | 'renewal' | 'placementScore'
302
314
  | 'placementEligibility'>, nowArg: number): string[] => [
303
315
  ...accountArg.lifecycle === 'lapsed' ? ['lapsed · never placed on']
304
316
  : accountArg.lifecycle === 'canceled' && accountArg.lapsesAt !== null
305
317
  ? [`canceled · lapses in ${compactUntil(accountArg.lapsesAt, nowArg)}`] : [],
318
+ ...accountArg.lifecycle === 'lapsed' || accountArg.renewal === null ? []
319
+ : [renewalLine(accountArg.renewal, accountArg.lifecycle, nowArg)],
306
320
  ...accountArg.lifecycle === 'lapsed' ? []
307
321
  : [`placement ${placementScoreText(accountArg.placementScore)}${accountArg.placementEligibility === 'last_resort'
308
322
  ? ' · last resort' : ''}`],
309
323
  ];
310
324
 
325
+ /**
326
+ * The renewal line of an account cell: `renews in 9d 4h (set by the owner)`. A canceled account does not renew, so
327
+ * placement ignores it then, and the line says so.
328
+ */
329
+ const renewalLine = (renewalArg: IAuthSwitchRenewal, lifecycleArg: TAuthSwitchAccountLifecycle, nowArg: number): string =>
330
+ `renews in ${compactUntil(renewalArg.at, nowArg)} (set by the owner${lifecycleArg === 'canceled'
331
+ ? ', ignored while it lapses' : ''})`;
332
+
311
333
  /** A placement score as a cell shows it: percent per hour, or `unscored` without a counted window. */
312
334
  const placementScoreText = (scoreArg: number | null): string => scoreArg === null ? 'unscored'
313
335
  : `${scoreArg < 10 ? scoreArg.toFixed(2) : Math.round(scoreArg)}%/h`;
@@ -321,7 +343,7 @@ const accountCell = (accountArg: IAuthSwitchAccountOverview, nowArg: number): st
321
343
  plainText(accountArg.plan === null ? 'plan not reported' : `${accountArg.plan} plan`),
322
344
  ...accountArg.paymentProblem === null ? [] : [`payment problem since ${asOfTime(accountArg.paymentProblem.at, nowArg)}`],
323
345
  ...limitLines(accountArg.maxUsagePercent, accountArg.limit, nowArg),
324
- ...placementLines({ lifecycle: accountArg.lifecycle, lapsesAt: accountArg.lapsesAt,
346
+ ...placementLines({ lifecycle: accountArg.lifecycle, lapsesAt: accountArg.lapsesAt, renewal: accountArg.renewal,
325
347
  placementScore: accountArg.placement.score, placementEligibility: accountArg.placement.eligibility }, nowArg),
326
348
  ...accountArg.loginHealth === null ? ['no login']
327
349
  : accountArg.loginHealth === 'ready' ? []
@@ -1,17 +1,18 @@
1
1
  /**
2
2
  * Where a new session goes: an account's lifecycle against its lapse date, and how much of its usage it can spend per
3
- * hour before that usage resets or the account lapses. The inference proxy places new sessions by it, and the authswitch
4
- * command line and `agl proxy status` show it; an existing session keeps its account for the prompt cache and is never
5
- * placed again by it.
3
+ * hour before that usage resets, the account lapses or it renews. The inference proxy places new sessions by it, and the
4
+ * authswitch command line and `agl proxy status` show it; an existing session keeps its account for the prompt cache and
5
+ * is never placed again by it.
6
6
  *
7
- * Besides types, the module imports only the limit rule of `authority-usagelimit.ts`, the window reader it uses and the
8
- * spend month of `authority-spend.ts`, whose own imports carry nothing to a page, so it bundles for a browser with
9
- * nothing behind it.
7
+ * Besides types, the module imports only the limit rule of `authority-usagelimit.ts`, the window reader it uses, the
8
+ * spend month of `authority-spend.ts` and the renewal of `authority-renewal.ts`, whose own imports carry nothing to a
9
+ * page, so it bundles for a browser with nothing behind it.
10
10
  */
11
11
  import type { TAuthSwitchUsageReading } from './classes.authorityusage.js';
12
12
  import { authSwitchCountedWindows, authSwitchEffectiveMaxUsage } from './authority-usagelimit.js';
13
13
  import { authSwitchUsageWindowPercent, authSwitchUsageWindowResetAt } from './authority-usagewindows.js';
14
14
  import { authSwitchSpendMonthEnded, authSwitchSpendPeriod } from './authority-spend.js';
15
+ import { authSwitchNextRenewal } from './authority-renewal.js';
15
16
 
16
17
  /**
17
18
  * `active`: the account has no lapse date. `canceled`: its subscription ends at `lapsesAt`, which is still ahead.
@@ -36,8 +37,8 @@ export interface IAuthSwitchPlacement {
36
37
  eligibility: TAuthSwitchPlacementEligibility;
37
38
  /**
38
39
  * The percent of its usage the account can spend per hour and still stay within every counted window before that
39
- * window resets or the account lapses, whichever comes first; the smallest over its counted windows. `null` when the
40
- * reading counts no window.
40
+ * window resets, the account lapses or it renews, whichever comes first; the smallest over its counted windows.
41
+ * `null` when the reading counts no window.
41
42
  */
42
43
  score: number | null;
43
44
  }
@@ -48,22 +49,29 @@ export const authSwitchAccountLifecycle = (lapsesAtArg: string | null, nowArg: n
48
49
 
49
50
  /**
50
51
  * Where an account stands for a new session at `nowArg`, from its usage reading (`null` when none is held), its usage
51
- * threshold and its lapse date.
52
+ * threshold, its lapse date and its renewal anchor (`IAuthSwitchAccount.renewsAt`, `null` when its owner set none).
52
53
  *
53
54
  * The score is taken over the windows the account's limit counts (`authSwitchCountedWindows`). Per window it is the
54
55
  * headroom left below the threshold -- the percent the limit decides by, the estimate between reads where present --
55
- * divided by the hours until the window's deadline: its reset, or the account's lapse when that comes first, and at
56
- * least an hour. Usage that resets soon, or is lost when the account lapses, is worth more now than usage that stays for
57
- * days; placing by it uses that first and spares the accounts that reset later.
56
+ * divided by the hours until the window's deadline: the earliest of its reset, the account's lapse and its next renewal
57
+ * (`authSwitchNextRenewal` from `nowArg`), and at least an hour. Usage that resets soon, or is lost when the account
58
+ * lapses, is worth more now than usage that stays for days; placing by it uses that first and spares the accounts that
59
+ * reset later. Usage a window still holds at the renewal counts the same way, as spent by the renewal. Whether a
60
+ * provider's windows reset at a renewal is not known: the renewal is a scoring deadline only, and eligibility, lifecycle
61
+ * and capacity never read it. An account with a lapse date ignores its renewal, since a canceled subscription does not
62
+ * renew.
58
63
  *
59
64
  * An API key's spend reading whose month ended (`authSwitchSpendMonthEnded`, as `authSwitchUsageLimit` judges it) says
60
65
  * nothing about the current month, which starts with nothing spent: its window counts as 0% used, with the end of the
61
66
  * current month (`authSwitchSpendPeriod`) as its reset.
62
67
  */
63
68
  export const authSwitchPlacement = (readingArg: TAuthSwitchUsageReading | null, maxUsagePercentArg: number | null,
64
- lapsesAtArg: string | null, nowArg: number, reserveLiftUntilArg: string | null = null): IAuthSwitchPlacement => {
69
+ lapsesAtArg: string | null, renewalAnchorArg: string | null, nowArg: number,
70
+ reserveLiftUntilArg: string | null = null): IAuthSwitchPlacement => {
65
71
  const lifecycle = authSwitchAccountLifecycle(lapsesAtArg, nowArg);
66
72
  const lapsesAt = lapsesAtArg === null ? Infinity : Date.parse(lapsesAtArg);
73
+ const renewsAt = lapsesAtArg !== null || renewalAnchorArg === null ? Infinity
74
+ : authSwitchNextRenewal(renewalAnchorArg, nowArg);
67
75
  const eligibility: TAuthSwitchPlacementEligibility = lifecycle === 'lapsed' ? 'never'
68
76
  : lapsesAt - nowArg <= lapseHorizonMs ? 'last_resort' : 'normal';
69
77
  const threshold = authSwitchEffectiveMaxUsage(maxUsagePercentArg, reserveLiftUntilArg, nowArg) ?? 100;
@@ -72,7 +80,7 @@ export const authSwitchPlacement = (readingArg: TAuthSwitchUsageReading | null,
72
80
  const scores = windows.map((windowArg) => {
73
81
  const headroom = spendMonthEnded ? threshold : Math.max(0, threshold - authSwitchUsageWindowPercent(windowArg));
74
82
  const resetAt = spendMonthEnded ? Date.parse(authSwitchSpendPeriod(nowArg).end) : authSwitchUsageWindowResetAt(windowArg, nowArg);
75
- const deadline = Math.min(resetAt, lapsesAt);
83
+ const deadline = Math.min(resetAt, lapsesAt, renewsAt);
76
84
  return headroom / (Math.max(deadline - nowArg, minimumDeadlineMs) / 3_600_000);
77
85
  });
78
86
  return { lifecycle, eligibility, score: scores.length ? Math.min(...scores) : null };
@@ -89,9 +97,9 @@ export interface IAuthSwitchPlacementRank {
89
97
  /**
90
98
  * The order a new session is placed in: an account that lapses within `lapseHorizonMs` only after every other one;
91
99
  * then by the account's score shared among the requests it serves now -- `score / (1 + in flight)`, so new sessions
92
- * spread over the accounts in proportion to what each can spend per hour, and usage that resets or lapses soon is
93
- * spent first -- then by headroom and id. An account without a counted window comes after every scored one, the least
94
- * busy of them first.
100
+ * spread over the accounts in proportion to what each can spend per hour, and usage that resets, lapses or meets a
101
+ * renewal soon is spent first -- then by headroom and id. An account without a counted window comes after every scored
102
+ * one, the least busy of them first.
95
103
  */
96
104
  export const authSwitchPlacementOrder = (inFlightArg: (accountIdArg: string) => number) => (
97
105
  left: IAuthSwitchPlacementRank,
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A Claude sign-in's monthly renewal (AGL-1644), as its owner set it: the anchor is one date and time the subscription
3
+ * renewed or renews (`IAuthSwitchAccount.renewsAt`), and every renewal is a calendar month from it. AGL derives no
4
+ * renewal from anything a provider states; the owner sets the anchor, and nothing else does.
5
+ *
6
+ * Whether a provider's usage windows reset at the renewal is not known. Placement uses the renewal only as a deadline
7
+ * (`authority-placement.ts`): usage still held at the renewal counts as spent by then.
8
+ *
9
+ * The module imports nothing, so it bundles for a browser as it is.
10
+ */
11
+
12
+ /**
13
+ * The renewal anchor rule, the one the authority applies to `authswitch.authority.renewal`: a date-time `Date.parse`
14
+ * reads, in any year from 2000 to 9999, as the lapse date rule (`isAuthSwitchLapsesAt`). A past anchor is valid: the
15
+ * next renewal is a whole number of months after it. A consumer validates with this rather than restating it; the
16
+ * authority stores the anchor as its ISO 8601 UTC form and answers any other value with the `invalid_input` refusal.
17
+ */
18
+ export const isAuthSwitchRenewsAt = (value: unknown): value is string => {
19
+ if (typeof value !== 'string' || value.length > 64) return false;
20
+ const at = Date.parse(value);
21
+ return Number.isFinite(at) && at >= Date.UTC(2000, 0, 1) && at < Date.UTC(10000, 0, 1);
22
+ };
23
+
24
+ /** The renewal `monthsArg` months after the anchor: the anchor's UTC day clamped to that month, at the anchor's UTC time. */
25
+ const renewalAfter = (anchor: Date, monthsArg: number): number => {
26
+ const year = anchor.getUTCFullYear();
27
+ const month = anchor.getUTCMonth() + monthsArg;
28
+ // Day 0 of the following month is the last day of this one; `Date.UTC` carries a month past December into the year.
29
+ const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
30
+ const timeOfDay = anchor.getTime() - Date.UTC(year, anchor.getUTCMonth(), anchor.getUTCDate());
31
+ return Date.UTC(year, month, Math.min(anchor.getUTCDate(), lastDay)) + timeOfDay;
32
+ };
33
+
34
+ /**
35
+ * The first monthly renewal strictly after `nowArg` (epoch milliseconds), as epoch milliseconds, from the anchor
36
+ * `anchorArg` (`isAuthSwitchRenewsAt`). An anchor still ahead is itself the next renewal. Every renewal is computed from
37
+ * the anchor, never from the renewal before it: the anchor's UTC day, clamped to the month's last day, at the anchor's
38
+ * UTC time, so an anchor on January 31st renews on February 28th (29th in a leap year) and again on March 31st.
39
+ * Throws for an anchor the rule refuses or a `nowArg` that is not a finite number.
40
+ */
41
+ export const authSwitchNextRenewal = (anchorArg: string, nowArg: number): number => {
42
+ if (!isAuthSwitchRenewsAt(anchorArg) || !Number.isFinite(nowArg)) throw new Error('Invalid renewal anchor or time.');
43
+ const anchor = new Date(Date.parse(anchorArg));
44
+ if (anchor.getTime() > nowArg) return anchor.getTime();
45
+ const now = new Date(nowArg);
46
+ // The whole months between the two, less one, lie at or before now; count up from there.
47
+ let months = Math.max(0, (now.getUTCFullYear() - anchor.getUTCFullYear()) * 12
48
+ + now.getUTCMonth() - anchor.getUTCMonth() - 1);
49
+ while (renewalAfter(anchor, months) <= nowArg) months += 1;
50
+ return renewalAfter(anchor, months);
51
+ };
52
+
53
+ /** An account's next renewal as the account lists and `agl proxy status` show it; `source` says who set it. */
54
+ export interface IAuthSwitchRenewal {
55
+ /** The next renewal, ISO 8601 UTC (`authSwitchNextRenewal`). */
56
+ at: string;
57
+ /** `manual`: the owner set the anchor. AGL derives no renewal, so there is no other source. */
58
+ source: 'manual';
59
+ }
60
+
61
+ /** The next renewal of an account with the anchor `renewsAtArg` at `nowArg`, or `null` without an anchor. */
62
+ export const authSwitchRenewal = (renewsAtArg: string | null, nowArg: number): IAuthSwitchRenewal | null =>
63
+ renewsAtArg === null ? null
64
+ : { at: new Date(authSwitchNextRenewal(renewsAtArg, nowArg)).toISOString(), source: 'manual' };
@@ -10,6 +10,7 @@ import { AuthSwitchRefusal, authSwitchKeyHint, isAuthSwitchReserveLiftHours, isA
10
10
  import { authSwitchApiKeyOtherProvider, authSwitchApiKeyProviderNames, authSwitchApiKeyVerifier,
11
11
  type TAuthSwitchApiKeyVerdict, type TAuthSwitchApiKeyVerifier } from './authority-apikeys.js';
12
12
  import { isAuthSwitchSpendLimitMicroUsd } from './authority-spend.js';
13
+ import { isAuthSwitchRenewsAt } from './authority-renewal.js';
13
14
  import { AuthSwitchAuthorityDatabase, authorityBindPurpose, authSwitchBindPurposes, type TAuthSwitchBindPurpose,
14
15
  type TStoredNativeHome } from './classes.authoritydatabase.js';
15
16
  import { authorityApiKeyProvider, type IStoredAuthorityAccount, type IStoredAuthorityBinding,
@@ -156,7 +157,8 @@ const notOnApiKey = 'An API key account has no usage windows to keep a reserve o
156
157
  const publicAccount = (account: IStoredAuthorityAccount): IAuthSwitchAccount => ({
157
158
  id: account.id, providerId: account.providerId, label: account.label, email: account.email,
158
159
  plan: account.plan, organizationId: account.workspaceId, maxUsagePercent: account.maxUsagePercent, reserveLiftUntil: account.reserveLiftUntil,
159
- lapsesAt: account.lapsesAt, spendLimitMicroUsd: account.spendLimitMicroUsd, keyHint: account.keyHint, claudeCode: account.claudeCode,
160
+ lapsesAt: account.lapsesAt, renewsAt: account.renewsAt ?? null, spendLimitMicroUsd: account.spendLimitMicroUsd,
161
+ keyHint: account.keyHint, claudeCode: account.claudeCode,
160
162
  removed: account.removed, revision: account.revision, statusObservedAt: account.statusObservedAt,
161
163
  });
162
164
 
@@ -941,6 +943,37 @@ export class AuthSwitchAuthorityBroker {
941
943
  return publicAccount(updated.account);
942
944
  }
943
945
 
946
+ /**
947
+ * Sets or clears the anchor of a Claude sign-in's monthly renewal, as `setAccountLapse` sets its lapse date. The
948
+ * anchor is stored in its ISO 8601 UTC form; a past one is kept as given, since every renewal is a whole number of
949
+ * months after it. Only an account on a Claude sign-in has one; any other account is refused as `invalid_input`.
950
+ * The stored record carries `renewsAt` only while it is set: clearing removes the member, so an account that never
951
+ * had one is the record an earlier accounts service reads.
952
+ */
953
+ public async setAccountRenewal(accountId: string, expectedRevision: number,
954
+ renewsAt: string | null): Promise<IAuthSwitchAccount> {
955
+ if (!isId(accountId) || !validRevision(expectedRevision)) throw new Error('Invalid account change.');
956
+ if (renewsAt !== null && !isAuthSwitchRenewsAt(renewsAt)) {
957
+ // Spelled out like the lapse rule: an owner-facing instruction carries no bare number.
958
+ throw new AuthSwitchRefusal('invalid_input', 'An account\'s renewal is a date and time written year first, '
959
+ + 'as an ISO date is. Choose another value, or clear it.');
960
+ }
961
+ const stored = renewsAt === null ? null : new Date(Date.parse(renewsAt)).toISOString();
962
+ const updateId = plugins.crypto.randomUUID();
963
+ const updated = await this.database.changeAccount(updateId, accountId, account => {
964
+ if (!account || account.removed || account.revision !== expectedRevision) throw new AuthSwitchRefusal('account_changed', 'Account changed; refresh before editing.');
965
+ if (account.providerId !== 'anthropic' || isApiKeyAccount(account)) {
966
+ throw new AuthSwitchRefusal('invalid_input', 'Only an account on a Claude sign-in has a monthly renewal to '
967
+ + 'set.');
968
+ }
969
+ const { renewsAt: _previous, ...rest } = account;
970
+ return { ...rest, ...(stored === null ? {} : { renewsAt: stored }), revision: account.revision + 1, updateId,
971
+ statusObservedAt: new Date(this.now()).toISOString() };
972
+ });
973
+ this.publish();
974
+ return publicAccount(updated.account);
975
+ }
976
+
944
977
  /** Refuses a removal that would not go ahead, changing nothing; `removeAccount` refuses the same. */
945
978
  public async assertAccountRemovable(accountId: string, expectedRevision: number): Promise<void> {
946
979
  if (!isId(accountId) || !validRevision(expectedRevision)) throw new Error('Invalid account change.');