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
@@ -1,42 +1,136 @@
1
- import type {
2
- IControllerEvent,
3
- IControllerMessageBundle,
4
- IControllerPermission,
5
- IControllerQuestion,
6
- IControllerRuntimeId,
7
- IControllerSessionFeedRow,
8
- TControllerElicitation,
9
- TControllerEventType,
10
- TControllerSessionFeedDelta,
1
+ import * as plugins from './plugins.js';
2
+ import {
3
+ controllerOperationFailedErrorCode,
4
+ proxyCapacityProviders,
5
+ type IControllerAuthorityProjection,
6
+ type IControllerDevice,
7
+ type IControllerDriverStatus,
8
+ type IControllerEvent,
9
+ type IControllerFleetWorkerView,
10
+ type IControllerGatewayStatus,
11
+ type IControllerInboxDeployGo,
12
+ type IControllerInboxSnapshot,
13
+ type IControllerMessageBundle,
14
+ type IControllerPermission,
15
+ type IControllerQuestion,
16
+ type IControllerRuntimeId,
17
+ type IControllerSessionFeedRow,
18
+ type IDirectReportView,
19
+ type IFleetDeployPlan,
20
+ type IFleetDeployStatus,
21
+ type IFleetDeployTargetStatus,
22
+ type IFleetDeployTicketPlacement,
23
+ type IProxyCapacityAnswer,
24
+ type IProxyCapacityMember,
25
+ type ITicket,
26
+ type ITicketBoard,
27
+ type ITicketComment,
28
+ type ITicketFilters,
29
+ type ITicketPerson,
30
+ type ITicketQuestion,
31
+ type TControllerAccountLogin,
32
+ type TControllerAccountsAnswer,
33
+ type TControllerAccountUsage,
34
+ type TControllerAuthorityDaemonState,
35
+ type TControllerElicitation,
36
+ type TControllerDriverErrorCode,
37
+ type TControllerEventType,
38
+ type TControllerGatewayState,
39
+ type TControllerInboxDelta,
40
+ type TControllerInboxItem,
41
+ type TControllerInboxWhere,
42
+ type TControllerSessionFeedDelta,
43
+ type IFleetWorkerJob,
11
44
  } from '../ts_interfaces/index.js';
12
45
  import {
13
46
  deviceLabelMaximumCharacters,
14
47
  deviceMessageMaximumBytes,
48
+ deviceTicketDiscussionPage,
49
+ deviceTicketRefusalCodes,
50
+ type IDeviceApiKeyGroup,
51
+ type IDeviceDeployGo,
52
+ type IDeviceDeployPlan,
53
+ type IDeviceDeployTarget,
54
+ type IDeviceDirectReport,
55
+ type IDeviceDriverStatus,
56
+ type IDeviceHostAgl,
57
+ type IDeviceHostApiKeys,
58
+ type IDeviceHostDeploys,
59
+ type IDeviceHostDevice,
60
+ type IDeviceHostPools,
61
+ type IDeviceHostUnavailable,
62
+ type IDevicePoolMember,
63
+ type IDeviceInboxDelta,
15
64
  type IDeviceMessage,
16
65
  type IDevicePermission,
66
+ type IDeviceTicketQuestion,
67
+ type IReq_DeviceInboxList,
68
+ type IReq_DeviceTicketAnswer,
69
+ type TDeviceInboxAnswer,
70
+ type TDeviceInboxItem,
71
+ type TDeviceInboxWhere,
17
72
  type IDeviceQuestion,
18
73
  type IDeviceSessionFeedDelta,
19
74
  type IDeviceSessionRow,
75
+ type IDeviceTicket,
76
+ type IDeviceTicketCard,
77
+ type IDeviceTicketComment,
78
+ type IDeviceTicketPerson,
79
+ type IDeviceTicketPlacement,
80
+ type IDeviceTicketPlans,
20
81
  type IReq_DeviceAuthChallenge,
21
82
  type IReq_DeviceAuthProve,
83
+ type IReq_DeviceBoardList,
84
+ type IReq_DeviceDirectReportMessage,
85
+ type IReq_DeviceDriverRead,
86
+ type IReq_DeviceDriverSend,
22
87
  type IReq_DeviceElicitationReply,
88
+ type IReq_DeviceHostGet,
23
89
  type IReq_DevicePair,
24
90
  type IReq_DevicePermissionReply,
25
91
  type IReq_DeviceQuestionReply,
26
92
  type IReq_DeviceSessionRead,
27
93
  type IReq_DeviceSessionSend,
94
+ type IReq_DeviceTicketAsk,
95
+ type IReq_DeviceTicketComment,
96
+ type IReq_DeviceTicketGet,
97
+ type IReq_DeviceTicketMove,
98
+ type TDeviceAccountProvider,
99
+ type TDeviceAssigneeFilter,
28
100
  type TDeviceEvent,
29
101
  type TDeviceElicitation,
102
+ type TDeviceGatewayState,
103
+ type TDeviceHostUnavailableReason,
104
+ type TDeviceRefusalCode,
30
105
  type TDeviceMessagePart,
106
+ type TDeviceTicketColumn,
107
+ type TDeviceTicketRefusalCode,
31
108
  } from '../ts_interfaces/devices.js';
32
109
  import { isControllerSessionFeedRowId } from '../ts_interfaces/sessionfeed.js';
33
- import { assertElicitationReply, assertKeys, assertObject, assertQuestionAnswers } from './classes.validation.js';
110
+ import { assertDirectReportMessageRequest, assertElicitationReply, assertKeys, assertObject, assertQuestionAnswers } from './classes.validation.js';
34
111
  import { sessionFeedRowId } from './classes.sessionfeed.js';
112
+ import { directReportReachable, directReportRuntimeId } from './driver/classes.directreports.js';
113
+ import { DriverError, type DriverService, type IDriverNeedsInput } from './driver/classes.driverservice.js';
114
+ import { deviceRefusal } from './classes.controllerdevices.js';
115
+ import { controllerFailureJournal } from './classes.failurejournal.js';
116
+ import { DeployError } from './fleet/classes.deploymonitor.js';
117
+ import { AglProxyOutdatedError, AglProxyRefusedError, AglProxyUnavailableError } from './classes.proxycontrolclient.js';
118
+ import { TicketError, ticketBoardNarrows, ticketFilter, type ITicketBoardNarrowing, type TTicketErrorCode } from './classes.ticketstore.js';
119
+ import { assertTicketRequest } from './functions.ticketvalidation.js';
120
+ import { ticketColumns, ticketAutoLabels, type ticketErrorMessages } from '../ts_interfaces/tickets.js';
121
+ import type { TAuthErrorCode } from './interfaces.auth.js';
122
+ import { configurationErrorCodes, type TConfigurationErrorCode } from './configuration/classes.configurationerror.js';
123
+ import type { ControllerElicitationReplyError } from './functions.elicitation.js';
124
+ import type { FleetNativeTurnError } from './fleet/interfaces.workers.js';
125
+ import type { TClaudeDispatchRefusal } from './classes.claudeharness.js';
126
+ import type { INativeSessionFailedErrorData } from './classes.nativesessions.js';
35
127
 
36
128
  /*
37
129
  * The device API's requests and projections: what a device may ask, checked before anything is read, and the reduced
38
130
  * shapes of what it gets. A device sees the session feed without host paths, tickets or terminals, transcripts with
39
- * tool calls reduced to name, title and status, and an allowlist of events.
131
+ * tool calls reduced to name, title and status, the driver's status without its project or session, direct reports
132
+ * by name, the host's status without anything that names an account, a key or a probe's address, the shared board
133
+ * with people by name (the owner as `owner`) and sessions only as the feed lists them, and an allowlist of events.
40
134
  */
41
135
 
42
136
  /** The controller events a device receives, each projected by `deviceEvent`; every other event never reaches one. */
@@ -48,8 +142,632 @@ export const deviceRelayedEventTypes: ReadonlySet<TControllerEventType> = new Se
48
142
  'permissions.changed',
49
143
  'session.text.updated',
50
144
  'session.text.delta',
145
+ 'inbox.changed',
146
+ 'driver.changed',
147
+ 'directreports.changed',
148
+ 'fleet.workers.changed',
149
+ 'tickets.changed',
150
+ 'deployments.changed',
151
+ 'accounts.changed',
51
152
  ]);
52
153
 
