agl 41.2.0 → 42.0.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 (91) hide show
  1. package/changelog.md +35 -0
  2. package/dist_serve/bundle.js +1996 -1999
  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 +22 -0
  11. package/dist_ts/classes.authstore.js +152 -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 +12 -12
  17. package/dist_ts/classes.controller.js +46 -117
  18. package/dist_ts/classes.controllermanagement.d.ts +42 -9
  19. package/dist_ts/classes.controllermanagement.js +72 -23
  20. package/dist_ts/classes.controllerservice.d.ts +3 -31
  21. package/dist_ts/classes.controllerservice.js +3 -47
  22. package/dist_ts/classes.mcpcontrollerhost.js +9 -3
  23. package/dist_ts/classes.processinspection.d.ts +8 -1
  24. package/dist_ts/classes.processinspection.js +92 -2
  25. package/dist_ts/classes.proxycontrol.js +6 -1
  26. package/dist_ts/classes.proxydaemon.d.ts +2 -2
  27. package/dist_ts/classes.proxydaemon.js +1 -1
  28. package/dist_ts/classes.proxystore.d.ts +2 -11
  29. package/dist_ts/classes.proxystore.js +3 -25
  30. package/dist_ts/classes.tpmsecretcodec.d.ts +13 -0
  31. package/dist_ts/classes.tpmsecretcodec.js +28 -0
  32. package/dist_ts/classes.trustedproxysecrets.d.ts +91 -0
  33. package/dist_ts/classes.trustedproxysecrets.js +338 -0
  34. package/dist_ts/classes.upgradecoordinator.d.ts +14 -1
  35. package/dist_ts/classes.upgradecoordinator.js +21 -3
  36. package/dist_ts/classes.upgradetransaction.d.ts +32 -0
  37. package/dist_ts/classes.upgradetransaction.js +101 -4
  38. package/dist_ts/functions.controlleradmission.d.ts +67 -0
  39. package/dist_ts/functions.controlleradmission.js +127 -0
  40. package/dist_ts/functions.remotecli.d.ts +27 -0
  41. package/dist_ts/functions.remotecli.js +236 -0
  42. package/dist_ts/functions.retiredenvironment.d.ts +11 -2
  43. package/dist_ts/functions.retiredenvironment.js +22 -5
  44. package/dist_ts/index.d.ts +1 -0
  45. package/dist_ts/index.js +2 -1
  46. package/dist_ts/interfaces.auth.d.ts +29 -4
  47. package/dist_ts/interfaces.auth.js +5 -1
  48. package/dist_ts/interfaces.config.d.ts +14 -0
  49. package/dist_ts/interfaces.config.js +9 -2
  50. package/dist_ts/interfaces.lifecycle.d.ts +3 -0
  51. package/dist_ts_authswitch/classes.authoritydaemon.js +6 -1
  52. package/dist_ts_interfaces/interfaces.d.ts +2 -2
  53. package/dist_ts_interfaces/interfaces.js +1 -1
  54. package/dist_ts_interfaces/management.d.ts +2 -2
  55. package/dist_ts_interfaces/management.js +2 -2
  56. package/dist_ts_interfaces/requests.d.ts +1 -2
  57. package/dist_ts_interfaces/requests.js +1 -1
  58. package/dist_ts_interfaces/requests.upgrade.d.ts +0 -12
  59. package/package.json +12 -11
  60. package/readme.md +84 -24
  61. package/ts/00_commitinfo_data.ts +1 -1
  62. package/ts/aglapi/aglapisurface.document.ts +3 -3
  63. package/ts/classes.authmodels.ts +68 -25
  64. package/ts/classes.authstore.ts +151 -24
  65. package/ts/classes.cli.ts +38 -61
  66. package/ts/classes.config.ts +70 -21
  67. package/ts/classes.controller.ts +50 -163
  68. package/ts/classes.controllermanagement.ts +123 -49
  69. package/ts/classes.controllerservice.ts +3 -56
  70. package/ts/classes.mcpcontrollerhost.ts +10 -5
  71. package/ts/classes.processinspection.ts +84 -3
  72. package/ts/classes.proxycontrol.ts +2 -0
  73. package/ts/classes.proxydaemon.ts +3 -2
  74. package/ts/classes.proxystore.ts +4 -25
  75. package/ts/classes.tpmsecretcodec.ts +26 -0
  76. package/ts/classes.trustedproxysecrets.ts +317 -0
  77. package/ts/classes.upgradecoordinator.ts +33 -3
  78. package/ts/classes.upgradetransaction.ts +130 -1
  79. package/ts/functions.controlleradmission.ts +168 -0
  80. package/ts/functions.remotecli.ts +264 -0
  81. package/ts/functions.retiredenvironment.ts +25 -3
  82. package/ts/index.ts +1 -0
  83. package/ts/interfaces.auth.ts +36 -3
  84. package/ts/interfaces.config.ts +15 -0
  85. package/ts/interfaces.lifecycle.ts +3 -0
  86. package/ts_authswitch/classes.authoritydaemon.ts +2 -0
  87. package/ts_interfaces/interfaces.ts +2 -2
  88. package/ts_interfaces/management.ts +2 -2
  89. package/ts_interfaces/requests.ts +0 -10
  90. package/ts_interfaces/requests.upgrade.ts +0 -16
  91. package/ts_web/00_commitinfo_data.ts +1 -1
