agl 43.7.0 → 43.9.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 (143) hide show
  1. package/changelog.md +33 -0
  2. package/dist_serve/bundle.js +871 -858
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/aglapisurface.document.js +824 -6
  6. package/dist_ts/aglapi/interfaces.d.ts +43 -0
  7. package/dist_ts/aglapi/interfaces.js +11 -1
  8. package/dist_ts/classes.apnsclient.d.ts +97 -0
  9. package/dist_ts/classes.apnsclient.js +363 -0
  10. package/dist_ts/classes.authmodels.js +19 -6
  11. package/dist_ts/classes.authstore.js +15 -2
  12. package/dist_ts/classes.cli.js +8 -1
  13. package/dist_ts/classes.controller.d.ts +30 -3
  14. package/dist_ts/classes.controller.js +250 -9
  15. package/dist_ts/classes.controllerdevices.d.ts +35 -7
  16. package/dist_ts/classes.controllerdevices.js +86 -13
  17. package/dist_ts/classes.controllerpush.d.ts +111 -0
  18. package/dist_ts/classes.controllerpush.js +299 -0
  19. package/dist_ts/classes.fcmclient.d.ts +78 -0
  20. package/dist_ts/classes.fcmclient.js +278 -0
  21. package/dist_ts/classes.inbox.d.ts +10 -2
  22. package/dist_ts/classes.inbox.js +9 -2
  23. package/dist_ts/classes.mcpclient.d.ts +5 -0
  24. package/dist_ts/classes.mcpclient.js +20 -8
  25. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
  26. package/dist_ts/classes.mcpcontrollerhost.js +21 -2
  27. package/dist_ts/classes.mcptools.d.ts +1 -1
  28. package/dist_ts/classes.mcptools.js +2 -1
  29. package/dist_ts/classes.mcpvalidation.js +4 -1
  30. package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
  31. package/dist_ts/classes.mcpworkercaller.js +26 -4
  32. package/dist_ts/classes.pushdelivery.d.ts +115 -0
  33. package/dist_ts/classes.pushdelivery.js +311 -0
  34. package/dist_ts/classes.pushhandover.d.ts +46 -0
  35. package/dist_ts/classes.pushhandover.js +131 -0
  36. package/dist_ts/classes.pushregistrations.d.ts +96 -0
  37. package/dist_ts/classes.pushregistrations.js +263 -0
  38. package/dist_ts/classes.pushsettings.d.ts +125 -0
  39. package/dist_ts/classes.pushsettings.js +377 -0
  40. package/dist_ts/classes.ticketstore.d.ts +3 -3
  41. package/dist_ts/classes.ticketstore.js +23 -4
  42. package/dist_ts/classes.workercallers.d.ts +73 -2
  43. package/dist_ts/classes.workercallers.js +354 -43
  44. package/dist_ts/driver/classes.directreports.d.ts +5 -0
  45. package/dist_ts/driver/classes.directreports.js +3 -2
  46. package/dist_ts/fleet/classes.workerlaunches.d.ts +6 -4
  47. package/dist_ts/fleet/classes.workerlaunches.js +10 -9
  48. package/dist_ts/fleet/classes.workers.d.ts +12 -2
  49. package/dist_ts/fleet/classes.workers.js +82 -2
  50. package/dist_ts/functions.deviceapi.d.ts +23 -3
  51. package/dist_ts/functions.deviceapi.js +43 -3
  52. package/dist_ts/functions.mcptickettools.d.ts +60 -0
  53. package/dist_ts/functions.mcptickettools.js +4 -3
  54. package/dist_ts/functions.pushcli.d.ts +43 -0
  55. package/dist_ts/functions.pushcli.js +201 -0
  56. package/dist_ts/functions.pushcredentials.d.ts +53 -0
  57. package/dist_ts/functions.pushcredentials.js +111 -0
  58. package/dist_ts/functions.pushwire.d.ts +8 -0
  59. package/dist_ts/functions.pushwire.js +83 -0
  60. package/dist_ts/functions.remotecli.d.ts +2 -2
  61. package/dist_ts/functions.remotecli.js +4 -4
  62. package/dist_ts/functions.ticketcli.d.ts +4 -2
  63. package/dist_ts/functions.ticketcli.js +70 -4
  64. package/dist_ts/functions.ticketlisting.d.ts +38 -0
  65. package/dist_ts/functions.ticketlisting.js +211 -0
  66. package/dist_ts/functions.ticketvalidation.d.ts +62 -0
  67. package/dist_ts/functions.ticketvalidation.js +41 -3
  68. package/dist_ts/functions.workercallervalidation.js +3 -2
  69. package/dist_ts/functions.workerprocessproof.d.ts +12 -0
  70. package/dist_ts/functions.workerprocessproof.js +32 -1
  71. package/dist_ts/interfaces.auth.d.ts +27 -3
  72. package/dist_ts/interfaces.auth.js +9 -1
  73. package/dist_ts/interfaces.lifecycle.d.ts +7 -1
  74. package/dist_ts/interfaces.push.d.ts +69 -0
  75. package/dist_ts/interfaces.push.js +25 -0
  76. package/dist_ts/plugins.d.ts +3 -1
  77. package/dist_ts/plugins.js +4 -2
  78. package/dist_ts_interfaces/devices.d.ts +178 -2
  79. package/dist_ts_interfaces/devices.js +24 -2
  80. package/dist_ts_interfaces/index.d.ts +1 -0
  81. package/dist_ts_interfaces/index.js +2 -1
  82. package/dist_ts_interfaces/mcprequests.d.ts +3 -2
  83. package/dist_ts_interfaces/mcprequests.js +3 -1
  84. package/dist_ts_interfaces/push.d.ts +166 -0
  85. package/dist_ts_interfaces/push.js +24 -0
  86. package/dist_ts_interfaces/requests.tickets.d.ts +31 -3
  87. package/dist_ts_interfaces/requests.tickets.js +2 -2
  88. package/dist_ts_interfaces/tickets.d.ts +174 -2
  89. package/dist_ts_interfaces/tickets.js +20 -2
  90. package/dist_ts_interfaces/workercallers.d.ts +43 -3
  91. package/package.json +2 -2
  92. package/readme.md +95 -14
  93. package/ts/00_commitinfo_data.ts +1 -1
  94. package/ts/aglapi/aglapisurface.document.ts +823 -5
  95. package/ts/aglapi/interfaces.ts +10 -0
  96. package/ts/classes.apnsclient.ts +389 -0
  97. package/ts/classes.authmodels.ts +21 -5
  98. package/ts/classes.authstore.ts +14 -1
  99. package/ts/classes.cli.ts +7 -0
  100. package/ts/classes.controller.ts +273 -7
  101. package/ts/classes.controllerdevices.ts +94 -12
  102. package/ts/classes.controllerpush.ts +351 -0
  103. package/ts/classes.fcmclient.ts +292 -0
  104. package/ts/classes.inbox.ts +13 -2
  105. package/ts/classes.mcpclient.ts +22 -7
  106. package/ts/classes.mcpcontrollerhost.ts +22 -1
  107. package/ts/classes.mcptools.ts +1 -0
  108. package/ts/classes.mcpvalidation.ts +2 -0
  109. package/ts/classes.mcpworkercaller.ts +24 -2
  110. package/ts/classes.pushdelivery.ts +378 -0
  111. package/ts/classes.pushhandover.ts +98 -0
  112. package/ts/classes.pushregistrations.ts +244 -0
  113. package/ts/classes.pushsettings.ts +428 -0
  114. package/ts/classes.ticketstore.ts +21 -3
  115. package/ts/classes.workercallers.ts +329 -37
  116. package/ts/driver/classes.directreports.ts +7 -1
  117. package/ts/fleet/classes.workerlaunches.ts +9 -7
  118. package/ts/fleet/classes.workers.ts +65 -2
  119. package/ts/functions.deviceapi.ts +54 -2
  120. package/ts/functions.mcptickettools.ts +3 -2
  121. package/ts/functions.pushcli.ts +212 -0
  122. package/ts/functions.pushcredentials.ts +129 -0
  123. package/ts/functions.pushwire.ts +106 -0
  124. package/ts/functions.remotecli.ts +3 -2
  125. package/ts/functions.ticketcli.ts +70 -5
  126. package/ts/functions.ticketlisting.ts +214 -0
  127. package/ts/functions.ticketvalidation.ts +41 -2
  128. package/ts/functions.workercallervalidation.ts +2 -1
  129. package/ts/functions.workerprocessproof.ts +34 -0
  130. package/ts/interfaces.auth.ts +26 -3
  131. package/ts/interfaces.lifecycle.ts +7 -1
  132. package/ts/interfaces.push.ts +78 -0
  133. package/ts/plugins.ts +3 -1
  134. package/ts_interfaces/devices.schema.json +327 -0
  135. package/ts_interfaces/devices.ts +206 -1
  136. package/ts_interfaces/index.ts +1 -0
  137. package/ts_interfaces/mcprequests.ts +3 -0
  138. package/ts_interfaces/push.ts +162 -0
  139. package/ts_interfaces/requests.tickets.ts +32 -2
  140. package/ts_interfaces/tickets.ts +136 -3
  141. package/ts_interfaces/workercallers.ts +34 -2
  142. package/ts_web/00_commitinfo_data.ts +1 -1
  143. package/ts_web/elements.inbox.ts +50 -9