154
+ /** Every refusal code of the device contract, once: what a device request may be refused with as it is. */
155
+ export const deviceRefusalCodes: ReadonlySet<string> = new Set([...Object.keys({
156
+ device_unknown: true,
157
+ device_pairing_invalid: true,
158
+ device_pairing_unavailable: true,
159
+ device_limit: true,
160
+ device_already_paired: true,
161
+ device_proof_invalid: true,
162
+ device_challenge_invalid: true,
163
+ device_authentication_required: true,
164
+ session_not_found: true,
165
+ session_read_only: true,
166
+ driver_absent: true,
167
+ direct_report_failed: true,
168
+ direct_report_busy: true,
169
+ rate_limited: true,
170
+ invalid_request: true,
171
+ controller_unavailable: true,
172
+ operation_limit: true,
173
+ concurrent_change: true,
174
+ outcome_unknown: true,
175
+ controller_failed: true,
176
+ } satisfies Record<Exclude<TDeviceRefusalCode, TDeviceTicketRefusalCode>, true>), ...deviceTicketRefusalCodes]);
177
+
178
+ /**
179
+ * Every code the controller refuses a device's request with before the device error translation: the codes of the
180
+ * typed errors `asTypedResponseError` passes on as their own (the auth store's, the configuration authority's, an
181
+ * elicitation reply's, a native Codex turn's), the codes it gives the others (`controller_operation_failed` for a fault
182
+ * under a failure journal reference), and the codes the browser's shared functions a device runs refuse with (session
183
+ * reads and sends, native sessions, answers, direct children).
184
+ */
185
+ export type TControllerRefusalCode =
186
+ | TAuthErrorCode
187
+ | TConfigurationErrorCode
188
+ | ControllerElicitationReplyError['code']
189
+ | FleetNativeTurnError['code']
190
+ | typeof controllerOperationFailedErrorCode
191
+ | 'concurrent_change'
192
+ | 'operation_limit'
193
+ | 'session_not_found'
194
+ | 'outcome_unknown'
195
+ | 'flex_not_ready'
196
+ | 'flex_operation_failed'
197
+ | 'flex_projection_not_found'
198
+ | 'flex_projection_cursor_invalid'
199
+ | 'flex_projection_invalid'
200
+ | 'controller_unavailable'
201
+ | 'invalid_request'
202
+ | 'rate_limited'
203
+ | 'session_read_only'
204
+ | 'project_not_found'
205
+ | 'harness_unavailable'
206
+ | 'native_session_failed'
207
+ | 'not_found'
208
+ | 'child_scope_invalid'
209
+ | 'model_not_found'
210
+ | 'model_harness_mismatch'
211
+ | 'attachments_unsupported'
212
+ | 'message_rate_limited';
213
+
214
+ /** A controller refusal's device code, by its code alone or, where its data says more, by its data. */
215
+ type TDeviceRefusalOf = TDeviceRefusalCode | ((errorDataArg: Readonly<Record<string, unknown>>) => TDeviceRefusalCode);
216
+
217
+ /** A native send Claude Code refused before it went out because it was busy: nothing was sent, so read again. */
218
+ const deviceClaudeDispatchRefusals: Readonly<Record<TClaudeDispatchRefusal, TDeviceRefusalCode>> = {
219
+ // The conversation still works on a turn: another change to the same session runs.
220
+ busy: 'concurrent_change',
221
+ // As many Claude Code conversations work as the host runs: the controller's operation limit.
222
+ capacity: 'operation_limit',
223
+ };
224
+
225
+ /**
226
+ * A failed native session operation in the device contract: unless it says nothing reached the session (`refused`), the
227
+ * send or answer may have happened; a refusal a busy conversation or host caused is that state, any other a fault.
228
+ */
229
+ const deviceNativeSessionFailure = (errorDataArg: Readonly<Partial<Record<keyof INativeSessionFailedErrorData, unknown>>>): TDeviceRefusalCode => {
230
+ if (errorDataArg.outcome !== 'refused') return 'outcome_unknown';
231
+ const refusal = errorDataArg.refusal;
232
+ return typeof refusal === 'string' && Object.hasOwn(deviceClaudeDispatchRefusals, refusal)
233
+ ? deviceClaudeDispatchRefusals[refusal as TClaudeDispatchRefusal] : 'controller_failed';
234
+ };
235
+
236
+ /**
237
+ * How every controller code outside the device contract reaches a device: the one table the device error translation
238
+ * reads, so the compiler names every code a new controller refusal adds before a device can meet it. A state of the
239
+ * controller is `controller_unavailable`; a race AGL lost before it acted `concurrent_change`; a dispatch that may have
240
+ * happened `outcome_unknown`; a session the device can no longer reach `session_not_found`; a refusal the owner resolves
241
+ * in the browser `session_read_only`; and a fault, or a refusal of a request no device makes, `controller_failed` with
242
+ * the failure journal's reference.
243
+ */
244
+ export const deviceControllerRefusals: Readonly<Record<Exclude<TControllerRefusalCode, TDeviceRefusalCode>, TDeviceRefusalOf>> = {
245
+ // The auth store and the audit trail every device operation writes.
246
+ not_initialized: 'controller_unavailable',
247
+ config_mismatch: 'controller_failed',
248
+ setup_unavailable: 'controller_failed',
249
+ setup_invalid: 'controller_failed',
250
+ setup_expired: 'controller_failed',
251
+ ceremony_limit: 'controller_failed',
252
+ ceremony_invalid: 'controller_failed',
253
+ ceremony_replayed: 'controller_failed',
254
+ ceremony_expired: 'controller_failed',
255
+ origin_mismatch: 'controller_failed',
256
+ peer_mismatch: 'controller_failed',
257
+ verification_failed: 'controller_failed',
258
+ credential_not_found: 'controller_failed',
259
+ // A write whose commit AGL could not confirm.
260
+ ambiguous_write: 'outcome_unknown',
261
+ counter_conflict: 'controller_failed',
262
+ // A project that went away under the session a device names.
263
+ invalid_project: 'session_not_found',
264
+ invalid_resource: 'controller_failed',
265
+ invalid_settings: 'controller_failed',
266
+ temp_password_invalid: 'controller_failed',
267
+ temp_password_limit: 'controller_failed',
268
+ // The configuration authority the driver, the direct reports and the deploy monitor read.
269
+ invalid_argument: 'controller_failed',
270
+ conflict: 'concurrent_change',
271
+ // A prompt answered or withdrawn meanwhile (a native session's, an elicitation's), or a configuration record gone.
272
+ not_found: 'concurrent_change',
273
+ unsupported: 'controller_failed',
274
+ unbound: 'controller_unavailable',
275
+ unauthorized: 'controller_failed',
276
+ unavailable: 'controller_unavailable',
277
+ // A Codex turn that ended, or that another client runs, before the message reached it: nothing was sent.
278
+ turn_ended: 'concurrent_change',
279
+ delivery_unsupported: 'concurrent_change',
280
+ controller_operation_failed: 'controller_failed',
281
+ // The Flex harness: starting or recovering is a state; a page cursor it no longer knows is the device's to drop.
282
+ flex_not_ready: 'controller_unavailable',
283
+ flex_operation_failed: 'controller_failed',
284
+ flex_projection_not_found: 'session_not_found',
285
+ flex_projection_cursor_invalid: 'invalid_request',
286
+ flex_projection_invalid: 'controller_failed',
287
+ project_not_found: 'session_not_found',
288
+ harness_unavailable: 'controller_unavailable',
289
+ // A native session's failure says whether a send or an answer may have happened; without that, it may have.
290
+ native_session_failed: deviceNativeSessionFailure,
291
+ child_scope_invalid: 'session_not_found',
292
+ model_not_found: 'session_read_only',
293
+ model_harness_mismatch: 'session_read_only',
294
+ attachments_unsupported: 'session_read_only',
295
+ message_rate_limited: 'rate_limited',
296
+ };
297
+
298
+ /**
299
+ * The controller codes whose message may carry a raw cause (a socket path, a spawn error, a dependency's own text): a
300
+ * native session's failure, an unavailable harness's diagnostic, and the configuration authority's refusals. A device
301
+ * gets the sentence of the device code they map to instead (`deviceRefusalSentences`); the cause stays in the log.
302
+ */
303
+ const deviceRawTextCodes: ReadonlySet<string> = new Set<TControllerRefusalCode>(['native_session_failed', 'harness_unavailable', ...configurationErrorCodes]);
304
+
305
+ /** What a device reads for `outcome_unknown` in place of a message that may carry a raw cause. */
306
+ const deviceOutcomeUnknownSentence = 'The request may have taken effect. Read again to learn whether it did before sending it again.';
307
+
308
+ /** The device's own sentence for a refusal whose controller message may carry a raw cause. */
309
+ const deviceRefusalSentences: Readonly<Partial<Record<TDeviceRefusalCode, string>>> = {
310
+ outcome_unknown: deviceOutcomeUnknownSentence,
311
+ concurrent_change: 'Something else changed this at the same time, and nothing was done. Read it again, then decide.',
312
+ operation_limit: 'The controller is busy. Try again once current work has finished.',
313
+ controller_unavailable: 'The controller cannot do this now. Try again later.',
314
+ // Only for a refusal of `deviceRawTextCodes`, which says the message did not go out.
315
+ direct_report_failed: 'The direct report did not take the message.',
316
+ };
317
+
318
+ /** What a device reads for `controller_failed`: the cause is the failure journal's, under the reference beside it. */
319
+ const deviceControllerFailedSentence = 'The controller operation failed.';
320
+
321
+ /** A controller refusal's code in the device contract: as it is where the contract has it, else by the table. */
322
+ const deviceRefusalCodeOf = (codeArg: unknown, errorDataArg: Readonly<Record<string, unknown>>): TDeviceRefusalCode | undefined => {
323
+ if (typeof codeArg !== 'string') return undefined;
324
+ if (deviceRefusalCodes.has(codeArg)) return codeArg as TDeviceRefusalCode;
325
+ if (!Object.hasOwn(deviceControllerRefusals, codeArg)) return undefined;
326
+ const refusal = deviceControllerRefusals[codeArg as keyof typeof deviceControllerRefusals];
327
+ return typeof refusal === 'function' ? refusal(errorDataArg) : refusal;
328
+ };
329
+
330
+ /**
331
+ * The device error translation: the refusal a device receives for the typed refusal `typedArg` the controller answers
332
+ * `causeArg` with, always a code of the device contract. A contract code passes as it is; every other code maps through
333
+ * `deviceControllerRefusals`, with the controller's message, or the device code's own sentence where that message may
334
+ * carry a raw cause (`deviceRawTextCodes`). A fault, and a code the table does not know, is `controller_failed` with one
335
+ * fixed sentence and the failure journal's reference: the controller's own when it kept the cause, else one recorded
336
+ * here for `methodArg`.
337
+ */
338
+ export const deviceContractError = (
339
+ typedArg: plugins.typedrequest.TypedResponseError,
340
+ causeArg: unknown,
341
+ methodArg: string,
342
+ ): plugins.typedrequest.TypedResponseError => {
343
+ const errorData: Readonly<Record<string, unknown>> = typeof typedArg.errorData === 'object' && typedArg.errorData !== null
344
+ ? typedArg.errorData as Record<string, unknown> : {};
345
+ const code = deviceRefusalCodeOf(errorData.code, errorData);
346
+ if (code !== undefined && code !== 'controller_failed') {
347
+ if (code === errorData.code) return typedArg;
348
+ return deviceRefusal(code, typeof errorData.code === 'string' && deviceRawTextCodes.has(errorData.code)
349
+ ? deviceRefusalSentences[code] ?? 'AGL refused the request.' : typedArg.errorText);
350
+ }
351
+ let reference = errorData.reference;
352
+ if (typeof reference !== 'string') {
353
+ reference = controllerFailureJournal.record({ operation: methodArg, cause: causeArg });
354
+ console.error(`A device's ${methodArg} failed (ref ${reference}):`, causeArg);
355
+ }
356
+ return new plugins.typedrequest.TypedResponseError(deviceControllerFailedSentence, { code: 'controller_failed' satisfies TDeviceRefusalCode, reference });
357
+ };
358
+
359
+ /** The code a typed refusal carries, if any. */
360
+ const typedResponseErrorCode = (errorArg: unknown): unknown => (
361
+ errorArg instanceof plugins.typedrequest.TypedResponseError ? (errorArg.errorData as { code?: unknown } | undefined)?.code : undefined
362
+ );
363
+
364
+ /** How a driver error reaches a device: as a code of the device contract, never as the browser's own. */
365
+ const deviceDriverErrorRefusals: Record<TControllerDriverErrorCode, TDeviceRefusalCode> = {
366
+ // The Flex harness or the configuration authority is not available: a state of the controller, as for any request.
367
+ DRIVER_UNAVAILABLE: 'controller_unavailable',
368
+ // No driver project, so no driver session; a device never creates one.
369
+ DRIVER_PROJECT_REQUIRED: 'driver_absent',
370
+ // An operation the driver session never takes: a device asks none.
371
+ DRIVER_SESSION_PROTECTED: 'invalid_request',
372
+ };
373
+
374
+ /**
375
+ * Runs a device's driver request and answers its failures in the device contract: a driver error by its device code,
376
+ * and a driver project or session that went away after the status named it as `driver_absent`. Every other failure is
377
+ * the session read's or send's own, as `device.session.read` and `device.session.send` answer it.
378
+ */
379
+ export const serveDeviceDriver = async <T>(operationArg: () => Promise<T>): Promise<T> => {
380
+ try {
381
+ return await operationArg();
382
+ } catch (errorArg) {
383
+ if (errorArg instanceof DriverError) throw deviceRefusal(deviceDriverErrorRefusals[errorArg.code], errorArg.message);
384
+ const code = typedResponseErrorCode(errorArg);
385
+ if (code === 'project_not_found' || code === 'session_not_found') {
386
+ throw deviceRefusal('driver_absent', 'The driver session is gone; the owner starts the driver in the browser.');
387
+ }
388
+ throw errorArg;
389
+ }
390
+ };
391
+
392
+ /**
393
+ * A failure of the owner's message to a direct report, in the device contract: another Codex client's turn is
394
+ * `direct_report_busy` (a device reads no turn to name), the agent message rate `rate_limited` (final, as for every
395
+ * device request), and every other refusal outside the contract `direct_report_failed` with its text and the failure
396
+ * journal's reference, where AGL kept the cause; a refusal whose message may carry a raw cause (`deviceRawTextCodes`)
397
+ * reads `deviceRefusalSentences.direct_report_failed` instead, its message kept in the failure journal. Other failures
398
+ * are answered as `serveDirectReport` answers them.
399
+ */
400
+ export const deviceDirectReportMessageRefusal = (errorArg: unknown): unknown => {
401
+ if (!(errorArg instanceof plugins.typedrequest.TypedResponseError)) return errorArg;
402
+ const code = typedResponseErrorCode(errorArg);
403
+ if (code === 'delivery_unsupported') {
404
+ return deviceRefusal('direct_report_busy', 'Another Codex client runs this report\'s turn, which a device does not steer; nothing was sent. Send it again once the turn ended.');
405
+ }
406
+ if (code === 'message_rate_limited') return deviceRefusal('rate_limited', errorArg.errorText);
407
+ if (typeof code === 'string' && deviceRefusalCodes.has(code)) return errorArg;
408
+ // A message that may have reached the report is never `direct_report_failed`, which says it took none.
409
+ if (deviceRefusalCodeOf(code, errorArg.errorData as Readonly<Record<string, unknown>>) === 'outcome_unknown') {
410
+ return deviceContractError(errorArg, errorArg, 'device.directreport.message');
411
+ }
412
+ if (typeof code === 'string' && deviceRawTextCodes.has(code)) {
413
+ const reference = controllerFailureJournal.record({ operation: 'device.directreport.message', cause: errorArg });
414
+ console.error(`A device's direct report message failed (ref ${reference}):`, errorArg);
415
+ return new plugins.typedrequest.TypedResponseError(`${deviceRefusalSentences.direct_report_failed} (ref ${reference})`,
416
+ { code: 'direct_report_failed' satisfies TDeviceRefusalCode });
417
+ }
418
+ const reference = code === controllerOperationFailedErrorCode ? (errorArg.errorData as { reference?: unknown }).reference : undefined;
419
+ return deviceRefusal('direct_report_failed', `${errorArg.errorText}${typeof reference === 'string' ? ` (ref ${reference})` : ''}`.slice(0, 4096));
420
+ };
421
+
422
+ /**
423
+ * A device's refusal of its message to a direct report whose fleet job failed. A job that may have delivered the
424
+ * message (`IFleetWorkerJob.errorOutcome` other than `refused`: the steer failed after its dispatch, or nothing proves
425
+ * it did not) is `outcome_unknown`, which a client never sends again on its own, never `direct_report_failed`, which
426
+ * says the report took no message. A job that sent nothing is `direct_report_failed`: a refusal the fleet wrote itself
427
+ * (`errorCode`) with its text, any other with the controller's generic sentence. Where the device does not read the
428
+ * job's error, the failure journal keeps it under the reference the message ends with, as the Driver view shows it.
429
+ */
430
+ export const deviceDirectReportJobRefusal = (jobArg: IFleetWorkerJob): plugins.typedrequest.TypedResponseError => {
431
+ const delivered = jobArg.errorOutcome !== 'refused';
432
+ if (!delivered && jobArg.errorCode !== undefined && jobArg.error !== undefined) return deviceRefusal('direct_report_failed', jobArg.error.slice(0, 4096));
433
+ const cause = jobArg.error ?? 'The fleet job failed without an error.';
434
+ const reference = controllerFailureJournal.record({ operation: 'device.directreport.message', cause });
435
+ console.error(`A device's direct report message failed in fleet job ${jobArg.id} (ref ${reference}):`, cause);
436
+ return delivered ? deviceRefusal('outcome_unknown', `${deviceOutcomeUnknownSentence} (ref ${reference})`)
437
+ : deviceRefusal('direct_report_failed', `${deviceControllerFailedSentence} (ref ${reference})`);
438
+ };
439
+
440
+ /**
441
+ * How the ticket store's refusals outside `ticketErrorMessages` reach a device: a concurrent change the transaction lost
442
+ * wrote nothing and reads as the board having changed meanwhile; a commit whose outcome is unknown may have happened,
443
+ * which a client never resends but reads the ticket again to learn; a fleet event's conflict and an owner capability the
444
+ * controller could not verify answer no device request.
445
+ */
446
+ const deviceTicketStoreRefusals: Readonly<Record<Exclude<TTicketErrorCode, keyof typeof ticketErrorMessages>, TDeviceRefusalCode>> = {
447
+ concurrent_change: 'ticket_revision_conflict',
448
+ outcome_unknown: 'outcome_unknown',
449
+ ticket_fleet_event_conflict: 'invalid_request',
450
+ unauthorized: 'invalid_request',
451
+ };
452
+
453
+ const deviceTicketCodes: ReadonlySet<string> = new Set(deviceTicketRefusalCodes);
454
+
455
+ /**
456
+ * A refusal of a device's ticket request in the device contract, whether the store's own (`TicketError`) or as the
457
+ * browser's ticket functions answer it: the store's codes `deviceTicketRefusalCodes` lists as they are, with the
458
+ * store's reason, and its other codes by `deviceTicketStoreRefusals`. Every other failure is answered as any device
459
+ * request's.
460
+ */
461
+ export const deviceTicketRefusal = (errorArg: unknown): unknown => {
462
+ const [code, text] = errorArg instanceof TicketError ? [errorArg.code, errorArg.message]
463
+ : errorArg instanceof plugins.typedrequest.TypedResponseError ? [typedResponseErrorCode(errorArg), errorArg.errorText] : [undefined, ''];
464
+ if (typeof code !== 'string') return errorArg;
465
+ if (deviceTicketCodes.has(code)) {
466
+ return errorArg instanceof TicketError ? deviceRefusal(code as TDeviceTicketRefusalCode, text) : errorArg;
467
+ }
468
+ return Object.hasOwn(deviceTicketStoreRefusals, code)
469
+ ? deviceRefusal(deviceTicketStoreRefusals[code as keyof typeof deviceTicketStoreRefusals], text) : errorArg;
470
+ };
471
+
472
+ /** What a device event reads of the driver as it is sent: the controller's `DriverService`. */
473
+ export type TDeviceDriverSource = Pick<DriverService, 'isSessionChange' | 'current' | 'needsInput'>;
474
+
475
+ /**
476
+ * The driver's status as a device sees it: no project, no session, no failure or limit text. The `needs input:` line
477
+ * only while it is what the status's `needs_input` stands for.
478
+ */
479
+ export const deviceDriverStatus = (statusArg: IControllerDriverStatus, needsInputArg: IDriverNeedsInput | undefined): IDeviceDriverStatus => ({
480
+ activity: statusArg.activity,
481
+ unreadCount: statusArg.unreadCount,
482
+ ...(statusArg.session?.title ? { title: statusArg.session.title } : {}),
483
+ ...(statusArg.activity === 'needs_input' && needsInputArg !== undefined && needsInputArg.nativeId === statusArg.sessionId?.nativeId
484
+ ? { needsInput: needsInputArg.line } : {}),
485
+ updatedAt: statusArg.updatedAt,
486
+ });
487
+
488
+ /**
489
+ * A direct report as a device sees it, with the fleet workers that report to it: named, never by the report's stored
490
+ * id (which holds the configuration authority's id); the workers without their directories or profiles.
491
+ */
492
+ export const deviceDirectReport = (viewArg: IDirectReportView, workersArg: readonly IControllerFleetWorkerView[]): IDeviceDirectReport => {
493
+ const { report } = viewArg;
494
+ return {
495
+ name: report.name,
496
+ kind: report.session.kind,
497
+ harness: directReportRuntimeId(report).harnessId,
498
+ ...(viewArg.status === undefined ? {} : { status: viewArg.status }),
499
+ sessionId: report.sessionId,
500
+ projects: [...report.projects],
501
+ ticketKey: report.driverTicketKey,
502
+ ...(report.latestResult === undefined ? {} : { latestResult: { text: report.latestResult.text, at: Date.parse(report.latestResult.at) } }),
503
+ openQuestions: viewArg.openQuestions.map(({ ticketKey, project, question }) => ({ ticketKey, project, question: deviceTicketQuestion(question) })),
504
+ openQuestionCount: viewArg.openQuestionCount,
505
+ workers: workersArg.map(({ worker, status }) => ({
506
+ name: worker.name,
507
+ harness: worker.harness,
508
+ ...(status === undefined ? {} : { status }),
509
+ ...(worker.ticketKey === undefined ? {} : { ticketKey: worker.ticketKey }),
510
+ })),
511
+ messageable: directReportReachable(report),
512
+ };
513
+ };
514
+
515
+ /** Where the host's route on its gateway stands, in the device contract's words. */
516
+ const deviceGatewayStates: Readonly<Record<Exclude<TControllerGatewayState, 'not_enrolled'>, TDeviceGatewayState>> = {
517
+ finalize_pending: 'finalize_pending',
518
+ syncing: 'syncing',
519
+ synced: 'synced',
520
+ retrying: 'retrying',
521
+ waiting: 'waiting',
522
+ failed: 'failed',
523
+ stopped: 'stopped',
524
+ };
525
+
526
+ /**
527
+ * The AGL that runs, as a device sees it: its release, its start, its public origin, and how a device reaches it --
528
+ * through the gateway AGL keeps its route on, with where that route's sync stands (never the gateway's address, the
529
+ * client AGL is there or the route's target), or through the owner's own reverse proxy while AGL is enrolled with no
530
+ * gateway.
531
+ */
532
+ export const deviceHostAgl = (aglArg: {
533
+ version: string;
534
+ startedAt: number;
535
+ origin: string;
536
+ gateway: IControllerGatewayStatus | undefined;
537
+ }): IDeviceHostAgl => ({
538
+ version: aglArg.version,
539
+ startedAt: aglArg.startedAt,
540
+ origin: aglArg.origin,
541
+ reach: aglArg.gateway === undefined || aglArg.gateway.state === 'not_enrolled'
542
+ ? { kind: 'proxy' }
543
+ : { kind: 'gateway', state: deviceGatewayStates[aglArg.gateway.state] },
544
+ });
545
+
546
+ /** A device's own record as it reads it: no id, key or fingerprint, and nothing it could change. */
547
+ export const deviceHostDevice = (deviceArg: IControllerDevice): IDeviceHostDevice => ({
548
+ name: deviceArg.name,
549
+ model: deviceArg.model,
550
+ pairedAt: deviceArg.pairedAt,
551
+ ...(deviceArg.lastSeenAt === undefined ? {} : { lastSeenAt: deviceArg.lastSeenAt }),
552
+ });
553
+
554
+ /**
555
+ * A planned deploy as a device sees it: its ticket, the release and the owner's go, and the window it is queued into by
556
+ * its times alone. Never its question or who deploys it, a session of the host.
557
+ */
558
+ const deviceDeployPlan = (planArg: IFleetDeployPlan): IDeviceDeployPlan => ({
559
+ ticketKey: planArg.key,
560
+ title: planArg.title,
561
+ version: planArg.version,
562
+ go: planArg.go,
563
+ ...(planArg.window === undefined ? {} : { window: { from: Date.parse(planArg.window.from), to: Date.parse(planArg.window.to) } }),
564
+ });
565
+
566
+ /**
567
+ * A deploy target as a device sees it: what it runs, whether its probe answers, the releases it does not run and its
568
+ * planned deploys, never the probe's address, the owner's notes on how it deploys and what a deploy interrupts, or a
569
+ * failed probe's text. Its planned deploys are tickets, so `tickets.changed` tells a device of them as well as
570
+ * `deployments.changed`.
571
+ */
572
+ const deviceDeployTarget = (statusArg: IFleetDeployTargetStatus): IDeviceDeployTarget => {
573
+ const { target, running, probe, latest } = statusArg;
574
+ return {
575
+ id: target.id,
576
+ ...(target.name === undefined ? {} : { name: target.name }),
577
+ ...(target.environment === undefined ? {} : { environment: target.environment }),
578
+ repo: target.repo,
579
+ ...(running === undefined ? {} : {
580
+ running: {
581
+ version: running.version,
582
+ since: Date.parse(running.since),
583
+ ...(running.previousVersion === undefined ? {} : { previousVersion: running.previousVersion }),
584
+ rolledBack: running.rolledBack === true,
585
+ untagged: running.untagged === true,
586
+ },
587
+ }),
588
+ probe: probe.state,
589
+ ...(probe.checkedAt === undefined ? {} : { probedAt: Date.parse(probe.checkedAt) }),
590
+ ...(probe.downSince === undefined ? {} : { downSince: Date.parse(probe.downSince) }),
591
+ ...(latest === undefined ? {} : { latest: latest.version }),
592
+ undeployed: statusArg.notRunning.releases.map((releaseArg) => releaseArg.version),
593
+ deployWhen: statusArg.deployWhen,
594
+ plans: statusArg.deployPlans.map(deviceDeployPlan),
595
+ };
596
+ };
597
+
598
+ /** The deploy monitor's status of every target, as a device sees it. */
599
+ const deviceHostDeploys = (statusArg: IFleetDeployStatus): IDeviceHostDeploys => ({
600
+ state: 'ready',
601
+ checkedAt: Date.parse(statusArg.checkedAt),
602
+ targets: statusArg.targets.map(deviceDeployTarget),
603
+ });
604
+
605
+ /** A pool's account as a device sees it: its plan, its state and the window its room is bound by, never its id. */
606
+ const devicePoolMember = (memberArg: IProxyCapacityMember): IDevicePoolMember => ({
607
+ plan: memberArg.plan,
608
+ state: memberArg.state,
609
+ ...(memberArg.binding === null ? {} : {
610
+ window: {
611
+ name: memberArg.binding.name,
612
+ usedPercent: memberArg.binding.usedPercent,
613
+ estimated: memberArg.binding.estimated,
614
+ ...(memberArg.binding.resetAt === null ? {} : { resetAt: Date.parse(memberArg.binding.resetAt) }),
615
+ },
616
+ }),
617
+ });
618
+
619
+ /**
620
+ * A pool's accounts in the order a device lists them: by plan, then the most used first (one without a window last),
621
+ * then by everything else it shows. The order follows only what the device sees; the proxy's own order follows its
622
+ * accounts, so a position there would stand in for an account.
623
+ */
624
+ const devicePoolMemberOrder = (leftArg: IDevicePoolMember, rightArg: IDevicePoolMember): number => (
625
+ leftArg.plan.localeCompare(rightArg.plan, 'en')
626
+ || (rightArg.window?.usedPercent ?? -1) - (leftArg.window?.usedPercent ?? -1)
627
+ || leftArg.state.localeCompare(rightArg.state, 'en')
628
+ || (leftArg.window?.name ?? '').localeCompare(rightArg.window?.name ?? '', 'en')
629
+ || Number(leftArg.window?.estimated ?? false) - Number(rightArg.window?.estimated ?? false)
630
+ || (leftArg.window?.resetAt ?? 0) - (rightArg.window?.resetAt ?? 0)
631
+ );
632
+
633
+ /** The inference proxy's pools as a device sees them: anonymous accounts, and times as Unix milliseconds. */
634
+ const deviceHostPools = (answerArg: IProxyCapacityAnswer): IDeviceHostPools => ({
635
+ state: 'ready',
636
+ pools: answerArg.pools.map((poolArg) => ({
637
+ provider: poolArg.provider,
638
+ verdict: poolArg.verdict.state === 'open'
639
+ ? { state: 'open' }
640
+ : { state: 'wait', reason: poolArg.verdict.reason, ...(poolArg.verdict.until === null ? {} : { until: Date.parse(poolArg.verdict.until) }) },
641
+ room: poolArg.room,
642
+ members: poolArg.members.map(devicePoolMember).sort(devicePoolMemberOrder),
643
+ })),
644
+ });
645
+
646
+ /**
647
+ * The provider of an API key's login, or none for a sign-in. Every login purpose is named, so a new one is decided
648
+ * here rather than counted by default.
649
+ */
650
+ const apiKeyProviders: Readonly<Record<TControllerAccountLogin['purpose'], TDeviceAccountProvider | null>> = {
651
+ openai_managed: null,
652
+ claude_host_native: null,
653
+ claude_container_setup: null,
654
+ opencode_native: null,
655
+ anthropic_api_key: 'anthropic',
656
+ openai_api_key: 'openai',
657
+ };
658
+
659
+ /** Why the accounts service cannot be asked, in the device contract's words. */
660
+ const deviceAuthorityUnavailable: Readonly<Record<Exclude<TControllerAuthorityDaemonState, 'ready'>, TDeviceHostUnavailableReason>> = {
661
+ absent: 'not_running',
662
+ connecting: 'not_running',
663
+ incompatible: 'outdated',
664
+ outdated: 'outdated',
665
+ };
666
+
667
+ /** What `device.host.get` reads besides the AGL and the device, each section from its owner. */
668
+ export interface IDeviceHostSources {
669
+ /** The deploy monitor's status of every target, as the Deployments view reads it; never a probe. */
670
+ deployStatus: () => Promise<IFleetDeployStatus>;
671
+ /** The inference proxy's pools; absent while no proxy runs here. */
672
+ capacity: ((signalArg: AbortSignal) => Promise<IProxyCapacityAnswer>) | undefined;
673
+ /** The accounts service as the controller holds it. */
674
+ authority: () => IControllerAuthorityProjection;
675
+ /** The usage the accounts service holds for one login; it reads no provider for it. */
676
+ usage: (accountIdArg: string, loginIdArg: string, signalArg: AbortSignal) => Promise<TControllerAccountsAnswer<TControllerAccountUsage>>;
677
+ }
678
+
679
+ /**
680
+ * The host's API keys, counted per provider against their monthly spend limits by the rule the proxy places by
681
+ * (`authSwitchSpendPercent` is null without a limit; `authSwitchSpendExhausted` holds a key at it), from the month the
682
+ * accounts service holds for each key's login: never a label, an email, an account or key id, or a dollar amount. A
683
+ * key whose month was not read counts as `unread`.
684
+ */
685
+ const readDeviceApiKeys = async (sourcesArg: Pick<IDeviceHostSources, 'authority' | 'usage'>, nowArg: number,
686
+ signalArg: AbortSignal): Promise<IDeviceHostApiKeys | IDeviceHostUnavailable> => {
687
+ const authority = sourcesArg.authority();
688
+ if (authority.state !== 'ready') return { state: 'unavailable', reason: deviceAuthorityUnavailable[authority.state] };
689
+ const snapshot = authority.snapshot;
690
+ if (snapshot === null) return { state: 'unavailable', reason: 'not_running' };
691
+ const keys = snapshot.accounts.flatMap((accountArg) => {
692
+ const provider = accountArg.removed ? undefined : snapshot.logins
693
+ .map((loginArg) => (loginArg.accountId === accountArg.id ? apiKeyProviders[loginArg.purpose] : null))
694
+ .find((providerArg) => providerArg !== null);
695
+ return provider ? [{ provider, accountId: accountArg.id, login: plugins.authswitchOverview.authSwitchUsageLogin(snapshot, accountArg.id) }] : [];
696
+ });
697
+ const months = await Promise.all(keys.map(async ({ provider, accountId, login }) => {
698
+ const answer = login === null ? undefined : await sourcesArg.usage(accountId, login.id, signalArg);
699
+ const reading = answer?.state === 'done' ? answer.value.reading : null;
700
+ return { provider, spend: reading?.kind === 'spend' ? reading.spend : null };
701
+ }));
702
+ const groups = new Map<TDeviceAccountProvider, IDeviceApiKeyGroup>();
703
+ for (const { provider, spend } of months) {
704
+ const group = groups.get(provider) ?? { provider, within: 0, over: 0, unlimited: 0, unread: 0 };
705
+ groups.set(provider, group);
706
+ if (spend === null) {
707
+ group.unread += 1;
708
+ } else if (plugins.authswitchSpend.authSwitchSpendPercent(spend) === null) {
709
+ group.unlimited += 1;
710
+ } else if (plugins.authswitchSpend.authSwitchSpendExhausted(spend, nowArg)) {
711
+ group.over += 1;
712
+ const resetAt = Date.parse(spend.resetAt);
713
+ group.resetAt = group.resetAt === undefined ? resetAt : Math.min(group.resetAt, resetAt);
714
+ } else {
715
+ group.within += 1;
716
+ }
717
+ }
718
+ return { state: 'ready', groups: proxyCapacityProviders.flatMap((providerArg) => groups.get(providerArg) ?? []) };
719
+ };
720
+
721
+ /**
722
+ * Why a section's owner did not answer, when that is a state of the host rather than a fault: the configuration
723
+ * service the deploy monitor reads its targets from, or the inference proxy and the accounts service behind it.
724
+ */
725
+ const deviceHostUnavailableReason = (errorArg: unknown): Exclude<TDeviceHostUnavailableReason, 'failed'> | undefined => {
726
+ if (errorArg instanceof DeployError) return errorArg.code === 'deploy_unavailable' ? 'not_running' : undefined;
727
+ if (errorArg instanceof AglProxyUnavailableError) return 'not_running';
728
+ if (errorArg instanceof AglProxyRefusedError) return errorArg.code === 'authority_unavailable' ? 'not_running' : undefined;
729
+ if (errorArg instanceof AglProxyOutdatedError) return 'outdated';
730
+ return undefined;
731
+ };
732
+
733
+ /**
734
+ * Reads one section of a device's answer on its own (a section of the host's status, a ticket's placement): a state of
735
+ * the host is `unavailable` with its reason, and every other failure `failed`, its cause kept in the failure journal
736
+ * and the log under the reference the device gets. A request the device's connection or its revocation aborted fails
737
+ * as a whole. `operationArg` names the section in the journal, `whatArg` in the log.
738
+ */
739
+ const readDeviceSection = async <T>(operationArg: string, whatArg: string, signalArg: AbortSignal,
740
+ readArg: () => Promise<T | IDeviceHostUnavailable>): Promise<T | IDeviceHostUnavailable> => {
741
+ try {
742
+ return await readArg();
743
+ } catch (errorArg) {
744
+ if (signalArg.aborted) throw errorArg;
745
+ const reason = deviceHostUnavailableReason(errorArg);
746
+ if (reason !== undefined) return { state: 'unavailable', reason };
747
+ const reference = controllerFailureJournal.record({ operation: operationArg, cause: errorArg });
748
+ console.error(`Reading ${whatArg} for a device failed (ref ${reference}):`, errorArg);
749
+ return { state: 'unavailable', reason: 'failed', reference };
750
+ }
751
+ };
752
+
753
+ const readDeviceHostSection = <T>(sectionArg: string, signalArg: AbortSignal,
754
+ readArg: () => Promise<T | IDeviceHostUnavailable>): Promise<T | IDeviceHostUnavailable> => (
755
+ readDeviceSection(`device.host.get ${sectionArg}`, `the host's ${sectionArg}`, signalArg, readArg)
756
+ );
757
+
758
+ /** The host's deploy targets, account pools and API keys, read at once and each on its own. */
759
+ export const readDeviceHostSections = async (sourcesArg: IDeviceHostSources, nowArg: number, signalArg: AbortSignal):
760
+ Promise<Pick<IReq_DeviceHostGet['response'], 'deploys' | 'pools' | 'apiKeys'>> => {
761
+ const [deploys, pools, apiKeys] = await Promise.all([
762
+ readDeviceHostSection<IDeviceHostDeploys>('deploys', signalArg, async () => deviceHostDeploys(await sourcesArg.deployStatus())),
763
+ readDeviceHostSection<IDeviceHostPools>('pools', signalArg, async () => (
764
+ sourcesArg.capacity === undefined ? { state: 'unavailable', reason: 'not_running' } : deviceHostPools(await sourcesArg.capacity(signalArg))
765
+ )),
766
+ readDeviceHostSection<IDeviceHostApiKeys>('apiKeys', signalArg, () => readDeviceApiKeys(sourcesArg, nowArg, signalArg)),
767
+ ]);
768
+ return { deploys, pools, apiKeys };
769
+ };
770
+
53
771
  /** A feed row as a device sees it; none for a terminal row, which a device does not open. */
