agl 43.1.0 → 43.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/changelog.md +32 -0
  2. package/dist_serve/bundle.js +5950 -5530
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +31 -31
  5. package/dist_serve/bundle.js.third-party-notices.txt +31 -31
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +521 -17
  8. package/dist_ts/aglapi/interfaces.d.ts +3 -0
  9. package/dist_ts/aglapi/interfaces.js +2 -1
  10. package/dist_ts/classes.accountsactions.d.ts +3 -1
  11. package/dist_ts/classes.accountsactions.js +21 -3
  12. package/dist_ts/classes.authmodels.js +17 -4
  13. package/dist_ts/classes.authstore.js +16 -2
  14. package/dist_ts/classes.claudeharness.d.ts +16 -0
  15. package/dist_ts/classes.claudeharness.js +24 -2
  16. package/dist_ts/classes.cli.d.ts +4 -2
  17. package/dist_ts/classes.cli.js +6 -3
  18. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  19. package/dist_ts/classes.codexclientadapter.js +14 -2
  20. package/dist_ts/classes.controller.d.ts +175 -11
  21. package/dist_ts/classes.controller.js +1213 -173
  22. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  23. package/dist_ts/classes.controllerdevices.js +6 -1
  24. package/dist_ts/classes.controllermanagement.d.ts +14 -4
  25. package/dist_ts/classes.controllermanagement.js +20 -2
  26. package/dist_ts/classes.gatewayclient.d.ts +115 -0
  27. package/dist_ts/classes.gatewayclient.js +336 -0
  28. package/dist_ts/classes.gatewayclientstore.d.ts +97 -0
  29. package/dist_ts/classes.gatewayclientstore.js +261 -0
  30. package/dist_ts/classes.inbox.d.ts +72 -0
  31. package/dist_ts/classes.inbox.js +231 -0
  32. package/dist_ts/classes.inferencerouter.d.ts +19 -0
  33. package/dist_ts/classes.inferencerouter.js +15 -3
  34. package/dist_ts/classes.inferenceservice.d.ts +9 -0
  35. package/dist_ts/classes.inferenceservice.js +28 -2
  36. package/dist_ts/classes.mcpclient.d.ts +4 -1
  37. package/dist_ts/classes.mcpclient.js +42 -6
  38. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -1
  39. package/dist_ts/classes.mcpcontrollerhost.js +11 -1
  40. package/dist_ts/classes.mcptools.d.ts +3 -3
  41. package/dist_ts/classes.mcptools.js +38 -8
  42. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  43. package/dist_ts/classes.mcpvalidation.js +38 -2
  44. package/dist_ts/classes.nativesessions.d.ts +17 -4
  45. package/dist_ts/classes.nativesessions.js +41 -9
  46. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  47. package/dist_ts/classes.opencodeclient.js +47 -3
  48. package/dist_ts/classes.proxycontrol.d.ts +11 -0
  49. package/dist_ts/classes.proxycontrol.js +7 -1
  50. package/dist_ts/classes.proxycontrolclient.d.ts +17 -0
  51. package/dist_ts/classes.proxycontrolclient.js +35 -1
  52. package/dist_ts/classes.proxydaemon.js +8 -1
  53. package/dist_ts/classes.proxymonitor.d.ts +7 -0
  54. package/dist_ts/classes.proxymonitor.js +13 -1
  55. package/dist_ts/classes.publishedset.d.ts +38 -0
  56. package/dist_ts/classes.publishedset.js +50 -0
  57. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  58. package/dist_ts/classes.sessionfeed.js +18 -26
  59. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  60. package/dist_ts/classes.systemmetricssampler.js +15 -3
  61. package/dist_ts/classes.ticketstore.d.ts +50 -3
  62. package/dist_ts/classes.ticketstore.js +45 -8
  63. package/dist_ts/classes.trustedproxysecrets.d.ts +2 -0
  64. package/dist_ts/classes.trustedproxysecrets.js +5 -1
  65. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  66. package/dist_ts/driver/classes.directreports.js +25 -6
  67. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  68. package/dist_ts/driver/classes.driverservice.js +50 -16
  69. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  70. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  71. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  72. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  73. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  74. package/dist_ts/fleet/classes.workercommand.js +15 -4
  75. package/dist_ts/fleet/classes.workers.d.ts +5 -1
  76. package/dist_ts/fleet/classes.workers.js +8 -2
  77. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  78. package/dist_ts/fleet/functions.workervalidation.js +2 -2
  79. package/dist_ts/fleet/interfaces.workers.d.ts +21 -3
  80. package/dist_ts/fleet/interfaces.workers.js +1 -1
  81. package/dist_ts/functions.agentmessage.d.ts +3 -0
  82. package/dist_ts/functions.agentmessage.js +4 -1
  83. package/dist_ts/functions.controllermanagementsurface.d.ts +4 -0
  84. package/dist_ts/functions.controllermanagementsurface.js +15 -1
  85. package/dist_ts/functions.deviceapi.d.ts +151 -4
  86. package/dist_ts/functions.deviceapi.js +893 -38
  87. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  88. package/dist_ts/functions.fleetworkercli.js +11 -8
  89. package/dist_ts/functions.gatewaycli.d.ts +24 -0
  90. package/dist_ts/functions.gatewaycli.js +395 -0
  91. package/dist_ts/functions.gatewayroute.d.ts +135 -0
  92. package/dist_ts/functions.gatewayroute.js +366 -0
  93. package/dist_ts/functions.inferencecli.js +32 -1
  94. package/dist_ts/functions.inferencecliarguments.d.ts +8 -2
  95. package/dist_ts/functions.inferencecliarguments.js +31 -3
  96. package/dist_ts/functions.mcpfleetworkertools.js +2 -2
  97. package/dist_ts/functions.proxycapacity.d.ts +50 -0
  98. package/dist_ts/functions.proxycapacity.js +142 -0
  99. package/dist_ts/functions.proxycapacitycli.d.ts +30 -0
  100. package/dist_ts/functions.proxycapacitycli.js +65 -0
  101. package/dist_ts/functions.remotecli.d.ts +30 -3
  102. package/dist_ts/functions.remotecli.js +44 -18
  103. package/dist_ts/functions.ticketvalidation.js +11 -2
  104. package/dist_ts/interfaces.auth.d.ts +25 -4
  105. package/dist_ts/interfaces.auth.js +15 -1
  106. package/dist_ts/plugins.d.ts +5 -1
  107. package/dist_ts/plugins.js +10 -2
  108. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  109. package/dist_ts_authswitch/authority-contract.js +1 -1
  110. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  111. package/dist_ts_authswitch/authority-overview.js +17 -6
  112. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  113. package/dist_ts_authswitch/authority-placement.js +19 -26
  114. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  115. package/dist_ts_authswitch/authority-renewal.js +56 -0
  116. package/dist_ts_authswitch/authority-usagelimit.d.ts +29 -0
  117. package/dist_ts_authswitch/authority-usagelimit.js +66 -2
  118. package/dist_ts_authswitch/authority-usagewindows.d.ts +6 -0
  119. package/dist_ts_authswitch/authority-usagewindows.js +15 -1
  120. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  121. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  122. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  123. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  124. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  125. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  126. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  127. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  128. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  129. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  130. package/dist_ts_interfaces/devices.d.ts +1012 -5
  131. package/dist_ts_interfaces/devices.js +68 -2
  132. package/dist_ts_interfaces/fleetworkers.d.ts +5 -3
  133. package/dist_ts_interfaces/gateway.d.ts +151 -0
  134. package/dist_ts_interfaces/gateway.js +66 -0
  135. package/dist_ts_interfaces/inbox.d.ts +234 -0
  136. package/dist_ts_interfaces/inbox.js +101 -0
  137. package/dist_ts_interfaces/index.d.ts +3 -0
  138. package/dist_ts_interfaces/index.js +4 -1
  139. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  140. package/dist_ts_interfaces/interfaces.js +4 -2
  141. package/dist_ts_interfaces/management.d.ts +4 -4
  142. package/dist_ts_interfaces/management.js +3 -2
  143. package/dist_ts_interfaces/mcprequests.d.ts +48 -6
  144. package/dist_ts_interfaces/mcprequests.js +12 -1
  145. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  146. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  147. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  148. package/dist_ts_interfaces/plugins.d.ts +2 -1
  149. package/dist_ts_interfaces/plugins.js +4 -2
  150. package/dist_ts_interfaces/proxycapacity.d.ts +99 -0
  151. package/dist_ts_interfaces/proxycapacity.js +74 -0
  152. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  153. package/dist_ts_interfaces/requests.accounts.js +3 -1
  154. package/dist_ts_interfaces/requests.d.ts +3 -2
  155. package/dist_ts_interfaces/requests.js +1 -1
  156. package/docs/authswitch.md +20 -1
  157. package/package.json +6 -5
  158. package/readme.md +191 -31
  159. package/ts/00_commitinfo_data.ts +1 -1
  160. package/ts/aglapi/aglapisurface.document.ts +520 -16
  161. package/ts/aglapi/interfaces.ts +1 -0
  162. package/ts/classes.accountsactions.ts +30 -3
  163. package/ts/classes.authmodels.ts +22 -3
  164. package/ts/classes.authstore.ts +15 -1
  165. package/ts/classes.claudeharness.ts +27 -1
  166. package/ts/classes.cli.ts +7 -3
  167. package/ts/classes.codexclientadapter.ts +14 -1
  168. package/ts/classes.controller.ts +1428 -249
  169. package/ts/classes.controllerdevices.ts +6 -0
  170. package/ts/classes.controllermanagement.ts +40 -7
  171. package/ts/classes.gatewayclient.ts +401 -0
  172. package/ts/classes.gatewayclientstore.ts +272 -0
  173. package/ts/classes.inbox.ts +239 -0
  174. package/ts/classes.inferencerouter.ts +27 -2
  175. package/ts/classes.inferenceservice.ts +28 -1
  176. package/ts/classes.mcpclient.ts +42 -3
  177. package/ts/classes.mcpcontrollerhost.ts +15 -0
  178. package/ts/classes.mcptools.ts +42 -9
  179. package/ts/classes.mcpvalidation.ts +32 -1
  180. package/ts/classes.nativesessions.ts +50 -12
  181. package/ts/classes.opencodeclient.ts +55 -4
  182. package/ts/classes.proxycontrol.ts +16 -0
  183. package/ts/classes.proxycontrolclient.ts +30 -0
  184. package/ts/classes.proxydaemon.ts +8 -0
  185. package/ts/classes.proxymonitor.ts +12 -0
  186. package/ts/classes.publishedset.ts +56 -0
  187. package/ts/classes.sessionfeed.ts +17 -20
  188. package/ts/classes.systemmetricssampler.ts +13 -2
  189. package/ts/classes.ticketstore.ts +73 -12
  190. package/ts/classes.trustedproxysecrets.ts +5 -0
  191. package/ts/driver/classes.directreports.ts +25 -6
  192. package/ts/driver/classes.driverservice.ts +75 -14
  193. package/ts/fleet/classes.claudeworkers.ts +112 -39
  194. package/ts/fleet/classes.codexworkers.ts +21 -6
  195. package/ts/fleet/classes.workercommand.ts +14 -4
  196. package/ts/fleet/classes.workers.ts +9 -2
  197. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  198. package/ts/fleet/functions.workervalidation.ts +1 -1
  199. package/ts/fleet/interfaces.workers.ts +20 -5
  200. package/ts/functions.agentmessage.ts +3 -0
  201. package/ts/functions.controllermanagementsurface.ts +15 -0
  202. package/ts/functions.deviceapi.ts +1071 -34
  203. package/ts/functions.fleetworkercli.ts +10 -7
  204. package/ts/functions.gatewaycli.ts +436 -0
  205. package/ts/functions.gatewayroute.ts +429 -0
  206. package/ts/functions.inferencecli.ts +26 -0
  207. package/ts/functions.inferencecliarguments.ts +30 -4
  208. package/ts/functions.mcpfleetworkertools.ts +1 -1
  209. package/ts/functions.proxycapacity.ts +191 -0
  210. package/ts/functions.proxycapacitycli.ts +104 -0
  211. package/ts/functions.remotecli.ts +56 -20
  212. package/ts/functions.ticketvalidation.ts +11 -1
  213. package/ts/interfaces.auth.ts +36 -4
  214. package/ts/plugins.ts +12 -0
  215. package/ts_authswitch/authority-contract.ts +20 -0
  216. package/ts_authswitch/authority-overview.ts +28 -6
  217. package/ts_authswitch/authority-placement.ts +27 -32
  218. package/ts_authswitch/authority-renewal.ts +64 -0
  219. package/ts_authswitch/authority-usagelimit.ts +84 -1
  220. package/ts_authswitch/authority-usagewindows.ts +13 -0
  221. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  222. package/ts_authswitch/classes.authoritycli.ts +49 -2
  223. package/ts_authswitch/classes.authorityclient.ts +14 -4
  224. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  225. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  226. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  227. package/ts_authswitch/native-contracts.md +21 -0
  228. package/ts_authswitch/readme.md +1 -1
  229. package/ts_interfaces/devices.schema.json +3573 -603
  230. package/ts_interfaces/devices.ts +1093 -4
  231. package/ts_interfaces/fleetworkers.ts +5 -3
  232. package/ts_interfaces/gateway.ts +242 -0
  233. package/ts_interfaces/inbox.ts +287 -0
  234. package/ts_interfaces/index.ts +3 -0
  235. package/ts_interfaces/interfaces.ts +9 -2
  236. package/ts_interfaces/management.ts +6 -4
  237. package/ts_interfaces/mcprequests.ts +61 -4
  238. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  239. package/ts_interfaces/nativesessions.ts +17 -3
  240. package/ts_interfaces/plugins.ts +3 -1
  241. package/ts_interfaces/proxycapacity.ts +162 -0
  242. package/ts_interfaces/requests.accounts.ts +20 -0
  243. package/ts_interfaces/requests.ts +4 -0
  244. package/ts_web/00_commitinfo_data.ts +1 -1
  245. package/ts_web/accounts.plugins.ts +4 -2
  246. package/ts_web/classes.accountsreadmodel.ts +33 -0
  247. package/ts_web/classes.browserpresentation.ts +19 -6
  248. package/ts_web/classes.inboxfeed.ts +329 -0
  249. package/ts_web/classes.nativesessionstate.ts +9 -23
  250. package/ts_web/elements.accounts.ts +121 -113
  251. package/ts_web/elements.configurationpane.ts +24 -37
  252. package/ts_web/elements.deployments.ts +66 -2
  253. package/ts_web/elements.devices.ts +4 -17
  254. package/ts_web/elements.flexlimitstrip.ts +21 -70
  255. package/ts_web/elements.harnesscontrollerapp.ts +198 -222
  256. package/ts_web/elements.inbox.ts +808 -0
  257. package/ts_web/functions.inbox.ts +95 -0
  258. package/ts_web/functions.sessioncards.ts +40 -0
  259. package/ts_web/plugins.ts +2 -0
@@ -8,7 +8,7 @@ import { ControllerWorkerCallers, type IWorkerCodexCallerOrigin } from './classe
8
8
  import { WorkerCallerBindingStore } from './classes.workercallerbindings.js';
9
9
  import { FleetWorkerLaunches } from './fleet/classes.workerlaunches.js';
10
10
  import { workerCallerEnrollmentToolName } from './classes.mcpworkercaller.js';
11
- import { readWorkerProcessSnapshot, readWorkerUnixSocketOwner, workerSnapshotsEqual, isWorkerCallerProofRefusal, type IWorkerCallerConnection } from './functions.workerprocessproof.js';
11
+ import { proveConnectionProcessAncestry, readWorkerProcessSnapshot, readWorkerUnixSocketOwner, workerSnapshotsEqual, isWorkerCallerProofRefusal, type IWorkerCallerConnection } from './functions.workerprocessproof.js';
12
12
  import { proveCliCallerClaudeSession } from './functions.cliticketsession.js';
13
13
  import type { IFleetWorkerCallerHooks, TFleetWorkerCallerLaunch } from '../ts_interfaces/workercallers.js';
14
14
  import { awaitWithAbortSignal } from './functions.abort.js';
@@ -52,7 +52,7 @@ import { AccountsActions } from './classes.accountsactions.js';
52
52
  import { AglProxyMonitor } from './classes.proxymonitor.js';
53
53
  import type { TAglProxyLeaseCatalog } from './classes.proxycontrol.js';
54
54
  import { AglProxyLeaseHolder } from './classes.proxyleaseholder.js';
55
- import { AglProxyRefusedError } from './classes.proxycontrolclient.js';
55
+ import { AglProxyOutdatedError, AglProxyRefusedError, AglProxyUnavailableError } from './classes.proxycontrolclient.js';
56
56
  import { inferenceHarnessLaunch } from './functions.inferencelaunch.js';
57
57
  import type { IControllerTerminalAgentInferenceSession } from './classes.terminalmanager.js';
58
58
  import type { TConfigurationHostClaudeLogin } from './configuration/classes.inferencereview.js';
@@ -109,7 +109,36 @@ import {
109
109
  deviceRelayedEventTypes,
110
110
  deviceSessionRow,
111
111
  deviceSessionRows,
112
+ deviceInboxList,
113
+ deviceTicketQuestion,
114
+ deviceDriverStatus,
115
+ deviceDirectReport,
116
+ assertDeviceTicketAnswerRequest,
117
+ assertDeviceDriverReadRequest,
118
+ assertDeviceDriverSendRequest,
119
+ assertDeviceDirectReportMessageRequest,
120
+ serveDeviceDriver,
121
+ deviceDirectReportMessageRefusal,
122
+ deviceHostAgl,
123
+ deviceHostDevice,
124
+ readDeviceHostSections,
125
+ assertDeviceBoardListRequest,
126
+ assertDeviceTicketGetRequest,
127
+ assertDeviceTicketCommentRequest,
128
+ assertDeviceTicketAskRequest,
129
+ assertDeviceTicketMoveRequest,
130
+ deviceBoardPage,
131
+ deviceTicket,
132
+ deviceTicketCard,
133
+ deviceTicketComment,
134
+ deviceTicketDiscussion,
135
+ deviceTicketPlans,
136
+ deviceTicketRefusal,
137
+ readDeviceTicketPlacement,
138
+ type IDeviceTicketViewer,
112
139
  } from './functions.deviceapi.js';
