agl 43.2.0 → 43.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/changelog.md +29 -0
  2. package/dist_serve/bundle.js +2845 -2638
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +1 -1
  5. package/dist_serve/bundle.js.third-party-notices.txt +1 -1
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +197 -17
  8. package/dist_ts/classes.accountsactions.d.ts +3 -1
  9. package/dist_ts/classes.accountsactions.js +21 -3
  10. package/dist_ts/classes.authstore.d.ts +7 -0
  11. package/dist_ts/classes.authstore.js +9 -1
  12. package/dist_ts/classes.claudeharness.d.ts +29 -2
  13. package/dist_ts/classes.claudeharness.js +35 -6
  14. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  15. package/dist_ts/classes.codexclientadapter.js +14 -2
  16. package/dist_ts/classes.controller.d.ts +187 -12
  17. package/dist_ts/classes.controller.js +1208 -186
  18. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  19. package/dist_ts/classes.controllerdevices.js +6 -1
  20. package/dist_ts/classes.inbox.d.ts +72 -0
  21. package/dist_ts/classes.inbox.js +231 -0
  22. package/dist_ts/classes.inferencerouter.d.ts +10 -0
  23. package/dist_ts/classes.inferencerouter.js +5 -3
  24. package/dist_ts/classes.inferenceservice.js +2 -2
  25. package/dist_ts/classes.mcpclient.d.ts +1 -1
  26. package/dist_ts/classes.mcpclient.js +24 -6
  27. package/dist_ts/classes.mcpcontrollerhost.js +6 -1
  28. package/dist_ts/classes.mcptools.js +18 -8
  29. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  30. package/dist_ts/classes.mcpvalidation.js +32 -2
  31. package/dist_ts/classes.nativesessions.d.ts +29 -4
  32. package/dist_ts/classes.nativesessions.js +41 -9
  33. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  34. package/dist_ts/classes.opencodeclient.js +47 -3
  35. package/dist_ts/classes.publishedset.d.ts +38 -0
  36. package/dist_ts/classes.publishedset.js +50 -0
  37. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  38. package/dist_ts/classes.sessionfeed.js +18 -26
  39. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  40. package/dist_ts/classes.systemmetricssampler.js +15 -3
  41. package/dist_ts/classes.ticketstore.d.ts +50 -3
  42. package/dist_ts/classes.ticketstore.js +45 -8
  43. package/dist_ts/classes.workercallers.js +4 -2
  44. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  45. package/dist_ts/driver/classes.directreports.js +42 -23
  46. package/dist_ts/driver/classes.directreportstore.d.ts +8 -1
  47. package/dist_ts/driver/classes.directreportstore.js +20 -10
  48. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  49. package/dist_ts/driver/classes.driverservice.js +50 -16
  50. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  51. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  52. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  53. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  54. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  55. package/dist_ts/fleet/classes.workercommand.js +15 -4
  56. package/dist_ts/fleet/classes.workers.d.ts +21 -1
  57. package/dist_ts/fleet/classes.workers.js +80 -40
  58. package/dist_ts/fleet/classes.workerstore.js +14 -8
  59. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  60. package/dist_ts/fleet/functions.workervalidation.js +11 -4
  61. package/dist_ts/fleet/interfaces.workers.d.ts +27 -5
  62. package/dist_ts/fleet/interfaces.workers.js +8 -4
  63. package/dist_ts/functions.agentmessage.d.ts +3 -0
  64. package/dist_ts/functions.agentmessage.js +4 -1
  65. package/dist_ts/functions.deviceapi.d.ts +198 -4
  66. package/dist_ts/functions.deviceapi.js +1060 -38
  67. package/dist_ts/functions.exactpersistence.d.ts +3 -0
  68. package/dist_ts/functions.exactpersistence.js +4 -0
  69. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  70. package/dist_ts/functions.fleetworkercli.js +11 -8
  71. package/dist_ts/functions.inferencecli.js +3 -1
  72. package/dist_ts/functions.mcpfleetworkertools.js +3 -3
  73. package/dist_ts/functions.ticketactor.d.ts +17 -1
  74. package/dist_ts/functions.ticketactor.js +55 -15
  75. package/dist_ts/functions.ticketvalidation.js +11 -2
  76. package/dist_ts/interfaces.auth.d.ts +1 -1
  77. package/dist_ts/interfaces.auth.js +9 -1
  78. package/dist_ts/plugins.d.ts +3 -1
  79. package/dist_ts/plugins.js +7 -2
  80. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  81. package/dist_ts_authswitch/authority-contract.js +1 -1
  82. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  83. package/dist_ts_authswitch/authority-overview.js +17 -6
  84. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  85. package/dist_ts_authswitch/authority-placement.js +17 -10
  86. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  87. package/dist_ts_authswitch/authority-renewal.js +56 -0
  88. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  89. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  90. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  91. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  92. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  93. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  94. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  95. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  96. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  97. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  98. package/dist_ts_interfaces/devices.d.ts +1027 -7
  99. package/dist_ts_interfaces/devices.js +68 -2
  100. package/dist_ts_interfaces/fleetworkers.d.ts +37 -10
  101. package/dist_ts_interfaces/fleetworkers.js +19 -8
  102. package/dist_ts_interfaces/inbox.d.ts +234 -0
  103. package/dist_ts_interfaces/inbox.js +101 -0
  104. package/dist_ts_interfaces/index.d.ts +1 -0
  105. package/dist_ts_interfaces/index.js +2 -1
  106. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  107. package/dist_ts_interfaces/interfaces.js +4 -2
  108. package/dist_ts_interfaces/mcprequests.d.ts +34 -4
  109. package/dist_ts_interfaces/mcprequests.js +11 -1
  110. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  111. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  112. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  113. package/dist_ts_interfaces/plugins.d.ts +2 -1
  114. package/dist_ts_interfaces/plugins.js +4 -2
  115. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  116. package/dist_ts_interfaces/requests.accounts.js +3 -1
  117. package/dist_ts_interfaces/requests.d.ts +3 -2
  118. package/dist_ts_interfaces/requests.js +1 -1
  119. package/dist_ts_interfaces/workercallers.d.ts +2 -0
  120. package/dist_ts_migration/classes.documentmigrationrunner.d.ts +14 -0
  121. package/dist_ts_migration/classes.documentmigrationrunner.js +20 -1
  122. package/dist_ts_migration/index.d.ts +1 -0
  123. package/dist_ts_migration/index.js +2 -1
  124. package/dist_ts_migration/v43_ticketactornames.d.ts +32 -0
  125. package/dist_ts_migration/v43_ticketactornames.js +236 -0
  126. package/docs/authswitch.md +20 -1
  127. package/package.json +3 -3
  128. package/readme.md +144 -27
  129. package/ts/00_commitinfo_data.ts +1 -1
  130. package/ts/aglapi/aglapisurface.document.ts +196 -16
  131. package/ts/classes.accountsactions.ts +30 -3
  132. package/ts/classes.authstore.ts +10 -0
  133. package/ts/classes.claudeharness.ts +45 -5
  134. package/ts/classes.codexclientadapter.ts +14 -1
  135. package/ts/classes.controller.ts +1412 -262
  136. package/ts/classes.controllerdevices.ts +6 -0
  137. package/ts/classes.inbox.ts +239 -0
  138. package/ts/classes.inferencerouter.ts +15 -2
  139. package/ts/classes.inferenceservice.ts +1 -1
  140. package/ts/classes.mcpclient.ts +24 -3
  141. package/ts/classes.mcpcontrollerhost.ts +5 -0
  142. package/ts/classes.mcptools.ts +17 -7
  143. package/ts/classes.mcpvalidation.ts +27 -1
  144. package/ts/classes.nativesessions.ts +63 -12
  145. package/ts/classes.opencodeclient.ts +55 -4
  146. package/ts/classes.publishedset.ts +56 -0
  147. package/ts/classes.sessionfeed.ts +17 -20
  148. package/ts/classes.systemmetricssampler.ts +13 -2
  149. package/ts/classes.ticketstore.ts +73 -12
  150. package/ts/classes.workercallers.ts +3 -1
  151. package/ts/driver/classes.directreports.ts +42 -23
  152. package/ts/driver/classes.directreportstore.ts +20 -9
  153. package/ts/driver/classes.driverservice.ts +75 -14
  154. package/ts/fleet/classes.claudeworkers.ts +112 -39
  155. package/ts/fleet/classes.codexworkers.ts +21 -6
  156. package/ts/fleet/classes.workercommand.ts +14 -4
  157. package/ts/fleet/classes.workers.ts +75 -41
  158. package/ts/fleet/classes.workerstore.ts +11 -7
  159. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  160. package/ts/fleet/functions.workervalidation.ts +8 -3
  161. package/ts/fleet/interfaces.workers.ts +26 -7
  162. package/ts/functions.agentmessage.ts +3 -0
  163. package/ts/functions.deviceapi.ts +1292 -34
  164. package/ts/functions.exactpersistence.ts +5 -0
  165. package/ts/functions.fleetworkercli.ts +10 -7
  166. package/ts/functions.inferencecli.ts +2 -0
  167. package/ts/functions.mcpfleetworkertools.ts +2 -2
  168. package/ts/functions.ticketactor.ts +58 -14
  169. package/ts/functions.ticketvalidation.ts +11 -1
  170. package/ts/interfaces.auth.ts +8 -0
  171. package/ts/plugins.ts +7 -0
  172. package/ts_authswitch/authority-contract.ts +20 -0
  173. package/ts_authswitch/authority-overview.ts +28 -6
  174. package/ts_authswitch/authority-placement.ts +25 -17
  175. package/ts_authswitch/authority-renewal.ts +64 -0
  176. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  177. package/ts_authswitch/classes.authoritycli.ts +49 -2
  178. package/ts_authswitch/classes.authorityclient.ts +14 -4
  179. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  180. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  181. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  182. package/ts_authswitch/native-contracts.md +21 -0
  183. package/ts_authswitch/readme.md +1 -1
  184. package/ts_interfaces/devices.schema.json +3576 -603
  185. package/ts_interfaces/devices.ts +1111 -6
  186. package/ts_interfaces/fleetworkers.ts +38 -10
  187. package/ts_interfaces/inbox.ts +287 -0
  188. package/ts_interfaces/index.ts +1 -0
  189. package/ts_interfaces/interfaces.ts +9 -2
  190. package/ts_interfaces/mcprequests.ts +43 -4
  191. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  192. package/ts_interfaces/nativesessions.ts +17 -3
  193. package/ts_interfaces/plugins.ts +3 -1
  194. package/ts_interfaces/requests.accounts.ts +20 -0
  195. package/ts_interfaces/requests.ts +4 -0
  196. package/ts_interfaces/workercallers.ts +2 -0
  197. package/ts_migration/classes.documentmigrationrunner.ts +21 -0
  198. package/ts_migration/index.ts +1 -0
  199. package/ts_migration/v43_ticketactornames.ts +225 -0
  200. package/ts_web/00_commitinfo_data.ts +1 -1
  201. package/ts_web/accounts.plugins.ts +4 -2
  202. package/ts_web/classes.accountsreadmodel.ts +33 -0
  203. package/ts_web/classes.browserpresentation.ts +10 -5
  204. package/ts_web/classes.inboxfeed.ts +329 -0
  205. package/ts_web/classes.nativesessionstate.ts +9 -23
  206. package/ts_web/elements.accounts.ts +81 -0
  207. package/ts_web/elements.deployments.ts +66 -2
  208. package/ts_web/elements.fleetworker.ts +4 -2
  209. package/ts_web/elements.harnesscontrollerapp.ts +107 -37
  210. package/ts_web/elements.inbox.ts +808 -0
  211. package/ts_web/functions.inbox.ts +95 -0
  212. package/ts_web/functions.sessioncards.ts +40 -0
  213. package/ts_web/plugins.ts +2 -0
