agl 42.0.0 → 42.1.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 (58) hide show
  1. package/changelog.md +6 -0
  2. package/dist_serve/bundle.js +2493 -2143
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/aglapisurface.document.js +2 -2
  6. package/dist_ts/classes.authstore.d.ts +2 -0
  7. package/dist_ts/classes.authstore.js +50 -17
  8. package/dist_ts/classes.controller.d.ts +71 -2
  9. package/dist_ts/classes.controller.js +500 -113
  10. package/dist_ts/classes.controllerdevices.d.ts +128 -0
  11. package/dist_ts/classes.controllerdevices.js +472 -0
  12. package/dist_ts/classes.sessionfeed.d.ts +10 -1
  13. package/dist_ts/classes.sessionfeed.js +12 -2
  14. package/dist_ts/classes.validation.d.ts +2 -0
  15. package/dist_ts/classes.validation.js +2 -2
  16. package/dist_ts/functions.deviceapi.d.ts +28 -0
  17. package/dist_ts/functions.deviceapi.js +246 -0
  18. package/dist_ts/functions.deviceproof.d.ts +33 -0
  19. package/dist_ts/functions.deviceproof.js +93 -0
  20. package/dist_ts/functions.remotecli.d.ts +1 -1
  21. package/dist_ts/functions.remotecli.js +12 -7
  22. package/dist_ts/interfaces.auth.d.ts +1 -1
  23. package/dist_ts/interfaces.auth.js +6 -1
  24. package/dist_ts_interfaces/devices.d.ts +331 -0
  25. package/dist_ts_interfaces/devices.js +34 -0
  26. package/dist_ts_interfaces/index.d.ts +2 -0
  27. package/dist_ts_interfaces/index.js +3 -1
  28. package/dist_ts_interfaces/interfaces.d.ts +4 -2
  29. package/dist_ts_interfaces/interfaces.js +3 -2
  30. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  31. package/dist_ts_interfaces/requests.d.ts +2 -1
  32. package/dist_ts_interfaces/requests.devices.d.ts +89 -0
  33. package/dist_ts_interfaces/requests.devices.js +2 -0
  34. package/dist_ts_interfaces/requests.js +1 -1
  35. package/package.json +1 -1
  36. package/readme.md +36 -4
  37. package/ts/00_commitinfo_data.ts +1 -1
  38. package/ts/aglapi/aglapisurface.document.ts +2 -2
  39. package/ts/classes.authstore.ts +46 -14
  40. package/ts/classes.controller.ts +697 -167
  41. package/ts/classes.controllerdevices.ts +469 -0
  42. package/ts/classes.sessionfeed.ts +13 -1
  43. package/ts/classes.validation.ts +1 -1
  44. package/ts/functions.deviceapi.ts +295 -0
  45. package/ts/functions.deviceproof.ts +118 -0
  46. package/ts/functions.remotecli.ts +11 -5
  47. package/ts/interfaces.auth.ts +5 -0
  48. package/ts_interfaces/devices.schema.json +890 -0
  49. package/ts_interfaces/devices.ts +392 -0
  50. package/ts_interfaces/index.ts +2 -0
  51. package/ts_interfaces/interfaces.ts +4 -1
  52. package/ts_interfaces/mcprequests.ts +1 -1
  53. package/ts_interfaces/requests.devices.ts +95 -0
  54. package/ts_interfaces/requests.ts +10 -0
  55. package/ts_web/00_commitinfo_data.ts +1 -1
  56. package/ts_web/classes.controllersocketclient.ts +27 -0
  57. package/ts_web/elements.devices.ts +752 -0
  58. package/ts_web/elements.harnesscontrollerapp.ts +18 -1