54
772
  export const deviceSessionRow = (rowArg: IControllerSessionFeedRow): IDeviceSessionRow | undefined => (
55
773
  rowArg.open.kind === 'terminal' ? undefined : {
@@ -140,6 +858,363 @@ export const deviceElicitations = (elicitationsArg: readonly TControllerElicitat
140
858
  }
141
859
  });
142
860
 
861
+ /** A ticket question as a device answers it: its options by id, and who asked and answered by name. */
862
+ export const deviceTicketQuestion = (questionArg: ITicketQuestion): IDeviceTicketQuestion => ({
863
+ id: questionArg.id,
864
+ question: questionArg.question,
865
+ options: questionArg.options.map(({ id, label, description }) => ({ id, label, ...(description === undefined ? {} : { description }) })),
866
+ multiSelect: questionArg.multiSelect,
867
+ allowCustom: questionArg.allowCustom,
868
+ askedBy: questionArg.askedBy.name,
869
+ createdAt: Date.parse(questionArg.createdAt),
870
+ ...(questionArg.answer === undefined ? {} : {
871
+ answer: {
872
+ choices: [...questionArg.answer.choices],
873
+ ...(questionArg.answer.text === undefined ? {} : { text: questionArg.answer.text }),
874
+ answeredBy: questionArg.answer.answeredBy.name,
875
+ answeredAt: Date.parse(questionArg.answer.answeredAt),
876
+ },
877
+ }),
878
+ });
879
+
880
+ /**
881
+ * What a device's ticket views read besides the tickets: the owner's principal id (`owner:<webauthnUserId>`), which
882
+ * names the owner's account and never reaches a device, and the session feed's published rows.
883
+ */
884
+ export interface IDeviceTicketViewer {
885
+ ownerId: string;
886
+ rowOf: (rowIdArg: string) => IControllerSessionFeedRow | undefined;
887
+ }
888
+
889
+ /**
890
+ * A person on a ticket as a device sees it: by name and kind, the owner as `kind` `owner` (never the owner's principal
891
+ * id), and a session only as the session feed names it while the feed lists it for devices, so never the driver's own
892
+ * session or one the feed does not list. A person's id never reaches a device.
893
+ */
894
+ export const deviceTicketPerson = (personArg: ITicketPerson, viewerArg: IDeviceTicketViewer): IDeviceTicketPerson => {
895
+ const row = personArg.sessionId === undefined ? undefined : viewerArg.rowOf(personArg.sessionId);
896
+ const kind = personArg.id === viewerArg.ownerId ? 'owner' : personArg.kind;
897
+ return {
898
+ name: personArg.name,
899
+ ...(kind === undefined ? {} : { kind }),
900
+ ...(row !== undefined && row.open.kind !== 'terminal' ? { sessionId: row.id } : {}),
901
+ };
902
+ };
903
+
904
+ /** The epic a ticket belongs to, when `parentArg`, the ticket its `parentId` names, is one. */
905
+ const deviceTicketEpic = (ticketArg: ITicket, parentArg: ITicket | undefined): { key: string; title: string } | undefined => (
906
+ parentArg !== undefined && parentArg.kind === 'epic' && ticketArg.parentId === parentArg.key ? { key: parentArg.key, title: parentArg.title } : undefined
907
+ );
908
+
909
+ /** A ticket as a device's card shows it; `parentArg` is the ticket its `parentId` names, when read. */
910
+ export const deviceTicketCard = (ticketArg: ITicket, parentArg: ITicket | undefined, viewerArg: IDeviceTicketViewer): IDeviceTicketCard => {
911
+ const epic = deviceTicketEpic(ticketArg, parentArg);
912
+ return {
913
+ key: ticketArg.key,
914
+ title: ticketArg.title,
915
+ kind: ticketArg.kind,
916
+ project: ticketArg.project,
917
+ column: ticketArg.columnId,
918
+ priority: ticketArg.priority,
919
+ ...(ticketArg.assignee === undefined ? {} : { assignee: deviceTicketPerson(ticketArg.assignee, viewerArg) }),
920
+ labels: [...ticketArg.labels],
921
+ autoLabels: [...(ticketArg.autoLabels ?? [])],
922
+ ...(epic === undefined ? {} : { epic }),
923
+ updatedAt: Date.parse(ticketArg.updatedAt),
924
+ };
925
+ };
926
+
927
+ /** Every link a ticket holds, field by field. */
928
+ const deviceTicketLink = (linkArg: ITicket['links'][number]): IDeviceTicket['links'][number] => {
929
+ switch (linkArg.kind) {
930
+ case 'branch': return { kind: 'branch', repo: linkArg.repo, branch: linkArg.branch, sha: linkArg.sha };
931
+ case 'commit': return { kind: 'commit', repo: linkArg.repo, sha: linkArg.sha };
932
+ case 'release': return { kind: 'release', version: linkArg.version, ...(linkArg.package === undefined ? {} : { package: linkArg.package }),
933
+ ...(linkArg.repo === undefined ? {} : { repo: linkArg.repo }), ...(linkArg.sha === undefined ? {} : { sha: linkArg.sha }) };
934
+ case 'affects': return { kind: 'affects', repo: linkArg.repo, version: linkArg.version };
935
+ }
936
+ };
937
+
938
+ /**
939
+ * A ticket as a device's detail shows it: its card, description, source words, evidence and parent; never its source
940
+ * attachments, its plans' questions, who created or last changed it, or its permissions.
941
+ */
942
+ export const deviceTicket = (ticketArg: ITicket, parentArg: ITicket | undefined, viewerArg: IDeviceTicketViewer): IDeviceTicket => ({
943
+ ...deviceTicketCard(ticketArg, parentArg, viewerArg),
944
+ description: ticketArg.description,
945
+ source: { kind: ticketArg.source.kind, text: ticketArg.source.text, by: deviceTicketPerson(ticketArg.source.actor, viewerArg) },
946
+ links: ticketArg.links.map(deviceTicketLink),
947
+ ...(parentArg !== undefined && ticketArg.parentId === parentArg.key ? { parent: { key: parentArg.key, title: parentArg.title } } : {}),
948
+ revision: ticketArg.revision,
949
+ createdAt: Date.parse(ticketArg.createdAt),
950
+ });
951
+
952
+ export const deviceTicketComment = (commentArg: ITicketComment, viewerArg: IDeviceTicketViewer): IDeviceTicketComment => ({
953
+ id: commentArg.id,
954
+ author: deviceTicketPerson(commentArg.author, viewerArg),
955
+ createdAt: Date.parse(commentArg.createdAt),
956
+ body: commentArg.body.map((partArg) => (partArg.type === 'text'
957
+ ? { type: 'text' as const, text: partArg.text } : { type: 'reference' as const, id: partArg.id, label: partArg.label })),
958
+ });
959
+
960
+ /** How the board's assignee filter of a device narrows the board: the owner by the owner's principal id. */
961
+ const deviceAssigneeNarrowing = (filterArg: TDeviceAssigneeFilter, ownerIdArg: string): NonNullable<ITicketBoardNarrowing['assignee']> => {
962
+ switch (filterArg.kind) {
963
+ case 'owner': return { kind: 'person', id: ownerIdArg };
964
+ case 'unassigned': return { kind: 'unassigned' };
965
+ case 'session': return { kind: 'session', sessionId: filterArg.sessionId };
966
+ }
967
+ };
968
+
969
+ /**
970
+ * One column of the board as `device.board.list` answers it, from one read of the whole board (`board`): the tasks the
971
+ * store's own filters (`ticketFilter`: text and project) and the board's narrowing (`ticketBoardNarrows`: epic,
972
+ * assignee, AutoLabel) let through, as the browser's board shows its cards, counted per column, and the page of the
973
+ * requested column in the column's order; the projects and the epics a filter may choose, as the browser's board
974
+ * offers them (the epics in the chosen project, their own or one of their tasks', and the chosen epic).
975
+ */
976
+ export const deviceBoardPage = (
977
+ boardArg: ITicketBoard, requestArg: IReq_DeviceBoardList['request'], viewerArg: IDeviceTicketViewer,
978
+ ): IReq_DeviceBoardList['response'] => {
979
+ const byKey = new Map(boardArg.tickets.map((ticketArg) => [ticketArg.key, ticketArg]));
980
+ const matches = ticketFilter({
981
+ ...(requestArg.text === undefined ? {} : { text: requestArg.text }),
982
+ ...(requestArg.project === undefined ? {} : { project: requestArg.project }),
983
+ }, undefined);
984
+ const narrowing: ITicketBoardNarrowing = {
985
+ ...(requestArg.epic === undefined ? {} : { epic: requestArg.epic }),
986
+ ...(requestArg.assignee === undefined ? {} : { assignee: deviceAssigneeNarrowing(requestArg.assignee, viewerArg.ownerId) }),
987
+ ...(requestArg.label === undefined ? {} : { autoLabel: requestArg.label }),
988
+ };
989
+ const shown = boardArg.tickets.filter((ticketArg) => ticketArg.kind === 'task' && matches(ticketArg) && ticketBoardNarrows(ticketArg, narrowing));
990
+ const counts = new Map<TDeviceTicketColumn, number>();
991
+ for (const ticket of shown) counts.set(ticket.columnId, (counts.get(ticket.columnId) ?? 0) + 1);
992
+ const column = shown.filter((ticketArg) => ticketArg.columnId === requestArg.column);
993
+ const offset = requestArg.offset ?? 0;
994
+ const project = requestArg.project;
995
+ const inProject = (epicArg: ITicket, projectArg: string): boolean => epicArg.project === projectArg
996
+ || boardArg.tickets.some((taskArg) => taskArg.parentId === epicArg.key && taskArg.project === projectArg);
997
+ return {
998
+ revision: boardArg.revision,
999
+ columns: boardArg.columns.map((columnArg) => ({ id: columnArg.id, title: columnArg.title, done: columnArg.done === true,
1000
+ count: counts.get(columnArg.id) ?? 0 })),
1001
+ tickets: column.slice(offset, offset + (requestArg.limit ?? 50))
1002
+ .map((ticketArg) => deviceTicketCard(ticketArg, ticketArg.parentId === undefined ? undefined : byKey.get(ticketArg.parentId), viewerArg)),
1003
+ total: column.length,
1004
+ projects: [...new Set(boardArg.tickets.map((ticketArg) => ticketArg.project))].sort((leftArg, rightArg) => leftArg.localeCompare(rightArg, 'en')),
1005
+ epics: boardArg.tickets
1006
+ .filter((ticketArg) => ticketArg.kind === 'epic' && (project === undefined || ticketArg.key === requestArg.epic || inProject(ticketArg, project)))
1007
+ .sort((leftArg, rightArg) => leftArg.order - rightArg.order || leftArg.key.localeCompare(rightArg.key, 'en'))
1008
+ .map(({ key, title }) => ({ key, title })),
1009
+ };
1010
+ };
1011
+
1012
+ /** A comment or a question of a ticket's discussion, in the order they were written, and the cursor that names it. */
1013
+ interface IDeviceDiscussionEntry {
1014
+ cursor: string;
1015
+ at: number;
1016
+ /** Questions before comments written in the same millisecond, each in its own order. */
1017
+ rank: number;
1018
+ order: string | number;
1019
+ item: { comment: IDeviceTicketComment } | { question: IDeviceTicketQuestion };
1020
+ }
1021
+
1022
+ const discussionOrder = (leftArg: IDeviceDiscussionEntry, rightArg: IDeviceDiscussionEntry): number => (
1023
+ leftArg.at - rightArg.at || leftArg.rank - rightArg.rank
1024
+ || (leftArg.order < rightArg.order ? -1 : leftArg.order > rightArg.order ? 1 : 0)
1025
+ );
1026
+
1027
+ /**
1028
+ * One page of a ticket's discussion, its comments and questions together in the order they were written: those
1029
+ * before the entry `before` names (`c:<comment id>` or `q:<question id>`, as a page returned it), or the newest, at
1030
+ * most `limit` and `deviceTicketDiscussionPage.bytes` of them as JSON but at least one, each list oldest first, and the
1031
+ * cursor of the next older page, `null` at the first entry. A `before` that names no entry is refused.
1032
+ */
1033
+ export const deviceTicketDiscussion = (
1034
+ commentsArg: readonly ITicketComment[], questionsArg: readonly ITicketQuestion[], pageArg: { before?: string; limit?: number },
1035
+ viewerArg: IDeviceTicketViewer,
1036
+ ): Pick<IReq_DeviceTicketGet['response'], 'comments' | 'questions' | 'before'> => {
1037
+ const entries: IDeviceDiscussionEntry[] = [
1038
+ ...commentsArg.map((commentArg) => ({ cursor: `c:${commentArg.id}`, at: Date.parse(commentArg.createdAt), rank: 1, order: commentArg.id,
1039
+ item: { comment: deviceTicketComment(commentArg, viewerArg) } })),
1040
+ ...questionsArg.map((questionArg) => ({ cursor: `q:${questionArg.id}`, at: Date.parse(questionArg.createdAt), rank: 0,
1041
+ order: Number(questionArg.id.slice(1)), item: { question: deviceTicketQuestion(questionArg) } })),
1042
+ ].sort(discussionOrder);
1043
+ const end = pageArg.before === undefined ? entries.length : entries.findIndex((entryArg) => entryArg.cursor === pageArg.before);
1044
+ if (end < 0) throw deviceRefusal('invalid_request', 'before names nothing in this ticket\'s discussion; read its newest page.');
1045
+ const limit = pageArg.limit ?? deviceTicketDiscussionPage.default;
1046
+ let start = end;
1047
+ let bytes = 0;
1048
+ while (start > 0 && end - start < limit) {
1049
+ const size = Buffer.byteLength(JSON.stringify(entries[start - 1]!.item), 'utf8');
1050
+ if (end > start && bytes + size > deviceTicketDiscussionPage.bytes) break;
1051
+ bytes += size;
1052
+ start -= 1;
1053
+ }
1054
+ const page = entries.slice(start, end).map((entryArg) => entryArg.item);
1055
+ return {
1056
+ questions: page.flatMap((itemArg) => ('question' in itemArg ? [itemArg.question] : [])),
1057
+ comments: page.flatMap((itemArg) => ('comment' in itemArg ? [itemArg.comment] : [])),
1058
+ before: start > 0 ? entries[start]!.cursor : null,
1059
+ };
1060
+ };
1061
+
1062
+ /** Where a ticket's work runs as a device sees it: the deploy monitor's placement, the targets by id and name. */
1063
+ export const deviceTicketPlacement = (placementArg: IFleetDeployTicketPlacement): IDeviceTicketPlacement => ({
1064
+ state: 'ready',
1065
+ landed: placementArg.landed.map((landedArg) => ({ repo: landedArg.repo, sha: landedArg.sha,
1066
+ ...(landedArg.branch === undefined ? {} : { branch: landedArg.branch }), ...(landedArg.fixedIn === undefined ? {} : { fixedIn: landedArg.fixedIn.version }) })),
1067
+ runs: placementArg.runs.map((runArg) => ({ target: runArg.targetId, name: runArg.name,
1068
+ ...(runArg.environment === undefined ? {} : { environment: runArg.environment }), repo: runArg.repo,
1069
+ ...(runArg.version === undefined ? {} : { version: runArg.version }), probe: runArg.probe, runs: runArg.runs,
1070
+ ...(runArg.shippedIn === undefined ? {} : { shippedIn: runArg.shippedIn }) })),
1071
+ foundIn: placementArg.foundIn.map(({ repo, version }) => ({ repo, version })),
1072
+ });
1073
+
1074
+ /**
1075
+ * What a ticket plans, from the ticket itself: its release plan, its maintenance window and its deploy plan; while the
1076
+ * deploy monitor answered (`placementArg`), where the window stands and the owner's go on it and on the deploy. Never a
1077
+ * plan's question or who deploys it.
1078
+ */
1079
+ export const deviceTicketPlans = (ticketArg: ITicket, placementArg: IFleetDeployTicketPlacement | undefined): IDeviceTicketPlans => {
1080
+ const { releasePlan, maintenanceWindow, deployPlan } = ticketArg;
1081
+ const observedWindow = placementArg?.maintenanceWindow;
1082
+ const observedPlan = placementArg?.deployPlan;
1083
+ return {
1084
+ ...(releasePlan === undefined ? {} : { release: { repo: releasePlan.repo, ...(releasePlan.version === undefined ? {} : { version: releasePlan.version }) } }),
1085
+ ...(maintenanceWindow === undefined ? {} : { window: {
1086
+ from: Date.parse(maintenanceWindow.from), to: Date.parse(maintenanceWindow.to), targets: [...maintenanceWindow.targets],
1087
+ ...(observedWindow === undefined ? {} : { state: observedWindow.state, go: observedWindow.go }),
1088
+ } }),
1089
+ ...(deployPlan === undefined ? {} : { deploy: {
1090
+ target: deployPlan.target, version: deployPlan.version,
1091
+ ...(observedPlan === undefined ? {} : {
1092
+ targetName: observedPlan.targetName, ...(observedPlan.environment === undefined ? {} : { environment: observedPlan.environment }),
1093
+ go: observedPlan.plan.go, deployWhen: observedPlan.deployWhen,
1094
+ ...(observedPlan.plan.window === undefined ? {} : { window: { from: Date.parse(observedPlan.plan.window.from), to: Date.parse(observedPlan.plan.window.to) } }),
1095
+ }),
1096
+ } }),
1097
+ };
1098
+ };
1099
+
1100
+ /** A ticket's placement for `device.ticket.get`, read on its own as a section of `device.host.get` is. */
1101
+ export const readDeviceTicketPlacement = async (readArg: () => Promise<IFleetDeployTicketPlacement>, signalArg: AbortSignal):
1102
+ Promise<{ placement: IDeviceTicketPlacement | IDeviceHostUnavailable; observed: IFleetDeployTicketPlacement | undefined }> => {
1103
+ let observed: IFleetDeployTicketPlacement | undefined;
1104
+ const placement = await readDeviceSection<IDeviceTicketPlacement>('device.ticket.get placement', 'a ticket\'s placement', signalArg, async () => {
1105
+ observed = await readArg();
1106
+ return deviceTicketPlacement(observed);
1107
+ });
1108
+ return { placement, observed };
1109
+ };
1110
+
1111
+ const deviceDeployGo = (planArg: IControllerInboxDeployGo): IDeviceDeployGo => ({
1112
+ target: planArg.target,
1113
+ ...(planArg.targetName === undefined ? {} : { targetName: planArg.targetName }),
1114
+ ...(planArg.environment === undefined ? {} : { environment: planArg.environment }),
1115
+ version: planArg.version,
1116
+ ...(planArg.runs === undefined ? {} : { runs: planArg.runs }),
1117
+ ...(planArg.deployWhen === undefined ? {} : { deployWhen: planArg.deployWhen }),
1118
+ ...(planArg.window === undefined ? {} : { window: { from: Date.parse(planArg.window.from), to: Date.parse(planArg.window.to) } }),
1119
+ ships: planArg.ships.map(({ key, title }) => ({ key, title })),
1120
+ shipsTotal: planArg.shipsTotal,
1121
+ });
1122
+
1123
+ /**
1124
+ * Where an Inbox item lives as a device names it, and how a device answers it: a session only by a row the feed lists
1125
+ * for devices, never by host paths; the driver, which no row stands for, without an answer.
1126
+ */
1127
+ const deviceInboxPlace = (
1128
+ whereArg: TControllerInboxWhere,
1129
+ answerArg: TControllerInboxItem['answer'],
1130
+ rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
1131
+ ): { where: TDeviceInboxWhere; answer: TDeviceInboxAnswer } => {
1132
+ switch (whereArg.kind) {
1133
+ case 'conversation':
1134
+ case 'native':
1135
+ case 'child': {
1136
+ const row = rowOfArg(whereArg.rowId);
1137
+ const listed = row !== undefined && row.open.kind !== 'terminal';
1138
+ const where: TDeviceInboxWhere = {
1139
+ kind: 'session', sessionId: whereArg.rowId, harness: whereArg.harness, name: whereArg.name,
1140
+ ...(whereArg.kind === 'child' ? { childSessionId: whereArg.childSessionId.nativeId, childName: whereArg.childName } : {}),
1141
+ };
1142
+ const answer: TDeviceInboxAnswer = answerArg === 'none' || !listed ? 'none' : whereArg.kind === 'child' ? 'child' : 'session';
1143
+ return { where, answer };
1144
+ }
1145
+ case 'driver':
1146
+ return { where: { kind: 'driver' }, answer: 'none' };
1147
+ case 'ticket':
1148
+ return {
1149
+ where: { kind: 'ticket', ticketKey: whereArg.ticketKey, ticketTitle: whereArg.ticketTitle, project: whereArg.project },
1150
+ answer: answerArg === 'ticket' ? 'ticket' : 'none',
1151
+ };
1152
+ }
1153
+ };
1154
+
1155
+ /** An Inbox item as a device sees it: the same item without host paths, in the device protocol's shapes. */
1156
+ export const deviceInboxItem = (
1157
+ itemArg: TControllerInboxItem,
1158
+ rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
1159
+ ): TDeviceInboxItem => {
1160
+ const base = {
1161
+ id: itemArg.id, since: itemArg.since, title: itemArg.title,
1162
+ ...deviceInboxPlace(itemArg.where, itemArg.answer, rowOfArg),
1163
+ ...(itemArg.omitted === undefined ? {} : { omitted: { ...itemArg.omitted } }),
1164
+ };
1165
+ switch (itemArg.kind) {
1166
+ case 'permission':
1167
+ return { ...base, kind: 'permission', ...(itemArg.permission ? { permission: devicePermissions([itemArg.permission])[0] } : {}) };
1168
+ case 'question':
1169
+ return { ...base, kind: 'question', ...(itemArg.question ? { question: deviceQuestions([itemArg.question])[0] } : {}) };
1170
+ case 'elicitation':
1171
+ return { ...base, kind: 'elicitation', ...(itemArg.elicitation ? { elicitation: deviceElicitations([itemArg.elicitation])[0] } : {}) };
1172
+ case 'native_wait':
1173
+ return { ...base, kind: 'native_wait', reason: itemArg.nativeWait.reason, host: itemArg.host };
1174
+ case 'driver':
1175
+ return { ...base, kind: 'driver', ...(itemArg.line === undefined ? {} : { line: itemArg.line }) };
1176
+ case 'deploy_go':
1177
+ return { ...base, kind: 'deploy_go', plan: deviceDeployGo(itemArg.plan), ...(itemArg.question ? { question: deviceTicketQuestion(itemArg.question) } : {}) };
1178
+ case 'window_go':
1179
+ return {
1180
+ ...base, kind: 'window_go',
1181
+ window: { from: Date.parse(itemArg.window.from), to: Date.parse(itemArg.window.to), targets: [...itemArg.window.targets] },
1182
+ ...(itemArg.question ? { question: deviceTicketQuestion(itemArg.question) } : {}),
1183
+ };
1184
+ case 'ticket_question':
1185
+ return { ...base, kind: 'ticket_question', ...(itemArg.question ? { question: deviceTicketQuestion(itemArg.question) } : {}) };
1186
+ }
1187
+ };
1188
+
1189
+ /** The Inbox as `device.inbox.list` answers it. */
1190
+ export const deviceInboxList = (
1191
+ snapshotArg: IControllerInboxSnapshot,
1192
+ rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
1193
+ ): IReq_DeviceInboxList['response'] => ({
1194
+ epoch: snapshotArg.epoch,
1195
+ revision: snapshotArg.revision,
1196
+ items: snapshotArg.items.map((itemArg) => deviceInboxItem(itemArg, rowOfArg)),
1197
+ total: snapshotArg.total,
1198
+ limited: snapshotArg.limited,
1199
+ });
1200
+
1201
+ /** An Inbox change as a device applies it: the same epoch, revision and order. */
1202
+ export const deviceInboxDelta = (
1203
+ deltaArg: TControllerInboxDelta,
1204
+ rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
1205
+ ): IDeviceInboxDelta => 'reset' in deltaArg
1206
+ ? { epoch: deltaArg.epoch, revision: deltaArg.revision, reset: true, upserts: [], removed: [], order: [], total: 0, limited: false }
1207
+ : {
1208
+ epoch: deltaArg.epoch,
1209
+ revision: deltaArg.revision,
1210
+ reset: false,
1211
+ upserts: deltaArg.upserts.map((itemArg) => deviceInboxItem(itemArg, rowOfArg)),
1212
+ removed: [...deltaArg.removed],
1213
+ order: [...deltaArg.order],
1214
+ total: deltaArg.total,
1215
+ limited: deltaArg.limited,
1216
+ };
1217
+
143
1218
  /**
144
1219
  * The row id a device names a conversation by, when the feed lists it as something a device opens; events about any
145
1220
  * other session (a driver, a child, a terminal's agent, one the feed has not listed yet) reach no device.
@@ -154,35 +1229,63 @@ const visibleRowId = (
154
1229
  return row && row.open.kind !== 'terminal' ? rowId : undefined;
155
1230
  };
156
1231
 
157
- /** A controller event as a device receives it, or none. `rowOfArg` answers the feed's published rows. */
1232
+ /**
1233
+ * A controller event as a device receives it: none, one, or several in the order they are sent (a ticket change is
1234
+ * the board's, the direct reports' and the host's). `rowOfArg` answers the feed's published rows; `driverArg` the driver as it
1235
+ * is now, whose own session changes reach a device as `driver.changed` (never its streamed content).
1236
+ */
158
1237
  export const deviceEvent = (
159
1238
  eventArg: IControllerEvent,
160
1239
  rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
161
- ): TDeviceEvent | undefined => {
1240
+ driverArg: TDeviceDriverSource | undefined,
1241
+ ): readonly TDeviceEvent[] => {
162
1242
  switch (eventArg.type) {
163
1243
  case 'sessionfeed.changed':
164
- return eventArg.sessionFeed ? { type: 'sessionfeed.changed', delta: deviceFeedDelta(eventArg.sessionFeed) } : undefined;
1244
+ return eventArg.sessionFeed ? [{ type: 'sessionfeed.changed', delta: deviceFeedDelta(eventArg.sessionFeed) }] : [];
1245
+ case 'inbox.changed':
1246
+ return eventArg.inbox ? [{ type: 'inbox.changed', delta: deviceInboxDelta(eventArg.inbox, rowOfArg) }] : [];
165
1247
  case 'sessions.changed':
166
- return { type: 'sessions.changed' };
1248
+ return [{ type: 'sessions.changed' }];
1249
+ case 'driver.changed':
1250
+ return eventArg.driverStatus
1251
+ ? [{ type: 'driver.changed', driver: deviceDriverStatus(eventArg.driverStatus, driverArg?.needsInput()) }] : [];
1252
+ // A report's status is its worker's, and its open questions are tickets'.
1253
+ case 'directreports.changed':
1254
+ case 'fleet.workers.changed':
1255
+ return [{ type: 'directreports.changed' }];
1256
+ // The board, which no key names; tickets also hold the reports' open questions and the deploy targets' planned deploys.
1257
+ case 'tickets.changed':
1258
+ return [
1259
+ { type: 'tickets.changed', ...(eventArg.ticketRevision === undefined ? {} : { revision: eventArg.ticketRevision }) },
1260
+ { type: 'directreports.changed' },
1261
+ { type: 'host.changed' },
1262
+ ];
1263
+ // What the host's status reads: its deploy targets and its accounts. Never what these events carry.
1264
+ case 'deployments.changed':
1265
+ case 'accounts.changed':
1266
+ return [{ type: 'host.changed' }];
167
1267
  case 'session.changed':
168
1268
  case 'session.history.changed':
169
1269
  case 'permissions.changed': {
170
- if (!eventArg.sessionId) return eventArg.type === 'permissions.changed' ? { type: 'sessions.changed' } : undefined;
1270
+ if (driverArg?.isSessionChange(eventArg)) {
1271
+ return [{ type: 'driver.changed', driver: deviceDriverStatus(driverArg.current(), driverArg.needsInput()) }];
1272
+ }
1273
+ if (!eventArg.sessionId) return eventArg.type === 'permissions.changed' ? [{ type: 'sessions.changed' }] : [];
171
1274
  const sessionId = visibleRowId(eventArg.sessionId, rowOfArg);
172
- return sessionId === undefined ? undefined : { type: 'session.changed', sessionId };
1275
+ return sessionId === undefined ? [] : [{ type: 'session.changed', sessionId }];
173
1276
  }
174
1277
  case 'session.text.updated': {
175
1278
  const update = eventArg.textUpdate;
176
1279
  const sessionId = visibleRowId(update?.sessionId, rowOfArg);
177
- return update && sessionId !== undefined ? {
1280
+ return update && sessionId !== undefined ? [{
178
1281
  type: 'session.text.updated',
179
1282
  update: { sessionId, messageId: update.messageId.nativeId, partId: update.partId.nativeId, text: update.text },
180
- } : undefined;
1283
+ }] : [];
181
1284
  }
182
1285
  case 'session.text.delta': {
183
1286
  const delta = eventArg.textDelta;
184
1287
  const sessionId = visibleRowId(delta?.sessionId, rowOfArg);
185
- return delta && sessionId !== undefined ? {
1288
+ return delta && sessionId !== undefined ? [{
186
1289
  type: 'session.text.delta',
187
1290
  delta: {
188
1291
  sessionId,
@@ -192,10 +1295,10 @@ export const deviceEvent = (
192
1295
  baseTextUtf8Bytes: delta.baseTextUtf8Bytes,
193
1296
  textUtf8Bytes: delta.textUtf8Bytes,
194
1297
  },
195
- } : undefined;
1298
+ }] : [];
196
1299
  }
197
1300
  default:
198
- return undefined;
1301
+ return [];
199
1302
  }
200
1303
  };
201
1304
 
@@ -249,33 +1352,71 @@ export const assertDeviceAuthProveRequest = (valueArg: unknown): IReq_DeviceAuth
249
1352
  return { deviceId: assertDeviceId(value.deviceId), signature: assertText(value.signature, 'signature', 128) };
250
1353
  };
