agl 41.2.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 (120) hide show
  1. package/changelog.md +41 -0
  2. package/dist_serve/bundle.js +2625 -2278
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +3 -68
  5. package/dist_serve/bundle.js.third-party-notices.txt +4 -137
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/aglapi/aglapisurface.document.js +4 -4
  8. package/dist_ts/classes.authmodels.d.ts +2 -8
  9. package/dist_ts/classes.authmodels.js +60 -23
  10. package/dist_ts/classes.authstore.d.ts +24 -0
  11. package/dist_ts/classes.authstore.js +185 -23
  12. package/dist_ts/classes.cli.d.ts +3 -6
  13. package/dist_ts/classes.cli.js +38 -51
  14. package/dist_ts/classes.config.d.ts +17 -3
  15. package/dist_ts/classes.config.js +55 -18
  16. package/dist_ts/classes.controller.d.ts +83 -14
  17. package/dist_ts/classes.controller.js +545 -229
  18. package/dist_ts/classes.controllerdevices.d.ts +128 -0
  19. package/dist_ts/classes.controllerdevices.js +472 -0
  20. package/dist_ts/classes.controllermanagement.d.ts +42 -9
  21. package/dist_ts/classes.controllermanagement.js +72 -23
  22. package/dist_ts/classes.controllerservice.d.ts +3 -31
  23. package/dist_ts/classes.controllerservice.js +3 -47
  24. package/dist_ts/classes.mcpcontrollerhost.js +9 -3
  25. package/dist_ts/classes.processinspection.d.ts +8 -1
  26. package/dist_ts/classes.processinspection.js +92 -2
  27. package/dist_ts/classes.proxycontrol.js +6 -1
  28. package/dist_ts/classes.proxydaemon.d.ts +2 -2
  29. package/dist_ts/classes.proxydaemon.js +1 -1
  30. package/dist_ts/classes.proxystore.d.ts +2 -11
  31. package/dist_ts/classes.proxystore.js +3 -25
  32. package/dist_ts/classes.sessionfeed.d.ts +10 -1
  33. package/dist_ts/classes.sessionfeed.js +12 -2
  34. package/dist_ts/classes.tpmsecretcodec.d.ts +13 -0
  35. package/dist_ts/classes.tpmsecretcodec.js +28 -0
  36. package/dist_ts/classes.trustedproxysecrets.d.ts +91 -0
  37. package/dist_ts/classes.trustedproxysecrets.js +338 -0
  38. package/dist_ts/classes.upgradecoordinator.d.ts +14 -1
  39. package/dist_ts/classes.upgradecoordinator.js +21 -3
  40. package/dist_ts/classes.upgradetransaction.d.ts +32 -0
  41. package/dist_ts/classes.upgradetransaction.js +101 -4
  42. package/dist_ts/classes.validation.d.ts +2 -0
  43. package/dist_ts/classes.validation.js +2 -2
  44. package/dist_ts/functions.controlleradmission.d.ts +67 -0
  45. package/dist_ts/functions.controlleradmission.js +127 -0
  46. package/dist_ts/functions.deviceapi.d.ts +28 -0
  47. package/dist_ts/functions.deviceapi.js +246 -0
  48. package/dist_ts/functions.deviceproof.d.ts +33 -0
  49. package/dist_ts/functions.deviceproof.js +93 -0
  50. package/dist_ts/functions.remotecli.d.ts +27 -0
  51. package/dist_ts/functions.remotecli.js +241 -0
  52. package/dist_ts/functions.retiredenvironment.d.ts +11 -2
  53. package/dist_ts/functions.retiredenvironment.js +22 -5
  54. package/dist_ts/index.d.ts +1 -0
  55. package/dist_ts/index.js +2 -1
  56. package/dist_ts/interfaces.auth.d.ts +29 -4
  57. package/dist_ts/interfaces.auth.js +10 -1
  58. package/dist_ts/interfaces.config.d.ts +14 -0
  59. package/dist_ts/interfaces.config.js +9 -2
  60. package/dist_ts/interfaces.lifecycle.d.ts +3 -0
  61. package/dist_ts_authswitch/classes.authoritydaemon.js +6 -1
  62. package/dist_ts_interfaces/devices.d.ts +331 -0
  63. package/dist_ts_interfaces/devices.js +34 -0
  64. package/dist_ts_interfaces/index.d.ts +2 -0
  65. package/dist_ts_interfaces/index.js +3 -1
  66. package/dist_ts_interfaces/interfaces.d.ts +5 -3
  67. package/dist_ts_interfaces/interfaces.js +3 -2
  68. package/dist_ts_interfaces/management.d.ts +2 -2
  69. package/dist_ts_interfaces/management.js +2 -2
  70. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  71. package/dist_ts_interfaces/requests.d.ts +2 -2
  72. package/dist_ts_interfaces/requests.devices.d.ts +89 -0
  73. package/dist_ts_interfaces/requests.devices.js +2 -0
  74. package/dist_ts_interfaces/requests.upgrade.d.ts +0 -12
  75. package/package.json +12 -11
  76. package/readme.md +116 -24
  77. package/ts/00_commitinfo_data.ts +1 -1
  78. package/ts/aglapi/aglapisurface.document.ts +3 -3
  79. package/ts/classes.authmodels.ts +68 -25
  80. package/ts/classes.authstore.ts +183 -24
  81. package/ts/classes.cli.ts +38 -61
  82. package/ts/classes.config.ts +70 -21
  83. package/ts/classes.controller.ts +746 -329
  84. package/ts/classes.controllerdevices.ts +469 -0
  85. package/ts/classes.controllermanagement.ts +123 -49
  86. package/ts/classes.controllerservice.ts +3 -56
  87. package/ts/classes.mcpcontrollerhost.ts +10 -5
  88. package/ts/classes.processinspection.ts +84 -3
  89. package/ts/classes.proxycontrol.ts +2 -0
  90. package/ts/classes.proxydaemon.ts +3 -2
  91. package/ts/classes.proxystore.ts +4 -25
  92. package/ts/classes.sessionfeed.ts +13 -1
  93. package/ts/classes.tpmsecretcodec.ts +26 -0
  94. package/ts/classes.trustedproxysecrets.ts +317 -0
  95. package/ts/classes.upgradecoordinator.ts +33 -3
  96. package/ts/classes.upgradetransaction.ts +130 -1
  97. package/ts/classes.validation.ts +1 -1
  98. package/ts/functions.controlleradmission.ts +168 -0
  99. package/ts/functions.deviceapi.ts +295 -0
  100. package/ts/functions.deviceproof.ts +118 -0
  101. package/ts/functions.remotecli.ts +270 -0
  102. package/ts/functions.retiredenvironment.ts +25 -3
  103. package/ts/index.ts +1 -0
  104. package/ts/interfaces.auth.ts +41 -3
  105. package/ts/interfaces.config.ts +15 -0
  106. package/ts/interfaces.lifecycle.ts +3 -0
  107. package/ts_authswitch/classes.authoritydaemon.ts +2 -0
  108. package/ts_interfaces/devices.schema.json +890 -0
  109. package/ts_interfaces/devices.ts +392 -0
  110. package/ts_interfaces/index.ts +2 -0
  111. package/ts_interfaces/interfaces.ts +5 -2
  112. package/ts_interfaces/management.ts +2 -2
  113. package/ts_interfaces/mcprequests.ts +1 -1
  114. package/ts_interfaces/requests.devices.ts +95 -0
  115. package/ts_interfaces/requests.ts +10 -10
  116. package/ts_interfaces/requests.upgrade.ts +0 -16
  117. package/ts_web/00_commitinfo_data.ts +1 -1
  118. package/ts_web/classes.controllersocketclient.ts +27 -0
  119. package/ts_web/elements.devices.ts +752 -0
  120. 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,
