agl 43.2.0 → 43.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/changelog.md +20 -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.claudeharness.d.ts +16 -0
  11. package/dist_ts/classes.claudeharness.js +24 -2
  12. package/dist_ts/classes.codexclientadapter.d.ts +11 -0
  13. package/dist_ts/classes.codexclientadapter.js +14 -2
  14. package/dist_ts/classes.controller.d.ts +165 -11
  15. package/dist_ts/classes.controller.js +1095 -170
  16. package/dist_ts/classes.controllerdevices.d.ts +2 -0
  17. package/dist_ts/classes.controllerdevices.js +6 -1
  18. package/dist_ts/classes.inbox.d.ts +72 -0
  19. package/dist_ts/classes.inbox.js +231 -0
  20. package/dist_ts/classes.inferencerouter.d.ts +10 -0
  21. package/dist_ts/classes.inferencerouter.js +5 -3
  22. package/dist_ts/classes.inferenceservice.js +2 -2
  23. package/dist_ts/classes.mcpclient.d.ts +1 -1
  24. package/dist_ts/classes.mcpclient.js +24 -6
  25. package/dist_ts/classes.mcpcontrollerhost.js +3 -1
  26. package/dist_ts/classes.mcptools.js +13 -8
  27. package/dist_ts/classes.mcpvalidation.d.ts +5 -0
  28. package/dist_ts/classes.mcpvalidation.js +32 -2
  29. package/dist_ts/classes.nativesessions.d.ts +17 -4
  30. package/dist_ts/classes.nativesessions.js +41 -9
  31. package/dist_ts/classes.opencodeclient.d.ts +23 -2
  32. package/dist_ts/classes.opencodeclient.js +47 -3
  33. package/dist_ts/classes.publishedset.d.ts +38 -0
  34. package/dist_ts/classes.publishedset.js +50 -0
  35. package/dist_ts/classes.sessionfeed.d.ts +3 -3
  36. package/dist_ts/classes.sessionfeed.js +18 -26
  37. package/dist_ts/classes.systemmetricssampler.d.ts +6 -0
  38. package/dist_ts/classes.systemmetricssampler.js +15 -3
  39. package/dist_ts/classes.ticketstore.d.ts +50 -3
  40. package/dist_ts/classes.ticketstore.js +45 -8
  41. package/dist_ts/driver/classes.directreports.d.ts +14 -4
  42. package/dist_ts/driver/classes.directreports.js +25 -6
  43. package/dist_ts/driver/classes.driverservice.d.ts +44 -3
  44. package/dist_ts/driver/classes.driverservice.js +50 -16
  45. package/dist_ts/fleet/classes.claudeworkers.d.ts +21 -5
  46. package/dist_ts/fleet/classes.claudeworkers.js +142 -46
  47. package/dist_ts/fleet/classes.codexworkers.d.ts +16 -4
  48. package/dist_ts/fleet/classes.codexworkers.js +22 -5
  49. package/dist_ts/fleet/classes.workercommand.d.ts +6 -1
  50. package/dist_ts/fleet/classes.workercommand.js +15 -4
  51. package/dist_ts/fleet/classes.workers.d.ts +5 -1
  52. package/dist_ts/fleet/classes.workers.js +8 -2
  53. package/dist_ts/fleet/functions.unbounddrivers.js +2 -2
  54. package/dist_ts/fleet/functions.workervalidation.js +2 -2
  55. package/dist_ts/fleet/interfaces.workers.d.ts +21 -3
  56. package/dist_ts/fleet/interfaces.workers.js +1 -1
  57. package/dist_ts/functions.agentmessage.d.ts +3 -0
  58. package/dist_ts/functions.agentmessage.js +4 -1
  59. package/dist_ts/functions.deviceapi.d.ts +151 -4
  60. package/dist_ts/functions.deviceapi.js +893 -38
  61. package/dist_ts/functions.fleetworkercli.d.ts +1 -1
  62. package/dist_ts/functions.fleetworkercli.js +11 -8
  63. package/dist_ts/functions.inferencecli.js +3 -1
  64. package/dist_ts/functions.mcpfleetworkertools.js +2 -2
  65. package/dist_ts/functions.ticketvalidation.js +11 -2
  66. package/dist_ts/interfaces.auth.d.ts +1 -1
  67. package/dist_ts/interfaces.auth.js +9 -1
  68. package/dist_ts/plugins.d.ts +3 -1
  69. package/dist_ts/plugins.js +7 -2
  70. package/dist_ts_authswitch/authority-contract.d.ts +25 -0
  71. package/dist_ts_authswitch/authority-contract.js +1 -1
  72. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  73. package/dist_ts_authswitch/authority-overview.js +17 -6
  74. package/dist_ts_authswitch/authority-placement.d.ts +20 -16
  75. package/dist_ts_authswitch/authority-placement.js +17 -10
  76. package/dist_ts_authswitch/authority-renewal.d.ts +34 -0
  77. package/dist_ts_authswitch/authority-renewal.js +56 -0
  78. package/dist_ts_authswitch/classes.authoritybroker.d.ts +8 -0
  79. package/dist_ts_authswitch/classes.authoritybroker.js +35 -2
  80. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  81. package/dist_ts_authswitch/classes.authoritycli.js +44 -3
  82. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  83. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  84. package/dist_ts_authswitch/classes.authoritydaemon.js +8 -1
  85. package/dist_ts_authswitch/classes.authoritydatabase.js +6 -2
  86. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  87. package/dist_ts_authswitch/classes.authoritymodels.js +21 -5
  88. package/dist_ts_interfaces/devices.d.ts +1012 -5
  89. package/dist_ts_interfaces/devices.js +68 -2
  90. package/dist_ts_interfaces/fleetworkers.d.ts +5 -3
  91. package/dist_ts_interfaces/inbox.d.ts +234 -0
  92. package/dist_ts_interfaces/inbox.js +101 -0
  93. package/dist_ts_interfaces/index.d.ts +1 -0
  94. package/dist_ts_interfaces/index.js +2 -1
  95. package/dist_ts_interfaces/interfaces.d.ts +10 -3
  96. package/dist_ts_interfaces/interfaces.js +4 -2
  97. package/dist_ts_interfaces/mcprequests.d.ts +34 -4
  98. package/dist_ts_interfaces/mcprequests.js +11 -1
  99. package/dist_ts_interfaces/mcpworkspacerequests.d.ts +4 -1
  100. package/dist_ts_interfaces/mcpworkspacerequests.js +1 -1
  101. package/dist_ts_interfaces/nativesessions.d.ts +16 -3
  102. package/dist_ts_interfaces/plugins.d.ts +2 -1
  103. package/dist_ts_interfaces/plugins.js +4 -2
  104. package/dist_ts_interfaces/requests.accounts.d.ts +21 -0
  105. package/dist_ts_interfaces/requests.accounts.js +3 -1
  106. package/dist_ts_interfaces/requests.d.ts +3 -2
  107. package/dist_ts_interfaces/requests.js +1 -1
  108. package/docs/authswitch.md +20 -1
  109. package/package.json +3 -3
  110. package/readme.md +112 -26
  111. package/ts/00_commitinfo_data.ts +1 -1
  112. package/ts/aglapi/aglapisurface.document.ts +196 -16
  113. package/ts/classes.accountsactions.ts +30 -3
  114. package/ts/classes.claudeharness.ts +27 -1
  115. package/ts/classes.codexclientadapter.ts +14 -1
  116. package/ts/classes.controller.ts +1294 -246
  117. package/ts/classes.controllerdevices.ts +6 -0
  118. package/ts/classes.inbox.ts +239 -0
  119. package/ts/classes.inferencerouter.ts +15 -2
  120. package/ts/classes.inferenceservice.ts +1 -1
  121. package/ts/classes.mcpclient.ts +24 -3
  122. package/ts/classes.mcpcontrollerhost.ts +2 -0
  123. package/ts/classes.mcptools.ts +12 -7
  124. package/ts/classes.mcpvalidation.ts +27 -1
  125. package/ts/classes.nativesessions.ts +50 -12
  126. package/ts/classes.opencodeclient.ts +55 -4
  127. package/ts/classes.publishedset.ts +56 -0
  128. package/ts/classes.sessionfeed.ts +17 -20
  129. package/ts/classes.systemmetricssampler.ts +13 -2
  130. package/ts/classes.ticketstore.ts +73 -12
  131. package/ts/driver/classes.directreports.ts +25 -6
  132. package/ts/driver/classes.driverservice.ts +75 -14
  133. package/ts/fleet/classes.claudeworkers.ts +112 -39
  134. package/ts/fleet/classes.codexworkers.ts +21 -6
  135. package/ts/fleet/classes.workercommand.ts +14 -4
  136. package/ts/fleet/classes.workers.ts +9 -2
  137. package/ts/fleet/functions.unbounddrivers.ts +1 -1
  138. package/ts/fleet/functions.workervalidation.ts +1 -1
  139. package/ts/fleet/interfaces.workers.ts +20 -5
  140. package/ts/functions.agentmessage.ts +3 -0
  141. package/ts/functions.deviceapi.ts +1071 -34
  142. package/ts/functions.fleetworkercli.ts +10 -7
  143. package/ts/functions.inferencecli.ts +2 -0
  144. package/ts/functions.mcpfleetworkertools.ts +1 -1
  145. package/ts/functions.ticketvalidation.ts +11 -1
  146. package/ts/interfaces.auth.ts +8 -0
  147. package/ts/plugins.ts +7 -0
  148. package/ts_authswitch/authority-contract.ts +20 -0
  149. package/ts_authswitch/authority-overview.ts +28 -6
  150. package/ts_authswitch/authority-placement.ts +25 -17
  151. package/ts_authswitch/authority-renewal.ts +64 -0
  152. package/ts_authswitch/classes.authoritybroker.ts +34 -1
  153. package/ts_authswitch/classes.authoritycli.ts +49 -2
  154. package/ts_authswitch/classes.authorityclient.ts +14 -4
  155. package/ts_authswitch/classes.authoritydaemon.ts +9 -1
  156. package/ts_authswitch/classes.authoritydatabase.ts +5 -1
  157. package/ts_authswitch/classes.authoritymodels.ts +23 -3
  158. package/ts_authswitch/native-contracts.md +21 -0
  159. package/ts_authswitch/readme.md +1 -1
  160. package/ts_interfaces/devices.schema.json +3573 -603
  161. package/ts_interfaces/devices.ts +1093 -4
  162. package/ts_interfaces/fleetworkers.ts +5 -3
  163. package/ts_interfaces/inbox.ts +287 -0
  164. package/ts_interfaces/index.ts +1 -0
  165. package/ts_interfaces/interfaces.ts +9 -2
  166. package/ts_interfaces/mcprequests.ts +43 -4
  167. package/ts_interfaces/mcpworkspacerequests.ts +4 -2
  168. package/ts_interfaces/nativesessions.ts +17 -3
  169. package/ts_interfaces/plugins.ts +3 -1
  170. package/ts_interfaces/requests.accounts.ts +20 -0
  171. package/ts_interfaces/requests.ts +4 -0
  172. package/ts_web/00_commitinfo_data.ts +1 -1
  173. package/ts_web/accounts.plugins.ts +4 -2
  174. package/ts_web/classes.accountsreadmodel.ts +33 -0
  175. package/ts_web/classes.browserpresentation.ts +10 -5
  176. package/ts_web/classes.inboxfeed.ts +329 -0
  177. package/ts_web/classes.nativesessionstate.ts +9 -23
  178. package/ts_web/elements.accounts.ts +81 -0
  179. package/ts_web/elements.deployments.ts +66 -2
  180. package/ts_web/elements.harnesscontrollerapp.ts +107 -37
  181. package/ts_web/elements.inbox.ts +808 -0
  182. package/ts_web/functions.inbox.ts +95 -0
  183. package/ts_web/functions.sessioncards.ts +40 -0
  184. package/ts_web/plugins.ts +2 -0
@@ -109,7 +109,36 @@ import {
109
109
  deviceRelayedEventTypes,
110
110
  deviceSessionRow,
111
111
  deviceSessionRows,
112
+ deviceInboxList,
113
+ deviceTicketQuestion,
114
+ deviceDriverStatus,
115
+ deviceDirectReport,
116
+ assertDeviceTicketAnswerRequest,
117
+ assertDeviceDriverReadRequest,
118
+ assertDeviceDriverSendRequest,
119
+ assertDeviceDirectReportMessageRequest,
120
+ serveDeviceDriver,
121
+ deviceDirectReportMessageRefusal,
122
+ deviceHostAgl,
123
+ deviceHostDevice,
124
+ readDeviceHostSections,
125
+ assertDeviceBoardListRequest,
126
+ assertDeviceTicketGetRequest,
127
+ assertDeviceTicketCommentRequest,
128
+ assertDeviceTicketAskRequest,
129
+ assertDeviceTicketMoveRequest,
130
+ deviceBoardPage,
131
+ deviceTicket,
132
+ deviceTicketCard,
133
+ deviceTicketComment,
134
+ deviceTicketDiscussion,
135
+ deviceTicketPlans,
136
+ deviceTicketRefusal,
137
+ readDeviceTicketPlacement,
138
+ type IDeviceTicketViewer,
112
139
  } from './functions.deviceapi.js';