140
+ import { ControllerInbox, inboxTitle, type TInboxSource } from './classes.inbox.js';
141
+ import { compareFleetVersions } from '../ts_interfaces/functions.fleetversion.js';
113
142
  import {
114
143
  controllerPackageName,
115
144
  controllerBuiltinCommands,
@@ -337,6 +366,9 @@ import {
337
366
  type IReq_ControllerSetupBegin,
338
367
  type IReq_ControllerSetupFinish,
339
368
  type IReq_ControllerStatus,
369
+ type IReq_ControllerManagementStatus,
370
+ type IReq_ControllerGatewaySync,
371
+ type IControllerGatewayStatus,
340
372
  type IReq_ControllerUpgradeLaunch,
341
373
  type IReq_ControllerUpgradePrepareBegin,
342
374
  type IReq_ControllerUpgradeFinalize,
@@ -345,6 +377,10 @@ import {
345
377
  type IReq_ControllerSystemMetricsHistory,
346
378
  type IReq_ControllerMcpProjectsList,
347
379
  type IReq_ControllerMcpSessionRead,
380
+ type IControllerMcpNativeSessionDetail,
381
+ type TControllerMcpSessionDetail,
382
+ controllerMcpNativeDeliveries,
383
+ controllerMcpNativeSessionSettledLimit,
348
384
  type IReq_ControllerMcpSessionScratchpadRead,
349
385
  type IReq_ControllerMcpSessionScratchpadUpdate,
350
386
  type IReq_ControllerMcpSessionSend,
@@ -371,7 +407,29 @@ import {
371
407
  type IReq_DeviceSessionRead,
372
408
  type IReq_DeviceSessionSend,
373
409
  type IReq_DeviceSessionsList,
410
+ type IReq_DeviceInboxList,
411
+ type IReq_DeviceTicketAnswer,
412
+ type IReq_DeviceDriverGet,
413
+ type IReq_DeviceDriverSeen,
414
+ type IReq_DeviceDriverRead,
415
+ type IReq_DeviceDriverSend,
416
+ type IReq_DeviceDirectReportsList,
417
+ type IReq_DeviceDirectReportMessage,
418
+ type IReq_DeviceHostGet,
419
+ type IReq_DeviceBoardList,
420
+ type IReq_DeviceTicketGet,
421
+ type IReq_DeviceTicketComment,
422
+ type IReq_DeviceTicketAsk,
423
+ type IReq_DeviceTicketMove,
374
424
  type IControllerSessionFeedRow,
425
+ type IReq_ControllerInboxList,
426
+ type TControllerInboxAnswer,
427
+ type TControllerElicitation,
428
+ type TControllerInboxItem,
429
+ type TControllerInboxWhere,
430
+ type TControllerSessionFeedHarness,
431
+ type IFleetDeployStatus,
432
+ controllerInboxLimits,
375
433
  deviceProtocolVersion,
376
434
  deviceRevokedCloseCode,
377
435
  type IControllerProviderAccountRateLimits,
@@ -394,6 +452,11 @@ import {
394
452
  import { controllerListenerOptions } from './functions.controlleradmission.js';
395
453
  import { ControllerTrustedProxySecrets } from './classes.trustedproxysecrets.js';
396
454
  import { TpmSecretCodec } from './classes.tpmsecretcodec.js';
455
+ import { ControllerGatewayClient } from './classes.gatewayclient.js';
456
+ import { ControllerGatewayClientStore } from './classes.gatewayclientstore.js';
457
+ import { gatewayRouteKey } from './functions.gatewayroute.js';
458
+ import { readManagementPeerConnection } from './functions.controllermanagementsurface.js';
459
+ import { assertConfigurationLocalCliActor } from './functions.configurationactor.js';
397
460
  import { resolveAGLHomePaths } from './classes.aglhome.js';
398
461
  import { selectControllerBrowserPaint } from './functions.browserpaintartifact.js';
399
462
  import { ControllerBrowserViewerAssets } from './functions.browserpaintassets.js';
@@ -512,16 +575,17 @@ import { FleetService } from './fleet/classes.service.js';
512
575
  import type { IFleetConfiguration, IFleetDriverConfiguration, IFleetOperation, IFleetScope, IFleetUnboundDriver, TFleetOperation, TFleetRequest } from '../ts_interfaces/fleet.js';
513
576
  import { findFleetRepository, fleetRepositorySlug } from './fleet/functions.releasefacts.js';
514
577
  import { discoverFleetRepositories } from './fleet/functions.discovery.js';
515
- import { DriverError, DriverService } from './driver/classes.driverservice.js';
578
+ import { DriverError, DriverService, type IDriverAssistantMessage } from './driver/classes.driverservice.js';
516
579
  import { DriverEventRelay, driverRelayMaximumMessageBytes } from './driver/classes.drivereventrelay.js';
517
- import { DirectReports, type TDirectReportChannel } from './driver/classes.directreports.js';
580
+ import { DirectReports, directReportRuntimeId, type TDirectReportChannel } from './driver/classes.directreports.js';
518
581
  import { driverToolsByName, driverDirectReportReadDefaultLimit, type TDriverDirectReportOperation } from './driver/functions.drivertools.js';
519
- import { controllerDriverErrorCodes } from '../ts_interfaces/driver.js';
582
+ import { controllerDriverErrorCodes, type IControllerDriverStatus } from '../ts_interfaces/driver.js';
520
583
  import type { IReq_ControllerDriverEnsure, IReq_ControllerDriverGet, IReq_ControllerDriverSeen } from '../ts_interfaces/requests.driver.js';
521
584
  import type { IReq_ControllerFleetWorkerList, IReq_ControllerFleetWorkerRead, IReq_ControllerFleetWorkerSteer } from '../ts_interfaces/requests.fleetworkers.js';
522
585
  import type {
523
586
  IControllerNativeSession,
524
587
  IControllerNativeSessionRef,
588
+ TControllerNativeJobDelivery,
525
589
  IReq_ControllerNativeSessionAuxiliaryGet,
526
590
  IReq_ControllerNativeSessionIntelligenceAsk,
527
591
  IReq_ControllerNativeSessionPermissionReply,
@@ -533,19 +597,19 @@ import type {
533
597
  } from '../ts_interfaces/nativesessions.js';
534
598
  import { ControllerUploadManager, type IControllerUploadHandle } from './classes.uploadmanager.js';
535
599
  import type { IReq_ControllerDirectReportAdopt, IReq_ControllerDirectReportAppoint, IReq_ControllerDirectReportList, IReq_ControllerDirectReportMessage, IReq_ControllerDirectReportPreflight, IReq_ControllerDirectReportRead, IReq_ControllerDirectReportRetire, TDirectReportPage } from '../ts_interfaces/requests.directreports.js';
536
- import { SessionFeed, SessionFeedAcknowledgementError, SessionFeedTranscripts, type ISessionFeedTerminal, type TSessionFeedProjectRead } from './classes.sessionfeed.js';
600
+ import { SessionFeed, SessionFeedAcknowledgementError, SessionFeedTranscripts, sessionFeedRowId, type ISessionFeedTerminal, type TSessionFeedProjectRead } from './classes.sessionfeed.js';
537
601
  import { SessionFeedAcknowledgementStore } from './classes.sessionfeedacknowledgements.js';
538
602
  import { HarnessReleaseNotices, type THarnessReleaseSource } from './classes.harnessreleases.js';
539
603
  import { assertSessionFeedAcknowledgeRequest } from './functions.sessionfeedvalidation.js';
540
- import { NativeSessions, type IResolvedNativeSession } from './classes.nativesessions.js';
604
+ import { NativeSessions, nativeSessionReadOnlyMessages, type IResolvedNativeSession } from './classes.nativesessions.js';
541
605
  import { claudeProfileForHome, fleetAdoptCommand, listUnboundDrivers } from './fleet/functions.unbounddrivers.js';
542
606
  import type { IReq_ControllerSessionFeedAcknowledge, IReq_ControllerSessionFeedList } from '../ts_interfaces/sessionfeed.js';
543
607
  import { UsageFeed, UsageFeedRefusal } from './classes.usagefeed.js';
544
608
  import type { IReq_ControllerUsageUnwatch, IReq_ControllerUsageWatch, TControllerUsageDelta } from '../ts_interfaces/metrics.js';
545
609
  import { ticketActorFromCaller } from './functions.ticketactor.js';
546
610
  import { ticketOwnerActor, ticketOwnerPrincipalId, resolveTicketOwnerAssignment } from './functions.ticketowner.js';
547
- import { ticketInputSchemas } from './functions.ticketvalidation.js';
548
- import { readTicketRevisionConflict, type ITicket, type ITicketActor, type TTicketOperation, type TTicketRequest, type TTicketFleetEvent, type ITicketFleetEventResult } from '../ts_interfaces/tickets.js';
611
+ import { assertTicketRequest, ticketInputSchemas } from './functions.ticketvalidation.js';
612
+ import { readTicketRevisionConflict, type ITicket, type ITicketActor, type ITicketBoard, type ITicketComment, type ITicketDetail, type TTicketOperation, type TTicketRequest, type TTicketResponse, type TTicketFleetEvent, type ITicketFleetEventResult } from '../ts_interfaces/tickets.js';
549
613
  import type { TControllerTicketRequest } from '../ts_interfaces/requests.tickets.js';
550
614
  import { ControllerJobSupervisor } from './classes.jobsupervisor.js';
551
615
  import {
@@ -2426,6 +2490,23 @@ const assertNativeSessionWritable = (resolvedArg: IResolvedNativeSession): void
2426
2490
  const { readOnly } = resolvedArg.session;
2427
2491
  if (readOnly) throw new plugins.typedrequest.TypedResponseError(readOnly.message, { code: 'session_read_only' });
2428
2492
  };
2493
+ /**
2494
+ * A Claude Code session outside AGL as an MCP caller sees it: agents reach only background jobs, so any other session
2495
+ * that would take the owner's message is read-only for them (`notBackgroundJob`).
2496
+ */
2497
+ const mcpNativeSession = (resolvedArg: IResolvedNativeSession): IControllerNativeSession => (
2498
+ resolvedArg.claudeJob || resolvedArg.session.readOnly ? resolvedArg.session
2499
+ : { ...resolvedArg.session, readOnly: { reason: 'notBackgroundJob', message: nativeSessionReadOnlyMessages.notBackgroundJob } }
2500
+ );
2501
+ /** Refuses an MCP agent message to a Claude Code session outside AGL that takes none now, naming why. */
2502
+ const assertMcpNativeMessageable = (sessionArg: IControllerNativeSession): void => {
2503
+ if (sessionArg.readOnly) throw new plugins.typedrequest.TypedResponseError(sessionArg.readOnly.message, { code: 'session_read_only' });
2504
+ if (!sessionArg.jobDelivery) throw new plugins.typedrequest.TypedResponseError(nativeSessionReadOnlyMessages.notBackgroundJob, { code: 'session_read_only' });
2505
+ };
2506
+ /** The canonical path of an existing directory, or `undefined`; a session's directory matches a project's only so. */
2507
+ const canonicalDirectory = async (pathArg: string): Promise<string | undefined> => {
2508
+ try { return await plugins.fs.promises.realpath(pathArg); } catch { return undefined; }
2509
+ };
2429
2510
  /**
2430
2511
  * A harness's refusal of an elicitation reply -- the answer does not fit the request, or the request is gone -- as the
2431
2512
  * typed refusal it is; its text never carries what the owner entered. Every other error passes as it is.
@@ -2436,6 +2517,14 @@ const elicitationRefusal = (errorArg: unknown): unknown => (
2436
2517
  : errorArg
2437
2518
  );
2438
2519
 
2520
+ /** The ticket changes the owner makes from the browser's board or a paired device, each with its audit type. */
2521
+ type TTicketChangeOperation = 'comment' | 'ask' | 'move';
2522
+ const ticketChangeAuditTypes = {
2523
+ comment: 'ticket.comment',
2524
+ ask: 'ticket.ask',
2525
+ move: 'ticket.move',
2526
+ } as const satisfies Record<TTicketChangeOperation, TControllerAuditEventType>;
2527
+
2439
2528
  const validateRequest = <T>(validatorArg: () => T): T => {
2440
2529
  try {
2441
2530
  return validatorArg();
@@ -3223,6 +3312,8 @@ export class OpenCodeController {
3223
3312
  this.fleetWorkers = new FleetWorkers({ sample: () => this.systemMetricsSampler.sample(), ticketEffects: this.requireFleetTicketEffects(), sessionBindings: directReports,
3224
3313
  nativeMessages: { send: (_owner, request, actor) => this.sendFleetNativeMessage(request, actor) },
3225
3314
  claudeReleases: (releaseArg) => this.observeClaudeRelease(releaseArg, 'fleet'),
3315
+ // No controller event names a native thread; the Inbox reads the fleet connection's requests again.
3316
+ onNativeCodexAttention: () => this.inbox?.nativeAttentionChanged('codex'),
3226
3317
  ...(this.fleetWorkerLaunches ? { callers: this.fleetWorkerLaunches } : {}) });
3227
3318
  // The Driver view's direct reports, an open fleet worker and the session feed follow worker changes and newly observed statuses.
3228
3319
  this.fleetWorkers.watchViews(() => {
@@ -3414,6 +3505,314 @@ export class OpenCodeController {
3414
3505
  });
3415
3506
  this.sessionFeed.start();
3416
3507
  }
3508
+ /** What waits for the owner, for the browser and devices alike (AGL-1635). */
3509
+ private inbox?: ControllerInbox;
3510
+ private startInbox(): void {
3511
+ if (this.inbox) return;
3512
+ this.inbox = new ControllerInbox({
3513
+ read: (sourceArg, previousArg, signalArg) => this.readInboxSource(sourceArg, previousArg, signalArg),
3514
+ hasViewers: async () => this.devices?.hasLivePeers() === true || (await this.controllerEventViewers()).length > 0,
3515
+ publish: (deltaArg) => {
3516
+ void this.pushControllerEvent({ type: 'inbox.changed', inbox: deltaArg, timestamp: Date.now() }).catch(() => undefined);
3517
+ },
3518
+ reportError: (messageArg, errorArg) => console.error(messageArg, errorArg),
3519
+ });
3520
+ }
3521
+
3522
+ /** The Inbox's items of one source, each read from the component that owns them. */
3523
+ private async readInboxSource(
3524
+ sourceArg: TInboxSource,
3525
+ previousArg: readonly TControllerInboxItem[],
3526
+ signalArg: AbortSignal,
3527
+ ): Promise<TControllerInboxItem[]> {
3528
+ switch (sourceArg) {
3529
+ case 'claude': return this.readInboxClaude();
3530
+ case 'codex': return this.readInboxCodex();
3531
+ case 'opencode': return this.readInboxOpenCode(previousArg, signalArg);
3532
+ case 'flex': return this.readInboxFlex(previousArg, signalArg);
3533
+ case 'native_waits': return this.readInboxNativeWaits();
3534
+ case 'driver': return this.readInboxDriver();
3535
+ case 'tickets': return this.readInboxTickets(signalArg);
3536
+ }
3537
+ }
3538
+
3539
+ /** The session feed's row of a session, and the name the Inbox shows for it. */
3540
+ private inboxRow(harnessArg: TControllerSessionFeedHarness, nativeIdArg: string, fallbackNameArg: string): { rowId: string; name: string } {
3541
+ const rowId = sessionFeedRowId(harnessArg, nativeIdArg);
3542
+ return { rowId, name: this.sessionFeed?.publishedRow(rowId)?.name ?? (fallbackNameArg.trim() || 'Untitled session') };
3543
+ }
3544
+
3545
+ /**
3546
+ * The items of a session's requests. A permission that the owner's auto-accept answers (`autoAcceptedArg`) waits for
3547
+ * nobody and is left out; questions and MCP forms are never answered automatically.
3548
+ */
3549
+ private inboxSessionItems(
3550
+ whereArg: Extract<TControllerInboxWhere, { kind: 'conversation' | 'child' | 'native' | 'driver' }>,
3551
+ answerArg: TControllerInboxAnswer,
3552
+ attentionArg: { permissions: readonly IControllerPermission[]; questions: readonly IControllerQuestion[]; elicitations?: readonly TControllerElicitation[] },
3553
+ autoAcceptedArg = false,
3554
+ ): TControllerInboxItem[] {
3555
+ const id = (kindArg: string, requestArg: { id: IControllerRuntimeId }, sessionArg: IControllerRuntimeId) => (
3556
+ `${kindArg}:${sessionArg.harnessId}:${sessionArg.nativeId}:${requestArg.id.nativeId}`
3557
+ );
3558
+ return [
3559
+ ...(autoAcceptedArg ? [] : attentionArg.permissions).map((permissionArg): TControllerInboxItem => ({
3560
+ id: id('permission', permissionArg, permissionArg.sessionId), kind: 'permission', since: permissionArg.createdAt,
3561
+ title: inboxTitle(permissionArg.title || permissionArg.type), where: whereArg, answer: answerArg, permission: permissionArg,
3562
+ })),
3563
+ ...attentionArg.questions.map((questionArg): TControllerInboxItem => ({
3564
+ id: id('question', questionArg, questionArg.sessionId), kind: 'question', since: questionArg.createdAt,
3565
+ title: inboxTitle(questionArg.questions[0]?.question || questionArg.questions[0]?.header || 'A question'),
3566
+ where: whereArg, answer: answerArg, question: questionArg,
3567
+ })),
3568
+ ...(attentionArg.elicitations ?? []).map((elicitationArg): TControllerInboxItem => ({
3569
+ id: id('elicitation', elicitationArg, elicitationArg.sessionId), kind: 'elicitation', since: elicitationArg.createdAt,
3570
+ title: inboxTitle(elicitationArg.message || `${elicitationArg.serverName} asks for input`),
3571
+ where: whereArg, answer: answerArg, elicitation: elicitationArg,
3572
+ })),
3573
+ ];
3574
+ }
3575
+
3576
+ /** A native session as the Inbox names it: where it runs and how the browser opens it. */
3577
+ private inboxNativeWhere(harnessArg: 'claude' | 'codex', nativeIdArg: string, titleArg: string): Extract<TControllerInboxWhere, { kind: 'native' }> {
3578
+ return { kind: 'native', session: { harness: harnessArg, nativeId: nativeIdArg }, harness: harnessArg,
3579
+ ...this.inboxRow(harnessArg, nativeIdArg, titleArg), host: plugins.os.hostname() };
3580
+ }
3581
+
3582
+ /** The requests Claude Code holds: its conversations' and those of AGL's turns in native sessions. */
3583
+ private readInboxClaude(): TControllerInboxItem[] {
3584
+ const harness = this.claudeHarness;
3585
+ if (!harness || harness.closed) return [];
3586
+ return harness.pendingAttention().flatMap((entryArg) => {
3587
+ if (entryArg.projectId === undefined) {
3588
+ return this.inboxSessionItems(this.inboxNativeWhere('claude', entryArg.nativeId, entryArg.title), 'native', entryArg.attention);
3589
+ }
3590
+ const sessionId = claudeRuntimeId(entryArg.nativeId);
3591
+ return this.inboxSessionItems({
3592
+ kind: 'conversation', projectId: entryArg.projectId, sessionId, harness: 'claude',
3593
+ ...this.inboxRow('claude', entryArg.nativeId, entryArg.title),
3594
+ }, 'conversation', entryArg.attention, this.isProjectAutoAcceptedSession(entryArg.projectId, sessionId));
3595
+ });
3596
+ }
3597
+
3598
+ /** The requests the Codex connections hold: the conversations' and, on the fleet's connection, the native threads'. */
3599
+ private readInboxCodex(): TControllerInboxItem[] {
3600
+ const clients = this.codexConnections
3601
+ ? this.codexConnections.all().flatMap((runtimeArg) => runtimeArg.supervisor.getStatus().healthy ? [runtimeArg.client] : [])
3602
+ : this.codexClient && this.codexSupervisor?.getStatus().healthy ? [this.codexClient] : [];
3603
+ const conversations = clients.flatMap((clientArg) => clientArg.pendingAttention().flatMap((entryArg) => {
3604
+ const sessionId = codexRuntimeId(entryArg.threadId);
3605
+ return this.inboxSessionItems({
3606
+ kind: 'conversation', projectId: entryArg.projectId, sessionId, harness: 'codex',
3607
+ ...this.inboxRow('codex', entryArg.threadId, entryArg.session.title),
3608
+ }, 'conversation', entryArg.attention, this.isProjectAutoAcceptedSession(entryArg.projectId, sessionId));
3609
+ }));
3610
+ const native = (this.fleetWorkers?.nativePendingAttention('codex') ?? []).flatMap((entryArg) => (
3611
+ this.inboxSessionItems(this.inboxNativeWhere('codex', entryArg.nativeId, entryArg.title), 'native', entryArg.attention)
3612
+ ));
3613
+ return [...conversations, ...native];
3614
+ }
3615
+
3616
+ /**
3617
+ * The requests of the OpenCode conversations the feed shows waiting, from the project's pending lists, and of their
3618
+ * direct children (subagents), from `readOpenCodeFamilyAttention`, the read the browser's child scopes use: only a
3619
+ * managed conversation has children AGL answers. A project or a conversation whose read fails keeps the items it had.
3620
+ */
3621
+ private async readInboxOpenCode(previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3622
+ const client = this.openCodeClient;
3623
+ if (!client) return [];
3624
+ const byProject = new Map<string, IControllerSessionFeedRow[]>();
3625
+ for (const row of this.sessionFeed?.publishedRows() ?? []) {
3626
+ if (row.harness !== 'opencode' || row.state !== 'needs_input' || row.nativeWait !== undefined || row.open.kind !== 'conversation') continue;
3627
+ byProject.set(row.open.projectId, [...byProject.get(row.open.projectId) ?? [], row]);
3628
+ }
3629
+ const kept = (predicateArg: (whereArg: TControllerInboxWhere) => boolean) => previousArg.filter((itemArg) => predicateArg(itemArg.where));
3630
+ const items: TControllerInboxItem[] = [];
3631
+ for (const [projectId, rows] of byProject) {
3632
+ signalArg.throwIfAborted();
3633
+ let pending: { permissions: IControllerPermission[]; questions: IControllerQuestion[] };
3634
+ try {
3635
+ const { directory } = await this.resolveProject(projectId);
3636
+ const [permissions, questions] = await Promise.all([
3637
+ client.listPermissions(directory, undefined, signalArg), client.listQuestions(directory, undefined, signalArg),
3638
+ ]);
3639
+ pending = { permissions, questions };
3640
+ } catch (errorArg) {
3641
+ signalArg.throwIfAborted();
3642
+ this.reportInboxError(`opencode:${projectId}`, errorArg);
3643
+ items.push(...kept((whereArg) => (whereArg.kind === 'conversation' || whereArg.kind === 'child') && whereArg.projectId === projectId));
3644
+ continue;
3645
+ }
3646
+ const roots = new Set(rows.map((rowArg) => (rowArg.open as { sessionId: IControllerRuntimeId }).sessionId.nativeId));
3647
+ const asksElsewhere = [...pending.permissions, ...pending.questions].some((requestArg) => !roots.has(requestArg.sessionId.nativeId));
3648
+ for (const row of rows) {
3649
+ const open = row.open as Extract<IControllerSessionFeedRow['open'], { kind: 'conversation' }>;
3650
+ const parentSessionId = open.sessionId as IControllerRuntimeId & { harnessId: 'opencode' };
3651
+ const own = (requestArg: { sessionId: IControllerRuntimeId }) => requestArg.sessionId.nativeId === parentSessionId.nativeId;
3652
+ const autoAccepted = this.isProjectAutoAcceptedSession(projectId, parentSessionId);
3653
+ items.push(...this.inboxSessionItems({
3654
+ kind: 'conversation', projectId, sessionId: parentSessionId, harness: 'opencode', rowId: row.id, name: row.name,
3655
+ }, 'conversation', { permissions: pending.permissions.filter(own), questions: pending.questions.filter(own) }, autoAccepted));
3656
+ if (!asksElsewhere) continue;
3657
+ try {
3658
+ for (const { child, permissions, questions } of (await this.readOpenCodeFamilyAttention(projectId, parentSessionId, signalArg, true))?.children ?? []) {
3659
+ items.push(...this.inboxSessionItems({
3660
+ kind: 'child', projectId, parentSessionId, childSessionId: child.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
3661
+ harness: 'opencode', rowId: row.id, name: row.name, childName: child.session.title || 'Subagent',
3662
+ }, 'child', { permissions, questions }, autoAccepted));
3663
+ }
3664
+ } catch (errorArg) {
3665
+ signalArg.throwIfAborted();
3666
+ // A conversation AGL does not manage has no children it answers.
3667
+ if (errorArg instanceof ControllerSessionIdentityError && (errorArg.code === 'not_found' || errorArg.code === 'tombstoned')) continue;
3668
+ this.reportInboxError(`opencode:${row.id}`, errorArg);
3669
+ items.push(...kept((whereArg) => whereArg.kind === 'child' && whereArg.rowId === row.id));
3670
+ }
3671
+ }
3672
+ }
3673
+ return items;
3674
+ }
3675
+
3676
+ /** The failures of the Inbox's partial reads, by what failed: a lasting one is reported once. */
3677
+ private readonly inboxErrors = new Map<string, string>();
3678
+ private reportInboxError(keyArg: string, errorArg: unknown): void {
3679
+ const message = errorArg instanceof Error ? errorArg.message : String(errorArg);
3680
+ if (this.inboxErrors.get(keyArg) === message) return;
3681
+ if (this.inboxErrors.size >= 256) this.inboxErrors.clear();
3682
+ this.inboxErrors.set(keyArg, message);
3683
+ console.error(`Inbox: reading ${keyArg} failed.`, errorArg);
3684
+ }
3685
+
3686
+ /**
3687
+ * The Flex permissions of the conversations the feed shows waiting, and of the driver, by the run that asks (a
3688
+ * subagent's by its root conversation). A permission the owner's auto-accept answers is left out.
3689
+ */
3690
+ private async readInboxFlex(previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3691
+ const supervisor = this.flexSupervisor;
3692
+ if (!supervisor || !this.flexIsOperational()) return [];
3693
+ const rows = new Map((this.sessionFeed?.publishedRows() ?? []).flatMap((rowArg) => rowArg.harness === 'flex'
3694
+ && rowArg.state === 'needs_input' && rowArg.nativeWait === undefined && rowArg.open.kind === 'conversation'
3695
+ ? [[`${rowArg.open.projectId}\0${rowArg.open.sessionId.nativeId}`, rowArg] as const] : []));
3696
+ const driver = await this.driverService?.driverSession();
3697
+ // The driver's status follows its session through `driver.changed`, which marks this source stale.
3698
+ const driverWaits = driver !== undefined && this.driverService?.current().session?.attention === true;
3699
+ const projectIds = new Set([...rows.values()].map((rowArg) => (rowArg.open as { projectId: string }).projectId));
3700
+ if (driverWaits) projectIds.add(driver.projectId);
3701
+ const items: TControllerInboxItem[] = [];
3702
+ for (const projectId of projectIds) {
3703
+ signalArg.throwIfAborted();
3704
+ try {
3705
+ const { permissions } = await supervisor.request('permission.list', { scopeId: projectId }, signalArg);
3706
+ for (const permission of permissions) {
3707
+ const authority = this.flexPermissionAuthority(projectId, permission);
3708
+ if (!authority || this.autoAcceptedFlexPermission(projectId, permission)) continue;
3709
+ const rootNativeId = authority.type === 'managed' ? authority.run.sessionId : authority.lease.rootAuthority.sessionId;
3710
+ const sessionId = flexRuntimeId(rootNativeId);
3711
+ if (driverWaits && driver.projectId === projectId && driver.nativeId === rootNativeId) {
3712
+ items.push(...this.inboxSessionItems({ kind: 'driver', projectId, sessionId }, 'conversation',
3713
+ { permissions: [this.toFlexPermission(permission)], questions: [] }));
3714
+ continue;
3715
+ }
3716
+ const row = rows.get(`${projectId}\0${rootNativeId}`);
3717
+ if (!row) continue;
3718
+ items.push(...this.inboxSessionItems({
3719
+ kind: 'conversation', projectId, sessionId, harness: 'flex', rowId: row.id, name: row.name,
3720
+ }, 'conversation', { permissions: [this.toFlexPermission(permission)], questions: [] }));
3721
+ }
3722
+ } catch (errorArg) {
3723
+ signalArg.throwIfAborted();
3724
+ this.reportInboxError(`flex:${projectId}`, errorArg);
3725
+ items.push(...previousArg.filter((itemArg) => (itemArg.where.kind === 'conversation' || itemArg.where.kind === 'driver')
3726
+ && itemArg.where.projectId === projectId));
3727
+ }
3728
+ }
3729
+ return items;
3730
+ }
3731
+
3732
+ /** The sessions whose harness waits in its own client: AGL holds no request for them, so they are answered there. */
3733
+ private readInboxNativeWaits(): TControllerInboxItem[] {
3734
+ const harnessLabels: Record<TControllerSessionFeedHarness, string> = { claude: 'Claude Code', codex: 'Codex', flex: 'Flex', opencode: 'OpenCode' };
3735
+ return (this.sessionFeed?.publishedRows() ?? []).flatMap((rowArg): TControllerInboxItem[] => {
3736
+ const nativeWait = rowArg.nativeWait;
3737
+ if (rowArg.state !== 'needs_input' || !nativeWait || rowArg.open.kind === 'terminal') return [];
3738
+ const label = harnessLabels[rowArg.harness];
3739
+ const title = nativeWait.reason === 'approval' ? `Waits for approval in ${label}`
3740
+ : nativeWait.reason === 'user_input' ? `Waits for input in ${label}` : `Waits in ${label}`;
3741
+ const where: Extract<TControllerInboxWhere, { kind: 'conversation' | 'native' }> = rowArg.open.kind === 'conversation'
3742
+ ? { kind: 'conversation', projectId: rowArg.open.projectId, sessionId: rowArg.open.sessionId, harness: rowArg.harness, rowId: rowArg.id, name: rowArg.name }
3743
+ : { kind: 'native', session: nativeSessionRefOfFeed(rowArg.open), harness: rowArg.open.harness, rowId: rowArg.id, name: rowArg.name,
3744
+ host: plugins.os.hostname() };
3745
+ return [{ id: `native_wait:${rowArg.id}`, kind: 'native_wait', since: rowArg.updatedAt, title, where, answer: 'none',
3746
+ nativeWait: { reason: nativeWait.reason }, host: plugins.os.hostname() }];
3747
+ });
3748
+ }
3749
+
3750
+ /** The driver's `needs input:` turn, as the driver service found it; its own prompts are Flex session prompts. */
3751
+ private readInboxDriver(): TControllerInboxItem[] {
3752
+ const turn = this.driverService?.needsInput();
3753
+ if (!turn) return [];
3754
+ return [{ id: `driver:${turn.nativeId}:${turn.messageId}`, kind: 'driver', since: turn.at, title: inboxTitle(turn.line),
3755
+ where: { kind: 'driver', projectId: turn.projectId, sessionId: flexRuntimeId(turn.nativeId) }, answer: 'none',
3756
+ line: turn.line, messageId: turn.messageId }];
3757
+ }
3758
+
3759
+ /**
3760
+ * The board's open questions that wait for the owner: every one the owner did not ask, on a ticket that is not done.
3761
+ * A deploy plan's and a maintenance window's question is the owner's go, shown with what the deploy monitor observes.
3762
+ */
3763
+ private async readInboxTickets(signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3764
+ const open = (await this.ticketStore.openQuestionTickets(signalArg))
3765
+ .filter(({ question }) => question.askedBy.role !== 'owner');
3766
+ const goes = open.some(({ ticket, question }) => ticket.deployPlan?.questionId === question.id);
3767
+ let status: IFleetDeployStatus | undefined;
3768
+ if (goes && this.deployMonitor) {
3769
+ try {
3770
+ status = await this.deployMonitor.status();
3771
+ } catch (errorArg) {
3772
+ signalArg.throwIfAborted();
3773
+ // The go is the owner's either way; what runs where is shown once the monitor answers.
3774
+ this.reportInboxError('deployments', errorArg);
3775
+ }
3776
+ }
3777
+ return open.map(({ ticket, question }): TControllerInboxItem => {
3778
+ const where: Extract<TControllerInboxWhere, { kind: 'ticket' }> = {
3779
+ kind: 'ticket', ticketId: ticket.id, ticketKey: ticket.key, ticketTitle: ticket.title, project: ticket.project, columnId: ticket.columnId,
3780
+ };
3781
+ const base = { since: Date.parse(question.createdAt), where, answer: 'ticket' as const, question };
3782
+ if (ticket.deployPlan?.questionId === question.id) {
3783
+ const plan = ticket.deployPlan;
3784
+ const target = status?.targets.find((targetArg) => targetArg.target.id === plan.target);
3785
+ const planned = target?.deployPlans.find((planArg) => planArg.key === ticket.key);
3786
+ const ships = (target?.notRunning.tickets ?? []).filter((ticketArg) => ticketArg.version !== undefined
3787
+ && compareFleetVersions(ticketArg.version, plan.version) <= 0);
3788
+ const name = target?.target.name ?? plan.target;
3789
+ return {
3790
+ ...base, id: `deploy_go:${ticket.key}:${question.id}`, kind: 'deploy_go',
3791
+ title: inboxTitle(`${name}${target?.target.environment ? ` → ${target.target.environment}` : ''}, ${target?.running ? `${target.running.version} → ` : ''}${plan.version}`),
3792
+ plan: {
3793
+ target: plan.target, version: plan.version,
3794
+ ...(target?.target.name === undefined ? {} : { targetName: target.target.name }),
3795
+ ...(target?.target.environment === undefined ? {} : { environment: target.target.environment }),
3796
+ ...(target?.running ? { runs: target.running.version } : {}),
3797
+ ...(target ? { deployWhen: target.deployWhen } : {}),
3798
+ ...(planned?.window ? { window: { from: planned.window.from, to: planned.window.to } } : {}),
3799
+ ships: ships.slice(0, controllerInboxLimits.ships).map(({ key, title }) => ({ key, title })),
3800
+ shipsTotal: ships.length,
3801
+ ...(planned?.assignee === undefined ? {} : { assignee: planned.assignee }),
3802
+ },
3803
+ };
3804
+ }
3805
+ if (ticket.maintenanceWindow?.questionId === question.id) {
3806
+ const window = ticket.maintenanceWindow;
3807
+ return {
3808
+ ...base, id: `window_go:${ticket.key}:${question.id}`, kind: 'window_go',
3809
+ title: inboxTitle(`Maintenance window for ${window.targets.join(', ')}`),
3810
+ window: { from: window.from, to: window.to, targets: [...window.targets] },
3811
+ };
3812
+ }
3813
+ return { ...base, id: `ticket_question:${ticket.key}:${question.id}`, kind: 'ticket_question', title: inboxTitle(question.question) };
3814
+ });
3815
+ }
3417
3816
  private ticketNotifier?: TicketNotifier;
3418
3817
  private boardPump?: BoardPump;
3419
3818
  private deployMonitor?: DeployMonitor;
@@ -3452,6 +3851,8 @@ export class OpenCodeController {
3452
3851
  private passkeyManager?: PasskeyManager;
3453
3852
  /** TLS-proxy mode only: the secret admission accepts from the reverse proxy, and its rotation. */
3454
3853
  private trustedProxySecrets?: ControllerTrustedProxySecrets;
3854
+ /** The controller's own route on its gateway (`agl remote gateway`), synced in the background once it is ready. */
3855
+ private gatewayClient?: ControllerGatewayClient;
3455
3856
  private openCodeSupervisor?: OpenCodeSupervisor;
3456
3857
  private openCodeClient?: OpenCodeClientAdapter;
3457
3858
  private flexSupervisor?: FlexSupervisor;
@@ -4886,6 +5287,8 @@ export class OpenCodeController {
4886
5287
  launch: (signalArg) => this.claudeLaunch(signalArg),
4887
5288
  emit: (eventArg) => this.handleClaudeEvent(eventArg),
4888
5289
  onSessionIdle: (projectIdArg, nativeIdArg) => this.scheduleQueuedClaudePrompt(projectIdArg, claudeRuntimeId(nativeIdArg)),
5290
+ // No controller event names a native session; the Inbox reads the harness's requests again.
5291
+ onNativeAttention: () => this.inbox?.nativeAttentionChanged('claude'),
4889
5292
  });
4890
5293
  try {
4891
5294
  await this.withCurrentSessionIdentityProjects(
@@ -6979,7 +7382,7 @@ export class OpenCodeController {
6979
7382
  peerIdArg: string,
6980
7383
  requestArg: IReq_ControllerMcpSessionsList['request'],
6981
7384
  signalArg: AbortSignal,
6982
- ): Promise<IReq_ControllerMcpSessionsList['response']> {
7385
+ ): Promise<Pick<IReq_ControllerMcpSessionsList['response'], 'sessions'>> {
6983
7386
  const { projectId } = requestArg;
6984
7387
  return this.runAudited(
6985
7388
  { type: 'session.list', peerId: this.auditPeerId(principalArg, peerIdArg) },
@@ -7057,7 +7460,7 @@ export class OpenCodeController {
7057
7460
  peerIdArg: string,
7058
7461
  requestArg: IReq_ControllerMcpSessionRead['request'],
7059
7462
  signalArg: AbortSignal,
7060
- ): Promise<IReq_ControllerMcpSessionRead['response']> {
7463
+ ): Promise<TControllerMcpSessionDetail> {
7061
7464
  const { projectId, sessionId } = requestArg;
7062
7465
  return this.runAudited(
7063
7466
  {
@@ -7418,6 +7821,7 @@ export class OpenCodeController {
7418
7821
  { code: 'delivery_unsupported' },
7419
7822
  );
7420
7823
  }
7824
+ if (await this.isMcpNativeClaudeId(projectId, sessionId)) return this.deliverNativeAgentMessage(peerIdArg, requestArg, subjectArg, signalArg);
7421
7825
  await this.requireMcpMessageTarget(projectId, sessionId, signalArg);
7422
7826
  const sender: IControllerPromptSender = { kind: 'agent', label, subject: await subjectArg() };
7423
7827
  if (!this.agentMessageLimiter.admit(`${peerIdArg}\0${projectId}\0${controllerRuntimeIdKey(sessionId)}`)) {
@@ -9095,6 +9499,163 @@ export class OpenCodeController {
9095
9499
  return this.assertSessionExists(projectIdArg, sessionIdArg, signalArg);
9096
9500
  }
9097
9501
 
9502
+ /**
9503
+ * Whether an MCP request names a Claude Code session outside AGL's conversations of the project: a `claude` id that no
9504
+ * conversation of this project records. Such an id is served by the native path, everything else by the managed one.
9505
+ */
9506
+ private async isMcpNativeClaudeId(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<boolean> {
9507
+ if (sessionIdArg.harnessId !== 'claude') return false;
9508
+ await this.resolveProject(projectIdArg);
9509
+ return !await this.requireAuthStore().requireClaudeSessions().get(projectIdArg, sessionIdArg.nativeId);
9510
+ }
9511
+
9512
+ /**
9513
+ * The Claude Code session outside AGL that an MCP caller names in a project: only a session of the host's own Claude
9514
+ * Code home, as the session feed lists it, whose directory is the project folder itself, and that no other project's
9515
+ * conversation records. Anything else is `session_not_found`; nothing is recorded.
9516
+ */
9517
+ private async requireMcpNativeClaudeTarget(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<{
9518
+ ref: IControllerNativeSessionRef; resolved: IResolvedNativeSession; session: IControllerNativeSession;
9519
+ }> {
9520
+ const project = await this.resolveProject(projectIdArg);
9521
+ const ref: IControllerNativeSessionRef = { harness: 'claude', nativeId: sessionIdArg.nativeId };
9522
+ const notFound = () => new plugins.typedrequest.TypedResponseError('The requested session was not found.', { code: 'session_not_found' });
9523
+ let resolved: IResolvedNativeSession;
9524
+ try {
9525
+ resolved = await this.nativeSessions.resolve(ref);
9526
+ } catch (errorArg) {
9527
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'session_not_found') throw notFound();
9528
+ throw errorArg;
9529
+ }
9530
+ if (!await this.inMcpNativeScope(resolved, project.directory)) throw notFound();
9531
+ return { ref, resolved, session: mcpNativeSession(resolved) };
9532
+ }
9533
+
9534
+ /** The project's scope for Claude Code sessions outside AGL: the host's own home, the exact folder, no other project's conversation. */
9535
+ private async inMcpNativeScope(resolvedArg: IResolvedNativeSession, projectDirectoryArg: string): Promise<boolean> {
9536
+ if (resolvedArg.native.home !== undefined || resolvedArg.session.readOnly?.reason === 'projectConversation') return false;
9537
+ const directory = await canonicalDirectory(projectDirectoryArg);
9538
+ return directory !== undefined && await canonicalDirectory(resolvedArg.session.cwd) === directory;
9539
+ }
9540
+
9541
+ /**
9542
+ * The Claude Code sessions of the host's own Claude Code home whose directory is the project folder itself and that no
9543
+ * project conversation records, for `sessions_list`: running ones first, all of them, then the newest settled ones up
9544
+ * to `controllerMcpNativeSessionSettledLimit`. An inventory that cannot be read is named, never hidden.
9545
+ */
9546
+ private async listMcpNativeClaudeSessions(projectIdArg: string): Promise<Omit<IReq_ControllerMcpSessionsList['response'], 'sessions'>> {
9547
+ const project = await this.resolveProject(projectIdArg);
9548
+ let agents: Awaited<ReturnType<FleetWorkers['nativeAgents']>>;
9549
+ try {
9550
+ agents = await this.requireFleetWorkers().nativeAgents(undefined, 3_000);
9551
+ } catch (errorArg) {
9552
+ const reason = errorArg instanceof Error ? errorArg.message : 'unknown failure.';
9553
+ return { nativeSessions: [], nativeSessionsError: `The host's Claude Code inventory could not be read: ${reason}`.slice(0, 1024) };
9554
+ }
9555
+ const directory = await canonicalDirectory(project.directory);
9556
+ if (directory === undefined) return { nativeSessions: [] };
9557
+ const running = (agentArg: typeof agents[number]): boolean => agentArg.pid !== undefined || agentArg.state === 'working';
9558
+ const candidates: typeof agents = [], seen = new Set<string>();
9559
+ for (const agent of agents) {
9560
+ if (seen.has(agent.sessionId)) continue;
9561
+ seen.add(agent.sessionId);
9562
+ if (await canonicalDirectory(agent.cwd) === directory) candidates.push(agent);
9563
+ }
9564
+ candidates.sort((left, right) => Number(running(right)) - Number(running(left)) || (right.startedAt ?? 0) - (left.startedAt ?? 0));
9565
+ const nativeSessions: IControllerNativeSession[] = [];
9566
+ let settled = 0;
9567
+ for (const agent of candidates) {
9568
+ // Running sessions sort first and are never cut; only settled ones count toward the limit.
9569
+ if (!running(agent) && settled >= controllerMcpNativeSessionSettledLimit) return { nativeSessions, nativeSessionsTruncated: true };
9570
+ let resolved: IResolvedNativeSession;
9571
+ try {
9572
+ resolved = await this.nativeSessions.resolve({ harness: 'claude', nativeId: agent.sessionId });
9573
+ } catch (errorArg) {
9574
+ // A session that left the inventory since it was read is no longer listed.
9575
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'session_not_found') continue;
9576
+ throw errorArg;
9577
+ }
9578
+ if (!await this.inMcpNativeScope(resolved, project.directory)) continue;
9579
+ nativeSessions.push(mcpNativeSession(resolved));
9580
+ if (!running(agent)) settled += 1;
9581
+ }
9582
+ return { nativeSessions };
9583
+ }
9584
+
9585
+ /** `session_read` of a Claude Code session outside AGL: the session, its newest transcript page and its scratchpad. */
9586
+ private async readMcpNativeClaudeSession(
9587
+ principalArg: TControllerOperationPrincipal,
9588
+ requestArg: IReq_ControllerMcpSessionRead['request'],
9589
+ signalArg: AbortSignal,
9590
+ ): Promise<IControllerMcpNativeSessionDetail> {
9591
+ return this.runAudited(
9592
+ { type: 'session.read', peerId: this.auditPeerId(principalArg, 'mcp'), sessionId: requestArg.sessionId },
9593
+ () => this.serveNativeSession(signalArg, async () => {
9594
+ const { ref, resolved, session } = await this.requireMcpNativeClaudeTarget(requestArg.projectId, requestArg.sessionId);
9595
+ const [page, state] = await Promise.all([
9596
+ this.requireFleetWorkers().nativeHistory('claude', resolved.native, controllerInitialMessageBundleLimit),
9597
+ this.requireAuthStore().getSessionState(resolved.scope, nativeSessionRuntimeId(ref), signalArg),
9598
+ ]);
9599
+ signalArg.throwIfAborted();
9600
+ return {
9601
+ kind: 'native' as const,
9602
+ session,
9603
+ messagePage: boundControllerMessagePage({
9604
+ bundles: page.bundles,
9605
+ ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
9606
+ ...(page.earlier && page.nextCursor === undefined ? { truncated: true } : {}),
9607
+ }, controllerInitialMessageBundleLimit),
9608
+ scratchpad: state.scratchpad,
9609
+ };
9610
+ }),
9611
+ );
9612
+ }
9613
+
9614
+ /**
9615
+ * An agent message to a Claude Code background job outside AGL, after the project's switch: behind the
9616
+ * `session_message` header naming the caller, through the one native send, which wakes a settled job and puts the
9617
+ * message into a running job's inbox. A send that may have reached the job is `outcome_unknown`, never resent.
9618
+ */
9619
+ private async deliverNativeAgentMessage(
9620
+ peerIdArg: string,
9621
+ requestArg: IReq_ControllerMcpSessionMessage['request'],
9622
+ subjectArg: () => Promise<string>,
9623
+ signalArg: AbortSignal,
9624
+ ): Promise<IReq_ControllerMcpSessionMessage['response']> {
9625
+ const { projectId, sessionId, sender: label } = requestArg;
9626
+ if (requestArg.expectedTurnId !== undefined) {
9627
+ throw new plugins.typedrequest.TypedResponseError(
9628
+ 'A Claude Code background job outside AGL takes no turn guard; omit expectedTurnId.',
9629
+ { code: 'delivery_unsupported' },
9630
+ );
9631
+ }
9632
+ const target = await this.requireMcpNativeClaudeTarget(projectId, sessionId);
9633
+ assertMcpNativeMessageable(target.session);
9634
+ const sender: IControllerPromptSender = { kind: 'agent', label, subject: await subjectArg() };
9635
+ if (!this.agentMessageLimiter.admit(`${peerIdArg}\0${projectId}\0${controllerRuntimeIdKey(sessionId)}`)) {
9636
+ throw new plugins.typedrequest.TypedResponseError(
9637
+ 'Too many agent messages to this task; wait before sending another.',
9638
+ { code: 'message_rate_limited' },
9639
+ );
9640
+ }
9641
+ let job: TControllerNativeJobDelivery | undefined;
9642
+ try {
9643
+ ({ job } = await this.sendNativeSession(peerIdArg, target.ref, formatAgentMessage(sender, requestArg.text), undefined, signalArg,
9644
+ (resolvedArg) => {
9645
+ if (resolvedArg.native.home !== undefined) throw new plugins.typedrequest.TypedResponseError('The requested session was not found.', { code: 'session_not_found' });
9646
+ assertMcpNativeMessageable(mcpNativeSession(resolvedArg));
9647
+ }));
9648
+ } catch (errorArg) {
9649
+ // Only a refusal before dispatch proves that nothing reached the job.
9650
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'native_session_failed' && errorArg.errorData?.outcome !== 'refused') {
9651
+ throw new plugins.typedrequest.TypedResponseError('The message may have reached the Claude Code job; read the session before sending again.', { code: 'outcome_unknown' });
9652
+ }
9653
+ throw errorArg;
9654
+ }
9655
+ if (!job) throw new plugins.typedrequest.TypedResponseError('The message may have reached the Claude Code job; read the session before sending again.', { code: 'outcome_unknown' });
9656
+ return { accepted: true as const, delivery: controllerMcpNativeDeliveries[job], native: job };
9657
+ }
9658
+
9098
9659
  /**
9099
9660
  * Any caller may message a task: unlike a task mutation, no ownership is required. The target
9100
9661
  * must still be an active root task of the project the request names; archived tasks and child
@@ -9191,6 +9752,10 @@ export class OpenCodeController {
9191
9752
  await this.resolveProject(project.id);
9192
9753
  if (!requestArg.sessionId) return { project };
9193
9754
  const target = requestArg.sessionId;
9755
+ // A Claude Code session outside AGL answers as itself and is recorded nowhere.
9756
+ if (await this.isMcpNativeClaudeId(project.id, target)) {
9757
+ return { project, nativeSession: (await this.requireMcpNativeClaudeTarget(project.id, target)).session };
9758
+ }
9194
9759
  const { sessions } = await this.listSessionsForPrincipal(
9195
9760
  principalArg, peerIdArg, { projectId: project.id }, signalArg,
9196
9761
  );
@@ -9867,6 +10432,21 @@ export class OpenCodeController {
9867
10432
  throw errorArg;
9868
10433
  }
9869
10434
  }),
10435
+ // A read for every caller (AGL-1097): the answer names accounts by id alone.
10436
+ proxyCapacity: (requestArg, signalArg) => run(signalArg, async (operationSignalArg) => {
10437
+ const monitor = this.proxyMonitor;
10438
+ if (!monitor) throw new plugins.typedrequest.TypedResponseError('The AGL proxy is not running.', { code: 'proxy_unavailable' });
10439
+ try {
10440
+ return await monitor.capacity(requestArg, operationSignalArg);
10441
+ } catch (errorArg) {
10442
+ const code = errorArg instanceof AglProxyUnavailableError ? 'proxy_unavailable'
10443
+ : errorArg instanceof AglProxyOutdatedError ? 'proxy_outdated'
10444
+ : errorArg instanceof AglProxyRefusedError && errorArg.code === 'authority_unavailable' ? 'proxy_accounts_unavailable'
10445
+ : undefined;
10446
+ if (code && errorArg instanceof Error) throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code });
10447
+ throw errorArg;
10448
+ }
10449
+ }),
9870
10450
  status: async (principalArg, signalArg) => run(signalArg, async () => ({
9871
10451
  status: this.statusForPrincipal(principalArg),
9872
10452
  controllerPort: controllerPortArg,
@@ -9882,16 +10462,17 @@ export class OpenCodeController {
9882
10462
  ),
9883
10463
  listSessions: async (principalArg, requestArg, signalArg) => run(
9884
10464
  signalArg,
9885
- async (operationSignalArg) => this.listSessionsForPrincipal(
9886
- principalArg,
9887
- 'mcp',
9888
- requestArg,
9889
- operationSignalArg,
9890
- ),
10465
+ async (operationSignalArg) => {
10466
+ const listed = await this.listSessionsForPrincipal(principalArg, 'mcp', requestArg, operationSignalArg);
10467
+ return { ...listed, ...await this.listMcpNativeClaudeSessions(requestArg.projectId) };
10468
+ },
9891
10469
  ),
9892
10470
  readSession: async (principalArg, requestArg, signalArg) => run(
9893
10471
  signalArg,
9894
10472
  async (operationSignalArg) => {
10473
+ if (await this.isMcpNativeClaudeId(requestArg.projectId, requestArg.sessionId)) {
10474
+ return this.readMcpNativeClaudeSession(principalArg, requestArg, operationSignalArg);
10475
+ }
9895
10476
  await this.prepareMcpSessionTarget(requestArg.projectId, requestArg.sessionId, operationSignalArg);
9896
10477
  return this.readSessionForPrincipal(
9897
10478
  principalArg,
@@ -10239,6 +10820,19 @@ export class OpenCodeController {
10239
10820
  this.assertStartActive();
10240
10821
  }
10241
10822
  const trustedProxySecrets = this.trustedProxySecrets;
10823
+ // Its enrolment is read now; its first sync runs once the controller is ready, never holding up the start.
10824
+ const gatewayClient = new ControllerGatewayClient({
10825
+ store: new ControllerGatewayClientStore({
10826
+ controllerId: authDocument.id,
10827
+ issuerId: issuerIdentity.issuerId,
10828
+ codec: this.options.trustedProxySecretCodec ?? new TpmSecretCodec(),
10829
+ }),
10830
+ runtimeConfig: () => this.requireRuntimeConfig(),
10831
+ secrets: () => this.trustedProxySecrets,
10832
+ });
10833
+ this.gatewayClient = gatewayClient;
10834
+ await gatewayClient.load();
10835
+ this.assertStartActive();
10242
10836
  const publicHostname = new URL(runtimeConfig.publicOrigin).hostname;
10243
10837
  const hostnames = [...new Set([publicHostname, 'localhost', '127.0.0.1'])];
10244
10838
  const serveDirectory = plugins.path.resolve(
@@ -10797,6 +11391,7 @@ export class OpenCodeController {
10797
11391
  startupOpenCodeExitSignal,
10798
11392
  );
10799
11393
  this.lifecycleState = 'ready';
11394
+ this.gatewayClient?.start();
10800
11395
  this.requireFleetWorkers();
10801
11396
  // New Claude Code releases an earlier run recorded but did not announce are announced now, once.
10802
11397
  const harnessReleases = this.harnessReleases;
@@ -10805,6 +11400,7 @@ export class OpenCodeController {
10805
11400
  .catch((errorArg) => console.error('Announcing new Claude Code releases failed.', errorArg));
10806
11401
  }
10807
11402
  this.startSessionFeed();
11403
+ this.startInbox();
10808
11404
  // Assignees hear of others' changes to their tickets through the fleet's native steering.
10809
11405
  this.ticketNotifier ??= new TicketNotifier({
10810
11406
  deliver: async (sessionIdArg, ticketKeyArg, textArg) => {
@@ -13181,7 +13777,9 @@ export class OpenCodeController {
13181
13777
  await stopPart(async () => { await this.fleetService?.close(); this.fleetService = undefined; });
13182
13778
  await stopPart(async () => { await this.boardPump?.close(); this.boardPump = undefined; });
13183
13779
  await stopPart(async () => { await this.deployMonitor?.close(); this.deployMonitor = undefined; });
13780
+ await stopPart(async () => { await this.gatewayClient?.close(); this.gatewayClient = undefined; });
13184
13781
  await stopPart(async () => { await this.ticketNotifier?.close(); this.ticketNotifier = undefined; });
13782
+ await stopPart(async () => { await this.inbox?.close(); this.inbox = undefined; });
13185
13783
  await stopPart(async () => { await this.sessionFeed?.close(); this.sessionFeed = undefined; });
13186
13784
  await stopPart(async () => { await this.usageFeed?.stop(); this.usageFeed = undefined; });
13187
13785
  await stopPart(async () => { const notices = this.harnessReleases; this.harnessReleases = undefined; await notices?.close(); });
@@ -13735,13 +14333,14 @@ export class OpenCodeController {
13735
14333
  this.registerDirectReportHandlers(protectedRouter);
13736
14334
  this.registerNativeSessionHandlers(protectedRouter);
13737
14335
  this.registerSessionFeedHandlers(protectedRouter);
14336
+ this.registerInboxHandlers(protectedRouter);
13738
14337
  this.registerDeployHandlers(protectedRouter);
13739
14338
  this.registerUsageFeedHandlers(protectedRouter);
13740
14339
  this.registerTerminalHandlers(protectedRouter);
13741
14340
  this.registerDevicesHandlers(protectedRouter);
13742
14341
 
13743
14342
  this.registerDevicePairingHandlers(devicePairingRouter);
13744
- this.registerDeviceHandlers(deviceRouter);
14343
+ this.registerDeviceHandlers(deviceRouter, publicOriginArg);
13745
14344
 
13746
14345
  return rootRouter;
13747
14346
  }
@@ -13863,11 +14462,295 @@ export class OpenCodeController {
13863
14462
  });
13864
14463
  }
13865
14464
 
14465
+ /**
14466
+ * A device's answer to a direct child (an OpenCode subagent) of the session it names: the session must be an OpenCode
14467
+ * conversation the feed lists, and the child is proven a running direct child of it as the browser's child scopes do.
14468
+ */
14469
+ private replyDeviceChildRequest(
14470
+ auditPeerIdArg: string,
14471
+ openArg: Exclude<IControllerSessionFeedRow['open'], { kind: 'terminal' }>,
14472
+ childSessionIdArg: string,
14473
+ requestIdArg: string,
14474
+ replyArg: { reply: TControllerPermissionReply; message?: string } | { answers: string[][] | null },
14475
+ signalArg: AbortSignal,
14476
+ ): Promise<{ success: boolean }> {
14477
+ if (openArg.kind !== 'conversation' || openArg.sessionId.harnessId !== 'opencode') {
14478
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
14479
+ }
14480
+ const projectId = openArg.projectId;
14481
+ const parentSessionId = openArg.sessionId as IControllerRuntimeId & { harnessId: 'opencode' };
14482
+ const childSessionId = { harnessId: 'opencode' as const, nativeId: childSessionIdArg };
14483
+ return this.replyChildRequestForPrincipal('device', auditPeerIdArg, {
14484
+ projectId, parentSessionId, childSessionId, requestId: { harnessId: 'opencode', nativeId: requestIdArg }, ...replyArg,
14485
+ }, (activeRequiredArg) => this.verifyDeviceDirectChild(projectId, parentSessionId, childSessionId, signalArg, activeRequiredArg), signalArg);
14486
+ }
14487
+
14488
+ /**
14489
+ * A conversation's transcript page and what it waits for, as a device reads it through the browser's session read:
14490
+ * the newest page without `before`, sized by the controller, else the next older page of `limit` messages.
14491
+ */
14492
+ private async readDeviceConversation(
14493
+ auditPeerIdArg: string,
14494
+ projectIdArg: string,
14495
+ sessionIdArg: IControllerRuntimeId,
14496
+ requestArg: { before?: string; limit?: number },
14497
+ signalArg: AbortSignal,
14498
+ ): Promise<Omit<IReq_DeviceSessionRead['response'], 'session'>> {
14499
+ const detail = await this.readSessionForPrincipal('device', auditPeerIdArg, { projectId: projectIdArg, sessionId: sessionIdArg }, signalArg);
14500
+ const before = requestArg.before;
14501
+ const page = before === undefined ? detail.messagePage : await this.runAudited(
14502
+ { type: 'session.messages.page', peerId: auditPeerIdArg, sessionId: sessionIdArg },
14503
+ async () => this.readSessionMessagePage(
14504
+ await this.resolveProject(projectIdArg),
14505
+ sessionIdArg,
14506
+ { limit: requestArg.limit ?? controllerInitialMessageBundleLimit, before },
14507
+ signalArg,
14508
+ ),
14509
+ );
14510
+ return {
14511
+ messages: deviceMessages(page.bundles),
14512
+ before: page.nextCursor ?? null,
14513
+ permissions: devicePermissions(detail.permissions),
14514
+ questions: deviceQuestions(detail.questions),
14515
+ elicitations: deviceElicitations(detail.elicitations),
14516
+ };
14517
+ }
14518
+
14519
+ /**
14520
+ * The host's driver session for a device's read or send, as the driver's status names it now; refused while there is
14521
+ * none. A device never creates the driver.
14522
+ */
14523
+ private async deviceDriverSession(signalArg: AbortSignal): Promise<{
14524
+ driver: IControllerDriverStatus;
14525
+ projectId: string;
14526
+ sessionId: TControllerSessionId;
14527
+ }> {
14528
+ const driver = await this.requireDriverService().get(signalArg);
14529
+ if (driver.activity === 'absent' || driver.projectId === undefined || driver.sessionId === undefined) {
14530
+ throw deviceRefusal('driver_absent', 'This host has no driver session; the owner starts the driver in the browser.');
14531
+ }
14532
+ return { driver, projectId: driver.projectId, sessionId: driver.sessionId };
14533
+ }
14534
+
13866
14535
  /**
13867
14536
  * Scope `device`: the session feed, bounded transcript reads, direct sends and permission and question answers of an
13868
- * authenticated device -- through the same operations the owner's browser runs, audited as `device:<id>`.
14537
+ * authenticated device, the Inbox, the driver, the direct reports, the host's status and the shared board -- through
14538
+ * the same operations the owner's browser runs, audited as `device:<id>`. `publicOriginArg` is the origin the scope
14539
+ * admits.
13869
14540
  */
13870
- private registerDeviceHandlers(routerArg: ControllerProtectedRouter): void {
14541
+ private registerDeviceHandlers(routerArg: ControllerProtectedRouter, publicOriginArg: string): void {
14542
+ routerArg.addHandler<IReq_DeviceInboxList>('device.inbox.list', async (requestArg, toolsArg) => {
14543
+ validateRequest(() => assertEmptyRequest(requestArg));
14544
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14545
+ return this.runDeviceOperation(peer, deviceId, async () => deviceInboxList(
14546
+ await this.requireInbox().list(), (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg),
14547
+ ), toolsArg?.abortSignal);
14548
+ });
14549
+
14550
+ routerArg.addHandler<IReq_DeviceTicketAnswer>('device.ticket.answer', async (requestArg, toolsArg) => {
14551
+ const request = validateRequest(() => assertDeviceTicketAnswerRequest(requestArg));
14552
+ const answer = validateRequest(() => assertTicketRequest('answer', {
14553
+ ticketId: request.ticketKey, questionId: request.questionId,
14554
+ ...(request.choices === undefined ? {} : { choices: request.choices }),
14555
+ ...(request.text === undefined ? {} : { text: request.text }),
14556
+ }));
14557
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14558
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14559
+ try {
14560
+ const { question } = await this.answerTicketForPrincipal('device', deviceAuditPeerId(deviceId), answer, signalArg);
14561
+ return { question: deviceTicketQuestion(question) };
14562
+ } catch (errorArg) {
14563
+ throw deviceTicketRefusal(errorArg);
14564
+ }
14565
+ }, toolsArg?.abortSignal);
14566
+ });
14567
+
14568
+ // The shared board (AGL-1637): the browser board's own reads and changes, as the owner and audited as the device. A
14569
+ // device creates, edits and assigns no ticket; a refusal changes nothing and carries the store's code and reason.
14570
+ routerArg.addHandler<IReq_DeviceBoardList>('device.board.list', async (requestArg, toolsArg) => {
14571
+ const request = validateRequest(() => assertDeviceBoardListRequest(requestArg));
14572
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14573
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14574
+ const { owner, viewer } = await this.deviceTicketViewer();
14575
+ let board: ITicketBoard;
14576
+ try {
14577
+ board = await this.ticketStore.execute('board', {}, owner, signalArg);
14578
+ } catch (errorArg) {
14579
+ throw deviceTicketRefusal(errorArg);
14580
+ }
14581
+ return deviceBoardPage(board, request, viewer);
14582
+ }, toolsArg?.abortSignal);
14583
+ });
14584
+
14585
+ routerArg.addHandler<IReq_DeviceTicketGet>('device.ticket.get', async (requestArg, toolsArg) => {
14586
+ const request = validateRequest(() => assertDeviceTicketGetRequest(requestArg));
14587
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14588
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14589
+ const { owner, viewer } = await this.deviceTicketViewer();
14590
+ let detail: ITicketDetail;
14591
+ let comments: ITicketComment[];
14592
+ try {
14593
+ // The ticket and every question, then every comment: the discussion is paged here, by what a device shows.
14594
+ detail = await this.ticketStore.execute('get', { ticketId: request.ticketKey, limit: 1 }, owner, signalArg);
14595
+ comments = (await this.ticketStore.execute('comments', { ticketId: request.ticketKey }, owner, signalArg)).comments;
14596
+ } catch (errorArg) {
14597
+ throw deviceTicketRefusal(errorArg);
14598
+ }
14599
+ const parent = await this.deviceTicketParent(owner, detail.ticket, signalArg);
14600
+ const { placement, observed } = await readDeviceTicketPlacement(
14601
+ () => this.requireDeployMonitor().ticketPlacement(detail.ticket.key), signalArg,
14602
+ );
14603
+ return {
14604
+ ticket: deviceTicket(detail.ticket, parent, viewer),
14605
+ ...deviceTicketDiscussion(comments, detail.questions, request, viewer),
14606
+ placement,
14607
+ plans: deviceTicketPlans(detail.ticket, observed),
14608
+ };
14609
+ }, toolsArg?.abortSignal);
14610
+ });
14611
+
14612
+ routerArg.addHandler<IReq_DeviceTicketComment>('device.ticket.comment', async (requestArg, toolsArg) => {
14613
+ const request = validateRequest(() => assertDeviceTicketCommentRequest(requestArg));
14614
+ const comment = validateRequest(() => assertTicketRequest('comment', { ticketId: request.ticketKey, body: request.text }));
14615
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14616
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14617
+ const { viewer } = await this.deviceTicketViewer();
14618
+ try {
14619
+ const written = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'comment', comment, signalArg);
14620
+ return { comment: deviceTicketComment(written.comment, viewer) };
14621
+ } catch (errorArg) {
14622
+ throw deviceTicketRefusal(errorArg);
14623
+ }
14624
+ }, toolsArg?.abortSignal);
14625
+ });
14626
+
14627
+ routerArg.addHandler<IReq_DeviceTicketAsk>('device.ticket.ask', async (requestArg, toolsArg) => {
14628
+ const request = validateRequest(() => assertDeviceTicketAskRequest(requestArg));
14629
+ // Text alone, answered with text, as the browser board's question card asks.
14630
+ const ask = validateRequest(() => assertTicketRequest('ask', { ticketId: request.ticketKey, question: request.question }));
14631
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14632
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14633
+ try {
14634
+ const { question } = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'ask', ask, signalArg);
14635
+ return { question: deviceTicketQuestion(question) };
14636
+ } catch (errorArg) {
14637
+ throw deviceTicketRefusal(errorArg);
14638
+ }
14639
+ }, toolsArg?.abortSignal);
14640
+ });
14641
+
14642
+ // "Move to…": the phone's drag on the browser's board, to the end of the column.
14643
+ routerArg.addHandler<IReq_DeviceTicketMove>('device.ticket.move', async (requestArg, toolsArg) => {
14644
+ const request = validateRequest(() => assertDeviceTicketMoveRequest(requestArg));
14645
+ const move = validateRequest(() => assertTicketRequest('move', { ticketId: request.ticketKey, columnId: request.column }));
14646
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14647
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14648
+ const { owner, viewer } = await this.deviceTicketViewer();
14649
+ let moved: ITicket;
14650
+ try {
14651
+ const { tickets } = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'move', move, signalArg);
14652
+ // A ticket already last in its column moves nowhere and is not among the tickets the move changed.
14653
+ moved = tickets.find((ticketArg) => ticketArg.key === request.ticketKey)
14654
+ ?? (await this.ticketStore.execute('get', { ticketId: request.ticketKey, limit: 1 }, owner, signalArg)).ticket;
14655
+ } catch (errorArg) {
14656
+ throw deviceTicketRefusal(errorArg);
14657
+ }
14658
+ return { ticket: deviceTicketCard(moved, await this.deviceTicketParent(owner, moved, signalArg), viewer) };
14659
+ }, toolsArg?.abortSignal);
14660
+ });
14661
+
14662
+ // The driver as the browser's topbar and Driver view reach it; its own prompts are read-only on a device.
14663
+ routerArg.addHandler<IReq_DeviceDriverGet>('device.driver.get', async (requestArg, toolsArg) => {
14664
+ validateRequest(() => assertEmptyRequest(requestArg));
14665
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14666
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14667
+ const service = this.requireDriverService();
14668
+ return { driver: deviceDriverStatus(await service.get(signalArg), service.needsInput()) };
14669
+ }), toolsArg?.abortSignal);
14670
+ });
14671
+
14672
+ routerArg.addHandler<IReq_DeviceDriverSeen>('device.driver.seen', async (requestArg, toolsArg) => {
14673
+ validateRequest(() => assertEmptyRequest(requestArg));
14674
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14675
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14676
+ const service = this.requireDriverService();
14677
+ return { driver: deviceDriverStatus(await service.seen(signalArg), service.needsInput()) };
14678
+ }), toolsArg?.abortSignal);
14679
+ });
14680
+
14681
+ routerArg.addHandler<IReq_DeviceDriverRead>('device.driver.read', async (requestArg, toolsArg) => {
14682
+ const request = validateRequest(() => assertDeviceDriverReadRequest(requestArg));
14683
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14684
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14685
+ const { driver, projectId, sessionId } = await this.deviceDriverSession(signalArg);
14686
+ const transcript = await this.readDeviceConversation(deviceAuditPeerId(deviceId), projectId, sessionId, request, signalArg);
14687
+ return { driver: deviceDriverStatus(driver, this.requireDriverService().needsInput()), ...transcript };
14688
+ }), toolsArg?.abortSignal);
14689
+ });
14690
+
14691
+ routerArg.addHandler<IReq_DeviceDriverSend>('device.driver.send', async (requestArg, toolsArg) => {
14692
+ const request = validateRequest(() => assertDeviceDriverSendRequest(requestArg));
14693
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14694
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14695
+ const { projectId, sessionId } = await this.deviceDriverSession(signalArg);
14696
+ // A direct message, as to any conversation: never the browser's shared draft.
14697
+ await this.sendSessionForPrincipal('device', deviceAuditPeerId(deviceId), {
14698
+ source: 'direct', projectId, sessionId, text: request.text,
14699
+ }, signalArg);
14700
+ return { accepted: true as const };
14701
+ }), toolsArg?.abortSignal);
14702
+ });
14703
+
14704
+ routerArg.addHandler<IReq_DeviceDirectReportsList>('device.directreports.list', async (requestArg, toolsArg) => {
14705
+ validateRequest(() => assertEmptyRequest(requestArg));
14706
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14707
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => this.serveDirectReport(signalArg, async (ownerArg) => {
14708
+ const directReports = this.requireDirectReports();
14709
+ const [views, workers] = await Promise.all([directReports.list(ownerArg, false, signalArg), directReports.reportWorkers(ownerArg)]);
14710
+ return { reports: views.map((viewArg) => deviceDirectReport(viewArg, workers.get(viewArg.report.name) ?? [])) };
14711
+ }), toolsArg?.abortSignal);
14712
+ });
14713
+
14714
+ routerArg.addHandler<IReq_DeviceDirectReportMessage>('device.directreport.message', async (requestArg, toolsArg) => {
14715
+ const request = validateRequest(() => assertDeviceDirectReportMessageRequest(requestArg));
14716
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14717
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => this.serveDirectReport(signalArg, async (ownerArg) => {
14718
+ let answer: IReq_ControllerDirectReportMessage['response'];
14719
+ try {
14720
+ answer = await this.messageDirectReportForPrincipal('device', deviceAuditPeerId(deviceId), ownerArg, request, signalArg);
14721
+ } catch (errorArg) {
14722
+ throw deviceDirectReportMessageRefusal(errorArg);
14723
+ }
14724
+ if (!('job' in answer)) return { delivery: answer.delivery };
14725
+ if (answer.job.state !== 'succeeded') {
14726
+ throw deviceRefusal('direct_report_failed', (answer.job.error ?? 'The fleet did not deliver the message.').slice(0, 4096));
14727
+ }
14728
+ return { delivery: 'fleet' as const };
14729
+ }), toolsArg?.abortSignal);
14730
+ });
14731
+
14732
+ // The Host view (AGL-824) is read-only: what the browser's status, Deployments view and accounts read, reduced so
14733
+ // nothing names an account, a key or a probe's address, and no deploy probe runs for it.
14734
+ routerArg.addHandler<IReq_DeviceHostGet>('device.host.get', async (requestArg, toolsArg) => {
14735
+ validateRequest(() => assertEmptyRequest(requestArg));
14736
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14737
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14738
+ const device = this.requireDevices().get(deviceId);
14739
+ if (device === undefined) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
14740
+ const proxyMonitor = this.proxyMonitor;
14741
+ return {
14742
+ agl: deviceHostAgl({ version: commitinfo.version, startedAt: this.startedAt, origin: publicOriginArg, gateway: this.gatewayClient?.status() }),
14743
+ device: deviceHostDevice(device),
14744
+ ...await readDeviceHostSections({
14745
+ deployStatus: () => this.requireDeployMonitor().status(),
14746
+ capacity: proxyMonitor === undefined ? undefined : (operationSignalArg) => proxyMonitor.capacity({}, operationSignalArg),
14747
+ authority: () => this.authorityState.getProjection(),
14748
+ usage: (accountIdArg, loginIdArg, operationSignalArg) => this.accountsActions.usage({ accountId: accountIdArg, loginId: loginIdArg }, operationSignalArg),
14749
+ }, Date.now(), signalArg),
14750
+ };
14751
+ }, toolsArg?.abortSignal);
14752
+ });
14753
+
13871
14754
  routerArg.addHandler<IReq_DeviceSessionsList>('device.sessions.list', async (requestArg, toolsArg) => {
13872
14755
  validateRequest(() => assertEmptyRequest(requestArg));
13873
14756
  const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
@@ -13885,26 +14768,7 @@ export class OpenCodeController {
13885
14768
  const { row, open } = await this.deviceSessionTarget(request.sessionId);
13886
14769
  const session = deviceSessionRow(row)!;
13887
14770
  if (open.kind === 'conversation') {
13888
- const { projectId, sessionId } = open;
13889
- const detail = await this.readSessionForPrincipal('device', auditPeerId, { projectId, sessionId }, signalArg);
13890
- const before = request.before;
13891
- const page = before === undefined ? detail.messagePage : await this.runAudited(
13892
- { type: 'session.messages.page', peerId: auditPeerId, sessionId },
13893
- async () => this.readSessionMessagePage(
13894
- await this.resolveProject(projectId),
13895
- sessionId,
13896
- { limit: request.limit ?? controllerInitialMessageBundleLimit, before },
13897
- signalArg,
13898
- ),
13899
- );
13900
- return {
13901
- session,
13902
- messages: deviceMessages(page.bundles),
13903
- before: page.nextCursor ?? null,
13904
- permissions: devicePermissions(detail.permissions),
13905
- questions: deviceQuestions(detail.questions),
13906
- elicitations: deviceElicitations(detail.elicitations),
13907
- };
14771
+ return { session, ...await this.readDeviceConversation(auditPeerId, open.projectId, open.sessionId, request, signalArg) };
13908
14772
  }
13909
14773
  // As for a conversation, `limit` sizes older pages only; the newest page is the controller's own bound.
13910
14774
  const native = await this.readNativeSessionForPrincipal('device', auditPeerId, {
@@ -13936,6 +14800,7 @@ export class OpenCodeController {
13936
14800
  } else {
13937
14801
  await this.sendNativeSession(
13938
14802
  auditPeerId, nativeSessionRefOfFeed(open), request.text, undefined, signalArg, assertNativeSessionWritable,
14803
+ { kind: 'agent', label: 'Owner', subject: agentMessageSubjects.ownerDevice },
13939
14804
  );
13940
14805
  }
13941
14806
  return { accepted: true as const };
@@ -13948,6 +14813,11 @@ export class OpenCodeController {
13948
14813
  return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13949
14814
  const auditPeerId = deviceAuditPeerId(deviceId);
13950
14815
  const { open } = await this.deviceSessionTarget(request.sessionId);
14816
+ if (request.childSessionId !== undefined) {
14817
+ return this.replyDeviceChildRequest(auditPeerId, open, request.childSessionId, request.permissionId, {
14818
+ reply: request.reply, ...(request.message === undefined ? {} : { message: request.message }),
14819
+ }, signalArg);
14820
+ }
13951
14821
  if (open.kind === 'conversation') {
13952
14822
  return this.replyPermissionForPrincipal('device', auditPeerId, validateRequest(() => assertPermissionReplyRequest({
13953
14823
  projectId: open.projectId,
@@ -13973,6 +14843,11 @@ export class OpenCodeController {
13973
14843
  return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13974
14844
  const auditPeerId = deviceAuditPeerId(deviceId);
13975
14845
  const { open } = await this.deviceSessionTarget(request.sessionId);
14846
+ if (request.childSessionId !== undefined) {
14847
+ return this.replyDeviceChildRequest(auditPeerId, open, request.childSessionId, request.questionId, {
14848
+ answers: request.answers,
14849
+ }, signalArg);
14850
+ }
13976
14851
  if (open.kind === 'conversation') {
13977
14852
  return this.replyQuestionForPrincipal('device', auditPeerId, validateRequest(() => assertQuestionReplyRequest({
13978
14853
  projectId: open.projectId,
@@ -14093,13 +14968,104 @@ export class OpenCodeController {
14093
14968
  */
14094
14969
  private createManagementRouter(): plugins.typedrequest.TypedRouter {
14095
14970
  const router = new plugins.typedrequest.TypedRouter();
14096
- router.addTypedHandler(this.createStatusHandler());
14971
+ router.addTypedHandler(this.createManagementStatusHandler());
14097
14972
  router.addTypedHandler(this.createUpgradeLaunchHandler());
14098
14973
  router.addTypedHandler(this.createUpgradePrepareBeginHandler());
14099
14974
  router.addTypedHandler(this.createUpgradeFinalizeHandler());
14975
+ router.addTypedHandler(this.createGatewaySyncHandler());
14100
14976
  return router;
14101
14977
  }
14102
14978
 
14979
+ /** The browser's status and, on the management endpoint only, the gateway client's (AGL-828). */
14980
+ private createManagementStatusHandler(): plugins.typedrequest.TypedHandler<IReq_ControllerManagementStatus> {
14981
+ return new plugins.typedrequest.TypedHandler<IReq_ControllerManagementStatus>(
14982
+ 'controller.status',
14983
+ async (requestArg) => {
14984
+ validateRequest(() => assertEmptyRequest(requestArg));
14985
+ return { ...this.statusForPrincipal('browser'), gateway: this.gatewayClient?.status() ?? { state: 'not_enrolled' } };
14986
+ },
14987
+ );
14988
+ }
14989
+
14990
+ /**
14991
+ * `agl remote gateway sync [--rotate]`: only a process of the controller's own OS user that holds the request's
14992
+ * loopback connection (the `localCli` it names, proved from the kernel) syncs the route now, rotating the
14993
+ * trusted-proxy secret first when asked; audited as `remote.gateway.sync`.
14994
+ */
14995
+ private createGatewaySyncHandler(): plugins.typedrequest.TypedHandler<IReq_ControllerGatewaySync> {
14996
+ return new plugins.typedrequest.TypedHandler<IReq_ControllerGatewaySync>(
14997
+ 'controller.gateway.sync',
14998
+ async (requestArg, toolsArg) => {
14999
+ const peer = peerFromLocalData(toolsArg?.localData);
15000
+ this.recordUnauthenticatedPreflightOperation(peer.id);
15001
+ const invalid = () => new plugins.typedrequest.TypedResponseError(
15002
+ 'The gateway sync request is invalid.',
15003
+ { code: 'invalid_request' },
15004
+ );
15005
+ if (
15006
+ !requestArg
15007
+ || typeof requestArg !== 'object'
15008
+ || Array.isArray(requestArg)
15009
+ || Object.keys(requestArg).length !== 2
15010
+ || typeof requestArg.rotate !== 'boolean'
15011
+ ) throw invalid();
15012
+ try {
15013
+ assertConfigurationLocalCliActor(requestArg.localCli);
15014
+ } catch {
15015
+ throw invalid();
15016
+ }
15017
+ const localCli = requestArg.localCli;
15018
+ try {
15019
+ const [caller] = await proveConnectionProcessAncestry(readManagementPeerConnection(toolsArg?.localData), localCli.pid, 1);
15020
+ if (!caller || caller.parentPid !== localCli.parentPid) throw new Error('The caller is not the process it names.');
15021
+ } catch (errorArg) {
15022
+ if (!(errorArg instanceof Error)) throw errorArg;
15023
+ throw new plugins.typedrequest.TypedResponseError(
15024
+ 'Only a process of the controller\'s own OS user that holds its connection syncs the gateway route.',
15025
+ { code: 'unauthorized' },
15026
+ );
15027
+ }
15028
+ const gatewayClient = this.gatewayClient;
15029
+ const authStore = this.requireAuthStore();
15030
+ if (!gatewayClient || this.lifecycleState !== 'ready') {
15031
+ throw new plugins.typedrequest.TypedResponseError('The controller is not ready.', { code: 'not_ready' });
15032
+ }
15033
+ const before = gatewayClient.status();
15034
+ const enrolment = before.enrolment;
15035
+ if (!enrolment) {
15036
+ throw new plugins.typedrequest.TypedResponseError(
15037
+ `controller:${this.requireRuntimeConfig().controllerPort} is not enrolled with a gateway: run \`agl remote gateway enrol\` first.`,
15038
+ { code: 'not_enrolled' },
15039
+ );
15040
+ }
15041
+ const details = { gateway: {
15042
+ gatewayUrl: enrolment.gatewayUrl,
15043
+ gatewayClientId: enrolment.gatewayClientId,
15044
+ appId: enrolment.appId,
15045
+ hostname: enrolment.hostname,
15046
+ targetHost: enrolment.target.host,
15047
+ targetPort: enrolment.target.port,
15048
+ routeKey: gatewayRouteKey({ gatewayClientId: enrolment.gatewayClientId, appId: enrolment.appId, hostname: enrolment.hostname }),
15049
+ rotate: requestArg.rotate,
15050
+ } };
15051
+ const audit = { type: 'remote.gateway.sync' as const, peerId: peer.id, localCli, details };
15052
+ await authStore.recordAuditEvent({ ...audit, outcome: 'attempted' });
15053
+ let gateway: IControllerGatewayStatus;
15054
+ try {
15055
+ gateway = await gatewayClient.sync({ rotate: requestArg.rotate });
15056
+ } catch (errorArg) {
15057
+ await authStore.recordAuditEvent({ ...audit, outcome: 'failed' });
15058
+ throw new plugins.typedrequest.TypedResponseError(
15059
+ errorArg instanceof Error ? errorArg.message : 'The gateway sync failed.',
15060
+ { code: 'gateway_sync_failed' },
15061
+ );
15062
+ }
15063
+ await authStore.recordAuditEvent({ ...audit, outcome: gateway.state === 'synced' ? 'succeeded' : 'failed' });
15064
+ return { gateway };
15065
+ },
15066
+ );
15067
+ }
15068
+
14103
15069
  private createStatusHandler(): plugins.typedrequest.TypedHandler<IReq_ControllerStatus> {
14104
15070
  return new plugins.typedrequest.TypedHandler<IReq_ControllerStatus>(
14105
15071
  'controller.status',
@@ -15980,38 +16946,10 @@ export class OpenCodeController {
15980
16946
  const request = validateRequest(
15981
16947
  () => assertSessionChildPermissionReplyRequest(requestArg),
15982
16948
  );
15983
- return this.runOperation(peer, async (signalArg) => this.runAudited(
15984
- {
15985
- type: 'permission.reply',
15986
- peerId: peer.id,
15987
- sessionId: request.childSessionId,
15988
- requestId: request.requestId,
15989
- },
15990
- async () => this.withHarnessSubmissionAdmission(
15991
- request.projectId,
15992
- request.parentSessionId,
15993
- signalArg,
15994
- async () => {
15995
- const scope = this.requireChildScope(peer, request);
15996
- const first = await this.revalidateChildScope(scope, signalArg, true);
15997
- const pending = await first.parent.client.listPermissions(
15998
- first.parent.project.directory,
15999
- request.childSessionId.nativeId,
16000
- AbortSignal.any([signalArg, first.parent.runtimeAuthority.signal]),
16001
- );
16002
- this.assertAttentionRequestOwned(pending, request.requestId, 'permission');
16003
- const current = await this.revalidateChildScope(scope, signalArg, true);
16004
- const success = await current.parent.client.replyPermission(
16005
- current.parent.project.directory,
16006
- request.requestId.nativeId,
16007
- request.reply,
16008
- request.message,
16009
- AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]),
16010
- );
16011
- await this.revalidateChildScope(scope, signalArg);
16012
- return { success };
16013
- },
16014
- ),
16949
+ return this.runOperation(peer, async (signalArg) => this.replyChildRequestForPrincipal(
16950
+ 'browser', peer.id, request,
16951
+ (activeRequiredArg) => this.revalidateChildScope(this.requireChildScope(peer, request), signalArg, activeRequiredArg),
16952
+ signalArg,
16015
16953
  ));
16016
16954
  },
16017
16955
  );
@@ -16023,43 +16961,10 @@ export class OpenCodeController {
16023
16961
  const request = validateRequest(
16024
16962
  () => assertSessionChildQuestionReplyRequest(requestArg),
16025
16963
  );
16026
- return this.runOperation(peer, async (signalArg) => this.runAudited(
16027
- {
16028
- type: 'question.reply',
16029
- peerId: peer.id,
16030
- sessionId: request.childSessionId,
16031
- requestId: request.requestId,
16032
- },
16033
- async () => this.withHarnessSubmissionAdmission(
16034
- request.projectId,
16035
- request.parentSessionId,
16036
- signalArg,
16037
- async () => {
16038
- const scope = this.requireChildScope(peer, request);
16039
- const first = await this.revalidateChildScope(scope, signalArg, true);
16040
- const pending = await first.parent.client.listQuestions(
16041
- first.parent.project.directory,
16042
- request.childSessionId.nativeId,
16043
- AbortSignal.any([signalArg, first.parent.runtimeAuthority.signal]),
16044
- );
16045
- this.assertAttentionRequestOwned(pending, request.requestId, 'question');
16046
- const current = await this.revalidateChildScope(scope, signalArg, true);
16047
- const success = request.answers === null
16048
- ? await current.parent.client.rejectQuestion(
16049
- current.parent.project.directory,
16050
- request.requestId.nativeId,
16051
- AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]),
16052
- )
16053
- : await current.parent.client.replyQuestion(
16054
- current.parent.project.directory,
16055
- request.requestId.nativeId,
16056
- request.answers,
16057
- AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]),
16058
- );
16059
- await this.revalidateChildScope(scope, signalArg);
16060
- return { success };
16061
- },
16062
- ),
16964
+ return this.runOperation(peer, async (signalArg) => this.replyChildRequestForPrincipal(
16965
+ 'browser', peer.id, request,
16966
+ (activeRequiredArg) => this.revalidateChildScope(this.requireChildScope(peer, request), signalArg, activeRequiredArg),
16967
+ signalArg,
16063
16968
  ));
16064
16969
  },
16065
16970
  );
@@ -16804,6 +17709,86 @@ export class OpenCodeController {
16804
17709
  * alike. The harness checks the reply against the pending request before it sends anything; elicitations are never
16805
17710
  * answered automatically, auto-accept included.
16806
17711
  */
17712
+ /**
17713
+ * Answers a permission or question of a direct child (an OpenCode subagent) of a managed root conversation, for the
17714
+ * owner's browser and a paired device alike: `verifyArg` proves the session is a direct child of the root (the
17715
+ * browser's child scope, or the same direct-child check for a device) and, while `activeRequiredArg`, that it runs. It
17716
+ * runs before the pending list is read, before the answer is sent and after it; `null` answers reject a question.
17717
+ */
17718
+ private async replyChildRequestForPrincipal(
17719
+ principalArg: TControllerOperationPrincipal,
17720
+ peerIdArg: string,
17721
+ requestArg: {
17722
+ projectId: string;
17723
+ parentSessionId: IControllerRuntimeId & { harnessId: 'opencode' };
17724
+ childSessionId: IControllerRuntimeId & { harnessId: 'opencode' };
17725
+ requestId: IControllerRuntimeId & { harnessId: 'opencode' };
17726
+ } & ({ reply: TControllerPermissionReply; message?: string } | { answers: string[][] | null }),
17727
+ verifyArg: (activeRequiredArg: boolean) => Promise<{ parent: IOpenCodeManagedSessionScopeAuthority }>,
17728
+ signalArg: AbortSignal,
17729
+ ): Promise<{ success: boolean }> {
17730
+ const kind = 'reply' in requestArg ? 'permission' : 'question';
17731
+ return this.runAudited(
17732
+ {
17733
+ type: kind === 'permission' ? 'permission.reply' : 'question.reply',
17734
+ peerId: this.auditPeerId(principalArg, peerIdArg),
17735
+ sessionId: requestArg.childSessionId,
17736
+ requestId: requestArg.requestId,
17737
+ },
17738
+ async () => this.withHarnessSubmissionAdmission(
17739
+ requestArg.projectId,
17740
+ requestArg.parentSessionId,
17741
+ signalArg,
17742
+ async () => {
17743
+ const first = await verifyArg(true);
17744
+ const firstSignal = AbortSignal.any([signalArg, first.parent.runtimeAuthority.signal]);
17745
+ const pending = kind === 'permission'
17746
+ ? await first.parent.client.listPermissions(first.parent.project.directory, requestArg.childSessionId.nativeId, firstSignal)
17747
+ : await first.parent.client.listQuestions(first.parent.project.directory, requestArg.childSessionId.nativeId, firstSignal);
17748
+ this.assertAttentionRequestOwned(pending, requestArg.requestId, kind);
17749
+ const current = await verifyArg(true);
17750
+ const signal = AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]);
17751
+ const { directory } = current.parent.project;
17752
+ const success = 'reply' in requestArg
17753
+ ? await current.parent.client.replyPermission(directory, requestArg.requestId.nativeId, requestArg.reply, requestArg.message, signal)
17754
+ : requestArg.answers === null
17755
+ ? await current.parent.client.rejectQuestion(directory, requestArg.requestId.nativeId, signal)
17756
+ : await current.parent.client.replyQuestion(directory, requestArg.requestId.nativeId, requestArg.answers, signal);
17757
+ await verifyArg(false);
17758
+ return { success };
17759
+ },
17760
+ ),
17761
+ );
17762
+ }
17763
+
17764
+ /**
17765
+ * A device's proof that `childSessionIdArg` is a direct child of the managed root conversation, by the check the
17766
+ * browser's child scopes run (`observeOpenCodeDirectChild`), and, while `activeRequiredArg`, that it runs: a child
17767
+ * whose turn ended takes no answer.
17768
+ */
17769
+ private async verifyDeviceDirectChild(
17770
+ projectIdArg: string,
17771
+ parentSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
17772
+ childSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
17773
+ signalArg: AbortSignal,
17774
+ activeRequiredArg: boolean,
17775
+ ): Promise<{ parent: IOpenCodeManagedSessionScopeAuthority }> {
17776
+ let observation: Awaited<ReturnType<OpenCodeController['observeOpenCodeDirectChild']>>;
17777
+ try {
17778
+ observation = await this.observeOpenCodeDirectChild(projectIdArg, parentSessionIdArg, childSessionIdArg, signalArg);
17779
+ } catch (errorArg) {
17780
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError
17781
+ && (errorArg.errorData as { code?: unknown } | undefined)?.code === 'child_scope_invalid') {
17782
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
17783
+ }
17784
+ throw errorArg;
17785
+ }
17786
+ if (activeRequiredArg && this.childScopeObservedMode(observation.child.session) !== 'active') {
17787
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
17788
+ }
17789
+ return observation;
17790
+ }
17791
+
16807
17792
  private async replyElicitationForPrincipal(
16808
17793
  principalArg: TControllerOperationPrincipal,
16809
17794
  peerIdArg: string,
@@ -17246,6 +18231,16 @@ export class OpenCodeController {
17246
18231
  protectedRouterArg.addHandler<TControllerTicketRequest<TTicketOperation>>(`controller.ticket.${operation}`,
17247
18232
  async (requestArg, toolsArg) => {
17248
18233
  const peer = peerFromLocalData(toolsArg?.localData);
18234
+ if (operation === 'answer') {
18235
+ const request = validateRequest(() => assertTicketRequest('answer', requestArg));
18236
+ return this.runOperation(peer, async (signalArg) => this.answerTicketForPrincipal('browser', peer.id, request, signalArg),
18237
+ toolsArg?.abortSignal);
18238
+ }
18239
+ if (operation === 'comment' || operation === 'ask' || operation === 'move') {
18240
+ const request = validateRequest(() => assertTicketRequest(operation, requestArg));
18241
+ return this.runOperation(peer, async (signalArg) => this.changeTicketForPrincipal('browser', peer.id, operation, request, signalArg),
18242
+ toolsArg?.abortSignal);
18243
+ }
17249
18244
  return this.runOperation(peer, async (signalArg) => {
17250
18245
  try {
17251
18246
  const owner = ticketOwnerActor(await this.requireAuthStore().getState());
@@ -17261,6 +18256,88 @@ export class OpenCodeController {
17261
18256
  }
17262
18257
  }
17263
18258
 
18259
+ /**
18260
+ * Answers a ticket question as the owner, for the owner's browser and a paired device alike, audited as
18261
+ * `ticket.answer` with the peer. A deploy plan's or a maintenance window's question takes it as the owner's go. The
18262
+ * identical answer again is a confirmed replay; a different one is refused (`ticket_question_answered`), and the
18263
+ * client keeps the owner's choice.
18264
+ */
18265
+ private async answerTicketForPrincipal(
18266
+ principalArg: TControllerOperationPrincipal,
18267
+ peerIdArg: string,
18268
+ requestArg: TTicketRequest<'answer'>,
18269
+ signalArg: AbortSignal,
18270
+ ): Promise<TTicketResponse<'answer'>> {
18271
+ return this.runAudited({ type: 'ticket.answer', peerId: this.auditPeerId(principalArg, peerIdArg) }, async () => {
18272
+ try {
18273
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18274
+ return await this.ticketStore.execute('answer', requestArg, owner, signalArg);
18275
+ } catch (errorArg) {
18276
+ if (errorArg instanceof TicketError) throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
18277
+ throw errorArg;
18278
+ }
18279
+ });
18280
+ }
18281
+
18282
+ /**
18283
+ * Comments on a ticket, asks on it or moves it as the owner, for the owner's browser and a paired device alike,
18284
+ * audited as `ticket.comment`, `ticket.ask` or `ticket.move` with the peer (the envelope alone). The ticket store
18285
+ * decides every change in one transaction: a refusal changes nothing and carries the store's code and reason.
18286
+ */
18287
+ private async changeTicketForPrincipal<TMethod extends TTicketChangeOperation>(
18288
+ principalArg: TControllerOperationPrincipal,
18289
+ peerIdArg: string,
18290
+ methodArg: TMethod,
18291
+ requestArg: TTicketRequest<TMethod>,
18292
+ signalArg: AbortSignal,
18293
+ ): Promise<TTicketResponse<TMethod>> {
18294
+ return this.runAudited({ type: ticketChangeAuditTypes[methodArg], peerId: this.auditPeerId(principalArg, peerIdArg) }, async () => {
18295
+ try {
18296
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18297
+ return await this.ticketStore.execute(methodArg, requestArg, owner, signalArg);
18298
+ } catch (errorArg) {
18299
+ if (errorArg instanceof TicketError) throw new plugins.typedrequest.TypedResponseError(errorArg.message,
18300
+ { code: errorArg.code, ...readTicketRevisionConflict(errorArg) });
18301
+ throw errorArg;
18302
+ }
18303
+ });
18304
+ }
18305
+
18306
+ /**
18307
+ * The owner, whom a device's ticket request runs as, and what the device's ticket views read besides the tickets:
18308
+ * the owner's principal id, which they replace with the `owner` kind, and the session feed's published rows.
18309
+ */
18310
+ private async deviceTicketViewer(): Promise<{ owner: ITicketActor; viewer: IDeviceTicketViewer }> {
18311
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18312
+ return { owner, viewer: { ownerId: owner.id, rowOf: (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg) } };
18313
+ }
18314
+
18315
+ /** The ticket a ticket's `parentId` names, which a device's card and detail name; a store refusal as a device's. */
18316
+ private async deviceTicketParent(ownerArg: ITicketActor, ticketArg: ITicket, signalArg: AbortSignal): Promise<ITicket | undefined> {
18317
+ if (ticketArg.parentId === undefined) return undefined;
18318
+ try {
18319
+ return (await this.ticketStore.execute('get', { ticketId: ticketArg.parentId, limit: 1 }, ownerArg, signalArg)).ticket;
18320
+ } catch (errorArg) {
18321
+ throw deviceTicketRefusal(errorArg);
18322
+ }
18323
+ }
18324
+
18325
+ private requireInbox(): ControllerInbox {
18326
+ if (!this.inbox) {
18327
+ throw new plugins.typedrequest.TypedResponseError('The Inbox is not running.', { code: 'controller_unavailable' });
18328
+ }
18329
+ return this.inbox;
18330
+ }
18331
+
18332
+ /** The Inbox: what waits for the owner, read after every source that changed (AGL-1635). */
18333
+ private registerInboxHandlers(protectedRouterArg: ControllerProtectedRouter): void {
18334
+ protectedRouterArg.addHandler<IReq_ControllerInboxList>('controller.inbox.list', async (requestArg, toolsArg) => {
18335
+ validateRequest(() => assertEmptyRequest(requestArg));
18336
+ const peer = peerFromLocalData(toolsArg?.localData);
18337
+ return this.runOperation(peer, async () => this.requireInbox().list(), toolsArg?.abortSignal);
18338
+ });
18339
+ }
18340
+
17264
18341
  /**
17265
18342
  * The host's driver: one Flex session that no session list shows, opened from the topbar. Fleet
17266
18343
  * events reach it through the relay once it exists.
@@ -17302,8 +18379,8 @@ export class OpenCodeController {
17302
18379
  ...(model?.providerConnectionId === undefined ? {} : { providerConnectionId: model.providerConnectionId }),
17303
18380
  }, signalArg, { nativeId: nativeIdArg });
17304
18381
  },
17305
- latestAssistantText: (projectIdArg, nativeIdArg, signalArg) => (
17306
- this.latestDriverAssistantText(projectIdArg, nativeIdArg, signalArg)
18382
+ latestAssistantMessage: (projectIdArg, nativeIdArg, signalArg) => (
18383
+ this.latestDriverAssistantMessage(projectIdArg, nativeIdArg, signalArg)
17307
18384
  ),
17308
18385
  publish: (statusArg) => {
17309
18386
  void this.pushControllerEvent({ type: 'driver.changed', driverStatus: statusArg, timestamp: Date.now() })
@@ -17341,7 +18418,8 @@ export class OpenCodeController {
17341
18418
  relayed: async (eventsArg) => {
17342
18419
  const authority = this.configurationAuthority;
17343
18420
  if (!authority) throw new Error('The configuration authority is unavailable.');
17344
- const reportWorkers = await this.requireDirectReports().reportWorkers((await authority.getResource()).resourceId);
18421
+ const groups = await this.requireDirectReports().reportWorkers((await authority.getResource()).resourceId);
18422
+ const reportWorkers = new Set([...groups.values()].flat().map(({ worker }) => worker.name));
17345
18423
  return eventsArg.filter((eventArg) => !eventArg.workerName || !reportWorkers.has(eventArg.workerName));
17346
18424
  },
17347
18425
  });
@@ -17542,17 +18620,19 @@ export class OpenCodeController {
17542
18620
  }
17543
18621
  }
17544
18622
 
17545
- private async latestDriverAssistantText(
18623
+ /** The driver's newest assistant transcript entry with text: the entry's own id (a Flex message or part id). */
18624
+ private async latestDriverAssistantMessage(
17546
18625
  projectIdArg: string,
17547
18626
  nativeIdArg: string,
17548
18627
  signalArg?: AbortSignal,
17549
- ): Promise<string | undefined> {
18628
+ ): Promise<IDriverAssistantMessage | undefined> {
17550
18629
  try {
17551
18630
  const page = await this.requireFlexProjectionReader().listMessagePage(projectIdArg, nativeIdArg, { limit: 8 }, signalArg);
17552
- return page.messages
18631
+ const message = page.messages
17553
18632
  .flatMap((messageArg) => this.toFlexMessageBundle(messageArg).messages)
17554
18633
  .reverse()
17555
- .find((messageArg) => messageArg.role === 'assistant' && messageArg.text.trim())?.text;
18634
+ .find((messageArg) => messageArg.role === 'assistant' && messageArg.text.trim());
18635
+ return message === undefined ? undefined : { id: message.id.nativeId, text: message.text, createdAt: message.createdAt };
17556
18636
  } catch (errorArg) {
17557
18637
  if (errorArg instanceof FlexProjectionNotFoundError) return undefined;
17558
18638
  throw errorArg;
@@ -17642,18 +18722,21 @@ export class OpenCodeController {
17642
18722
  );
17643
18723
  }
17644
18724
 
18725
+ /** A driver operation for the browser: a `DriverError` is answered with its own code (a device's: `serveDeviceDriver`). */
18726
+ private async serveDriver<T>(operationArg: () => Promise<T>): Promise<T> {
18727
+ try {
18728
+ return await operationArg();
18729
+ } catch (errorArg) {
18730
+ if (errorArg instanceof DriverError) {
18731
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
18732
+ }
18733
+ throw errorArg;
18734
+ }
18735
+ }
18736
+
17645
18737
  /** The driver topbar: the host's one driver session, its status, and the unread turns it marks seen. */
17646
18738
  private registerDriverHandlers(protectedRouterArg: ControllerProtectedRouter): void {
17647
- const serve = async <T>(operationArg: () => Promise<T>): Promise<T> => {
17648
- try {
17649
- return await operationArg();
17650
- } catch (errorArg) {
17651
- if (errorArg instanceof DriverError) {
17652
- throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
17653
- }
17654
- throw errorArg;
17655
- }
17656
- };
18739
+ const serve = <T>(operationArg: () => Promise<T>): Promise<T> => this.serveDriver(operationArg);
17657
18740
  protectedRouterArg.addHandler<IReq_ControllerDriverGet>(
17658
18741
  'controller.driver.get',
17659
18742
  async (requestArg, toolsArg) => {
@@ -17902,9 +18985,12 @@ export class OpenCodeController {
17902
18985
  async (requestArg, toolsArg) => {
17903
18986
  const peer = peerFromLocalData(toolsArg?.localData);
17904
18987
  const { session: ref, text, attachments } = validateRequest(() => assertNativeSessionSendRequest(requestArg));
17905
- return this.runOperation(peer, async (signalArg) => ({
17906
- session: await this.sendNativeSession(peer.id, ref, text, attachments, signalArg, assertNativeSessionWritable),
17907
- }), toolsArg?.abortSignal);
18988
+ return this.runOperation(peer, async (signalArg) => {
18989
+ await this.sendNativeSession(peer.id, ref, text, attachments, signalArg, assertNativeSessionWritable,
18990
+ { kind: 'agent', label: 'Owner', subject: agentMessageSubjects.ownerNativeView });
18991
+ // The session as the send left it, read apart from the audited send.
18992
+ return { session: await this.serveNativeSession(signalArg, async () => (await this.nativeSessions.resolve(ref)).session) };
18993
+ }, toolsArg?.abortSignal);
17908
18994
  },
17909
18995
  );
17910
18996
 
@@ -18137,16 +19223,22 @@ export class OpenCodeController {
18137
19223
  if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
18138
19224
  // The session state store states its own refusals: a stale scratchpad revision, a missing record.
18139
19225
  if (errorArg instanceof AuthError) throw asTypedResponseError(errorArg, 'native session');
18140
- throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'native_session_failed' });
19226
+ // Whether the message may have reached the session: a refusal before dispatch did not, a dispatched failure may have.
19227
+ const outcome = errorArg instanceof FleetDispatchError ? { outcome: errorArg.dispatched ? 'unknown' as const : 'refused' as const } : {};
19228
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'native_session_failed', ...outcome });
18141
19229
  }
18142
19230
  }
18143
19231
 
18144
19232
  /**
18145
- * The one send to a native session, for the browser's `controller.nativesession.send` and the fleet's
18146
- * `native-message`: audited as `session.send`, under the session's lock, where the session is resolved again and
18147
- * `assertArg` refuses what this caller may not write to, so a session that started running meanwhile is refused. A
18148
- * Codex thread goes through its shared server, a Claude Code background job is woken through Claude Code itself, and
18149
- * another settled Claude Code session resumes in AGL's own Claude Code. Resolves with the session after the send.
19233
+ * The one send to a native session, for the browser's `controller.nativesession.send`, a paired device, the fleet's
19234
+ * `native-message` and an MCP `session_message`: audited as `session.send`, under the session's lock, where the
19235
+ * session is resolved again and `assertArg` refuses what this caller may not write to, so a session whose state
19236
+ * changed meanwhile is refused. A Codex thread goes through its shared server, a Claude Code background job is reached
19237
+ * through Claude Code itself (woken while settled, its inbox while it runs), and another settled Claude Code session
19238
+ * resumes in AGL's own Claude Code. The owner's own text (`ownerArg`) goes into a job's inbox as the owner's agent
19239
+ * message: a peer message names no sender of its own. Resolves right after the dispatch with, for a job, how it took
19240
+ * the message, and reads nothing after it: a failed read must never turn a delivered message into a refusal, which a
19241
+ * caller would answer by sending again. A caller that shows the session reads it afterwards.
18150
19242
  */
18151
19243
  private async sendNativeSession(
18152
19244
  peerIdArg: string,
@@ -18155,25 +19247,29 @@ export class OpenCodeController {
18155
19247
  attachmentsArg: readonly IControllerDraftAttachment[] | undefined,
18156
19248
  signalArg: AbortSignal,
18157
19249
  assertArg: (resolvedArg: IResolvedNativeSession) => void,
18158
- ): Promise<IControllerNativeSession> {
19250
+ ownerArg?: IControllerPromptSender,
19251
+ ): Promise<{ job?: TControllerNativeJobDelivery }> {
18159
19252
  const sessionId = nativeSessionRuntimeId(refArg);
18160
19253
  return this.runAudited({ type: 'session.send', peerId: peerIdArg, sessionId }, () => this.serveNativeSession(signalArg, async () => {
18161
19254
  const scope = (await this.nativeSessions.resolve(refArg)).scope;
19255
+ let job: TControllerNativeJobDelivery | undefined;
18162
19256
  await this.withSessionStateMutation(scope, sessionId, async () => {
18163
19257
  const resolved = await this.nativeSessions.resolve(refArg);
18164
19258
  assertArg(resolved);
18165
19259
  if (refArg.harness === 'codex') await this.sendNativeCodexSession(resolved, textArg, attachmentsArg);
18166
- else if (resolved.claudeJob) await this.sendNativeClaudeJob(resolved, textArg, attachmentsArg);
18167
- else await this.sendNativeClaudeSession(resolved, textArg, attachmentsArg, signalArg);
19260
+ else if (resolved.claudeJob) {
19261
+ job = await this.sendNativeClaudeJob(resolved, resolved.claudeJob === 'inbox' && ownerArg ? formatAgentMessage(ownerArg, textArg) : textArg, attachmentsArg);
19262
+ } else await this.sendNativeClaudeSession(resolved, textArg, attachmentsArg, signalArg);
18168
19263
  });
18169
- return (await this.nativeSessions.resolve(refArg)).session;
19264
+ return job === undefined ? {} : { job };
18170
19265
  }));
18171
19266
  }
18172
19267
 
18173
19268
  /**
18174
19269
  * The fleet's `native-message`: resolves the Claude Code background job the caller names by id or prefix, refuses
18175
19270
  * what the browser's send would refuse and what is no background job, each with its reason and the adopt command,
18176
- * and sends the message behind the `session_message` attribution header through `sendNativeSession`.
19271
+ * and sends the message behind the `session_message` attribution header through `sendNativeSession`: a wake of a
19272
+ * settled job, or its inbox while it runs.
18177
19273
  */
18178
19274
  private async sendFleetNativeMessage(
18179
19275
  requestArg: TFleetWorkerRequest<'native-message'>,
@@ -18190,7 +19286,7 @@ export class OpenCodeController {
18190
19286
  if (readOnly) {
18191
19287
  // What the caller can do instead: steer the worker, wait for the job to settle, or adopt it into its profile.
18192
19288
  const next = readOnly.reason === 'fleetWorker' && workerName ? ` Message it with \`agl fleet worker message ${workerName}\`.`
18193
- : readOnly.reason === 'running' || readOnly.reason === 'jobHeld' ? ` Message it, or adopt it, once it settles; it is adopted with \`${adopt}\`.`
19289
+ : readOnly.reason === 'running' || readOnly.reason === 'jobHeld' || readOnly.reason === 'unaddressable' ? ` Message it, or adopt it, once it settles; it is adopted with \`${adopt}\`.`
18194
19290
  : readOnly.reason === 'jobFailed' ? ` A failed job takes no wake; adopt it with \`${adopt}\`.`
18195
19291
  : readOnly.reason === 'profileHome' ? ` Adopt it as a worker of that profile with \`${adopt}\`.` : '';
18196
19292
  throw new plugins.typedrequest.TypedResponseError(`${readOnly.message}${next}`, { code: 'session_read_only' });
@@ -18205,12 +19301,16 @@ export class OpenCodeController {
18205
19301
  const jobId = found.agent.id;
18206
19302
  if (!jobId) throw new plugins.typedrequest.TypedResponseError('Claude Code lists this session without a job id, so it cannot wake it.', { code: 'session_read_only' });
18207
19303
  const text = formatAgentMessage({ kind: 'agent', label: requestArg.sender, subject: this.ownerMessageSubject(actorArg) }, requestArg.text);
18208
- await this.sendNativeSession(peerId, found.ref, text, undefined, this.operationAbortController.signal, assertMessageable);
19304
+ const { job } = await this.sendNativeSession(peerId, found.ref, text, undefined, this.operationAbortController.signal, assertMessageable);
18209
19305
  return {
18210
- delivery: 'native-wake', nativeId: found.agent.sessionId, jobId, cwd: found.agent.cwd,
19306
+ delivery: job === 'inbox' ? 'native-inbox' : 'native-wake', nativeId: found.agent.sessionId, jobId, cwd: found.agent.cwd,
18211
19307
  ...(profileId ? { profileId } : {}),
18212
- note: 'Delivered as a native wake of a Claude Code background job no fleet worker binds: it holds no dispatch fence, '
18213
- + 'writes no ticket comment and does not observe the woken turn. Adopt the job to steer and observe it as a fleet worker.',
19308
+ note: job === 'inbox'
19309
+ ? 'Delivered into the inbox of a running Claude Code background job no fleet worker binds, through Claude Code\'s own '
19310
+ + 'SendMessage: accepted and queued there, not yet read. It holds no dispatch fence, writes no ticket comment and does not '
19311
+ + 'observe the turn that reads it. Adopt the job, once it settles, to steer and observe it as a fleet worker.'
19312
+ : 'Delivered as a native wake of a Claude Code background job no fleet worker binds: it holds no dispatch fence, '
19313
+ + 'writes no ticket comment and does not observe the woken turn. Adopt the job to steer and observe it as a fleet worker.',
18214
19314
  adopt,
18215
19315
  };
18216
19316
  }
@@ -18271,18 +19371,21 @@ export class OpenCodeController {
18271
19371
  }
18272
19372
 
18273
19373
  /**
18274
- * Wakes a settled Claude Code background job with the message through Claude Code itself, so the job stays the
18275
- * session's owner. Claude Code does not report when the woken turn ends, so the upload stays for the sweep unless
18276
- * the message never reached Claude Code.
19374
+ * Sends to a Claude Code background job through Claude Code itself, so the job stays the session's owner: a settled
19375
+ * job is woken with the message, a running one takes it in its inbox, as the resolution prepared it. Claude Code does
19376
+ * not report when the turn that reads it ends, so the upload stays for the sweep unless the message never reached
19377
+ * Claude Code.
18277
19378
  */
18278
19379
  private async sendNativeClaudeJob(
18279
19380
  resolvedArg: IResolvedNativeSession,
18280
19381
  textArg: string,
18281
19382
  attachmentsArg: readonly IControllerDraftAttachment[] | undefined,
18282
- ): Promise<void> {
19383
+ ): Promise<TControllerNativeJobDelivery> {
18283
19384
  const upload = await this.createRetainedUpload(attachmentsArg);
19385
+ let receipt: Awaited<ReturnType<FleetWorkers['nativeSend']>>;
18284
19386
  try {
18285
- await this.requireFleetWorkers().nativeSend('claude', resolvedArg.native, `${textArg}${upload?.promptSuffix ?? ''}`, () => undefined);
19387
+ const session = { ...resolvedArg.native, jobDelivery: resolvedArg.claudeJob!, ...(resolvedArg.peerHomes ? { peerHomes: resolvedArg.peerHomes } : {}) };
19388
+ receipt = await this.requireFleetWorkers().nativeSend('claude', session, `${textArg}${upload?.promptSuffix ?? ''}`, () => undefined);
18286
19389
  } catch (errorArg) {
18287
19390
  if (upload && errorArg instanceof FleetDispatchError && !errorArg.dispatched) {
18288
19391
  void this.trackOperationPromise(upload.cleanup())
@@ -18291,6 +19394,8 @@ export class OpenCodeController {
18291
19394
  throw errorArg;
18292
19395
  }
18293
19396
  upload?.release();
19397
+ if (!receipt.job) throw new FleetDispatchError('Claude Code did not say how the background job took the message. Inspect it before sending again.', true);
19398
+ return receipt.job;
18294
19399
  }
18295
19400
 
18296
19401
  /**
@@ -18316,17 +19421,24 @@ export class OpenCodeController {
18316
19421
  }
18317
19422
  }
18318
19423
 
19424
+ /**
19425
+ * A direct report operation for the owner's browser or a device, given the owner: its failures are bounded messages
19426
+ * for the owner (`direct_report_failed`), which the Driver view and a device show as they are.
19427
+ */
19428
+ private async serveDirectReport<T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> {
19429
+ try {
19430
+ return await operationArg((await this.readFleetScope()).owner);
19431
+ } catch (errorArg) {
19432
+ if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
19433
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'direct_report_failed' });
19434
+ }
19435
+ }
19436
+
18319
19437
  /** The Driver view's direct reports: sessions that report to the owner, appointed from the fleet or adopted by reference. */
18320
19438
  private registerDirectReportHandlers(protectedRouterArg: ControllerProtectedRouter): void {
18321
- // Direct report failures are bounded messages for the owner; the Driver view shows them as they are.
18322
- const serve = async <T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> => {
18323
- try {
18324
- return await operationArg((await this.readFleetScope()).owner);
18325
- } catch (errorArg) {
18326
- if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
18327
- throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'direct_report_failed' });
18328
- }
18329
- };
19439
+ const serve = <T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> => (
19440
+ this.serveDirectReport(signalArg, operationArg)
19441
+ );
18330
19442
  protectedRouterArg.addHandler<IReq_ControllerDirectReportList>(
18331
19443
  'controller.directreport.list',
18332
19444
  async (requestArg, toolsArg) => {
@@ -18387,36 +19499,61 @@ export class OpenCodeController {
18387
19499
  )), toolsArg?.abortSignal);
18388
19500
  },
18389
19501
  );
18390
- // The owner's steer of a fleet worker report goes through the report's driver ticket, as the driver's
18391
- // directreport_message does; a Codex thread takes it as the owner's agent message.
18392
19502
  protectedRouterArg.addHandler<IReq_ControllerDirectReportMessage>(
18393
19503
  'controller.directreport.message',
18394
19504
  async (requestArg, toolsArg) => {
18395
- const { name, text, expectedTurnId, attachments } = validateRequest(() => assertDirectReportMessageRequest(requestArg));
19505
+ const request = validateRequest(() => assertDirectReportMessageRequest(requestArg));
18396
19506
  const peer = peerFromLocalData(toolsArg?.localData);
18397
- return this.runOperation(peer, (signalArg) => serve(signalArg, async (ownerArg) => {
18398
- const channel = await this.requireDirectReports().channelOf(ownerArg, name);
18399
- if (channel.kind === 'session') {
18400
- if (attachments) {
18401
- throw new plugins.typedrequest.TypedResponseError(
18402
- 'A Codex thread report takes text only.', { code: 'invalid_request' },
18403
- );
18404
- }
18405
- const { delivery, turnId } = await this.messageDirectReportSession(channel, 'owner', peer.id, text, expectedTurnId);
18406
- return { delivery, ...(turnId === undefined ? {} : { turnId }) };
18407
- }
18408
- if (expectedTurnId !== undefined) throw new Error('expectedTurnId names the turn of a Codex thread; a fleet worker report is steered through its ticket.');
18409
- const fleetWorkers = this.requireFleetWorkers();
18410
- const configuration = (await this.readFleetScope()).configuration;
18411
- const job = await this.withRetainedSteerUpload(attachments, async (suffixArg) => (await fleetWorkers.execute('steer', {
18412
- messages: [{ name: channel.workerName, text: formatOwnerFleetMessage(`${text}${suffixArg}`) }], ticketKey: channel.report.driverTicketKey,
18413
- }, configuration, ownerArg, signalArg)).job);
18414
- return { job: await fleetWorkers.settled(ownerArg, job.id, signalArg) };
18415
- }), toolsArg?.abortSignal);
19507
+ return this.runOperation(peer, (signalArg) => serve(signalArg, async (ownerArg) => (
19508
+ this.messageDirectReportForPrincipal('browser', peer.id, ownerArg, request, signalArg)
19509
+ )), toolsArg?.abortSignal);
18416
19510
  },
18417
19511
  );
18418
19512
  }
18419
19513
 
19514
+ /**
19515
+ * The owner's own message to the active direct report `name`, from the Driver view or a paired device, audited as
19516
+ * `session.message` from the `Owner` for the caller. A fleet worker report is steered through the report's driver
19517
+ * ticket, as the driver's `directreport_message` does, and answers with the settled steer job, audited `failed`
19518
+ * unless the job succeeded; a steer the fleet refused is `direct_report_failed` with the fleet's reason, also audited
19519
+ * `failed`. A Codex thread takes it as the owner's agent message.
19520
+ */
19521
+ private async messageDirectReportForPrincipal(
19522
+ principalArg: TControllerOperationPrincipal,
19523
+ peerIdArg: string,
19524
+ ownerArg: string,
19525
+ requestArg: IReq_ControllerDirectReportMessage['request'],
19526
+ signalArg: AbortSignal,
19527
+ ): Promise<IReq_ControllerDirectReportMessage['response']> {
19528
+ const peerId = this.auditPeerId(principalArg, peerIdArg);
19529
+ const { name, text, expectedTurnId, attachments } = requestArg;
19530
+ const channel = await this.requireDirectReports().channelOf(ownerArg, name);
19531
+ if (channel.kind === 'session') {
19532
+ if (attachments) {
19533
+ throw new plugins.typedrequest.TypedResponseError(
19534
+ 'A Codex thread report takes text only.', { code: 'invalid_request' },
19535
+ );
19536
+ }
19537
+ const { delivery, turnId } = await this.messageDirectReportSession(channel, 'owner', peerId, text, expectedTurnId);
19538
+ return { delivery, ...(turnId === undefined ? {} : { turnId }) };
19539
+ }
19540
+ if (expectedTurnId !== undefined) throw new Error('expectedTurnId names the turn of a Codex thread; a fleet worker report is steered through its ticket.');
19541
+ return await this.runAudited({ type: 'session.message', peerId, sessionId: directReportRuntimeId(channel.report), senderLabel: 'Owner' }, async () => {
19542
+ try {
19543
+ const fleetWorkers = this.requireFleetWorkers();
19544
+ const configuration = (await this.readFleetScope()).configuration;
19545
+ const job = await this.withRetainedSteerUpload(attachments, async (suffixArg) => (await fleetWorkers.execute('steer', {
19546
+ messages: [{ name: channel.workerName, text: formatOwnerFleetMessage(`${text}${suffixArg}`) }], ticketKey: channel.report.driverTicketKey,
19547
+ }, configuration, ownerArg, signalArg)).job);
19548
+ return { job: await fleetWorkers.settled(ownerArg, job.id, signalArg) };
19549
+ } catch (errorArg) {
19550
+ // The fleet's own reason, as `serveDirectReport` gives it, before the audit would reduce it to a generic failure.
19551
+ if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
19552
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'direct_report_failed' });
19553
+ }
19554
+ }, ({ job }) => job.state === 'succeeded' ? 'succeeded' : 'failed');
19555
+ }
19556
+
18420
19557
  /** The driver session's instructions, notes and tools; the caller checked its session authority. */
18421
19558
  private async handleFlexDriverHostRequest(
18422
19559
  methodArg: 'driver.resolve' | 'driver.tool',
@@ -19113,9 +20250,14 @@ export class OpenCodeController {
19113
20250
  );
19114
20251
  }
19115
20252
 
20253
+ /**
20254
+ * Runs an operation between its `attempted` record and its terminal one. `outcomeOfArg` names the outcome of an
20255
+ * operation that returns its own failure (a settled job that failed), which is then recorded `failed`.
20256
+ */
19116
20257
  private async runAudited<T>(
19117
20258
  auditArg: Omit<IRecordAuditEventInput, 'outcome'>,
19118
20259
  operationArg: (operationIdArg: string) => Promise<T>,
20260
+ outcomeOfArg: (resultArg: T) => 'succeeded' | 'failed' = () => 'succeeded',
19119
20261
  ): Promise<T> {
19120
20262
  const operationId = plugins.crypto.randomBytes(24).toString('base64url');
19121
20263
  const correlatedAudit = { ...auditArg, operationId };
@@ -19135,11 +20277,12 @@ export class OpenCodeController {
19135
20277
  try {
19136
20278
  result = await operationArg(operationId);
19137
20279
  } catch (error) {
19138
- // A refused workspace path is a policy decision, recorded as one.
19139
- const outcome = error instanceof AuthError
20280
+ // A refused workspace path is a policy decision, recorded as one; a direct report that took no message is a failure.
20281
+ const outcome = (error instanceof AuthError
19140
20282
  || error instanceof plugins.typedrequest.TypedResponseError
19141
20283
  || error instanceof ControllerWorkspaceError
19142
- || error instanceof ConfigurationError
20284
+ || error instanceof ConfigurationError)
20285
+ && !(error instanceof plugins.typedrequest.TypedResponseError && error.errorData?.code === 'direct_report_failed')
19143
20286
  ? 'denied'
19144
20287
  : 'failed';
19145
20288
  const suppressUnboundedDenialAudit = error instanceof AuthError
@@ -19170,7 +20313,7 @@ export class OpenCodeController {
19170
20313
  try {
19171
20314
  await this.requireAuthStore().recordAuditEvent({
19172
20315
  ...correlatedAudit,
19173
- outcome: 'succeeded',
20316
+ outcome: outcomeOfArg(result),
19174
20317
  });
19175
20318
  } catch {
19176
20319
  // The durable attempted record preserves the audit gap. The completed
@@ -20161,6 +21304,7 @@ export class OpenCodeController {
20161
21304
  reading,
20162
21305
  account.maxUsagePercent,
20163
21306
  account.lapsesAt,
21307
+ account.renewsAt,
20164
21308
  now,
20165
21309
  account.reserveLiftUntil,
20166
21310
  );
@@ -23394,6 +24538,80 @@ export class OpenCodeController {
23394
24538
  });
23395
24539
  }
23396
24540
 
24541
+ /**
24542
+ * The requests that wait in a managed OpenCode root conversation and in its direct children, from the controller's
24543
+ * own reads (OpenCode's pending lists and the root's direct children), whichever browser has the conversation open:
24544
+ * the root's own requests, and each direct child with requests, the most recently updated first. `strictArg` lets a
24545
+ * failed pending list fail the read instead of reading as empty.
24546
+ */
24547
+ private async readOpenCodeFamilyAttention(
24548
+ projectIdArg: string,
24549
+ parentSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
24550
+ signalArg: AbortSignal,
24551
+ strictArg = false,
24552
+ ): Promise<{
24553
+ parent: IOpenCodeManagedSessionScopeAuthority;
24554
+ own: { permissions: IControllerPermission[]; questions: IControllerQuestion[] };
24555
+ children: Array<{ child: IOpenCodeDirectChildObservation; permissions: IControllerPermission[]; questions: IControllerQuestion[] }>;
24556
+ } | undefined> {
24557
+ const parent = await this.readManagedOpenCodeScopeAuthority(
24558
+ projectIdArg,
24559
+ parentSessionIdArg,
24560
+ signalArg,
24561
+ );
24562
+ if (parent.session.parentId !== undefined || parent.session.archivedAt !== undefined) return undefined;
24563
+ const signal = AbortSignal.any([signalArg, parent.runtimeAuthority.signal]);
24564
+ const permissionsRead = parent.client.listPermissions(parent.project.directory, undefined, signal);
24565
+ const questionsRead = parent.client.listQuestions(parent.project.directory, undefined, signal);
24566
+ const [children, pending] = await Promise.all([
24567
+ parent.client.listDirectChildSessionObservations(
24568
+ parent.project.directory,
24569
+ parentSessionIdArg.nativeId,
24570
+ signal,
24571
+ ),
24572
+ strictArg
24573
+ ? Promise.all([permissionsRead, questionsRead]).then(([permissions, questions]) => ({ permissions, questions }))
24574
+ : settleControllerAttentionLists(permissionsRead, questionsRead),
24575
+ ]);
24576
+ this.assertOpenCodeSessionIdentityGenerationCurrent(
24577
+ parent.supervisor,
24578
+ parent.client,
24579
+ parent.runtimeAuthority,
24580
+ );
24581
+ this.assertChildScopeParentAdmission(projectIdArg, parentSessionIdArg);
24582
+
24583
+ const permissionsBySession = new Map<string, IControllerPermission[]>();
24584
+ for (const permission of pending.permissions) {
24585
+ const key = controllerRuntimeIdKey(permission.sessionId);
24586
+ const entries = permissionsBySession.get(key) ?? [];
24587
+ entries.push(permission);
24588
+ permissionsBySession.set(key, entries);
24589
+ }
24590
+ const questionsBySession = new Map<string, IControllerQuestion[]>();
24591
+ for (const question of pending.questions) {
24592
+ const key = controllerRuntimeIdKey(question.sessionId);
24593
+ const entries = questionsBySession.get(key) ?? [];
24594
+ entries.push(question);
24595
+ questionsBySession.set(key, entries);
24596
+ }
24597
+ const parentKey = controllerRuntimeIdKey(parentSessionIdArg);
24598
+ return {
24599
+ parent,
24600
+ own: { permissions: permissionsBySession.get(parentKey) ?? [], questions: questionsBySession.get(parentKey) ?? [] },
24601
+ children: children
24602
+ .flatMap((childArg) => {
24603
+ const key = controllerRuntimeIdKey(childArg.session.id);
24604
+ const permissions = permissionsBySession.get(key) ?? [];
24605
+ const questions = questionsBySession.get(key) ?? [];
24606
+ return permissions.length > 0 || questions.length > 0 ? [{ child: childArg, permissions, questions }] : [];
24607
+ })
24608
+ .sort((leftArg, rightArg) => (
24609
+ rightArg.child.session.updatedAt - leftArg.child.session.updatedAt
24610
+ || leftArg.child.session.id.nativeId.localeCompare(rightArg.child.session.id.nativeId)
24611
+ )),
24612
+ };
24613
+ }
24614
+
23397
24615
  private async readBrowserChildAttention(
23398
24616
  peerArg: IControllerPeer,
23399
24617
  projectIdArg: string,
@@ -23401,62 +24619,13 @@ export class OpenCodeController {
23401
24619
  signalArg: AbortSignal,
23402
24620
  ): Promise<Pick<IReq_ControllerSessionGet['response'], 'childAttention' | 'childAttentionLimited'>> {
23403
24621
  try {
23404
- const parent = await this.readManagedOpenCodeScopeAuthority(
23405
- projectIdArg,
23406
- parentSessionIdArg,
23407
- signalArg,
23408
- );
23409
- if (parent.session.parentId !== undefined || parent.session.archivedAt !== undefined) return {};
23410
- const signal = AbortSignal.any([signalArg, parent.runtimeAuthority.signal]);
23411
- const [children, pending] = await Promise.all([
23412
- parent.client.listDirectChildSessionObservations(
23413
- parent.project.directory,
23414
- parentSessionIdArg.nativeId,
23415
- signal,
23416
- ),
23417
- settleControllerAttentionLists(
23418
- parent.client.listPermissions(parent.project.directory, undefined, signal),
23419
- parent.client.listQuestions(parent.project.directory, undefined, signal),
23420
- ),
23421
- ]);
23422
- this.assertOpenCodeSessionIdentityGenerationCurrent(
23423
- parent.supervisor,
23424
- parent.client,
23425
- parent.runtimeAuthority,
23426
- );
23427
- this.assertChildScopeParentAdmission(projectIdArg, parentSessionIdArg);
23428
-
23429
- const permissionsBySession = new Map<string, IControllerPermission[]>();
23430
- for (const permission of pending.permissions) {
23431
- const key = controllerRuntimeIdKey(permission.sessionId);
23432
- const entries = permissionsBySession.get(key) ?? [];
23433
- entries.push(permission);
23434
- permissionsBySession.set(key, entries);
23435
- }
23436
- const questionsBySession = new Map<string, IControllerQuestion[]>();
23437
- for (const question of pending.questions) {
23438
- const key = controllerRuntimeIdKey(question.sessionId);
23439
- const entries = questionsBySession.get(key) ?? [];
23440
- entries.push(question);
23441
- questionsBySession.set(key, entries);
23442
- }
23443
- const candidates = children
23444
- .filter((childArg) => {
23445
- const key = controllerRuntimeIdKey(childArg.session.id);
23446
- return (permissionsBySession.get(key)?.length ?? 0) > 0
23447
- || (questionsBySession.get(key)?.length ?? 0) > 0;
23448
- })
23449
- .sort((leftArg, rightArg) => (
23450
- rightArg.session.updatedAt - leftArg.session.updatedAt
23451
- || leftArg.session.id.nativeId.localeCompare(rightArg.session.id.nativeId)
23452
- ));
24622
+ const family = await this.readOpenCodeFamilyAttention(projectIdArg, parentSessionIdArg, signalArg);
24623
+ if (!family) return {};
24624
+ const candidates = family.children;
23453
24625
  let limited = candidates.length > maxChildAttentionChildren
23454
- || candidates.reduce((countArg, childArg) => {
23455
- const key = controllerRuntimeIdKey(childArg.session.id);
23456
- return countArg
23457
- + (permissionsBySession.get(key)?.length ?? 0)
23458
- + (questionsBySession.get(key)?.length ?? 0);
23459
- }, 0) > maxChildAttentionItems;
24626
+ || candidates.reduce((countArg, candidateArg) => (
24627
+ countArg + candidateArg.permissions.length + candidateArg.questions.length
24628
+ ), 0) > maxChildAttentionItems;
23460
24629
  const childAttention: IControllerChildAttention[] = [];
23461
24630
  let itemCount = 0;
23462
24631
  for (const candidate of candidates.slice(0, maxChildAttentionChildren)) {
@@ -23466,7 +24635,7 @@ export class OpenCodeController {
23466
24635
  detail = await this.openChildScope(peerArg, {
23467
24636
  projectId: projectIdArg,
23468
24637
  parentSessionId: parentSessionIdArg,
23469
- childSessionId: candidate.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
24638
+ childSessionId: candidate.child.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
23470
24639
  }, signalArg);
23471
24640
  } catch {
23472
24641
  signalArg.throwIfAborted();
@@ -35934,6 +37103,7 @@ export class OpenCodeController {
35934
37103
  private async pushControllerEvent(eventArg: IControllerEvent): Promise<void> {
35935
37104
  this.driverService?.observe(eventArg);
35936
37105
  this.sessionFeed?.observe(eventArg);
37106
+ this.inbox?.observe(eventArg);
35937
37107
  const browsers = this.controllerEventDeliveryQueues().push(eventArg);
35938
37108
  // A device receives an allowlist of events in its own reduced shape (`deviceEvent`), through queues of its own.
35939
37109
  if (this.devices?.hasLivePeers() === true && deviceRelayedEventTypes.has(eventArg.type)) {
@@ -35959,14 +37129,23 @@ export class OpenCodeController {
35959
37129
  ));
35960
37130
  return targets.map((targetArg) => ({
35961
37131
  peerId: targetArg.peer.id,
37132
+ // One queued controller event may be several device events: each is sent in order, as the queue sends its
37133
+ // events, every one attempted though one before it was not acknowledged; the first failure is the send's.
35962
37134
  send: async (eventArg: IControllerEvent) => {
35963
- const event = deviceEvent(eventArg, (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg));
35964
- if (event === undefined || devices.deviceIdOf(targetArg.peer) === undefined) return;
35965
- await typedSocket.createTypedRequest<IReq_DeviceEventPush>(
35966
- 'device.event',
35967
- targetArg,
35968
- { timeoutMs: 2_000 },
35969
- ).fire({ event }, { timeoutMs: 2_000, maxRetries: 0 });
37135
+ let failure: { error: unknown } | undefined;
37136
+ for (const event of deviceEvent(eventArg, (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg), this.driverService)) {
37137
+ if (devices.deviceIdOf(targetArg.peer) === undefined) break;
37138
+ try {
37139
+ await typedSocket.createTypedRequest<IReq_DeviceEventPush>(
37140
+ 'device.event',
37141
+ targetArg,
37142
+ { timeoutMs: 2_000 },
37143
+ ).fire({ event }, { timeoutMs: 2_000, maxRetries: 0 });
37144
+ } catch (errorArg) {
37145
+ failure ??= { error: errorArg };
37146
+ }
37147
+ }
37148
+ if (failure !== undefined) throw failure.error;
35970
37149
  },
35971
37150
  }));
35972
37151
  },