251
1354
 
252
- export const assertDeviceSessionReadRequest = (valueArg: unknown): IReq_DeviceSessionRead['request'] => {
253
- const value = assertObject(valueArg, 'device session read request');
254
- assertKeys(value, ['sessionId'], ['before', 'limit']);
255
- if (value.limit !== undefined && (!Number.isSafeInteger(value.limit) || (value.limit as number) < 1 || (value.limit as number) > 50)) {
1355
+ /** A transcript page a device asks for: the `before` cursor of a newer page, and 1 to 50 messages. */
1356
+ const assertDevicePage = (valueArg: Record<string, unknown>): { before?: string; limit?: number } => {
1357
+ if (valueArg.limit !== undefined && (!Number.isSafeInteger(valueArg.limit) || (valueArg.limit as number) < 1 || (valueArg.limit as number) > 50)) {
256
1358
  throw new Error('limit must be an integer from 1 to 50.');
257
1359
  }
258
1360
  return {
259
- sessionId: assertRowId(value.sessionId),
260
- ...(value.before === undefined ? {} : { before: assertText(value.before, 'before', 4096) }),
261
- ...(value.limit === undefined ? {} : { limit: value.limit as number }),
1361
+ ...(valueArg.before === undefined ? {} : { before: assertText(valueArg.before, 'before', 4096) }),
1362
+ ...(valueArg.limit === undefined ? {} : { limit: valueArg.limit as number }),
262
1363
  };
263
1364
  };
264
1365
 
1366
+ /** A device's message: 1 to 64 KiB of UTF-8, not blank. */
1367
+ const assertDeviceMessageText = (valueArg: unknown): string => {
1368
+ const text = assertText(valueArg, 'text', deviceMessageMaximumBytes);
1369
+ if (!text.trim() || text.includes('\0')) throw new Error('text must be a message that is not blank.');
1370
+ return text;
1371
+ };
1372
+
1373
+ export const assertDeviceSessionReadRequest = (valueArg: unknown): IReq_DeviceSessionRead['request'] => {
1374
+ const value = assertObject(valueArg, 'device session read request');
1375
+ assertKeys(value, ['sessionId'], ['before', 'limit']);
1376
+ return { sessionId: assertRowId(value.sessionId), ...assertDevicePage(value) };
1377
+ };
1378
+
265
1379
  export const assertDeviceSessionSendRequest = (valueArg: unknown): IReq_DeviceSessionSend['request'] => {
266
1380
  const value = assertObject(valueArg, 'device session send request');
267
1381
  assertKeys(value, ['sessionId', 'text']);
268
- const text = assertText(value.text, 'text', deviceMessageMaximumBytes);
269
- if (!text.trim() || text.includes('\0')) throw new Error('text must be a message that is not blank.');
1382
+ const text = assertDeviceMessageText(value.text);
270
1383
  return { sessionId: assertRowId(value.sessionId), text };
271
1384
  };
272
1385
 
1386
+ export const assertDeviceDriverReadRequest = (valueArg: unknown): IReq_DeviceDriverRead['request'] => {
1387
+ const value = assertObject(valueArg, 'device driver read request');
1388
+ assertKeys(value, [], ['before', 'limit']);
1389
+ return assertDevicePage(value);
1390
+ };
1391
+
1392
+ export const assertDeviceDriverSendRequest = (valueArg: unknown): IReq_DeviceDriverSend['request'] => {
1393
+ const value = assertObject(valueArg, 'device driver send request');
1394
+ assertKeys(value, ['text']);
1395
+ return { text: assertDeviceMessageText(value.text) };
1396
+ };
1397
+
1398
+ /** A device's message to a direct report, in shape; the Driver view's own rules check the name and the text. */
1399
+ export const assertDeviceDirectReportMessageRequest = (valueArg: unknown): IReq_DeviceDirectReportMessage['request'] => {
1400
+ const value = assertObject(valueArg, 'device direct report message request');
1401
+ assertKeys(value, ['name', 'text']);
1402
+ const { name, text } = assertDirectReportMessageRequest({ name: value.name, text: value.text });
1403
+ return { name, text };
1404
+ };
1405
+
1406
+ /** A direct child's OpenCode session id, as the Inbox names it. */
1407
+ const assertChildSessionId = (valueArg: unknown): string => {
1408
+ const id = assertText(valueArg, 'childSessionId', 512);
1409
+ if (!/^[^\s\p{Cc}]+$/u.test(id)) throw new Error('childSessionId must name a session as the Inbox does.');
1410
+ return id;
1411
+ };
1412
+
273
1413
  export const assertDevicePermissionReplyRequest = (valueArg: unknown): IReq_DevicePermissionReply['request'] => {
274
1414
  const value = assertObject(valueArg, 'device permission reply request');
275
- assertKeys(value, ['sessionId', 'permissionId', 'reply'], ['message']);
1415
+ assertKeys(value, ['sessionId', 'permissionId', 'reply'], ['message', 'childSessionId']);
276
1416
  if (value.reply !== 'once' && value.reply !== 'reject') throw new Error('reply must be once or reject.');
277
1417
  return {
278
1418
  sessionId: assertRowId(value.sessionId),
1419
+ ...(value.childSessionId === undefined ? {} : { childSessionId: assertChildSessionId(value.childSessionId) }),
279
1420
  permissionId: assertText(value.permissionId, 'permissionId', 512),
280
1421
  reply: value.reply,
281
1422
  ...(value.message === undefined ? {} : { message: assertText(value.message, 'message', 2048) }),
@@ -284,9 +1425,10 @@ export const assertDevicePermissionReplyRequest = (valueArg: unknown): IReq_Devi
284
1425
 
285
1426
  export const assertDeviceQuestionReplyRequest = (valueArg: unknown): IReq_DeviceQuestionReply['request'] => {
286
1427
  const value = assertObject(valueArg, 'device question reply request');
287
- assertKeys(value, ['sessionId', 'questionId', 'answers']);
1428
+ assertKeys(value, ['sessionId', 'questionId', 'answers'], ['childSessionId']);
288
1429
  return {
289
1430
  sessionId: assertRowId(value.sessionId),
1431
+ ...(value.childSessionId === undefined ? {} : { childSessionId: assertChildSessionId(value.childSessionId) }),
290
1432
  questionId: assertText(value.questionId, 'questionId', 512),
291
1433
  answers: assertQuestionAnswers(value.answers),
292
1434
  };
@@ -302,6 +1444,122 @@ export const assertDeviceElicitationReplyRequest = (valueArg: unknown): IReq_Dev
302
1444
  };
303
1445
  };
304
1446
 
1447
+ /**
1448
+ * A ticket answer of a device, in shape: the ticket by key, the question, option ids and text. The ticket store's own
1449
+ * rules (`assertTicketRequest`) check the values as for the browser.
1450
+ */
1451
+ export const assertDeviceTicketAnswerRequest = (valueArg: unknown): IReq_DeviceTicketAnswer['request'] => {
1452
+ const value = assertObject(valueArg, 'device ticket answer request');
1453
+ assertKeys(value, ['ticketKey', 'questionId'], ['choices', 'text']);
1454
+ if (value.choices !== undefined && (!Array.isArray(value.choices) || value.choices.some((choiceArg) => typeof choiceArg !== 'string'))) {
1455
+ throw new Error('choices must be option ids.');
1456
+ }
1457
+ if (value.text !== undefined && typeof value.text !== 'string') throw new Error('text must be text.');
1458
+ return {
1459
+ ticketKey: assertText(value.ticketKey, 'ticketKey', 64),
1460
+ questionId: assertText(value.questionId, 'questionId', 16),
1461
+ ...(value.choices === undefined ? {} : { choices: [...value.choices as string[]] }),
1462
+ ...(value.text === undefined ? {} : { text: value.text as string }),
1463
+ };
1464
+ };
1465
+
1466
+ /** A ticket's key, as the board names it (`AGL-12`). */
1467
+ const assertTicketKey = (valueArg: unknown, nameArg: string): string => {
1468
+ if (typeof valueArg !== 'string' || !/^AGL-[1-9][0-9]{0,15}$/u.test(valueArg)) throw new Error(`${nameArg} must name a ticket, such as AGL-12.`);
1469
+ return valueArg;
1470
+ };
1471
+
1472
+ const assertTicketColumn = (valueArg: unknown, nameArg: string): TDeviceTicketColumn => {
1473
+ if (!(ticketColumns as readonly unknown[]).includes(valueArg)) throw new Error(`${nameArg} must be a column of the board: ${ticketColumns.join(', ')}.`);
1474
+ return valueArg as TDeviceTicketColumn;
1475
+ };
1476
+
1477
+ /** An integer from `minimumArg` to `maximumArg`, or absent. */
1478
+ const assertBoundedInteger = (valueArg: unknown, nameArg: string, minimumArg: number, maximumArg: number): number | undefined => {
1479
+ if (valueArg === undefined) return undefined;
1480
+ if (!Number.isSafeInteger(valueArg) || (valueArg as number) < minimumArg || (valueArg as number) > maximumArg) {
1481
+ throw new Error(`${nameArg} must be an integer from ${minimumArg} to ${maximumArg}.`);
1482
+ }
1483
+ return valueArg as number;
1484
+ };
1485
+
1486
+ const assertDeviceAssigneeFilter = (valueArg: unknown): TDeviceAssigneeFilter => {
1487
+ const value = assertObject(valueArg, 'assignee');
1488
+ if (value.kind === 'owner' || value.kind === 'unassigned') {
1489
+ assertKeys(value, ['kind']);
1490
+ return { kind: value.kind };
1491
+ }
1492
+ if (value.kind !== 'session') throw new Error('assignee must be the owner, unassigned or a session.');
1493
+ assertKeys(value, ['kind', 'sessionId']);
1494
+ return { kind: 'session', sessionId: assertRowId(value.sessionId) };
1495
+ };
1496
+
1497
+ /**
1498
+ * A page of the board a device asks for: a column, the board's filters (text 1 to 200 characters, a project, an epic, an
1499
+ * assignee, an AutoLabel) and `limit` (1 to 100) tickets from `offset`. The store's own rules check the text and the
1500
+ * project as for every listing (`assertTicketRequest('board')`).
1501
+ */
1502
+ export const assertDeviceBoardListRequest = (valueArg: unknown): IReq_DeviceBoardList['request'] => {
1503
+ const value = assertObject(valueArg, 'device board list request');
1504
+ assertKeys(value, ['column'], ['text', 'project', 'epic', 'assignee', 'label', 'offset', 'limit']);
1505
+ if (value.text !== undefined && (typeof value.text !== 'string' || value.text.length === 0 || [...value.text].length > 200)) {
1506
+ throw new Error('text must hold 1-200 characters.');
1507
+ }
1508
+ if (value.label !== undefined && !(ticketAutoLabels as readonly unknown[]).includes(value.label)) {
1509
+ throw new Error(`label must be an AutoLabel: ${ticketAutoLabels.join(', ')}.`);
1510
+ }
1511
+ const filters = assertTicketRequest('board', {
1512
+ ...(value.text === undefined ? {} : { text: value.text }),
1513
+ ...(value.project === undefined ? {} : { project: value.project }),
1514
+ });
1515
+ const offset = assertBoundedInteger(value.offset, 'offset', 0, Number.MAX_SAFE_INTEGER);
1516
+ const limit = assertBoundedInteger(value.limit, 'limit', 1, 100);
1517
+ return {
1518
+ column: assertTicketColumn(value.column, 'column'),
1519
+ ...(filters.text === undefined ? {} : { text: filters.text }),
1520
+ ...(filters.project === undefined ? {} : { project: filters.project }),
1521
+ ...(value.epic === undefined ? {} : { epic: assertTicketKey(value.epic, 'epic') }),
1522
+ ...(value.assignee === undefined ? {} : { assignee: assertDeviceAssigneeFilter(value.assignee) }),
1523
+ ...(value.label === undefined ? {} : { label: value.label as NonNullable<IReq_DeviceBoardList['request']['label']> }),
1524
+ ...(offset === undefined ? {} : { offset }),
1525
+ ...(limit === undefined ? {} : { limit }),
1526
+ };
1527
+ };
1528
+
1529
+ /** A ticket a device opens, and the page of its discussion: the `before` of a newer page, and 1 to 50 entries. */
1530
+ export const assertDeviceTicketGetRequest = (valueArg: unknown): IReq_DeviceTicketGet['request'] => {
1531
+ const value = assertObject(valueArg, 'device ticket get request');
1532
+ assertKeys(value, ['ticketKey'], ['before', 'limit']);
1533
+ const limit = assertBoundedInteger(value.limit, 'limit', 1, deviceTicketDiscussionPage.maximum);
1534
+ return {
1535
+ ticketKey: assertTicketKey(value.ticketKey, 'ticketKey'),
1536
+ ...(value.before === undefined ? {} : { before: assertText(value.before, 'before', 2048) }),
1537
+ ...(limit === undefined ? {} : { limit }),
1538
+ };
1539
+ };
1540
+
1541
+ /** A device's comment: 1 to 64 KiB of UTF-8, not blank. The store's own rules check it as the browser's. */
1542
+ export const assertDeviceTicketCommentRequest = (valueArg: unknown): IReq_DeviceTicketComment['request'] => {
1543
+ const value = assertObject(valueArg, 'device ticket comment request');
1544
+ assertKeys(value, ['ticketKey', 'text']);
1545
+ return { ticketKey: assertTicketKey(value.ticketKey, 'ticketKey'), text: assertDeviceMessageText(value.text) };
1546
+ };
1547
+
1548
+ /** A device's question: text alone, 1 to 16 KiB of UTF-8, not blank. The store's own rules check it as the browser's. */
1549
+ export const assertDeviceTicketAskRequest = (valueArg: unknown): IReq_DeviceTicketAsk['request'] => {
1550
+ const value = assertObject(valueArg, 'device ticket ask request');
1551
+ assertKeys(value, ['ticketKey', 'question']);
1552
+ const question = assertText(value.question, 'question', 16 * 1024);
1553
+ if (!question.trim() || question.includes('\0')) throw new Error('question must be a question that is not blank.');
1554
+ return { ticketKey: assertTicketKey(value.ticketKey, 'ticketKey'), question };
1555
+ };
1556
+
1557
+ export const assertDeviceTicketMoveRequest = (valueArg: unknown): IReq_DeviceTicketMove['request'] => {
1558
+ const value = assertObject(valueArg, 'device ticket move request');
1559
+ assertKeys(value, ['ticketKey', 'column']);
1560
+ return { ticketKey: assertTicketKey(value.ticketKey, 'ticketKey'), column: assertTicketColumn(value.column, 'column') };
1561
+ };
1562
+
305
1563
  export const assertDevicePairingCancelRequest = (valueArg: unknown): { pairingId: string } => {
306
1564
  const value = assertObject(valueArg, 'pairing cancel request');
307
1565
  assertKeys(value, ['pairingId']);