140
+ import { ControllerInbox, inboxTitle, type TInboxSource } from './classes.inbox.js';
141
+ import { compareFleetVersions } from '../ts_interfaces/functions.fleetversion.js';
113
142
  import {
114
143
  controllerPackageName,
115
144
  controllerBuiltinCommands,
@@ -348,6 +377,10 @@ import {
348
377
  type IReq_ControllerSystemMetricsHistory,
349
378
  type IReq_ControllerMcpProjectsList,
350
379
  type IReq_ControllerMcpSessionRead,
380
+ type IControllerMcpNativeSessionDetail,
381
+ type TControllerMcpSessionDetail,
382
+ controllerMcpNativeDeliveries,
383
+ controllerMcpNativeSessionSettledLimit,
351
384
  type IReq_ControllerMcpSessionScratchpadRead,
352
385
  type IReq_ControllerMcpSessionScratchpadUpdate,
353
386
  type IReq_ControllerMcpSessionSend,
@@ -374,7 +407,29 @@ import {
374
407
  type IReq_DeviceSessionRead,
375
408
  type IReq_DeviceSessionSend,
376
409
  type IReq_DeviceSessionsList,
410
+ type IReq_DeviceInboxList,
411
+ type IReq_DeviceTicketAnswer,
412
+ type IReq_DeviceDriverGet,
413
+ type IReq_DeviceDriverSeen,
414
+ type IReq_DeviceDriverRead,
415
+ type IReq_DeviceDriverSend,
416
+ type IReq_DeviceDirectReportsList,
417
+ type IReq_DeviceDirectReportMessage,
418
+ type IReq_DeviceHostGet,
419
+ type IReq_DeviceBoardList,
420
+ type IReq_DeviceTicketGet,
421
+ type IReq_DeviceTicketComment,
422
+ type IReq_DeviceTicketAsk,
423
+ type IReq_DeviceTicketMove,
377
424
  type IControllerSessionFeedRow,
425
+ type IReq_ControllerInboxList,
426
+ type TControllerInboxAnswer,
427
+ type TControllerElicitation,
428
+ type TControllerInboxItem,
429
+ type TControllerInboxWhere,
430
+ type TControllerSessionFeedHarness,
431
+ type IFleetDeployStatus,
432
+ controllerInboxLimits,
378
433
  deviceProtocolVersion,
379
434
  deviceRevokedCloseCode,
380
435
  type IControllerProviderAccountRateLimits,
@@ -520,16 +575,17 @@ import { FleetService } from './fleet/classes.service.js';
520
575
  import type { IFleetConfiguration, IFleetDriverConfiguration, IFleetOperation, IFleetScope, IFleetUnboundDriver, TFleetOperation, TFleetRequest } from '../ts_interfaces/fleet.js';
521
576
  import { findFleetRepository, fleetRepositorySlug } from './fleet/functions.releasefacts.js';
522
577
  import { discoverFleetRepositories } from './fleet/functions.discovery.js';
523
- import { DriverError, DriverService } from './driver/classes.driverservice.js';
578
+ import { DriverError, DriverService, type IDriverAssistantMessage } from './driver/classes.driverservice.js';
524
579
  import { DriverEventRelay, driverRelayMaximumMessageBytes } from './driver/classes.drivereventrelay.js';
525
- import { DirectReports, type TDirectReportChannel } from './driver/classes.directreports.js';
580
+ import { DirectReports, directReportRuntimeId, type TDirectReportChannel } from './driver/classes.directreports.js';
526
581
  import { driverToolsByName, driverDirectReportReadDefaultLimit, type TDriverDirectReportOperation } from './driver/functions.drivertools.js';
527
- import { controllerDriverErrorCodes } from '../ts_interfaces/driver.js';
582
+ import { controllerDriverErrorCodes, type IControllerDriverStatus } from '../ts_interfaces/driver.js';
528
583
  import type { IReq_ControllerDriverEnsure, IReq_ControllerDriverGet, IReq_ControllerDriverSeen } from '../ts_interfaces/requests.driver.js';
529
584
  import type { IReq_ControllerFleetWorkerList, IReq_ControllerFleetWorkerRead, IReq_ControllerFleetWorkerSteer } from '../ts_interfaces/requests.fleetworkers.js';
530
585
  import type {
531
586
  IControllerNativeSession,
532
587
  IControllerNativeSessionRef,
588
+ TControllerNativeJobDelivery,
533
589
  IReq_ControllerNativeSessionAuxiliaryGet,
534
590
  IReq_ControllerNativeSessionIntelligenceAsk,
535
591
  IReq_ControllerNativeSessionPermissionReply,
@@ -541,19 +597,19 @@ import type {
541
597
  } from '../ts_interfaces/nativesessions.js';
542
598
  import { ControllerUploadManager, type IControllerUploadHandle } from './classes.uploadmanager.js';
543
599
  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';
600
+ import { SessionFeed, SessionFeedAcknowledgementError, SessionFeedTranscripts, sessionFeedRowId, type ISessionFeedTerminal, type TSessionFeedProjectRead } from './classes.sessionfeed.js';
545
601
  import { SessionFeedAcknowledgementStore } from './classes.sessionfeedacknowledgements.js';
546
602
  import { HarnessReleaseNotices, type THarnessReleaseSource } from './classes.harnessreleases.js';
547
603
  import { assertSessionFeedAcknowledgeRequest } from './functions.sessionfeedvalidation.js';
548
- import { NativeSessions, type IResolvedNativeSession } from './classes.nativesessions.js';
604
+ import { NativeSessions, nativeSessionReadOnlyMessages, type IResolvedNativeSession } from './classes.nativesessions.js';
549
605
  import { claudeProfileForHome, fleetAdoptCommand, listUnboundDrivers } from './fleet/functions.unbounddrivers.js';
550
606
  import type { IReq_ControllerSessionFeedAcknowledge, IReq_ControllerSessionFeedList } from '../ts_interfaces/sessionfeed.js';
551
607
  import { UsageFeed, UsageFeedRefusal } from './classes.usagefeed.js';
552
608
  import type { IReq_ControllerUsageUnwatch, IReq_ControllerUsageWatch, TControllerUsageDelta } from '../ts_interfaces/metrics.js';
553
609
  import { ticketActorFromCaller } from './functions.ticketactor.js';
554
610
  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';
611
+ import { assertTicketRequest, ticketInputSchemas } from './functions.ticketvalidation.js';
612
+ import { readTicketRevisionConflict, type ITicket, type ITicketActor, type ITicketBoard, type ITicketComment, type ITicketDetail, type TTicketOperation, type TTicketRequest, type TTicketResponse, type TTicketFleetEvent, type ITicketFleetEventResult } from '../ts_interfaces/tickets.js';
557
613
  import type { TControllerTicketRequest } from '../ts_interfaces/requests.tickets.js';
558
614
  import { ControllerJobSupervisor } from './classes.jobsupervisor.js';
559
615
  import {
@@ -2434,6 +2490,23 @@ const assertNativeSessionWritable = (resolvedArg: IResolvedNativeSession): void
2434
2490
  const { readOnly } = resolvedArg.session;
2435
2491
  if (readOnly) throw new plugins.typedrequest.TypedResponseError(readOnly.message, { code: 'session_read_only' });
2436
2492
  };
2493
+ /**
2494
+ * A Claude Code session outside AGL as an MCP caller sees it: agents reach only background jobs, so any other session
2495
+ * that would take the owner's message is read-only for them (`notBackgroundJob`).
2496
+ */
2497
+ const mcpNativeSession = (resolvedArg: IResolvedNativeSession): IControllerNativeSession => (
2498
+ resolvedArg.claudeJob || resolvedArg.session.readOnly ? resolvedArg.session
2499
+ : { ...resolvedArg.session, readOnly: { reason: 'notBackgroundJob', message: nativeSessionReadOnlyMessages.notBackgroundJob } }
2500
+ );
2501
+ /** Refuses an MCP agent message to a Claude Code session outside AGL that takes none now, naming why. */
2502
+ const assertMcpNativeMessageable = (sessionArg: IControllerNativeSession): void => {
2503
+ if (sessionArg.readOnly) throw new plugins.typedrequest.TypedResponseError(sessionArg.readOnly.message, { code: 'session_read_only' });
2504
+ if (!sessionArg.jobDelivery) throw new plugins.typedrequest.TypedResponseError(nativeSessionReadOnlyMessages.notBackgroundJob, { code: 'session_read_only' });
2505
+ };
2506
+ /** The canonical path of an existing directory, or `undefined`; a session's directory matches a project's only so. */
2507
+ const canonicalDirectory = async (pathArg: string): Promise<string | undefined> => {
2508
+ try { return await plugins.fs.promises.realpath(pathArg); } catch { return undefined; }
2509
+ };
2437
2510
  /**
2438
2511
  * A harness's refusal of an elicitation reply -- the answer does not fit the request, or the request is gone -- as the
2439
2512
  * typed refusal it is; its text never carries what the owner entered. Every other error passes as it is.
@@ -2444,6 +2517,14 @@ const elicitationRefusal = (errorArg: unknown): unknown => (
2444
2517
  : errorArg
2445
2518
  );
2446
2519
 
2520
+ /** The ticket changes the owner makes from the browser's board or a paired device, each with its audit type. */
2521
+ type TTicketChangeOperation = 'comment' | 'ask' | 'move';
2522
+ const ticketChangeAuditTypes = {
2523
+ comment: 'ticket.comment',
2524
+ ask: 'ticket.ask',
2525
+ move: 'ticket.move',
2526
+ } as const satisfies Record<TTicketChangeOperation, TControllerAuditEventType>;
2527
+
2447
2528
  const validateRequest = <T>(validatorArg: () => T): T => {
2448
2529
  try {
2449
2530
  return validatorArg();
@@ -3231,6 +3312,8 @@ export class OpenCodeController {
3231
3312
  this.fleetWorkers = new FleetWorkers({ sample: () => this.systemMetricsSampler.sample(), ticketEffects: this.requireFleetTicketEffects(), sessionBindings: directReports,
3232
3313
  nativeMessages: { send: (_owner, request, actor) => this.sendFleetNativeMessage(request, actor) },
3233
3314
  claudeReleases: (releaseArg) => this.observeClaudeRelease(releaseArg, 'fleet'),
3315
+ // No controller event names a native thread; the Inbox reads the fleet connection's requests again.
3316
+ onNativeCodexAttention: () => this.inbox?.nativeAttentionChanged('codex'),
3234
3317
  ...(this.fleetWorkerLaunches ? { callers: this.fleetWorkerLaunches } : {}) });
3235
3318
  // The Driver view's direct reports, an open fleet worker and the session feed follow worker changes and newly observed statuses.
3236
3319
  this.fleetWorkers.watchViews(() => {
@@ -3422,6 +3505,314 @@ export class OpenCodeController {
3422
3505
  });
3423
3506
  this.sessionFeed.start();
3424
3507
  }
3508
+ /** What waits for the owner, for the browser and devices alike (AGL-1635). */
3509
+ private inbox?: ControllerInbox;
3510
+ private startInbox(): void {
3511
+ if (this.inbox) return;
3512
+ this.inbox = new ControllerInbox({
3513
+ read: (sourceArg, previousArg, signalArg) => this.readInboxSource(sourceArg, previousArg, signalArg),
3514
+ hasViewers: async () => this.devices?.hasLivePeers() === true || (await this.controllerEventViewers()).length > 0,
3515
+ publish: (deltaArg) => {
3516
+ void this.pushControllerEvent({ type: 'inbox.changed', inbox: deltaArg, timestamp: Date.now() }).catch(() => undefined);
3517
+ },
3518
+ reportError: (messageArg, errorArg) => console.error(messageArg, errorArg),
3519
+ });
3520
+ }
3521
+
3522
+ /** The Inbox's items of one source, each read from the component that owns them. */
3523
+ private async readInboxSource(
3524
+ sourceArg: TInboxSource,
3525
+ previousArg: readonly TControllerInboxItem[],
3526
+ signalArg: AbortSignal,
3527
+ ): Promise<TControllerInboxItem[]> {
3528
+ switch (sourceArg) {
3529
+ case 'claude': return this.readInboxClaude();
3530
+ case 'codex': return this.readInboxCodex();
3531
+ case 'opencode': return this.readInboxOpenCode(previousArg, signalArg);
3532
+ case 'flex': return this.readInboxFlex(previousArg, signalArg);
3533
+ case 'native_waits': return this.readInboxNativeWaits();
3534
+ case 'driver': return this.readInboxDriver();
3535
+ case 'tickets': return this.readInboxTickets(signalArg);
3536
+ }
3537
+ }
3538
+
3539
+ /** The session feed's row of a session, and the name the Inbox shows for it. */
3540
+ private inboxRow(harnessArg: TControllerSessionFeedHarness, nativeIdArg: string, fallbackNameArg: string): { rowId: string; name: string } {
3541
+ const rowId = sessionFeedRowId(harnessArg, nativeIdArg);
3542
+ return { rowId, name: this.sessionFeed?.publishedRow(rowId)?.name ?? (fallbackNameArg.trim() || 'Untitled session') };
3543
+ }
3544
+
3545
+ /**
3546
+ * The items of a session's requests. A permission that the owner's auto-accept answers (`autoAcceptedArg`) waits for
3547
+ * nobody and is left out; questions and MCP forms are never answered automatically.
3548
+ */
3549
+ private inboxSessionItems(
3550
+ whereArg: Extract<TControllerInboxWhere, { kind: 'conversation' | 'child' | 'native' | 'driver' }>,
3551
+ answerArg: TControllerInboxAnswer,
3552
+ attentionArg: { permissions: readonly IControllerPermission[]; questions: readonly IControllerQuestion[]; elicitations?: readonly TControllerElicitation[] },
3553
+ autoAcceptedArg = false,
3554
+ ): TControllerInboxItem[] {
3555
+ const id = (kindArg: string, requestArg: { id: IControllerRuntimeId }, sessionArg: IControllerRuntimeId) => (
3556
+ `${kindArg}:${sessionArg.harnessId}:${sessionArg.nativeId}:${requestArg.id.nativeId}`
3557
+ );
3558
+ return [
3559
+ ...(autoAcceptedArg ? [] : attentionArg.permissions).map((permissionArg): TControllerInboxItem => ({
3560
+ id: id('permission', permissionArg, permissionArg.sessionId), kind: 'permission', since: permissionArg.createdAt,
3561
+ title: inboxTitle(permissionArg.title || permissionArg.type), where: whereArg, answer: answerArg, permission: permissionArg,
3562
+ })),
3563
+ ...attentionArg.questions.map((questionArg): TControllerInboxItem => ({
3564
+ id: id('question', questionArg, questionArg.sessionId), kind: 'question', since: questionArg.createdAt,
3565
+ title: inboxTitle(questionArg.questions[0]?.question || questionArg.questions[0]?.header || 'A question'),
3566
+ where: whereArg, answer: answerArg, question: questionArg,
3567
+ })),
3568
+ ...(attentionArg.elicitations ?? []).map((elicitationArg): TControllerInboxItem => ({
3569
+ id: id('elicitation', elicitationArg, elicitationArg.sessionId), kind: 'elicitation', since: elicitationArg.createdAt,
3570
+ title: inboxTitle(elicitationArg.message || `${elicitationArg.serverName} asks for input`),
3571
+ where: whereArg, answer: answerArg, elicitation: elicitationArg,
3572
+ })),
3573
+ ];
3574
+ }
3575
+
3576
+ /** A native session as the Inbox names it: where it runs and how the browser opens it. */
3577
+ private inboxNativeWhere(harnessArg: 'claude' | 'codex', nativeIdArg: string, titleArg: string): Extract<TControllerInboxWhere, { kind: 'native' }> {
3578
+ return { kind: 'native', session: { harness: harnessArg, nativeId: nativeIdArg }, harness: harnessArg,
3579
+ ...this.inboxRow(harnessArg, nativeIdArg, titleArg), host: plugins.os.hostname() };
3580
+ }
3581
+
3582
+ /** The requests Claude Code holds: its conversations' and those of AGL's turns in native sessions. */
3583
+ private readInboxClaude(): TControllerInboxItem[] {
3584
+ const harness = this.claudeHarness;
3585
+ if (!harness || harness.closed) return [];
3586
+ return harness.pendingAttention().flatMap((entryArg) => {
3587
+ if (entryArg.projectId === undefined) {
3588
+ return this.inboxSessionItems(this.inboxNativeWhere('claude', entryArg.nativeId, entryArg.title), 'native', entryArg.attention);
3589
+ }
3590
+ const sessionId = claudeRuntimeId(entryArg.nativeId);
3591
+ return this.inboxSessionItems({
3592
+ kind: 'conversation', projectId: entryArg.projectId, sessionId, harness: 'claude',
3593
+ ...this.inboxRow('claude', entryArg.nativeId, entryArg.title),
3594
+ }, 'conversation', entryArg.attention, this.isProjectAutoAcceptedSession(entryArg.projectId, sessionId));
3595
+ });
3596
+ }
3597
+
3598
+ /** The requests the Codex connections hold: the conversations' and, on the fleet's connection, the native threads'. */
3599
+ private readInboxCodex(): TControllerInboxItem[] {
3600
+ const clients = this.codexConnections
3601
+ ? this.codexConnections.all().flatMap((runtimeArg) => runtimeArg.supervisor.getStatus().healthy ? [runtimeArg.client] : [])
3602
+ : this.codexClient && this.codexSupervisor?.getStatus().healthy ? [this.codexClient] : [];
3603
+ const conversations = clients.flatMap((clientArg) => clientArg.pendingAttention().flatMap((entryArg) => {
3604
+ const sessionId = codexRuntimeId(entryArg.threadId);
3605
+ return this.inboxSessionItems({
3606
+ kind: 'conversation', projectId: entryArg.projectId, sessionId, harness: 'codex',
3607
+ ...this.inboxRow('codex', entryArg.threadId, entryArg.session.title),
3608
+ }, 'conversation', entryArg.attention, this.isProjectAutoAcceptedSession(entryArg.projectId, sessionId));
3609
+ }));
3610
+ const native = (this.fleetWorkers?.nativePendingAttention('codex') ?? []).flatMap((entryArg) => (
3611
+ this.inboxSessionItems(this.inboxNativeWhere('codex', entryArg.nativeId, entryArg.title), 'native', entryArg.attention)
3612
+ ));
3613
+ return [...conversations, ...native];
3614
+ }
3615
+
3616
+ /**
3617
+ * The requests of the OpenCode conversations the feed shows waiting, from the project's pending lists, and of their
3618
+ * direct children (subagents), from `readOpenCodeFamilyAttention`, the read the browser's child scopes use: only a
3619
+ * managed conversation has children AGL answers. A project or a conversation whose read fails keeps the items it had.
3620
+ */
3621
+ private async readInboxOpenCode(previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3622
+ const client = this.openCodeClient;
3623
+ if (!client) return [];
3624
+ const byProject = new Map<string, IControllerSessionFeedRow[]>();
3625
+ for (const row of this.sessionFeed?.publishedRows() ?? []) {
3626
+ if (row.harness !== 'opencode' || row.state !== 'needs_input' || row.nativeWait !== undefined || row.open.kind !== 'conversation') continue;
3627
+ byProject.set(row.open.projectId, [...byProject.get(row.open.projectId) ?? [], row]);
3628
+ }
3629
+ const kept = (predicateArg: (whereArg: TControllerInboxWhere) => boolean) => previousArg.filter((itemArg) => predicateArg(itemArg.where));
3630
+ const items: TControllerInboxItem[] = [];
3631
+ for (const [projectId, rows] of byProject) {
3632
+ signalArg.throwIfAborted();
3633
+ let pending: { permissions: IControllerPermission[]; questions: IControllerQuestion[] };
3634
+ try {
3635
+ const { directory } = await this.resolveProject(projectId);
3636
+ const [permissions, questions] = await Promise.all([
3637
+ client.listPermissions(directory, undefined, signalArg), client.listQuestions(directory, undefined, signalArg),
3638
+ ]);
3639
+ pending = { permissions, questions };
3640
+ } catch (errorArg) {
3641
+ signalArg.throwIfAborted();
3642
+ this.reportInboxError(`opencode:${projectId}`, errorArg);
3643
+ items.push(...kept((whereArg) => (whereArg.kind === 'conversation' || whereArg.kind === 'child') && whereArg.projectId === projectId));
3644
+ continue;
3645
+ }
3646
+ const roots = new Set(rows.map((rowArg) => (rowArg.open as { sessionId: IControllerRuntimeId }).sessionId.nativeId));
3647
+ const asksElsewhere = [...pending.permissions, ...pending.questions].some((requestArg) => !roots.has(requestArg.sessionId.nativeId));
3648
+ for (const row of rows) {
3649
+ const open = row.open as Extract<IControllerSessionFeedRow['open'], { kind: 'conversation' }>;
3650
+ const parentSessionId = open.sessionId as IControllerRuntimeId & { harnessId: 'opencode' };
3651
+ const own = (requestArg: { sessionId: IControllerRuntimeId }) => requestArg.sessionId.nativeId === parentSessionId.nativeId;
3652
+ const autoAccepted = this.isProjectAutoAcceptedSession(projectId, parentSessionId);
3653
+ items.push(...this.inboxSessionItems({
3654
+ kind: 'conversation', projectId, sessionId: parentSessionId, harness: 'opencode', rowId: row.id, name: row.name,
3655
+ }, 'conversation', { permissions: pending.permissions.filter(own), questions: pending.questions.filter(own) }, autoAccepted));
3656
+ if (!asksElsewhere) continue;
3657
+ try {
3658
+ for (const { child, permissions, questions } of (await this.readOpenCodeFamilyAttention(projectId, parentSessionId, signalArg, true))?.children ?? []) {
3659
+ items.push(...this.inboxSessionItems({
3660
+ kind: 'child', projectId, parentSessionId, childSessionId: child.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
3661
+ harness: 'opencode', rowId: row.id, name: row.name, childName: child.session.title || 'Subagent',
3662
+ }, 'child', { permissions, questions }, autoAccepted));
3663
+ }
3664
+ } catch (errorArg) {
3665
+ signalArg.throwIfAborted();
3666
+ // A conversation AGL does not manage has no children it answers.
3667
+ if (errorArg instanceof ControllerSessionIdentityError && (errorArg.code === 'not_found' || errorArg.code === 'tombstoned')) continue;
3668
+ this.reportInboxError(`opencode:${row.id}`, errorArg);
3669
+ items.push(...kept((whereArg) => whereArg.kind === 'child' && whereArg.rowId === row.id));
3670
+ }
3671
+ }
3672
+ }
3673
+ return items;
3674
+ }
3675
+
3676
+ /** The failures of the Inbox's partial reads, by what failed: a lasting one is reported once. */
3677
+ private readonly inboxErrors = new Map<string, string>();
3678
+ private reportInboxError(keyArg: string, errorArg: unknown): void {
3679
+ const message = errorArg instanceof Error ? errorArg.message : String(errorArg);
3680
+ if (this.inboxErrors.get(keyArg) === message) return;
3681
+ if (this.inboxErrors.size >= 256) this.inboxErrors.clear();
3682
+ this.inboxErrors.set(keyArg, message);
3683
+ console.error(`Inbox: reading ${keyArg} failed.`, errorArg);
3684
+ }
3685
+
3686
+ /**
3687
+ * The Flex permissions of the conversations the feed shows waiting, and of the driver, by the run that asks (a
3688
+ * subagent's by its root conversation). A permission the owner's auto-accept answers is left out.
3689
+ */
3690
+ private async readInboxFlex(previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3691
+ const supervisor = this.flexSupervisor;
3692
+ if (!supervisor || !this.flexIsOperational()) return [];
3693
+ const rows = new Map((this.sessionFeed?.publishedRows() ?? []).flatMap((rowArg) => rowArg.harness === 'flex'
3694
+ && rowArg.state === 'needs_input' && rowArg.nativeWait === undefined && rowArg.open.kind === 'conversation'
3695
+ ? [[`${rowArg.open.projectId}\0${rowArg.open.sessionId.nativeId}`, rowArg] as const] : []));
3696
+ const driver = await this.driverService?.driverSession();
3697
+ // The driver's status follows its session through `driver.changed`, which marks this source stale.
3698
+ const driverWaits = driver !== undefined && this.driverService?.current().session?.attention === true;
3699
+ const projectIds = new Set([...rows.values()].map((rowArg) => (rowArg.open as { projectId: string }).projectId));
3700
+ if (driverWaits) projectIds.add(driver.projectId);
3701
+ const items: TControllerInboxItem[] = [];
3702
+ for (const projectId of projectIds) {
3703
+ signalArg.throwIfAborted();
3704
+ try {
3705
+ const { permissions } = await supervisor.request('permission.list', { scopeId: projectId }, signalArg);
3706
+ for (const permission of permissions) {
3707
+ const authority = this.flexPermissionAuthority(projectId, permission);
3708
+ if (!authority || this.autoAcceptedFlexPermission(projectId, permission)) continue;
3709
+ const rootNativeId = authority.type === 'managed' ? authority.run.sessionId : authority.lease.rootAuthority.sessionId;
3710
+ const sessionId = flexRuntimeId(rootNativeId);
3711
+ if (driverWaits && driver.projectId === projectId && driver.nativeId === rootNativeId) {
3712
+ items.push(...this.inboxSessionItems({ kind: 'driver', projectId, sessionId }, 'conversation',
3713
+ { permissions: [this.toFlexPermission(permission)], questions: [] }));
3714
+ continue;
3715
+ }
3716
+ const row = rows.get(`${projectId}\0${rootNativeId}`);
3717
+ if (!row) continue;
3718
+ items.push(...this.inboxSessionItems({
3719
+ kind: 'conversation', projectId, sessionId, harness: 'flex', rowId: row.id, name: row.name,
3720
+ }, 'conversation', { permissions: [this.toFlexPermission(permission)], questions: [] }));
3721
+ }
3722
+ } catch (errorArg) {
3723
+ signalArg.throwIfAborted();
3724
+ this.reportInboxError(`flex:${projectId}`, errorArg);
3725
+ items.push(...previousArg.filter((itemArg) => (itemArg.where.kind === 'conversation' || itemArg.where.kind === 'driver')
3726
+ && itemArg.where.projectId === projectId));
3727
+ }
3728
+ }
3729
+ return items;
3730
+ }
3731
+
3732
+ /** The sessions whose harness waits in its own client: AGL holds no request for them, so they are answered there. */
3733
+ private readInboxNativeWaits(): TControllerInboxItem[] {
3734
+ const harnessLabels: Record<TControllerSessionFeedHarness, string> = { claude: 'Claude Code', codex: 'Codex', flex: 'Flex', opencode: 'OpenCode' };
3735
+ return (this.sessionFeed?.publishedRows() ?? []).flatMap((rowArg): TControllerInboxItem[] => {
3736
+ const nativeWait = rowArg.nativeWait;
3737
+ if (rowArg.state !== 'needs_input' || !nativeWait || rowArg.open.kind === 'terminal') return [];
3738
+ const label = harnessLabels[rowArg.harness];
3739
+ const title = nativeWait.reason === 'approval' ? `Waits for approval in ${label}`
3740
+ : nativeWait.reason === 'user_input' ? `Waits for input in ${label}` : `Waits in ${label}`;
3741
+ const where: Extract<TControllerInboxWhere, { kind: 'conversation' | 'native' }> = rowArg.open.kind === 'conversation'
3742
+ ? { kind: 'conversation', projectId: rowArg.open.projectId, sessionId: rowArg.open.sessionId, harness: rowArg.harness, rowId: rowArg.id, name: rowArg.name }
3743
+ : { kind: 'native', session: nativeSessionRefOfFeed(rowArg.open), harness: rowArg.open.harness, rowId: rowArg.id, name: rowArg.name,
3744
+ host: plugins.os.hostname() };
3745
+ return [{ id: `native_wait:${rowArg.id}`, kind: 'native_wait', since: rowArg.updatedAt, title, where, answer: 'none',
3746
+ nativeWait: { reason: nativeWait.reason }, host: plugins.os.hostname() }];
3747
+ });
3748
+ }
3749
+
3750
+ /** The driver's `needs input:` turn, as the driver service found it; its own prompts are Flex session prompts. */
3751
+ private readInboxDriver(): TControllerInboxItem[] {
3752
+ const turn = this.driverService?.needsInput();
3753
+ if (!turn) return [];
3754
+ return [{ id: `driver:${turn.nativeId}:${turn.messageId}`, kind: 'driver', since: turn.at, title: inboxTitle(turn.line),
3755
+ where: { kind: 'driver', projectId: turn.projectId, sessionId: flexRuntimeId(turn.nativeId) }, answer: 'none',
3756
+ line: turn.line, messageId: turn.messageId }];
3757
+ }
3758
+
3759
+ /**
3760
+ * The board's open questions that wait for the owner: every one the owner did not ask, on a ticket that is not done.
3761
+ * A deploy plan's and a maintenance window's question is the owner's go, shown with what the deploy monitor observes.
3762
+ */
3763
+ private async readInboxTickets(signalArg: AbortSignal): Promise<TControllerInboxItem[]> {
3764
+ const open = (await this.ticketStore.openQuestionTickets(signalArg))
3765
+ .filter(({ question }) => question.askedBy.role !== 'owner');
3766
+ const goes = open.some(({ ticket, question }) => ticket.deployPlan?.questionId === question.id);
3767
+ let status: IFleetDeployStatus | undefined;
3768
+ if (goes && this.deployMonitor) {
3769
+ try {
3770
+ status = await this.deployMonitor.status();
3771
+ } catch (errorArg) {
3772
+ signalArg.throwIfAborted();
3773
+ // The go is the owner's either way; what runs where is shown once the monitor answers.
3774
+ this.reportInboxError('deployments', errorArg);
3775
+ }
3776
+ }
3777
+ return open.map(({ ticket, question }): TControllerInboxItem => {
3778
+ const where: Extract<TControllerInboxWhere, { kind: 'ticket' }> = {
3779
+ kind: 'ticket', ticketId: ticket.id, ticketKey: ticket.key, ticketTitle: ticket.title, project: ticket.project, columnId: ticket.columnId,
3780
+ };
3781
+ const base = { since: Date.parse(question.createdAt), where, answer: 'ticket' as const, question };
3782
+ if (ticket.deployPlan?.questionId === question.id) {
3783
+ const plan = ticket.deployPlan;
3784
+ const target = status?.targets.find((targetArg) => targetArg.target.id === plan.target);
3785
+ const planned = target?.deployPlans.find((planArg) => planArg.key === ticket.key);
3786
+ const ships = (target?.notRunning.tickets ?? []).filter((ticketArg) => ticketArg.version !== undefined
3787
+ && compareFleetVersions(ticketArg.version, plan.version) <= 0);
3788
+ const name = target?.target.name ?? plan.target;
3789
+ return {
3790
+ ...base, id: `deploy_go:${ticket.key}:${question.id}`, kind: 'deploy_go',
3791
+ title: inboxTitle(`${name}${target?.target.environment ? ` → ${target.target.environment}` : ''}, ${target?.running ? `${target.running.version} → ` : ''}${plan.version}`),
3792
+ plan: {
3793
+ target: plan.target, version: plan.version,
3794
+ ...(target?.target.name === undefined ? {} : { targetName: target.target.name }),
3795
+ ...(target?.target.environment === undefined ? {} : { environment: target.target.environment }),
3796
+ ...(target?.running ? { runs: target.running.version } : {}),
3797
+ ...(target ? { deployWhen: target.deployWhen } : {}),
3798
+ ...(planned?.window ? { window: { from: planned.window.from, to: planned.window.to } } : {}),
3799
+ ships: ships.slice(0, controllerInboxLimits.ships).map(({ key, title }) => ({ key, title })),
3800
+ shipsTotal: ships.length,
3801
+ ...(planned?.assignee === undefined ? {} : { assignee: planned.assignee }),
3802
+ },
3803
+ };
3804
+ }
3805
+ if (ticket.maintenanceWindow?.questionId === question.id) {
3806
+ const window = ticket.maintenanceWindow;
3807
+ return {
3808
+ ...base, id: `window_go:${ticket.key}:${question.id}`, kind: 'window_go',
3809
+ title: inboxTitle(`Maintenance window for ${window.targets.join(', ')}`),
3810
+ window: { from: window.from, to: window.to, targets: [...window.targets] },
3811
+ };
3812
+ }
3813
+ return { ...base, id: `ticket_question:${ticket.key}:${question.id}`, kind: 'ticket_question', title: inboxTitle(question.question) };
3814
+ });
3815
+ }
3425
3816
  private ticketNotifier?: TicketNotifier;
3426
3817
  private boardPump?: BoardPump;
3427
3818
  private deployMonitor?: DeployMonitor;
@@ -4896,6 +5287,8 @@ export class OpenCodeController {
4896
5287
  launch: (signalArg) => this.claudeLaunch(signalArg),
4897
5288
  emit: (eventArg) => this.handleClaudeEvent(eventArg),
4898
5289
  onSessionIdle: (projectIdArg, nativeIdArg) => this.scheduleQueuedClaudePrompt(projectIdArg, claudeRuntimeId(nativeIdArg)),
5290
+ // No controller event names a native session; the Inbox reads the harness's requests again.
5291
+ onNativeAttention: () => this.inbox?.nativeAttentionChanged('claude'),
4899
5292
  });
4900
5293
  try {
4901
5294
  await this.withCurrentSessionIdentityProjects(
@@ -6989,7 +7382,7 @@ export class OpenCodeController {
6989
7382
  peerIdArg: string,
6990
7383
  requestArg: IReq_ControllerMcpSessionsList['request'],
6991
7384
  signalArg: AbortSignal,
6992
- ): Promise<IReq_ControllerMcpSessionsList['response']> {
7385
+ ): Promise<Pick<IReq_ControllerMcpSessionsList['response'], 'sessions'>> {
6993
7386
  const { projectId } = requestArg;
6994
7387
  return this.runAudited(
6995
7388
  { type: 'session.list', peerId: this.auditPeerId(principalArg, peerIdArg) },
@@ -7067,7 +7460,7 @@ export class OpenCodeController {
7067
7460
  peerIdArg: string,
7068
7461
  requestArg: IReq_ControllerMcpSessionRead['request'],
7069
7462
  signalArg: AbortSignal,
7070
- ): Promise<IReq_ControllerMcpSessionRead['response']> {
7463
+ ): Promise<TControllerMcpSessionDetail> {
7071
7464
  const { projectId, sessionId } = requestArg;
7072
7465
  return this.runAudited(
7073
7466
  {
@@ -7428,6 +7821,7 @@ export class OpenCodeController {
7428
7821
  { code: 'delivery_unsupported' },
7429
7822
  );
7430
7823
  }
7824
+ if (await this.isMcpNativeClaudeId(projectId, sessionId)) return this.deliverNativeAgentMessage(peerIdArg, requestArg, subjectArg, signalArg);
7431
7825
  await this.requireMcpMessageTarget(projectId, sessionId, signalArg);
7432
7826
  const sender: IControllerPromptSender = { kind: 'agent', label, subject: await subjectArg() };
7433
7827
  if (!this.agentMessageLimiter.admit(`${peerIdArg}\0${projectId}\0${controllerRuntimeIdKey(sessionId)}`)) {
@@ -9105,6 +9499,163 @@ export class OpenCodeController {
9105
9499
  return this.assertSessionExists(projectIdArg, sessionIdArg, signalArg);
9106
9500
  }
9107
9501
 
9502
+ /**
9503
+ * Whether an MCP request names a Claude Code session outside AGL's conversations of the project: a `claude` id that no
9504
+ * conversation of this project records. Such an id is served by the native path, everything else by the managed one.
9505
+ */
9506
+ private async isMcpNativeClaudeId(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<boolean> {
9507
+ if (sessionIdArg.harnessId !== 'claude') return false;
9508
+ await this.resolveProject(projectIdArg);
9509
+ return !await this.requireAuthStore().requireClaudeSessions().get(projectIdArg, sessionIdArg.nativeId);
9510
+ }
9511
+
9512
+ /**
9513
+ * The Claude Code session outside AGL that an MCP caller names in a project: only a session of the host's own Claude
9514
+ * Code home, as the session feed lists it, whose directory is the project folder itself, and that no other project's
9515
+ * conversation records. Anything else is `session_not_found`; nothing is recorded.
9516
+ */
9517
+ private async requireMcpNativeClaudeTarget(projectIdArg: string, sessionIdArg: IControllerRuntimeId): Promise<{
9518
+ ref: IControllerNativeSessionRef; resolved: IResolvedNativeSession; session: IControllerNativeSession;
9519
+ }> {
9520
+ const project = await this.resolveProject(projectIdArg);
9521
+ const ref: IControllerNativeSessionRef = { harness: 'claude', nativeId: sessionIdArg.nativeId };
9522
+ const notFound = () => new plugins.typedrequest.TypedResponseError('The requested session was not found.', { code: 'session_not_found' });
9523
+ let resolved: IResolvedNativeSession;
9524
+ try {
9525
+ resolved = await this.nativeSessions.resolve(ref);
9526
+ } catch (errorArg) {
9527
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'session_not_found') throw notFound();
9528
+ throw errorArg;
9529
+ }
9530
+ if (!await this.inMcpNativeScope(resolved, project.directory)) throw notFound();
9531
+ return { ref, resolved, session: mcpNativeSession(resolved) };
9532
+ }
9533
+
9534
+ /** The project's scope for Claude Code sessions outside AGL: the host's own home, the exact folder, no other project's conversation. */
9535
+ private async inMcpNativeScope(resolvedArg: IResolvedNativeSession, projectDirectoryArg: string): Promise<boolean> {
9536
+ if (resolvedArg.native.home !== undefined || resolvedArg.session.readOnly?.reason === 'projectConversation') return false;
9537
+ const directory = await canonicalDirectory(projectDirectoryArg);
9538
+ return directory !== undefined && await canonicalDirectory(resolvedArg.session.cwd) === directory;
9539
+ }
9540
+
9541
+ /**
9542
+ * The Claude Code sessions of the host's own Claude Code home whose directory is the project folder itself and that no
9543
+ * project conversation records, for `sessions_list`: running ones first, all of them, then the newest settled ones up
9544
+ * to `controllerMcpNativeSessionSettledLimit`. An inventory that cannot be read is named, never hidden.
9545
+ */
9546
+ private async listMcpNativeClaudeSessions(projectIdArg: string): Promise<Omit<IReq_ControllerMcpSessionsList['response'], 'sessions'>> {
9547
+ const project = await this.resolveProject(projectIdArg);
9548
+ let agents: Awaited<ReturnType<FleetWorkers['nativeAgents']>>;
9549
+ try {
9550
+ agents = await this.requireFleetWorkers().nativeAgents(undefined, 3_000);
9551
+ } catch (errorArg) {
9552
+ const reason = errorArg instanceof Error ? errorArg.message : 'unknown failure.';
9553
+ return { nativeSessions: [], nativeSessionsError: `The host's Claude Code inventory could not be read: ${reason}`.slice(0, 1024) };
9554
+ }
9555
+ const directory = await canonicalDirectory(project.directory);
9556
+ if (directory === undefined) return { nativeSessions: [] };
9557
+ const running = (agentArg: typeof agents[number]): boolean => agentArg.pid !== undefined || agentArg.state === 'working';
9558
+ const candidates: typeof agents = [], seen = new Set<string>();
9559
+ for (const agent of agents) {
9560
+ if (seen.has(agent.sessionId)) continue;
9561
+ seen.add(agent.sessionId);
9562
+ if (await canonicalDirectory(agent.cwd) === directory) candidates.push(agent);
9563
+ }
9564
+ candidates.sort((left, right) => Number(running(right)) - Number(running(left)) || (right.startedAt ?? 0) - (left.startedAt ?? 0));
9565
+ const nativeSessions: IControllerNativeSession[] = [];
9566
+ let settled = 0;
9567
+ for (const agent of candidates) {
9568
+ // Running sessions sort first and are never cut; only settled ones count toward the limit.
9569
+ if (!running(agent) && settled >= controllerMcpNativeSessionSettledLimit) return { nativeSessions, nativeSessionsTruncated: true };
9570
+ let resolved: IResolvedNativeSession;
9571
+ try {
9572
+ resolved = await this.nativeSessions.resolve({ harness: 'claude', nativeId: agent.sessionId });
9573
+ } catch (errorArg) {
9574
+ // A session that left the inventory since it was read is no longer listed.
9575
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'session_not_found') continue;
9576
+ throw errorArg;
9577
+ }
9578
+ if (!await this.inMcpNativeScope(resolved, project.directory)) continue;
9579
+ nativeSessions.push(mcpNativeSession(resolved));
9580
+ if (!running(agent)) settled += 1;
9581
+ }
9582
+ return { nativeSessions };
9583
+ }
9584
+
9585
+ /** `session_read` of a Claude Code session outside AGL: the session, its newest transcript page and its scratchpad. */
9586
+ private async readMcpNativeClaudeSession(
9587
+ principalArg: TControllerOperationPrincipal,
9588
+ requestArg: IReq_ControllerMcpSessionRead['request'],
9589
+ signalArg: AbortSignal,
9590
+ ): Promise<IControllerMcpNativeSessionDetail> {
9591
+ return this.runAudited(
9592
+ { type: 'session.read', peerId: this.auditPeerId(principalArg, 'mcp'), sessionId: requestArg.sessionId },
9593
+ () => this.serveNativeSession(signalArg, async () => {
9594
+ const { ref, resolved, session } = await this.requireMcpNativeClaudeTarget(requestArg.projectId, requestArg.sessionId);
9595
+ const [page, state] = await Promise.all([
9596
+ this.requireFleetWorkers().nativeHistory('claude', resolved.native, controllerInitialMessageBundleLimit),
9597
+ this.requireAuthStore().getSessionState(resolved.scope, nativeSessionRuntimeId(ref), signalArg),
9598
+ ]);
9599
+ signalArg.throwIfAborted();
9600
+ return {
9601
+ kind: 'native' as const,
9602
+ session,
9603
+ messagePage: boundControllerMessagePage({
9604
+ bundles: page.bundles,
9605
+ ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
9606
+ ...(page.earlier && page.nextCursor === undefined ? { truncated: true } : {}),
9607
+ }, controllerInitialMessageBundleLimit),
9608
+ scratchpad: state.scratchpad,
9609
+ };
9610
+ }),
9611
+ );
9612
+ }
9613
+
9614
+ /**
9615
+ * An agent message to a Claude Code background job outside AGL, after the project's switch: behind the
9616
+ * `session_message` header naming the caller, through the one native send, which wakes a settled job and puts the
9617
+ * message into a running job's inbox. A send that may have reached the job is `outcome_unknown`, never resent.
9618
+ */
9619
+ private async deliverNativeAgentMessage(
9620
+ peerIdArg: string,
9621
+ requestArg: IReq_ControllerMcpSessionMessage['request'],
9622
+ subjectArg: () => Promise<string>,
9623
+ signalArg: AbortSignal,
9624
+ ): Promise<IReq_ControllerMcpSessionMessage['response']> {
9625
+ const { projectId, sessionId, sender: label } = requestArg;
9626
+ if (requestArg.expectedTurnId !== undefined) {
9627
+ throw new plugins.typedrequest.TypedResponseError(
9628
+ 'A Claude Code background job outside AGL takes no turn guard; omit expectedTurnId.',
9629
+ { code: 'delivery_unsupported' },
9630
+ );
9631
+ }
9632
+ const target = await this.requireMcpNativeClaudeTarget(projectId, sessionId);
9633
+ assertMcpNativeMessageable(target.session);
9634
+ const sender: IControllerPromptSender = { kind: 'agent', label, subject: await subjectArg() };
9635
+ if (!this.agentMessageLimiter.admit(`${peerIdArg}\0${projectId}\0${controllerRuntimeIdKey(sessionId)}`)) {
9636
+ throw new plugins.typedrequest.TypedResponseError(
9637
+ 'Too many agent messages to this task; wait before sending another.',
9638
+ { code: 'message_rate_limited' },
9639
+ );
9640
+ }
9641
+ let job: TControllerNativeJobDelivery | undefined;
9642
+ try {
9643
+ ({ job } = await this.sendNativeSession(peerIdArg, target.ref, formatAgentMessage(sender, requestArg.text), undefined, signalArg,
9644
+ (resolvedArg) => {
9645
+ if (resolvedArg.native.home !== undefined) throw new plugins.typedrequest.TypedResponseError('The requested session was not found.', { code: 'session_not_found' });
9646
+ assertMcpNativeMessageable(mcpNativeSession(resolvedArg));
9647
+ }));
9648
+ } catch (errorArg) {
9649
+ // Only a refusal before dispatch proves that nothing reached the job.
9650
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError && errorArg.errorData?.code === 'native_session_failed' && errorArg.errorData?.outcome !== 'refused') {
9651
+ throw new plugins.typedrequest.TypedResponseError('The message may have reached the Claude Code job; read the session before sending again.', { code: 'outcome_unknown' });
9652
+ }
9653
+ throw errorArg;
9654
+ }
9655
+ if (!job) throw new plugins.typedrequest.TypedResponseError('The message may have reached the Claude Code job; read the session before sending again.', { code: 'outcome_unknown' });
9656
+ return { accepted: true as const, delivery: controllerMcpNativeDeliveries[job], native: job };
9657
+ }
9658
+
9108
9659
  /**
9109
9660
  * Any caller may message a task: unlike a task mutation, no ownership is required. The target
9110
9661
  * must still be an active root task of the project the request names; archived tasks and child
@@ -9201,6 +9752,10 @@ export class OpenCodeController {
9201
9752
  await this.resolveProject(project.id);
9202
9753
  if (!requestArg.sessionId) return { project };
9203
9754
  const target = requestArg.sessionId;
9755
+ // A Claude Code session outside AGL answers as itself and is recorded nowhere.
9756
+ if (await this.isMcpNativeClaudeId(project.id, target)) {
9757
+ return { project, nativeSession: (await this.requireMcpNativeClaudeTarget(project.id, target)).session };
9758
+ }
9204
9759
  const { sessions } = await this.listSessionsForPrincipal(
9205
9760
  principalArg, peerIdArg, { projectId: project.id }, signalArg,
9206
9761
  );
@@ -9907,16 +10462,17 @@ export class OpenCodeController {
9907
10462
  ),
9908
10463
  listSessions: async (principalArg, requestArg, signalArg) => run(
9909
10464
  signalArg,
9910
- async (operationSignalArg) => this.listSessionsForPrincipal(
9911
- principalArg,
9912
- 'mcp',
9913
- requestArg,
9914
- operationSignalArg,
9915
- ),
10465
+ async (operationSignalArg) => {
10466
+ const listed = await this.listSessionsForPrincipal(principalArg, 'mcp', requestArg, operationSignalArg);
10467
+ return { ...listed, ...await this.listMcpNativeClaudeSessions(requestArg.projectId) };
10468
+ },
9916
10469
  ),
9917
10470
  readSession: async (principalArg, requestArg, signalArg) => run(
9918
10471
  signalArg,
9919
10472
  async (operationSignalArg) => {
10473
+ if (await this.isMcpNativeClaudeId(requestArg.projectId, requestArg.sessionId)) {
10474
+ return this.readMcpNativeClaudeSession(principalArg, requestArg, operationSignalArg);
10475
+ }
9920
10476
  await this.prepareMcpSessionTarget(requestArg.projectId, requestArg.sessionId, operationSignalArg);
9921
10477
  return this.readSessionForPrincipal(
9922
10478
  principalArg,
@@ -10844,6 +11400,7 @@ export class OpenCodeController {
10844
11400
  .catch((errorArg) => console.error('Announcing new Claude Code releases failed.', errorArg));
10845
11401
  }
10846
11402
  this.startSessionFeed();
11403
+ this.startInbox();
10847
11404
  // Assignees hear of others' changes to their tickets through the fleet's native steering.
10848
11405
  this.ticketNotifier ??= new TicketNotifier({
10849
11406
  deliver: async (sessionIdArg, ticketKeyArg, textArg) => {
@@ -13222,6 +13779,7 @@ export class OpenCodeController {
13222
13779
  await stopPart(async () => { await this.deployMonitor?.close(); this.deployMonitor = undefined; });
13223
13780
  await stopPart(async () => { await this.gatewayClient?.close(); this.gatewayClient = undefined; });
13224
13781
  await stopPart(async () => { await this.ticketNotifier?.close(); this.ticketNotifier = undefined; });
13782
+ await stopPart(async () => { await this.inbox?.close(); this.inbox = undefined; });
13225
13783
  await stopPart(async () => { await this.sessionFeed?.close(); this.sessionFeed = undefined; });
13226
13784
  await stopPart(async () => { await this.usageFeed?.stop(); this.usageFeed = undefined; });
13227
13785
  await stopPart(async () => { const notices = this.harnessReleases; this.harnessReleases = undefined; await notices?.close(); });
@@ -13775,13 +14333,14 @@ export class OpenCodeController {
13775
14333
  this.registerDirectReportHandlers(protectedRouter);
13776
14334
  this.registerNativeSessionHandlers(protectedRouter);
13777
14335
  this.registerSessionFeedHandlers(protectedRouter);
14336
+ this.registerInboxHandlers(protectedRouter);
13778
14337
  this.registerDeployHandlers(protectedRouter);
13779
14338
  this.registerUsageFeedHandlers(protectedRouter);
13780
14339
  this.registerTerminalHandlers(protectedRouter);
13781
14340
  this.registerDevicesHandlers(protectedRouter);
13782
14341
 
13783
14342
  this.registerDevicePairingHandlers(devicePairingRouter);
13784
- this.registerDeviceHandlers(deviceRouter);
14343
+ this.registerDeviceHandlers(deviceRouter, publicOriginArg);
13785
14344
 
13786
14345
  return rootRouter;
13787
14346
  }
@@ -13903,11 +14462,295 @@ export class OpenCodeController {
13903
14462
  });
13904
14463
  }
13905
14464
 
14465
+ /**
14466
+ * A device's answer to a direct child (an OpenCode subagent) of the session it names: the session must be an OpenCode
14467
+ * conversation the feed lists, and the child is proven a running direct child of it as the browser's child scopes do.
14468
+ */
14469
+ private replyDeviceChildRequest(
14470
+ auditPeerIdArg: string,
14471
+ openArg: Exclude<IControllerSessionFeedRow['open'], { kind: 'terminal' }>,
14472
+ childSessionIdArg: string,
14473
+ requestIdArg: string,
14474
+ replyArg: { reply: TControllerPermissionReply; message?: string } | { answers: string[][] | null },
14475
+ signalArg: AbortSignal,
14476
+ ): Promise<{ success: boolean }> {
14477
+ if (openArg.kind !== 'conversation' || openArg.sessionId.harnessId !== 'opencode') {
14478
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
14479
+ }
14480
+ const projectId = openArg.projectId;
14481
+ const parentSessionId = openArg.sessionId as IControllerRuntimeId & { harnessId: 'opencode' };
14482
+ const childSessionId = { harnessId: 'opencode' as const, nativeId: childSessionIdArg };
14483
+ return this.replyChildRequestForPrincipal('device', auditPeerIdArg, {
14484
+ projectId, parentSessionId, childSessionId, requestId: { harnessId: 'opencode', nativeId: requestIdArg }, ...replyArg,
14485
+ }, (activeRequiredArg) => this.verifyDeviceDirectChild(projectId, parentSessionId, childSessionId, signalArg, activeRequiredArg), signalArg);
14486
+ }
14487
+
14488
+ /**
14489
+ * A conversation's transcript page and what it waits for, as a device reads it through the browser's session read:
14490
+ * the newest page without `before`, sized by the controller, else the next older page of `limit` messages.
14491
+ */
14492
+ private async readDeviceConversation(
14493
+ auditPeerIdArg: string,
14494
+ projectIdArg: string,
14495
+ sessionIdArg: IControllerRuntimeId,
14496
+ requestArg: { before?: string; limit?: number },
14497
+ signalArg: AbortSignal,
14498
+ ): Promise<Omit<IReq_DeviceSessionRead['response'], 'session'>> {
14499
+ const detail = await this.readSessionForPrincipal('device', auditPeerIdArg, { projectId: projectIdArg, sessionId: sessionIdArg }, signalArg);
14500
+ const before = requestArg.before;
14501
+ const page = before === undefined ? detail.messagePage : await this.runAudited(
14502
+ { type: 'session.messages.page', peerId: auditPeerIdArg, sessionId: sessionIdArg },
14503
+ async () => this.readSessionMessagePage(
14504
+ await this.resolveProject(projectIdArg),
14505
+ sessionIdArg,
14506
+ { limit: requestArg.limit ?? controllerInitialMessageBundleLimit, before },
14507
+ signalArg,
14508
+ ),
14509
+ );
14510
+ return {
14511
+ messages: deviceMessages(page.bundles),
14512
+ before: page.nextCursor ?? null,
14513
+ permissions: devicePermissions(detail.permissions),
14514
+ questions: deviceQuestions(detail.questions),
14515
+ elicitations: deviceElicitations(detail.elicitations),
14516
+ };
14517
+ }
14518
+
14519
+ /**
14520
+ * The host's driver session for a device's read or send, as the driver's status names it now; refused while there is
14521
+ * none. A device never creates the driver.
14522
+ */
14523
+ private async deviceDriverSession(signalArg: AbortSignal): Promise<{
14524
+ driver: IControllerDriverStatus;
14525
+ projectId: string;
14526
+ sessionId: TControllerSessionId;
14527
+ }> {
14528
+ const driver = await this.requireDriverService().get(signalArg);
14529
+ if (driver.activity === 'absent' || driver.projectId === undefined || driver.sessionId === undefined) {
14530
+ throw deviceRefusal('driver_absent', 'This host has no driver session; the owner starts the driver in the browser.');
14531
+ }
14532
+ return { driver, projectId: driver.projectId, sessionId: driver.sessionId };
14533
+ }
14534
+
13906
14535
  /**
13907
14536
  * 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>`.
14537
+ * authenticated device, the Inbox, the driver, the direct reports, the host's status and the shared board -- through
14538
+ * the same operations the owner's browser runs, audited as `device:<id>`. `publicOriginArg` is the origin the scope
14539
+ * admits.
13909
14540
  */
13910
- private registerDeviceHandlers(routerArg: ControllerProtectedRouter): void {
14541
+ private registerDeviceHandlers(routerArg: ControllerProtectedRouter, publicOriginArg: string): void {
14542
+ routerArg.addHandler<IReq_DeviceInboxList>('device.inbox.list', async (requestArg, toolsArg) => {
14543
+ validateRequest(() => assertEmptyRequest(requestArg));
14544
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14545
+ return this.runDeviceOperation(peer, deviceId, async () => deviceInboxList(
14546
+ await this.requireInbox().list(), (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg),
14547
+ ), toolsArg?.abortSignal);
14548
+ });
14549
+
14550
+ routerArg.addHandler<IReq_DeviceTicketAnswer>('device.ticket.answer', async (requestArg, toolsArg) => {
14551
+ const request = validateRequest(() => assertDeviceTicketAnswerRequest(requestArg));
14552
+ const answer = validateRequest(() => assertTicketRequest('answer', {
14553
+ ticketId: request.ticketKey, questionId: request.questionId,
14554
+ ...(request.choices === undefined ? {} : { choices: request.choices }),
14555
+ ...(request.text === undefined ? {} : { text: request.text }),
14556
+ }));
14557
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14558
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14559
+ try {
14560
+ const { question } = await this.answerTicketForPrincipal('device', deviceAuditPeerId(deviceId), answer, signalArg);
14561
+ return { question: deviceTicketQuestion(question) };
14562
+ } catch (errorArg) {
14563
+ throw deviceTicketRefusal(errorArg);
14564
+ }
14565
+ }, toolsArg?.abortSignal);
14566
+ });
14567
+
14568
+ // The shared board (AGL-1637): the browser board's own reads and changes, as the owner and audited as the device. A
14569
+ // device creates, edits and assigns no ticket; a refusal changes nothing and carries the store's code and reason.
14570
+ routerArg.addHandler<IReq_DeviceBoardList>('device.board.list', async (requestArg, toolsArg) => {
14571
+ const request = validateRequest(() => assertDeviceBoardListRequest(requestArg));
14572
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14573
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14574
+ const { owner, viewer } = await this.deviceTicketViewer();
14575
+ let board: ITicketBoard;
14576
+ try {
14577
+ board = await this.ticketStore.execute('board', {}, owner, signalArg);
14578
+ } catch (errorArg) {
14579
+ throw deviceTicketRefusal(errorArg);
14580
+ }
14581
+ return deviceBoardPage(board, request, viewer);
14582
+ }, toolsArg?.abortSignal);
14583
+ });
14584
+
14585
+ routerArg.addHandler<IReq_DeviceTicketGet>('device.ticket.get', async (requestArg, toolsArg) => {
14586
+ const request = validateRequest(() => assertDeviceTicketGetRequest(requestArg));
14587
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14588
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14589
+ const { owner, viewer } = await this.deviceTicketViewer();
14590
+ let detail: ITicketDetail;
14591
+ let comments: ITicketComment[];
14592
+ try {
14593
+ // The ticket and every question, then every comment: the discussion is paged here, by what a device shows.
14594
+ detail = await this.ticketStore.execute('get', { ticketId: request.ticketKey, limit: 1 }, owner, signalArg);
14595
+ comments = (await this.ticketStore.execute('comments', { ticketId: request.ticketKey }, owner, signalArg)).comments;
14596
+ } catch (errorArg) {
14597
+ throw deviceTicketRefusal(errorArg);
14598
+ }
14599
+ const parent = await this.deviceTicketParent(owner, detail.ticket, signalArg);
14600
+ const { placement, observed } = await readDeviceTicketPlacement(
14601
+ () => this.requireDeployMonitor().ticketPlacement(detail.ticket.key), signalArg,
14602
+ );
14603
+ return {
14604
+ ticket: deviceTicket(detail.ticket, parent, viewer),
14605
+ ...deviceTicketDiscussion(comments, detail.questions, request, viewer),
14606
+ placement,
14607
+ plans: deviceTicketPlans(detail.ticket, observed),
14608
+ };
14609
+ }, toolsArg?.abortSignal);
14610
+ });
14611
+
14612
+ routerArg.addHandler<IReq_DeviceTicketComment>('device.ticket.comment', async (requestArg, toolsArg) => {
14613
+ const request = validateRequest(() => assertDeviceTicketCommentRequest(requestArg));
14614
+ const comment = validateRequest(() => assertTicketRequest('comment', { ticketId: request.ticketKey, body: request.text }));
14615
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14616
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14617
+ const { viewer } = await this.deviceTicketViewer();
14618
+ try {
14619
+ const written = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'comment', comment, signalArg);
14620
+ return { comment: deviceTicketComment(written.comment, viewer) };
14621
+ } catch (errorArg) {
14622
+ throw deviceTicketRefusal(errorArg);
14623
+ }
14624
+ }, toolsArg?.abortSignal);
14625
+ });
14626
+
14627
+ routerArg.addHandler<IReq_DeviceTicketAsk>('device.ticket.ask', async (requestArg, toolsArg) => {
14628
+ const request = validateRequest(() => assertDeviceTicketAskRequest(requestArg));
14629
+ // Text alone, answered with text, as the browser board's question card asks.
14630
+ const ask = validateRequest(() => assertTicketRequest('ask', { ticketId: request.ticketKey, question: request.question }));
14631
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14632
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14633
+ try {
14634
+ const { question } = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'ask', ask, signalArg);
14635
+ return { question: deviceTicketQuestion(question) };
14636
+ } catch (errorArg) {
14637
+ throw deviceTicketRefusal(errorArg);
14638
+ }
14639
+ }, toolsArg?.abortSignal);
14640
+ });
14641
+
14642
+ // "Move to…": the phone's drag on the browser's board, to the end of the column.
14643
+ routerArg.addHandler<IReq_DeviceTicketMove>('device.ticket.move', async (requestArg, toolsArg) => {
14644
+ const request = validateRequest(() => assertDeviceTicketMoveRequest(requestArg));
14645
+ const move = validateRequest(() => assertTicketRequest('move', { ticketId: request.ticketKey, columnId: request.column }));
14646
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14647
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14648
+ const { owner, viewer } = await this.deviceTicketViewer();
14649
+ let moved: ITicket;
14650
+ try {
14651
+ const { tickets } = await this.changeTicketForPrincipal('device', deviceAuditPeerId(deviceId), 'move', move, signalArg);
14652
+ // A ticket already last in its column moves nowhere and is not among the tickets the move changed.
14653
+ moved = tickets.find((ticketArg) => ticketArg.key === request.ticketKey)
14654
+ ?? (await this.ticketStore.execute('get', { ticketId: request.ticketKey, limit: 1 }, owner, signalArg)).ticket;
14655
+ } catch (errorArg) {
14656
+ throw deviceTicketRefusal(errorArg);
14657
+ }
14658
+ return { ticket: deviceTicketCard(moved, await this.deviceTicketParent(owner, moved, signalArg), viewer) };
14659
+ }, toolsArg?.abortSignal);
14660
+ });
14661
+
14662
+ // The driver as the browser's topbar and Driver view reach it; its own prompts are read-only on a device.
14663
+ routerArg.addHandler<IReq_DeviceDriverGet>('device.driver.get', async (requestArg, toolsArg) => {
14664
+ validateRequest(() => assertEmptyRequest(requestArg));
14665
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14666
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14667
+ const service = this.requireDriverService();
14668
+ return { driver: deviceDriverStatus(await service.get(signalArg), service.needsInput()) };
14669
+ }), toolsArg?.abortSignal);
14670
+ });
14671
+
14672
+ routerArg.addHandler<IReq_DeviceDriverSeen>('device.driver.seen', async (requestArg, toolsArg) => {
14673
+ validateRequest(() => assertEmptyRequest(requestArg));
14674
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14675
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14676
+ const service = this.requireDriverService();
14677
+ return { driver: deviceDriverStatus(await service.seen(signalArg), service.needsInput()) };
14678
+ }), toolsArg?.abortSignal);
14679
+ });
14680
+
14681
+ routerArg.addHandler<IReq_DeviceDriverRead>('device.driver.read', async (requestArg, toolsArg) => {
14682
+ const request = validateRequest(() => assertDeviceDriverReadRequest(requestArg));
14683
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14684
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14685
+ const { driver, projectId, sessionId } = await this.deviceDriverSession(signalArg);
14686
+ const transcript = await this.readDeviceConversation(deviceAuditPeerId(deviceId), projectId, sessionId, request, signalArg);
14687
+ return { driver: deviceDriverStatus(driver, this.requireDriverService().needsInput()), ...transcript };
14688
+ }), toolsArg?.abortSignal);
14689
+ });
14690
+
14691
+ routerArg.addHandler<IReq_DeviceDriverSend>('device.driver.send', async (requestArg, toolsArg) => {
14692
+ const request = validateRequest(() => assertDeviceDriverSendRequest(requestArg));
14693
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14694
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => serveDeviceDriver(async () => {
14695
+ const { projectId, sessionId } = await this.deviceDriverSession(signalArg);
14696
+ // A direct message, as to any conversation: never the browser's shared draft.
14697
+ await this.sendSessionForPrincipal('device', deviceAuditPeerId(deviceId), {
14698
+ source: 'direct', projectId, sessionId, text: request.text,
14699
+ }, signalArg);
14700
+ return { accepted: true as const };
14701
+ }), toolsArg?.abortSignal);
14702
+ });
14703
+
14704
+ routerArg.addHandler<IReq_DeviceDirectReportsList>('device.directreports.list', async (requestArg, toolsArg) => {
14705
+ validateRequest(() => assertEmptyRequest(requestArg));
14706
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14707
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => this.serveDirectReport(signalArg, async (ownerArg) => {
14708
+ const directReports = this.requireDirectReports();
14709
+ const [views, workers] = await Promise.all([directReports.list(ownerArg, false, signalArg), directReports.reportWorkers(ownerArg)]);
14710
+ return { reports: views.map((viewArg) => deviceDirectReport(viewArg, workers.get(viewArg.report.name) ?? [])) };
14711
+ }), toolsArg?.abortSignal);
14712
+ });
14713
+
14714
+ routerArg.addHandler<IReq_DeviceDirectReportMessage>('device.directreport.message', async (requestArg, toolsArg) => {
14715
+ const request = validateRequest(() => assertDeviceDirectReportMessageRequest(requestArg));
14716
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14717
+ return this.runDeviceOperation(peer, deviceId, (signalArg) => this.serveDirectReport(signalArg, async (ownerArg) => {
14718
+ let answer: IReq_ControllerDirectReportMessage['response'];
14719
+ try {
14720
+ answer = await this.messageDirectReportForPrincipal('device', deviceAuditPeerId(deviceId), ownerArg, request, signalArg);
14721
+ } catch (errorArg) {
14722
+ throw deviceDirectReportMessageRefusal(errorArg);
14723
+ }
14724
+ if (!('job' in answer)) return { delivery: answer.delivery };
14725
+ if (answer.job.state !== 'succeeded') {
14726
+ throw deviceRefusal('direct_report_failed', (answer.job.error ?? 'The fleet did not deliver the message.').slice(0, 4096));
14727
+ }
14728
+ return { delivery: 'fleet' as const };
14729
+ }), toolsArg?.abortSignal);
14730
+ });
14731
+
14732
+ // The Host view (AGL-824) is read-only: what the browser's status, Deployments view and accounts read, reduced so
14733
+ // nothing names an account, a key or a probe's address, and no deploy probe runs for it.
14734
+ routerArg.addHandler<IReq_DeviceHostGet>('device.host.get', async (requestArg, toolsArg) => {
14735
+ validateRequest(() => assertEmptyRequest(requestArg));
14736
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14737
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14738
+ const device = this.requireDevices().get(deviceId);
14739
+ if (device === undefined) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
14740
+ const proxyMonitor = this.proxyMonitor;
14741
+ return {
14742
+ agl: deviceHostAgl({ version: commitinfo.version, startedAt: this.startedAt, origin: publicOriginArg, gateway: this.gatewayClient?.status() }),
14743
+ device: deviceHostDevice(device),
14744
+ ...await readDeviceHostSections({
14745
+ deployStatus: () => this.requireDeployMonitor().status(),
14746
+ capacity: proxyMonitor === undefined ? undefined : (operationSignalArg) => proxyMonitor.capacity({}, operationSignalArg),
14747
+ authority: () => this.authorityState.getProjection(),
14748
+ usage: (accountIdArg, loginIdArg, operationSignalArg) => this.accountsActions.usage({ accountId: accountIdArg, loginId: loginIdArg }, operationSignalArg),
14749
+ }, Date.now(), signalArg),
14750
+ };
14751
+ }, toolsArg?.abortSignal);
14752
+ });
14753
+
13911
14754
  routerArg.addHandler<IReq_DeviceSessionsList>('device.sessions.list', async (requestArg, toolsArg) => {
13912
14755
  validateRequest(() => assertEmptyRequest(requestArg));
13913
14756
  const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
@@ -13925,26 +14768,7 @@ export class OpenCodeController {
13925
14768
  const { row, open } = await this.deviceSessionTarget(request.sessionId);
13926
14769
  const session = deviceSessionRow(row)!;
13927
14770
  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
- };
14771
+ return { session, ...await this.readDeviceConversation(auditPeerId, open.projectId, open.sessionId, request, signalArg) };
13948
14772
  }
13949
14773
  // As for a conversation, `limit` sizes older pages only; the newest page is the controller's own bound.
13950
14774
  const native = await this.readNativeSessionForPrincipal('device', auditPeerId, {
@@ -13976,6 +14800,7 @@ export class OpenCodeController {
13976
14800
  } else {
13977
14801
  await this.sendNativeSession(
13978
14802
  auditPeerId, nativeSessionRefOfFeed(open), request.text, undefined, signalArg, assertNativeSessionWritable,
14803
+ { kind: 'agent', label: 'Owner', subject: agentMessageSubjects.ownerDevice },
13979
14804
  );
13980
14805
  }
13981
14806
  return { accepted: true as const };
@@ -13988,6 +14813,11 @@ export class OpenCodeController {
13988
14813
  return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13989
14814
  const auditPeerId = deviceAuditPeerId(deviceId);
13990
14815
  const { open } = await this.deviceSessionTarget(request.sessionId);
14816
+ if (request.childSessionId !== undefined) {
14817
+ return this.replyDeviceChildRequest(auditPeerId, open, request.childSessionId, request.permissionId, {
14818
+ reply: request.reply, ...(request.message === undefined ? {} : { message: request.message }),
14819
+ }, signalArg);
14820
+ }
13991
14821
  if (open.kind === 'conversation') {
13992
14822
  return this.replyPermissionForPrincipal('device', auditPeerId, validateRequest(() => assertPermissionReplyRequest({
13993
14823
  projectId: open.projectId,
@@ -14013,6 +14843,11 @@ export class OpenCodeController {
14013
14843
  return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14014
14844
  const auditPeerId = deviceAuditPeerId(deviceId);
14015
14845
  const { open } = await this.deviceSessionTarget(request.sessionId);
14846
+ if (request.childSessionId !== undefined) {
14847
+ return this.replyDeviceChildRequest(auditPeerId, open, request.childSessionId, request.questionId, {
14848
+ answers: request.answers,
14849
+ }, signalArg);
14850
+ }
14016
14851
  if (open.kind === 'conversation') {
14017
14852
  return this.replyQuestionForPrincipal('device', auditPeerId, validateRequest(() => assertQuestionReplyRequest({
14018
14853
  projectId: open.projectId,
@@ -16111,38 +16946,10 @@ export class OpenCodeController {
16111
16946
  const request = validateRequest(
16112
16947
  () => assertSessionChildPermissionReplyRequest(requestArg),
16113
16948
  );
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
- ),
16949
+ return this.runOperation(peer, async (signalArg) => this.replyChildRequestForPrincipal(
16950
+ 'browser', peer.id, request,
16951
+ (activeRequiredArg) => this.revalidateChildScope(this.requireChildScope(peer, request), signalArg, activeRequiredArg),
16952
+ signalArg,
16146
16953
  ));
16147
16954
  },
16148
16955
  );
@@ -16154,43 +16961,10 @@ export class OpenCodeController {
16154
16961
  const request = validateRequest(
16155
16962
  () => assertSessionChildQuestionReplyRequest(requestArg),
16156
16963
  );
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
- ),
16964
+ return this.runOperation(peer, async (signalArg) => this.replyChildRequestForPrincipal(
16965
+ 'browser', peer.id, request,
16966
+ (activeRequiredArg) => this.revalidateChildScope(this.requireChildScope(peer, request), signalArg, activeRequiredArg),
16967
+ signalArg,
16194
16968
  ));
16195
16969
  },
16196
16970
  );
@@ -16935,6 +17709,86 @@ export class OpenCodeController {
16935
17709
  * alike. The harness checks the reply against the pending request before it sends anything; elicitations are never
16936
17710
  * answered automatically, auto-accept included.
16937
17711
  */
17712
+ /**
17713
+ * Answers a permission or question of a direct child (an OpenCode subagent) of a managed root conversation, for the
17714
+ * owner's browser and a paired device alike: `verifyArg` proves the session is a direct child of the root (the
17715
+ * browser's child scope, or the same direct-child check for a device) and, while `activeRequiredArg`, that it runs. It
17716
+ * runs before the pending list is read, before the answer is sent and after it; `null` answers reject a question.
17717
+ */
17718
+ private async replyChildRequestForPrincipal(
17719
+ principalArg: TControllerOperationPrincipal,
17720
+ peerIdArg: string,
17721
+ requestArg: {
17722
+ projectId: string;
17723
+ parentSessionId: IControllerRuntimeId & { harnessId: 'opencode' };
17724
+ childSessionId: IControllerRuntimeId & { harnessId: 'opencode' };
17725
+ requestId: IControllerRuntimeId & { harnessId: 'opencode' };
17726
+ } & ({ reply: TControllerPermissionReply; message?: string } | { answers: string[][] | null }),
17727
+ verifyArg: (activeRequiredArg: boolean) => Promise<{ parent: IOpenCodeManagedSessionScopeAuthority }>,
17728
+ signalArg: AbortSignal,
17729
+ ): Promise<{ success: boolean }> {
17730
+ const kind = 'reply' in requestArg ? 'permission' : 'question';
17731
+ return this.runAudited(
17732
+ {
17733
+ type: kind === 'permission' ? 'permission.reply' : 'question.reply',
17734
+ peerId: this.auditPeerId(principalArg, peerIdArg),
17735
+ sessionId: requestArg.childSessionId,
17736
+ requestId: requestArg.requestId,
17737
+ },
17738
+ async () => this.withHarnessSubmissionAdmission(
17739
+ requestArg.projectId,
17740
+ requestArg.parentSessionId,
17741
+ signalArg,
17742
+ async () => {
17743
+ const first = await verifyArg(true);
17744
+ const firstSignal = AbortSignal.any([signalArg, first.parent.runtimeAuthority.signal]);
17745
+ const pending = kind === 'permission'
17746
+ ? await first.parent.client.listPermissions(first.parent.project.directory, requestArg.childSessionId.nativeId, firstSignal)
17747
+ : await first.parent.client.listQuestions(first.parent.project.directory, requestArg.childSessionId.nativeId, firstSignal);
17748
+ this.assertAttentionRequestOwned(pending, requestArg.requestId, kind);
17749
+ const current = await verifyArg(true);
17750
+ const signal = AbortSignal.any([signalArg, current.parent.runtimeAuthority.signal]);
17751
+ const { directory } = current.parent.project;
17752
+ const success = 'reply' in requestArg
17753
+ ? await current.parent.client.replyPermission(directory, requestArg.requestId.nativeId, requestArg.reply, requestArg.message, signal)
17754
+ : requestArg.answers === null
17755
+ ? await current.parent.client.rejectQuestion(directory, requestArg.requestId.nativeId, signal)
17756
+ : await current.parent.client.replyQuestion(directory, requestArg.requestId.nativeId, requestArg.answers, signal);
17757
+ await verifyArg(false);
17758
+ return { success };
17759
+ },
17760
+ ),
17761
+ );
17762
+ }
17763
+
17764
+ /**
17765
+ * A device's proof that `childSessionIdArg` is a direct child of the managed root conversation, by the check the
17766
+ * browser's child scopes run (`observeOpenCodeDirectChild`), and, while `activeRequiredArg`, that it runs: a child
17767
+ * whose turn ended takes no answer.
17768
+ */
17769
+ private async verifyDeviceDirectChild(
17770
+ projectIdArg: string,
17771
+ parentSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
17772
+ childSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
17773
+ signalArg: AbortSignal,
17774
+ activeRequiredArg: boolean,
17775
+ ): Promise<{ parent: IOpenCodeManagedSessionScopeAuthority }> {
17776
+ let observation: Awaited<ReturnType<OpenCodeController['observeOpenCodeDirectChild']>>;
17777
+ try {
17778
+ observation = await this.observeOpenCodeDirectChild(projectIdArg, parentSessionIdArg, childSessionIdArg, signalArg);
17779
+ } catch (errorArg) {
17780
+ if (errorArg instanceof plugins.typedrequest.TypedResponseError
17781
+ && (errorArg.errorData as { code?: unknown } | undefined)?.code === 'child_scope_invalid') {
17782
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
17783
+ }
17784
+ throw errorArg;
17785
+ }
17786
+ if (activeRequiredArg && this.childScopeObservedMode(observation.child.session) !== 'active') {
17787
+ throw deviceRefusal('session_not_found', 'The session has no such direct child that runs; read the session again.');
17788
+ }
17789
+ return observation;
17790
+ }
17791
+
16938
17792
  private async replyElicitationForPrincipal(
16939
17793
  principalArg: TControllerOperationPrincipal,
16940
17794
  peerIdArg: string,
@@ -17377,6 +18231,16 @@ export class OpenCodeController {
17377
18231
  protectedRouterArg.addHandler<TControllerTicketRequest<TTicketOperation>>(`controller.ticket.${operation}`,
17378
18232
  async (requestArg, toolsArg) => {
17379
18233
  const peer = peerFromLocalData(toolsArg?.localData);
18234
+ if (operation === 'answer') {
18235
+ const request = validateRequest(() => assertTicketRequest('answer', requestArg));
18236
+ return this.runOperation(peer, async (signalArg) => this.answerTicketForPrincipal('browser', peer.id, request, signalArg),
18237
+ toolsArg?.abortSignal);
18238
+ }
18239
+ if (operation === 'comment' || operation === 'ask' || operation === 'move') {
18240
+ const request = validateRequest(() => assertTicketRequest(operation, requestArg));
18241
+ return this.runOperation(peer, async (signalArg) => this.changeTicketForPrincipal('browser', peer.id, operation, request, signalArg),
18242
+ toolsArg?.abortSignal);
18243
+ }
17380
18244
  return this.runOperation(peer, async (signalArg) => {
17381
18245
  try {
17382
18246
  const owner = ticketOwnerActor(await this.requireAuthStore().getState());
@@ -17392,6 +18256,88 @@ export class OpenCodeController {
17392
18256
  }
17393
18257
  }
17394
18258
 
18259
+ /**
18260
+ * Answers a ticket question as the owner, for the owner's browser and a paired device alike, audited as
18261
+ * `ticket.answer` with the peer. A deploy plan's or a maintenance window's question takes it as the owner's go. The
18262
+ * identical answer again is a confirmed replay; a different one is refused (`ticket_question_answered`), and the
18263
+ * client keeps the owner's choice.
18264
+ */
18265
+ private async answerTicketForPrincipal(
18266
+ principalArg: TControllerOperationPrincipal,
18267
+ peerIdArg: string,
18268
+ requestArg: TTicketRequest<'answer'>,
18269
+ signalArg: AbortSignal,
18270
+ ): Promise<TTicketResponse<'answer'>> {
18271
+ return this.runAudited({ type: 'ticket.answer', peerId: this.auditPeerId(principalArg, peerIdArg) }, async () => {
18272
+ try {
18273
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18274
+ return await this.ticketStore.execute('answer', requestArg, owner, signalArg);
18275
+ } catch (errorArg) {
18276
+ if (errorArg instanceof TicketError) throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
18277
+ throw errorArg;
18278
+ }
18279
+ });
18280
+ }
18281
+
18282
+ /**
18283
+ * Comments on a ticket, asks on it or moves it as the owner, for the owner's browser and a paired device alike,
18284
+ * audited as `ticket.comment`, `ticket.ask` or `ticket.move` with the peer (the envelope alone). The ticket store
18285
+ * decides every change in one transaction: a refusal changes nothing and carries the store's code and reason.
18286
+ */
18287
+ private async changeTicketForPrincipal<TMethod extends TTicketChangeOperation>(
18288
+ principalArg: TControllerOperationPrincipal,
18289
+ peerIdArg: string,
18290
+ methodArg: TMethod,
18291
+ requestArg: TTicketRequest<TMethod>,
18292
+ signalArg: AbortSignal,
18293
+ ): Promise<TTicketResponse<TMethod>> {
18294
+ return this.runAudited({ type: ticketChangeAuditTypes[methodArg], peerId: this.auditPeerId(principalArg, peerIdArg) }, async () => {
18295
+ try {
18296
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18297
+ return await this.ticketStore.execute(methodArg, requestArg, owner, signalArg);
18298
+ } catch (errorArg) {
18299
+ if (errorArg instanceof TicketError) throw new plugins.typedrequest.TypedResponseError(errorArg.message,
18300
+ { code: errorArg.code, ...readTicketRevisionConflict(errorArg) });
18301
+ throw errorArg;
18302
+ }
18303
+ });
18304
+ }
18305
+
18306
+ /**
18307
+ * The owner, whom a device's ticket request runs as, and what the device's ticket views read besides the tickets:
18308
+ * the owner's principal id, which they replace with the `owner` kind, and the session feed's published rows.
18309
+ */
18310
+ private async deviceTicketViewer(): Promise<{ owner: ITicketActor; viewer: IDeviceTicketViewer }> {
18311
+ const owner = ticketOwnerActor(await this.requireAuthStore().getState());
18312
+ return { owner, viewer: { ownerId: owner.id, rowOf: (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg) } };
18313
+ }
18314
+
18315
+ /** The ticket a ticket's `parentId` names, which a device's card and detail name; a store refusal as a device's. */
18316
+ private async deviceTicketParent(ownerArg: ITicketActor, ticketArg: ITicket, signalArg: AbortSignal): Promise<ITicket | undefined> {
18317
+ if (ticketArg.parentId === undefined) return undefined;
18318
+ try {
18319
+ return (await this.ticketStore.execute('get', { ticketId: ticketArg.parentId, limit: 1 }, ownerArg, signalArg)).ticket;
18320
+ } catch (errorArg) {
18321
+ throw deviceTicketRefusal(errorArg);
18322
+ }
18323
+ }
18324
+
18325
+ private requireInbox(): ControllerInbox {
18326
+ if (!this.inbox) {
18327
+ throw new plugins.typedrequest.TypedResponseError('The Inbox is not running.', { code: 'controller_unavailable' });
18328
+ }
18329
+ return this.inbox;
18330
+ }
18331
+
18332
+ /** The Inbox: what waits for the owner, read after every source that changed (AGL-1635). */
18333
+ private registerInboxHandlers(protectedRouterArg: ControllerProtectedRouter): void {
18334
+ protectedRouterArg.addHandler<IReq_ControllerInboxList>('controller.inbox.list', async (requestArg, toolsArg) => {
18335
+ validateRequest(() => assertEmptyRequest(requestArg));
18336
+ const peer = peerFromLocalData(toolsArg?.localData);
18337
+ return this.runOperation(peer, async () => this.requireInbox().list(), toolsArg?.abortSignal);
18338
+ });
18339
+ }
18340
+
17395
18341
  /**
17396
18342
  * The host's driver: one Flex session that no session list shows, opened from the topbar. Fleet
17397
18343
  * events reach it through the relay once it exists.
@@ -17433,8 +18379,8 @@ export class OpenCodeController {
17433
18379
  ...(model?.providerConnectionId === undefined ? {} : { providerConnectionId: model.providerConnectionId }),
17434
18380
  }, signalArg, { nativeId: nativeIdArg });
17435
18381
  },
17436
- latestAssistantText: (projectIdArg, nativeIdArg, signalArg) => (
17437
- this.latestDriverAssistantText(projectIdArg, nativeIdArg, signalArg)
18382
+ latestAssistantMessage: (projectIdArg, nativeIdArg, signalArg) => (
18383
+ this.latestDriverAssistantMessage(projectIdArg, nativeIdArg, signalArg)
17438
18384
  ),
17439
18385
  publish: (statusArg) => {
17440
18386
  void this.pushControllerEvent({ type: 'driver.changed', driverStatus: statusArg, timestamp: Date.now() })
@@ -17472,7 +18418,8 @@ export class OpenCodeController {
17472
18418
  relayed: async (eventsArg) => {
17473
18419
  const authority = this.configurationAuthority;
17474
18420
  if (!authority) throw new Error('The configuration authority is unavailable.');
17475
- const reportWorkers = await this.requireDirectReports().reportWorkers((await authority.getResource()).resourceId);
18421
+ const groups = await this.requireDirectReports().reportWorkers((await authority.getResource()).resourceId);
18422
+ const reportWorkers = new Set([...groups.values()].flat().map(({ worker }) => worker.name));
17476
18423
  return eventsArg.filter((eventArg) => !eventArg.workerName || !reportWorkers.has(eventArg.workerName));
17477
18424
  },
17478
18425
  });
@@ -17673,17 +18620,19 @@ export class OpenCodeController {
17673
18620
  }
17674
18621
  }
17675
18622
 
17676
- private async latestDriverAssistantText(
18623
+ /** The driver's newest assistant transcript entry with text: the entry's own id (a Flex message or part id). */
18624
+ private async latestDriverAssistantMessage(
17677
18625
  projectIdArg: string,
17678
18626
  nativeIdArg: string,
17679
18627
  signalArg?: AbortSignal,
17680
- ): Promise<string | undefined> {
18628
+ ): Promise<IDriverAssistantMessage | undefined> {
17681
18629
  try {
17682
18630
  const page = await this.requireFlexProjectionReader().listMessagePage(projectIdArg, nativeIdArg, { limit: 8 }, signalArg);
17683
- return page.messages
18631
+ const message = page.messages
17684
18632
  .flatMap((messageArg) => this.toFlexMessageBundle(messageArg).messages)
17685
18633
  .reverse()
17686
- .find((messageArg) => messageArg.role === 'assistant' && messageArg.text.trim())?.text;
18634
+ .find((messageArg) => messageArg.role === 'assistant' && messageArg.text.trim());
18635
+ return message === undefined ? undefined : { id: message.id.nativeId, text: message.text, createdAt: message.createdAt };
17687
18636
  } catch (errorArg) {
17688
18637
  if (errorArg instanceof FlexProjectionNotFoundError) return undefined;
17689
18638
  throw errorArg;
@@ -17773,18 +18722,21 @@ export class OpenCodeController {
17773
18722
  );
17774
18723
  }
17775
18724
 
18725
+ /** A driver operation for the browser: a `DriverError` is answered with its own code (a device's: `serveDeviceDriver`). */
18726
+ private async serveDriver<T>(operationArg: () => Promise<T>): Promise<T> {
18727
+ try {
18728
+ return await operationArg();
18729
+ } catch (errorArg) {
18730
+ if (errorArg instanceof DriverError) {
18731
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
18732
+ }
18733
+ throw errorArg;
18734
+ }
18735
+ }
18736
+
17776
18737
  /** The driver topbar: the host's one driver session, its status, and the unread turns it marks seen. */
17777
18738
  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
- };
18739
+ const serve = <T>(operationArg: () => Promise<T>): Promise<T> => this.serveDriver(operationArg);
17788
18740
  protectedRouterArg.addHandler<IReq_ControllerDriverGet>(
17789
18741
  'controller.driver.get',
17790
18742
  async (requestArg, toolsArg) => {
@@ -18033,9 +18985,12 @@ export class OpenCodeController {
18033
18985
  async (requestArg, toolsArg) => {
18034
18986
  const peer = peerFromLocalData(toolsArg?.localData);
18035
18987
  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);
18988
+ return this.runOperation(peer, async (signalArg) => {
18989
+ await this.sendNativeSession(peer.id, ref, text, attachments, signalArg, assertNativeSessionWritable,
18990
+ { kind: 'agent', label: 'Owner', subject: agentMessageSubjects.ownerNativeView });
18991
+ // The session as the send left it, read apart from the audited send.
18992
+ return { session: await this.serveNativeSession(signalArg, async () => (await this.nativeSessions.resolve(ref)).session) };
18993
+ }, toolsArg?.abortSignal);
18039
18994
  },
18040
18995
  );
18041
18996
 
@@ -18268,16 +19223,22 @@ export class OpenCodeController {
18268
19223
  if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
18269
19224
  // The session state store states its own refusals: a stale scratchpad revision, a missing record.
18270
19225
  if (errorArg instanceof AuthError) throw asTypedResponseError(errorArg, 'native session');
18271
- throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'native_session_failed' });
19226
+ // Whether the message may have reached the session: a refusal before dispatch did not, a dispatched failure may have.
19227
+ const outcome = errorArg instanceof FleetDispatchError ? { outcome: errorArg.dispatched ? 'unknown' as const : 'refused' as const } : {};
19228
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'native_session_failed', ...outcome });
18272
19229
  }
18273
19230
  }
18274
19231
 
18275
19232
  /**
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.
19233
+ * The one send to a native session, for the browser's `controller.nativesession.send`, a paired device, the fleet's
19234
+ * `native-message` and an MCP `session_message`: audited as `session.send`, under the session's lock, where the
19235
+ * session is resolved again and `assertArg` refuses what this caller may not write to, so a session whose state
19236
+ * changed meanwhile is refused. A Codex thread goes through its shared server, a Claude Code background job is reached
19237
+ * through Claude Code itself (woken while settled, its inbox while it runs), and another settled Claude Code session
19238
+ * resumes in AGL's own Claude Code. The owner's own text (`ownerArg`) goes into a job's inbox as the owner's agent
19239
+ * message: a peer message names no sender of its own. Resolves right after the dispatch with, for a job, how it took
19240
+ * the message, and reads nothing after it: a failed read must never turn a delivered message into a refusal, which a
19241
+ * caller would answer by sending again. A caller that shows the session reads it afterwards.
18281
19242
  */
18282
19243
  private async sendNativeSession(
18283
19244
  peerIdArg: string,
@@ -18286,25 +19247,29 @@ export class OpenCodeController {
18286
19247
  attachmentsArg: readonly IControllerDraftAttachment[] | undefined,
18287
19248
  signalArg: AbortSignal,
18288
19249
  assertArg: (resolvedArg: IResolvedNativeSession) => void,
18289
- ): Promise<IControllerNativeSession> {
19250
+ ownerArg?: IControllerPromptSender,
19251
+ ): Promise<{ job?: TControllerNativeJobDelivery }> {
18290
19252
  const sessionId = nativeSessionRuntimeId(refArg);
18291
19253
  return this.runAudited({ type: 'session.send', peerId: peerIdArg, sessionId }, () => this.serveNativeSession(signalArg, async () => {
18292
19254
  const scope = (await this.nativeSessions.resolve(refArg)).scope;
19255
+ let job: TControllerNativeJobDelivery | undefined;
18293
19256
  await this.withSessionStateMutation(scope, sessionId, async () => {
18294
19257
  const resolved = await this.nativeSessions.resolve(refArg);
18295
19258
  assertArg(resolved);
18296
19259
  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);
19260
+ else if (resolved.claudeJob) {
19261
+ job = await this.sendNativeClaudeJob(resolved, resolved.claudeJob === 'inbox' && ownerArg ? formatAgentMessage(ownerArg, textArg) : textArg, attachmentsArg);
19262
+ } else await this.sendNativeClaudeSession(resolved, textArg, attachmentsArg, signalArg);
18299
19263
  });
18300
- return (await this.nativeSessions.resolve(refArg)).session;
19264
+ return job === undefined ? {} : { job };
18301
19265
  }));
18302
19266
  }
18303
19267
 
18304
19268
  /**
18305
19269
  * The fleet's `native-message`: resolves the Claude Code background job the caller names by id or prefix, refuses
18306
19270
  * 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`.
19271
+ * and sends the message behind the `session_message` attribution header through `sendNativeSession`: a wake of a
19272
+ * settled job, or its inbox while it runs.
18308
19273
  */
18309
19274
  private async sendFleetNativeMessage(
18310
19275
  requestArg: TFleetWorkerRequest<'native-message'>,
@@ -18321,7 +19286,7 @@ export class OpenCodeController {
18321
19286
  if (readOnly) {
18322
19287
  // What the caller can do instead: steer the worker, wait for the job to settle, or adopt it into its profile.
18323
19288
  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}\`.`
19289
+ : readOnly.reason === 'running' || readOnly.reason === 'jobHeld' || readOnly.reason === 'unaddressable' ? ` Message it, or adopt it, once it settles; it is adopted with \`${adopt}\`.`
18325
19290
  : readOnly.reason === 'jobFailed' ? ` A failed job takes no wake; adopt it with \`${adopt}\`.`
18326
19291
  : readOnly.reason === 'profileHome' ? ` Adopt it as a worker of that profile with \`${adopt}\`.` : '';
18327
19292
  throw new plugins.typedrequest.TypedResponseError(`${readOnly.message}${next}`, { code: 'session_read_only' });
@@ -18336,12 +19301,16 @@ export class OpenCodeController {
18336
19301
  const jobId = found.agent.id;
18337
19302
  if (!jobId) throw new plugins.typedrequest.TypedResponseError('Claude Code lists this session without a job id, so it cannot wake it.', { code: 'session_read_only' });
18338
19303
  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);
19304
+ const { job } = await this.sendNativeSession(peerId, found.ref, text, undefined, this.operationAbortController.signal, assertMessageable);
18340
19305
  return {
18341
- delivery: 'native-wake', nativeId: found.agent.sessionId, jobId, cwd: found.agent.cwd,
19306
+ delivery: job === 'inbox' ? 'native-inbox' : 'native-wake', nativeId: found.agent.sessionId, jobId, cwd: found.agent.cwd,
18342
19307
  ...(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.',
19308
+ note: job === 'inbox'
19309
+ ? 'Delivered into the inbox of a running Claude Code background job no fleet worker binds, through Claude Code\'s own '
19310
+ + 'SendMessage: accepted and queued there, not yet read. It holds no dispatch fence, writes no ticket comment and does not '
19311
+ + 'observe the turn that reads it. Adopt the job, once it settles, to steer and observe it as a fleet worker.'
19312
+ : 'Delivered as a native wake of a Claude Code background job no fleet worker binds: it holds no dispatch fence, '
19313
+ + 'writes no ticket comment and does not observe the woken turn. Adopt the job to steer and observe it as a fleet worker.',
18345
19314
  adopt,
18346
19315
  };
18347
19316
  }
@@ -18402,18 +19371,21 @@ export class OpenCodeController {
18402
19371
  }
18403
19372
 
18404
19373
  /**
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.
19374
+ * Sends to a Claude Code background job through Claude Code itself, so the job stays the session's owner: a settled
19375
+ * job is woken with the message, a running one takes it in its inbox, as the resolution prepared it. Claude Code does
19376
+ * not report when the turn that reads it ends, so the upload stays for the sweep unless the message never reached
19377
+ * Claude Code.
18408
19378
  */
18409
19379
  private async sendNativeClaudeJob(
18410
19380
  resolvedArg: IResolvedNativeSession,
18411
19381
  textArg: string,
18412
19382
  attachmentsArg: readonly IControllerDraftAttachment[] | undefined,
18413
- ): Promise<void> {
19383
+ ): Promise<TControllerNativeJobDelivery> {
18414
19384
  const upload = await this.createRetainedUpload(attachmentsArg);
19385
+ let receipt: Awaited<ReturnType<FleetWorkers['nativeSend']>>;
18415
19386
  try {
18416
- await this.requireFleetWorkers().nativeSend('claude', resolvedArg.native, `${textArg}${upload?.promptSuffix ?? ''}`, () => undefined);
19387
+ const session = { ...resolvedArg.native, jobDelivery: resolvedArg.claudeJob!, ...(resolvedArg.peerHomes ? { peerHomes: resolvedArg.peerHomes } : {}) };
19388
+ receipt = await this.requireFleetWorkers().nativeSend('claude', session, `${textArg}${upload?.promptSuffix ?? ''}`, () => undefined);
18417
19389
  } catch (errorArg) {
18418
19390
  if (upload && errorArg instanceof FleetDispatchError && !errorArg.dispatched) {
18419
19391
  void this.trackOperationPromise(upload.cleanup())
@@ -18422,6 +19394,8 @@ export class OpenCodeController {
18422
19394
  throw errorArg;
18423
19395
  }
18424
19396
  upload?.release();
19397
+ if (!receipt.job) throw new FleetDispatchError('Claude Code did not say how the background job took the message. Inspect it before sending again.', true);
19398
+ return receipt.job;
18425
19399
  }
18426
19400
 
18427
19401
  /**
@@ -18447,17 +19421,24 @@ export class OpenCodeController {
18447
19421
  }
18448
19422
  }
18449
19423
 
19424
+ /**
19425
+ * A direct report operation for the owner's browser or a device, given the owner: its failures are bounded messages
19426
+ * for the owner (`direct_report_failed`), which the Driver view and a device show as they are.
19427
+ */
19428
+ private async serveDirectReport<T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> {
19429
+ try {
19430
+ return await operationArg((await this.readFleetScope()).owner);
19431
+ } catch (errorArg) {
19432
+ if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
19433
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'direct_report_failed' });
19434
+ }
19435
+ }
19436
+
18450
19437
  /** The Driver view's direct reports: sessions that report to the owner, appointed from the fleet or adopted by reference. */
18451
19438
  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
- };
19439
+ const serve = <T>(signalArg: AbortSignal, operationArg: (ownerArg: string) => Promise<T>): Promise<T> => (
19440
+ this.serveDirectReport(signalArg, operationArg)
19441
+ );
18461
19442
  protectedRouterArg.addHandler<IReq_ControllerDirectReportList>(
18462
19443
  'controller.directreport.list',
18463
19444
  async (requestArg, toolsArg) => {
@@ -18518,36 +19499,61 @@ export class OpenCodeController {
18518
19499
  )), toolsArg?.abortSignal);
18519
19500
  },
18520
19501
  );
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
19502
  protectedRouterArg.addHandler<IReq_ControllerDirectReportMessage>(
18524
19503
  'controller.directreport.message',
18525
19504
  async (requestArg, toolsArg) => {
18526
- const { name, text, expectedTurnId, attachments } = validateRequest(() => assertDirectReportMessageRequest(requestArg));
19505
+ const request = validateRequest(() => assertDirectReportMessageRequest(requestArg));
18527
19506
  const peer = peerFromLocalData(toolsArg?.localData);
18528
- 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) };
18546
- }), toolsArg?.abortSignal);
19507
+ return this.runOperation(peer, (signalArg) => serve(signalArg, async (ownerArg) => (
19508
+ this.messageDirectReportForPrincipal('browser', peer.id, ownerArg, request, signalArg)
19509
+ )), toolsArg?.abortSignal);
18547
19510
  },
18548
19511
  );
18549
19512
  }
18550
19513
 
19514
+ /**
19515
+ * The owner's own message to the active direct report `name`, from the Driver view or a paired device, audited as
19516
+ * `session.message` from the `Owner` for the caller. A fleet worker report is steered through the report's driver
19517
+ * ticket, as the driver's `directreport_message` does, and answers with the settled steer job, audited `failed`
19518
+ * unless the job succeeded; a steer the fleet refused is `direct_report_failed` with the fleet's reason, also audited
19519
+ * `failed`. A Codex thread takes it as the owner's agent message.
19520
+ */
19521
+ private async messageDirectReportForPrincipal(
19522
+ principalArg: TControllerOperationPrincipal,
19523
+ peerIdArg: string,
19524
+ ownerArg: string,
19525
+ requestArg: IReq_ControllerDirectReportMessage['request'],
19526
+ signalArg: AbortSignal,
19527
+ ): Promise<IReq_ControllerDirectReportMessage['response']> {
19528
+ const peerId = this.auditPeerId(principalArg, peerIdArg);
19529
+ const { name, text, expectedTurnId, attachments } = requestArg;
19530
+ const channel = await this.requireDirectReports().channelOf(ownerArg, name);
19531
+ if (channel.kind === 'session') {
19532
+ if (attachments) {
19533
+ throw new plugins.typedrequest.TypedResponseError(
19534
+ 'A Codex thread report takes text only.', { code: 'invalid_request' },
19535
+ );
19536
+ }
19537
+ const { delivery, turnId } = await this.messageDirectReportSession(channel, 'owner', peerId, text, expectedTurnId);
19538
+ return { delivery, ...(turnId === undefined ? {} : { turnId }) };
19539
+ }
19540
+ if (expectedTurnId !== undefined) throw new Error('expectedTurnId names the turn of a Codex thread; a fleet worker report is steered through its ticket.');
19541
+ return await this.runAudited({ type: 'session.message', peerId, sessionId: directReportRuntimeId(channel.report), senderLabel: 'Owner' }, async () => {
19542
+ try {
19543
+ const fleetWorkers = this.requireFleetWorkers();
19544
+ const configuration = (await this.readFleetScope()).configuration;
19545
+ const job = await this.withRetainedSteerUpload(attachments, async (suffixArg) => (await fleetWorkers.execute('steer', {
19546
+ messages: [{ name: channel.workerName, text: formatOwnerFleetMessage(`${text}${suffixArg}`) }], ticketKey: channel.report.driverTicketKey,
19547
+ }, configuration, ownerArg, signalArg)).job);
19548
+ return { job: await fleetWorkers.settled(ownerArg, job.id, signalArg) };
19549
+ } catch (errorArg) {
19550
+ // The fleet's own reason, as `serveDirectReport` gives it, before the audit would reduce it to a generic failure.
19551
+ if (signalArg.aborted || errorArg instanceof plugins.typedrequest.TypedResponseError || !(errorArg instanceof Error)) throw errorArg;
19552
+ throw new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 4096), { code: 'direct_report_failed' });
19553
+ }
19554
+ }, ({ job }) => job.state === 'succeeded' ? 'succeeded' : 'failed');
19555
+ }
19556
+
18551
19557
  /** The driver session's instructions, notes and tools; the caller checked its session authority. */
18552
19558
  private async handleFlexDriverHostRequest(
18553
19559
  methodArg: 'driver.resolve' | 'driver.tool',
@@ -19244,9 +20250,14 @@ export class OpenCodeController {
19244
20250
  );
19245
20251
  }
19246
20252
 
20253
+ /**
20254
+ * Runs an operation between its `attempted` record and its terminal one. `outcomeOfArg` names the outcome of an
20255
+ * operation that returns its own failure (a settled job that failed), which is then recorded `failed`.
20256
+ */
19247
20257
  private async runAudited<T>(
19248
20258
  auditArg: Omit<IRecordAuditEventInput, 'outcome'>,
19249
20259
  operationArg: (operationIdArg: string) => Promise<T>,
20260
+ outcomeOfArg: (resultArg: T) => 'succeeded' | 'failed' = () => 'succeeded',
19250
20261
  ): Promise<T> {
19251
20262
  const operationId = plugins.crypto.randomBytes(24).toString('base64url');
19252
20263
  const correlatedAudit = { ...auditArg, operationId };
@@ -19266,11 +20277,12 @@ export class OpenCodeController {
19266
20277
  try {
19267
20278
  result = await operationArg(operationId);
19268
20279
  } catch (error) {
19269
- // A refused workspace path is a policy decision, recorded as one.
19270
- const outcome = error instanceof AuthError
20280
+ // A refused workspace path is a policy decision, recorded as one; a direct report that took no message is a failure.
20281
+ const outcome = (error instanceof AuthError
19271
20282
  || error instanceof plugins.typedrequest.TypedResponseError
19272
20283
  || error instanceof ControllerWorkspaceError
19273
- || error instanceof ConfigurationError
20284
+ || error instanceof ConfigurationError)
20285
+ && !(error instanceof plugins.typedrequest.TypedResponseError && error.errorData?.code === 'direct_report_failed')
19274
20286
  ? 'denied'
19275
20287
  : 'failed';
19276
20288
  const suppressUnboundedDenialAudit = error instanceof AuthError
@@ -19301,7 +20313,7 @@ export class OpenCodeController {
19301
20313
  try {
19302
20314
  await this.requireAuthStore().recordAuditEvent({
19303
20315
  ...correlatedAudit,
19304
- outcome: 'succeeded',
20316
+ outcome: outcomeOfArg(result),
19305
20317
  });
19306
20318
  } catch {
19307
20319
  // The durable attempted record preserves the audit gap. The completed
@@ -20292,6 +21304,7 @@ export class OpenCodeController {
20292
21304
  reading,
20293
21305
  account.maxUsagePercent,
20294
21306
  account.lapsesAt,
21307
+ account.renewsAt,
20295
21308
  now,
20296
21309
  account.reserveLiftUntil,
20297
21310
  );
@@ -23525,6 +24538,80 @@ export class OpenCodeController {
23525
24538
  });
23526
24539
  }
23527
24540
 
24541
+ /**
24542
+ * The requests that wait in a managed OpenCode root conversation and in its direct children, from the controller's
24543
+ * own reads (OpenCode's pending lists and the root's direct children), whichever browser has the conversation open:
24544
+ * the root's own requests, and each direct child with requests, the most recently updated first. `strictArg` lets a
24545
+ * failed pending list fail the read instead of reading as empty.
24546
+ */
24547
+ private async readOpenCodeFamilyAttention(
24548
+ projectIdArg: string,
24549
+ parentSessionIdArg: IControllerRuntimeId & { harnessId: 'opencode' },
24550
+ signalArg: AbortSignal,
24551
+ strictArg = false,
24552
+ ): Promise<{
24553
+ parent: IOpenCodeManagedSessionScopeAuthority;
24554
+ own: { permissions: IControllerPermission[]; questions: IControllerQuestion[] };
24555
+ children: Array<{ child: IOpenCodeDirectChildObservation; permissions: IControllerPermission[]; questions: IControllerQuestion[] }>;
24556
+ } | undefined> {
24557
+ const parent = await this.readManagedOpenCodeScopeAuthority(
24558
+ projectIdArg,
24559
+ parentSessionIdArg,
24560
+ signalArg,
24561
+ );
24562
+ if (parent.session.parentId !== undefined || parent.session.archivedAt !== undefined) return undefined;
24563
+ const signal = AbortSignal.any([signalArg, parent.runtimeAuthority.signal]);
24564
+ const permissionsRead = parent.client.listPermissions(parent.project.directory, undefined, signal);
24565
+ const questionsRead = parent.client.listQuestions(parent.project.directory, undefined, signal);
24566
+ const [children, pending] = await Promise.all([
24567
+ parent.client.listDirectChildSessionObservations(
24568
+ parent.project.directory,
24569
+ parentSessionIdArg.nativeId,
24570
+ signal,
24571
+ ),
24572
+ strictArg
24573
+ ? Promise.all([permissionsRead, questionsRead]).then(([permissions, questions]) => ({ permissions, questions }))
24574
+ : settleControllerAttentionLists(permissionsRead, questionsRead),
24575
+ ]);
24576
+ this.assertOpenCodeSessionIdentityGenerationCurrent(
24577
+ parent.supervisor,
24578
+ parent.client,
24579
+ parent.runtimeAuthority,
24580
+ );
24581
+ this.assertChildScopeParentAdmission(projectIdArg, parentSessionIdArg);
24582
+
24583
+ const permissionsBySession = new Map<string, IControllerPermission[]>();
24584
+ for (const permission of pending.permissions) {
24585
+ const key = controllerRuntimeIdKey(permission.sessionId);
24586
+ const entries = permissionsBySession.get(key) ?? [];
24587
+ entries.push(permission);
24588
+ permissionsBySession.set(key, entries);
24589
+ }
24590
+ const questionsBySession = new Map<string, IControllerQuestion[]>();
24591
+ for (const question of pending.questions) {
24592
+ const key = controllerRuntimeIdKey(question.sessionId);
24593
+ const entries = questionsBySession.get(key) ?? [];
24594
+ entries.push(question);
24595
+ questionsBySession.set(key, entries);
24596
+ }
24597
+ const parentKey = controllerRuntimeIdKey(parentSessionIdArg);
24598
+ return {
24599
+ parent,
24600
+ own: { permissions: permissionsBySession.get(parentKey) ?? [], questions: questionsBySession.get(parentKey) ?? [] },
24601
+ children: children
24602
+ .flatMap((childArg) => {
24603
+ const key = controllerRuntimeIdKey(childArg.session.id);
24604
+ const permissions = permissionsBySession.get(key) ?? [];
24605
+ const questions = questionsBySession.get(key) ?? [];
24606
+ return permissions.length > 0 || questions.length > 0 ? [{ child: childArg, permissions, questions }] : [];
24607
+ })
24608
+ .sort((leftArg, rightArg) => (
24609
+ rightArg.child.session.updatedAt - leftArg.child.session.updatedAt
24610
+ || leftArg.child.session.id.nativeId.localeCompare(rightArg.child.session.id.nativeId)
24611
+ )),
24612
+ };
24613
+ }
24614
+
23528
24615
  private async readBrowserChildAttention(
23529
24616
  peerArg: IControllerPeer,
23530
24617
  projectIdArg: string,
@@ -23532,62 +24619,13 @@ export class OpenCodeController {
23532
24619
  signalArg: AbortSignal,
23533
24620
  ): Promise<Pick<IReq_ControllerSessionGet['response'], 'childAttention' | 'childAttentionLimited'>> {
23534
24621
  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
- ));
24622
+ const family = await this.readOpenCodeFamilyAttention(projectIdArg, parentSessionIdArg, signalArg);
24623
+ if (!family) return {};
24624
+ const candidates = family.children;
23584
24625
  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;
24626
+ || candidates.reduce((countArg, candidateArg) => (
24627
+ countArg + candidateArg.permissions.length + candidateArg.questions.length
24628
+ ), 0) > maxChildAttentionItems;
23591
24629
  const childAttention: IControllerChildAttention[] = [];
23592
24630
  let itemCount = 0;
23593
24631
  for (const candidate of candidates.slice(0, maxChildAttentionChildren)) {
@@ -23597,7 +24635,7 @@ export class OpenCodeController {
23597
24635
  detail = await this.openChildScope(peerArg, {
23598
24636
  projectId: projectIdArg,
23599
24637
  parentSessionId: parentSessionIdArg,
23600
- childSessionId: candidate.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
24638
+ childSessionId: candidate.child.session.id as IControllerRuntimeId & { harnessId: 'opencode' },
23601
24639
  }, signalArg);
23602
24640
  } catch {
23603
24641
  signalArg.throwIfAborted();
@@ -36065,6 +37103,7 @@ export class OpenCodeController {
36065
37103
  private async pushControllerEvent(eventArg: IControllerEvent): Promise<void> {
36066
37104
  this.driverService?.observe(eventArg);
36067
37105
  this.sessionFeed?.observe(eventArg);
37106
+ this.inbox?.observe(eventArg);
36068
37107
  const browsers = this.controllerEventDeliveryQueues().push(eventArg);
36069
37108
  // A device receives an allowlist of events in its own reduced shape (`deviceEvent`), through queues of its own.
36070
37109
  if (this.devices?.hasLivePeers() === true && deviceRelayedEventTypes.has(eventArg.type)) {
@@ -36090,14 +37129,23 @@ export class OpenCodeController {
36090
37129
  ));
36091
37130
  return targets.map((targetArg) => ({
36092
37131
  peerId: targetArg.peer.id,
37132
+ // One queued controller event may be several device events: each is sent in order, as the queue sends its
37133
+ // events, every one attempted though one before it was not acknowledged; the first failure is the send's.
36093
37134
  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 });
37135
+ let failure: { error: unknown } | undefined;
37136
+ for (const event of deviceEvent(eventArg, (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg), this.driverService)) {
37137
+ if (devices.deviceIdOf(targetArg.peer) === undefined) break;
37138
+ try {
37139
+ await typedSocket.createTypedRequest<IReq_DeviceEventPush>(
37140
+ 'device.event',
37141
+ targetArg,
37142
+ { timeoutMs: 2_000 },
37143
+ ).fire({ event }, { timeoutMs: 2_000, maxRetries: 0 });
37144
+ } catch (errorArg) {
37145
+ failure ??= { error: errorArg };
37146
+ }
37147
+ }
37148
+ if (failure !== undefined) throw failure.error;
36101
37149
  },
36102
37150
  }));
36103
37151
  },