@@ -314,7 +333,6 @@ import {
314
333
  type IReq_ControllerSetupFinish,
315
334
  type IReq_ControllerStatus,
316
335
  type IReq_ControllerUpgradeLaunch,
317
- type IReq_ControllerUpgradePrepare,
318
336
  type IReq_ControllerUpgradePrepareBegin,
319
337
  type IReq_ControllerUpgradeFinalize,
320
338
  type IReq_ControllerFailureDetailGet,
@@ -333,6 +351,23 @@ import {
333
351
  type TControllerResource,
334
352
  type TControllerOperationPrincipal,
335
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,
336
371
  type IControllerProviderAccountRateLimits,
337
372
  type IControllerSessionRetrying,
338
373
  accountInHostCodexReason,
@@ -347,11 +382,12 @@ import {
347
382
  parseFlexAuthorityConnectionId,
348
383
  } from '../ts_interfaces/index.js';
349
384
  import {
350
- readTrustedProxySecret,
351
385
  resolveInitialRuntimeConfig,
352
386
  resolveStoredRuntimeConfig,
353
387
  } from './classes.config.js';
354
- import { assertControllerServiceTlsMode, controllerServiceDetachedRemedy } from './classes.controllerservice.js';
388
+ import { controllerListenerOptions } from './functions.controlleradmission.js';
389
+ import { ControllerTrustedProxySecrets } from './classes.trustedproxysecrets.js';
390
+ import { TpmSecretCodec } from './classes.tpmsecretcodec.js';
355
391
  import { resolveAGLHomePaths } from './classes.aglhome.js';
356
392
  import { selectControllerBrowserPaint } from './functions.browserpaintartifact.js';
357
393
  import { ControllerBrowserViewerAssets } from './functions.browserpaintassets.js';
@@ -795,7 +831,6 @@ const currentRuntimeName = currentCliName === upgradePackageTransitionTarget.cli
795
831
  const authenticatedPeerStateKey = '__opencodeControllerAuthenticatedCredentialId';
796
832
  const terminalPeerLifecycleStateKey = '__harnessControllerTerminalPeerLifecycle';
797
833
  const operationAbortControllerPeerStateKey = '__harnessControllerOperationAbortController';
798
- const trustedProxySecretHeader = 'x-harness-controller-proxy-secret';
799
834
  // Generous for a local single-user deployment: transcripts and inline
800
835
  // attachments are legitimately multi-megabyte, and an undersized limit
801
836
  // fail-closes the connection (and with it the per-connection auth).
@@ -935,6 +970,9 @@ const maxPendingFlexControllerEvents = 512;
935
970
  /** Events and serialized bytes one browser may have waiting before its queue collapses into a resync. */
936
971
  const maxPendingControllerEventsPerViewer = 512;
937
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;
938
976
  const maxLatestFlexToolExecutions = 512;
939
977
  const maxLatestFlexToolExecutionBytes = 8 * 1024 * 1024;
940
978
  const maxLatestFlexMessageUpdateBytes = 16 * 1024 * 1024;
@@ -2348,6 +2386,16 @@ const peerFromLocalData = (localDataArg: unknown): IControllerPeer => {
2348
2386
 
2349
2387
 
2350
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}`;
2351
2399
  /** The browser's native send writes to every session that states no read-only reason. */
2352
2400
  const assertNativeSessionWritable = (resolvedArg: IResolvedNativeSession): void => {
2353
2401
  const { readOnly } = resolvedArg.session;
@@ -2846,17 +2894,9 @@ const asTypedResponseError = (
2846
2894
  const hashResumeToken = (tokenArg: string): string =>
2847
2895
  plugins.crypto.createHash('sha256').update(tokenArg, 'utf8').digest('base64url');
2848
2896
 
2849
- const headerSecretsEqual = (candidateArg: string | null, expectedArg: string): boolean => {
2850
- if (candidateArg === null) return false;
2851
- const candidate = Buffer.from(candidateArg, 'utf8');
2852
- const expected = Buffer.from(expectedArg, 'utf8');
2853
- return candidate.byteLength === expected.byteLength
2854
- && plugins.crypto.timingSafeEqual(candidate, expected);
2855
- };
2856
-
2857
2897
  const assertControllerUpgradePreparationRequest: (
2858
2898
  requestArg: unknown,
2859
- ) => asserts requestArg is IReq_ControllerUpgradePrepare['request'] = (requestArg) => {
2899
+ ) => asserts requestArg is IReq_ControllerUpgradePrepareBegin['request'] = (requestArg) => {
2860
2900
  if (
2861
2901
  !requestArg
2862
2902
  || typeof requestArg !== 'object'
@@ -2873,24 +2913,6 @@ const assertControllerUpgradePreparationRequest: (
2873
2913
  );
2874
2914
  };
2875
2915
 
2876
- export const isControllerWebSocketRequestAllowed = (
2877
- headersArg: Headers,
2878
- publicOriginArg: string,
2879
- tlsModeArg: 'local' | 'proxy',
2880
- trustedProxySecretArg?: string,
2881
- ): boolean => {
2882
- const origin = headersArg.get('origin');
2883
- if (origin === null) return true;
2884
- if (origin !== publicOriginArg) return false;
2885
- if (tlsModeArg === 'local') return true;
2886
- return headersArg.get('x-forwarded-proto') === 'https'
2887
- && trustedProxySecretArg !== undefined
2888
- && headerSecretsEqual(
2889
- headersArg.get(trustedProxySecretHeader),
2890
- trustedProxySecretArg,
2891
- );
2892
- };
2893
-
2894
2916
  interface IControllerHarnessSessionEnumeration {
2895
2917
  openCode: PromiseSettledResult<IControllerSession[]>;
2896
2918
  flex: PromiseSettledResult<IControllerSession[]>;
@@ -3123,6 +3145,10 @@ export class OpenCodeController {
3123
3145
  private pendingFlexMessageEventBytes = 0;
3124
3146
  private flexControllerEventDrainTask?: Promise<void>;
3125
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;
3126
3152
  private flexAutoAcceptDrainTask?: Promise<void>;
3127
3153
  /** Sweeps whose auto-accept failed, queued again when the retry timer fires. */
3128
3154
  private readonly failedFlexAutoAcceptSweeps = new Map<string, IFlexAutoAcceptSweep>();
@@ -3338,7 +3364,7 @@ export class OpenCodeController {
3338
3364
  acknowledge: async (rowIdArg, updatedAtArg, actorArg) => {
3339
3365
  await this.sessionFeedAcknowledgements.put(await this.sessionFeedOwner(), rowIdArg, updatedAtArg, actorArg);
3340
3366
  },
3341
- hasViewers: async () => (await this.controllerEventViewers()).length > 0,
3367
+ hasViewers: async () => this.devices?.hasLivePeers() === true || (await this.controllerEventViewers()).length > 0,
3342
3368
  publish: (deltaArg) => {
3343
3369
  void this.pushControllerEvent({ type: 'sessionfeed.changed', sessionFeed: deltaArg, timestamp: Date.now() }).catch(() => undefined);
3344
3370
  },
@@ -3371,6 +3397,8 @@ export class OpenCodeController {
3371
3397
  return this.ticketStore.applyFleetEvent(eventArg, signalArg, originArg);
3372
3398
  }
3373
3399
  private passkeyManager?: PasskeyManager;
3400
+ /** TLS-proxy mode only: the secret admission accepts from the reverse proxy, and its rotation. */
3401
+ private trustedProxySecrets?: ControllerTrustedProxySecrets;
3374
3402
  private openCodeSupervisor?: OpenCodeSupervisor;
3375
3403
  private openCodeClient?: OpenCodeClientAdapter;
3376
3404
  private flexSupervisor?: FlexSupervisor;
@@ -4150,6 +4178,17 @@ export class OpenCodeController {
4150
4178
  }
4151
4179
  }
4152
4180
 
4181
+ /**
4182
+ * The trusted-proxy secret of a running controller in TLS-proxy mode, for its gateway client: the secret its route
4183
+ * carries (`routeSecret`), `rotate` and `confirm` once the route carries the new one. Refused in local mode.
4184
+ */
4185
+ public requireTrustedProxySecrets(): ControllerTrustedProxySecrets {
4186
+ if (!this.trustedProxySecrets) {
4187
+ throw new Error('This controller runs no trusted reverse proxy: it is in local mode or not running.');
4188
+ }
4189
+ return this.trustedProxySecrets;
4190
+ }
4191
+
4153
4192
  public getStatus(): IControllerStatus {
4154
4193
  const openCodeStatus = this.openCodeSupervisor?.getStatus() ?? {
4155
4194
  state: 'stopped' as const,
@@ -10064,9 +10103,6 @@ export class OpenCodeController {
10064
10103
  ? await resolveStoredRuntimeConfig(storedConfig, this.options.runtimeOverrides)
10065
10104
  : await resolveInitialRuntimeConfig(this.options.runtimeOverrides);
10066
10105
  this.assertStartActive();
10067
- if (this.options.serviceUnit !== undefined) {
10068
- assertControllerServiceTlsMode({ stored: runtimeConfig.tlsMode, remedy: controllerServiceDetachedRemedy });
10069
- }
10070
10106
  const authDocument = await authStore.resolveOrCreateRuntimeConfig(runtimeConfig);
10071
10107
  await authStore.migrateTicketOwnerPrincipal();
10072
10108
  this.assertStartActive();
@@ -10112,8 +10148,30 @@ export class OpenCodeController {
10112
10148
  this.setupRequired = authState.state === 'setupRequired';
10113
10149
  this.assertStartActive();
10114
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
+
10115
10165
  const router = this.createRouter(runtimeConfig.publicOrigin);
10116
- const trustedProxySecret = readTrustedProxySecret(runtimeConfig.tlsMode);
10166
+ if (runtimeConfig.tlsMode === 'proxy') {
10167
+ this.trustedProxySecrets = await ControllerTrustedProxySecrets.open({
10168
+ controllerId: authDocument.id,
10169
+ issuerId: issuerIdentity.issuerId,
10170
+ codec: this.options.trustedProxySecretCodec ?? new TpmSecretCodec(),
10171
+ });
10172
+ this.assertStartActive();
10173
+ }
10174
+ const trustedProxySecrets = this.trustedProxySecrets;
10117
10175
  const publicHostname = new URL(runtimeConfig.publicOrigin).hostname;
10118
10176
  const hostnames = [...new Set([publicHostname, 'localhost', '127.0.0.1'])];
10119
10177
  const serveDirectory = plugins.path.resolve(
@@ -10137,11 +10195,11 @@ export class OpenCodeController {
10137
10195
  this.assertStartActive();
10138
10196
  const typedServer = new plugins.typedserver.TypedServer({
10139
10197
  port: runtimeConfig.controllerPort,
10140
- // local mode has no transport secret and its admission rests on
10141
- // browser-supplied headers, which any network client can forge — so the
10142
- // listener itself is the boundary and must stay loopback-only. Proxy mode
10143
- // binds wide by design; the readme requires backend isolation there.
10144
- listenHostname: runtimeConfig.tlsMode === 'local' ? '127.0.0.1' : '0.0.0.0',
10198
+ // One listener: loopback unless a gateway reaches this controller from another address, and then every
10199
+ // interface, where admission refuses every address off loopback that is not a gateway source sending the
10200
+ // trusted-proxy secret, on every surface alike. The host firewall must still let only the gateways reach the
10201
+ // port (readme, "Remote Browser Access").
10202
+ ...controllerListenerOptions(runtimeConfig, (valueArg) => trustedProxySecrets?.accepts(valueArg) === true),
10145
10203
  cors: false,
10146
10204
  websocketMaxPayloadBytes: websocketPayloadLimit,
10147
10205
  connectionTimeout: 120_000,
@@ -10180,12 +10238,6 @@ export class OpenCodeController {
10180
10238
  headers: { Allow: 'GET, HEAD' },
10181
10239
  });
10182
10240
  },
10183
- websocketAdmission: (contextArg) => isControllerWebSocketRequestAllowed(
10184
- contextArg.headers,
10185
- runtimeConfig.publicOrigin,
10186
- runtimeConfig.tlsMode,
10187
- trustedProxySecret,
10188
- ),
10189
10241
  securityHeaders,
10190
10242
  },
10191
10243
  ],
@@ -12960,6 +13012,7 @@ export class OpenCodeController {
12960
13012
  peerArg: IControllerPeer,
12961
13013
  authStoreArg: SmartDataAuthStore,
12962
13014
  ): Promise<void> {
13015
+ this.devices?.disconnect(peerArg);
12963
13016
  const peerOperationAbortController = peerArg.context.state[
12964
13017
  operationAbortControllerPeerStateKey
12965
13018
  ];
@@ -13311,6 +13364,7 @@ export class OpenCodeController {
13311
13364
  ...(this.flexControllerEventDrainTask ? [this.flexControllerEventDrainTask] : []),
13312
13365
  ]);
13313
13366
  await this.controllerEventDelivery?.stop();
13367
+ await this.deviceEventDelivery?.stop();
13314
13368
 
13315
13369
  if (this.flexProjectionReader) {
13316
13370
  await stopPart(async () => {
@@ -13423,6 +13477,13 @@ export class OpenCodeController {
13423
13477
  && !this.flexProjectionReader
13424
13478
  && !this.eventStreamTask;
13425
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
+ }
13426
13487
  if (storesStoppable && this.authStore) {
13427
13488
  const authStore = this.authStore;
13428
13489
  if (this.controllerStartedRecorded && !this.controllerStoppedRecorded) {
@@ -13444,6 +13505,8 @@ export class OpenCodeController {
13444
13505
  await authStore.close();
13445
13506
  if (this.authStore === authStore) {
13446
13507
  this.authStore = undefined;
13508
+ this.trustedProxySecrets?.close();
13509
+ this.trustedProxySecrets = undefined;
13447
13510
  this.passkeyManager = undefined;
13448
13511
  this.controllerId = undefined;
13449
13512
  this.openCodeRuntimeDirectory = undefined;
@@ -13524,19 +13587,24 @@ export class OpenCodeController {
13524
13587
  }
13525
13588
 
13526
13589
  /**
13527
- * 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
13528
13591
  * registered on and by nothing else, so each `register*Handlers` method is handed
13529
13592
  * exactly one scope here, and test/test.routerscopes.node.ts freezes the resulting
13530
- * 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`.
13531
13595
  */
13532
13596
  private createRouter(publicOriginArg: string): plugins.typedrequest.TypedRouter {
13533
13597
  const rootRouter = new plugins.typedrequest.TypedRouter();
13534
13598
  const publicRouter = new plugins.typedrequest.TypedRouter();
13535
13599
  const browserAuthRouter = new plugins.typedrequest.TypedRouter();
13536
13600
  const protectedRouter = new ControllerProtectedRouter(asTypedResponseError);
13601
+ const devicePairingRouter = new ControllerProtectedRouter(asTypedResponseError);
13602
+ const deviceRouter = new ControllerProtectedRouter(asTypedResponseError);
13537
13603
  rootRouter.addTypedRouter(publicRouter);
13538
13604
  rootRouter.addTypedRouter(browserAuthRouter);
13539
13605
  rootRouter.addTypedRouter(protectedRouter);
13606
+ rootRouter.addTypedRouter(devicePairingRouter);
13607
+ rootRouter.addTypedRouter(deviceRouter);
13540
13608
 
13541
13609
  browserAuthRouter.addMiddleware(async (requestArg) => {
13542
13610
  const peer = peerFromLocalData(requestArg.localData);
@@ -13559,9 +13627,15 @@ export class OpenCodeController {
13559
13627
  );
13560
13628
  }
13561
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
+ });
13562
13637
 
13563
13638
  this.registerStatusHandlers(publicRouter);
13564
- this.registerUpgradeHandlers(publicRouter);
13565
13639
 
13566
13640
  this.registerAuthHandlers(browserAuthRouter, publicOriginArg);
13567
13641
  this.registerSignInHandlers(protectedRouter);
@@ -13592,31 +13666,332 @@ export class OpenCodeController {
13592
13666
  this.registerSessionFeedHandlers(protectedRouter);
13593
13667
  this.registerUsageFeedHandlers(protectedRouter);
13594
13668
  this.registerTerminalHandlers(protectedRouter);
13669
+ this.registerDevicesHandlers(protectedRouter);
13670
+
13671
+ this.registerDevicePairingHandlers(devicePairingRouter);
13672
+ this.registerDeviceHandlers(deviceRouter);
13595
13673
 
13596
13674
  return rootRouter;
13597
13675
  }
13598
13676
 
13599
- /** Public scope: a browser reads the status before it holds a passkey session. */
13600
- private registerStatusHandlers(publicRouterArg: plugins.typedrequest.TypedRouter): void {
13601
- publicRouterArg.addTypedHandler(this.createStatusHandler());
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;
13602
13689
  }
13603
13690
 
13604
13691
  /**
13605
- * Public scope: the caller is the upgrade command, which holds no passkey session.
13606
- * Every handler here authorises itself against the upgrade token it is handed.
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>`.
13607
13695
  */
13608
- private registerUpgradeHandlers(publicRouterArg: plugins.typedrequest.TypedRouter): void {
13609
- publicRouterArg.addTypedHandler(this.createUpgradeLaunchHandler());
13610
- publicRouterArg.addTypedHandler(this.createUpgradePrepareHandler());
13611
- publicRouterArg.addTypedHandler(this.createUpgradePrepareBeginHandler());
13612
- publicRouterArg.addTypedHandler(this.createUpgradeFinalizeHandler());
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
+
13984
+ /** Public scope: a browser reads the status before it holds a passkey session. */
13985
+ private registerStatusHandlers(publicRouterArg: plugins.typedrequest.TypedRouter): void {
13986
+ publicRouterArg.addTypedHandler(this.createStatusHandler());
13613
13987
  }
13614
13988
 
13615
13989
  /**
13616
13990
  * The router of the loopback management endpoint (`controllerManagementMethods`): the status read and the upgrade
13617
- * methods the CLI and an upgrade worker of this or another release call. Each handler comes from the factory its
13618
- * controller socket handler comes from, so it authorises itself exactly as it does there; the endpoint's admission
13619
- * grants a request only its own peer. No other method is reachable through it.
13991
+ * methods the CLI and an upgrade worker of this or another release call, which only this endpoint serves (the
13992
+ * controller socket keeps the status read for the browser). The status handler is the one the socket's public scope
13993
+ * uses, and each upgrade handler authorises itself against the upgrade token and one-time grant it is handed; the
13994
+ * endpoint's admission grants a request only its own peer. No other method is reachable through it.
13620
13995
  */
13621
13996
  private createManagementRouter(): plugins.typedrequest.TypedRouter {
13622
13997
  const router = new plugins.typedrequest.TypedRouter();
@@ -13727,52 +14102,6 @@ export class OpenCodeController {
13727
14102
  );
13728
14103
  }
13729
14104
 
13730
- /** The synchronous preparation an upgrade worker of an earlier release asks for; served on the socket only. */
13731
- private createUpgradePrepareHandler(): plugins.typedrequest.TypedHandler<IReq_ControllerUpgradePrepare> {
13732
- return new plugins.typedrequest.TypedHandler<IReq_ControllerUpgradePrepare>(
13733
- 'controller.upgrade.prepare',
13734
- async (requestArg, toolsArg) => {
13735
- const peer = peerFromLocalData(toolsArg?.localData);
13736
- this.recordUnauthenticatedPreflightOperation(peer.id);
13737
- assertControllerUpgradePreparationRequest(requestArg);
13738
- return this.runOperation(peer, async (signalArg) => (
13739
- this.runUpgradePreparationAdmission(async () => {
13740
- const installation = await resolveCurrentPnpmGlobalInstallation();
13741
- const coordinator = this.coordinatorForUpgradeToken(
13742
- requestArg.token,
13743
- installation.globalRoot,
13744
- );
13745
- const status = this.getStatus();
13746
- await coordinator.consumeControllerActionGrant({
13747
- token: requestArg.token,
13748
- action: 'prepare',
13749
- packageVersion: commitinfo.version,
13750
- controller: {
13751
- pid: status.controllerPid,
13752
- processGroupId: status.processGroupId,
13753
- processFingerprint: status.processFingerprint,
13754
- },
13755
- });
13756
- await coordinator.recordController(requestArg.token, {
13757
- pid: status.controllerPid,
13758
- processGroupId: status.processGroupId,
13759
- fingerprint: status.processFingerprint,
13760
- cliPath: installation.cliPath,
13761
- command: this.options.processMode === 'detached' ? '__serve' : 'foreground',
13762
- });
13763
- return await this.prepareUpgrade(
13764
- coordinator,
13765
- requestArg.token,
13766
- requestArg.targetVersion,
13767
- requestArg.gracePeriodMs,
13768
- signalArg,
13769
- );
13770
- })
13771
- ));
13772
- },
13773
- );
13774
- }
13775
-
13776
14105
  private createUpgradePrepareBeginHandler(): plugins.typedrequest.TypedHandler<IReq_ControllerUpgradePrepareBegin> {
13777
14106
  return new plugins.typedrequest.TypedHandler<IReq_ControllerUpgradePrepareBegin>(
13778
14107
  'controller.upgrade.prepare.begin',
@@ -13899,6 +14228,7 @@ export class OpenCodeController {
13899
14228
  const peer = peerFromLocalData(toolsArg?.localData);
13900
14229
  const validated = validateRequest(() => assertSetupBeginRequest(requestArg));
13901
14230
  return this.runOperation(peer, async () => {
14231
+ this.refuseDevicePeerSignIn(peer);
13902
14232
  try {
13903
14233
  return await this.requirePasskeyManager().beginSetup({
13904
14234
  peerId: peer.id,
@@ -13919,6 +14249,7 @@ export class OpenCodeController {
13919
14249
  const validated = validateRequest(() => assertSetupFinishRequest(requestArg));
13920
14250
  return this.runOperation(peer, async () => {
13921
14251
  this.recordUnauthenticatedPreflightOperation(peer.id);
14252
+ this.refuseDevicePeerSignIn(peer);
13922
14253
  try {
13923
14254
  await this.requirePasskeyManager().preflightSetupFinish({
13924
14255
  peerId: peer.id,
@@ -13953,6 +14284,7 @@ export class OpenCodeController {
13953
14284
  validateRequest(() => assertEmptyRequest(requestArg));
13954
14285
  const peer = peerFromLocalData(toolsArg?.localData);
13955
14286
  return this.runOperation(peer, async () => {
14287
+ this.refuseDevicePeerSignIn(peer);
13956
14288
  try {
13957
14289
  return await this.requirePasskeyManager().beginAuthentication({
13958
14290
  peerId: peer.id,
@@ -13974,6 +14306,7 @@ export class OpenCodeController {
13974
14306
  const peer = peerFromLocalData(toolsArg?.localData);
13975
14307
  return this.runOperation(peer, async () => {
13976
14308
  this.recordUnauthenticatedPreflightOperation(peer.id);
14309
+ this.refuseDevicePeerSignIn(peer);
13977
14310
  try {
13978
14311
  await this.requirePasskeyManager().preflightAuthenticationFinish({
13979
14312
  peerId: peer.id,
@@ -14008,6 +14341,7 @@ export class OpenCodeController {
14008
14341
  const peer = peerFromLocalData(toolsArg?.localData);
14009
14342
  return this.runOperation(peer, async () => {
14010
14343
  this.recordUnauthenticatedPreflightOperation(peer.id);
14344
+ this.refuseDevicePeerSignIn(peer);
14011
14345
  this.recordUnauthenticatedAuditOperation(peer.id);
14012
14346
  const result = await this.runAudited(
14013
14347
  { type: 'temppassword.login', peerId: peer.id },
@@ -14044,6 +14378,7 @@ export class OpenCodeController {
14044
14378
  const peer = peerFromLocalData(toolsArg?.localData);
14045
14379
  return this.runOperation(peer, async () => {
14046
14380
  this.recordUnauthenticatedPreflightOperation(peer.id);
14381
+ this.refuseDevicePeerSignIn(peer);
14047
14382
  this.recordUnauthenticatedAuditOperation(peer.id);
14048
14383
  const result = await this.runAudited(
14049
14384
  { type: 'auth.resume', peerId: peer.id },
@@ -16336,75 +16671,9 @@ export class OpenCodeController {
16336
16671
  'controller.permission.reply',
16337
16672
  async (requestArg, toolsArg) => {
16338
16673
  const peer = peerFromLocalData(toolsArg?.localData);
16339
- const { projectId, sessionId, requestId, reply, message } = validateRequest(
16340
- () => assertPermissionReplyRequest(requestArg),
16341
- );
16342
- return this.runOperation(peer, async (signalArg) => this.runAudited(
16343
- { type: 'permission.reply', peerId: peer.id, sessionId, requestId },
16344
- async () => {
16345
- const project = await this.resolveProject(projectId);
16346
- await this.assertSessionExists(projectId, sessionId, signalArg);
16347
- if (sessionId.harnessId === 'codex') {
16348
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16349
- signalArg.throwIfAborted();
16350
- this.requireCodexClient(sessionId.nativeId).replyPermission(sessionId.nativeId, requestId.nativeId, reply);
16351
- return { success: true };
16352
- });
16353
- }
16354
- if (sessionId.harnessId === 'claude') {
16355
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16356
- signalArg.throwIfAborted();
16357
- this.requireClaudeHarness().replyPermission(sessionId.nativeId, requestId.nativeId, reply);
16358
- return { success: true };
16359
- });
16360
- }
16361
- if (sessionId.harnessId === 'flex') {
16362
- signalArg.throwIfAborted();
16363
- const flexSupervisor = this.requireFlexSupervisor();
16364
- const pendingPermissions = await flexSupervisor.request('permission.list', {
16365
- scopeId: projectId,
16366
- }, signalArg);
16367
- const permission = pendingPermissions.permissions.find(
16368
- (candidate) => candidate.permissionId === requestId.nativeId,
16369
- );
16370
- if (!permission) throw new FlexServiceError('NOT_FOUND');
16371
- const authority = this.flexPermissionAuthority(projectId, permission);
16372
- if (
16373
- !authority
16374
- || (
16375
- authority.type === 'managed'
16376
- && authority.run.sessionId !== sessionId.nativeId
16377
- )
16378
- || (
16379
- authority.type === 'delegated'
16380
- && authority.lease.rootAuthority.sessionId !== sessionId.nativeId
16381
- )
16382
- ) throw new FlexServiceError('NOT_FOUND');
16383
- await this.respondToFlexPermission(
16384
- projectId,
16385
- permission,
16386
- reply,
16387
- authority,
16388
- signalArg,
16389
- );
16390
- return { success: true };
16391
- }
16392
- const pendingPermissions = await this.requireOpenCodeClient().listPermissions(
16393
- project.directory,
16394
- sessionId.nativeId,
16395
- signalArg,
16396
- );
16397
- this.assertAttentionRequestOwned(pendingPermissions, requestId, 'permission');
16398
- return {
16399
- success: await this.requireOpenCodeClient().replyPermission(
16400
- project.directory,
16401
- requestId.nativeId,
16402
- reply,
16403
- message,
16404
- signalArg,
16405
- ),
16406
- };
16407
- },
16674
+ const request = validateRequest(() => assertPermissionReplyRequest(requestArg));
16675
+ return this.runOperation(peer, async (signalArg) => this.replyPermissionForPrincipal(
16676
+ 'browser', peer.id, request, signalArg,
16408
16677
  ));
16409
16678
  },
16410
16679
  );
@@ -16413,55 +16682,149 @@ export class OpenCodeController {
16413
16682
  'controller.question.reply',
16414
16683
  async (requestArg, toolsArg) => {
16415
16684
  const peer = peerFromLocalData(toolsArg?.localData);
16416
- const { projectId, sessionId, requestId, answers } = validateRequest(
16417
- () => assertQuestionReplyRequest(requestArg),
16418
- );
16419
- return this.runOperation(peer, async (signalArg) => this.runAudited(
16420
- { type: 'question.reply', peerId: peer.id, sessionId, requestId },
16421
- async () => {
16422
- const project = await this.resolveProject(projectId);
16423
- await this.assertSessionExists(projectId, sessionId, signalArg);
16424
- if (sessionId.harnessId === 'codex') {
16425
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16426
- signalArg.throwIfAborted();
16427
- this.requireCodexClient(sessionId.nativeId).replyQuestion(sessionId.nativeId, requestId.nativeId, answers);
16428
- return { success: true };
16429
- });
16430
- }
16431
- if (sessionId.harnessId === 'claude') {
16432
- return this.withHarnessSubmissionAdmission(projectId, sessionId, signalArg, async () => {
16433
- signalArg.throwIfAborted();
16434
- this.requireClaudeHarness().replyQuestion(sessionId.nativeId, requestId.nativeId, answers);
16435
- return { success: true };
16436
- });
16437
- }
16438
- const openCodeClient = this.requireOpenCodeClient();
16439
- const pendingQuestions = await openCodeClient.listQuestions(
16440
- project.directory,
16441
- sessionId.nativeId,
16442
- signalArg,
16443
- );
16444
- this.assertAttentionRequestOwned(pendingQuestions, requestId, 'question');
16445
- return {
16446
- success: answers === null
16447
- ? await openCodeClient.rejectQuestion(
16448
- project.directory,
16449
- requestId.nativeId,
16450
- signalArg,
16451
- )
16452
- : await openCodeClient.replyQuestion(
16453
- project.directory,
16454
- requestId.nativeId,
16455
- answers,
16456
- signalArg,
16457
- ),
16458
- };
16459
- },
16685
+ const request = validateRequest(() => assertQuestionReplyRequest(requestArg));
16686
+ return this.runOperation(peer, async (signalArg) => this.replyQuestionForPrincipal(
16687
+ 'browser', peer.id, request, signalArg,
16460
16688
  ));
16461
16689
  },
16462
16690
  );
16463
16691
  }
16464
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
+
16465
16828
  private registerResourceHandlers(protectedRouterArg: ControllerProtectedRouter): void {
16466
16829
  protectedRouterArg.addHandler<IReq_ControllerResourceList>(
16467
16830
  'controller.resource.list',
@@ -17240,30 +17603,9 @@ export class OpenCodeController {
17240
17603
  'controller.nativesession.read',
17241
17604
  async (requestArg, toolsArg) => {
17242
17605
  const peer = peerFromLocalData(toolsArg?.localData);
17243
- const { session: ref, limit, before } = validateRequest(() => assertNativeSessionReadRequest(requestArg));
17244
- return this.runOperation(peer, (signalArg) => this.runAudited(
17245
- { type: 'session.read', peerId: peer.id, sessionId: runtimeId(ref) },
17246
- () => serve(signalArg, async () => {
17247
- const resolved = await this.nativeSessions.resolve(ref);
17248
- const [page, attention, state] = await Promise.all([
17249
- this.requireFleetWorkers().nativeHistory(ref.harness, resolved.native, limit ?? controllerInitialMessageBundleLimit, before),
17250
- this.nativeSessionAttention(resolved),
17251
- this.requireAuthStore().getSessionState(resolved.scope, runtimeId(ref), signalArg),
17252
- ]);
17253
- signalArg.throwIfAborted();
17254
- return {
17255
- session: resolved.session,
17256
- messagePage: boundControllerMessagePage({
17257
- bundles: page.bundles,
17258
- ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
17259
- ...(page.earlier && page.nextCursor === undefined ? { truncated: true } : {}),
17260
- }, controllerMaximumMessageBundles),
17261
- ...attention,
17262
- todos: [],
17263
- scratchpad: state.scratchpad,
17264
- intelligenceExchanges: state.intelligenceExchanges,
17265
- };
17266
- }),
17606
+ const request = validateRequest(() => assertNativeSessionReadRequest(requestArg));
17607
+ return this.runOperation(peer, (signalArg) => this.readNativeSessionForPrincipal(
17608
+ 'browser', peer.id, request, signalArg,
17267
17609
  ), toolsArg?.abortSignal);
17268
17610
  },
17269
17611
  );
@@ -17388,14 +17730,9 @@ export class OpenCodeController {
17388
17730
  'controller.nativesession.permission.reply',
17389
17731
  async (requestArg, toolsArg) => {
17390
17732
  const peer = peerFromLocalData(toolsArg?.localData);
17391
- const { session: ref, requestId, reply } = validateRequest(() => assertNativeSessionPermissionReplyRequest(requestArg));
17392
- return this.runOperation(peer, (signalArg) => this.runAudited(
17393
- { type: 'permission.reply', peerId: peer.id, sessionId: runtimeId(ref), requestId },
17394
- () => serve(signalArg, async () => {
17395
- const resolved = await this.nativeSessions.resolve(ref);
17396
- await this.replyNativeSessionRequest(resolved, requestId.nativeId, { permission: reply }, 'permission');
17397
- return { success: true };
17398
- }),
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,
17399
17736
  ), toolsArg?.abortSignal);
17400
17737
  },
17401
17738
  );
@@ -17404,19 +17741,80 @@ export class OpenCodeController {
17404
17741
  'controller.nativesession.question.reply',
17405
17742
  async (requestArg, toolsArg) => {
17406
17743
  const peer = peerFromLocalData(toolsArg?.localData);
17407
- const { session: ref, requestId, answers } = validateRequest(() => assertNativeSessionQuestionReplyRequest(requestArg));
17408
- return this.runOperation(peer, (signalArg) => this.runAudited(
17409
- { type: 'question.reply', peerId: peer.id, sessionId: runtimeId(ref), requestId },
17410
- () => serve(signalArg, async () => {
17411
- const resolved = await this.nativeSessions.resolve(ref);
17412
- await this.replyNativeSessionRequest(resolved, requestId.nativeId, { answers }, 'question');
17413
- return { success: true };
17414
- }),
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,
17415
17747
  ), toolsArg?.abortSignal);
17416
17748
  },
17417
17749
  );
17418
17750
  }
17419
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
+
17420
17818
  /** The requests of AGL's own turns in a native session that wait for an answer. */
17421
17819
  private async nativeSessionAttention(
17422
17820
  resolvedArg: IResolvedNativeSession,
@@ -21849,6 +22247,20 @@ export class OpenCodeController {
21849
22247
  return credentialId;
21850
22248
  }
21851
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
+
21852
22264
  private setAuthenticatedPeerCredential(
21853
22265
  peerArg: IControllerPeer,
21854
22266
  credentialIdArg: string,
@@ -35226,7 +35638,51 @@ export class OpenCodeController {
35226
35638
  private async pushControllerEvent(eventArg: IControllerEvent): Promise<void> {
35227
35639
  this.driverService?.observe(eventArg);
35228
35640
  this.sessionFeed?.observe(eventArg);
35229
- 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;
35230
35686
  }
35231
35687
 
35232
35688
  private runUpgradePreparationAdmission<T>(operationArg: () => Promise<T>): Promise<T> {
@@ -35325,7 +35781,6 @@ export class OpenCodeController {
35325
35781
 
35326
35782
  private async persistUpgradePreparation(
35327
35783
  contextArg: IUpgradePreparationContext,
35328
- asynchronousArg: boolean,
35329
35784
  ): Promise<void> {
35330
35785
  await contextArg.coordinator.mutateTransaction(contextArg.token, (current) => {
35331
35786
  if (current.version === upgradePackageTransitionTransactionVersion) {
@@ -35341,12 +35796,8 @@ export class OpenCodeController {
35341
35796
  sessionId: { ...session.sessionId },
35342
35797
  stopState: 'pending' as const,
35343
35798
  })),
35344
- ...(asynchronousArg
35345
- ? {
35346
- preparationAcceptedAt: contextArg.acceptedAt,
35347
- preparationDeadlineAt: contextArg.deadline,
35348
- }
35349
- : {}),
35799
+ preparationAcceptedAt: contextArg.acceptedAt,
35800
+ preparationDeadlineAt: contextArg.deadline,
35350
35801
  };
35351
35802
  }
35352
35803
  return {
@@ -35359,12 +35810,8 @@ export class OpenCodeController {
35359
35810
  sessionId: { ...session.sessionId },
35360
35811
  stopState: 'pending' as const,
35361
35812
  })),
35362
- ...(asynchronousArg
35363
- ? {
35364
- preparationAcceptedAt: contextArg.acceptedAt,
35365
- preparationDeadlineAt: contextArg.deadline,
35366
- }
35367
- : {}),
35813
+ preparationAcceptedAt: contextArg.acceptedAt,
35814
+ preparationDeadlineAt: contextArg.deadline,
35368
35815
  };
35369
35816
  });
35370
35817
  }
@@ -35388,7 +35835,7 @@ export class OpenCodeController {
35388
35835
  */
35389
35836
  private async completeUpgradePreparation(
35390
35837
  contextArg: IUpgradePreparationContext,
35391
- ): Promise<IReq_ControllerUpgradePrepare['response']> {
35838
+ ): Promise<void> {
35392
35839
  const {
35393
35840
  barrier,
35394
35841
  coordinator,
@@ -35497,7 +35944,6 @@ export class OpenCodeController {
35497
35944
  if (Date.now() > deadline) {
35498
35945
  throw new Error('The upgrade preparation deadline expired before completion.');
35499
35946
  }
35500
- return { prepared: true, sessionCount: barrier.sessions.length };
35501
35947
  }
35502
35948
 
35503
35949
  private async updateUpgradeBlockers(
@@ -35538,7 +35984,6 @@ export class OpenCodeController {
35538
35984
  private async compensateUpgradePreparationFailure(
35539
35985
  contextArg: IUpgradePreparationContext,
35540
35986
  errorArg: unknown,
35541
- finishTransactionArg: boolean,
35542
35987
  ): Promise<void> {
35543
35988
  let errorMessage = errorArg instanceof Error ? errorArg.message : String(errorArg);
35544
35989
  try {
@@ -35551,44 +35996,12 @@ export class OpenCodeController {
35551
35996
  } finally {
35552
35997
  this.clearUpgradePreparationAbortController(contextArg);
35553
35998
  }
35554
- if (finishTransactionArg) {
35555
- await contextArg.coordinator.finishTransaction(
35556
- contextArg.token,
35557
- false,
35558
- 'Upgrade preparation failed.',
35559
- errorMessage,
35560
- ).catch(() => undefined);
35561
- }
35562
- }
35563
-
35564
- private async prepareUpgrade(
35565
- coordinatorArg: UpgradeCoordinator,
35566
- tokenArg: string,
35567
- targetVersionArg: string,
35568
- gracePeriodMsArg: number,
35569
- operationSignalArg: AbortSignal,
35570
- ): Promise<IReq_ControllerUpgradePrepare['response']> {
35571
- const context = this.createUpgradePreparationContext(
35572
- coordinatorArg,
35573
- tokenArg,
35574
- targetVersionArg,
35575
- gracePeriodMsArg,
35576
- operationSignalArg,
35577
- );
35578
- const operation = Promise.resolve().then(async () => {
35579
- try {
35580
- await this.persistUpgradePreparation(context, false);
35581
- this.pushUpgradePreparationEvent();
35582
- const response = await this.completeUpgradePreparation(context);
35583
- this.clearUpgradePreparationAbortController(context);
35584
- return response;
35585
- } catch (errorArg) {
35586
- await this.compensateUpgradePreparationFailure(context, errorArg, false);
35587
- throw errorArg;
35588
- }
35589
- });
35590
- this.upgradePreparationTask = operation.then(() => undefined, () => undefined);
35591
- return await operation;
35999
+ await contextArg.coordinator.finishTransaction(
36000
+ contextArg.token,
36001
+ false,
36002
+ 'Upgrade preparation failed.',
36003
+ errorMessage,
36004
+ ).catch(() => undefined);
35592
36005
  }
35593
36006
 
35594
36007
  private async beginUpgradePreparation(
@@ -35644,13 +36057,13 @@ export class OpenCodeController {
35644
36057
  this.clearUpgradePreparationAbortController(context);
35645
36058
  return;
35646
36059
  }
35647
- await this.compensateUpgradePreparationFailure(context, errorArg, true);
36060
+ await this.compensateUpgradePreparationFailure(context, errorArg);
35648
36061
  }
35649
36062
  })();
35650
36063
  const trackedBackground = this.trackOperationPromise(background);
35651
36064
  this.upgradePreparationTask = trackedBackground;
35652
36065
  try {
35653
- await this.persistUpgradePreparation(context, true);
36066
+ await this.persistUpgradePreparation(context);
35654
36067
  releaseGate();
35655
36068
  this.pushUpgradePreparationEvent();
35656
36069
  return { accepted: true };
@@ -36094,7 +36507,18 @@ export class OpenCodeController {
36094
36507
  operationArg: (signalArg: AbortSignal) => Promise<T>,
36095
36508
  requestSignalArg?: AbortSignal,
36096
36509
  ): Promise<T> {
36097
- 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 {
36098
36522
  const storedPeerAbortController = peerArg.context.state[operationAbortControllerPeerStateKey];
36099
36523
  const peerAbortController = storedPeerAbortController instanceof AbortController
36100
36524
  && !storedPeerAbortController.signal.aborted
@@ -36103,14 +36527,7 @@ export class OpenCodeController {
36103
36527
  if (peerAbortController !== storedPeerAbortController) {
36104
36528
  peerArg.context.state[operationAbortControllerPeerStateKey] = peerAbortController;
36105
36529
  }
36106
- return this.runPrincipalOperation(
36107
- 'browser',
36108
- peerId,
36109
- operationArg,
36110
- requestSignalArg,
36111
- peerAbortController.signal,
36112
- typeof peerArg.context.state[authenticatedPeerStateKey] === 'string',
36113
- );
36530
+ return peerAbortController.signal;
36114
36531
  }
36115
36532
 
36116
36533
  private runPrincipalOperation<T>(
@@ -36171,7 +36588,7 @@ export class OpenCodeController {
36171
36588
  private assertControllerOperationPrincipal(
36172
36589
  principalArg: TControllerOperationPrincipal,
36173
36590
  ): void {
36174
- if (principalArg !== 'browser' && principalArg !== 'mcp') {
36591
+ if (principalArg !== 'browser' && principalArg !== 'mcp' && principalArg !== 'device') {
36175
36592
  throw new Error('The controller operation principal is invalid.');
36176
36593
  }
36177
36594
  }