@@ -89,6 +89,25 @@ import {
89
89
  import { commitinfo } from './00_commitinfo_data.js';
90
90
  import { controllerFailureJournal } from './classes.failurejournal.js';
91
91
  import { ControllerEventDelivery } from './classes.controllereventdelivery.js';
92
+ import { ControllerDevices, devicePeerStateKey, deviceRefusal, type IControllerDevicePeer } from './classes.controllerdevices.js';
93
+ import {
94
+ assertDeviceAuthChallengeRequest,
95
+ assertDeviceAuthProveRequest,
96
+ assertDevicePairingCancelRequest,
97
+ assertDevicePairRequest,
98
+ assertDeviceRevokeRequest,
99
+ assertDevicePermissionReplyRequest,
100
+ assertDeviceQuestionReplyRequest,
101
+ assertDeviceSessionReadRequest,
102
+ assertDeviceSessionSendRequest,
103
+ deviceEvent,
104
+ deviceMessages,
105
+ devicePermissions,
106
+ deviceQuestions,
107
+ deviceRelayedEventTypes,
108
+ deviceSessionRow,
109
+ deviceSessionRows,
110
+ } from './functions.deviceapi.js';
92
111
  import {
93
112
  controllerPackageName,
94
113
  controllerBuiltinCommands,
@@ -332,6 +351,23 @@ import {
332
351
  type TControllerResource,
333
352
  type TControllerOperationPrincipal,
334
353
  type TControllerResourceAttachmentTarget,
354
+ type IReq_ControllerDevicesList,
355
+ type IReq_ControllerDevicesPairingBegin,
356
+ type IReq_ControllerDevicesPairingCancel,
357
+ type IReq_ControllerDevicesRevoke,
358
+ type IReq_DeviceAuthChallenge,
359
+ type IReq_DeviceAuthProve,
360
+ type IReq_DeviceEventPush,
361
+ type IReq_DeviceHello,
362
+ type IReq_DevicePair,
363
+ type IReq_DevicePermissionReply,
364
+ type IReq_DeviceQuestionReply,
365
+ type IReq_DeviceSessionRead,
366
+ type IReq_DeviceSessionSend,
367
+ type IReq_DeviceSessionsList,
368
+ type IControllerSessionFeedRow,
369
+ deviceProtocolVersion,
370
+ deviceRevokedCloseCode,
335
371
  type IControllerProviderAccountRateLimits,
336
372
  type IControllerSessionRetrying,
337
373
  accountInHostCodexReason,
@@ -934,6 +970,9 @@ const maxPendingFlexControllerEvents = 512;
934
970
  /** Events and serialized bytes one browser may have waiting before its queue collapses into a resync. */
935
971
  const maxPendingControllerEventsPerViewer = 512;
936
972
  const maxPendingControllerEventBytesPerViewer = 16 * 1024 * 1024;
973
+ /** A device's queue collapses sooner: a phone on a VPN reads less, and its resync is one list and one read. */
974
+ const maxPendingDeviceEventsPerViewer = 256;
975
+ const maxPendingDeviceEventBytesPerViewer = 4 * 1024 * 1024;
937
976
  const maxLatestFlexToolExecutions = 512;
938
977
  const maxLatestFlexToolExecutionBytes = 8 * 1024 * 1024;
939
978
  const maxLatestFlexMessageUpdateBytes = 16 * 1024 * 1024;
@@ -2347,6 +2386,16 @@ const peerFromLocalData = (localDataArg: unknown): IControllerPeer => {
2347
2386
 
2348
2387
 
2349
2388
  const nativeSessionRuntimeId = (refArg: IControllerNativeSessionRef): IControllerRuntimeId => ({ harnessId: refArg.harness, nativeId: refArg.nativeId });
2389
+ /** The native session a feed row opens. */
2390
+ const nativeSessionRefOfFeed = (
2391
+ openArg: Extract<IControllerSessionFeedRow['open'], { kind: 'native' }>,
2392
+ ): IControllerNativeSessionRef => ({
2393
+ harness: openArg.harness,
2394
+ nativeId: openArg.nativeId,
2395
+ ...(openArg.profileId === undefined ? {} : { profileId: openArg.profileId }),
2396
+ });
2397
+ /** How the audit log and the operation budgets name an authenticated device. */
2398
+ const deviceAuditPeerId = (deviceIdArg: string): string => `device:${deviceIdArg}`;
2350
2399
  /** The browser's native send writes to every session that states no read-only reason. */
2351
2400
  const assertNativeSessionWritable = (resolvedArg: IResolvedNativeSession): void => {
2352
2401
  const { readOnly } = resolvedArg.session;
@@ -3096,6 +3145,10 @@ export class OpenCodeController {
3096
3145
  private pendingFlexMessageEventBytes = 0;
3097
3146
  private flexControllerEventDrainTask?: Promise<void>;
3098
3147
  private controllerEventDelivery?: ControllerEventDelivery;
3148
+ /** Every authenticated device connection's own ordered event queue, of the events a device receives. */
3149
+ private deviceEventDelivery?: ControllerEventDelivery;
3150
+ /** The paired devices, their pairing codes and authenticated connections; open while the controller runs. */
3151
+ private devices?: ControllerDevices;
3099
3152
  private flexAutoAcceptDrainTask?: Promise<void>;
3100
3153
  /** Sweeps whose auto-accept failed, queued again when the retry timer fires. */
3101
3154
  private readonly failedFlexAutoAcceptSweeps = new Map<string, IFlexAutoAcceptSweep>();
@@ -3311,7 +3364,7 @@ export class OpenCodeController {
3311
3364
  acknowledge: async (rowIdArg, updatedAtArg, actorArg) => {
3312
3365
  await this.sessionFeedAcknowledgements.put(await this.sessionFeedOwner(), rowIdArg, updatedAtArg, actorArg);
3313
3366
  },
3314
- hasViewers: async () => (await this.controllerEventViewers()).length > 0,
3367
+ hasViewers: async () => this.devices?.hasLivePeers() === true || (await this.controllerEventViewers()).length > 0,
3315
3368
  publish: (deltaArg) => {
3316
3369
  void this.pushControllerEvent({ type: 'sessionfeed.changed', sessionFeed: deltaArg, timestamp: Date.now() }).catch(() => undefined);
3317
3370
  },
@@ -10095,6 +10148,20 @@ export class OpenCodeController {
10095
10148
  this.setupRequired = authState.state === 'setupRequired';
10096
10149
  this.assertStartActive();
10097
10150
 
10151
+ this.devices = await ControllerDevices.open({
10152
+ controllerId: authDocument.id,
10153
+ publicOrigin: runtimeConfig.publicOrigin,
10154
+ tlsMode: runtimeConfig.tlsMode,
10155
+ changed: (pairingArg) => {
10156
+ void this.pushControllerEvent({
10157
+ type: 'devices.changed',
10158
+ ...(pairingArg === undefined ? {} : { devicePairing: pairingArg }),
10159
+ timestamp: Date.now(),
10160
+ }).catch(() => undefined);
10161
+ },
10162
+ });
10163
+ this.assertStartActive();
10164
+
10098
10165
  const router = this.createRouter(runtimeConfig.publicOrigin);
10099
10166
  if (runtimeConfig.tlsMode === 'proxy') {
10100
10167
  this.trustedProxySecrets = await ControllerTrustedProxySecrets.open({
@@ -12945,6 +13012,7 @@ export class OpenCodeController {
12945
13012
  peerArg: IControllerPeer,
12946
13013
  authStoreArg: SmartDataAuthStore,
12947
13014
  ): Promise<void> {
13015
+ this.devices?.disconnect(peerArg);
12948
13016
  const peerOperationAbortController = peerArg.context.state[
12949
13017
  operationAbortControllerPeerStateKey
12950
13018
  ];
@@ -13296,6 +13364,7 @@ export class OpenCodeController {
13296
13364
  ...(this.flexControllerEventDrainTask ? [this.flexControllerEventDrainTask] : []),
13297
13365
  ]);
13298
13366
  await this.controllerEventDelivery?.stop();
13367
+ await this.deviceEventDelivery?.stop();
13299
13368
 
13300
13369
  if (this.flexProjectionReader) {
13301
13370
  await stopPart(async () => {
@@ -13408,6 +13477,13 @@ export class OpenCodeController {
13408
13477
  && !this.flexProjectionReader
13409
13478
  && !this.eventStreamTask;
13410
13479
  if (storesStoppable) await stopPart(async () => this.attachmentCollection);
13480
+ if (this.devices) {
13481
+ const devices = this.devices;
13482
+ await stopPart(async () => {
13483
+ await devices.close();
13484
+ if (this.devices === devices) this.devices = undefined;
13485
+ });
13486
+ }
13411
13487
  if (storesStoppable && this.authStore) {
13412
13488
  const authStore = this.authStore;
13413
13489
  if (this.controllerStartedRecorded && !this.controllerStoppedRecorded) {
@@ -13511,19 +13587,24 @@ export class OpenCodeController {
13511
13587
  }
13512
13588
 
13513
13589
  /**
13514
- * Composes the three auth scopes. A handler is guarded by the scope router it is
13590
+ * Composes the five auth scopes. A handler is guarded by the scope router it is
13515
13591
  * registered on and by nothing else, so each `register*Handlers` method is handed
13516
13592
  * exactly one scope here, and test/test.routerscopes.node.ts freezes the resulting
13517
- * method-to-scope table.
13593
+ * method-to-scope table. A paired device reaches only `devicePairing` (before it is
13594
+ * authenticated) and `device`; it never reaches `protected`.
13518
13595
  */
13519
13596
  private createRouter(publicOriginArg: string): plugins.typedrequest.TypedRouter {
13520
13597
  const rootRouter = new plugins.typedrequest.TypedRouter();
13521
13598
  const publicRouter = new plugins.typedrequest.TypedRouter();
13522
13599
  const browserAuthRouter = new plugins.typedrequest.TypedRouter();
13523
13600
  const protectedRouter = new ControllerProtectedRouter(asTypedResponseError);
13601
+ const devicePairingRouter = new ControllerProtectedRouter(asTypedResponseError);
13602
+ const deviceRouter = new ControllerProtectedRouter(asTypedResponseError);
13524
13603
  rootRouter.addTypedRouter(publicRouter);
13525
13604
  rootRouter.addTypedRouter(browserAuthRouter);
13526
13605
  rootRouter.addTypedRouter(protectedRouter);
13606
+ rootRouter.addTypedRouter(devicePairingRouter);
13607
+ rootRouter.addTypedRouter(deviceRouter);
13527
13608
 
13528
13609
  browserAuthRouter.addMiddleware(async (requestArg) => {
13529
13610
  const peer = peerFromLocalData(requestArg.localData);
@@ -13546,6 +13627,13 @@ export class OpenCodeController {
13546
13627
  );
13547
13628
  }
13548
13629
  });
13630
+ // The connection's state says which device proved itself on it; a revoked device's connections lose it at once.
13631
+ deviceRouter.addMiddleware(async (requestArg) => {
13632
+ const peer = peerFromLocalData(requestArg.localData);
13633
+ if (this.devices?.deviceIdOf(peer) === undefined) {
13634
+ throw deviceRefusal('device_authentication_required', 'Device authentication is required on this connection.');
13635
+ }
13636
+ });
13549
13637
 
13550
13638
  this.registerStatusHandlers(publicRouter);
13551
13639
 
@@ -13578,10 +13666,321 @@ export class OpenCodeController {
13578
13666
  this.registerSessionFeedHandlers(protectedRouter);
13579
13667
  this.registerUsageFeedHandlers(protectedRouter);
13580
13668
  this.registerTerminalHandlers(protectedRouter);
13669
+ this.registerDevicesHandlers(protectedRouter);
13670
+
13671
+ this.registerDevicePairingHandlers(devicePairingRouter);
13672
+ this.registerDeviceHandlers(deviceRouter);
13581
13673
 
13582
13674
  return rootRouter;
13583
13675
  }
13584
13676
 
13677
+ private requireDevices(): ControllerDevices {
13678
+ if (!this.devices) {
13679
+ throw new plugins.typedrequest.TypedResponseError('The controller is not ready for devices.', { code: 'controller_unavailable' });
13680
+ }
13681
+ return this.devices;
13682
+ }
13683
+
13684
+ private requireSessionFeed(): SessionFeed {
13685
+ if (!this.sessionFeed) {
13686
+ throw new plugins.typedrequest.TypedResponseError('The session feed is not running.', { code: 'controller_unavailable' });
13687
+ }
13688
+ return this.sessionFeed;
13689
+ }
13690
+
13691
+ /**
13692
+ * Runs a device's request under the connection's operation budget and abort signal, which revoking the device
13693
+ * aborts. `deviceIdArg` names the authenticated device: its requests share one budget across its connections, count
13694
+ * against the authenticated rate limit and are audited as `device:<id>`.
13695
+ */
13696
+ private runDeviceOperation<T>(
13697
+ peerArg: IControllerPeer,
13698
+ deviceIdArg: string | undefined,
13699
+ operationArg: (signalArg: AbortSignal) => Promise<T>,
13700
+ requestSignalArg?: AbortSignal,
13701
+ ): Promise<T> {
13702
+ return this.runPrincipalOperation(
13703
+ 'device',
13704
+ deviceIdArg === undefined ? peerArg.id : deviceAuditPeerId(deviceIdArg),
13705
+ operationArg,
13706
+ requestSignalArg,
13707
+ this.peerOperationSignal(peerArg),
13708
+ deviceIdArg !== undefined,
13709
+ );
13710
+ }
13711
+
13712
+ /** The authenticated device of a request in the `device` scope, which its middleware checked. */
13713
+ private requestDevice(localDataArg: unknown): { peer: IControllerPeer; deviceId: string } {
13714
+ const peer = peerFromLocalData(localDataArg);
13715
+ const deviceId = this.devices?.deviceIdOf(peer);
13716
+ if (deviceId === undefined) {
13717
+ throw deviceRefusal('device_authentication_required', 'Device authentication is required on this connection.');
13718
+ }
13719
+ return { peer, deviceId };
13720
+ }
13721
+
13722
+ /** The session a device names, as the session feed lists it now: a conversation or a native session, never a terminal. */
13723
+ private async deviceSessionTarget(rowIdArg: string): Promise<{
13724
+ row: IControllerSessionFeedRow;
13725
+ open: Exclude<IControllerSessionFeedRow['open'], { kind: 'terminal' }>;
13726
+ }> {
13727
+ const row = await this.requireSessionFeed().find(rowIdArg);
13728
+ if (!row || row.open.kind === 'terminal') {
13729
+ throw deviceRefusal('session_not_found', 'The session feed lists no such session; list the sessions again.');
13730
+ }
13731
+ return { row, open: row.open };
13732
+ }
13733
+
13734
+ /**
13735
+ * Scope `devicePairing`: what a device asks before it is authenticated -- the protocol version, pairing with a QR
13736
+ * code, and the challenge and proof that authenticate a connection. Every request counts against the
13737
+ * unauthenticated preflight budget; a pairing and a proof are audited, under the unauthenticated audit budget.
13738
+ */
13739
+ private registerDevicePairingHandlers(routerArg: ControllerProtectedRouter): void {
13740
+ routerArg.addHandler<IReq_DeviceHello>('device.hello', async (requestArg, toolsArg) => {
13741
+ validateRequest(() => assertEmptyRequest(requestArg));
13742
+ const peer = peerFromLocalData(toolsArg?.localData);
13743
+ return this.runDeviceOperation(peer, undefined, async () => {
13744
+ this.recordUnauthenticatedPreflightOperation(peer.id);
13745
+ return { major: deviceProtocolVersion.major, minor: deviceProtocolVersion.minor };
13746
+ }, toolsArg?.abortSignal);
13747
+ });
13748
+
13749
+ routerArg.addHandler<IReq_DevicePair>('device.pair', async (requestArg, toolsArg) => {
13750
+ const request = validateRequest(() => assertDevicePairRequest(requestArg));
13751
+ const peer = peerFromLocalData(toolsArg?.localData);
13752
+ return this.runDeviceOperation(peer, undefined, async () => {
13753
+ this.recordUnauthenticatedPreflightOperation(peer.id);
13754
+ this.recordUnauthenticatedAuditOperation(peer.id);
13755
+ const outcome = await this.runAudited(
13756
+ { type: 'device.pair', peerId: peer.id },
13757
+ async () => this.requireDevices().pair(request),
13758
+ );
13759
+ return { deviceId: outcome.device.id, name: outcome.device.name };
13760
+ }, toolsArg?.abortSignal);
13761
+ });
13762
+
13763
+ routerArg.addHandler<IReq_DeviceAuthChallenge>('device.auth.challenge', async (requestArg, toolsArg) => {
13764
+ const request = validateRequest(() => assertDeviceAuthChallengeRequest(requestArg));
13765
+ const peer = peerFromLocalData(toolsArg?.localData);
13766
+ return this.runDeviceOperation(peer, undefined, async () => {
13767
+ this.recordUnauthenticatedPreflightOperation(peer.id);
13768
+ return this.requireDevices().challenge(peer, request.deviceId);
13769
+ }, toolsArg?.abortSignal);
13770
+ });
13771
+
13772
+ routerArg.addHandler<IReq_DeviceAuthProve>('device.auth.prove', async (requestArg, toolsArg) => {
13773
+ const request = validateRequest(() => assertDeviceAuthProveRequest(requestArg));
13774
+ const peer = peerFromLocalData(toolsArg?.localData);
13775
+ return this.runDeviceOperation(peer, undefined, async () => {
13776
+ this.recordUnauthenticatedPreflightOperation(peer.id);
13777
+ this.recordUnauthenticatedAuditOperation(peer.id);
13778
+ // A connection is either the owner's browser or a device, never both.
13779
+ if (typeof peer.context.state[authenticatedPeerStateKey] === 'string') {
13780
+ throw new plugins.typedrequest.TypedResponseError(
13781
+ 'This connection is signed in as the owner\'s browser; a device authenticates on a connection of its own.',
13782
+ { code: 'invalid_request' },
13783
+ );
13784
+ }
13785
+ const device = await this.runAudited(
13786
+ { type: 'device.auth', peerId: peer.id, credentialId: deviceAuditPeerId(request.deviceId) },
13787
+ async () => this.requireDevices().prove(peer, request.deviceId, request.signature),
13788
+ );
13789
+ return { name: device.name };
13790
+ }, toolsArg?.abortSignal);
13791
+ });
13792
+ }
13793
+
13794
+ /**
13795
+ * Scope `device`: the session feed, bounded transcript reads, direct sends and permission and question answers of an
13796
+ * authenticated device -- through the same operations the owner's browser runs, audited as `device:<id>`.
13797
+ */
13798
+ private registerDeviceHandlers(routerArg: ControllerProtectedRouter): void {
13799
+ routerArg.addHandler<IReq_DeviceSessionsList>('device.sessions.list', async (requestArg, toolsArg) => {
13800
+ validateRequest(() => assertEmptyRequest(requestArg));
13801
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
13802
+ return this.runDeviceOperation(peer, deviceId, async () => {
13803
+ const feed = await this.requireSessionFeed().list();
13804
+ return { epoch: feed.epoch, revision: feed.revision, rows: deviceSessionRows(feed.rows) };
13805
+ }, toolsArg?.abortSignal);
13806
+ });
13807
+
13808
+ routerArg.addHandler<IReq_DeviceSessionRead>('device.session.read', async (requestArg, toolsArg) => {
13809
+ const request = validateRequest(() => assertDeviceSessionReadRequest(requestArg));
13810
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
13811
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13812
+ const auditPeerId = deviceAuditPeerId(deviceId);
13813
+ const { row, open } = await this.deviceSessionTarget(request.sessionId);
13814
+ const session = deviceSessionRow(row)!;
13815
+ if (open.kind === 'conversation') {
13816
+ const { projectId, sessionId } = open;
13817
+ const detail = await this.readSessionForPrincipal('device', auditPeerId, { projectId, sessionId }, signalArg);
13818
+ const before = request.before;
13819
+ const page = before === undefined ? detail.messagePage : await this.runAudited(
13820
+ { type: 'session.messages.page', peerId: auditPeerId, sessionId },
13821
+ async () => this.readSessionMessagePage(
13822
+ await this.resolveProject(projectId),
13823
+ sessionId,
13824
+ { limit: request.limit ?? controllerInitialMessageBundleLimit, before },
13825
+ signalArg,
13826
+ ),
13827
+ );
13828
+ return {
13829
+ session,
13830
+ messages: deviceMessages(page.bundles),
13831
+ before: page.nextCursor ?? null,
13832
+ permissions: devicePermissions(detail.permissions),
13833
+ questions: deviceQuestions(detail.questions),
13834
+ };
13835
+ }
13836
+ // As for a conversation, `limit` sizes older pages only; the newest page is the controller's own bound.
13837
+ const native = await this.readNativeSessionForPrincipal('device', auditPeerId, {
13838
+ session: nativeSessionRefOfFeed(open),
13839
+ ...(request.before === undefined ? {} : { before: request.before, ...(request.limit === undefined ? {} : { limit: request.limit }) }),
13840
+ }, signalArg);
13841
+ return {
13842
+ session,
13843
+ messages: deviceMessages(native.messagePage.bundles),
13844
+ before: native.messagePage.nextCursor ?? null,
13845
+ permissions: devicePermissions(native.permissions),
13846
+ questions: deviceQuestions(native.questions),
13847
+ };
13848
+ }, toolsArg?.abortSignal);
13849
+ });
13850
+
13851
+ routerArg.addHandler<IReq_DeviceSessionSend>('device.session.send', async (requestArg, toolsArg) => {
13852
+ const request = validateRequest(() => assertDeviceSessionSendRequest(requestArg));
13853
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
13854
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13855
+ const auditPeerId = deviceAuditPeerId(deviceId);
13856
+ const { open } = await this.deviceSessionTarget(request.sessionId);
13857
+ if (open.kind === 'conversation') {
13858
+ // A direct message, as MCP sends one: never the browser's shared draft.
13859
+ await this.sendSessionForPrincipal('device', auditPeerId, {
13860
+ source: 'direct', projectId: open.projectId, sessionId: open.sessionId, text: request.text,
13861
+ }, signalArg);
13862
+ } else {
13863
+ await this.sendNativeSession(
13864
+ auditPeerId, nativeSessionRefOfFeed(open), request.text, undefined, signalArg, assertNativeSessionWritable,
13865
+ );
13866
+ }
13867
+ return { accepted: true as const };
13868
+ }, toolsArg?.abortSignal);
13869
+ });
13870
+
13871
+ routerArg.addHandler<IReq_DevicePermissionReply>('device.permission.reply', async (requestArg, toolsArg) => {
13872
+ const request = validateRequest(() => assertDevicePermissionReplyRequest(requestArg));
13873
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
13874
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13875
+ const auditPeerId = deviceAuditPeerId(deviceId);
13876
+ const { open } = await this.deviceSessionTarget(request.sessionId);
13877
+ if (open.kind === 'conversation') {
13878
+ return this.replyPermissionForPrincipal('device', auditPeerId, validateRequest(() => assertPermissionReplyRequest({
13879
+ projectId: open.projectId,
13880
+ sessionId: open.sessionId,
13881
+ requestId: { harnessId: open.sessionId.harnessId, nativeId: request.permissionId },
13882
+ reply: request.reply,
13883
+ ...(request.message === undefined ? {} : { message: request.message }),
13884
+ })), signalArg);
13885
+ }
13886
+ const ref = nativeSessionRefOfFeed(open);
13887
+ const native = validateRequest(() => assertNativeSessionPermissionReplyRequest({
13888
+ session: ref, requestId: { harnessId: ref.harness, nativeId: request.permissionId }, reply: request.reply,
13889
+ }));
13890
+ return this.replyNativeSessionForPrincipal('device', auditPeerId, {
13891
+ session: native.session, requestId: native.requestId, permission: native.reply,
13892
+ }, signalArg);
13893
+ }, toolsArg?.abortSignal);
13894
+ });
13895
+
13896
+ routerArg.addHandler<IReq_DeviceQuestionReply>('device.question.reply', async (requestArg, toolsArg) => {
13897
+ const request = validateRequest(() => assertDeviceQuestionReplyRequest(requestArg));
13898
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
13899
+ return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
13900
+ const auditPeerId = deviceAuditPeerId(deviceId);
13901
+ const { open } = await this.deviceSessionTarget(request.sessionId);
13902
+ if (open.kind === 'conversation') {
13903
+ return this.replyQuestionForPrincipal('device', auditPeerId, validateRequest(() => assertQuestionReplyRequest({
13904
+ projectId: open.projectId,
13905
+ sessionId: open.sessionId,
13906
+ requestId: { harnessId: open.sessionId.harnessId, nativeId: request.questionId },
13907
+ answers: request.answers,
13908
+ })), signalArg);
13909
+ }
13910
+ const ref = nativeSessionRefOfFeed(open);
13911
+ const native = validateRequest(() => assertNativeSessionQuestionReplyRequest({
13912
+ session: ref, requestId: { harnessId: ref.harness, nativeId: request.questionId }, answers: request.answers,
13913
+ }));
13914
+ return this.replyNativeSessionForPrincipal('device', auditPeerId, {
13915
+ session: native.session, requestId: native.requestId, answers: native.answers,
13916
+ }, signalArg);
13917
+ }, toolsArg?.abortSignal);
13918
+ });
13919
+ }
13920
+
13921
+ /**
13922
+ * The owner's side of the devices, in Settings → Devices: the list, the single-use pairing code of the QR, and
13923
+ * revoking a device, which closes its live connections with 4403 at once.
13924
+ */
13925
+ private registerDevicesHandlers(protectedRouterArg: ControllerProtectedRouter): void {
13926
+ protectedRouterArg.addHandler<IReq_ControllerDevicesList>('controller.devices.list', async (requestArg, toolsArg) => {
13927
+ validateRequest(() => assertEmptyRequest(requestArg));
13928
+ const peer = peerFromLocalData(toolsArg?.localData);
13929
+ return this.runOperation(peer, async () => {
13930
+ const devices = this.requireDevices();
13931
+ return { devices: devices.list(), pairing: devices.availability() };
13932
+ }, toolsArg?.abortSignal);
13933
+ });
13934
+
13935
+ protectedRouterArg.addHandler<IReq_ControllerDevicesPairingBegin>(
13936
+ 'controller.devices.pairing.begin',
13937
+ async (requestArg, toolsArg) => {
13938
+ validateRequest(() => assertEmptyRequest(requestArg));
13939
+ const peer = peerFromLocalData(toolsArg?.localData);
13940
+ return this.runOperation(peer, async () => this.runAudited(
13941
+ { type: 'device.pairing.begin', peerId: peer.id },
13942
+ async () => this.requireDevices().beginPairing(),
13943
+ ), toolsArg?.abortSignal);
13944
+ },
13945
+ );
13946
+
13947
+ protectedRouterArg.addHandler<IReq_ControllerDevicesPairingCancel>(
13948
+ 'controller.devices.pairing.cancel',
13949
+ async (requestArg, toolsArg) => {
13950
+ const { pairingId } = validateRequest(() => assertDevicePairingCancelRequest(requestArg));
13951
+ const peer = peerFromLocalData(toolsArg?.localData);
13952
+ return this.runOperation(peer, async () => ({ cancelled: this.requireDevices().cancelPairing(pairingId) }),
13953
+ toolsArg?.abortSignal);
13954
+ },
13955
+ );
13956
+
13957
+ protectedRouterArg.addHandler<IReq_ControllerDevicesRevoke>('controller.devices.revoke', async (requestArg, toolsArg) => {
13958
+ const { deviceId } = validateRequest(() => assertDeviceRevokeRequest(requestArg));
13959
+ const peer = peerFromLocalData(toolsArg?.localData);
13960
+ return this.runOperation(peer, async () => this.runAudited(
13961
+ { type: 'device.revoke', peerId: peer.id, credentialId: deviceAuditPeerId(deviceId) },
13962
+ async () => {
13963
+ const { revoked, peers } = await this.requireDevices().revoke(deviceId);
13964
+ for (const devicePeer of peers) this.closeRevokedDevicePeer(devicePeer);
13965
+ return { revoked };
13966
+ },
13967
+ ), toolsArg?.abortSignal);
13968
+ });
13969
+ }
13970
+
13971
+ /** Ends a revoked device's connection: its requests in flight are aborted, and it is closed with 4403. */
13972
+ private closeRevokedDevicePeer(peerArg: IControllerDevicePeer): void {
13973
+ const peerOperationAbortController = peerArg.context.state[operationAbortControllerPeerStateKey];
13974
+ if (peerOperationAbortController instanceof AbortController) {
13975
+ peerOperationAbortController.abort(new Error('The device was revoked.'));
13976
+ }
13977
+ try {
13978
+ peerArg.close?.(deviceRevokedCloseCode, 'The device was revoked.');
13979
+ } catch (errorArg) {
13980
+ console.error(`Closing device connection ${peerArg.id} after its device was revoked failed.`, errorArg);
13981
+ }
13982
+ }
13983
+
13585
13984
  /** Public scope: a browser reads the status before it holds a passkey session. */
13586
13985
  private registerStatusHandlers(publicRouterArg: plugins.typedrequest.TypedRouter): void {
13587
13986
  publicRouterArg.addTypedHandler(this.createStatusHandler());
@@ -13829,6 +14228,7 @@ export class OpenCodeController {
13829
14228
  const peer = peerFromLocalData(toolsArg?.localData);
13830
14229
  const validated = validateRequest(() => assertSetupBeginRequest(requestArg));
13831
14230
  return this.runOperation(peer, async () => {
14231
+ this.refuseDevicePeerSignIn(peer);
13832
14232
  try {
13833
14233
  return await this.requirePasskeyManager().beginSetup({
13834
14234
  peerId: peer.id,
@@ -13849,6 +14249,7 @@ export class OpenCodeController {
13849
14249
  const validated = validateRequest(() => assertSetupFinishRequest(requestArg));
13850
14250
  return this.runOperation(peer, async () => {
13851
14251
  this.recordUnauthenticatedPreflightOperation(peer.id);
14252
+ this.refuseDevicePeerSignIn(peer);
13852
14253
  try {
13853
14254
  await this.requirePasskeyManager().preflightSetupFinish({
13854
14255
  peerId: peer.id,
@@ -13883,6 +14284,7 @@ export class OpenCodeController {
13883
14284
  validateRequest(() => assertEmptyRequest(requestArg));
13884
14285
  const peer = peerFromLocalData(toolsArg?.localData);
13885
14286
  return this.runOperation(peer, async () => {
14287
+ this.refuseDevicePeerSignIn(peer);
13886
14288
  try {
13887
14289
  return await this.requirePasskeyManager().beginAuthentication({
13888
14290
  peerId: peer.id,
@@ -13904,6 +14306,7 @@ export class OpenCodeController {
13904
14306
  const peer = peerFromLocalData(toolsArg?.localData);
13905
14307
  return this.runOperation(peer, async () => {
13906
14308
  this.recordUnauthenticatedPreflightOperation(peer.id);
14309
+ this.refuseDevicePeerSignIn(peer);
13907
14310
  try {
13908
14311
  await this.requirePasskeyManager().preflightAuthenticationFinish({
13909
14312
  peerId: peer.id,
@@ -13938,6 +14341,7 @@ export class OpenCodeController {
13938
14341
  const peer = peerFromLocalData(toolsArg?.localData);
13939
14342
  return this.runOperation(peer, async () => {
13940
14343
  this.recordUnauthenticatedPreflightOperation(peer.id);
14344
+ this.refuseDevicePeerSignIn(peer);
13941
14345
  this.recordUnauthenticatedAuditOperation(peer.id);
13942
14346
  const result = await this.runAudited(
13943
14347
  { type: 'temppassword.login', peerId: peer.id },
@@ -13974,6 +14378,7 @@ export class OpenCodeController {
13974
14378
  const peer = peerFromLocalData(toolsArg?.localData);
13975
14379
  return this.runOperation(peer, async () => {
13976
14380
  this.recordUnauthenticatedPreflightOperation(peer.id);
14381
+ this.refuseDevicePeerSignIn(peer);
13977
14382
  this.recordUnauthenticatedAuditOperation(peer.id);
13978
14383
  const result = await this.runAudited(
13979
14384
  { type: 'auth.resume', peerId: peer.id },
@@ -16266,75 +16671,9 @@ export class OpenCodeController {
16266
16671
  'controller.permission.reply',
16267
16672
  async (requestArg, toolsArg) => {
16268
16673
  const peer = peerFromLocalData(toolsArg?.localData);
16269
- const { projectId, sessionId, requestId, reply, message } = validateRequest(
16270
- () => assertPermissionReplyRequest(requestArg),
16271
- );
16272
- return this.runOperation(peer, async (signalArg) => this.runAudited(
16273
- { type: 'permission.reply', peerId: peer.id, sessionId, requestId },
16274
- async () => {
16275
- const project = await this.resolveProject(projectId);
16276
- await this.assertSessionExists(projectId, sessionId, signalArg);
16277
- if (sessionId.harnessId === 'codex') {
16278
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16279
- signalArg.throwIfAborted();
16280
- this.requireCodexClient(sessionId.nativeId).replyPermission(sessionId.nativeId, requestId.nativeId, reply);
16281
- return { success: true };
16282
- });
16283
- }
16284
- if (sessionId.harnessId === 'claude') {
16285
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16286
- signalArg.throwIfAborted();
16287
- this.requireClaudeHarness().replyPermission(sessionId.nativeId, requestId.nativeId, reply);
16288
- return { success: true };
16289
- });
16290
- }
16291
- if (sessionId.harnessId === 'flex') {
16292
- signalArg.throwIfAborted();
16293
- const flexSupervisor = this.requireFlexSupervisor();
16294
- const pendingPermissions = await flexSupervisor.request('permission.list', {
16295
- scopeId: projectId,
16296
- }, signalArg);
16297
- const permission = pendingPermissions.permissions.find(
16298
- (candidate) => candidate.permissionId === requestId.nativeId,
16299
- );
16300
- if (!permission) throw new FlexServiceError('NOT_FOUND');
16301
- const authority = this.flexPermissionAuthority(projectId, permission);
16302
- if (
16303
- !authority
16304
- || (
16305
- authority.type === 'managed'
16306
- && authority.run.sessionId !== sessionId.nativeId
16307
- )
16308
- || (
16309
- authority.type === 'delegated'
16310
- && authority.lease.rootAuthority.sessionId !== sessionId.nativeId
16311
- )
16312
- ) throw new FlexServiceError('NOT_FOUND');
16313
- await this.respondToFlexPermission(
16314
- projectId,
16315
- permission,
16316
- reply,
16317
- authority,
16318
- signalArg,
16319
- );
16320
- return { success: true };
16321
- }
16322
- const pendingPermissions = await this.requireOpenCodeClient().listPermissions(
16323
- project.directory,
16324
- sessionId.nativeId,
16325
- signalArg,
16326
- );
16327
- this.assertAttentionRequestOwned(pendingPermissions, requestId, 'permission');
16328
- return {
16329
- success: await this.requireOpenCodeClient().replyPermission(
16330
- project.directory,
16331
- requestId.nativeId,
16332
- reply,
16333
- message,
16334
- signalArg,
16335
- ),
16336
- };
16337
- },
16674
+ const request = validateRequest(() => assertPermissionReplyRequest(requestArg));
16675
+ return this.runOperation(peer, async (signalArg) => this.replyPermissionForPrincipal(
16676
+ 'browser', peer.id, request, signalArg,
16338
16677
  ));
16339
16678
  },
16340
16679
  );
@@ -16343,55 +16682,149 @@ export class OpenCodeController {
16343
16682
  'controller.question.reply',
16344
16683
  async (requestArg, toolsArg) => {
16345
16684
  const peer = peerFromLocalData(toolsArg?.localData);
16346
- const { projectId, sessionId, requestId, answers } = validateRequest(
16347
- () => assertQuestionReplyRequest(requestArg),
16348
- );
16349
- return this.runOperation(peer, async (signalArg) => this.runAudited(
16350
- { type: 'question.reply', peerId: peer.id, sessionId, requestId },
16351
- async () => {
16352
- const project = await this.resolveProject(projectId);
16353
- await this.assertSessionExists(projectId, sessionId, signalArg);
16354
- if (sessionId.harnessId === 'codex') {
16355
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16356
- signalArg.throwIfAborted();
16357
- this.requireCodexClient(sessionId.nativeId).replyQuestion(sessionId.nativeId, requestId.nativeId, answers);
16358
- return { success: true };
16359
- });
16360
- }
16361
- if (sessionId.harnessId === 'claude') {
16362
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16363
- signalArg.throwIfAborted();
16364
- this.requireClaudeHarness().replyQuestion(sessionId.nativeId, requestId.nativeId, answers);
16365
- return { success: true };
16366
- });
16367
- }
16368
- const openCodeClient = this.requireOpenCodeClient();
16369
- const pendingQuestions = await openCodeClient.listQuestions(
16370
- project.directory,
16371
- sessionId.nativeId,
16372
- signalArg,
16373
- );
16374
- this.assertAttentionRequestOwned(pendingQuestions, requestId, 'question');
16375
- return {
16376
- success: answers === null
16377
- ? await openCodeClient.rejectQuestion(
16378
- project.directory,
16379
- requestId.nativeId,
16380
- signalArg,
16381
- )
16382
- : await openCodeClient.replyQuestion(
16383
- project.directory,
16384
- requestId.nativeId,
16385
- answers,
16386
- signalArg,
16387
- ),
16388
- };
16389
- },
16685
+ const request = validateRequest(() => assertQuestionReplyRequest(requestArg));
16686
+ return this.runOperation(peer, async (signalArg) => this.replyQuestionForPrincipal(
16687
+ 'browser', peer.id, request, signalArg,
16390
16688
  ));
16391
16689
  },
16392
16690
  );
16393
16691
  }
16394
16692
 
16693
+ /**
16694
+ * Answers a permission request of a conversation, for the owner's browser and a paired device alike: the request must
16695
+ * be pending in the session, and the harness that owns it takes the answer.
16696
+ */
16697
+ private async replyPermissionForPrincipal(
16698
+ principalArg: TControllerOperationPrincipal,
16699
+ peerIdArg: string,
16700
+ requestArg: IReq_ControllerPermissionReply['request'],
16701
+ signalArg: AbortSignal,
16702
+ ): Promise<IReq_ControllerPermissionReply['response']> {
16703
+ const { projectId, sessionId, requestId, reply, message } = requestArg;
16704
+ return this.runAudited(
16705
+ { type: 'permission.reply', peerId: this.auditPeerId(principalArg, peerIdArg), sessionId, requestId },
16706
+ async () => {
16707
+ const project = await this.resolveProject(projectId);
16708
+ await this.assertSessionExists(projectId, sessionId, signalArg);
16709
+ if (sessionId.harnessId === 'codex') {
16710
+ return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16711
+ signalArg.throwIfAborted();
16712
+ this.requireCodexClient(sessionId.nativeId).replyPermission(sessionId.nativeId, requestId.nativeId, reply);
16713
+ return { success: true };
16714
+ });
16715
+ }
16716
+ if (sessionId.harnessId === 'claude') {
16717
+ return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16718
+ signalArg.throwIfAborted();
16719
+ this.requireClaudeHarness().replyPermission(sessionId.nativeId, requestId.nativeId, reply);
16720
+ return { success: true };
16721
+ });
16722
+ }
16723
+ if (sessionId.harnessId === 'flex') {
16724
+ signalArg.throwIfAborted();
16725
+ const flexSupervisor = this.requireFlexSupervisor();
16726
+ const pendingPermissions = await flexSupervisor.request('permission.list', {
16727
+ scopeId: projectId,
16728
+ }, signalArg);
16729
+ const permission = pendingPermissions.permissions.find(
16730
+ (candidate) => candidate.permissionId === requestId.nativeId,
16731
+ );
16732
+ if (!permission) throw new FlexServiceError('NOT_FOUND');
16733
+ const authority = this.flexPermissionAuthority(projectId, permission);
16734
+ if (
16735
+ !authority
16736
+ || (
16737
+ authority.type === 'managed'
16738
+ && authority.run.sessionId !== sessionId.nativeId
16739
+ )
16740
+ || (
16741
+ authority.type === 'delegated'
16742
+ && authority.lease.rootAuthority.sessionId !== sessionId.nativeId
16743
+ )
16744
+ ) throw new FlexServiceError('NOT_FOUND');
16745
+ await this.respondToFlexPermission(
16746
+ projectId,
16747
+ permission,
16748
+ reply,
16749
+ authority,
16750
+ signalArg,
16751
+ );
16752
+ return { success: true };
16753
+ }
16754
+ const pendingPermissions = await this.requireOpenCodeClient().listPermissions(
16755
+ project.directory,
16756
+ sessionId.nativeId,
16757
+ signalArg,
16758
+ );
16759
+ this.assertAttentionRequestOwned(pendingPermissions, requestId, 'permission');
16760
+ return {
16761
+ success: await this.requireOpenCodeClient().replyPermission(
16762
+ project.directory,
16763
+ requestId.nativeId,
16764
+ reply,
16765
+ message,
16766
+ signalArg,
16767
+ ),
16768
+ };
16769
+ },
16770
+ );
16771
+ }
16772
+
16773
+ /**
16774
+ * Answers a question of a conversation, for the owner's browser and a paired device alike; `null` rejects it. The
16775
+ * question must be pending in the session. Questions are never answered automatically.
16776
+ */
16777
+ private async replyQuestionForPrincipal(
16778
+ principalArg: TControllerOperationPrincipal,
16779
+ peerIdArg: string,
16780
+ requestArg: IReq_ControllerQuestionReply['request'],
16781
+ signalArg: AbortSignal,
16782
+ ): Promise<IReq_ControllerQuestionReply['response']> {
16783
+ const { projectId, sessionId, requestId, answers } = requestArg;
16784
+ return this.runAudited(
16785
+ { type: 'question.reply', peerId: this.auditPeerId(principalArg, peerIdArg), sessionId, requestId },
16786
+ async () => {
16787
+ const project = await this.resolveProject(projectId);
16788
+ await this.assertSessionExists(projectId, sessionId, signalArg);
16789
+ if (sessionId.harnessId === 'codex') {
16790
+ return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16791
+ signalArg.throwIfAborted();
16792
+ this.requireCodexClient(sessionId.nativeId).replyQuestion(sessionId.nativeId, requestId.nativeId, answers);
16793
+ return { success: true };
16794
+ });
16795
+ }
16796
+ if (sessionId.harnessId === 'claude') {
16797
+ return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16798
+ signalArg.throwIfAborted();
16799
+ this.requireClaudeHarness().replyQuestion(sessionId.nativeId, requestId.nativeId, answers);
16800
+ return { success: true };
16801
+ });
16802
+ }
16803
+ const openCodeClient = this.requireOpenCodeClient();
16804
+ const pendingQuestions = await openCodeClient.listQuestions(
16805
+ project.directory,
16806
+ sessionId.nativeId,
16807
+ signalArg,
16808
+ );
16809
+ this.assertAttentionRequestOwned(pendingQuestions, requestId, 'question');
16810
+ return {
16811
+ success: answers === null
16812
+ ? await openCodeClient.rejectQuestion(
16813
+ project.directory,
16814
+ requestId.nativeId,
16815
+ signalArg,
16816
+ )
16817
+ : await openCodeClient.replyQuestion(
16818
+ project.directory,
16819
+ requestId.nativeId,
16820
+ answers,
16821
+ signalArg,
16822
+ ),
16823
+ };
16824
+ },
16825
+ );
16826
+ }
16827
+
16395
16828
  private registerResourceHandlers(protectedRouterArg: ControllerProtectedRouter): void {
16396
16829
  protectedRouterArg.addHandler<IReq_ControllerResourceList>(
16397
16830
  'controller.resource.list',
@@ -17170,30 +17603,9 @@ export class OpenCodeController {
17170
17603
  'controller.nativesession.read',
17171
17604
  async (requestArg, toolsArg) => {
17172
17605
  const peer = peerFromLocalData(toolsArg?.localData);
17173
- const { session: ref, limit, before } = validateRequest(() => assertNativeSessionReadRequest(requestArg));
17174
- return this.runOperation(peer, (signalArg) => this.runAudited(
17175
- { type: 'session.read', peerId: peer.id, sessionId: runtimeId(ref) },
17176
- () => serve(signalArg, async () => {
17177
- const resolved = await this.nativeSessions.resolve(ref);
17178
- const [page, attention, state] = await Promise.all([
17179
- this.requireFleetWorkers().nativeHistory(ref.harness, resolved.native, limit ?? controllerInitialMessageBundleLimit, before),
17180
- this.nativeSessionAttention(resolved),
17181
- this.requireAuthStore().getSessionState(resolved.scope, runtimeId(ref), signalArg),
17182
- ]);
17183
- signalArg.throwIfAborted();
17184
- return {
17185
- session: resolved.session,
17186
- messagePage: boundControllerMessagePage({
17187
- bundles: page.bundles,
17188
- ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
17189
- ...(page.earlier && page.nextCursor === undefined ? { truncated: true } : {}),
17190
- }, controllerMaximumMessageBundles),
17191
- ...attention,
17192
- todos: [],
17193
- scratchpad: state.scratchpad,
17194
- intelligenceExchanges: state.intelligenceExchanges,
17195
- };
17196
- }),
17606
+ const request = validateRequest(() => assertNativeSessionReadRequest(requestArg));
17607
+ return this.runOperation(peer, (signalArg) => this.readNativeSessionForPrincipal(
17608
+ 'browser', peer.id, request, signalArg,
17197
17609
  ), toolsArg?.abortSignal);
17198
17610
  },
17199
17611
  );
@@ -17318,14 +17730,9 @@ export class OpenCodeController {
17318
17730
  'controller.nativesession.permission.reply',
17319
17731
  async (requestArg, toolsArg) => {
17320
17732
  const peer = peerFromLocalData(toolsArg?.localData);
17321
- const { session: ref, requestId, reply } = validateRequest(() => assertNativeSessionPermissionReplyRequest(requestArg));
17322
- return this.runOperation(peer, (signalArg) => this.runAudited(
17323
- { type: 'permission.reply', peerId: peer.id, sessionId: runtimeId(ref), requestId },
17324
- () => serve(signalArg, async () => {
17325
- const resolved = await this.nativeSessions.resolve(ref);
17326
- await this.replyNativeSessionRequest(resolved, requestId.nativeId, { permission: reply }, 'permission');
17327
- return { success: true };
17328
- }),
17733
+ const request = validateRequest(() => assertNativeSessionPermissionReplyRequest(requestArg));
17734
+ return this.runOperation(peer, (signalArg) => this.replyNativeSessionForPrincipal(
17735
+ 'browser', peer.id, { session: request.session, requestId: request.requestId, permission: request.reply }, signalArg,
17329
17736
  ), toolsArg?.abortSignal);
17330
17737
  },
17331
17738
  );
@@ -17334,19 +17741,80 @@ export class OpenCodeController {
17334
17741
  'controller.nativesession.question.reply',
17335
17742
  async (requestArg, toolsArg) => {
17336
17743
  const peer = peerFromLocalData(toolsArg?.localData);
17337
- const { session: ref, requestId, answers } = validateRequest(() => assertNativeSessionQuestionReplyRequest(requestArg));
17338
- return this.runOperation(peer, (signalArg) => this.runAudited(
17339
- { type: 'question.reply', peerId: peer.id, sessionId: runtimeId(ref), requestId },
17340
- () => serve(signalArg, async () => {
17341
- const resolved = await this.nativeSessions.resolve(ref);
17342
- await this.replyNativeSessionRequest(resolved, requestId.nativeId, { answers }, 'question');
17343
- return { success: true };
17344
- }),
17744
+ const request = validateRequest(() => assertNativeSessionQuestionReplyRequest(requestArg));
17745
+ return this.runOperation(peer, (signalArg) => this.replyNativeSessionForPrincipal(
17746
+ 'browser', peer.id, { session: request.session, requestId: request.requestId, answers: request.answers }, signalArg,
17345
17747
  ), toolsArg?.abortSignal);
17346
17748
  },
17347
17749
  );
17348
17750
  }
17349
17751
 
17752
+ /**
17753
+ * A native session, a bounded page of its transcript and what AGL's own turns in it wait for, for the owner's browser
17754
+ * and a paired device alike. The session resolves only through what the session feed's sources list.
17755
+ */
17756
+ private async readNativeSessionForPrincipal(
17757
+ principalArg: TControllerOperationPrincipal,
17758
+ peerIdArg: string,
17759
+ requestArg: IReq_ControllerNativeSessionRead['request'],
17760
+ signalArg: AbortSignal,
17761
+ ): Promise<IReq_ControllerNativeSessionRead['response']> {
17762
+ const { session: ref, limit, before } = requestArg;
17763
+ const sessionId = nativeSessionRuntimeId(ref);
17764
+ return this.runAudited(
17765
+ { type: 'session.read', peerId: this.auditPeerId(principalArg, peerIdArg), sessionId },
17766
+ () => this.serveNativeSession(signalArg, async () => {
17767
+ const resolved = await this.nativeSessions.resolve(ref);
17768
+ const [page, attention, state] = await Promise.all([
17769
+ this.requireFleetWorkers().nativeHistory(ref.harness, resolved.native, limit ?? controllerInitialMessageBundleLimit, before),
17770
+ this.nativeSessionAttention(resolved),
17771
+ this.requireAuthStore().getSessionState(resolved.scope, sessionId, signalArg),
17772
+ ]);
17773
+ signalArg.throwIfAborted();
17774
+ return {
17775
+ session: resolved.session,
17776
+ messagePage: boundControllerMessagePage({
17777
+ bundles: page.bundles,
17778
+ ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
17779
+ ...(page.earlier && page.nextCursor === undefined ? { truncated: true } : {}),
17780
+ }, controllerMaximumMessageBundles),
17781
+ ...attention,
17782
+ todos: [],
17783
+ scratchpad: state.scratchpad,
17784
+ intelligenceExchanges: state.intelligenceExchanges,
17785
+ };
17786
+ }),
17787
+ );
17788
+ }
17789
+
17790
+ /**
17791
+ * Answers a permission (`permission`) or a question (`answers`, `null` rejects it) of AGL's own turn in a native
17792
+ * session, for the owner's browser and a paired device alike. The request must still be pending.
17793
+ */
17794
+ private async replyNativeSessionForPrincipal(
17795
+ principalArg: TControllerOperationPrincipal,
17796
+ peerIdArg: string,
17797
+ requestArg: { session: IControllerNativeSessionRef; requestId: IControllerRuntimeId }
17798
+ & ({ permission: TControllerPermissionReply } | { answers: string[][] | null }),
17799
+ signalArg: AbortSignal,
17800
+ ): Promise<{ success: boolean }> {
17801
+ const { session: ref, requestId } = requestArg;
17802
+ const kind = 'permission' in requestArg ? 'permission' : 'question';
17803
+ return this.runAudited(
17804
+ { type: `${kind}.reply`, peerId: this.auditPeerId(principalArg, peerIdArg), sessionId: nativeSessionRuntimeId(ref), requestId },
17805
+ () => this.serveNativeSession(signalArg, async () => {
17806
+ const resolved = await this.nativeSessions.resolve(ref);
17807
+ await this.replyNativeSessionRequest(
17808
+ resolved,
17809
+ requestId.nativeId,
17810
+ 'permission' in requestArg ? { permission: requestArg.permission } : { answers: requestArg.answers },
17811
+ kind,
17812
+ );
17813
+ return { success: true };
17814
+ }),
17815
+ );
17816
+ }
17817
+
17350
17818
  /** The requests of AGL's own turns in a native session that wait for an answer. */
17351
17819
  private async nativeSessionAttention(
17352
17820
  resolvedArg: IResolvedNativeSession,
@@ -21779,6 +22247,20 @@ export class OpenCodeController {
21779
22247
  return credentialId;
21780
22248
  }
21781
22249
 
22250
+ /**
22251
+ * A connection is either the owner's browser or a device, never both: every browser sign-in step (setup, passkey,
22252
+ * temporary password, resume) refuses a connection a device authenticated, before it reads or consumes anything, as
22253
+ * `device.auth.prove` refuses a connection signed in as the browser.
22254
+ */
22255
+ private refuseDevicePeerSignIn(peerArg: IControllerPeer): void {
22256
+ if (typeof peerArg.context.state[devicePeerStateKey] === 'string') {
22257
+ throw new plugins.typedrequest.TypedResponseError(
22258
+ 'This connection is authenticated as a paired device; the owner\'s browser signs in on a connection of its own.',
22259
+ { code: 'invalid_request' },
22260
+ );
22261
+ }
22262
+ }
22263
+
21782
22264
  private setAuthenticatedPeerCredential(
21783
22265
  peerArg: IControllerPeer,
21784
22266
  credentialIdArg: string,
@@ -35156,7 +35638,51 @@ export class OpenCodeController {
35156
35638
  private async pushControllerEvent(eventArg: IControllerEvent): Promise<void> {
35157
35639
  this.driverService?.observe(eventArg);
35158
35640
  this.sessionFeed?.observe(eventArg);
35159
- await this.controllerEventDeliveryQueues().push(eventArg);
35641
+ const browsers = this.controllerEventDeliveryQueues().push(eventArg);
35642
+ // A device receives an allowlist of events in its own reduced shape (`deviceEvent`), through queues of its own.
35643
+ if (this.devices?.hasLivePeers() === true && deviceRelayedEventTypes.has(eventArg.type)) {
35644
+ await Promise.all([browsers, this.deviceEventDeliveryQueues().push(eventArg)]);
35645
+ return;
35646
+ }
35647
+ await browsers;
35648
+ }
35649
+
35650
+ /**
35651
+ * Every authenticated device connection's own ordered event queue, created with the first event a device receives:
35652
+ * the queues and their collapse rules are the browsers', the limits smaller, and each event is projected to the
35653
+ * device's shape (`deviceEvent`) as it is sent, so a session the feed does not list reaches no device.
35654
+ */
35655
+ private deviceEventDeliveryQueues(): ControllerEventDelivery {
35656
+ this.deviceEventDelivery ??= new ControllerEventDelivery({
35657
+ viewers: async () => {
35658
+ const typedSocket = this.typedServer?.typedsocket;
35659
+ const devices = this.devices;
35660
+ if (!typedSocket || !devices?.hasLivePeers()) return [];
35661
+ const targets = await typedSocket.findAllTargetConnections(async (connectionArg) => (
35662
+ devices.deviceIdOf(connectionArg.peer) !== undefined
35663
+ ));
35664
+ return targets.map((targetArg) => ({
35665
+ peerId: targetArg.peer.id,
35666
+ send: async (eventArg: IControllerEvent) => {
35667
+ const event = deviceEvent(eventArg, (rowIdArg) => this.sessionFeed?.publishedRow(rowIdArg));
35668
+ if (event === undefined || devices.deviceIdOf(targetArg.peer) === undefined) return;
35669
+ await typedSocket.createTypedRequest<IReq_DeviceEventPush>(
35670
+ 'device.event',
35671
+ targetArg,
35672
+ { timeoutMs: 2_000 },
35673
+ ).fire({ event }, { timeoutMs: 2_000, maxRetries: 0 });
35674
+ },
35675
+ }));
35676
+ },
35677
+ eventKey: (eventArg) => this.controllerEventKey(eventArg),
35678
+ mergeDelta: mergeControllerMessageDeltaEvents,
35679
+ limits: {
35680
+ events: maxPendingDeviceEventsPerViewer,
35681
+ bytes: maxPendingDeviceEventBytesPerViewer,
35682
+ mergedDeltaBytes: controllerMaxLiveMessageEventBytes,
35683
+ },
35684
+ });
35685
+ return this.deviceEventDelivery;
35160
35686
  }
35161
35687
 
35162
35688
  private runUpgradePreparationAdmission<T>(operationArg: () => Promise<T>): Promise<T> {
@@ -35981,7 +36507,18 @@ export class OpenCodeController {
35981
36507
  operationArg: (signalArg: AbortSignal) => Promise<T>,
35982
36508
  requestSignalArg?: AbortSignal,
35983
36509
  ): Promise<T> {
35984
- const peerId = peerArg.id;
36510
+ return this.runPrincipalOperation(
36511
+ 'browser',
36512
+ peerArg.id,
36513
+ operationArg,
36514
+ requestSignalArg,
36515
+ this.peerOperationSignal(peerArg),
36516
+ typeof peerArg.context.state[authenticatedPeerStateKey] === 'string',
36517
+ );
36518
+ }
36519
+
36520
+ /** The signal every operation of a connection runs under: its close, and a revoked device's revocation, abort it. */
36521
+ private peerOperationSignal(peerArg: IControllerPeer): AbortSignal {
35985
36522
  const storedPeerAbortController = peerArg.context.state[operationAbortControllerPeerStateKey];
35986
36523
  const peerAbortController = storedPeerAbortController instanceof AbortController
35987
36524
  && !storedPeerAbortController.signal.aborted
@@ -35990,14 +36527,7 @@ export class OpenCodeController {
35990
36527
  if (peerAbortController !== storedPeerAbortController) {
35991
36528
  peerArg.context.state[operationAbortControllerPeerStateKey] = peerAbortController;
35992
36529
  }
35993
- return this.runPrincipalOperation(
35994
- 'browser',
35995
- peerId,
35996
- operationArg,
35997
- requestSignalArg,
35998
- peerAbortController.signal,
35999
- typeof peerArg.context.state[authenticatedPeerStateKey] === 'string',
36000
- );
36530
+ return peerAbortController.signal;
36001
36531
  }
36002
36532
 
36003
36533
  private runPrincipalOperation<T>(
@@ -36058,7 +36588,7 @@ export class OpenCodeController {
36058
36588
  private assertControllerOperationPrincipal(
36059
36589
  principalArg: TControllerOperationPrincipal,
36060
36590
  ): void {
36061
- if (principalArg !== 'browser' && principalArg !== 'mcp') {
36591
+ if (principalArg !== 'browser' && principalArg !== 'mcp' && principalArg !== 'device') {
36062
36592
  throw new Error('The controller operation principal is invalid.');
36063
36593
  }
36064
36594
  }