@@ -314,7 +314,6 @@ import {
314
314
  type IReq_ControllerSetupFinish,
315
315
  type IReq_ControllerStatus,
316
316
  type IReq_ControllerUpgradeLaunch,
317
- type IReq_ControllerUpgradePrepare,
318
317
  type IReq_ControllerUpgradePrepareBegin,
319
318
  type IReq_ControllerUpgradeFinalize,
320
319
  type IReq_ControllerFailureDetailGet,
@@ -347,11 +346,12 @@ import {
347
346
  parseFlexAuthorityConnectionId,
348
347
  } from '../ts_interfaces/index.js';
349
348
  import {
350
- readTrustedProxySecret,
351
349
  resolveInitialRuntimeConfig,
352
350
  resolveStoredRuntimeConfig,
353
351
  } from './classes.config.js';
354
- import { assertControllerServiceTlsMode, controllerServiceDetachedRemedy } from './classes.controllerservice.js';
352
+ import { controllerListenerOptions } from './functions.controlleradmission.js';
353
+ import { ControllerTrustedProxySecrets } from './classes.trustedproxysecrets.js';
354
+ import { TpmSecretCodec } from './classes.tpmsecretcodec.js';
355
355
  import { resolveAGLHomePaths } from './classes.aglhome.js';
356
356
  import { selectControllerBrowserPaint } from './functions.browserpaintartifact.js';
357
357
  import { ControllerBrowserViewerAssets } from './functions.browserpaintassets.js';
@@ -795,7 +795,6 @@ const currentRuntimeName = currentCliName === upgradePackageTransitionTarget.cli
795
795
  const authenticatedPeerStateKey = '__opencodeControllerAuthenticatedCredentialId';
796
796
  const terminalPeerLifecycleStateKey = '__harnessControllerTerminalPeerLifecycle';
797
797
  const operationAbortControllerPeerStateKey = '__harnessControllerOperationAbortController';
798
- const trustedProxySecretHeader = 'x-harness-controller-proxy-secret';
799
798
  // Generous for a local single-user deployment: transcripts and inline
800
799
  // attachments are legitimately multi-megabyte, and an undersized limit
801
800
  // fail-closes the connection (and with it the per-connection auth).
@@ -2846,17 +2845,9 @@ const asTypedResponseError = (
2846
2845
  const hashResumeToken = (tokenArg: string): string =>
2847
2846
  plugins.crypto.createHash('sha256').update(tokenArg, 'utf8').digest('base64url');
2848
2847
 
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
2848
  const assertControllerUpgradePreparationRequest: (
2858
2849
  requestArg: unknown,
2859
- ) => asserts requestArg is IReq_ControllerUpgradePrepare['request'] = (requestArg) => {
2850
+ ) => asserts requestArg is IReq_ControllerUpgradePrepareBegin['request'] = (requestArg) => {
2860
2851
  if (
2861
2852
  !requestArg
2862
2853
  || typeof requestArg !== 'object'
@@ -2873,24 +2864,6 @@ const assertControllerUpgradePreparationRequest: (
2873
2864
  );
2874
2865
  };
2875
2866
 
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
2867
  interface IControllerHarnessSessionEnumeration {
2895
2868
  openCode: PromiseSettledResult<IControllerSession[]>;
2896
2869
  flex: PromiseSettledResult<IControllerSession[]>;
@@ -3371,6 +3344,8 @@ export class OpenCodeController {
3371
3344
  return this.ticketStore.applyFleetEvent(eventArg, signalArg, originArg);
3372
3345
  }
3373
3346
  private passkeyManager?: PasskeyManager;
3347
+ /** TLS-proxy mode only: the secret admission accepts from the reverse proxy, and its rotation. */
3348
+ private trustedProxySecrets?: ControllerTrustedProxySecrets;
3374
3349
  private openCodeSupervisor?: OpenCodeSupervisor;
3375
3350
  private openCodeClient?: OpenCodeClientAdapter;
3376
3351
  private flexSupervisor?: FlexSupervisor;
@@ -4150,6 +4125,17 @@ export class OpenCodeController {
4150
4125
  }
4151
4126
  }
4152
4127
 
4128
+ /**
4129
+ * The trusted-proxy secret of a running controller in TLS-proxy mode, for its gateway client: the secret its route
4130
+ * carries (`routeSecret`), `rotate` and `confirm` once the route carries the new one. Refused in local mode.
4131
+ */
4132
+ public requireTrustedProxySecrets(): ControllerTrustedProxySecrets {
4133
+ if (!this.trustedProxySecrets) {
4134
+ throw new Error('This controller runs no trusted reverse proxy: it is in local mode or not running.');
4135
+ }
4136
+ return this.trustedProxySecrets;
4137
+ }
4138
+
4153
4139
  public getStatus(): IControllerStatus {
4154
4140
  const openCodeStatus = this.openCodeSupervisor?.getStatus() ?? {
4155
4141
  state: 'stopped' as const,
@@ -10064,9 +10050,6 @@ export class OpenCodeController {
10064
10050
  ? await resolveStoredRuntimeConfig(storedConfig, this.options.runtimeOverrides)
10065
10051
  : await resolveInitialRuntimeConfig(this.options.runtimeOverrides);
10066
10052
  this.assertStartActive();
10067
- if (this.options.serviceUnit !== undefined) {
10068
- assertControllerServiceTlsMode({ stored: runtimeConfig.tlsMode, remedy: controllerServiceDetachedRemedy });
10069
- }
10070
10053
  const authDocument = await authStore.resolveOrCreateRuntimeConfig(runtimeConfig);
10071
10054
  await authStore.migrateTicketOwnerPrincipal();
10072
10055
  this.assertStartActive();
@@ -10113,7 +10096,15 @@ export class OpenCodeController {
10113
10096
  this.assertStartActive();
10114
10097
 
10115
10098
  const router = this.createRouter(runtimeConfig.publicOrigin);
10116
- const trustedProxySecret = readTrustedProxySecret(runtimeConfig.tlsMode);
10099
+ if (runtimeConfig.tlsMode === 'proxy') {
10100
+ this.trustedProxySecrets = await ControllerTrustedProxySecrets.open({
10101
+ controllerId: authDocument.id,
10102
+ issuerId: issuerIdentity.issuerId,
10103
+ codec: this.options.trustedProxySecretCodec ?? new TpmSecretCodec(),
10104
+ });
10105
+ this.assertStartActive();
10106
+ }
10107
+ const trustedProxySecrets = this.trustedProxySecrets;
10117
10108
  const publicHostname = new URL(runtimeConfig.publicOrigin).hostname;
10118
10109
  const hostnames = [...new Set([publicHostname, 'localhost', '127.0.0.1'])];
10119
10110
  const serveDirectory = plugins.path.resolve(
@@ -10137,11 +10128,11 @@ export class OpenCodeController {
10137
10128
  this.assertStartActive();
10138
10129
  const typedServer = new plugins.typedserver.TypedServer({
10139
10130
  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',
10131
+ // One listener: loopback unless a gateway reaches this controller from another address, and then every
10132
+ // interface, where admission refuses every address off loopback that is not a gateway source sending the
10133
+ // trusted-proxy secret, on every surface alike. The host firewall must still let only the gateways reach the
10134
+ // port (readme, "Remote Browser Access").
10135
+ ...controllerListenerOptions(runtimeConfig, (valueArg) => trustedProxySecrets?.accepts(valueArg) === true),
10145
10136
  cors: false,
10146
10137
  websocketMaxPayloadBytes: websocketPayloadLimit,
10147
10138
  connectionTimeout: 120_000,
@@ -10180,12 +10171,6 @@ export class OpenCodeController {
10180
10171
  headers: { Allow: 'GET, HEAD' },
10181
10172
  });
10182
10173
  },
10183
- websocketAdmission: (contextArg) => isControllerWebSocketRequestAllowed(
10184
- contextArg.headers,
10185
- runtimeConfig.publicOrigin,
10186
- runtimeConfig.tlsMode,
10187
- trustedProxySecret,
10188
- ),
10189
10174
  securityHeaders,
10190
10175
  },
10191
10176
  ],
@@ -13444,6 +13429,8 @@ export class OpenCodeController {
13444
13429
  await authStore.close();
13445
13430
  if (this.authStore === authStore) {
13446
13431
  this.authStore = undefined;
13432
+ this.trustedProxySecrets?.close();
13433
+ this.trustedProxySecrets = undefined;
13447
13434
  this.passkeyManager = undefined;
13448
13435
  this.controllerId = undefined;
13449
13436
  this.openCodeRuntimeDirectory = undefined;
@@ -13561,7 +13548,6 @@ export class OpenCodeController {
13561
13548
  });
13562
13549
 
13563
13550
  this.registerStatusHandlers(publicRouter);
13564
- this.registerUpgradeHandlers(publicRouter);
13565
13551
 
13566
13552
  this.registerAuthHandlers(browserAuthRouter, publicOriginArg);
13567
13553
  this.registerSignInHandlers(protectedRouter);
@@ -13601,22 +13587,12 @@ export class OpenCodeController {
13601
13587
  publicRouterArg.addTypedHandler(this.createStatusHandler());
13602
13588
  }
13603
13589
 
13604
- /**
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.
13607
- */
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());
13613
- }
13614
-
13615
13590
  /**
13616
13591
  * 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.
13592
+ * methods the CLI and an upgrade worker of this or another release call, which only this endpoint serves (the
13593
+ * controller socket keeps the status read for the browser). The status handler is the one the socket's public scope
13594
+ * uses, and each upgrade handler authorises itself against the upgrade token and one-time grant it is handed; the
13595
+ * endpoint's admission grants a request only its own peer. No other method is reachable through it.
13620
13596
  */
13621
13597
  private createManagementRouter(): plugins.typedrequest.TypedRouter {
13622
13598
  const router = new plugins.typedrequest.TypedRouter();
@@ -13727,52 +13703,6 @@ export class OpenCodeController {
13727
13703
  );
13728
13704
  }
13729
13705
 
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
13706
  private createUpgradePrepareBeginHandler(): plugins.typedrequest.TypedHandler<IReq_ControllerUpgradePrepareBegin> {
13777
13707
  return new plugins.typedrequest.TypedHandler<IReq_ControllerUpgradePrepareBegin>(
13778
13708
  'controller.upgrade.prepare.begin',
@@ -35325,7 +35255,6 @@ export class OpenCodeController {
35325
35255
 
35326
35256
  private async persistUpgradePreparation(
35327
35257
  contextArg: IUpgradePreparationContext,
35328
- asynchronousArg: boolean,
35329
35258
  ): Promise<void> {
35330
35259
  await contextArg.coordinator.mutateTransaction(contextArg.token, (current) => {
35331
35260
  if (current.version === upgradePackageTransitionTransactionVersion) {
@@ -35341,12 +35270,8 @@ export class OpenCodeController {
35341
35270
  sessionId: { ...session.sessionId },
35342
35271
  stopState: 'pending' as const,
35343
35272
  })),
35344
- ...(asynchronousArg
35345
- ? {
35346
- preparationAcceptedAt: contextArg.acceptedAt,
35347
- preparationDeadlineAt: contextArg.deadline,
35348
- }
35349
- : {}),
35273
+ preparationAcceptedAt: contextArg.acceptedAt,
35274
+ preparationDeadlineAt: contextArg.deadline,
35350
35275
  };
35351
35276
  }
35352
35277
  return {
@@ -35359,12 +35284,8 @@ export class OpenCodeController {
35359
35284
  sessionId: { ...session.sessionId },
35360
35285
  stopState: 'pending' as const,
35361
35286
  })),
35362
- ...(asynchronousArg
35363
- ? {
35364
- preparationAcceptedAt: contextArg.acceptedAt,
35365
- preparationDeadlineAt: contextArg.deadline,
35366
- }
35367
- : {}),
35287
+ preparationAcceptedAt: contextArg.acceptedAt,
35288
+ preparationDeadlineAt: contextArg.deadline,
35368
35289
  };
35369
35290
  });
35370
35291
  }
@@ -35388,7 +35309,7 @@ export class OpenCodeController {
35388
35309
  */
35389
35310
  private async completeUpgradePreparation(
35390
35311
  contextArg: IUpgradePreparationContext,
35391
- ): Promise<IReq_ControllerUpgradePrepare['response']> {
35312
+ ): Promise<void> {
35392
35313
  const {
35393
35314
  barrier,
35394
35315
  coordinator,
@@ -35497,7 +35418,6 @@ export class OpenCodeController {
35497
35418
  if (Date.now() > deadline) {
35498
35419
  throw new Error('The upgrade preparation deadline expired before completion.');
35499
35420
  }
35500
- return { prepared: true, sessionCount: barrier.sessions.length };
35501
35421
  }
35502
35422
 
35503
35423
  private async updateUpgradeBlockers(
@@ -35538,7 +35458,6 @@ export class OpenCodeController {
35538
35458
  private async compensateUpgradePreparationFailure(
35539
35459
  contextArg: IUpgradePreparationContext,
35540
35460
  errorArg: unknown,
35541
- finishTransactionArg: boolean,
35542
35461
  ): Promise<void> {
35543
35462
  let errorMessage = errorArg instanceof Error ? errorArg.message : String(errorArg);
35544
35463
  try {
@@ -35551,44 +35470,12 @@ export class OpenCodeController {
35551
35470
  } finally {
35552
35471
  this.clearUpgradePreparationAbortController(contextArg);
35553
35472
  }
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;
35473
+ await contextArg.coordinator.finishTransaction(
35474
+ contextArg.token,
35475
+ false,
35476
+ 'Upgrade preparation failed.',
35477
+ errorMessage,
35478
+ ).catch(() => undefined);
35592
35479
  }
35593
35480
 
35594
35481
  private async beginUpgradePreparation(
@@ -35644,13 +35531,13 @@ export class OpenCodeController {
35644
35531
  this.clearUpgradePreparationAbortController(context);
35645
35532
  return;
35646
35533
  }
35647
- await this.compensateUpgradePreparationFailure(context, errorArg, true);
35534
+ await this.compensateUpgradePreparationFailure(context, errorArg);
35648
35535
  }
35649
35536
  })();
35650
35537
  const trackedBackground = this.trackOperationPromise(background);
35651
35538
  this.upgradePreparationTask = trackedBackground;
35652
35539
  try {
35653
- await this.persistUpgradePreparation(context, true);
35540
+ await this.persistUpgradePreparation(context);
35654
35541
  releaseGate();
35655
35542
  this.pushUpgradePreparationEvent();
35656
35543
  return { accepted: true };
@@ -16,6 +16,7 @@ import {
16
16
  } from '../ts_interfaces/index.js';
17
17
  import {
18
18
  controllerProcessIdentityIsLive,
19
+ installedControllerHoldsPort,
19
20
  signalVerifiedControllerProcess,
20
21
  } from './classes.processinspection.js';
21
22
  import { AglControllerService } from './classes.controllerservice.js';
@@ -38,8 +39,13 @@ export const isControllerManagementProtocolVersion = (valueArg: unknown): valueA
38
39
  typeof valueArg === 'number' && Number.isSafeInteger(valueArg) && valueArg >= 1
39
40
  );
40
41
 
41
- /** A controller a management call is addressed to, by what it declares about its management endpoint. */
42
+ /**
43
+ * A controller a management call is addressed to: what it declares about its management endpoint, which decides
44
+ * whether this build manages it at all, and its package and version, which only a refusal names.
45
+ */
42
46
  export interface IControllerManagementTarget {
47
+ packageName: string;
48
+ packageVersion: string;
43
49
  /**
44
50
  * The management protocol the controller declares (`controllerManagementProtocolVersion`): the status's own
45
51
  * `managementProtocolVersion` once the controller runs, or what the installed package that runs it declares in
@@ -48,6 +54,51 @@ export interface IControllerManagementTarget {
48
54
  managementProtocolVersion?: number;
49
55
  }
50
56
 
57
+ /**
58
+ * The oldest management protocol this build manages a controller through. It speaks only the loopback management
59
+ * endpoint: a controller that declares none (AGL 41.0.x or older, reachable only over its TypedSocket 8 socket, which
60
+ * this build cannot speak) is refused by name, never reached some other way.
61
+ */
62
+ export const controllerManagementProtocolFloor = 1;
63
+
64
+ /** What a refusal of an older controller tells its operator, in the CLI and in the upgrade log. */
65
+ export const controllerManagementUpgradeOrder = 'AGL 41.0.x or older must upgrade to 41.1.x before 42.';
66
+
67
+ /** The first release whose controller has the loopback management endpoint. */
68
+ export const controllerManagementEndpointRelease = '41.1.0';
69
+
70
+ /** Whether a declaration is one this build manages a controller through. */
71
+ export const isManagedControllerManagementProtocol = (valueArg: unknown): boolean => (
72
+ isControllerManagementProtocolVersion(valueArg) && valueArg >= controllerManagementProtocolFloor
73
+ );
74
+
75
+ /**
76
+ * The controller a refusal names: a release by package and version, when its declaration or an upgrade transaction
77
+ * names one, or only the port, when nothing does.
78
+ */
79
+ export type TUnmanagedController =
80
+ | Pick<IControllerManagementTarget, 'packageName' | 'packageVersion'>
81
+ | { port: number };
82
+
83
+ /** The refusal of a controller this build cannot manage; its version appears only here. */
84
+ export const unmanagedControllerError = (controllerArg: TUnmanagedController): ControllerManagementError => (
85
+ new ControllerManagementError(
86
+ 'port' in controllerArg
87
+ ? `The controller on port ${controllerArg.port} has no loopback management endpoint: it is a controller older `
88
+ + `than ${controllerManagementEndpointRelease}, which this release does not manage. ${controllerManagementUpgradeOrder}`
89
+ : `The controller of ${controllerArg.packageName}@${controllerArg.packageVersion} predates the loopback management `
90
+ + `endpoint, through which alone this release manages a controller. ${controllerManagementUpgradeOrder}`,
91
+ 'management_protocol_unsupported',
92
+ )
93
+ );
94
+
95
+ /** Refuses, by name, a controller whose declaration this build cannot manage it through. */
96
+ export const assertManagedController = (targetArg: IControllerManagementTarget): void => {
97
+ if (!isManagedControllerManagementProtocol(targetArg.managementProtocolVersion)) {
98
+ throw unmanagedControllerError(targetArg);
99
+ }
100
+ };
101
+
51
102
  /**
52
103
  * A status read: the identity the status must report, and the declaration that decides how it is read, which comes
53
104
  * from the package expected to run the controller, since there is no status yet. Every caller states it, absent
@@ -55,6 +106,13 @@ export interface IControllerManagementTarget {
55
106
  */
56
107
  export interface IControllerStatusQuery extends IControllerStatusExpectation {
57
108
  managementProtocolVersion: number | undefined;
109
+ /**
110
+ * Where `packageName` and `packageVersion` come from: an upgrade transaction (`transaction`), which names the
111
+ * release it left on the port, or only the caller's own expectation (`caller`, the CLI's own build). A controller
112
+ * without the management endpoint is refused by the transaction's release, or else as one older than
113
+ * `controllerManagementEndpointRelease`, never by a version nobody read from it.
114
+ */
115
+ identity: 'transaction' | 'caller';
58
116
  }
59
117
 
60
118
  const harnessStates = ['starting', 'ready', 'stopping', 'stopped', 'failed'] as const;
@@ -224,19 +282,6 @@ export const assertControllerStatus = (
224
282
  return readableStatus as IControllerStatus;
225
283
  };
226
284
 
227
- /**
228
- * How this build reaches a controller's management methods, decided by the controller's declaration alone: over its
229
- * loopback management endpoint when it declares a management protocol, which every later release keeps whatever
230
- * transport its browser speaks, and over its controller socket when it declares none (a release older than the
231
- * endpoint, such as a source an upgrade recovery restores), which serves them in every release up to this one.
232
- * There is no second attempt over the other transport.
233
- */
234
- export const controllerManagementTransport = (
235
- targetArg: IControllerManagementTarget,
236
- ): 'http' | 'socket' => (
237
- isControllerManagementProtocolVersion(targetArg.managementProtocolVersion) ? 'http' : 'socket'
238
- );
239
-
240
285
  /** A management request the controller answered with an error, or whose answer this build cannot read. */
241
286
  export class ControllerManagementError extends Error {
242
287
  constructor(messageArg: string, public readonly code?: string) {
@@ -281,6 +326,12 @@ const readControllerManagementAnswer = (
281
326
  throw new ControllerManagementError(text, code);
282
327
  };
283
328
 
329
+ /**
330
+ * The `Allow` header of the 405 with which the controller of every release before the loopback management endpoint
331
+ * refuses a `POST` (its `requestAdmission` admits only GET and HEAD; TypedServer 14.2.1 sends the header as given).
332
+ */
333
+ const preEndpointControllerAllow = 'GET, HEAD';
334
+
284
335
  /** Sends one envelope to the management endpoint on 127.0.0.1 and returns the answer's bytes. */
285
336
  const postControllerManagementEnvelope = (
286
337
  portArg: number,
@@ -305,6 +356,16 @@ const postControllerManagementEnvelope = (
305
356
  }, (responseArg) => {
306
357
  const statusCode = responseArg.statusCode ?? 0;
307
358
  const contentType = responseArg.headers['content-type'];
359
+ if (statusCode === 405 && responseArg.headers.allow === preEndpointControllerAllow) {
360
+ // The endpoint takes every POST it admits, so this is a listener without it that answers as the controller of a
361
+ // release older than the endpoint does; whether it is one, `requestManagedController` confirms.
362
+ responseArg.resume();
363
+ reject(new ControllerManagementError(
364
+ 'The listener answered as a controller without the loopback management endpoint.',
365
+ 'management_endpoint_missing',
366
+ ));
367
+ return;
368
+ }
308
369
  if (statusCode !== 200) {
309
370
  responseArg.resume();
310
371
  reject(new ControllerManagementError(
@@ -384,41 +445,38 @@ export const requestControllerManagement = async <T extends TControllerManagemen
384
445
  return readControllerManagementAnswer(answer, identity);
385
446
  };
386
447
 
387
- /** Fires one management request over the controller socket, for a controller that declares no management protocol. */
388
- const requestControllerManagementOverSocket = async <T extends TControllerManagementTypedRequest>(
448
+ /**
449
+ * Sends one management request to a controller that declares the endpoint. One that turns out to have none is
450
+ * refused as `refusalArg` names it: by default the target, whose identity is what it declared or reported.
451
+ *
452
+ * It has none only when both signs of an older controller hold: the listener refused the `POST` with that
453
+ * controller's 405 (`Allow: GET, HEAD`), and the process holding the port's listening socket runs an installed AGL
454
+ * package's controller for this port (`installedControllerHoldsPort`). Any other listener, a 405 of its own included,
455
+ * is a refusal of HTTP (`http_refused`), which callers treat as a busy port, never as an AGL controller.
456
+ */
457
+ const requestManagedController = async <T extends TControllerManagementTypedRequest>(
389
458
  portArg: number,
459
+ controllerArg: IControllerManagementTarget,
390
460
  methodArg: T['method'],
391
461
  requestArg: T['request'],
392
462
  optionsArg: { timeoutMs: number },
463
+ refusalArg: TUnmanagedController = controllerArg,
393
464
  ): Promise<unknown> => {
394
- const signal = AbortSignal.timeout(optionsArg.timeoutMs);
395
- let socket: plugins.typedsocket.TypedSocket | undefined;
465
+ assertManagedController(controllerArg);
396
466
  try {
397
- socket = await plugins.typedsocket.TypedSocket.createClient(
398
- new plugins.typedrequest.TypedRouter(),
399
- `http://127.0.0.1:${portArg}`,
400
- { autoReconnect: false, maxRetries: 0, abortSignal: signal },
401
- );
402
- return await socket.createTypedRequest<T>(
403
- methodArg,
404
- undefined,
405
- { timeoutMs: optionsArg.timeoutMs, abortSignal: signal },
406
- ).fire(requestArg);
407
- } finally {
408
- await socket?.stop();
467
+ return await requestControllerManagement<T>(portArg, methodArg, requestArg, optionsArg);
468
+ } catch (errorArg) {
469
+ if (errorArg instanceof ControllerManagementError && errorArg.code === 'management_endpoint_missing') {
470
+ if (await installedControllerHoldsPort(portArg)) throw unmanagedControllerError(refusalArg);
471
+ throw new ControllerManagementError(
472
+ 'The controller refused the management request with HTTP 405.',
473
+ 'http_refused',
474
+ );
475
+ }
476
+ throw errorArg;
409
477
  }
410
478
  };
411
479
 
412
- const requestManagedController = <T extends TControllerManagementTypedRequest>(
413
- portArg: number,
414
- controllerArg: IControllerManagementTarget,
415
- methodArg: T['method'],
416
- requestArg: T['request'],
417
- optionsArg: { timeoutMs: number },
418
- ): Promise<unknown> => controllerManagementTransport(controllerArg) === 'http'
419
- ? requestControllerManagement<T>(portArg, methodArg, requestArg, optionsArg)
420
- : requestControllerManagementOverSocket<T>(portArg, methodArg, requestArg, optionsArg);
421
-
422
480
  export const requestControllerUpgradePrepareBegin = async (
423
481
  portArg: number,
424
482
  controllerArg: IControllerManagementTarget,
@@ -474,24 +532,40 @@ export const queryControllerStatus = async (
474
532
  portArg: number,
475
533
  queryArg: IControllerStatusQuery,
476
534
  timeoutMsArg = 2_500,
477
- ): Promise<IControllerStatus> => assertControllerStatus(
478
- await requestManagedController<IReq_ControllerStatus>(
479
- portArg,
535
+ ): Promise<IControllerStatus> => {
536
+ const status = assertControllerStatus(
537
+ await requestManagedController<IReq_ControllerStatus>(
538
+ portArg,
539
+ queryArg,
540
+ 'controller.status',
541
+ {},
542
+ { timeoutMs: timeoutMsArg },
543
+ queryArg.identity === 'transaction' ? queryArg : { port: portArg },
544
+ ),
480
545
  queryArg,
481
- 'controller.status',
482
- {},
483
- { timeoutMs: timeoutMsArg },
484
- ),
485
- queryArg,
546
+ );
547
+ // From here on the controller's own report is the gate, whatever its package declared before it ran.
548
+ assertManagedController(status);
549
+ return status;
550
+ };
551
+
552
+ /** Whether `errorArg` refuses a controller this build cannot manage, which is there all the same. */
553
+ export const isUnmanagedControllerError = (errorArg: unknown): errorArg is ControllerManagementError => (
554
+ errorArg instanceof ControllerManagementError && errorArg.code === 'management_protocol_unsupported'
486
555
  );
487
556
 
557
+ /**
558
+ * Reads the status of a controller if one this build manages answers; `undefined` when none answers or its answer is
559
+ * not one. A controller that answers but that this build cannot manage is refused, never reported as absent.
560
+ */
488
561
  export const tryQueryControllerStatus = async (
489
562
  portArg: number,
490
563
  queryArg: IControllerStatusQuery,
491
564
  ): Promise<IControllerStatus | undefined> => {
492
565
  try {
493
566
  return await queryControllerStatus(portArg, queryArg);
494
- } catch {
567
+ } catch (errorArg) {
568
+ if (isUnmanagedControllerError(errorArg)) throw errorArg;
495
569
  return undefined;
496
570
  }
497
571
  };