@@ -2,7 +2,8 @@ import { flexMessageDeliveryProof, type TFlexDeliveryEvidence, type TFlexDeliver
2
2
  import { FleetWorkers, fleetNativeSessionNames } from './fleet/classes.workers.js';
3
3
  import { FleetTicketEffects } from './fleet/classes.ticketeffects.js';
4
4
  import { FleetDispatchError, FleetWorkerError } from './fleet/interfaces.workers.js';
5
- import type { TFleetWorkerAction, TFleetWorkerRequest } from '../ts_interfaces/fleetworkers.js';
5
+ import { DirectReportError } from './driver/classes.directreportstore.js';
6
+ import type { IFleetWorkerJob, TFleetWorkerAction, TFleetWorkerRequest } from '../ts_interfaces/fleetworkers.js';
6
7
  import { ControllerBrowserOperationAuthority } from './classes.browseroperationauthority.js';
7
8
  import { ControllerWorkerCallers, type IWorkerCodexCallerOrigin } from './classes.workercallers.js';
8
9
  import { WorkerCallerBindingStore } from './classes.workercallerbindings.js';
@@ -109,7 +110,38 @@ import {
109
110
  deviceRelayedEventTypes,
110
111
  deviceSessionRow,
111
112
  deviceSessionRows,
113
+ deviceInboxList,
114
+ deviceTicketQuestion,
115
+ deviceDriverStatus,
116
+ deviceDirectReport,
117
+ assertDeviceTicketAnswerRequest,
118
+ assertDeviceDriverReadRequest,
119
+ assertDeviceDriverSendRequest,
120
+ assertDeviceDirectReportMessageRequest,
121
+ serveDeviceDriver,
122
+ deviceDirectReportJobRefusal,
123
+ deviceDirectReportMessageRefusal,
124
+ deviceHostAgl,
125
+ deviceHostDevice,
126
+ readDeviceHostSections,
127
+ assertDeviceBoardListRequest,
128
+ assertDeviceTicketGetRequest,
129
+ assertDeviceTicketCommentRequest,
130
+ assertDeviceTicketAskRequest,
131
+ assertDeviceTicketMoveRequest,
132
+ deviceBoardPage,
133
+ deviceTicket,
134
+ deviceTicketCard,
135
+ deviceTicketComment,
136
+ deviceTicketDiscussion,
137
+ deviceTicketPlans,
138
+ deviceTicketRefusal,
139
+ deviceContractError,
140
+ readDeviceTicketPlacement,
141
+ type IDeviceTicketViewer,
112
142
  } from './functions.deviceapi.js';
143
+ import { ControllerInbox, inboxTitle, type TInboxSource } from './classes.inbox.js';
144
+ import { compareFleetVersions } from '../ts_interfaces/functions.fleetversion.js';
113
145
  import {
114
146
  controllerPackageName,
115
147
  controllerBuiltinCommands,
@@ -348,6 +380,10 @@ import {
348
380
  type IReq_ControllerSystemMetricsHistory,
349
381
  type IReq_ControllerMcpProjectsList,
350
382
  type IReq_ControllerMcpSessionRead,
383
+ type IControllerMcpNativeSessionDetail,
384
+ type TControllerMcpSessionDetail,
385
+ controllerMcpNativeDeliveries,
386
+ controllerMcpNativeSessionSettledLimit,
351
387
  type IReq_ControllerMcpSessionScratchpadRead,
352
388
  type IReq_ControllerMcpSessionScratchpadUpdate,
353
389
  type IReq_ControllerMcpSessionSend,
@@ -374,7 +410,29 @@ import {
374
410
  type IReq_DeviceSessionRead,
375
411
  type IReq_DeviceSessionSend,
376
412
  type IReq_DeviceSessionsList,
413
+ type IReq_DeviceInboxList,
414
+ type IReq_DeviceTicketAnswer,
415
+ type IReq_DeviceDriverGet,
416
+ type IReq_DeviceDriverSeen,
417
+ type IReq_DeviceDriverRead,
418
+ type IReq_DeviceDriverSend,
419
+ type IReq_DeviceDirectReportsList,
420
+ type IReq_DeviceDirectReportMessage,
421
+ type IReq_DeviceHostGet,
422
+ type IReq_DeviceBoardList,
423
+ type IReq_DeviceTicketGet,
424
+ type IReq_DeviceTicketComment,
425
+ type IReq_DeviceTicketAsk,
426
+ type IReq_DeviceTicketMove,
377
427
  type IControllerSessionFeedRow,
428
+ type IReq_ControllerInboxList,
429
+ type TControllerInboxAnswer,
430
+ type TControllerElicitation,
431
+ type TControllerInboxItem,
432
+ type TControllerInboxWhere,
433
+ type TControllerSessionFeedHarness,
434
+ type IFleetDeployStatus,
435
+ controllerInboxLimits,
378
436
  deviceProtocolVersion,
379
437
  deviceRevokedCloseCode,
380
438
  type IControllerProviderAccountRateLimits,
@@ -520,16 +578,17 @@ import { FleetService } from './fleet/classes.service.js';
520
578
  import type { IFleetConfiguration, IFleetDriverConfiguration, IFleetOperation, IFleetScope, IFleetUnboundDriver, TFleetOperation, TFleetRequest } from '../ts_interfaces/fleet.js';
521
579
  import { findFleetRepository, fleetRepositorySlug } from './fleet/functions.releasefacts.js';
522
580
  import { discoverFleetRepositories } from './fleet/functions.discovery.js';
523
- import { DriverError, DriverService } from './driver/classes.driverservice.js';
581
+ import { DriverError, DriverService, type IDriverAssistantMessage } from './driver/classes.driverservice.js';
524
582
  import { DriverEventRelay, driverRelayMaximumMessageBytes } from './driver/classes.drivereventrelay.js';
525
- import { DirectReports, type TDirectReportChannel } from './driver/classes.directreports.js';
583
+ import { DirectReports, directReportRuntimeId, type TDirectReportChannel } from './driver/classes.directreports.js';
526
584
  import { driverToolsByName, driverDirectReportReadDefaultLimit, type TDriverDirectReportOperation } from './driver/functions.drivertools.js';
527
- import { controllerDriverErrorCodes } from '../ts_interfaces/driver.js';
585
+ import { controllerDriverErrorCodes, type IControllerDriverStatus } from '../ts_interfaces/driver.js';
528
586
  import type { IReq_ControllerDriverEnsure, IReq_ControllerDriverGet, IReq_ControllerDriverSeen } from '../ts_interfaces/requests.driver.js';
529
587
  import type { IReq_ControllerFleetWorkerList, IReq_ControllerFleetWorkerRead, IReq_ControllerFleetWorkerSteer } from '../ts_interfaces/requests.fleetworkers.js';
530
588
  import type {
531
589
  IControllerNativeSession,
532
590
  IControllerNativeSessionRef,
591
+ TControllerNativeJobDelivery,
533
592
  IReq_ControllerNativeSessionAuxiliaryGet,
534
593
  IReq_ControllerNativeSessionIntelligenceAsk,
535
594
  IReq_ControllerNativeSessionPermissionReply,
@@ -541,19 +600,19 @@ import type {
541
600
  } from '../ts_interfaces/nativesessions.js';
542
601
  import { ControllerUploadManager, type IControllerUploadHandle } from './classes.uploadmanager.js';
543
602
  import type { IReq_ControllerDirectReportAdopt, IReq_ControllerDirectReportAppoint, IReq_ControllerDirectReportList, IReq_ControllerDirectReportMessage, IReq_ControllerDirectReportPreflight, IReq_ControllerDirectReportRead, IReq_ControllerDirectReportRetire, TDirectReportPage } from '../ts_interfaces/requests.directreports.js';
544
- import { SessionFeed, SessionFeedAcknowledgementError, SessionFeedTranscripts, type ISessionFeedTerminal, type TSessionFeedProjectRead } from './classes.sessionfeed.js';
603
+ import { SessionFeed, SessionFeedAcknowledgementError, SessionFeedTranscripts, sessionFeedRowId, type ISessionFeedTerminal, type TSessionFeedProjectRead } from './classes.sessionfeed.js';
545
604
  import { SessionFeedAcknowledgementStore } from './classes.sessionfeedacknowledgements.js';
546
605
  import { HarnessReleaseNotices, type THarnessReleaseSource } from './classes.harnessreleases.js';
547
606
  import { assertSessionFeedAcknowledgeRequest } from './functions.sessionfeedvalidation.js';
548
- import { NativeSessions, type IResolvedNativeSession } from './classes.nativesessions.js';
607
+ import { NativeSessions, nativeSessionReadOnlyMessages, type INativeSessionFailedErrorData, type IResolvedNativeSession } from './classes.nativesessions.js';
549
608
  import { claudeProfileForHome, fleetAdoptCommand, listUnboundDrivers } from './fleet/functions.unbounddrivers.js';
550
609
  import type { IReq_ControllerSessionFeedAcknowledge, IReq_ControllerSessionFeedList } from '../ts_interfaces/sessionfeed.js';
551
610
  import { UsageFeed, UsageFeedRefusal } from './classes.usagefeed.js';
552
611
  import type { IReq_ControllerUsageUnwatch, IReq_ControllerUsageWatch, TControllerUsageDelta } from '../ts_interfaces/metrics.js';
553
- import { ticketActorFromCaller } from './functions.ticketactor.js';
612
+ import { ticketActorFromCaller, ticketCallerSessionId } from './functions.ticketactor.js';
554
613
  import { ticketOwnerActor, ticketOwnerPrincipalId, resolveTicketOwnerAssignment } from './functions.ticketowner.js';
555
- import { ticketInputSchemas } from './functions.ticketvalidation.js';
556
- import { readTicketRevisionConflict, type ITicket, type ITicketActor, type TTicketOperation, type TTicketRequest, type TTicketFleetEvent, type ITicketFleetEventResult } from '../ts_interfaces/tickets.js';
614
+ import { assertTicketRequest, ticketInputSchemas } from './functions.ticketvalidation.js';
615
+ 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';
557
616
  import type { TControllerTicketRequest } from '../ts_interfaces/requests.tickets.js';
558
617
  import { ControllerJobSupervisor } from './classes.jobsupervisor.js';
559
618
  import {
@@ -2434,6 +2493,23 @@ const assertNativeSessionWritable = (resolvedArg: IResolvedNativeSession): void
2434
2493
  const { readOnly } = resolvedArg.session;
2435
2494
  if (readOnly) throw new plugins.typedrequest.TypedResponseError(readOnly.message, { code: 'session_read_only' });
2436
2495
  };
2496
+ /**
2497
+ * A Claude Code session outside AGL as an MCP caller sees it: agents reach only background jobs, so any other session
2498
+ * that would take the owner's message is read-only for them (`notBackgroundJob`).
2499
+ */
2500
+ const mcpNativeSession = (resolvedArg: IResolvedNativeSession): IControllerNativeSession => (
2501
+ resolvedArg.claudeJob || resolvedArg.session.readOnly ? resolvedArg.session
2502
+ : { ...resolvedArg.session, readOnly: { reason: 'notBackgroundJob', message: nativeSessionReadOnlyMessages.notBackgroundJob } }
2503
+ );
2504
+ /** Refuses an MCP agent message to a Claude Code session outside AGL that takes none now, naming why. */
2505
+ const assertMcpNativeMessageable = (sessionArg: IControllerNativeSession): void => {
2506
+ if (sessionArg.readOnly) throw new plugins.typedrequest.TypedResponseError(sessionArg.readOnly.message, { code: 'session_read_only' });
2507
+ if (!sessionArg.jobDelivery) throw new plugins.typedrequest.TypedResponseError(nativeSessionReadOnlyMessages.notBackgroundJob, { code: 'session_read_only' });
2508
+ };
2509
+ /** The canonical path of an existing directory, or `undefined`; a session's directory matches a project's only so. */
2510
+ const canonicalDirectory = async (pathArg: string): Promise<string | undefined> => {
2511
+ try { return await plugins.fs.promises.realpath(pathArg); } catch { return undefined; }
2512
+ };
2437
2513
  /**
2438
2514
  * A harness's refusal of an elicitation reply -- the answer does not fit the request, or the request is gone -- as the
2439
2515
  * typed refusal it is; its text never carries what the owner entered. Every other error passes as it is.
@@ -2444,6 +2520,14 @@ const elicitationRefusal = (errorArg: unknown): unknown => (
2444
2520
  : errorArg
2445
2521
  );
2446
2522
 
2523
+ /** The ticket changes the owner makes from the browser's board or a paired device, each with its audit type. */
2524
+ type TTicketChangeOperation = 'comment' | 'ask' | 'move';
2525
+ const ticketChangeAuditTypes = {
2526
+ comment: 'ticket.comment',
2527
+ ask: 'ticket.ask',
2528
+ move: 'ticket.move',
2529
+ } as const satisfies Record<TTicketChangeOperation, TControllerAuditEventType>;
2530
+
2447
2531
  const validateRequest = <T>(validatorArg: () => T): T => {
2448
2532
  try {
2449
2533
  return validatorArg();
@@ -2934,6 +3018,70 @@ const asTypedResponseError = (
2934
3018
  });
2935
3019
  };
2936
3020
 
3021
+ /**
3022
+ * The device error translation of both device scopes: a failure as `asTypedResponseError` reduces it, in the device
3023
+ * contract (`deviceContractError`), so no device method ever answers a code outside `TDeviceRefusalCode`.
3024
+ */
3025
+ const asDeviceResponseError = (
3026
+ errorArg: unknown,
3027
+ methodArg: string,
3028
+ ): plugins.typedrequest.TypedResponseError => deviceContractError(asTypedResponseError(errorArg, methodArg), errorArg, methodArg);
3029
+
3030
+ /**
3031
+ * A direct report operation's failure as the Driver view and a device receive it, decided by the error's class, never
3032
+ * its text: the refusals AGL writes itself keep their message as `direct_report_failed` (`DirectReportError`, the
3033
+ * direct reports' and their store's own, `FleetWorkerError` and `FleetNativeTurnError`, the fleet's), with a failure
3034
+ * journal reference where they stand for a dependency's error (`cause`); every other error, whose message may be a
3035
+ * dependency's (a spawn error, a socket path, a fleet job's recorded failure), is the controller's one generic failure,
3036
+ * `controller_operation_failed`, whose response carries the reference under which the failure journal keeps the cause
3037
+ * and which a device receives as its own (`deviceDirectReportMessageRefusal`, `deviceContractError`).
3038
+ */
3039
+ const directReportFailure = (errorArg: Error, operationArg: string): plugins.typedrequest.TypedResponseError => {
3040
+ if (errorArg instanceof DirectReportError || errorArg instanceof FleetWorkerError || errorArg instanceof FleetNativeTurnError) {
3041
+ const reference = errorArg.cause === undefined ? undefined : controllerFailureJournal.record({ operation: operationArg, cause: errorArg.cause });
3042
+ return new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), {
3043
+ code: 'direct_report_failed', ...(reference === undefined ? {} : { reference }),
3044
+ });
3045
+ }
3046
+ const reference = controllerFailureJournal.record({ operation: operationArg, cause: errorArg });
3047
+ console.error(`${currentRuntimeName} direct report operation failed (${operationArg}, ref ${reference}):`, errorArg);
3048
+ return new plugins.typedrequest.TypedResponseError('The controller operation failed.', { code: controllerOperationFailedErrorCode, reference });
3049
+ };
3050
+
3051
+ /**
3052
+ * A direct report message's settled fleet job as the Driver view receives it, by the same rule: a failure the fleet
3053
+ * refused itself (`errorCode`) keeps its text; any other job error, which may be a dependency's output (a harness's
3054
+ * own text, a failed delivery), reads "The controller operation failed." with the failure journal's reference, under
3055
+ * which the journal keeps it. The job's `errorOutcome` stays: the Driver view shows a failure that may have delivered
3056
+ * the message as of unknown outcome, never as a message the report did not take. A device's view of the job is
3057
+ * `deviceDirectReportJobRefusal`'s.
3058
+ */
3059
+ const directReportJobView = (jobArg: IFleetWorkerJob): IFleetWorkerJob => {
3060
+ if (jobArg.state !== 'failed' || jobArg.errorCode !== undefined) return jobArg;
3061
+ const cause = jobArg.error ?? 'The fleet job failed without an error.';
3062
+ const reference = controllerFailureJournal.record({ operation: 'directreport.message', cause });
3063
+ console.error(`${currentRuntimeName} direct report message failed in fleet job ${jobArg.id} (ref ${reference}):`, cause);
3064
+ return { ...jobArg, error: `The controller operation failed. (ref ${reference})` };
3065
+ };
3066
+
3067
+ /** The refusals of a native message's session, every one before its send: no such session, more than one, one it may not wake. */
3068
+ const fleetNativeMessageRefusals: ReadonlySet<string> = new Set(['session_not_found', 'ambiguous_session', 'session_read_only']);
3069
+
3070
+ /**
3071
+ * A failed fleet `native-message` in the fleet's terms, so its job's outcome says whether the message may have arrived
3072
+ * (`IFleetWorkerJob.errorOutcome`): a refusal that proves nothing reached the job, one of the send's own refusals of the
3073
+ * session (`fleetNativeMessageRefusals`, before the send and again under the session's lock) or a native send failure
3074
+ * that says `refused`, is a `FleetDispatchError` that sent nothing, with the same message; any other failure stays as
3075
+ * it is, an unknown outcome.
3076
+ */
3077
+ export const fleetNativeMessageFailure = (errorArg: unknown): unknown => {
3078
+ if (!(errorArg instanceof plugins.typedrequest.TypedResponseError)) return errorArg;
3079
+ const errorData = errorArg.errorData as Readonly<Record<string, unknown>> | undefined;
3080
+ const refused = typeof errorData?.code === 'string' && fleetNativeMessageRefusals.has(errorData.code)
3081
+ || errorData?.code === 'native_session_failed' && errorData.outcome === ('refused' satisfies INativeSessionFailedErrorData['outcome']);
3082
+ return refused ? new FleetDispatchError(errorArg.message, false, { cause: errorArg }) : errorArg;
3083
+ };
3084
+
2937
3085
  const hashResumeToken = (tokenArg: string): string =>
2938
3086
  plugins.crypto.createHash('sha256').update(tokenArg, 'utf8').digest('base64url');
2939
3087
 
@@ -3229,8 +3377,10 @@ export class OpenCodeController {
3229
3377
  this.fleetWorkerLaunches = new FleetWorkerLaunches({ hooks: () => this.workerCallerHooks, overlays: resolveAGLHomePaths().fleetMcpConfigs });
3230
3378
  }
3231
3379
  this.fleetWorkers = new FleetWorkers({ sample: () => this.systemMetricsSampler.sample(), ticketEffects: this.requireFleetTicketEffects(), sessionBindings: directReports,
3232
- nativeMessages: { send: (_owner, request, actor) => this.sendFleetNativeMessage(request, actor) },
3380
+ nativeMessages: { send: (_owner, request, actor) => this.sendFleetNativeMessage(request, actor).catch((errorArg: unknown) => { throw fleetNativeMessageFailure(errorArg); }) },
3233
3381
  claudeReleases: (releaseArg) => this.observeClaudeRelease(releaseArg, 'fleet'),
3382
+ // No controller event names a native thread; the Inbox reads the fleet connection's requests again.
3383
+ onNativeCodexAttention: () => this.inbox?.nativeAttentionChanged('codex'),
3234
3384
  ...(this.fleetWorkerLaunches ? { callers: this.fleetWorkerLaunches } : {}) });
3235
3385
  // The Driver view's direct reports, an open fleet worker and the session feed follow worker changes and newly observed statuses.
3236
3386
  this.fleetWorkers.watchViews(() => {
@@ -3259,9 +3409,14 @@ export class OpenCodeController {
3259
3409
  // The Driver view's owner relaunches unless a driver tool names its driver.
3260
3410
  const { job } = await fleetWorkers.execute('adopt', request, configuration, owner, signal, actor ?? ticketOwnerActor(await this.requireAuthStore().getState()));
3261
3411
  const settled = await fleetWorkers.settled(owner, job.id, signal);
3262
- if (settled.state !== 'succeeded') throw new Error(settled.error ?? 'The relaunch failed.');
3412
+ // A refusal the fleet wrote itself keeps its text; any other error may be a dependency's output, so it is the
3413
+ // cause the failure journal keeps (`directReportFailure`).
3414
+ if (settled.state !== 'succeeded') {
3415
+ if (settled.errorCode !== undefined) throw new FleetWorkerError(settled.errorCode, settled.error ?? 'The relaunch failed.');
3416
+ throw new Error(settled.error ?? 'The relaunch failed.');
3417
+ }
3263
3418
  const worker = (await fleetWorkers.views(owner)).find((view) => view.worker.name === request.name)?.worker;
3264
- if (!worker?.nativeId) throw new Error('The relaunched fleet worker is unavailable.');
3419
+ if (!worker?.nativeId) throw new DirectReportError('The relaunched fleet worker is unavailable.');
3265
3420
  return worker;
3266
3421
  },
3267
3422
  nativeSession: async (ref) => await this.nativeSessions.resolve(ref),
@@ -3422,6 +3577,314 @@ export class OpenCodeController {
3422
3577
  });
3423
3578
  this.sessionFeed.start();
3424
3579
  }
3580
+ /** What waits for the owner, for the browser and devices alike (AGL-1635). */
3581
+ private inbox?: ControllerInbox;
3582
+ private startInbox(): void {
3583
+ if (this.inbox) return;
3584
+ this.inbox = new ControllerInbox({
3585
+ read: (sourceArg, previousArg, signalArg) => this.readInboxSource(sourceArg, previousArg, signalArg),
3586
+ hasViewers: async () => this.devices?.hasLivePeers() === true || (await this.controllerEventViewers()).length > 0,
3587
+ publish: (deltaArg) => {
3588
+ void this.pushControllerEvent({ type: 'inbox.changed', inbox: deltaArg, timestamp: Date.now() }).catch(() => undefined);
3589
+ },
3590
+ reportError: (messageArg, errorArg) => console.error(messageArg, errorArg),
3591
+ });
3592
+ }
3593
+
3594
+ /** The Inbox's items of one source, each read from the component that owns them. */
3595
+ private async readInboxSource(
3596
+ sourceArg: TInboxSource,
3597
+ previousArg: readonly TControllerInboxItem[],
3598
+ signalArg: AbortSignal,
3599
+ ): Promise<TControllerInboxItem[]> {
3600
+ switch (sourceArg) {
3601
+ case 'claude': return this.readInboxClaude();
3602
+ case 'codex': return this.readInboxCodex();
3603
+ case 'opencode': return this.readInboxOpenCode(previousArg, signalArg);
3604
+ case 'flex': return this.readInboxFlex(previousArg, signalArg);
3605
+ case 'native_waits': return this.readInboxNativeWaits();
3606
+ case 'driver': return this.readInboxDriver();
3607
+ case 'tickets': return this.readInboxTickets(signalArg);
3608
+ }
3609
+ }
3610
+
3611
+ /** The session feed's row of a session, and the name the Inbox shows for it. */
3612
+ private inboxRow(harnessArg: TControllerSessionFeedHarness, nativeIdArg: string, fallbackNameArg: string): { rowId: string; name: string } {
3613
+ const rowId = sessionFeedRowId(harnessArg, nativeIdArg);
3614
+ return { rowId, name: this.sessionFeed?.publishedRow(rowId)?.name ?? (fallbackNameArg.trim() || 'Untitled session') };
3615
+ }
3616
+
3617
+ /**
3618
+ * The items of a session's requests. A permission that the owner's auto-accept answers (`autoAcceptedArg`) waits for
3619
+ * nobody and is left out; questions and MCP forms are never answered automatically.
3620
+ */
3621
+ private inboxSessionItems(
3622
+ whereArg: Extract<TControllerInboxWhere, { kind: 'conversation' | 'child' | 'native' | 'driver' }>,
3623
+ answerArg: TControllerInboxAnswer,
3624
+ attentionArg: { permissions: readonly IControllerPermission[]; questions: readonly IControllerQuestion[]; elicitations?: readonly TControllerElicitation[] },
3625
+ autoAcceptedArg = false,
3626
+ ): TControllerInboxItem[] {
3627
+ const id = (kindArg: string, requestArg: { id: IControllerRuntimeId }, sessionArg: IControllerRuntimeId) => (
3628
+ `${kindArg}:${sessionArg.harnessId}:${sessionArg.nativeId}:${requestArg.id.nativeId}`
3629
+ );
3630
+ return [
3631
+ ...(autoAcceptedArg ? [] : attentionArg.permissions).map((permissionArg): TControllerInboxItem => ({
3632
+ id: id('permission', permissionArg, permissionArg.sessionId), kind: 'permission', since: permissionArg.createdAt,
3633
+ title: inboxTitle(permissionArg.title || permissionArg.type), where: whereArg, answer: answerArg, permission: permissionArg,
3634
+ })),
3635
+ ...attentionArg.questions.map((questionArg): TControllerInboxItem => ({
3636
+ id: id('question', questionArg, questionArg.sessionId), kind: 'question', since: questionArg.createdAt,
3637
+ title: inboxTitle(questionArg.questions[0]?.question || questionArg.questions[0]?.header || 'A question'),
3638
+ where: whereArg, answer: answerArg, question: questionArg,
3639
+ })),
3640
+ ...(attentionArg.elicitations ?? []).map((elicitationArg): TControllerInboxItem => ({
3641
+ id: id('elicitation', elicitationArg, elicitationArg.sessionId), kind: 'elicitation', since: elicitationArg.createdAt,
3642
+ title: inboxTitle(elicitationArg.message || `${elicitationArg.serverName} asks for input`),
3643
+ where: whereArg, answer: answerArg, elicitation: elicitationArg,
3644
+ })),
3645
+ ];
3646
+ }
3647
+
3648
+ /** A native session as the Inbox names it: where it runs and how the browser opens it. */
3649
+ private inboxNativeWhere(harnessArg: 'claude' | 'codex', nativeIdArg: string, titleArg: string): Extract<TControllerInboxWhere, { kind: 'native' }> {
3650
+ return { kind: 'native', session: { harness: harnessArg, nativeId: nativeIdArg }, harness: harnessArg,
3651
+ ...this.inboxRow(harnessArg, nativeIdArg, titleArg), host: plugins.os.hostname() };
3652
+ }
3653
+
3654
+ /** The requests Claude Code holds: its conversations' and those of AGL's turns in native sessions. */
3655
+ private readInboxClaude(): TControllerInboxItem[] {
3656
+ const harness = this.claudeHarness;
3657
+ if (!harness || harness.closed) return [];
3658
+ return harness.pendingAttention().flatMap((entryArg) => {
3659
+ if (entryArg.projectId === undefined) {
3660
+ return this.inboxSessionItems(this.inboxNativeWhere('claude', entryArg.nativeId, entryArg.title), 'native', entryArg.attention);
3661
+ }
3662
+ const sessionId = claudeRuntimeId(entryArg.nativeId);
3663
+ return this.inboxSessionItems({
3664
+ kind: 'conversation', projectId: entryArg.projectId, sessionId, harness: 'claude',
3665
+ ...this.inboxRow('claude', entryArg.nativeId, entryArg.title),
3666
+ }, 'conversation', entryArg.attention, this.isProjectAutoAcceptedSession(entryArg.projectId, sessionId));
3667
+ });
3668
+ }
3669
+
3670
+ /** The requests the Codex connections hold: the conversations' and, on the fleet's connection, the native threads'. */
3671
+ private readInboxCodex(): TControllerInboxItem[] {
3672
+ const clients = this.codexConnections
3673
+ ? this.codexConnections.all().flatMap((runtimeArg) => runtimeArg.supervisor.getStatus().healthy ? [runtimeArg.client] : [])
3674
+ : this.codexClient && this.codexSupervisor?.getStatus().healthy ? [this.codexClient] : [];
3675
+ const conversations = clients.flatMap((clientArg) => clientArg.pendingAttention().flatMap((entryArg) => {
3676
+ const sessionId = codexRuntimeId(entryArg.threadId);
3677
+ return this.inboxSessionItems({
3678
+ kind: 'conversation', projectId: entryArg.projectId, sessionId, harness: 'codex',
3679
+ ...this.inboxRow('codex', entryArg.threadId, entryArg.session.title),
3680
+ }, 'conversation', entryArg.attention, this.isProjectAutoAcceptedSession(entryArg.projectId, sessionId));
3681
+ }));
3682
+ const native = (this.fleetWorkers?.nativePendingAttention('codex') ?? []).flatMap((entryArg) => (
3683
+ this.inboxSessionItems(this.inboxNativeWhere('codex', entryArg.nativeId, entryArg.title), 'native', entryArg.attention)
3684
+ ));
3685
+ return [...conversations, ...native];
3686
+ }
3687
+
3688
+ /**
3689
+ * The requests of the OpenCode conversations the feed shows waiting, from the project's pending lists, and of their
3690
+ * direct children (subagents), from `readOpenCodeFamilyAttention`, the read the browser's child scopes use: only a
3691
+ * managed conversation has children AGL answers. A project or a conversation whose read fails keeps the items it had.
3692
+ */
3693
+ private async readInboxOpenCode(previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3694
+ const client = this.openCodeClient;
3695
+ if (!client) return [];
3696
+ const byProject = new Map<string, IControllerSessionFeedRow[]>();
3697
+ for (const row of this.sessionFeed?.publishedRows() ?? []) {
3698
+ if (row.harness !== 'opencode' || row.state !== 'needs_input' || row.nativeWait !== undefined || row.open.kind !== 'conversation') continue;
3699
+ byProject.set(row.open.projectId, [...byProject.get(row.open.projectId) ?? [], row]);
3700
+ }
3701
+ const kept = (predicateArg: (whereArg: TControllerInboxWhere) => boolean) => previousArg.filter((itemArg) => predicateArg(itemArg.where));
3702
+ const items: TControllerInboxItem[] = [];
3703
+ for (const [projectId, rows] of byProject) {
3704
+ signalArg.throwIfAborted();
3705
+ let pending: { permissions: IControllerPermission[]; questions: IControllerQuestion[] };
3706
+ try {
3707
+ const { directory } = await this.resolveProject(projectId);
3708
+ const [permissions, questions] = await Promise.all([
3709
+ client.listPermissions(directory, undefined, signalArg), client.listQuestions(directory, undefined, signalArg),
3710
+ ]);
3711
+ pending = { permissions, questions };
3712
+ } catch (errorArg) {
3713
+ signalArg.throwIfAborted();
3714
+ this.reportInboxError(`opencode:${projectId}`, errorArg);
3715
+ items.push(...kept((whereArg) => (whereArg.kind === 'conversation' || whereArg.kind === 'child') && whereArg.projectId === projectId));
3716
+ continue;
3717
+ }
3718
+ const roots = new Set(rows.map((rowArg) => (rowArg.open as { sessionId: IControllerRuntimeId }).sessionId.nativeId));
3719
+ const asksElsewhere = [...pending.permissions, ...pending.questions].some((requestArg) => !roots.has(requestArg.sessionId.nativeId));
3720
+ for (const row of rows) {
3721
+ const open = row.open as Extract<IControllerSessionFeedRow['open'], { kind: 'conversation' }>;
3722
+ const parentSessionId = open.sessionId as IControllerRuntimeId & { harnessId: 'opencode' };
3723
+ const own = (requestArg: { sessionId: IControllerRuntimeId }) => requestArg.sessionId.nativeId === parentSessionId.nativeId;
3724
+ const autoAccepted = this.isProjectAutoAcceptedSession(projectId, parentSessionId);
3725
+ items.push(...this.inboxSessionItems({
3726
+ kind: 'conversation', projectId, sessionId: parentSessionId, harness: 'opencode', rowId: row.id, name: row.name,
3727
+ }, 'conversation', { permissions: pending.permissions.filter(own), questions: pending.questions.filter(own) }, autoAccepted));
3728
+ if (!asksElsewhere) continue;
3729
+ try {
3730
+ for (const { child, permissions, questions } of (await this.readOpenCodeFamilyAttention(projectId, parentSessionId, signalArg, true))?.children ?? []) {
3731
+ items.push(...this.inboxSessionItems({
3732
+ kind: 'child', projectId, parentSessionId, childSessionId: child.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
3733
+ harness: 'opencode', rowId: row.id, name: row.name, childName: child.session.title || 'Subagent',
3734
+ }, 'child', { permissions, questions }, autoAccepted));
3735
+ }
3736
+ } catch (errorArg) {
3737
+ signalArg.throwIfAborted();
3738
+ // A conversation AGL does not manage has no children it answers.
3739
+ if (errorArg instanceof ControllerSessionIdentityError && (errorArg.code === 'not_found' || errorArg.code === 'tombstoned')) continue;
3740
+ this.reportInboxError(`opencode:${row.id}`, errorArg);
3741
+ items.push(...kept((whereArg) => whereArg.kind === 'child' && whereArg.rowId === row.id));
3742
+ }
3743
+ }
3744
+ }
3745
+ return items;
3746
+ }
3747
+
3748
+ /** The failures of the Inbox's partial reads, by what failed: a lasting one is reported once. */
3749
+ private readonly inboxErrors = new Map<string, string>();
3750
+ private reportInboxError(keyArg: string, errorArg: unknown): void {
3751
+ const message = errorArg instanceof Error ? errorArg.message : String(errorArg);
3752
+ if (this.inboxErrors.get(keyArg) === message) return;
3753
+ if (this.inboxErrors.size >= 256) this.inboxErrors.clear();
3754
+ this.inboxErrors.set(keyArg, message);
3755
+ console.error(`Inbox: reading ${keyArg} failed.`, errorArg);
3756
+ }
3757
+
3758
+ /**
3759
+ * The Flex permissions of the conversations the feed shows waiting, and of the driver, by the run that asks (a
3760
+ * subagent's by its root conversation). A permission the owner's auto-accept answers is left out.
3761
+ */
3762
+ private async readInboxFlex(previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3763
+ const supervisor = this.flexSupervisor;
3764
+ if (!supervisor || !this.flexIsOperational()) return [];
3765
+ const rows = new Map((this.sessionFeed?.publishedRows() ?? []).flatMap((rowArg) => rowArg.harness === 'flex'
3766
+ && rowArg.state === 'needs_input' && rowArg.nativeWait === undefined && rowArg.open.kind === 'conversation'
3767
+ ? [[`${rowArg.open.projectId}\0${rowArg.open.sessionId.nativeId}`, rowArg] as const] : []));
3768
+ const driver = await this.driverService?.driverSession();
3769
+ // The driver's status follows its session through `driver.changed`, which marks this source stale.
3770
+ const driverWaits = driver !== undefined && this.driverService?.current().session?.attention === true;
3771
+ const projectIds = new Set([...rows.values()].map((rowArg) => (rowArg.open as { projectId: string }).projectId));
3772
+ if (driverWaits) projectIds.add(driver.projectId);
3773
+ const items: TControllerInboxItem[] = [];
3774
+ for (const projectId of projectIds) {
3775
+ signalArg.throwIfAborted();
3776
+ try {
3777
+ const { permissions } = await supervisor.request('permission.list', { scopeId: projectId }, signalArg);
3778
+ for (const permission of permissions) {
3779
+ const authority = this.flexPermissionAuthority(projectId, permission);
3780
+ if (!authority || this.autoAcceptedFlexPermission(projectId, permission)) continue;
3781
+ const rootNativeId = authority.type === 'managed' ? authority.run.sessionId : authority.lease.rootAuthority.sessionId;
3782
+ const sessionId = flexRuntimeId(rootNativeId);
3783
+ if (driverWaits && driver.projectId === projectId && driver.nativeId === rootNativeId) {
3784
+ items.push(...this.inboxSessionItems({ kind: 'driver', projectId, sessionId }, 'conversation',
3785
+ { permissions: [this.toFlexPermission(permission)], questions: [] }));
3786
+ continue;
3787
+ }
3788
+ const row = rows.get(`${projectId}\0${rootNativeId}`);
3789
+ if (!row) continue;
3790
+ items.push(...this.inboxSessionItems({
3791
+ kind: 'conversation', projectId, sessionId, harness: 'flex', rowId: row.id, name: row.name,
3792
+ }, 'conversation', { permissions: [this.toFlexPermission(permission)], questions: [] }));
3793
+ }
3794
+ } catch (errorArg) {
3795
+ signalArg.throwIfAborted();
3796
+ this.reportInboxError(`flex:${projectId}`, errorArg);
3797
+ items.push(...previousArg.filter((itemArg) => (itemArg.where.kind === 'conversation' || itemArg.where.kind === 'driver')
3798
+ && itemArg.where.projectId === projectId));
3799
+ }
3800
+ }
3801
+ return items;
3802
+ }
3803
+
3804
+ /** The sessions whose harness waits in its own client: AGL holds no request for them, so they are answered there. */
3805
+ private readInboxNativeWaits(): TControllerInboxItem[] {
3806
+ const harnessLabels: Record<TControllerSessionFeedHarness, string> = { claude: 'Claude Code', codex: 'Codex', flex: 'Flex', opencode: 'OpenCode' };
3807
+ return (this.sessionFeed?.publishedRows() ?? []).flatMap((rowArg): TControllerInboxItem[] => {
3808
+ const nativeWait = rowArg.nativeWait;
3809
+ if (rowArg.state !== 'needs_input' || !nativeWait || rowArg.open.kind === 'terminal') return [];
3810
+ const label = harnessLabels[rowArg.harness];
3811
+ const title = nativeWait.reason === 'approval' ? `Waits for approval in ${label}`
3812
+ : nativeWait.reason === 'user_input' ? `Waits for input in ${label}` : `Waits in ${label}`;
3813
+ const where: Extract<TControllerInboxWhere, { kind: 'conversation' | 'native' }> = rowArg.open.kind === 'conversation'
3814
+ ? { kind: 'conversation', projectId: rowArg.open.projectId, sessionId: rowArg.open.sessionId, harness: rowArg.harness, rowId: rowArg.id, name: rowArg.name }
3815
+ : { kind: 'native', session: nativeSessionRefOfFeed(rowArg.open), harness: rowArg.open.harness, rowId: rowArg.id, name: rowArg.name,
3816
+ host: plugins.os.hostname() };
3817
+ return [{ id: `native_wait:${rowArg.id}`, kind: 'native_wait', since: rowArg.updatedAt, title, where, answer: 'none',
3818
+ nativeWait: { reason: nativeWait.reason }, host: plugins.os.hostname() }];
3819
+ });
3820
+ }
3821
+
3822
+ /** The driver's `needs input:` turn, as the driver service found it; its own prompts are Flex session prompts. */
3823
+ private readInboxDriver(): TControllerInboxItem[] {
3824
+ const turn = this.driverService?.needsInput();
3825
+ if (!turn) return [];
3826
+ return [{ id: `driver:${turn.nativeId}:${turn.messageId}`, kind: 'driver', since: turn.at, title: inboxTitle(turn.line),
3827
+ where: { kind: 'driver', projectId: turn.projectId, sessionId: flexRuntimeId(turn.nativeId) }, answer: 'none',
3828
+ line: turn.line, messageId: turn.messageId }];
3829
+ }
3830
+
3831
+ /**
3832
+ * The board's open questions that wait for the owner: every one the owner did not ask, on a ticket that is not done.
3833
+ * A deploy plan's and a maintenance window's question is the owner's go, shown with what the deploy monitor observes.
3834
+ */
3835
+ private async readInboxTickets(signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3836
+ const open = (await this.ticketStore.openQuestionTickets(signalArg))
3837
+ .filter(({ question }) => question.askedBy.role !== 'owner');
3838
+ const goes = open.some(({ ticket, question }) => ticket.deployPlan?.questionId === question.id);
3839
+ let status: IFleetDeployStatus | undefined;
3840
+ if (goes && this.deployMonitor) {
3841
+ try {
3842
+ status = await this.deployMonitor.status();
3843
+ } catch (errorArg) {
3844
+ signalArg.throwIfAborted();
3845
+ // The go is the owner's either way; what runs where is shown once the monitor answers.
3846
+ this.reportInboxError('deployments', errorArg);
3847
+ }
3848
+ }
3849
+ return open.map(({ ticket, question }): TControllerInboxItem => {
3850
+ const where: Extract<TControllerInboxWhere, { kind: 'ticket' }> = {
3851
+ kind: 'ticket', ticketId: ticket.id, ticketKey: ticket.key, ticketTitle: ticket.title, project: ticket.project, columnId: ticket.columnId,
3852
+ };
3853
+ const base = { since: Date.parse(question.createdAt), where, answer: 'ticket' as const, question };
3854
+ if (ticket.deployPlan?.questionId === question.id) {
3855
+ const plan = ticket.deployPlan;
3856
+ const target = status?.targets.find((targetArg) => targetArg.target.id === plan.target);
3857
+ const planned = target?.deployPlans.find((planArg) => planArg.key === ticket.key);
3858
+ const ships = (target?.notRunning.tickets ?? []).filter((ticketArg) => ticketArg.version !== undefined
3859
+ && compareFleetVersions(ticketArg.version, plan.version) <= 0);
3860
+ const name = target?.target.name ?? plan.target;
3861
+ return {
3862
+ ...base, id: `deploy_go:${ticket.key}:${question.id}`, kind: 'deploy_go',
3863
+ title: inboxTitle(`${name}${target?.target.environment ? ` → ${target.target.environment}` : ''}, ${target?.running ? `${target.running.version} → ` : ''}${plan.version}`),
3864
+ plan: {
3865
+ target: plan.target, version: plan.version,
3866
+ ...(target?.target.name === undefined ? {} : { targetName: target.target.name }),
3867
+ ...(target?.target.environment === undefined ? {} : { environment: target.target.environment }),
3868
+ ...(target?.running ? { runs: target.running.version } : {}),
3869
+ ...(target ? { deployWhen: target.deployWhen } : {}),
3870
+ ...(planned?.window ? { window: { from: planned.window.from, to: planned.window.to } } : {}),
3871
+ ships: ships.slice(0, controllerInboxLimits.ships).map(({ key, title }) => ({ key, title })),
3872
+ shipsTotal: ships.length,
3873
+ ...(planned?.assignee === undefined ? {} : { assignee: planned.assignee }),
3874
+ },
3875
+ };
3876
+ }
3877
+ if (ticket.maintenanceWindow?.questionId === question.id) {
3878
+ const window = ticket.maintenanceWindow;
3879
+ return {
3880
+ ...base, id: `window_go:${ticket.key}:${question.id}`, kind: 'window_go',
3881
+ title: inboxTitle(`Maintenance window for ${window.targets.join(', ')}`),
3882
+ window: { from: window.from, to: window.to, targets: [...window.targets] },
3883
+ };
3884
+ }
3885
+ return { ...base, id: `ticket_question:${ticket.key}:${question.id}`, kind: 'ticket_question', title: inboxTitle(question.question) };
3886
+ });
3887
+ }
3425
3888
  private ticketNotifier?: TicketNotifier;
3426
3889
  private boardPump?: BoardPump;
3427
3890
  private deployMonitor?: DeployMonitor;
@@ -4896,6 +5359,8 @@ export class OpenCodeController {
4896
5359
  launch: (signalArg) => this.claudeLaunch(signalArg),
4897
5360
  emit: (eventArg) => this.handleClaudeEvent(eventArg),
4898
5361
  onSessionIdle: (projectIdArg, nativeIdArg) => this.scheduleQueuedClaudePrompt(projectIdArg, claudeRuntimeId(nativeIdArg)),
5362
+ // No controller event names a native session; the Inbox reads the harness's requests again.
5363
+ onNativeAttention: () => this.inbox?.nativeAttentionChanged('claude'),
4899
5364
  });
4900
5365
  try {
4901
5366
  await this.withCurrentSessionIdentityProjects(
@@ -6989,7 +7454,7 @@ export class OpenCodeController {
6989
7454
  peerIdArg: string,
6990
7455
  requestArg: IReq_ControllerMcpSessionsList['request'],
6991
7456
  signalArg: AbortSignal,
6992
- ): Promise<IReq_ControllerMcpSessionsList['response']> {
7457
+ ): Promise<Pick<IReq_ControllerMcpSessionsList['response'], 'sessions'>> {
6993
7458
  const { projectId } = requestArg;
6994
7459
  return this.runAudited(
6995
7460
  { type: 'session.list', peerId: this.auditPeerId(principalArg, peerIdArg) },
@@ -7067,7 +7532,7 @@ export class OpenCodeController {
7067
7532
  peerIdArg: string,
7068
7533
  requestArg: IReq_ControllerMcpSessionRead['request'],
7069
7534
  signalArg: AbortSignal,
7070
- ): Promise<IReq_ControllerMcpSessionRead['response']> {
7535
+ ): Promise<TControllerMcpSessionDetail> {
7071
7536
  const { projectId, sessionId } = requestArg;
7072
7537
  return this.runAudited(
7073
7538
  {
@@ -7428,6 +7893,7 @@ export class OpenCodeController {
7428
7893
  { code: 'delivery_unsupported' },
7429
7894
  );
7430
7895
  }
7896
+ if (await this.isMcpNativeClaudeId(projectId, sessionId)) return this.deliverNativeAgentMessage(peerIdArg, requestArg, subjectArg, signalArg);
7431
7897
  await this.requireMcpMessageTarget(projectId, sessionId, signalArg);
7432
7898
  const sender: IControllerPromptSender = { kind: 'agent', label, subject: await subjectArg() };
7433
7899
  if (!this.agentMessageLimiter.admit(`${peerIdArg}\0${projectId}\0${controllerRuntimeIdKey(sessionId)}`)) {
@@ -9105,6 +9571,163 @@ export class OpenCodeController {
9105
9571
  return this.assertSessionExists(projectIdArg, sessionIdArg, signalArg);
9106
9572
  }
9107
9573
 
9574
+ /**
9575
+ * Whether an MCP request names a Claude Code session outside AGL's conversations of the project: a `claude` id that no
9576
+ * conversation of this project records. Such an id is served by the native path, everything else by the managed one.
9577
+ */
9578
+ private async isMcpNativeClaudeId(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<boolean> {
9579
+ if (sessionIdArg.harnessId !== 'claude') return false;
9580
+ await this.resolveProject(projectIdArg);
9581
+ return !await this.requireAuthStore().requireClaudeSessions().get(projectIdArg, sessionIdArg.nativeId);
9582
+ }
9583
+
9584
+ /**
9585
+ * The Claude Code session outside AGL that an MCP caller names in a project: only a session of the host's own Claude
9586
+ * Code home, as the session feed lists it, whose directory is the project folder itself, and that no other project's
9587
+ * conversation records. Anything else is `session_not_found`; nothing is recorded.
9588
+ */
9589
+ private async requireMcpNativeClaudeTarget(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<{
9590
+ ref: IControllerNativeSessionRef; resolved: IResolvedNativeSession; session: IControllerNativeSession;
9591
+ }> {
9592
+ const project = await this.resolveProject(projectIdArg);
9593
+ const ref: IControllerNativeSessionRef = { harness: 'claude', nativeId: sessionIdArg.nativeId };
9594
+ const notFound = () => new plugins.typedrequest.TypedResponseError('The requested session was not found.', { code: 'session_not_found' });
9595
+ let resolved: IResolvedNativeSession;
9596
+ try {
9597
+ resolved = await this.nativeSessions.resolve(ref);
9598
+ } catch (errorArg) {
9599
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'session_not_found') throw notFound();
9600
+ throw errorArg;
9601
+ }
9602
+ if (!await this.inMcpNativeScope(resolved, project.directory)) throw notFound();
9603
+ return { ref, resolved, session: mcpNativeSession(resolved) };
9604
+ }
9605
+
9606
+ /** The project's scope for Claude Code sessions outside AGL: the host's own home, the exact folder, no other project's conversation. */
9607
+ private async inMcpNativeScope(resolvedArg: IResolvedNativeSession, projectDirectoryArg: string): Promise<boolean> {
9608
+ if (resolvedArg.native.home !== undefined || resolvedArg.session.readOnly?.reason === 'projectConversation') return false;
9609
+ const directory = await canonicalDirectory(projectDirectoryArg);
9610
+ return directory !== undefined && await canonicalDirectory(resolvedArg.session.cwd) === directory;
9611
+ }
9612
+
9613
+ /**
9614
+ * The Claude Code sessions of the host's own Claude Code home whose directory is the project folder itself and that no
9615
+ * project conversation records, for `sessions_list`: running ones first, all of them, then the newest settled ones up
9616
+ * to `controllerMcpNativeSessionSettledLimit`. An inventory that cannot be read is named, never hidden.
9617
+ */
9618
+ private async listMcpNativeClaudeSessions(projectIdArg: string): Promise<Omit<IReq_ControllerMcpSessionsList['response'], 'sessions'>> {
9619
+ const project = await this.resolveProject(projectIdArg);
9620
+ let agents: Awaited<ReturnType<FleetWorkers['nativeAgents']>>;
9621
+ try {
9622
+ agents = await this.requireFleetWorkers().nativeAgents(undefined, 3_000);
9623
+ } catch (errorArg) {
9624
+ const reason = errorArg instanceof Error ? errorArg.message : 'unknown failure.';
9625
+ return { nativeSessions: [], nativeSessionsError: `The host's Claude Code inventory could not be read: ${reason}`.slice(0, 1024) };
9626
+ }
9627
+ const directory = await canonicalDirectory(project.directory);
9628
+ if (directory === undefined) return { nativeSessions: [] };
9629
+ const running = (agentArg: typeof agents[number]): boolean => agentArg.pid !== undefined || agentArg.state === 'working';
9630
+ const candidates: typeof agents = [], seen = new Set<string>();
9631
+ for (const agent of agents) {
9632
+ if (seen.has(agent.sessionId)) continue;
9633
+ seen.add(agent.sessionId);
9634
+ if (await canonicalDirectory(agent.cwd) === directory) candidates.push(agent);
9635
+ }
9636
+ candidates.sort((left, right) => Number(running(right)) - Number(running(left)) || (right.startedAt ?? 0) - (left.startedAt ?? 0));
9637
+ const nativeSessions: IControllerNativeSession[] = [];
9638
+ let settled = 0;
9639
+ for (const agent of candidates) {
9640
+ // Running sessions sort first and are never cut; only settled ones count toward the limit.
9641
+ if (!running(agent) && settled >= controllerMcpNativeSessionSettledLimit) return { nativeSessions, nativeSessionsTruncated: true };
9642
+ let resolved: IResolvedNativeSession;
9643
+ try {
9644
+ resolved = await this.nativeSessions.resolve({ harness: 'claude', nativeId: agent.sessionId });
9645
+ } catch (errorArg) {
9646
+ // A session that left the inventory since it was read is no longer listed.
9647
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'session_not_found') continue;
9648
+ throw errorArg;
9649
+ }
9650
+ if (!await this.inMcpNativeScope(resolved, project.directory)) continue;
9651
+ nativeSessions.push(mcpNativeSession(resolved));
9652
+ if (!running(agent)) settled += 1;
9653
+ }
9654
+ return { nativeSessions };
9655
+ }
9656
+
9657
+ /** `session_read` of a Claude Code session outside AGL: the session, its newest transcript page and its scratchpad. */
9658
+ private async readMcpNativeClaudeSession(
9659
+ principalArg: TControllerOperationPrincipal,
9660
+ requestArg: IReq_ControllerMcpSessionRead['request'],
9661
+ signalArg: AbortSignal,
9662
+ ): Promise<IControllerMcpNativeSessionDetail> {
9663
+ return this.runAudited(
9664
+ { type: 'session.read', peerId: this.auditPeerId(principalArg, 'mcp'), sessionId: requestArg.sessionId },
9665
+ () => this.serveNativeSession(signalArg, 'none', async () => {
9666
+ const { ref, resolved, session } = await this.requireMcpNativeClaudeTarget(requestArg.projectId, requestArg.sessionId);
9667
+ const [page, state] = await Promise.all([
9668
+ this.requireFleetWorkers().nativeHistory('claude', resolved.native, controllerInitialMessageBundleLimit),
9669
+ this.requireAuthStore().getSessionState(resolved.scope, nativeSessionRuntimeId(ref), signalArg),
9670
+ ]);
9671
+ signalArg.throwIfAborted();
9672
+ return {
9673
+ kind: 'native' as const,
9674
+ session,
9675
+ messagePage: boundControllerMessagePage({
9676
+ bundles: page.bundles,
9677
+ ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
9678
+ ...(page.earlier && page.nextCursor === undefined ? { truncated: true } : {}),
9679
+ }, controllerInitialMessageBundleLimit),
9680
+ scratchpad: state.scratchpad,
9681
+ };
9682
+ }),
9683
+ );
9684
+ }
9685
+
9686
+ /**
9687
+ * An agent message to a Claude Code background job outside AGL, after the project's switch: behind the
9688
+ * `session_message` header naming the caller, through the one native send, which wakes a settled job and puts the
9689
+ * message into a running job's inbox. A send that may have reached the job is `outcome_unknown`, never resent.
9690
+ */
9691
+ private async deliverNativeAgentMessage(
9692
+ peerIdArg: string,
9693
+ requestArg: IReq_ControllerMcpSessionMessage['request'],
9694
+ subjectArg: () => Promise<string>,
9695
+ signalArg: AbortSignal,
9696
+ ): Promise<IReq_ControllerMcpSessionMessage['response']> {
9697
+ const { projectId, sessionId, sender: label } = requestArg;
9698
+ if (requestArg.expectedTurnId !== undefined) {
9699
+ throw new plugins.typedrequest.TypedResponseError(
9700
+ 'A Claude Code background job outside AGL takes no turn guard; omit expectedTurnId.',
9701
+ { code: 'delivery_unsupported' },
9702
+ );
9703
+ }
9704
+ const target = await this.requireMcpNativeClaudeTarget(projectId, sessionId);
9705
+ assertMcpNativeMessageable(target.session);
9706
+ const sender: IControllerPromptSender = { kind: 'agent', label, subject: await subjectArg() };
9707
+ if (!this.agentMessageLimiter.admit(`${peerIdArg}\0${projectId}\0${controllerRuntimeIdKey(sessionId)}`)) {
9708
+ throw new plugins.typedrequest.TypedResponseError(
9709
+ 'Too many agent messages to this task; wait before sending another.',
9710
+ { code: 'message_rate_limited' },
9711
+ );
9712
+ }
9713
+ let job: TControllerNativeJobDelivery | undefined;
9714
+ try {
9715
+ ({ job } = await this.sendNativeSession(peerIdArg, target.ref, formatAgentMessage(sender, requestArg.text), undefined, signalArg,
9716
+ (resolvedArg) => {
9717
+ if (resolvedArg.native.home !== undefined) throw new plugins.typedrequest.TypedResponseError('The requested session was not found.', { code: 'session_not_found' });
9718
+ assertMcpNativeMessageable(mcpNativeSession(resolvedArg));
9719
+ }));
9720
+ } catch (errorArg) {
9721
+ // Only a refusal before dispatch proves that nothing reached the job.
9722
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'native_session_failed' && errorArg.errorData?.outcome !== 'refused') {
9723
+ throw new plugins.typedrequest.TypedResponseError('The message may have reached the Claude Code job; read the session before sending again.', { code: 'outcome_unknown' });
9724
+ }
9725
+ throw errorArg;
9726
+ }
9727
+ 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' });
9728
+ return { accepted: true as const, delivery: controllerMcpNativeDeliveries[job], native: job };
9729
+ }
9730
+
9108
9731
  /**
9109
9732
  * Any caller may message a task: unlike a task mutation, no ownership is required. The target
9110
9733
  * must still be an active root task of the project the request names; archived tasks and child
@@ -9201,6 +9824,10 @@ export class OpenCodeController {
9201
9824
  await this.resolveProject(project.id);
9202
9825
  if (!requestArg.sessionId) return { project };
9203
9826
  const target = requestArg.sessionId;
9827
+ // A Claude Code session outside AGL answers as itself and is recorded nowhere.
9828
+ if (await this.isMcpNativeClaudeId(project.id, target)) {
9829
+ return { project, nativeSession: (await this.requireMcpNativeClaudeTarget(project.id, target)).session };
9830
+ }
9204
9831
  const { sessions } = await this.listSessionsForPrincipal(
9205
9832
  principalArg, peerIdArg, { projectId: project.id }, signalArg,
9206
9833
  );
@@ -9244,6 +9871,18 @@ export class OpenCodeController {
9244
9871
  return currentControllerMcpCaller();
9245
9872
  }
9246
9873
 
9874
+ /**
9875
+ * The owner's active direct report whose session an MCP caller acts in, read once per ticket request: a ticket names
9876
+ * the caller by it (AGL-1686). None for a caller without a session or whose session is no active report.
9877
+ */
9878
+ private async mcpCallerReportName(callerArg: IControllerMcpCaller): Promise<string | undefined> {
9879
+ const sessionId = ticketCallerSessionId(callerArg);
9880
+ if (sessionId === undefined) return undefined;
9881
+ const authority = this.configurationAuthority;
9882
+ if (!authority) throw new plugins.typedrequest.TypedResponseError('The configuration authority is unavailable.', { code: 'controller_unavailable' });
9883
+ return await this.requireDirectReports().reportOf((await authority.getResource()).resourceId, sessionId);
9884
+ }
9885
+
9247
9886
  private mcpIdentityRequired(): plugins.typedrequest.TypedResponseError {
9248
9887
  return new plugins.typedrequest.TypedResponseError(
9249
9888
  'This operation is available only to an AGL-launched chat; this MCP host has no AGL identity.',
@@ -9807,7 +10446,7 @@ export class OpenCodeController {
9807
10446
  // A worker a direct report's session starts, adopts, refreshes or moves reports to it.
9808
10447
  const caller = this.mcpCaller();
9809
10448
  const reportsTo = ['start', 'adopt', 'refresh', 'move'].includes(action) && caller.subject.kind !== 'anonymous'
9810
- ? await this.requireDirectReports().reportOf(owner.resourceId, ticketActorFromCaller(caller).sessionId) : undefined;
10449
+ ? await this.requireDirectReports().reportOf(owner.resourceId, ticketCallerSessionId(caller)) : undefined;
9811
10450
  try {
9812
10451
  return await this.requireFleetWorkers().execute(action, input as TFleetWorkerRequest<typeof action>, master.fleet ?? {}, owner.resourceId, operationSignal, actor, reportsTo);
9813
10452
  } catch (errorArg) {
@@ -9869,7 +10508,7 @@ export class OpenCodeController {
9869
10508
  resolveTicketOwnerAssignment(methodArg, request as TTicketRequest<typeof methodArg>, owner.id), actor, operationSignalArg);
9870
10509
  }
9871
10510
  const caller = this.mcpCaller();
9872
- const actor = caller.subject.kind === 'anonymous' ? undefined : ticketActorFromCaller(caller);
10511
+ const actor = caller.subject.kind === 'anonymous' ? undefined : ticketActorFromCaller(caller, await this.mcpCallerReportName(caller));
9873
10512
  return await this.ticketStore.execute(methodArg, request as TTicketRequest<typeof methodArg>, actor, operationSignalArg);
9874
10513
  } catch (errorArg) {
9875
10514
  if (errorArg instanceof TicketError) throw new plugins.typedrequest.TypedResponseError(errorArg.message,
@@ -9907,16 +10546,17 @@ export class OpenCodeController {
9907
10546
  ),
9908
10547
  listSessions: async (principalArg, requestArg, signalArg) => run(
9909
10548
  signalArg,
9910
- async (operationSignalArg) => this.listSessionsForPrincipal(
9911
- principalArg,
9912
- 'mcp',
9913
- requestArg,
9914
- operationSignalArg,
9915
- ),
10549
+ async (operationSignalArg) => {
10550
+ const listed = await this.listSessionsForPrincipal(principalArg, 'mcp', requestArg, operationSignalArg);
10551
+ return { ...listed, ...await this.listMcpNativeClaudeSessions(requestArg.projectId) };
10552
+ },
9916
10553
  ),
9917
10554
  readSession: async (principalArg, requestArg, signalArg) => run(
9918
10555
  signalArg,
9919
10556
  async (operationSignalArg) => {
10557
+ if (await this.isMcpNativeClaudeId(requestArg.projectId, requestArg.sessionId)) {
10558
+ return this.readMcpNativeClaudeSession(principalArg, requestArg, operationSignalArg);
10559
+ }
9920
10560
  await this.prepareMcpSessionTarget(requestArg.projectId, requestArg.sessionId, operationSignalArg);
9921
10561
  return this.readSessionForPrincipal(
9922
10562
  principalArg,
@@ -10194,9 +10834,9 @@ export class OpenCodeController {
10194
10834
  : await resolveInitialRuntimeConfig(this.options.runtimeOverrides);
10195
10835
  this.assertStartActive();
10196
10836
  const authDocument = await authStore.resolveOrCreateRuntimeConfig(runtimeConfig);
10197
- await authStore.migrateTicketOwnerPrincipal();
10198
- const closed = await authStore.migrateTicketClosedColumn();
10837
+ const { closed, renamed } = await authStore.migrateTicketsAtStart();
10199
10838
  if (closed.length) console.log(`Moved ${closed.length} tickets released without a release link or any code link to closed (AGL-916): ${closed.join(', ')}.`);
10839
+ if (renamed.length) console.log(`Named the people of ${renamed.length} tickets by their role instead of their session id (AGL-1686): ${renamed.join(', ')}.`);
10200
10840
  this.assertStartActive();
10201
10841
  this.runtimeConfig = runtimeConfig;
10202
10842
  this.controllerId = authDocument.id;
@@ -10844,6 +11484,7 @@ export class OpenCodeController {
10844
11484
  .catch((errorArg) => console.error('Announcing new Claude Code releases failed.', errorArg));
10845
11485
  }
10846
11486
  this.startSessionFeed();
11487
+ this.startInbox();
10847
11488
  // Assignees hear of others' changes to their tickets through the fleet's native steering.
10848
11489
  this.ticketNotifier ??= new TicketNotifier({
10849
11490
  deliver: async (sessionIdArg, ticketKeyArg, textArg) => {
@@ -13222,6 +13863,7 @@ export class OpenCodeController {
13222
13863
  await stopPart(async () => { await this.deployMonitor?.close(); this.deployMonitor = undefined; });
13223
13864
  await stopPart(async () => { await this.gatewayClient?.close(); this.gatewayClient = undefined; });
13224
13865
  await stopPart(async () => { await this.ticketNotifier?.close(); this.ticketNotifier = undefined; });
13866
+ await stopPart(async () => { await this.inbox?.close(); this.inbox = undefined; });
13225
13867
  await stopPart(async () => { await this.sessionFeed?.close(); this.sessionFeed = undefined; });
13226
13868
  await stopPart(async () => { await this.usageFeed?.stop(); this.usageFeed = undefined; });
13227
13869
  await stopPart(async () => { const notices = this.harnessReleases; this.harnessReleases = undefined; await notices?.close(); });
@@ -13709,8 +14351,8 @@ export class OpenCodeController {
13709
14351
  const publicRouter = new plugins.typedrequest.TypedRouter();
13710
14352
  const browserAuthRouter = new plugins.typedrequest.TypedRouter();
13711
14353
  const protectedRouter = new ControllerProtectedRouter(asTypedResponseError);
13712
- const devicePairingRouter = new ControllerProtectedRouter(asTypedResponseError);
13713
- const deviceRouter = new ControllerProtectedRouter(asTypedResponseError);
14354
+ const devicePairingRouter = new ControllerProtectedRouter(asDeviceResponseError);
14355
+ const deviceRouter = new ControllerProtectedRouter(asDeviceResponseError);
13714
14356
  rootRouter.addTypedRouter(publicRouter);
13715
14357
  rootRouter.addTypedRouter(browserAuthRouter);
13716
14358
  rootRouter.addTypedRouter(protectedRouter);
@@ -13775,13 +14417,14 @@ export class OpenCodeController {
13775
14417
  this.registerDirectReportHandlers(protectedRouter);
13776
14418
  this.registerNativeSessionHandlers(protectedRouter);
13777
14419
  this.registerSessionFeedHandlers(protectedRouter);
14420
+ this.registerInboxHandlers(protectedRouter);
13778
14421
  this.registerDeployHandlers(protectedRouter);
13779
14422
  this.registerUsageFeedHandlers(protectedRouter);
13780
14423
  this.registerTerminalHandlers(protectedRouter);
13781
14424
  this.registerDevicesHandlers(protectedRouter);
13782
14425
 
13783
14426
  this.registerDevicePairingHandlers(devicePairingRouter);
13784
- this.registerDeviceHandlers(deviceRouter);
14427
+ this.registerDeviceHandlers(deviceRouter, publicOriginArg);
13785
14428
 
13786
14429
  return rootRouter;
13787
14430
  }
@@ -13903,11 +14546,293 @@ export class OpenCodeController {
13903
14546
  });
13904
14547
  }
13905
14548
 
14549
+ /**
14550
+ * A device's answer to a direct child (an OpenCode subagent) of the session it names: the session must be an OpenCode
14551
+ * conversation the feed lists, and the child is proven a running direct child of it as the browser's child scopes do.
14552
+ */
14553
+ private replyDeviceChildRequest(
14554
+ auditPeerIdArg: string,
14555
+ openArg: Exclude<IControllerSessionFeedRow['open'], { kind: 'terminal' }>,
14556
+ childSessionIdArg: string,
14557
+ requestIdArg: string,
14558
+ replyArg: { reply: TControllerPermissionReply; message?: string } | { answers: string[][] | null },
14559
+ signalArg: AbortSignal,
14560
+ ): Promise<{ success: boolean }> {
14561
+ if (openArg.kind !== 'conversation' || openArg.sessionId.harnessId !== 'opencode') {
14562
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
14563
+ }
14564
+ const projectId = openArg.projectId;
14565
+ const parentSessionId = openArg.sessionId as IControllerRuntimeId & { harnessId: 'opencode' };
14566
+ const childSessionId = { harnessId: 'opencode' as const, nativeId: childSessionIdArg };
14567
+ return this.replyChildRequestForPrincipal('device', auditPeerIdArg, {
14568
+ projectId, parentSessionId, childSessionId, requestId: { harnessId: 'opencode', nativeId: requestIdArg }, ...replyArg,
14569
+ }, (activeRequiredArg) => this.verifyDeviceDirectChild(projectId, parentSessionId, childSessionId, signalArg, activeRequiredArg), signalArg);
14570
+ }
14571
+
14572
+ /**
14573
+ * A conversation's transcript page and what it waits for, as a device reads it through the browser's session read:
14574
+ * the newest page without `before`, sized by the controller, else the next older page of `limit` messages.
14575
+ */
14576
+ private async readDeviceConversation(
14577
+ auditPeerIdArg: string,
14578
+ projectIdArg: string,
14579
+ sessionIdArg: IControllerRuntimeId,
14580
+ requestArg: { before?: string; limit?: number },
14581
+ signalArg: AbortSignal,
14582
+ ): Promise<Omit<IReq_DeviceSessionRead['response'], 'session'>> {
14583
+ const detail = await this.readSessionForPrincipal('device', auditPeerIdArg, { projectId: projectIdArg, sessionId: sessionIdArg }, signalArg);
14584
+ const before = requestArg.before;
14585
+ const page = before === undefined ? detail.messagePage : await this.runAudited(
14586
+ { type: 'session.messages.page', peerId: auditPeerIdArg, sessionId: sessionIdArg },
14587
+ async () => this.readSessionMessagePage(
14588
+ await this.resolveProject(projectIdArg),
14589
+ sessionIdArg,
14590
+ { limit: requestArg.limit ?? controllerInitialMessageBundleLimit, before },
14591
+ signalArg,
14592
+ ),
14593
+ );
14594
+ return {
14595
+ messages: deviceMessages(page.bundles),
14596
+ before: page.nextCursor ?? null,
14597
+ permissions: devicePermissions(detail.permissions),
14598
+ questions: deviceQuestions(detail.questions),
14599
+ elicitations: deviceElicitations(detail.elicitations),
14600
+ };
14601
+ }
14602
+
14603
+ /**
14604
+ * The host's driver session for a device's read or send, as the driver's status names it now; refused while there is
14605
+ * none. A device never creates the driver.
14606
+ */
14607
+ private async deviceDriverSession(signalArg: AbortSignal): Promise<{
14608
+ driver: IControllerDriverStatus;
14609
+ projectId: string;
14610
+ sessionId: TControllerSessionId;
14611
+ }> {
14612
+ const driver = await this.requireDriverService().get(signalArg);
14613
+ if (driver.activity === 'absent' || driver.projectId === undefined || driver.sessionId === undefined) {
14614
+ throw deviceRefusal('driver_absent', 'This host has no driver session; the owner starts the driver in the browser.');
14615
+ }
14616
+ return { driver, projectId: driver.projectId, sessionId: driver.sessionId };
14617
+ }
14618
+
13906
14619
  /**
13907
14620
  * Scope `device`: the session feed, bounded transcript reads, direct sends and permission and question answers of an
13908
- * authenticated device -- through the same operations the owner's browser runs, audited as `device:<id>`.
14621
+ * authenticated device, the Inbox, the driver, the direct reports, the host's status and the shared board -- through
14622
+ * the same operations the owner's browser runs, audited as `device:<id>`. `publicOriginArg` is the origin the scope
14623
+ * admits.
13909
14624
  */
13910
- private registerDeviceHandlers(routerArg: ControllerProtectedRouter): void {
14625
+ private registerDeviceHandlers(routerArg: ControllerProtectedRouter, publicOriginArg: string): void {
14626
+ routerArg.addHandler<IReq_DeviceInboxList>('device.inbox.list', async (requestArg, toolsArg) => {
14627
+ validateRequest(() => assertEmptyRequest(requestArg));
14628
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14629
+ return this.runDeviceOperation(peer, deviceId, async () => deviceInboxList(
14630
+ await this.requireInbox().list(), (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg),
14631
+ ), toolsArg?.abortSignal);
14632
+ });
14633
+
14634
+ routerArg.addHandler<IReq_DeviceTicketAnswer>('device.ticket.answer', async (requestArg, toolsArg) => {
14635
+ const request = validateRequest(() => assertDeviceTicketAnswerRequest(requestArg));
14636
+ const answer = validateRequest(() => assertTicketRequest('answer', {
14637
+ ticketId: request.ticketKey, questionId: request.questionId,
14638
+ ...(request.choices === undefined ? {} : { choices: request.choices }),
14639
+ ...(request.text === undefined ? {} : { text: request.text }),
14640
+ }));
14641
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14642
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14643
+ try {
14644
+ const { question } = await this.answerTicketForPrincipal('device', deviceAuditPeerId(deviceId), answer, signalArg);
14645
+ return { question: deviceTicketQuestion(question) };
14646
+ } catch (errorArg) {
14647
+ throw deviceTicketRefusal(errorArg);
14648
+ }
14649
+ }, toolsArg?.abortSignal);
14650
+ });
14651
+
14652
+ // The shared board (AGL-1637): the browser board's own reads and changes, as the owner and audited as the device. A
14653
+ // device creates, edits and assigns no ticket; a refusal changes nothing and carries the store's code and reason.
14654
+ routerArg.addHandler<IReq_DeviceBoardList>('device.board.list', async (requestArg, toolsArg) => {
14655
+ const request = validateRequest(() => assertDeviceBoardListRequest(requestArg));
14656
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14657
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14658
+ const { owner, viewer } = await this.deviceTicketViewer();
14659
+ let board: ITicketBoard;
14660
+ try {
14661
+ board = await this.ticketStore.execute('board', {}, owner, signalArg);
14662
+ } catch (errorArg) {
14663
+ throw deviceTicketRefusal(errorArg);
14664
+ }
14665
+ return deviceBoardPage(board, request, viewer);
14666
+ }, toolsArg?.abortSignal);
14667
+ });
14668
+
14669
+ routerArg.addHandler<IReq_DeviceTicketGet>('device.ticket.get', async (requestArg, toolsArg) => {
14670
+ const request = validateRequest(() => assertDeviceTicketGetRequest(requestArg));
14671
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14672
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14673
+ const { owner, viewer } = await this.deviceTicketViewer();
14674
+ let detail: ITicketDetail;
14675
+ let comments: ITicketComment[];
14676
+ try {
14677
+ // The ticket and every question, then every comment: the discussion is paged here, by what a device shows.
14678
+ detail = await this.ticketStore.execute('get', { ticketId: request.ticketKey, limit: 1 }, owner, signalArg);
14679
+ comments = (await this.ticketStore.execute('comments', { ticketId: request.ticketKey }, owner, signalArg)).comments;
14680
+ } catch (errorArg) {
14681
+ throw deviceTicketRefusal(errorArg);
14682
+ }
14683
+ const parent = await this.deviceTicketParent(owner, detail.ticket, signalArg);
14684
+ const { placement, observed } = await readDeviceTicketPlacement(
14685
+ () => this.requireDeployMonitor().ticketPlacement(detail.ticket.key), signalArg,
14686
+ );
14687
+ return {
14688
+ ticket: deviceTicket(detail.ticket, parent, viewer),
14689
+ ...deviceTicketDiscussion(comments, detail.questions, request, viewer),
14690
+ placement,
14691
+ plans: deviceTicketPlans(detail.ticket, observed),
14692
+ };
14693
+ }, toolsArg?.abortSignal);
14694
+ });
14695
+
14696
+ routerArg.addHandler<IReq_DeviceTicketComment>('device.ticket.comment', async (requestArg, toolsArg) => {
14697
+ const request = validateRequest(() => assertDeviceTicketCommentRequest(requestArg));
14698
+ const comment = validateRequest(() => assertTicketRequest('comment', { ticketId: request.ticketKey, body: request.text }));
14699
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14700
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14701
+ const { viewer } = await this.deviceTicketViewer();
14702
+ try {
14703
+ const written = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'comment', comment, signalArg);
14704
+ return { comment: deviceTicketComment(written.comment, viewer) };
14705
+ } catch (errorArg) {
14706
+ throw deviceTicketRefusal(errorArg);
14707
+ }
14708
+ }, toolsArg?.abortSignal);
14709
+ });
14710
+
14711
+ routerArg.addHandler<IReq_DeviceTicketAsk>('device.ticket.ask', async (requestArg, toolsArg) => {
14712
+ const request = validateRequest(() => assertDeviceTicketAskRequest(requestArg));
14713
+ // Text alone, answered with text, as the browser board's question card asks.
14714
+ const ask = validateRequest(() => assertTicketRequest('ask', { ticketId: request.ticketKey, question: request.question }));
14715
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14716
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14717
+ try {
14718
+ const { question } = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'ask', ask, signalArg);
14719
+ return { question: deviceTicketQuestion(question) };
14720
+ } catch (errorArg) {
14721
+ throw deviceTicketRefusal(errorArg);
14722
+ }
14723
+ }, toolsArg?.abortSignal);
14724
+ });
14725
+
14726
+ // "Move to…": the phone's drag on the browser's board, to the end of the column.
14727
+ routerArg.addHandler<IReq_DeviceTicketMove>('device.ticket.move', async (requestArg, toolsArg) => {
14728
+ const request = validateRequest(() => assertDeviceTicketMoveRequest(requestArg));
14729
+ const move = validateRequest(() => assertTicketRequest('move', { ticketId: request.ticketKey, columnId: request.column }));
14730
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14731
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14732
+ const { owner, viewer } = await this.deviceTicketViewer();
14733
+ let moved: ITicket;
14734
+ try {
14735
+ const { tickets } = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'move', move, signalArg);
14736
+ // A ticket already last in its column moves nowhere and is not among the tickets the move changed.
14737
+ moved = tickets.find((ticketArg) => ticketArg.key === request.ticketKey)
14738
+ ?? (await this.ticketStore.execute('get', { ticketId: request.ticketKey, limit: 1 }, owner, signalArg)).ticket;
14739
+ } catch (errorArg) {
14740
+ throw deviceTicketRefusal(errorArg);
14741
+ }
14742
+ return { ticket: deviceTicketCard(moved, await this.deviceTicketParent(owner, moved, signalArg), viewer) };
14743
+ }, toolsArg?.abortSignal);
14744
+ });
14745
+
14746
+ // The driver as the browser's topbar and Driver view reach it; its own prompts are read-only on a device.
14747
+ routerArg.addHandler<IReq_DeviceDriverGet>('device.driver.get', async (requestArg, toolsArg) => {
14748
+ validateRequest(() => assertEmptyRequest(requestArg));
14749
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14750
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14751
+ const service = this.requireDriverService();
14752
+ return { driver: deviceDriverStatus(await service.get(signalArg), service.needsInput()) };
14753
+ }), toolsArg?.abortSignal);
14754
+ });
14755
+
14756
+ routerArg.addHandler<IReq_DeviceDriverSeen>('device.driver.seen', async (requestArg, toolsArg) => {
14757
+ validateRequest(() => assertEmptyRequest(requestArg));
14758
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14759
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14760
+ const service = this.requireDriverService();
14761
+ return { driver: deviceDriverStatus(await service.seen(signalArg), service.needsInput()) };
14762
+ }), toolsArg?.abortSignal);
14763
+ });
14764
+
14765
+ routerArg.addHandler<IReq_DeviceDriverRead>('device.driver.read', async (requestArg, toolsArg) => {
14766
+ const request = validateRequest(() => assertDeviceDriverReadRequest(requestArg));
14767
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14768
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14769
+ const { driver, projectId, sessionId } = await this.deviceDriverSession(signalArg);
14770
+ const transcript = await this.readDeviceConversation(deviceAuditPeerId(deviceId), projectId, sessionId, request, signalArg);
14771
+ return { driver: deviceDriverStatus(driver, this.requireDriverService().needsInput()), ...transcript };
14772
+ }), toolsArg?.abortSignal);
14773
+ });
14774
+
14775
+ routerArg.addHandler<IReq_DeviceDriverSend>('device.driver.send', async (requestArg, toolsArg) => {
14776
+ const request = validateRequest(() => assertDeviceDriverSendRequest(requestArg));
14777
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14778
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14779
+ const { projectId, sessionId } = await this.deviceDriverSession(signalArg);
14780
+ // A direct message, as to any conversation: never the browser's shared draft.
14781
+ await this.sendSessionForPrincipal('device', deviceAuditPeerId(deviceId), {
14782
+ source: 'direct', projectId, sessionId, text: request.text,
14783
+ }, signalArg);
14784
+ return { accepted: true as const };
14785
+ }), toolsArg?.abortSignal);
14786
+ });
14787
+
14788
+ routerArg.addHandler<IReq_DeviceDirectReportsList>('device.directreports.list', async (requestArg, toolsArg) => {
14789
+ validateRequest(() => assertEmptyRequest(requestArg));
14790
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14791
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => this.serveDirectReport(signalArg, async (ownerArg) => {
14792
+ const directReports = this.requireDirectReports();
14793
+ const [views, workers] = await Promise.all([directReports.list(ownerArg, false, signalArg), directReports.reportWorkers(ownerArg)]);
14794
+ return { reports: views.map((viewArg) => deviceDirectReport(viewArg, workers.get(viewArg.report.name) ?? [])) };
14795
+ }), toolsArg?.abortSignal);
14796
+ });
14797
+
14798
+ routerArg.addHandler<IReq_DeviceDirectReportMessage>('device.directreport.message', async (requestArg, toolsArg) => {
14799
+ const request = validateRequest(() => assertDeviceDirectReportMessageRequest(requestArg));
14800
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14801
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => this.serveDirectReport(signalArg, async (ownerArg) => {
14802
+ let answer: IReq_ControllerDirectReportMessage['response'];
14803
+ try {
14804
+ answer = await this.messageDirectReportForPrincipal('device', deviceAuditPeerId(deviceId), ownerArg, request, signalArg);
14805
+ } catch (errorArg) {
14806
+ throw deviceDirectReportMessageRefusal(errorArg);
14807
+ }
14808
+ if (!('job' in answer)) return { delivery: answer.delivery };
14809
+ if (answer.job.state !== 'succeeded') throw deviceDirectReportJobRefusal(answer.job);
14810
+ return { delivery: 'fleet' as const };
14811
+ }), toolsArg?.abortSignal);
14812
+ });
14813
+
14814
+ // The Host view (AGL-824) is read-only: what the browser's status, Deployments view and accounts read, reduced so
14815
+ // nothing names an account, a key or a probe's address, and no deploy probe runs for it.
14816
+ routerArg.addHandler<IReq_DeviceHostGet>('device.host.get', async (requestArg, toolsArg) => {
14817
+ validateRequest(() => assertEmptyRequest(requestArg));
14818
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14819
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14820
+ const device = this.requireDevices().get(deviceId);
14821
+ if (device === undefined) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
14822
+ const proxyMonitor = this.proxyMonitor;
14823
+ return {
14824
+ agl: deviceHostAgl({ version: commitinfo.version, startedAt: this.startedAt, origin: publicOriginArg, gateway: this.gatewayClient?.status() }),
14825
+ device: deviceHostDevice(device),
14826
+ ...await readDeviceHostSections({
14827
+ deployStatus: () => this.requireDeployMonitor().status(),
14828
+ capacity: proxyMonitor === undefined ? undefined : (operationSignalArg) => proxyMonitor.capacity({}, operationSignalArg),
14829
+ authority: () => this.authorityState.getProjection(),
14830
+ usage: (accountIdArg, loginIdArg, operationSignalArg) => this.accountsActions.usage({ accountId: accountIdArg, loginId: loginIdArg }, operationSignalArg),
14831
+ }, Date.now(), signalArg),
14832
+ };
14833
+ }, toolsArg?.abortSignal);
14834
+ });
14835
+
13911
14836
  routerArg.addHandler<IReq_DeviceSessionsList>('device.sessions.list', async (requestArg, toolsArg) => {
13912
14837
  validateRequest(() => assertEmptyRequest(requestArg));
13913
14838
  const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
@@ -13925,26 +14850,7 @@ export class OpenCodeController {
13925
14850
  const { row, open } = await this.deviceSessionTarget(request.sessionId);
13926
14851
  const session = deviceSessionRow(row)!;
13927
14852
  if (open.kind === 'conversation') {
13928
- const { projectId, sessionId } = open;
13929
- const detail = await this.readSessionForPrincipal('device', auditPeerId, { projectId, sessionId }, signalArg);
13930
- const before = request.before;
13931
- const page = before === undefined ? detail.messagePage : await this.runAudited(
13932
- { type: 'session.messages.page', peerId: auditPeerId, sessionId },
13933
- async () => this.readSessionMessagePage(
13934
- await this.resolveProject(projectId),
13935
- sessionId,
13936
- { limit: request.limit ?? controllerInitialMessageBundleLimit, before },
13937
- signalArg,
13938
- ),
13939
- );
13940
- return {
13941
- session,
13942
- messages: deviceMessages(page.bundles),
13943
- before: page.nextCursor ?? null,
13944
- permissions: devicePermissions(detail.permissions),
13945
- questions: deviceQuestions(detail.questions),
13946
- elicitations: deviceElicitations(detail.elicitations),
13947
- };
14853
+ return { session, ...await this.readDeviceConversation(auditPeerId, open.projectId, open.sessionId, request, signalArg) };
13948
14854
  }
13949
14855
  // As for a conversation, `limit` sizes older pages only; the newest page is the controller's own bound.
13950
14856
  const native = await this.readNativeSessionForPrincipal('device', auditPeerId, {
@@ -13976,6 +14882,7 @@ export class OpenCodeController {
13976
14882
  } else {
13977
14883
  await this.sendNativeSession(
13978
14884
  auditPeerId, nativeSessionRefOfFeed(open), request.text, undefined, signalArg, assertNativeSessionWritable,
14885
+ { kind: 'agent', label: 'Owner', subject: agentMessageSubjects.ownerDevice },
13979
14886
  );
13980
14887
  }
13981
14888
  return { accepted: true as const };
@@ -13988,6 +14895,11 @@ export class OpenCodeController {
13988
14895
  return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13989
14896
  const auditPeerId = deviceAuditPeerId(deviceId);
13990
14897
  const { open } = await this.deviceSessionTarget(request.sessionId);
14898
+ if (request.childSessionId !== undefined) {
14899
+ return this.replyDeviceChildRequest(auditPeerId, open, request.childSessionId, request.permissionId, {
14900
+ reply: request.reply, ...(request.message === undefined ? {} : { message: request.message }),
14901
+ }, signalArg);
14902
+ }
13991
14903
  if (open.kind === 'conversation') {
13992
14904
  return this.replyPermissionForPrincipal('device', auditPeerId, validateRequest(() => assertPermissionReplyRequest({
13993
14905
  projectId: open.projectId,
@@ -14013,6 +14925,11 @@ export class OpenCodeController {
14013
14925
  return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14014
14926
  const auditPeerId = deviceAuditPeerId(deviceId);
14015
14927
  const { open } = await this.deviceSessionTarget(request.sessionId);
14928
+ if (request.childSessionId !== undefined) {
14929
+ return this.replyDeviceChildRequest(auditPeerId, open, request.childSessionId, request.questionId, {
14930
+ answers: request.answers,
14931
+ }, signalArg);
14932
+ }
14016
14933
  if (open.kind === 'conversation') {
14017
14934
  return this.replyQuestionForPrincipal('device', auditPeerId, validateRequest(() => assertQuestionReplyRequest({
14018
14935
  projectId: open.projectId,
@@ -16111,38 +17028,10 @@ export class OpenCodeController {
16111
17028
  const request = validateRequest(
16112
17029
  () => assertSessionChildPermissionReplyRequest(requestArg),
16113
17030
  );
16114
- return this.runOperation(peer, async (signalArg) => this.runAudited(
16115
- {
16116
- type: 'permission.reply',
16117
- peerId: peer.id,
16118
- sessionId: request.childSessionId,
16119
- requestId: request.requestId,
16120
- },
16121
- async () => this.withHarnessSubmissionAdmission(
16122
- request.projectId,
16123
- request.parentSessionId,
16124
- signalArg,
16125
- async () => {
16126
- const scope = this.requireChildScope(peer, request);
16127
- const first = await this.revalidateChildScope(scope, signalArg, true);
16128
- const pending = await first.parent.client.listPermissions(
16129
- first.parent.project.directory,
16130
- request.childSessionId.nativeId,
16131
- AbortSignal.any([signalArg, first.parent.runtimeAuthority.signal]),
16132
- );
16133
- this.assertAttentionRequestOwned(pending, request.requestId, 'permission');
16134
- const current = await this.revalidateChildScope(scope, signalArg, true);
16135
- const success = await current.parent.client.replyPermission(
16136
- current.parent.project.directory,
16137
- request.requestId.nativeId,
16138
- request.reply,
16139
- request.message,
16140
- AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]),
16141
- );
16142
- await this.revalidateChildScope(scope, signalArg);
16143
- return { success };
16144
- },
16145
- ),
17031
+ return this.runOperation(peer, async (signalArg) => this.replyChildRequestForPrincipal(
17032
+ 'browser', peer.id, request,
17033
+ (activeRequiredArg) => this.revalidateChildScope(this.requireChildScope(peer, request), signalArg, activeRequiredArg),
17034
+ signalArg,
16146
17035
  ));
16147
17036
  },
16148
17037
  );
@@ -16154,43 +17043,10 @@ export class OpenCodeController {
16154
17043
  const request = validateRequest(
16155
17044
  () => assertSessionChildQuestionReplyRequest(requestArg),
16156
17045
  );
16157
- return this.runOperation(peer, async (signalArg) => this.runAudited(
16158
- {
16159
- type: 'question.reply',
16160
- peerId: peer.id,
16161
- sessionId: request.childSessionId,
16162
- requestId: request.requestId,
16163
- },
16164
- async () => this.withHarnessSubmissionAdmission(
16165
- request.projectId,
16166
- request.parentSessionId,
16167
- signalArg,
16168
- async () => {
16169
- const scope = this.requireChildScope(peer, request);
16170
- const first = await this.revalidateChildScope(scope, signalArg, true);
16171
- const pending = await first.parent.client.listQuestions(
16172
- first.parent.project.directory,
16173
- request.childSessionId.nativeId,
16174
- AbortSignal.any([signalArg, first.parent.runtimeAuthority.signal]),
16175
- );
16176
- this.assertAttentionRequestOwned(pending, request.requestId, 'question');
16177
- const current = await this.revalidateChildScope(scope, signalArg, true);
16178
- const success = request.answers === null
16179
- ? await current.parent.client.rejectQuestion(
16180
- current.parent.project.directory,
16181
- request.requestId.nativeId,
16182
- AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]),
16183
- )
16184
- : await current.parent.client.replyQuestion(
16185
- current.parent.project.directory,
16186
- request.requestId.nativeId,
16187
- request.answers,
16188
- AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]),
16189
- );
16190
- await this.revalidateChildScope(scope, signalArg);
16191
- return { success };
16192
- },
16193
- ),
17046
+ return this.runOperation(peer, async (signalArg) => this.replyChildRequestForPrincipal(
17047
+ 'browser', peer.id, request,
17048
+ (activeRequiredArg) => this.revalidateChildScope(this.requireChildScope(peer, request), signalArg, activeRequiredArg),
17049
+ signalArg,
16194
17050
  ));
16195
17051
  },
16196
17052
  );
@@ -16935,6 +17791,86 @@ export class OpenCodeController {
16935
17791
  * alike. The harness checks the reply against the pending request before it sends anything; elicitations are never
16936
17792
  * answered automatically, auto-accept included.
16937
17793
  */
17794
+ /**
17795
+ * Answers a permission or question of a direct child (an OpenCode subagent) of a managed root conversation, for the
17796
+ * owner's browser and a paired device alike: `verifyArg` proves the session is a direct child of the root (the
17797
+ * browser's child scope, or the same direct-child check for a device) and, while `activeRequiredArg`, that it runs. It
17798
+ * runs before the pending list is read, before the answer is sent and after it; `null` answers reject a question.
17799
+ */
17800
+ private async replyChildRequestForPrincipal(
17801
+ principalArg: TControllerOperationPrincipal,
17802
+ peerIdArg: string,
17803
+ requestArg: {
17804
+ projectId: string;
17805
+ parentSessionId: IControllerRuntimeId & { harnessId: 'opencode' };
17806
+ childSessionId: IControllerRuntimeId & { harnessId: 'opencode' };
17807
+ requestId: IControllerRuntimeId & { harnessId: 'opencode' };
17808
+ } & ({ reply: TControllerPermissionReply; message?: string } | { answers: string[][] | null }),
17809
+ verifyArg: (activeRequiredArg: boolean) => Promise<{ parent: IOpenCodeManagedSessionScopeAuthority }>,
17810
+ signalArg: AbortSignal,
17811
+ ): Promise<{ success: boolean }> {
17812
+ const kind = 'reply' in requestArg ? 'permission' : 'question';
17813
+ return this.runAudited(
17814
+ {
17815
+ type: kind === 'permission' ? 'permission.reply' : 'question.reply',
17816
+ peerId: this.auditPeerId(principalArg, peerIdArg),
17817
+ sessionId: requestArg.childSessionId,
17818
+ requestId: requestArg.requestId,
17819
+ },
17820
+ async () => this.withHarnessSubmissionAdmission(
17821
+ requestArg.projectId,
17822
+ requestArg.parentSessionId,
17823
+ signalArg,
17824
+ async () => {
17825
+ const first = await verifyArg(true);
17826
+ const firstSignal = AbortSignal.any([signalArg, first.parent.runtimeAuthority.signal]);
17827
+ const pending = kind === 'permission'
17828
+ ? await first.parent.client.listPermissions(first.parent.project.directory, requestArg.childSessionId.nativeId, firstSignal)
17829
+ : await first.parent.client.listQuestions(first.parent.project.directory, requestArg.childSessionId.nativeId, firstSignal);
17830
+ this.assertAttentionRequestOwned(pending, requestArg.requestId, kind);
17831
+ const current = await verifyArg(true);
17832
+ const signal = AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]);
17833
+ const { directory } = current.parent.project;
17834
+ const success = 'reply' in requestArg
17835
+ ? await current.parent.client.replyPermission(directory, requestArg.requestId.nativeId, requestArg.reply, requestArg.message, signal)
17836
+ : requestArg.answers === null
17837
+ ? await current.parent.client.rejectQuestion(directory, requestArg.requestId.nativeId, signal)
17838
+ : await current.parent.client.replyQuestion(directory, requestArg.requestId.nativeId, requestArg.answers, signal);
17839
+ await verifyArg(false);
17840
+ return { success };
17841
+ },
17842
+ ),
17843
+ );
17844
+ }
17845
+
17846
+ /**
17847
+ * A device's proof that `childSessionIdArg` is a direct child of the managed root conversation, by the check the
17848
+ * browser's child scopes run (`observeOpenCodeDirectChild`), and, while `activeRequiredArg`, that it runs: a child
17849
+ * whose turn ended takes no answer.
17850
+ */
17851
+ private async verifyDeviceDirectChild(
17852
+ projectIdArg: string,
17853
+ parentSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
17854
+ childSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
17855
+ signalArg: AbortSignal,
17856
+ activeRequiredArg: boolean,
17857
+ ): Promise<{ parent: IOpenCodeManagedSessionScopeAuthority }> {
17858
+ let observation: Awaited<ReturnType<OpenCodeController['observeOpenCodeDirectChild']>>;
17859
+ try {
17860
+ observation = await this.observeOpenCodeDirectChild(projectIdArg, parentSessionIdArg, childSessionIdArg, signalArg);
17861
+ } catch (errorArg) {
17862
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError
17863
+ && (errorArg.errorData as { code?: unknown } | undefined)?.code === 'child_scope_invalid') {
17864
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
17865
+ }
17866
+ throw errorArg;
17867
+ }
17868
+ if (activeRequiredArg && this.childScopeObservedMode(observation.child.session) !== 'active') {
17869
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
17870
+ }
17871
+ return observation;
17872
+ }
17873
+
16938
17874
  private async replyElicitationForPrincipal(
16939
17875
  principalArg: TControllerOperationPrincipal,
16940
17876
  peerIdArg: string,
@@ -17377,6 +18313,16 @@ export class OpenCodeController {
17377
18313
  protectedRouterArg.addHandler<TControllerTicketRequest<TTicketOperation>>(`controller.ticket.${operation}`,
17378
18314
  async (requestArg, toolsArg) => {
17379
18315
  const peer = peerFromLocalData(toolsArg?.localData);
18316
+ if (operation === 'answer') {
18317
+ const request = validateRequest(() => assertTicketRequest('answer', requestArg));
18318
+ return this.runOperation(peer, async (signalArg) => this.answerTicketForPrincipal('browser', peer.id, request, signalArg),
18319
+ toolsArg?.abortSignal);
18320
+ }
18321
+ if (operation === 'comment' || operation === 'ask' || operation === 'move') {
18322
+ const request = validateRequest(() => assertTicketRequest(operation, requestArg));
18323
+ return this.runOperation(peer, async (signalArg) => this.changeTicketForPrincipal('browser', peer.id, operation, request, signalArg),
18324
+ toolsArg?.abortSignal);
18325
+ }
17380
18326
  return this.runOperation(peer, async (signalArg) => {
17381
18327
  try {
17382
18328
  const owner = ticketOwnerActor(await this.requireAuthStore().getState());
@@ -17392,6 +18338,88 @@ export class OpenCodeController {
17392
18338
  }
17393
18339
  }
17394
18340
 
18341
+ /**
18342
+ * Answers a ticket question as the owner, for the owner's browser and a paired device alike, audited as
18343
+ * `ticket.answer` with the peer. A deploy plan's or a maintenance window's question takes it as the owner's go. The
18344
+ * identical answer again is a confirmed replay; a different one is refused (`ticket_question_answered`), and the
18345
+ * client keeps the owner's choice.
18346
+ */
18347
+ private async answerTicketForPrincipal(
18348
+ principalArg: TControllerOperationPrincipal,
18349
+ peerIdArg: string,
18350
+ requestArg: TTicketRequest<'answer'>,
18351
+ signalArg: AbortSignal,
18352
+ ): Promise<TTicketResponse<'answer'>> {
18353
+ return this.runAudited({ type: 'ticket.answer', peerId: this.auditPeerId(principalArg, peerIdArg) }, async () => {
18354
+ try {
18355
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18356
+ return await this.ticketStore.execute('answer', requestArg, owner, signalArg);
18357
+ } catch (errorArg) {
18358
+ if (errorArg instanceof TicketError) throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
18359
+ throw errorArg;
18360
+ }
18361
+ });
18362
+ }
18363
+
18364
+ /**
18365
+ * Comments on a ticket, asks on it or moves it as the owner, for the owner's browser and a paired device alike,
18366
+ * audited as `ticket.comment`, `ticket.ask` or `ticket.move` with the peer (the envelope alone). The ticket store
18367
+ * decides every change in one transaction: a refusal changes nothing and carries the store's code and reason.
18368
+ */
18369
+ private async changeTicketForPrincipal<TMethod extends TTicketChangeOperation>(
18370
+ principalArg: TControllerOperationPrincipal,
18371
+ peerIdArg: string,
18372
+ methodArg: TMethod,
18373
+ requestArg: TTicketRequest<TMethod>,
18374
+ signalArg: AbortSignal,
18375
+ ): Promise<TTicketResponse<TMethod>> {
18376
+ return this.runAudited({ type: ticketChangeAuditTypes[methodArg], peerId: this.auditPeerId(principalArg, peerIdArg) }, async () => {
18377
+ try {
18378
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18379
+ return await this.ticketStore.execute(methodArg, requestArg, owner, signalArg);
18380
+ } catch (errorArg) {
18381
+ if (errorArg instanceof TicketError) throw new plugins.typedrequest.TypedResponseError(errorArg.message,
18382
+ { code: errorArg.code, ...readTicketRevisionConflict(errorArg) });
18383
+ throw errorArg;
18384
+ }
18385
+ });
18386
+ }
18387
+
18388
+ /**
18389
+ * The owner, whom a device's ticket request runs as, and what the device's ticket views read besides the tickets:
18390
+ * the owner's principal id, which they replace with the `owner` kind, and the session feed's published rows.
18391
+ */
18392
+ private async deviceTicketViewer(): Promise<{ owner: ITicketActor; viewer: IDeviceTicketViewer }> {
18393
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18394
+ return { owner, viewer: { ownerId: owner.id, rowOf: (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg) } };
18395
+ }
18396
+
18397
+ /** The ticket a ticket's `parentId` names, which a device's card and detail name; a store refusal as a device's. */
18398
+ private async deviceTicketParent(ownerArg: ITicketActor, ticketArg: ITicket, signalArg: AbortSignal): Promise<ITicket | undefined> {
18399
+ if (ticketArg.parentId === undefined) return undefined;
18400
+ try {
18401
+ return (await this.ticketStore.execute('get', { ticketId: ticketArg.parentId, limit: 1 }, ownerArg, signalArg)).ticket;
18402
+ } catch (errorArg) {
18403
+ throw deviceTicketRefusal(errorArg);
18404
+ }
18405
+ }
18406
+
18407
+ private requireInbox(): ControllerInbox {
18408
+ if (!this.inbox) {
18409
+ throw new plugins.typedrequest.TypedResponseError('The Inbox is not running.', { code: 'controller_unavailable' });
18410
+ }
18411
+ return this.inbox;
18412
+ }
18413
+
18414
+ /** The Inbox: what waits for the owner, read after every source that changed (AGL-1635). */
18415
+ private registerInboxHandlers(protectedRouterArg: ControllerProtectedRouter): void {
18416
+ protectedRouterArg.addHandler<IReq_ControllerInboxList>('controller.inbox.list', async (requestArg, toolsArg) => {
18417
+ validateRequest(() => assertEmptyRequest(requestArg));
18418
+ const peer = peerFromLocalData(toolsArg?.localData);
18419
+ return this.runOperation(peer, async () => this.requireInbox().list(), toolsArg?.abortSignal);
18420
+ });
18421
+ }
18422
+
17395
18423
  /**
17396
18424
  * The host's driver: one Flex session that no session list shows, opened from the topbar. Fleet
17397
18425
  * events reach it through the relay once it exists.
@@ -17433,8 +18461,8 @@ export class OpenCodeController {
17433
18461
  ...(model?.providerConnectionId === undefined ? {} : { providerConnectionId: model.providerConnectionId }),
17434
18462
  }, signalArg, { nativeId: nativeIdArg });
17435
18463
  },
17436
- latestAssistantText: (projectIdArg, nativeIdArg, signalArg) => (
17437
- this.latestDriverAssistantText(projectIdArg, nativeIdArg, signalArg)
18464
+ latestAssistantMessage: (projectIdArg, nativeIdArg, signalArg) => (
18465
+ this.latestDriverAssistantMessage(projectIdArg, nativeIdArg, signalArg)
17438
18466
  ),
17439
18467
  publish: (statusArg) => {
17440
18468
  void this.pushControllerEvent({ type: 'driver.changed', driverStatus: statusArg, timestamp: Date.now() })
@@ -17472,7 +18500,8 @@ export class OpenCodeController {
17472
18500
  relayed: async (eventsArg) => {
17473
18501
  const authority = this.configurationAuthority;
17474
18502
  if (!authority) throw new Error('The configuration authority is unavailable.');
17475
- const reportWorkers = await this.requireDirectReports().reportWorkers((await authority.getResource()).resourceId);
18503
+ const groups = await this.requireDirectReports().reportWorkers((await authority.getResource()).resourceId);
18504
+ const reportWorkers = new Set([...groups.values()].flat().map(({ worker }) => worker.name));
17476
18505
  return eventsArg.filter((eventArg) => !eventArg.workerName || !reportWorkers.has(eventArg.workerName));
17477
18506
  },
17478
18507
  });
@@ -17673,17 +18702,19 @@ export class OpenCodeController {
17673
18702
  }
17674
18703
  }
17675
18704
 
17676
- private async latestDriverAssistantText(
18705
+ /** The driver's newest assistant transcript entry with text: the entry's own id (a Flex message or part id). */
18706
+ private async latestDriverAssistantMessage(
17677
18707
  projectIdArg: string,
17678
18708
  nativeIdArg: string,
17679
18709
  signalArg?: AbortSignal,
17680
- ): Promise<string | undefined> {
18710
+ ): Promise<IDriverAssistantMessage | undefined> {
17681
18711
  try {
17682
18712
  const page = await this.requireFlexProjectionReader().listMessagePage(projectIdArg, nativeIdArg, { limit: 8 }, signalArg);
17683
- return page.messages
18713
+ const message = page.messages
17684
18714
  .flatMap((messageArg) => this.toFlexMessageBundle(messageArg).messages)
17685
18715
  .reverse()
17686
- .find((messageArg) => messageArg.role === 'assistant' && messageArg.text.trim())?.text;
18716
+ .find((messageArg) => messageArg.role === 'assistant' && messageArg.text.trim());
18717
+ return message === undefined ? undefined : { id: message.id.nativeId, text: message.text, createdAt: message.createdAt };
17687
18718
  } catch (errorArg) {
17688
18719
  if (errorArg instanceof FlexProjectionNotFoundError) return undefined;
17689
18720
  throw errorArg;
@@ -17773,18 +18804,21 @@ export class OpenCodeController {
17773
18804
  );
17774
18805
  }
17775
18806
 
18807
+ /** A driver operation for the browser: a `DriverError` is answered with its own code (a device's: `serveDeviceDriver`). */
18808
+ private async serveDriver<T>(operationArg: () => Promise<T>): Promise<T> {
18809
+ try {
18810
+ return await operationArg();
18811
+ } catch (errorArg) {
18812
+ if (errorArg instanceof DriverError) {
18813
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
18814
+ }
18815
+ throw errorArg;
18816
+ }
18817
+ }
18818
+
17776
18819
  /** The driver topbar: the host's one driver session, its status, and the unread turns it marks seen. */
17777
18820
  private registerDriverHandlers(protectedRouterArg: ControllerProtectedRouter): void {
17778
- const serve = async <T>(operationArg: () => Promise<T>): Promise<T> => {
17779
- try {
17780
- return await operationArg();
17781
- } catch (errorArg) {
17782
- if (errorArg instanceof DriverError) {
17783
- throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
17784
- }
17785
- throw errorArg;
17786
- }
17787
- };
18821
+ const serve = <T>(operationArg: () => Promise<T>): Promise<T> => this.serveDriver(operationArg);
17788
18822
  protectedRouterArg.addHandler<IReq_ControllerDriverGet>(
17789
18823
  'controller.driver.get',
17790
18824
  async (requestArg, toolsArg) => {
@@ -17994,7 +19028,7 @@ export class OpenCodeController {
17994
19028
  */
17995
19029
  private registerNativeSessionHandlers(protectedRouterArg: ControllerProtectedRouter): void {
17996
19030
  const runtimeId = nativeSessionRuntimeId;
17997
- const serve = <T>(signalArg: AbortSignal, operationArg: () => Promise<T>): Promise<T> => this.serveNativeSession(signalArg, operationArg);
19031
+ const serve = <T>(signalArg: AbortSignal, operationArg: () => Promise<T>): Promise<T> => this.serveNativeSession(signalArg, 'none', operationArg);
17998
19032
 
17999
19033
  protectedRouterArg.addHandler<IReq_ControllerNativeSessionRead>(
18000
19034
  'controller.nativesession.read',
@@ -18033,9 +19067,12 @@ export class OpenCodeController {
18033
19067
  async (requestArg, toolsArg) => {
18034
19068
  const peer = peerFromLocalData(toolsArg?.localData);
18035
19069
  const { session: ref, text, attachments } = validateRequest(() => assertNativeSessionSendRequest(requestArg));
18036
- return this.runOperation(peer, async (signalArg) => ({
18037
- session: await this.sendNativeSession(peer.id, ref, text, attachments, signalArg, assertNativeSessionWritable),
18038
- }), toolsArg?.abortSignal);
19070
+ return this.runOperation(peer, async (signalArg) => {
19071
+ await this.sendNativeSession(peer.id, ref, text, attachments, signalArg, assertNativeSessionWritable,
19072
+ { kind: 'agent', label: 'Owner', subject: agentMessageSubjects.ownerNativeView });
19073
+ // The session as the send left it, read apart from the audited send.
19074
+ return { session: await this.serveNativeSession(signalArg, 'none', async () => (await this.nativeSessions.resolve(ref)).session) };
19075
+ }, toolsArg?.abortSignal);
18039
19076
  },
18040
19077
  );
18041
19078
 
@@ -18171,7 +19208,7 @@ export class OpenCodeController {
18171
19208
  const sessionId = nativeSessionRuntimeId(ref);
18172
19209
  return this.runAudited(
18173
19210
  { type: 'session.read', peerId: this.auditPeerId(principalArg, peerIdArg), sessionId },
18174
- () => this.serveNativeSession(signalArg, async () => {
19211
+ () => this.serveNativeSession(signalArg, 'none', async () => {
18175
19212
  const resolved = await this.nativeSessions.resolve(ref);
18176
19213
  const [page, attention, state] = await Promise.all([
18177
19214
  this.requireFleetWorkers().nativeHistory(ref.harness, resolved.native, limit ?? controllerInitialMessageBundleLimit, before),
@@ -18214,7 +19251,7 @@ export class OpenCodeController {
18214
19251
  : ['question', { answers: requestArg.answers }];
18215
19252
  return this.runAudited(
18216
19253
  { type: `${kind}.reply`, peerId: this.auditPeerId(principalArg, peerIdArg), sessionId: nativeSessionRuntimeId(ref), requestId },
18217
- () => this.serveNativeSession(signalArg, async () => {
19254
+ () => this.serveNativeSession(signalArg, 'dispatch', async () => {
18218
19255
  const resolved = await this.nativeSessions.resolve(ref);
18219
19256
  await this.replyNativeSessionRequest(resolved, requestId.nativeId, reply, kind);
18220
19257
  return { success: true };
@@ -18260,24 +19297,38 @@ export class OpenCodeController {
18260
19297
  }
18261
19298
  }
18262
19299
 
18263
- /** Native session failures are bounded messages; the session view and the fleet's receipt show them as they are. */
18264
- private async serveNativeSession<T>(signalArg: AbortSignal, operationArg: () => Promise<T>): Promise<T> {
19300
+ /**
19301
+ * Native session failures are bounded messages; the session view and the fleet's receipt show them as they are. Each
19302
+ * says what it did (`INativeSessionFailedErrorData`). `effectArg` `none` means the operation sends the session
19303
+ * nothing (a read, the session's resolution, AGL's own scratchpad), so it is `refused`: a scratchpad save under `none`
19304
+ * is safe to repeat because its `expectedRevision` refuses a second write of the same revision. A send or an answer
19305
+ * (`dispatch`) is `refused` only where the fleet proved it never went out, and `unknown` otherwise.
19306
+ */
19307
+ private async serveNativeSession<T>(signalArg: AbortSignal, effectArg: 'none' | 'dispatch', operationArg: () => Promise<T>): Promise<T> {
18265
19308
  try {
18266
19309
  return await operationArg();
18267
19310
  } catch (errorArg) {
18268
19311
  if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
18269
19312
  // The session state store states its own refusals: a stale scratchpad revision, a missing record.
18270
19313
  if (errorArg instanceof AuthError) throw asTypedResponseError(errorArg, 'native session');
18271
- throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'native_session_failed' });
19314
+ const errorData: INativeSessionFailedErrorData = {
19315
+ code: 'native_session_failed',
19316
+ outcome: effectArg === 'none' || (errorArg instanceof FleetDispatchError && !errorArg.dispatched) ? 'refused' : 'unknown',
19317
+ };
19318
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), errorData);
18272
19319
  }
18273
19320
  }
18274
19321
 
18275
19322
  /**
18276
- * The one send to a native session, for the browser's `controller.nativesession.send` and the fleet's
18277
- * `native-message`: audited as `session.send`, under the session's lock, where the session is resolved again and
18278
- * `assertArg` refuses what this caller may not write to, so a session that started running meanwhile is refused. A
18279
- * Codex thread goes through its shared server, a Claude Code background job is woken through Claude Code itself, and
18280
- * another settled Claude Code session resumes in AGL's own Claude Code. Resolves with the session after the send.
19323
+ * The one send to a native session, for the browser's `controller.nativesession.send`, a paired device, the fleet's
19324
+ * `native-message` and an MCP `session_message`: audited as `session.send`, under the session's lock, where the
19325
+ * session is resolved again and `assertArg` refuses what this caller may not write to, so a session whose state
19326
+ * changed meanwhile is refused. A Codex thread goes through its shared server, a Claude Code background job is reached
19327
+ * through Claude Code itself (woken while settled, its inbox while it runs), and another settled Claude Code session
19328
+ * resumes in AGL's own Claude Code. The owner's own text (`ownerArg`) goes into a job's inbox as the owner's agent
19329
+ * message: a peer message names no sender of its own. Resolves right after the dispatch with, for a job, how it took
19330
+ * the message, and reads nothing after it: a failed read must never turn a delivered message into a refusal, which a
19331
+ * caller would answer by sending again. A caller that shows the session reads it afterwards.
18281
19332
  */
18282
19333
  private async sendNativeSession(
18283
19334
  peerIdArg: string,
@@ -18286,25 +19337,29 @@ export class OpenCodeController {
18286
19337
  attachmentsArg: readonly IControllerDraftAttachment[] | undefined,
18287
19338
  signalArg: AbortSignal,
18288
19339
  assertArg: (resolvedArg: IResolvedNativeSession) => void,
18289
- ): Promise<IControllerNativeSession> {
19340
+ ownerArg?: IControllerPromptSender,
19341
+ ): Promise<{ job?: TControllerNativeJobDelivery }> {
18290
19342
  const sessionId = nativeSessionRuntimeId(refArg);
18291
- return this.runAudited({ type: 'session.send', peerId: peerIdArg, sessionId }, () => this.serveNativeSession(signalArg, async () => {
19343
+ return this.runAudited({ type: 'session.send', peerId: peerIdArg, sessionId }, () => this.serveNativeSession(signalArg, 'dispatch', async () => {
18292
19344
  const scope = (await this.nativeSessions.resolve(refArg)).scope;
19345
+ let job: TControllerNativeJobDelivery | undefined;
18293
19346
  await this.withSessionStateMutation(scope, sessionId, async () => {
18294
19347
  const resolved = await this.nativeSessions.resolve(refArg);
18295
19348
  assertArg(resolved);
18296
19349
  if (refArg.harness === 'codex') await this.sendNativeCodexSession(resolved, textArg, attachmentsArg);
18297
- else if (resolved.claudeJob) await this.sendNativeClaudeJob(resolved, textArg, attachmentsArg);
18298
- else await this.sendNativeClaudeSession(resolved, textArg, attachmentsArg, signalArg);
19350
+ else if (resolved.claudeJob) {
19351
+ job = await this.sendNativeClaudeJob(resolved, resolved.claudeJob === 'inbox' && ownerArg ? formatAgentMessage(ownerArg, textArg) : textArg, attachmentsArg);
19352
+ } else await this.sendNativeClaudeSession(resolved, textArg, attachmentsArg, signalArg);
18299
19353
  });
18300
- return (await this.nativeSessions.resolve(refArg)).session;
19354
+ return job === undefined ? {} : { job };
18301
19355
  }));
18302
19356
  }
18303
19357
 
18304
19358
  /**
18305
19359
  * The fleet's `native-message`: resolves the Claude Code background job the caller names by id or prefix, refuses
18306
19360
  * what the browser's send would refuse and what is no background job, each with its reason and the adopt command,
18307
- * and sends the message behind the `session_message` attribution header through `sendNativeSession`.
19361
+ * and sends the message behind the `session_message` attribution header through `sendNativeSession`: a wake of a
19362
+ * settled job, or its inbox while it runs.
18308
19363
  */
18309
19364
  private async sendFleetNativeMessage(
18310
19365
  requestArg: TFleetWorkerRequest<'native-message'>,
@@ -18321,7 +19376,7 @@ export class OpenCodeController {
18321
19376
  if (readOnly) {
18322
19377
  // What the caller can do instead: steer the worker, wait for the job to settle, or adopt it into its profile.
18323
19378
  const next = readOnly.reason === 'fleetWorker' && workerName ? ` Message it with \`agl fleet worker message ${workerName}\`.`
18324
- : readOnly.reason === 'running' || readOnly.reason === 'jobHeld' ? ` Message it, or adopt it, once it settles; it is adopted with \`${adopt}\`.`
19379
+ : readOnly.reason === 'running' || readOnly.reason === 'jobHeld' || readOnly.reason === 'unaddressable' ? ` Message it, or adopt it, once it settles; it is adopted with \`${adopt}\`.`
18325
19380
  : readOnly.reason === 'jobFailed' ? ` A failed job takes no wake; adopt it with \`${adopt}\`.`
18326
19381
  : readOnly.reason === 'profileHome' ? ` Adopt it as a worker of that profile with \`${adopt}\`.` : '';
18327
19382
  throw new plugins.typedrequest.TypedResponseError(`${readOnly.message}${next}`, { code: 'session_read_only' });
@@ -18336,12 +19391,16 @@ export class OpenCodeController {
18336
19391
  const jobId = found.agent.id;
18337
19392
  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' });
18338
19393
  const text = formatAgentMessage({ kind: 'agent', label: requestArg.sender, subject: this.ownerMessageSubject(actorArg) }, requestArg.text);
18339
- await this.sendNativeSession(peerId, found.ref, text, undefined, this.operationAbortController.signal, assertMessageable);
19394
+ const { job } = await this.sendNativeSession(peerId, found.ref, text, undefined, this.operationAbortController.signal, assertMessageable);
18340
19395
  return {
18341
- delivery: 'native-wake', nativeId: found.agent.sessionId, jobId, cwd: found.agent.cwd,
19396
+ delivery: job === 'inbox' ? 'native-inbox' : 'native-wake', nativeId: found.agent.sessionId, jobId, cwd: found.agent.cwd,
18342
19397
  ...(profileId ? { profileId } : {}),
18343
- note: 'Delivered as a native wake of a Claude Code background job no fleet worker binds: it holds no dispatch fence, '
18344
- + 'writes no ticket comment and does not observe the woken turn. Adopt the job to steer and observe it as a fleet worker.',
19398
+ note: job === 'inbox'
19399
+ ? 'Delivered into the inbox of a running Claude Code background job no fleet worker binds, through Claude Code\'s own '
19400
+ + 'SendMessage: accepted and queued there, not yet read. It holds no dispatch fence, writes no ticket comment and does not '
19401
+ + 'observe the turn that reads it. Adopt the job, once it settles, to steer and observe it as a fleet worker.'
19402
+ : 'Delivered as a native wake of a Claude Code background job no fleet worker binds: it holds no dispatch fence, '
19403
+ + 'writes no ticket comment and does not observe the woken turn. Adopt the job to steer and observe it as a fleet worker.',
18345
19404
  adopt,
18346
19405
  };
18347
19406
  }
@@ -18392,7 +19451,11 @@ export class OpenCodeController {
18392
19451
  } catch (errorArg) {
18393
19452
  if (errorArg instanceof ClaudeHarnessDispatchError && !errorArg.dispatched) {
18394
19453
  if (upload) cleanup();
18395
- throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: 'native_session_failed' });
19454
+ // Nothing went out: a busy conversation or host says so, which a sender reads as "try again once it ended".
19455
+ const errorData: INativeSessionFailedErrorData = {
19456
+ code: 'native_session_failed', outcome: 'refused', ...(errorArg.refusal === undefined ? {} : { refusal: errorArg.refusal }),
19457
+ };
19458
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message, errorData);
18396
19459
  }
18397
19460
  // Claude Code may have taken the message: the turn settles as Claude Code reports it, and its upload goes with
18398
19461
  // it. A conversation that no longer holds the message lost its process, and with it the turn.
@@ -18402,18 +19465,21 @@ export class OpenCodeController {
18402
19465
  }
18403
19466
 
18404
19467
  /**
18405
- * Wakes a settled Claude Code background job with the message through Claude Code itself, so the job stays the
18406
- * session's owner. Claude Code does not report when the woken turn ends, so the upload stays for the sweep unless
18407
- * the message never reached Claude Code.
19468
+ * Sends to a Claude Code background job through Claude Code itself, so the job stays the session's owner: a settled
19469
+ * job is woken with the message, a running one takes it in its inbox, as the resolution prepared it. Claude Code does
19470
+ * not report when the turn that reads it ends, so the upload stays for the sweep unless the message never reached
19471
+ * Claude Code.
18408
19472
  */
18409
19473
  private async sendNativeClaudeJob(
18410
19474
  resolvedArg: IResolvedNativeSession,
18411
19475
  textArg: string,
18412
19476
  attachmentsArg: readonly IControllerDraftAttachment[] | undefined,
18413
- ): Promise<void> {
19477
+ ): Promise<TControllerNativeJobDelivery> {
18414
19478
  const upload = await this.createRetainedUpload(attachmentsArg);
19479
+ let receipt: Awaited<ReturnType<FleetWorkers['nativeSend']>>;
18415
19480
  try {
18416
- await this.requireFleetWorkers().nativeSend('claude', resolvedArg.native, `${textArg}${upload?.promptSuffix ?? ''}`, () => undefined);
19481
+ const session = { ...resolvedArg.native, jobDelivery: resolvedArg.claudeJob!, ...(resolvedArg.peerHomes ? { peerHomes: resolvedArg.peerHomes } : {}) };
19482
+ receipt = await this.requireFleetWorkers().nativeSend('claude', session, `${textArg}${upload?.promptSuffix ?? ''}`, () => undefined);
18417
19483
  } catch (errorArg) {
18418
19484
  if (upload && errorArg instanceof FleetDispatchError && !errorArg.dispatched) {
18419
19485
  void this.trackOperationPromise(upload.cleanup())
@@ -18422,6 +19488,8 @@ export class OpenCodeController {
18422
19488
  throw errorArg;
18423
19489
  }
18424
19490
  upload?.release();
19491
+ if (!receipt.job) throw new FleetDispatchError('Claude Code did not say how the background job took the message. Inspect it before sending again.', true);
19492
+ return receipt.job;
18425
19493
  }
18426
19494
 
18427
19495
  /**
@@ -18447,17 +19515,24 @@ export class OpenCodeController {
18447
19515
  }
18448
19516
  }
18449
19517
 
19518
+ /**
19519
+ * A direct report operation for the owner's browser or a device, given the owner: its failures reach them as
19520
+ * `directReportFailure` decides, by the error's class.
19521
+ */
19522
+ private async serveDirectReport<T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> {
19523
+ try {
19524
+ return await operationArg((await this.readFleetScope()).owner);
19525
+ } catch (errorArg) {
19526
+ if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
19527
+ throw directReportFailure(errorArg, 'directreport');
19528
+ }
19529
+ }
19530
+
18450
19531
  /** The Driver view's direct reports: sessions that report to the owner, appointed from the fleet or adopted by reference. */
18451
19532
  private registerDirectReportHandlers(protectedRouterArg: ControllerProtectedRouter): void {
18452
- // Direct report failures are bounded messages for the owner; the Driver view shows them as they are.
18453
- const serve = async <T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> => {
18454
- try {
18455
- return await operationArg((await this.readFleetScope()).owner);
18456
- } catch (errorArg) {
18457
- if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
18458
- throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'direct_report_failed' });
18459
- }
18460
- };
19533
+ const serve = <T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> => (
19534
+ this.serveDirectReport(signalArg, operationArg)
19535
+ );
18461
19536
  protectedRouterArg.addHandler<IReq_ControllerDirectReportList>(
18462
19537
  'controller.directreport.list',
18463
19538
  async (requestArg, toolsArg) => {
@@ -18518,36 +19593,67 @@ export class OpenCodeController {
18518
19593
  )), toolsArg?.abortSignal);
18519
19594
  },
18520
19595
  );
18521
- // The owner's steer of a fleet worker report goes through the report's driver ticket, as the driver's
18522
- // directreport_message does; a Codex thread takes it as the owner's agent message.
18523
19596
  protectedRouterArg.addHandler<IReq_ControllerDirectReportMessage>(
18524
19597
  'controller.directreport.message',
18525
19598
  async (requestArg, toolsArg) => {
18526
- const { name, text, expectedTurnId, attachments } = validateRequest(() => assertDirectReportMessageRequest(requestArg));
19599
+ const request = validateRequest(() => assertDirectReportMessageRequest(requestArg));
18527
19600
  const peer = peerFromLocalData(toolsArg?.localData);
18528
19601
  return this.runOperation(peer, (signalArg) => serve(signalArg, async (ownerArg) => {
18529
- const channel = await this.requireDirectReports().channelOf(ownerArg, name);
18530
- if (channel.kind === 'session') {
18531
- if (attachments) {
18532
- throw new plugins.typedrequest.TypedResponseError(
18533
- 'A Codex thread report takes text only.', { code: 'invalid_request' },
18534
- );
18535
- }
18536
- const { delivery, turnId } = await this.messageDirectReportSession(channel, 'owner', peer.id, text, expectedTurnId);
18537
- return { delivery, ...(turnId === undefined ? {} : { turnId }) };
18538
- }
18539
- if (expectedTurnId !== undefined) throw new Error('expectedTurnId names the turn of a Codex thread; a fleet worker report is steered through its ticket.');
18540
- const fleetWorkers = this.requireFleetWorkers();
18541
- const configuration = (await this.readFleetScope()).configuration;
18542
- const job = await this.withRetainedSteerUpload(attachments, async (suffixArg) => (await fleetWorkers.execute('steer', {
18543
- messages: [{ name: channel.workerName, text: formatOwnerFleetMessage(`${text}${suffixArg}`) }], ticketKey: channel.report.driverTicketKey,
18544
- }, configuration, ownerArg, signalArg)).job);
18545
- return { job: await fleetWorkers.settled(ownerArg, job.id, signalArg) };
19602
+ const answer = await this.messageDirectReportForPrincipal('browser', peer.id, ownerArg, request, signalArg);
19603
+ return 'job' in answer ? { job: directReportJobView(answer.job) } : answer;
18546
19604
  }), toolsArg?.abortSignal);
18547
19605
  },
18548
19606
  );
18549
19607
  }
18550
19608
 
19609
+ /**
19610
+ * The owner's own message to the active direct report `name`, from the Driver view or a paired device, audited as
19611
+ * `session.message` from the `Owner` for the caller. A fleet worker report is steered through the report's driver
19612
+ * ticket, as the driver's `directreport_message` does, and answers with the settled steer job as the fleet recorded
19613
+ * it, audited `failed` unless the job succeeded; the caller shows a failed job's error by its code
19614
+ * (`directReportJobView`, `deviceDirectReportJobRefusal`), and one that may have delivered it (`errorOutcome`) as of
19615
+ * unknown outcome. A steer the fleet refused is `direct_report_failed`
19616
+ * (`directReportFailure`), also audited `failed`. A Codex thread takes it as the owner's agent message.
19617
+ */
19618
+ private async messageDirectReportForPrincipal(
19619
+ principalArg: TControllerOperationPrincipal,
19620
+ peerIdArg: string,
19621
+ ownerArg: string,
19622
+ requestArg: IReq_ControllerDirectReportMessage['request'],
19623
+ signalArg: AbortSignal,
19624
+ ): Promise<IReq_ControllerDirectReportMessage['response']> {
19625
+ const peerId = this.auditPeerId(principalArg, peerIdArg);
19626
+ const { name, text, expectedTurnId, attachments } = requestArg;
19627
+ const channel = await this.requireDirectReports().channelOf(ownerArg, name);
19628
+ if (channel.kind === 'session') {
19629
+ if (attachments) {
19630
+ throw new plugins.typedrequest.TypedResponseError(
19631
+ 'A Codex thread report takes text only.', { code: 'invalid_request' },
19632
+ );
19633
+ }
19634
+ const { delivery, turnId } = await this.messageDirectReportSession(channel, 'owner', peerId, text, expectedTurnId);
19635
+ return { delivery, ...(turnId === undefined ? {} : { turnId }) };
19636
+ }
19637
+ if (expectedTurnId !== undefined) {
19638
+ throw new plugins.typedrequest.TypedResponseError('expectedTurnId names the turn of a Codex thread; a fleet worker report is steered through its ticket.',
19639
+ { code: 'invalid_request' });
19640
+ }
19641
+ return await this.runAudited({ type: 'session.message', peerId, sessionId: directReportRuntimeId(channel.report), senderLabel: 'Owner' }, async () => {
19642
+ try {
19643
+ const fleetWorkers = this.requireFleetWorkers();
19644
+ const configuration = (await this.readFleetScope()).configuration;
19645
+ const job = await this.withRetainedSteerUpload(attachments, async (suffixArg) => (await fleetWorkers.execute('steer', {
19646
+ messages: [{ name: channel.workerName, text: formatOwnerFleetMessage(`${text}${suffixArg}`) }], ticketKey: channel.report.driverTicketKey,
19647
+ }, configuration, ownerArg, signalArg)).job);
19648
+ return { job: await fleetWorkers.settled(ownerArg, job.id, signalArg) };
19649
+ } catch (errorArg) {
19650
+ // The fleet's own reason, as `serveDirectReport` gives it, before the audit would reduce it to a generic failure.
19651
+ if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
19652
+ throw directReportFailure(errorArg, 'directreport.message');
19653
+ }
19654
+ }, ({ job }) => job.state === 'succeeded' ? 'succeeded' : 'failed');
19655
+ }
19656
+
18551
19657
  /** The driver session's instructions, notes and tools; the caller checked its session authority. */
18552
19658
  private async handleFlexDriverHostRequest(
18553
19659
  methodArg: 'driver.resolve' | 'driver.tool',
@@ -19244,9 +20350,14 @@ export class OpenCodeController {
19244
20350
  );
19245
20351
  }
19246
20352
 
20353
+ /**
20354
+ * Runs an operation between its `attempted` record and its terminal one. `outcomeOfArg` names the outcome of an
20355
+ * operation that returns its own failure (a settled job that failed), which is then recorded `failed`.
20356
+ */
19247
20357
  private async runAudited<T>(
19248
20358
  auditArg: Omit<IRecordAuditEventInput, 'outcome'>,
19249
20359
  operationArg: (operationIdArg: string) => Promise<T>,
20360
+ outcomeOfArg: (resultArg: T) => 'succeeded' | 'failed' = () => 'succeeded',
19250
20361
  ): Promise<T> {
19251
20362
  const operationId = plugins.crypto.randomBytes(24).toString('base64url');
19252
20363
  const correlatedAudit = { ...auditArg, operationId };
@@ -19266,11 +20377,14 @@ export class OpenCodeController {
19266
20377
  try {
19267
20378
  result = await operationArg(operationId);
19268
20379
  } catch (error) {
19269
- // A refused workspace path is a policy decision, recorded as one.
19270
- const outcome = error instanceof AuthError
20380
+ // A refused workspace path is a policy decision, recorded as one; a direct report that took no message, and a fault
20381
+ // already reduced to the controller's generic failure, are failures.
20382
+ const outcome = (error instanceof AuthError
19271
20383
  || error instanceof plugins.typedrequest.TypedResponseError
19272
20384
  || error instanceof ControllerWorkspaceError
19273
- || error instanceof ConfigurationError
20385
+ || error instanceof ConfigurationError)
20386
+ && !(error instanceof plugins.typedrequest.TypedResponseError
20387
+ && (error.errorData?.code === 'direct_report_failed' || error.errorData?.code === controllerOperationFailedErrorCode))
19274
20388
  ? 'denied'
19275
20389
  : 'failed';
19276
20390
  const suppressUnboundedDenialAudit = error instanceof AuthError
@@ -19301,7 +20415,7 @@ export class OpenCodeController {
19301
20415
  try {
19302
20416
  await this.requireAuthStore().recordAuditEvent({
19303
20417
  ...correlatedAudit,
19304
- outcome: 'succeeded',
20418
+ outcome: outcomeOfArg(result),
19305
20419
  });
19306
20420
  } catch {
19307
20421
  // The durable attempted record preserves the audit gap. The completed
@@ -20292,6 +21406,7 @@ export class OpenCodeController {
20292
21406
  reading,
20293
21407
  account.maxUsagePercent,
20294
21408
  account.lapsesAt,
21409
+ account.renewsAt,
20295
21410
  now,
20296
21411
  account.reserveLiftUntil,
20297
21412
  );
@@ -23525,6 +24640,80 @@ export class OpenCodeController {
23525
24640
  });
23526
24641
  }
23527
24642
 
24643
+ /**
24644
+ * The requests that wait in a managed OpenCode root conversation and in its direct children, from the controller's
24645
+ * own reads (OpenCode's pending lists and the root's direct children), whichever browser has the conversation open:
24646
+ * the root's own requests, and each direct child with requests, the most recently updated first. `strictArg` lets a
24647
+ * failed pending list fail the read instead of reading as empty.
24648
+ */
24649
+ private async readOpenCodeFamilyAttention(
24650
+ projectIdArg: string,
24651
+ parentSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
24652
+ signalArg: AbortSignal,
24653
+ strictArg = false,
24654
+ ): Promise<{
24655
+ parent: IOpenCodeManagedSessionScopeAuthority;
24656
+ own: { permissions: IControllerPermission[]; questions: IControllerQuestion[] };
24657
+ children: Array<{ child: IOpenCodeDirectChildObservation; permissions: IControllerPermission[]; questions: IControllerQuestion[] }>;
24658
+ } | undefined> {
24659
+ const parent = await this.readManagedOpenCodeScopeAuthority(
24660
+ projectIdArg,
24661
+ parentSessionIdArg,
24662
+ signalArg,
24663
+ );
24664
+ if (parent.session.parentId !== undefined || parent.session.archivedAt !== undefined) return undefined;
24665
+ const signal = AbortSignal.any([signalArg, parent.runtimeAuthority.signal]);
24666
+ const permissionsRead = parent.client.listPermissions(parent.project.directory, undefined, signal);
24667
+ const questionsRead = parent.client.listQuestions(parent.project.directory, undefined, signal);
24668
+ const [children, pending] = await Promise.all([
24669
+ parent.client.listDirectChildSessionObservations(
24670
+ parent.project.directory,
24671
+ parentSessionIdArg.nativeId,
24672
+ signal,
24673
+ ),
24674
+ strictArg
24675
+ ? Promise.all([permissionsRead, questionsRead]).then(([permissions, questions]) => ({ permissions, questions }))
24676
+ : settleControllerAttentionLists(permissionsRead, questionsRead),
24677
+ ]);
24678
+ this.assertOpenCodeSessionIdentityGenerationCurrent(
24679
+ parent.supervisor,
24680
+ parent.client,
24681
+ parent.runtimeAuthority,
24682
+ );
24683
+ this.assertChildScopeParentAdmission(projectIdArg, parentSessionIdArg);
24684
+
24685
+ const permissionsBySession = new Map<string, IControllerPermission[]>();
24686
+ for (const permission of pending.permissions) {
24687
+ const key = controllerRuntimeIdKey(permission.sessionId);
24688
+ const entries = permissionsBySession.get(key) ?? [];
24689
+ entries.push(permission);
24690
+ permissionsBySession.set(key, entries);
24691
+ }
24692
+ const questionsBySession = new Map<string, IControllerQuestion[]>();
24693
+ for (const question of pending.questions) {
24694
+ const key = controllerRuntimeIdKey(question.sessionId);
24695
+ const entries = questionsBySession.get(key) ?? [];
24696
+ entries.push(question);
24697
+ questionsBySession.set(key, entries);
24698
+ }
24699
+ const parentKey = controllerRuntimeIdKey(parentSessionIdArg);
24700
+ return {
24701
+ parent,
24702
+ own: { permissions: permissionsBySession.get(parentKey) ?? [], questions: questionsBySession.get(parentKey) ?? [] },
24703
+ children: children
24704
+ .flatMap((childArg) => {
24705
+ const key = controllerRuntimeIdKey(childArg.session.id);
24706
+ const permissions = permissionsBySession.get(key) ?? [];
24707
+ const questions = questionsBySession.get(key) ?? [];
24708
+ return permissions.length > 0 || questions.length > 0 ? [{ child: childArg, permissions, questions }] : [];
24709
+ })
24710
+ .sort((leftArg, rightArg) => (
24711
+ rightArg.child.session.updatedAt - leftArg.child.session.updatedAt
24712
+ || leftArg.child.session.id.nativeId.localeCompare(rightArg.child.session.id.nativeId)
24713
+ )),
24714
+ };
24715
+ }
24716
+
23528
24717
  private async readBrowserChildAttention(
23529
24718
  peerArg: IControllerPeer,
23530
24719
  projectIdArg: string,
@@ -23532,62 +24721,13 @@ export class OpenCodeController {
23532
24721
  signalArg: AbortSignal,
23533
24722
  ): Promise<Pick<IReq_ControllerSessionGet['response'], 'childAttention' | 'childAttentionLimited'>> {
23534
24723
  try {
23535
- const parent = await this.readManagedOpenCodeScopeAuthority(
23536
- projectIdArg,
23537
- parentSessionIdArg,
23538
- signalArg,
23539
- );
23540
- if (parent.session.parentId !== undefined || parent.session.archivedAt !== undefined) return {};
23541
- const signal = AbortSignal.any([signalArg, parent.runtimeAuthority.signal]);
23542
- const [children, pending] = await Promise.all([
23543
- parent.client.listDirectChildSessionObservations(
23544
- parent.project.directory,
23545
- parentSessionIdArg.nativeId,
23546
- signal,
23547
- ),
23548
- settleControllerAttentionLists(
23549
- parent.client.listPermissions(parent.project.directory, undefined, signal),
23550
- parent.client.listQuestions(parent.project.directory, undefined, signal),
23551
- ),
23552
- ]);
23553
- this.assertOpenCodeSessionIdentityGenerationCurrent(
23554
- parent.supervisor,
23555
- parent.client,
23556
- parent.runtimeAuthority,
23557
- );
23558
- this.assertChildScopeParentAdmission(projectIdArg, parentSessionIdArg);
23559
-
23560
- const permissionsBySession = new Map<string, IControllerPermission[]>();
23561
- for (const permission of pending.permissions) {
23562
- const key = controllerRuntimeIdKey(permission.sessionId);
23563
- const entries = permissionsBySession.get(key) ?? [];
23564
- entries.push(permission);
23565
- permissionsBySession.set(key, entries);
23566
- }
23567
- const questionsBySession = new Map<string, IControllerQuestion[]>();
23568
- for (const question of pending.questions) {
23569
- const key = controllerRuntimeIdKey(question.sessionId);
23570
- const entries = questionsBySession.get(key) ?? [];
23571
- entries.push(question);
23572
- questionsBySession.set(key, entries);
23573
- }
23574
- const candidates = children
23575
- .filter((childArg) => {
23576
- const key = controllerRuntimeIdKey(childArg.session.id);
23577
- return (permissionsBySession.get(key)?.length ?? 0) > 0
23578
- || (questionsBySession.get(key)?.length ?? 0) > 0;
23579
- })
23580
- .sort((leftArg, rightArg) => (
23581
- rightArg.session.updatedAt - leftArg.session.updatedAt
23582
- || leftArg.session.id.nativeId.localeCompare(rightArg.session.id.nativeId)
23583
- ));
24724
+ const family = await this.readOpenCodeFamilyAttention(projectIdArg, parentSessionIdArg, signalArg);
24725
+ if (!family) return {};
24726
+ const candidates = family.children;
23584
24727
  let limited = candidates.length > maxChildAttentionChildren
23585
- || candidates.reduce((countArg, childArg) => {
23586
- const key = controllerRuntimeIdKey(childArg.session.id);
23587
- return countArg
23588
- + (permissionsBySession.get(key)?.length ?? 0)
23589
- + (questionsBySession.get(key)?.length ?? 0);
23590
- }, 0) > maxChildAttentionItems;
24728
+ || candidates.reduce((countArg, candidateArg) => (
24729
+ countArg + candidateArg.permissions.length + candidateArg.questions.length
24730
+ ), 0) > maxChildAttentionItems;
23591
24731
  const childAttention: IControllerChildAttention[] = [];
23592
24732
  let itemCount = 0;
23593
24733
  for (const candidate of candidates.slice(0, maxChildAttentionChildren)) {
@@ -23597,7 +24737,7 @@ export class OpenCodeController {
23597
24737
  detail = await this.openChildScope(peerArg, {
23598
24738
  projectId: projectIdArg,
23599
24739
  parentSessionId: parentSessionIdArg,
23600
- childSessionId: candidate.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
24740
+ childSessionId: candidate.child.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
23601
24741
  }, signalArg);
23602
24742
  } catch {
23603
24743
  signalArg.throwIfAborted();
@@ -36065,6 +37205,7 @@ export class OpenCodeController {
36065
37205
  private async pushControllerEvent(eventArg: IControllerEvent): Promise<void> {
36066
37206
  this.driverService?.observe(eventArg);
36067
37207
  this.sessionFeed?.observe(eventArg);
37208
+ this.inbox?.observe(eventArg);
36068
37209
  const browsers = this.controllerEventDeliveryQueues().push(eventArg);
36069
37210
  // A device receives an allowlist of events in its own reduced shape (`deviceEvent`), through queues of its own.
36070
37211
  if (this.devices?.hasLivePeers() === true && deviceRelayedEventTypes.has(eventArg.type)) {
@@ -36090,14 +37231,23 @@ export class OpenCodeController {
36090
37231
  ));
36091
37232
  return targets.map((targetArg) => ({
36092
37233
  peerId: targetArg.peer.id,
37234
+ // One queued controller event may be several device events: each is sent in order, as the queue sends its
37235
+ // events, every one attempted though one before it was not acknowledged; the first failure is the send's.
36093
37236
  send: async (eventArg: IControllerEvent) => {
36094
- const event = deviceEvent(eventArg, (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg));
36095
- if (event === undefined || devices.deviceIdOf(targetArg.peer) === undefined) return;
36096
- await typedSocket.createTypedRequest<IReq_DeviceEventPush>(
36097
- 'device.event',
36098
- targetArg,
36099
- { timeoutMs: 2_000 },
36100
- ).fire({ event }, { timeoutMs: 2_000, maxRetries: 0 });
37237
+ let failure: { error: unknown } | undefined;
37238
+ for (const event of deviceEvent(eventArg, (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg), this.driverService)) {
37239
+ if (devices.deviceIdOf(targetArg.peer) === undefined) break;
37240
+ try {
37241
+ await typedSocket.createTypedRequest<IReq_DeviceEventPush>(
37242
+ 'device.event',
37243
+ targetArg,
37244
+ { timeoutMs: 2_000 },
37245
+ ).fire({ event }, { timeoutMs: 2_000, maxRetries: 0 });
37246
+ } catch (errorArg) {
37247
+ failure ??= { error: errorArg };
37248
+ }
37249
+ }
37250
+ if (failure !== undefined) throw failure.error;
36101
37251
  },
36102
37252
  }));
36103
37253
  },