@@ -124,6 +124,9 @@ import {
124
124
  deviceDirectReportMessageRefusal,
125
125
  deviceHostAgl,
126
126
  deviceHostDevice,
127
+ deviceHostPush,
128
+ assertDevicePushRegisterRequest,
129
+ type IDevicePushDelivery,
127
130
  readDeviceHostSections,
128
131
  assertDeviceBoardListRequest,
129
132
  assertDeviceTicketGetRequest,
@@ -420,6 +423,8 @@ import {
420
423
  type IReq_DeviceDirectReportsList,
421
424
  type IReq_DeviceDirectReportMessage,
422
425
  type IReq_DeviceHostGet,
426
+ type IReq_DevicePushRegister,
427
+ type IReq_DevicePushUnregister,
423
428
  type IReq_DeviceBoardList,
424
429
  type IReq_DeviceTicketGet,
425
430
  type IReq_DeviceTicketComment,
@@ -456,6 +461,24 @@ import {
456
461
  } from './classes.config.js';
457
462
  import { controllerListenerOptions } from './functions.controlleradmission.js';
458
463
  import { ControllerTrustedProxySecrets } from './classes.trustedproxysecrets.js';
464
+ import { ControllerPushSettings } from './classes.pushsettings.js';
465
+ import { ControllerPushDelivery } from './classes.pushdelivery.js';
466
+ import { ControllerPush } from './classes.controllerpush.js';
467
+ import { keepPushHandover, takePushHandover } from './classes.pushhandover.js';
468
+ import { pushKeySubjects, pushNotificationKey } from './classes.pushregistrations.js';
469
+ import { parseApnsCredential, parseFcmCredential, PushError } from './functions.pushcredentials.js';
470
+ import {
471
+ pushOperationOf,
472
+ type IPushChange,
473
+ type IPushOperations,
474
+ type IPushStatus,
475
+ type IPushTestResult,
476
+ type TControllerMcpPushMethod,
477
+ type TPushOperation,
478
+ } from '../ts_interfaces/push.js';
479
+ import { devicePushTestSentence, type TDevicePushPlatform } from '../ts_interfaces/devices.js';
480
+ import type { IControllerAuditPush } from './interfaces.auth.js';
481
+ import type { IConfigurationLocalCliActor } from '../ts_interfaces/configuration.js';
459
482
  import { TpmSecretCodec } from './classes.tpmsecretcodec.js';
460
483
  import { ControllerGatewayClient } from './classes.gatewayclient.js';
461
484
  import { ControllerGatewayClientStore } from './classes.gatewayclientstore.js';
@@ -3357,6 +3380,12 @@ export class OpenCodeController {
3357
3380
  private deviceEventDelivery?: ControllerEventDelivery;
3358
3381
  /** The paired devices, their pairing codes and authenticated connections; open while the controller runs. */
3359
3382
  private devices?: ControllerDevices;
3383
+ /** The host's push settings: previews and the APNs and FCM credentials (AGL-1639); open while the controller runs. */
3384
+ private pushSettings?: ControllerPushSettings;
3385
+ /** Sends notifications to the registered devices with those credentials; runs while the controller runs. */
3386
+ private pushDelivery?: ControllerPushDelivery;
3387
+ /** Turns the Inbox's deltas and the direct reports' new results into notifications for the delivery. */
3388
+ private controllerPush?: ControllerPush;
3360
3389
  private flexAutoAcceptDrainTask?: Promise<void>;
3361
3390
  /** Sweeps whose auto-accept failed, queued again when the retry timer fires. */
3362
3391
  private readonly failedFlexAutoAcceptSweeps = new Map<string, IFlexAutoAcceptSweep>();
@@ -3445,6 +3474,8 @@ export class OpenCodeController {
3445
3474
  relaunchBlocker: async ({ profile, nativeId, cwd }) =>
3446
3475
  await this.requireFleetWorkers().relaunchBlocker((await this.readFleetScope()).configuration, profile, nativeId, cwd),
3447
3476
  reportFailure: (message, error) => console.error(message, error),
3477
+ // The devices that asked for results get a notification of the newest one.
3478
+ resultRecorded: (_owner, report) => { this.controllerPush?.reportResult(report); },
3448
3479
  // The Driver view lists the reports again.
3449
3480
  changed: () => {
3450
3481
  void this.pushControllerEvent({ type: 'directreports.changed', timestamp: Date.now() }).catch(() => undefined);
@@ -3600,9 +3631,12 @@ export class OpenCodeController {
3600
3631
  if (this.inbox) return;
3601
3632
  this.inbox = new ControllerInbox({
3602
3633
  read: (sourceArg, previousArg, signalArg) => this.readInboxSource(sourceArg, previousArg, signalArg),
3603
- hasViewers: async () => this.devices?.hasLivePeers() === true || (await this.controllerEventViewers()).length > 0,
3634
+ // A registered device on a platform the host can send on counts too: notifications need the pass with nobody connected.
3635
+ hasViewers: async () => this.devices?.hasLivePeers() === true || (await this.controllerEventViewers()).length > 0
3636
+ || await this.controllerPush?.receives() === true,
3604
3637
  publish: (deltaArg) => {
3605
3638
  void this.pushControllerEvent({ type: 'inbox.changed', inbox: deltaArg, timestamp: Date.now() }).catch(() => undefined);
3639
+ this.controllerPush?.inboxChanged(deltaArg, () => this.inbox?.current());
3606
3640
  },
3607
3641
  reportError: (messageArg, errorArg) => console.error(messageArg, errorArg),
3608
3642
  });
@@ -10544,6 +10578,14 @@ export class OpenCodeController {
10544
10578
  const { ownerToken: _token, ...input } = request;
10545
10579
  return this.executeDeploy(method, input, operationSignalArg);
10546
10580
  }),
10581
+ push: (method, request, signal) => run(signal, async () => {
10582
+ if (!this.configurationAuthority || typeof request.ownerToken !== 'string') {
10583
+ throw new plugins.typedrequest.TypedResponseError('Push settings require a local-owner capability.', { code: 'unauthorized' });
10584
+ }
10585
+ const { localCli } = await this.configurationAuthority.verifyOwnerCapability({ token: request.ownerToken });
10586
+ const { ownerToken: _token, ...input } = request;
10587
+ return this.executePush(method, input, localCli);
10588
+ }),
10547
10589
  tickets: (methodArg, requestArg, signalArg, connectionArg) => run(signalArg, async (operationSignalArg) => {
10548
10590
  const { ownerToken, ...request } = requestArg;
10549
10591
  try {
@@ -10960,6 +11002,32 @@ export class OpenCodeController {
10960
11002
  },
10961
11003
  });
10962
11004
  this.assertStartActive();
11005
+ this.pushSettings = await ControllerPushSettings.open({
11006
+ controllerId: authDocument.id,
11007
+ issuerId: issuerIdentity.issuerId,
11008
+ codec: this.options.trustedProxySecretCodec ?? new TpmSecretCodec(),
11009
+ });
11010
+ const devices = this.devices;
11011
+ this.pushDelivery = new ControllerPushDelivery({
11012
+ settings: this.pushSettings,
11013
+ unregistered: async (deviceIdArg, tokenArg) => { await devices.deletePushHolding(deviceIdArg, tokenArg); },
11014
+ fault: (errorArg) => { controllerFailureJournal.record({ operation: 'push.delivery', cause: errorArg }); },
11015
+ ...(this.options.pushEndpoints === undefined ? {} : { endpoints: this.options.pushEndpoints }),
11016
+ });
11017
+ const pushSettings = this.pushSettings;
11018
+ const pushControllerId = authDocument.id;
11019
+ this.controllerPush = new ControllerPush({
11020
+ targets: () => devices.pushTargets(),
11021
+ delivery: this.pushDelivery,
11022
+ previews: () => pushSettings.previews(),
11023
+ // What the last clean stop announced, read (and removed) before the first change is sent; written by the stop.
11024
+ handover: {
11025
+ take: () => takePushHandover(pushControllerId),
11026
+ keep: (announcedArg) => keepPushHandover(pushControllerId, announcedArg),
11027
+ },
11028
+ fault: (errorArg) => { controllerFailureJournal.record({ operation: 'push.trigger', cause: errorArg }); },
11029
+ });
11030
+ this.assertStartActive();
10963
11031
 
10964
11032
  const router = this.createRouter(runtimeConfig.publicOrigin);
10965
11033
  if (runtimeConfig.tlsMode === 'proxy') {
@@ -11505,7 +11573,12 @@ export class OpenCodeController {
11505
11573
  // after Claude Code continued its job in another process; the fleet reads the job's inventory for that proof.
11506
11574
  bindings: new WorkerCallerBindingStore(),
11507
11575
  observeClaudeJob: async (request) => this.fleetWorkers
11508
- ? await this.fleetWorkers.observeCallerJob(request) : { state: 'unproven', reason: 'the fleet is not running yet' } });
11576
+ ? await this.fleetWorkers.observeCallerJob(request) : { state: 'unproven', reason: 'the fleet is not running yet' },
11577
+ // A bridge without a launch (a session adopted by reference, a launch kept by no store) is identified by the job
11578
+ // its parent runs, from the same fleet's inventory and registry (AGL-1888).
11579
+ identifyClaudeProcess: async (request) => this.fleetWorkers
11580
+ ? await this.fleetWorkers.identifyCallerProcess(request)
11581
+ : { state: 'refused', check: 'inventory', reason: 'the fleet is not running yet', forGood: false } });
11509
11582
  this.workerCallers = workerCallers;
11510
11583
  const mcpControllerHost = new ControllerMcpHost({
11511
11584
  controllerPort: runtimeConfig.controllerPort,
@@ -11552,6 +11625,12 @@ export class OpenCodeController {
11552
11625
  }
11553
11626
  this.startSessionFeed();
11554
11627
  this.startInbox();
11628
+ // What waits now goes out once more under its keys, replacing what a device shows: a host that can send passes now
11629
+ // rather than at the next event.
11630
+ const controllerPush = this.controllerPush;
11631
+ if (controllerPush) {
11632
+ void controllerPush.receives().then((receivesArg) => { if (receivesArg) this.inbox?.markStale(); });
11633
+ }
11555
11634
  // Assignees hear of others' changes to their tickets through the fleet's native steering.
11556
11635
  this.ticketNotifier ??= new TicketNotifier({
11557
11636
  deliver: async (sessionIdArg, ticketKeyArg, textArg) => {
@@ -13901,6 +13980,16 @@ export class OpenCodeController {
13901
13980
  await stopPart(async () => { await this.gatewayClient?.close(); this.gatewayClient = undefined; });
13902
13981
  await stopPart(async () => { await this.ticketNotifier?.close(); this.ticketNotifier = undefined; });
13903
13982
  await stopPart(async () => { await this.inbox?.close(); this.inbox = undefined; });
13983
+ if (this.controllerPush) {
13984
+ // The Inbox publishes nothing more: the trigger hands over what it announced now, early in the stop and with the
13985
+ // database open (it closes last), before the parts that may take long, so the 30 s an upgrade or `agl stop` gives
13986
+ // the stop before SIGKILL rarely cuts it. Before the delivery it sends through and the devices it reads from.
13987
+ const controllerPush = this.controllerPush;
13988
+ await stopPart(async () => {
13989
+ await controllerPush.stop();
13990
+ if (this.controllerPush === controllerPush) this.controllerPush = undefined;
13991
+ });
13992
+ }
13904
13993
  await stopPart(async () => { await this.sessionFeed?.close(); this.sessionFeed = undefined; });
13905
13994
  await stopPart(async () => { await this.usageFeed?.stop(); this.usageFeed = undefined; });
13906
13995
  await stopPart(async () => { const notices = this.harnessReleases; this.harnessReleases = undefined; await notices?.close(); });
@@ -14267,6 +14356,14 @@ export class OpenCodeController {
14267
14356
  && !this.flexProjectionReader
14268
14357
  && !this.eventStreamTask;
14269
14358
  if (storesStoppable) await stopPart(async () => this.attachmentCollection);
14359
+ if (this.pushDelivery) {
14360
+ // Before the devices: a send that ends may delete a registration through them.
14361
+ const pushDelivery = this.pushDelivery;
14362
+ await stopPart(async () => {
14363
+ await pushDelivery.stop();
14364
+ if (this.pushDelivery === pushDelivery) this.pushDelivery = undefined;
14365
+ });
14366
+ }
14270
14367
  if (this.devices) {
14271
14368
  const devices = this.devices;
14272
14369
  await stopPart(async () => {
@@ -14274,6 +14371,11 @@ export class OpenCodeController {
14274
14371
  if (this.devices === devices) this.devices = undefined;
14275
14372
  });
14276
14373
  }
14374
+ if (this.pushSettings) {
14375
+ const pushSettings = this.pushSettings;
14376
+ pushSettings.close();
14377
+ if (this.pushSettings === pushSettings) this.pushSettings = undefined;
14378
+ }
14277
14379
  if (storesStoppable && this.authStore) {
14278
14380
  const authStore = this.authStore;
14279
14381
  if (this.controllerStartedRecorded && !this.controllerStoppedRecorded) {
@@ -14466,6 +14568,148 @@ export class OpenCodeController {
14466
14568
  return rootRouter;
14467
14569
  }
14468
14570
 
14571
+ /**
14572
+ * What the host can send a registered device now: previews as the owner set them, whether it holds a usable credential
14573
+ * for the device's platform, and the device's last notification that did not go out.
14574
+ */
14575
+ private devicePushState(deviceIdArg: string, platformArg: TDevicePushPlatform): IDevicePushDelivery {
14576
+ const lastFailure = this.pushDelivery?.lastFailure(deviceIdArg);
14577
+ return {
14578
+ previews: this.pushSettings?.previews() ?? false,
14579
+ available: this.pushDelivery?.available(platformArg) ?? false,
14580
+ ...(lastFailure === undefined ? {} : { lastFailure }),
14581
+ };
14582
+ }
14583
+
14584
+ /** The host's push settings with each platform's registered devices, as `agl push status` shows them. */
14585
+ private async pushStatus(): Promise<IPushStatus> {
14586
+ const settings = this.requirePushSettings();
14587
+ const counts = await this.requireDevices().pushRegistrationCounts();
14588
+ const lastFailure = (platformArg: TDevicePushPlatform) => {
14589
+ const failure = this.pushDelivery?.platformFailure(platformArg);
14590
+ return failure === undefined ? {} : { lastFailure: failure };
14591
+ };
14592
+ return {
14593
+ previews: settings.previews(),
14594
+ apns: { ...settings.apnsStatus(), registrations: counts.apns, ...lastFailure('apns') },
14595
+ fcm: { ...settings.fcmStatus(), registrations: counts.fcm, ...lastFailure('fcm') },
14596
+ };
14597
+ }
14598
+
14599
+ private requirePushSettings(): ControllerPushSettings {
14600
+ if (!this.pushSettings) {
14601
+ throw new plugins.typedrequest.TypedResponseError('The controller is not ready for push settings.', { code: 'push_unavailable' });
14602
+ }
14603
+ return this.pushSettings;
14604
+ }
14605
+
14606
+ /**
14607
+ * `agl push` (AGL-1639), for the local owner: reads the push settings, or changes one, audited as `push.*` with
14608
+ * what it set in `details.push`. A key is checked, sealed and kept; no answer, audit entry, log or refusal repeats it.
14609
+ */
14610
+ private async executePush(
14611
+ methodArg: TControllerMcpPushMethod,
14612
+ requestArg: Record<string, unknown>,
14613
+ localCliArg: IConfigurationLocalCliActor | undefined,
14614
+ ): Promise<IPushOperations[TPushOperation]['response']> {
14615
+ const operation = pushOperationOf(methodArg);
14616
+ if (operation === 'status') return this.pushStatus();
14617
+ if (operation === 'test') return this.sendPushTest(requestArg.deviceId, localCliArg);
14618
+ const settings = this.requirePushSettings();
14619
+ const change = async (
14620
+ typeArg: 'push.apns.set' | 'push.apns.unset' | 'push.fcm.set' | 'push.fcm.unset' | 'push.previews',
14621
+ detailsArg: IControllerAuditPush | undefined,
14622
+ applyArg: () => Promise<boolean>,
14623
+ ): Promise<IPushChange> => {
14624
+ const changed = await this.runAudited({
14625
+ type: typeArg,
14626
+ peerId: localCliArg ? 'local_cli' : 'mcp',
14627
+ ...(localCliArg ? { localCli: localCliArg } : {}),
14628
+ ...(detailsArg === undefined ? {} : { details: { push: detailsArg } }),
14629
+ }, applyArg);
14630
+ return { changed, status: await this.pushStatus() };
14631
+ };
14632
+ if (operation === 'apns.set') {
14633
+ const credential = this.parsePushCredential(() => parseApnsCredential({
14634
+ keyId: requestArg.keyId, teamId: requestArg.teamId, topic: requestArg.topic, signingKey: requestArg.signingKey,
14635
+ }));
14636
+ return change('push.apns.set', { keyId: credential.keyId, teamId: credential.teamId, topic: credential.topic },
14637
+ () => settings.setApns(credential));
14638
+ }
14639
+ if (operation === 'fcm.set') {
14640
+ const credential = this.parsePushCredential(() => parseFcmCredential(requestArg.serviceAccount));
14641
+ return change('push.fcm.set', { projectId: credential.projectId, clientEmail: credential.clientEmail },
14642
+ () => settings.setFcm(credential));
14643
+ }
14644
+ if (operation === 'apns.unset') return change('push.apns.unset', undefined, () => settings.unset('apns'));
14645
+ if (operation === 'fcm.unset') return change('push.fcm.unset', undefined, () => settings.unset('fcm'));
14646
+ const previews = requestArg.previews === true;
14647
+ return change('push.previews', { previews }, () => settings.setPreviews(previews));
14648
+ }
14649
+
14650
+ /**
14651
+ * `agl push test`: the owner's test notification (`IDevicePushTestData`) to every registered device, or to the one
14652
+ * `deviceIdArg` names, one attempt each through the delivery, and what each push service answered; never a token.
14653
+ * Audited as `push.test` with how many devices it went to and how many got it.
14654
+ */
14655
+ private async sendPushTest(
14656
+ deviceIdArg: unknown,
14657
+ localCliArg: IConfigurationLocalCliActor | undefined,
14658
+ ): Promise<{ results: IPushTestResult[] }> {
14659
+ if (deviceIdArg !== undefined && typeof deviceIdArg !== 'string') {
14660
+ throw new plugins.typedrequest.TypedResponseError('deviceId must be a device id.', { code: 'invalid_request' });
14661
+ }
14662
+ const delivery = this.pushDelivery;
14663
+ if (!delivery) {
14664
+ throw new plugins.typedrequest.TypedResponseError('The controller is not ready for push settings.', { code: 'push_unavailable' });
14665
+ }
14666
+ const targets = await this.requireDevices().pushTargets(deviceIdArg);
14667
+ if (deviceIdArg !== undefined && targets.length === 0) {
14668
+ throw new plugins.typedrequest.TypedResponseError('No paired device with that id is registered for notifications.', { code: 'push_device_unknown' });
14669
+ }
14670
+ // Recorded before anything is sent; the closing event carries how many devices it went to and how many got it.
14671
+ const audit = {
14672
+ type: 'push.test' as const,
14673
+ operationId: plugins.crypto.randomBytes(24).toString('base64url'),
14674
+ peerId: localCliArg ? 'local_cli' : 'mcp',
14675
+ ...(localCliArg ? { localCli: localCliArg } : {}),
14676
+ };
14677
+ await this.requireAuthStore().recordAuditEvent({ ...audit, outcome: 'attempted' });
14678
+ const results = await Promise.all(targets.map(async (targetArg): Promise<IPushTestResult> => {
14679
+ const attempt = await delivery.deliver(targetArg, {
14680
+ type: 'test', key: pushNotificationKey(targetArg.salt, pushKeySubjects.test), body: devicePushTestSentence,
14681
+ });
14682
+ return {
14683
+ deviceId: targetArg.deviceId,
14684
+ name: targetArg.name,
14685
+ platform: targetArg.platform,
14686
+ ...(targetArg.environment === undefined ? {} : { environment: targetArg.environment }),
14687
+ outcome: attempt.outcome,
14688
+ ...(attempt.vendorReason === undefined ? {} : { vendorReason: attempt.vendorReason }),
14689
+ };
14690
+ }));
14691
+ try {
14692
+ await this.requireAuthStore().recordAuditEvent({
14693
+ ...audit,
14694
+ outcome: 'succeeded',
14695
+ details: { push: { devices: results.length, delivered: results.filter((resultArg) => resultArg.outcome === 'delivered').length } },
14696
+ });
14697
+ } catch {
14698
+ // The attempted record stands: the notifications went out, and the owner reads their outcome below.
14699
+ }
14700
+ return { results };
14701
+ }
14702
+
14703
+ /** A credential the owner gave, checked before anything is audited or stored; a refusal names the rule only. */
14704
+ private parsePushCredential<T>(parseArg: () => T): T {
14705
+ try {
14706
+ return parseArg();
14707
+ } catch (errorArg) {
14708
+ if (errorArg instanceof PushError) throw new plugins.typedrequest.TypedResponseError(errorArg.message, { code: errorArg.code });
14709
+ throw errorArg;
14710
+ }
14711
+ }
14712
+
14469
14713
  private requireDevices(): ControllerDevices {
14470
14714
  if (!this.devices) {
14471
14715
  throw new plugins.typedrequest.TypedResponseError('The controller is not ready for devices.', { code: 'controller_unavailable' });
@@ -14655,9 +14899,9 @@ export class OpenCodeController {
14655
14899
 
14656
14900
  /**
14657
14901
  * Scope `device`: the session feed, bounded transcript reads, direct sends and permission and question answers of an
14658
- * authenticated device, the Inbox, the driver, the direct reports, the host's status and the shared board -- through
14659
- * the same operations the owner's browser runs, audited as `device:<id>`. `publicOriginArg` is the origin the scope
14660
- * admits.
14902
+ * authenticated device, the Inbox, the driver, the direct reports, the host's status, the shared board and its own
14903
+ * notification registration -- through the same operations the owner's browser runs, audited as `device:<id>`.
14904
+ * `publicOriginArg` is the origin the scope admits.
14661
14905
  */
14662
14906
  private registerDeviceHandlers(routerArg: ControllerProtectedRouter, publicOriginArg: string): void {
14663
14907
  routerArg.addHandler<IReq_DeviceInboxList>('device.inbox.list', async (requestArg, toolsArg) => {
@@ -14854,12 +15098,15 @@ export class OpenCodeController {
14854
15098
  validateRequest(() => assertEmptyRequest(requestArg));
14855
15099
  const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
14856
15100
  return this.runDeviceOperation(peer, deviceId, async (signalArg) => {
14857
- const device = this.requireDevices().get(deviceId);
15101
+ const devices = this.requireDevices();
15102
+ const device = devices.get(deviceId);
14858
15103
  if (device === undefined) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
15104
+ const registration = await devices.pushRegistration(deviceId);
14859
15105
  const proxyMonitor = this.proxyMonitor;
14860
15106
  return {
14861
15107
  agl: deviceHostAgl({ version: commitinfo.version, startedAt: this.startedAt, origin: publicOriginArg, gateway: this.gatewayClient?.status() }),
14862
- device: deviceHostDevice(device),
15108
+ device: deviceHostDevice(device, registration === undefined ? undefined
15109
+ : deviceHostPush(registration, this.devicePushState(deviceId, registration.platform))),
14863
15110
  ...await readDeviceHostSections({
14864
15111
  deployStatus: (operationSignalArg) => this.requireDeployMonitor().status(undefined, operationSignalArg),
14865
15112
  capacity: proxyMonitor === undefined ? undefined : (operationSignalArg) => proxyMonitor.capacity({}, operationSignalArg),
@@ -14870,6 +15117,23 @@ export class OpenCodeController {
14870
15117
  }, toolsArg?.abortSignal);
14871
15118
  });
14872
15119
 
15120
+ // Notifications (AGL-1639): a device registers itself, never another; the token it sends stays in its registration.
15121
+ routerArg.addHandler<IReq_DevicePushRegister>('device.push.register', async (requestArg, toolsArg) => {
15122
+ const request = validateRequest(() => assertDevicePushRegisterRequest(requestArg));
15123
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
15124
+ return this.runDeviceOperation(peer, deviceId, async () => ({
15125
+ push: deviceHostPush(await this.requireDevices().registerPush(deviceId, request), this.devicePushState(deviceId, request.platform)),
15126
+ }), toolsArg?.abortSignal);
15127
+ });
15128
+
15129
+ routerArg.addHandler<IReq_DevicePushUnregister>('device.push.unregister', async (requestArg, toolsArg) => {
15130
+ validateRequest(() => assertEmptyRequest(requestArg));
15131
+ const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
15132
+ return this.runDeviceOperation(peer, deviceId, async () => ({
15133
+ removed: await this.requireDevices().unregisterPush(deviceId).finally(() => this.pushDelivery?.forget(deviceId)),
15134
+ }), toolsArg?.abortSignal);
15135
+ });
15136
+
14873
15137
  routerArg.addHandler<IReq_DeviceSessionsList>('device.sessions.list', async (requestArg, toolsArg) => {
14874
15138
  validateRequest(() => assertEmptyRequest(requestArg));
14875
15139
  const { peer, deviceId } = this.requestDevice(toolsArg?.localData);
@@ -15053,6 +15317,8 @@ export class OpenCodeController {
15053
15317
  { type: 'device.revoke', peerId: peer.id, credentialId: deviceAuditPeerId(deviceId) },
15054
15318
  async () => {
15055
15319
  const { revoked, peers } = await this.requireDevices().revoke(deviceId);
15320
+ // Nothing queued for it goes out any more.
15321
+ this.pushDelivery?.forget(deviceId);
15056
15322
  for (const devicePeer of peers) this.closeRevokedDevicePeer(devicePeer);
15057
15323
  return { revoked };
15058
15324
  },
@@ -8,6 +8,7 @@ import {
8
8
  maximumDevices,
9
9
  maximumPendingDevicePairings,
10
10
  type IReq_DevicePair,
11
+ type TDevicePushPlatform,
11
12
  type TDeviceRefusalCode,
12
13
  } from '../ts_interfaces/devices.js';
13
14
  import type {
@@ -25,6 +26,18 @@ import {
25
26
  importDevicePublicKey,
26
27
  verifyDeviceSignature,
27
28
  } from './functions.deviceproof.js';
29
+ import {
30
+ countPushRegistrations,
31
+ deletePushRegistration,
32
+ deletePushRegistrationHolding,
33
+ readPushRegistration,
34
+ readPushTargets,
35
+ sweepPushRegistrations,
36
+ writePushRegistration,
37
+ type IControllerPushTarget,
38
+ type TControllerPushRegistrationRequest,
39
+ type TControllerPushRegistrationState,
40
+ } from './classes.pushregistrations.js';
28
41
 
29
42
  /** One paired device of a controller. Revoking it deletes the record; its history is the audit log's. */
30
43
  export interface IControllerDeviceDocument {
@@ -93,9 +106,9 @@ export class ControllerDeviceModel extends plugins.nosqldb.SmartDataDbDoc<Contro
93
106
  }
94
107
 
95
108
  /**
96
- * Deletes every device of a controller whose public origin moves: each signed the old origin and could never
97
- * authenticate at the new one. Answers how many it deleted. `optionsArg.session` runs it inside the caller's
98
- * transaction (`moveRuntimeConfig` deletes the devices with the configuration change, or not at all).
109
+ * Deletes every device of a controller whose public origin moves, with its push registration: each signed the old
110
+ * origin and could never authenticate at the new one. Answers how many it deleted. `optionsArg.session` runs it inside
111
+ * the caller's transaction (`moveRuntimeConfig` deletes the devices with the configuration change, or not at all).
99
112
  */
100
113
  export const deleteControllerDevices = async (
101
114
  controllerIdArg: string,
@@ -103,8 +116,9 @@ export const deleteControllerDevices = async (
103
116
  ): Promise<number> => {
104
117
  let deleted = 0;
105
118
  for (const current of await ControllerDeviceModel.exact.findStored({ filter: { controllerId: controllerIdArg }, ...optionsArg })) {
106
- const result = await ControllerDeviceModel.exact.delete({ current }, optionsArg);
107
119
  const { id } = ControllerDeviceModel.exact.toPersisted(current);
120
+ await deletePushRegistration(id, optionsArg);
121
+ const result = await ControllerDeviceModel.exact.delete({ current }, optionsArg);
108
122
  if (result.status !== 'deleted' && await ControllerDeviceModel.exact.findStoredOne({ id }, optionsArg)) {
109
123
  throw new Error('A paired device could not be removed.');
110
124
  }
@@ -171,13 +185,19 @@ export class ControllerDevices {
171
185
 
172
186
  private constructor(private readonly options: IControllerDevicesOptions) {}
173
187
 
174
- /** Reads the devices of the controller. */
188
+ /**
189
+ * Reads the devices of the controller, and deletes every push registration whose device is gone (paired with no
190
+ * controller of the store).
191
+ */
175
192
  public static async open(optionsArg: IControllerDevicesOptions): Promise<ControllerDevices> {
176
193
  const devices = new ControllerDevices(optionsArg);
177
194
  for (const stored of await ControllerDeviceModel.exact.findStored({ filter: { controllerId: optionsArg.controllerId } })) {
178
195
  const record = ControllerDeviceModel.exact.toPersisted(stored);
179
196
  devices.records.set(record.id, record);
180
197
  }
198
+ await sweepPushRegistrations(async (deviceIdArg) => (
199
+ devices.records.has(deviceIdArg) || await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg }) !== null
200
+ ));
181
201
  return devices;
182
202
  }
183
203
 
@@ -444,18 +464,30 @@ export class ControllerDevices {
444
464
  }
445
465
 
446
466
  /**
447
- * Revokes a device: its record is deleted, and every connection authenticated as it loses that at once. Answers the
448
- * connections, which the caller closes, or `revoked: false` for a device that is gone already.
467
+ * Revokes a device: its record and its push registration are deleted in one transaction, and every connection
468
+ * authenticated as it loses that at once. Answers the connections, which the caller closes, or `revoked: false` for
469
+ * a device that is gone already.
449
470
  */
450
471
  public revoke(deviceIdArg: string): Promise<{ revoked: boolean; peers: IControllerDevicePeer[] }> {
451
472
  return this.mutate(async () => {
452
473
  if (!this.records.has(deviceIdArg)) return { revoked: false, peers: [] };
453
- const current = await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg });
454
- if (current) {
455
- const result = await ControllerDeviceModel.exact.delete({ current });
456
- if (result.status !== 'deleted' && await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg })) {
457
- throw new Error('The device record changed concurrently and was not revoked.');
474
+ const session = ControllerDeviceModel.collection.smartdataDb.createSession();
475
+ try {
476
+ await session.withTransaction(async (transactionArg) => {
477
+ await deletePushRegistration(deviceIdArg, { session: transactionArg });
478
+ const current = await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg }, { session: transactionArg });
479
+ if (current === null) return;
480
+ const result = await ControllerDeviceModel.exact.delete({ current }, { session: transactionArg });
481
+ if (result.status !== 'deleted') throw new Error('The device record changed concurrently and was not revoked.');
482
+ });
483
+ } catch (errorArg) {
484
+ if (plugins.nosqldb.SmartdataSession.getCommitOutcome(errorArg) === 'not_committed') throw errorArg;
485
+ // The commit may have landed: the device is revoked only if the store holds neither of them any more.
486
+ if (await ControllerDeviceModel.exact.findStoredOne({ id: deviceIdArg }) !== null || await readPushRegistration(deviceIdArg)) {
487
+ throw new Error('The device revocation has an ambiguous outcome.', { cause: errorArg });
458
488
  }
489
+ } finally {
490
+ await session.close();
459
491
  }
460
492
  this.records.delete(deviceIdArg);
461
493
  const peers = [...this.live.get(deviceIdArg) ?? []];
@@ -466,6 +498,56 @@ export class ControllerDevices {
466
498
  });
467
499
  }
468
500
 
501
+ /** The push registration of a paired device, without its token; none while it holds none. */
502
+ public async pushRegistration(deviceIdArg: string): Promise<TControllerPushRegistrationState | undefined> {
503
+ if (!this.records.has(deviceIdArg)) return undefined;
504
+ return readPushRegistration(deviceIdArg);
505
+ }
506
+
507
+ /**
508
+ * Registers a paired device for notifications, replacing its registration: it runs in the order of the device
509
+ * writes, after a revocation that came first, so a revoked device is never registered.
510
+ */
511
+ public registerPush(deviceIdArg: string, requestArg: TControllerPushRegistrationRequest): Promise<TControllerPushRegistrationState> {
512
+ if (this.closed) return Promise.reject(deviceRefusal('controller_unavailable', 'The controller is stopping.'));
513
+ return this.mutate(async () => {
514
+ if (!this.records.has(deviceIdArg)) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
515
+ return writePushRegistration(deviceIdArg, requestArg, this.now());
516
+ });
517
+ }
518
+
519
+ /**
520
+ * The registrations of the paired devices, with their tokens and the devices' names, or of the one device
521
+ * `deviceIdArg` names: what the delivery sends to.
522
+ */
523
+ public async pushTargets(deviceIdArg?: string): Promise<Array<IControllerPushTarget & { name: string }>> {
524
+ const ids = deviceIdArg === undefined ? [...this.records.keys()] : this.records.has(deviceIdArg) ? [deviceIdArg] : [];
525
+ return (await readPushTargets(ids)).map((targetArg) => ({ ...targetArg, name: this.records.get(targetArg.deviceId)?.name ?? '' }));
526
+ }
527
+
528
+ /**
529
+ * Deletes a paired device's registration if it still holds `tokenArg`, in the order of the device's writes: its push
530
+ * service called that token gone. Answers whether it deleted one.
531
+ */
532
+ public deletePushHolding(deviceIdArg: string, tokenArg: string): Promise<boolean> {
533
+ if (this.closed) return Promise.resolve(false);
534
+ return this.mutate(async () => this.records.has(deviceIdArg) && deletePushRegistrationHolding(deviceIdArg, tokenArg));
535
+ }
536
+
537
+ /** How many paired devices hold a registration, per platform. */
538
+ public pushRegistrationCounts(): Promise<Record<TDevicePushPlatform, number>> {
539
+ return countPushRegistrations(new Set(this.records.keys()));
540
+ }
541
+
542
+ /** Ends a paired device's registration; answers whether it held one. */
543
+ public unregisterPush(deviceIdArg: string): Promise<boolean> {
544
+ if (this.closed) return Promise.reject(deviceRefusal('controller_unavailable', 'The controller is stopping.'));
545
+ return this.mutate(async () => {
546
+ if (!this.records.has(deviceIdArg)) throw deviceRefusal('device_unknown', 'No such device is paired with this controller.');
547
+ return deletePushRegistration(deviceIdArg);
548
+ });
549
+ }
550
+
469
551
  /** Voids every pairing code and refuses everything from now on; waits for the writes already taken. */
470
552
  public async close(): Promise<void> {
471
553
  this.closed = true;