agl 43.7.0 → 43.8.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 (116) hide show
  1. package/changelog.md +17 -0
  2. package/dist_serve/bundle.js +786 -786
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/interfaces.d.ts +35 -0
  6. package/dist_ts/aglapi/interfaces.js +9 -1
  7. package/dist_ts/classes.apnsclient.d.ts +97 -0
  8. package/dist_ts/classes.apnsclient.js +363 -0
  9. package/dist_ts/classes.authmodels.js +19 -6
  10. package/dist_ts/classes.authstore.js +15 -2
  11. package/dist_ts/classes.cli.js +8 -1
  12. package/dist_ts/classes.controller.d.ts +30 -3
  13. package/dist_ts/classes.controller.js +250 -9
  14. package/dist_ts/classes.controllerdevices.d.ts +35 -7
  15. package/dist_ts/classes.controllerdevices.js +86 -13
  16. package/dist_ts/classes.controllerpush.d.ts +111 -0
  17. package/dist_ts/classes.controllerpush.js +299 -0
  18. package/dist_ts/classes.fcmclient.d.ts +78 -0
  19. package/dist_ts/classes.fcmclient.js +278 -0
  20. package/dist_ts/classes.inbox.d.ts +10 -2
  21. package/dist_ts/classes.inbox.js +9 -2
  22. package/dist_ts/classes.mcpclient.d.ts +5 -0
  23. package/dist_ts/classes.mcpclient.js +18 -6
  24. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
  25. package/dist_ts/classes.mcpcontrollerhost.js +19 -1
  26. package/dist_ts/classes.mcpvalidation.js +4 -1
  27. package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
  28. package/dist_ts/classes.mcpworkercaller.js +26 -4
  29. package/dist_ts/classes.pushdelivery.d.ts +115 -0
  30. package/dist_ts/classes.pushdelivery.js +311 -0
  31. package/dist_ts/classes.pushhandover.d.ts +46 -0
  32. package/dist_ts/classes.pushhandover.js +131 -0
  33. package/dist_ts/classes.pushregistrations.d.ts +96 -0
  34. package/dist_ts/classes.pushregistrations.js +263 -0
  35. package/dist_ts/classes.pushsettings.d.ts +125 -0
  36. package/dist_ts/classes.pushsettings.js +377 -0
  37. package/dist_ts/classes.workercallers.d.ts +73 -2
  38. package/dist_ts/classes.workercallers.js +354 -43
  39. package/dist_ts/driver/classes.directreports.d.ts +5 -0
  40. package/dist_ts/driver/classes.directreports.js +3 -2
  41. package/dist_ts/fleet/classes.workerlaunches.d.ts +6 -4
  42. package/dist_ts/fleet/classes.workerlaunches.js +10 -9
  43. package/dist_ts/fleet/classes.workers.d.ts +12 -2
  44. package/dist_ts/fleet/classes.workers.js +82 -2
  45. package/dist_ts/functions.deviceapi.d.ts +23 -3
  46. package/dist_ts/functions.deviceapi.js +41 -3
  47. package/dist_ts/functions.pushcli.d.ts +43 -0
  48. package/dist_ts/functions.pushcli.js +201 -0
  49. package/dist_ts/functions.pushcredentials.d.ts +53 -0
  50. package/dist_ts/functions.pushcredentials.js +111 -0
  51. package/dist_ts/functions.pushwire.d.ts +8 -0
  52. package/dist_ts/functions.pushwire.js +83 -0
  53. package/dist_ts/functions.remotecli.d.ts +2 -2
  54. package/dist_ts/functions.remotecli.js +4 -4
  55. package/dist_ts/functions.workercallervalidation.js +3 -2
  56. package/dist_ts/functions.workerprocessproof.d.ts +12 -0
  57. package/dist_ts/functions.workerprocessproof.js +32 -1
  58. package/dist_ts/interfaces.auth.d.ts +27 -3
  59. package/dist_ts/interfaces.auth.js +9 -1
  60. package/dist_ts/interfaces.lifecycle.d.ts +7 -1
  61. package/dist_ts/interfaces.push.d.ts +69 -0
  62. package/dist_ts/interfaces.push.js +25 -0
  63. package/dist_ts/plugins.d.ts +3 -1
  64. package/dist_ts/plugins.js +4 -2
  65. package/dist_ts_interfaces/devices.d.ts +178 -2
  66. package/dist_ts_interfaces/devices.js +24 -2
  67. package/dist_ts_interfaces/index.d.ts +1 -0
  68. package/dist_ts_interfaces/index.js +2 -1
  69. package/dist_ts_interfaces/mcprequests.d.ts +3 -2
  70. package/dist_ts_interfaces/mcprequests.js +3 -1
  71. package/dist_ts_interfaces/push.d.ts +166 -0
  72. package/dist_ts_interfaces/push.js +24 -0
  73. package/dist_ts_interfaces/workercallers.d.ts +43 -3
  74. package/package.json +1 -1
  75. package/readme.md +64 -11
  76. package/ts/00_commitinfo_data.ts +1 -1
  77. package/ts/aglapi/interfaces.ts +8 -0
  78. package/ts/classes.apnsclient.ts +389 -0
  79. package/ts/classes.authmodels.ts +21 -5
  80. package/ts/classes.authstore.ts +14 -1
  81. package/ts/classes.cli.ts +7 -0
  82. package/ts/classes.controller.ts +273 -7
  83. package/ts/classes.controllerdevices.ts +94 -12
  84. package/ts/classes.controllerpush.ts +351 -0
  85. package/ts/classes.fcmclient.ts +292 -0
  86. package/ts/classes.inbox.ts +13 -2
  87. package/ts/classes.mcpclient.ts +20 -5
  88. package/ts/classes.mcpcontrollerhost.ts +20 -0
  89. package/ts/classes.mcpvalidation.ts +2 -0
  90. package/ts/classes.mcpworkercaller.ts +24 -2
  91. package/ts/classes.pushdelivery.ts +378 -0
  92. package/ts/classes.pushhandover.ts +98 -0
  93. package/ts/classes.pushregistrations.ts +244 -0
  94. package/ts/classes.pushsettings.ts +428 -0
  95. package/ts/classes.workercallers.ts +329 -37
  96. package/ts/driver/classes.directreports.ts +7 -1
  97. package/ts/fleet/classes.workerlaunches.ts +9 -7
  98. package/ts/fleet/classes.workers.ts +65 -2
  99. package/ts/functions.deviceapi.ts +52 -2
  100. package/ts/functions.pushcli.ts +212 -0
  101. package/ts/functions.pushcredentials.ts +129 -0
  102. package/ts/functions.pushwire.ts +106 -0
  103. package/ts/functions.remotecli.ts +3 -2
  104. package/ts/functions.workercallervalidation.ts +2 -1
  105. package/ts/functions.workerprocessproof.ts +34 -0
  106. package/ts/interfaces.auth.ts +26 -3
  107. package/ts/interfaces.lifecycle.ts +7 -1
  108. package/ts/interfaces.push.ts +78 -0
  109. package/ts/plugins.ts +3 -1
  110. package/ts_interfaces/devices.schema.json +327 -0
  111. package/ts_interfaces/devices.ts +206 -1
  112. package/ts_interfaces/index.ts +1 -0
  113. package/ts_interfaces/mcprequests.ts +3 -0
  114. package/ts_interfaces/push.ts +162 -0
  115. package/ts_interfaces/workercallers.ts +34 -2
  116. package/ts_web/00_commitinfo_data.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agl",
3
- "version": "43.7.0",
3
+ "version": "43.8.0",
4
4
  "controllerUpgradeManagementVersion": 2,
5
5
  "controllerManagementProtocolVersion": 1,
6
6
  "controllerGatewaySourcesVersion": 1,
package/readme.md CHANGED
@@ -1507,7 +1507,8 @@ id: the `cwd` and name the inventory reports are where the session is now and wh
1507
1507
  now, and a worker that changes into a worktree or is renamed stays observable and steerable.
1508
1508
 
1509
1509
  Adoption by reference leaves the session's MCP configuration as it was launched, so it holds no
1510
- fleet caller launch and its MCP ticket writes are not admitted as the worker.
1510
+ fleet caller launch: from its next tool call on, its MCP bridge is identified by its process
1511
+ instead (below), also after a controller restart, and its ticket writes are admitted as the worker.
1511
1512
  `--relaunch-file FILE` adopts a settled Claude session with a verified identity instead: the
1512
1513
  fleet resumes it under its own control as a new worker, `claude --bg --resume <id>` with the
1513
1514
  worker's profile options, its caller overlay and the file's message after the profile preamble,
@@ -1540,7 +1541,9 @@ only `named`). It refuses a worker with a pending, unknown or lost dispatch, a r
1540
1541
  predecessor or successor, a reconfirmation whose ticket comment is not saved, and a session any
1541
1542
  worker of any owner is bound to, archived ones included. The re-bind stores `rebound` (resolver,
1542
1543
  reason, time and proof, with the previous session and its status), drops a reconfirmation that
1543
- named the previous session, and becomes an idempotent ticket comment attributed to the resolver
1544
+ named the previous session, revokes the worker's MCP caller identity once the worker names the new
1545
+ session (the previous session's process no longer writes as the worker; the new session's bridge
1546
+ is identified at its next call), and becomes an idempotent ticket comment attributed to the resolver
1544
1547
  under `fleet:rebound:RESOLUTION_ID`; repeating the same re-bind only synchronizes that comment
1545
1548
  from the saved record. Codex workers are not re-bound and fail closed.
1546
1549
 
@@ -2401,8 +2404,10 @@ that worker, not as the driver or anonymously:
2401
2404
  generation reach only the `agl` MCP server's environment, never the Claude process's.
2402
2405
  Once the agents listing shows the job's process, the fleet binds the launch to the job and
2403
2406
  that process; a job that already settled after a quick turn is bound without a process. A
2404
- start, wake or relaunch that fails at any step revokes its launch. Stop revokes the launch
2405
- and archive also removes the overlay. A start fails closed before Claude runs when the
2407
+ start, wake or relaunch that fails at any step revokes its launch. Stop and archive revoke
2408
+ whatever caller identity the controller holds for the worker, also one the fleet never
2409
+ prepared (kept from before a restart, or recorded for a bridge identified by its process,
2410
+ below), and archive also removes the overlay. A start fails closed before Claude runs when the
2406
2411
  Configuration master has no `agl` MCP server.
2407
2412
  - Fleet Codex workers prepare the launch on the fleet's own connection before
2408
2413
  `thread/start` and bind it before the first `turn/start`. Before steering a thread whose
@@ -2417,9 +2422,10 @@ that worker, not as the driver or anonymously:
2417
2422
  credential). When a bridge enrolls under another process than the bound one, or after a
2418
2423
  controller restart, the fleet reads a fresh Claude inventory (one read at a time) and the
2419
2424
  launch is bound to the bridge's process only when the inventory lists the worker's session,
2420
- once, as the same background job in exactly that process, the process runs the approved
2421
- Claude Code executable, and the bridge is its direct child running the recorded command
2422
- over its own connection. A launch a restarted controller restores is proved the same way
2425
+ once, as the same background job in exactly that process, the process runs an installed
2426
+ Claude Code release (a regular file of the controller's user in the directory of the release
2427
+ `claude` resolves to now; a process the launch was proved against keeps the release it runs),
2428
+ and the bridge is its direct child running the recorded command over its own connection. A launch a restarted controller restores is proved the same way
2423
2429
  before its first write, also when its process still runs. Every other process stays
2424
2430
  unverified, and a refused bridge is not proved again at every call: for the life of that
2425
2431
  process image, or for five seconds when the job showed no process yet, the inventory could
@@ -2436,6 +2442,27 @@ that worker, not as the driver or anonymously:
2436
2442
  with. Each reason an enrollment stays unverified is written once to the controller log,
2437
2443
  naming the worker and its session, never the launch ID or a credential; a bridge refused
2438
2444
  under both commands has both reasons, the recorded command's first.
2445
+ - A launch is only a hint. A bridge that presents none (a Claude session adopted by reference,
2446
+ whose saved options lack the overlay) or one the controller does not hold as presented
2447
+ (unknown, replaced, revoked, of another generation) is identified by its process chain when it
2448
+ enrolls before a call. All of these must hold: the bridge holds its own connection and runs the
2449
+ bridge command the controller approves now; the process it runs under directly, never one
2450
+ further up, runs an installed Claude Code release (proved before the fleet is asked, so a shell
2451
+ or terminal costs no inventory read), is listed exactly once by a fresh inventory of the
2452
+ fleet's Claude homes (those of its workers that are not archived) as the process of a
2453
+ background job, whose session the inventory lists once, and is unchanged across that read; and
2454
+ exactly one stored worker of any owner binds that session, a live Claude worker without a
2455
+ dispatch in flight or a lost one, under the profile home that lists it. The bridge
2456
+ then enrolls into the worker's current record, or into one bound to that process when the
2457
+ worker has none or a revoked one; a record a fleet wake prepared answers pending and is never
2458
+ replaced. That record is not kept in the store: after a restart the process proves itself
2459
+ again. A refused bridge is answered from memory for its image and its parent process, for the
2460
+ process's life or five seconds for a reason that may pass (an inventory that does not list that
2461
+ process yet, as after Claude Code moved a job to a new process, an unreadable inventory, a
2462
+ dispatch in flight, a worker that is not live), until the fleet adopts or re-binds a worker. A
2463
+ refusal read while the fleet adopted or re-bound a worker is not remembered.
2464
+ A bridge that gets a credential this way presents only it; without one, or when the controller
2465
+ rejects or fails the enrollment, it calls as before, with a caller credential it inherited, if any.
2439
2466
 
2440
2467
  The bridge exchanges credentials only through the private controller endpoint after Linux
2441
2468
  direct-loopback socket-inode ownership, approved executable/argv and current native
@@ -3489,6 +3516,7 @@ agl mcp [--port 4097]
3489
3516
  agl ticket list|get|create|update|move|comment|link|unlink|assign|ask|answer [options] [--json]
3490
3517
  agl deploy status [TARGET] | history TARGET | probe TARGET [--json]
3491
3518
  agl release status [REPO] [--json]
3519
+ agl push status [--json] | apns set|unset | fcm set|unset | previews on|off | test [--port 4097] [options]
3492
3520
  agl feed list [--state failed] [--json] | acknowledge <row-id> --updated-at <ms> [--json]
3493
3521
  agl foreground [options]
3494
3522
  agl temp-password [--port 4097] [--ttl-hours 24]
@@ -3865,13 +3893,13 @@ Each connection of a device authenticates on its own: the controller hands it a
3865
3893
 
3866
3894
  ### Managing devices
3867
3895
 
3868
- Settings → Devices lists every paired device with its model, when it paired, whether it is connected now and when it last connected. A device's page shows its key fingerprint and id. **Revoke** deletes the device and closes every connection of it at once with WebSocket close code 4403; the device must pair again with a new code. Moving the controller to another public origin with `agl remote set` or `agl remote unset` removes every device, since each signed the old origin; the devices go in the same transaction as the move, so a move that fails keeps them. Pairing, authentication and revocation are audited (`device.pairing.begin`, `device.pair`, `device.auth`, `device.revoke`), and every request of a device is audited under `device:<id>`.
3896
+ Settings → Devices lists every paired device with its model, when it paired, whether it is connected now and when it last connected. A device's page shows its key fingerprint and id. **Revoke** deletes the device and its notification registration and closes every connection of it at once with WebSocket close code 4403; the device must pair again with a new code. Moving the controller to another public origin with `agl remote set` or `agl remote unset` removes every device, since each signed the old origin; the devices and their registrations go in the same transaction as the move, so a move that fails keeps them. Pairing, authentication and revocation are audited (`device.pairing.begin`, `device.pair`, `device.auth`, `device.revoke`), and every request of a device is audited under `device:<id>`.
3869
3897
 
3870
3898
  ### The device protocol
3871
3899
 
3872
- The device API is its own contract, separate from the browser's: `ts_interfaces/devices.ts` in the package, and the same contracts as JSON Schema in `ts_interfaces/devices.schema.json` (each contract's request and response, and every named type they reach). A device asks `device.hello` for the device protocol version (`major` 1, `minor` 3) and speaks one major; within it, changes only add. Minor 1 added MCP elicitations: `elicitations` in every `device.session.read` (empty while none is pending; each one a `form` with its `fields`, a `url` or an `unsupported` request with its `reason`) and `device.elicitation.reply`. Minor 2 added the Inbox: `device.inbox.list` and its `inbox.changed` event (the same list as the browser's, without host paths; each item says whether a device answers it: `session`, `child`, `ticket` or `none`), `device.ticket.answer` (a ticket question or a go, as the owner) and `childSessionId` on `device.permission.reply` and `device.question.reply` for a direct child the Inbox names; a client sends `childSessionId` only to a controller that answers `minor` 2 or later. Minor 3 added the driver and the direct reports: `device.driver.get`, `device.driver.seen`, `device.driver.read` and `device.driver.send`, `device.directreports.list` and `device.directreport.message`, and the events `driver.changed` and `directreports.changed`, the host's status, read-only: `device.host.get` and its `host.changed` event, and the shared board: `device.board.list`, `device.ticket.get`, `device.ticket.comment`, `device.ticket.ask` and `device.ticket.move`, and the `tickets.changed` event; a client calls them only on a controller that answers `minor` 3 or later. A device does not tell the controller its minor, so a client ignores keys it does not know; the iOS (HarnessKit) and Android clients of minor 0 do. Apps generate their clients from these files.
3900
+ The device API is its own contract, separate from the browser's: `ts_interfaces/devices.ts` in the package, and the same contracts as JSON Schema in `ts_interfaces/devices.schema.json` (each contract's request and response, every named type they reach, the refusal codes and what a push notification carries). A device asks `device.hello` for the device protocol version (`major` 1, `minor` 4) and speaks one major; within it, changes only add. Minor 1 added MCP elicitations: `elicitations` in every `device.session.read` (empty while none is pending; each one a `form` with its `fields`, a `url` or an `unsupported` request with its `reason`) and `device.elicitation.reply`. Minor 2 added the Inbox: `device.inbox.list` and its `inbox.changed` event (the same list as the browser's, without host paths; each item says whether a device answers it: `session`, `child`, `ticket` or `none`), `device.ticket.answer` (a ticket question or a go, as the owner) and `childSessionId` on `device.permission.reply` and `device.question.reply` for a direct child the Inbox names; a client sends `childSessionId` only to a controller that answers `minor` 2 or later. Minor 3 added the driver and the direct reports: `device.driver.get`, `device.driver.seen`, `device.driver.read` and `device.driver.send`, `device.directreports.list` and `device.directreport.message`, and the events `driver.changed` and `directreports.changed`, the host's status, read-only: `device.host.get` and its `host.changed` event, and the shared board: `device.board.list`, `device.ticket.get`, `device.ticket.comment`, `device.ticket.ask` and `device.ticket.move`, and the `tickets.changed` event; a client calls them only on a controller that answers `minor` 3 or later. Minor 4 adds notifications: `device.push.register` and `device.push.unregister`, `push` on `device.host.get`'s `device` while the device is registered for them (whether it asked for direct report results, whether notifications carry previews, whether the host can send now, and the last notification that did not go out; never its token), and what a notification carries (`TDevicePushData`, one set of string values for both platforms: an Inbox item, a summary, a direct report's result and the removal of notifications whose items left the Inbox). A device does not tell the controller its minor, so a client ignores keys it does not know; the iOS (HarnessKit) and Android clients of minor 0 do. Apps generate their clients from these files.
3873
3901
 
3874
- - Before it is authenticated a connection reaches `device.hello`, `device.pair`, `device.auth.challenge` and `device.auth.prove`, under the controller's limits for unauthenticated requests: per connection, and in total together with the browser's sign-in requests. After that it reaches `device.sessions.list`, `device.session.read`, `device.session.send`, `device.permission.reply`, `device.question.reply`, `device.elicitation.reply`, `device.inbox.list`, `device.ticket.answer`, `device.driver.get`, `device.driver.seen`, `device.driver.read`, `device.driver.send`, `device.directreports.list`, `device.directreport.message`, `device.host.get`, `device.board.list`, `device.ticket.get`, `device.ticket.comment`, `device.ticket.ask` and `device.ticket.move`, under the limits of the owner's browser. A device never reaches a method of the browser, and the browser never one of a device. A connection is one or the other for its whole life: a connection signed in as the browser cannot authenticate as a device, and one a device authenticated cannot sign in as the browser.
3902
+ - Before it is authenticated a connection reaches `device.hello`, `device.pair`, `device.auth.challenge` and `device.auth.prove`, under the controller's limits for unauthenticated requests: per connection, and in total together with the browser's sign-in requests. After that it reaches `device.sessions.list`, `device.session.read`, `device.session.send`, `device.permission.reply`, `device.question.reply`, `device.elicitation.reply`, `device.inbox.list`, `device.ticket.answer`, `device.driver.get`, `device.driver.seen`, `device.driver.read`, `device.driver.send`, `device.directreports.list`, `device.directreport.message`, `device.host.get`, `device.push.register`, `device.push.unregister`, `device.board.list`, `device.ticket.get`, `device.ticket.comment`, `device.ticket.ask` and `device.ticket.move`, under the limits of the owner's browser. A device never reaches a method of the browser, and the browser never one of a device. A connection is one or the other for its whole life: a connection signed in as the browser cannot authenticate as a device, and one a device authenticated cannot sign in as the browser.
3875
3903
  - The feed is the sidebar's session feed without terminal rows, host directories or tickets. A transcript page reduces a tool call to its name, title and status; its input and output stay on the controller. `device.session.read` without `before` returns the newest page, sized by the controller whatever `limit` says; with `before` it returns the next older page of `limit` messages (1 to 50, default 20). A device names a session only by the feed's row id, and reaches only what the feed lists.
3876
3904
  - A message from a device is a direct message (it queues behind a running turn), never the browser's shared draft. A native session AGL does not write to (another process runs it, a fleet worker owns it) refuses it, as it refuses the browser.
3877
3905
  - A device answers as the owner on its own authenticated connection, audited as the device. Its Inbox lists the driver's turn and the driver's own prompts without an answer (the driver session is no feed row), and a native wait as information. A child's answer is sent only after the controller proved the child a running direct child of the session, as it does for the browser.
@@ -3879,16 +3907,41 @@ The device API is its own contract, separate from the browser's: `ts_interfaces/
3879
3907
  - `device.directreports.list` lists the active direct reports as the Driver view does, each by its name, with its session as the feed names it, status, projects, ticket, newest `result:` line, open questions and the fleet workers that report to it (name, harness, status, ticket; no directories or profiles), and whether it takes a message. `device.directreport.message` sends one the owner's message as the Driver view does: a fleet worker report is steered through its ticket and answers `fleet` once the steer succeeded (a steer the fleet refused before its dispatch is refused with `direct_report_failed` and the fleet's own text, such as "Worker is archived.", or "The controller operation failed." with the failure journal's reference where a harness's own text failed it; a steer that failed after its dispatch, or whose job does not prove it sent nothing (`errorOutcome` other than `refused`), may have delivered the message and is `outcome_unknown`, "The request may have taken effect. Read again to learn whether it did before sending it again." with the failure journal's reference, which a client never sends again on its own); a Codex thread takes it as the owner's agent message, `steer` into the turn AGL runs or `next-turn`. A turn another Codex client runs is refused with `direct_report_busy` (nothing was sent), a Claude Code session the fleet does not run with `direct_report_failed`, and messages to a report faster than its agent message rate with `rate_limited`. Messages are audited as `session.message` from `Owner` for the device.
3880
3908
  - The Host view is read-only (AGL-824): a device changes nothing on the host (no deploy or deploy probe, account, setting, upgrade or pairing). `device.host.get` answers what runs (`agl`: the AGL release, its start, its public origin, and whether a device reaches it through the gateway AGL keeps its route on, with where that route's sync stands, or through the owner's own reverse proxy; never the gateway's address, the client or the route's target), the device itself as the controller keeps it (`device`: name, model, when it paired and when it last connected; a device neither renames nor unpairs itself), the deploy targets (`deploys`: what each runs and since when, whether its probe answers, its newest release, the released versions it does not run (`undeployed`, newest first), and its planned deploys (`plans`: the ticket, the version, the owner's go and, for one queued into a maintenance window, the window's times); never a probe's address, the owner's notes on how it deploys and what a deploy interrupts, a failed probe's text, a plan's question or who deploys it, and the read runs no probe), the inference proxy's account pools (`pools`: each pool's verdict and room, and its accounts by plan and then the most used first, each only as its plan, state and the usage window it is bound by: no account id, and no order that stands in for one) and the API keys (`apiKeys`: per provider, how many keys are under their monthly spend limit, held at it, without one, or not read, judged by the rule AGL's inference proxy places by; no label, email, id or dollar amount). `deploys`, `pools` and `apiKeys` each answer `ready` or `unavailable` on their own, with the reason (`not_running`, `outdated`, or `failed` with the failure journal's `reference`), and the request still answers the others. `host.changed` (no payload) says when to read it again: the deploy targets, their planned deploys (tickets) or the accounts changed. Usage moves without an event, so a client reads it again when the Host view is opened or refreshed.
3881
3909
  - The shared board on a device is the browser's board (AGL-1637). `device.board.list` answers one column at a time, as the browser shows its cards (the tasks; an epic and a subtask open with `device.ticket.get`), in the column's order, `limit` (1 to 100, default 50) from `offset`, filtered as the browser filters: `text` (1 to 200 characters, in the key, title, description and source words), `project`, `epic` (the epic's own tasks), `assignee` (`{ kind: 'owner' }`, `{ kind: 'unassigned' }` or a session as the feed names it) and an AutoLabel (`openQuestion`, `planned`, `undeployed`). Every column's count under the same filters comes from the same read as the page, with `total`, the projects the board's tickets name, the epics a filter may choose and the board's `revision`: when a later page answers another revision, or `tickets.changed` arrives, a client reads the board again from offset 0. `device.ticket.get` answers a ticket with its description, source words, links and parent, one page of its discussion (comments and questions together in the order they were written, newest page first, at most `limit` of 1 to 50 and 256 KiB, `before` for the next older page), where it runs (`placement`, from the deploy monitor, `unavailable` on its own as a section of `device.host.get` is) and what it plans (`plans`: the release plan, the maintenance window and the deploy plan, with where the window stands and the owner's go while the monitor answers); no history of its other changes, no source attachments, no plan's question and nothing that names who deploys it. People appear by name: the owner as `kind: 'owner'`, never the owner's account, a person's id or a session the feed does not list (the driver's own session included). `device.ticket.comment` (Markdown, at most 64 KiB as the store keeps it), `device.ticket.ask` (text alone, at most 16 KiB, answered with text) and `device.ticket.move` (to the end of a column; "Move to…" stands in for the browser's drag) run the browser board's own function as the owner, audited as `ticket.comment`, `ticket.ask` and `ticket.move` for the device; `device.ticket.answer` answers a question. The controller decides every change: a refusal changes nothing and carries the ticket store's own code (`deviceTicketRefusalCodes`, such as `ticket_review_branch_required` for a move to review without a branch) and its reason. The app then keeps the owner's draft, reads the ticket again and shows the reason; it never sends a refused change again on its own. A change whose outcome AGL cannot tell is refused as `outcome_unknown` and stays fenced: the app reads the ticket again to learn whether it happened before the owner decides, and never sends it again on its own. Creating, editing and assigning tickets stay in the browser.
3910
+ - Notifications (AGL-1639): `device.push.register` registers the device itself, never another, with its push service's token (`platform` `apns` with the device token as lowercase hex and its `environment`, `sandbox` or `production`, or `fcm` with the registration token) and whether it wants the direct reports' results too (`reports`). A device holds one registration, which the next one replaces, so the app registers again with its current token on every connect; the same request again changes nothing. It answers the registration as `device.host.get` shows it (`push`: `reports`, `previews`, `available`, `lastFailure`), and is taken also while the host cannot send (`available` `false`: the owner has not set the platform's credential, or Apple or Google refused it; see [Notifications](#notifications)). `device.push.unregister` ends it (`removed` says whether there was one). The token is kept only in the registration (`agl_controller_push_registrations`, one record per device, beside the device record and never in it); no answer, event, audit entry or log repeats it. Revoking the device and an origin move delete its registration with it, in the same transaction, and a start removes every registration whose device is gone.
3882
3911
  - Every refusal of every device method carries one code of `TDeviceRefusalCode` as `error.data.code` and a message to show, whatever the controller refused it with (AGL-1670): the set is closed, and within a major it only grows. The pairing and the connection: `device_unknown` (forget the pairing), `device_pairing_invalid`, `device_pairing_unavailable`, `device_limit`, `device_already_paired`, `device_proof_invalid`, `device_challenge_invalid` and `device_authentication_required`. What the request names is gone: `session_not_found` (list the feed again), `driver_absent`, and the ticket store's `ticket_not_found` and `ticket_question_not_found`. Nothing was done because something else changed meanwhile, so read again, then decide: `concurrent_change` (among others an answer to a permission or question the session no longer holds, AGL-1687), `ticket_revision_conflict` and `direct_report_busy`. Refused by a rule, with the reason: `session_read_only` (including a session whose model or stopped message the owner resolves in the browser first), `invalid_request`, `direct_report_failed` and the ticket store's other codes (`deviceTicketRefusalCodes`). Limits: `rate_limited`, final as every refusal, and `operation_limit`. The controller: `controller_unavailable` (not ready: starting, stopping, or a harness or the Flex child not running) and `controller_failed` (a fault, always "The controller operation failed."; `error.data.reference` names the failure journal entry the owner's browser shows, and no message to a device carries a raw cause such as a socket path or a spawn error). `outcome_unknown` means the request may have happened: AGL dispatched it, or may have, and cannot tell whether it took effect. A client never resends it on its own; it keeps the owner's text, reads the session, the driver or the ticket again to learn the outcome, and the owner decides.
3883
3912
  - The controller pushes a device an allowlist of events in their own shape: feed changes, a session's change, its streaming text (snapshots and exact deltas), Inbox changes, the driver's changes (`driver.changed` with its status, also when its transcript or prompts changed, never its streaming text), the direct reports' changes (`directreports.changed`, with no payload, also when fleet workers or tickets changed), the host's changes (`host.changed`, with no payload, when the deploy targets or the accounts changed), the board's changes (`tickets.changed`, with no ticket key and with the board's revision when it moved, followed by `directreports.changed` and `host.changed`, since tickets hold the reports' questions and the planned deploys) and a resynchronization request. Every other event, and every event about a session the feed does not list, stays on the controller. A device that falls behind by 256 events or 4 MiB is resynchronized alone: on `sessions.changed` it lists the feed and reads the open session again, an open Driver view included (the driver's own changes may have folded into it).
3884
3913
  - Through the gateway, a device's WebSocket upgrade carries the public origin as `Origin`, like a browser's (Admission).
3885
3914
 
3915
+ ### Notifications
3916
+
3917
+ The host sends notifications of what waits in the Inbox itself, straight to Apple's push service (APNs) and to Firebase Cloud Messaging (FCM), to each paired device that registered for them (`device.push.register`); no relay sits between. It sends with the app publisher's own credentials, which the owner gives the running controller with `agl push`, as the local owner (the same owner capability `agl config` and `agl ticket` use); there is no way to upload a key through the browser.
3918
+
3919
+ ```sh
3920
+ agl push apns set --key-id ABC123DEFG --team-id DEF123GHIJ < AuthKey_ABC123DEFG.p8 # topic com.modelprofile.harness unless --topic names another
3921
+ agl push fcm set < service-account.json # the Firebase project's service account key file
3922
+ agl push previews on # off by default
3923
+ agl push status [--json]
3924
+ agl push test [--device DEVICE_ID] # the test notification to every registered device, with what Apple or Google answered
3925
+ agl push apns unset
3926
+ agl push fcm unset
3927
+ ```
3928
+
3929
+ - What is sent: one notification for each item that comes into the Inbox, to every registered device of this host, also to a device that is connected (the app does not show it in the foreground) and while nobody is connected at all: with a usable credential and a registered device the Inbox is kept current without an open browser. More than four items at once are one notification ("New items wait for you in the Inbox."). An item that leaves the Inbox, answered anywhere, removes its notification from the devices, and one still waiting to be sent is dropped; a changed item sends nothing. The badge is the Inbox's count. A clean stop (`agl stop`, `agl restart`, an upgrade) hands over what was announced, and what the handover before it named that has not come back yet: after it, an item that still waits as it did is not sent again, while one that came meanwhile, or that waits anew (another wait in the same session), is. After a crash or a kill, or when the handover could not be written or read (the failure journal says so), the items still waiting are sent once more under their keys: the notification shown is replaced, and it sounds again. The handover is one document per controller (`agl_controller_push_handover`) that the next start reads and removes; an older controller does not read it. A device that asked for direct reports' results gets a quiet notification, without a badge, for each new `result:` line of a direct report that is a fleet worker.
3930
+ - A key is read from standard input, from a pipe or a file and never from a terminal, and checked before it is kept: an APNs key is the AuthKey .p8 file (one P-256 private key) with its 10-character key id and the team id; an FCM key is the service account's JSON key file (`type` `service_account`, `project_id`, `client_email` and an RSA `private_key` of at least 2048 bits). The file's `token_uri` and its other URLs are ignored: the host asks only Google's own endpoints. A refusal names the field and the rule, never what was given.
3931
+ - Each key is TPM2-sealed in the controller's database (`agl_controller_push_settings`, one document per controller, `{ id, content }`) under a name bound to the controller, the platform and the credential's generation, as the trusted-proxy secret is; it exists in plaintext only in the running controller. No answer, CLI line, log line, audit entry, event or stored byte repeats a key. Setting a credential again replaces it.
3932
+ - `agl push status` shows previews and, for each platform, whether its credential is `ready`, `refused` (Apple or Google refused it: nothing is sent on the platform until the owner sets it again), `unreadable` (this machine cannot unseal it: set it again) or not set, what it is for (key id, team id and topic; project and service account), when it was set and how many devices registered for the platform. Removing a credential leaves the registrations in place.
3933
+ - Previews are one setting for every device of the host, off unless the owner turns them on. Off, a notification says one fixed sentence per kind of item; on, it also says where the item lives, what it asks and its id, which Apple or Google can read.
3934
+ - Sending: APNs over HTTP/2 to `api.push.apple.com`, or `api.sandbox.push.apple.com` for a development build's token, with an ES256 provider token signed with the key (renewed after 50 minutes, within Apple's 20-to-60-minute rule) and the bundle id as topic; FCM through the HTTP v1 API, with an access token the service account's RS256 assertion gets from Google's token endpoint. An iOS notification is an alert push (thread `inbox` or `reports`, interruption level `active` or `passive`, the default sound except for a report's result, the Inbox's count as badge) carrying the payload under `agl`, with the item's key as `apns-collapse-id`; removing notifications is a background push. An Android notification is a data-only message whose values are all strings; the app builds the notification itself. Apple and Google are told a notification expires after an hour.
3935
+ - A send never holds up the Inbox or event delivery. A notification Apple or Google could not take for a reason that passes (they asked the host to wait, failed, or could not be reached) waits in the device's queue, in memory only: the newest per key, sent again after 1 s, doubling up to 5 minutes or as long as the service asked, and dropped once it is an hour old. A notification refused for good is dropped. A token the push service no longer knows ends the device's registration, if the device still holds that token; the app registers again on its next connect. A credential Apple or Google refuses stops its platform until the owner sets it again; Google's bare "not found", which names neither the token nor the credential, drops only that notification. A refusal that does not name the credential waits and is sent again instead: Apple calling a provider token stale that the host signed less than 20 minutes ago (the host's clock is off, or a resumed VM's was), which is signed again once Apple allows it, an answer of Google's token endpoint that names neither the service account nor its key, and Google's `invalid_grant` while the `Date` of its answer is more than 60 seconds from the host's clock (the host's clock is off: `agl push status` and the failure journal say by how much and which clock is behind; set the host's clock right, NTP). A connection to Apple that has been quiet for a minute answers a ping before the next notification goes on it, so one a NAT or firewall dropped without a word is replaced within 3 seconds. `device.host.get` shows the device whether the host can send (`available`) and its last notification that did not go out (`lastFailure`); `agl push status` shows each platform's last failed send with the push service's own code, and how far the host's clock was off when that was why. Nothing of this survives a restart, and stopping the controller ends every request and connection.
3936
+ - `agl push test` sends the test notification ("Push from AGL works.") to every registered device, or to the one `--device` names, and prints for each what its push service answered: `delivered`, `not sent` without a usable credential, the reason it was not delivered with the service's code, that the service no longer knows the token (the registration is then removed), or `no answer in time` when it did not answer within 20 seconds (the notification may still arrive; the command never waits longer than its request may). It names each device by its name and id, never its token.
3937
+ - Every change is audited: `push.apns.set` (with the key id, team id and topic in `details.push`), `push.apns.unset`, `push.fcm.set` (with the project and the service account), `push.fcm.unset` and `push.previews` (with the setting), and every `agl push test` as `push.test` (with how many devices it went to and how many got it), each with the local CLI that made it. An earlier release (41.1.0 on) reads them as audit types it does not know and starts with the collection in place.
3938
+
3886
3939
  ## Security Boundaries
3887
3940
 
3888
3941
  - Local mode binds the controller to loopback only, and so does TLS-proxy mode without a gateway source. With one, a request from off loopback needs a configured gateway source address and the trusted-proxy secret, and only loopback connects without an `Origin`.
3889
3942
  - The trusted-proxy secret is generated and TPM2-sealed in the controller's database; it is never read from the environment, written to a file or logged.
3890
3943
  - Only `agl remote`, run by the local OS user against a stopped controller, changes a port's public origin, RP ID, TLS mode or gateway sources, and a changed origin or RP ID removes the passkey (a changed origin every paired device too).
3891
- - A paired device holds its own key; the controller stores only its public key. A device reaches only the device scope (feed, bounded reads, direct sends, permission, question and elicitation answers, the Inbox and ticket answers, the driver and the direct reports, the host's status, read-only, and the shared board's comments, questions and moves, as the owner), each connection proves the key over a fresh nonce, and revoking a device closes its connections at once. Pairing codes are single-use, live five minutes in memory only, and pairing is refused in local mode.
3944
+ - A paired device holds its own key; the controller stores only its public key. A device reaches only the device scope (feed, bounded reads, direct sends, permission, question and elicitation answers, the Inbox and ticket answers, the driver and the direct reports, the host's status, read-only, the shared board's comments, questions and moves, as the owner, and its own notification registration, whose push token it never reads back), each connection proves the key over a fresh nonce, and revoking a device closes its connections at once. Pairing codes are single-use, live five minutes in memory only, and pairing is refused in local mode.
3892
3945
  - The private OpenCode server always remains on loopback and uses a generated per-process password.
3893
3946
  - Application RPC starts only after the exact TypedSocket package-major handshake.
3894
3947
  - The management endpoint (`/management/typedrequest`, used by the CLI and the upgrade worker) answers only an HTTP `POST` of `application/json` from a loopback peer (`127.0.0.1` or `::1`), addressed to `127.0.0.1:<port>`, with no `Origin` and no forwarding header (`Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `X-Harness-Controller-Proxy-Secret`), so a browser or a request a proxy forwards is refused, also in proxy mode. It serves only the status read and the upgrade methods; each upgrade method authorises itself against the upgrade token and its one-time grant, as it does over the socket, and every upgrade request counts against the controller's global unauthenticated preflight limit.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: 'agl',
6
- version: '43.7.0',
6
+ version: '43.8.0',
7
7
  description: 'Agent Gateway Layer for OpenCode, FlexHarness, and Codex sessions'
8
8
  }
@@ -155,6 +155,14 @@ export const aglApiMethods = {
155
155
  'agl.mcp.deploy.release': { use: 'excluded', exclusion: 'person', reason: ownerToken },
156
156
  'agl.mcp.deploy.ticket': { use: 'excluded', exclusion: 'person', reason: ownerToken },
157
157
  'agl.mcp.deploy.refresh': { use: 'excluded', exclusion: 'person', reason: ownerToken },
158
+ // The host's push credentials and previews (AGL-1639): only the owner sets them, with `agl push`.
159
+ 'agl.mcp.push.status': { use: 'excluded', exclusion: 'person', reason: ownerToken },
160
+ 'agl.mcp.push.apns.set': { use: 'excluded', exclusion: 'person', reason: ownerToken },
161
+ 'agl.mcp.push.apns.unset': { use: 'excluded', exclusion: 'person', reason: ownerToken },
162
+ 'agl.mcp.push.fcm.set': { use: 'excluded', exclusion: 'person', reason: ownerToken },
163
+ 'agl.mcp.push.fcm.unset': { use: 'excluded', exclusion: 'person', reason: ownerToken },
164
+ 'agl.mcp.push.previews': { use: 'excluded', exclusion: 'person', reason: ownerToken },
165
+ 'agl.mcp.push.test': { use: 'excluded', exclusion: 'person', reason: ownerToken },
158
166
  'agl.mcp.worker.enroll': { use: 'excluded', exclusion: 'transport',
159
167
  reason: 'It enrols the caller credential of a launched worker: the MCP channel itself.' },
160
168
  } as const satisfies Record<TControllerMcpMethod, TAglApiMethodUse>;
@@ -0,0 +1,389 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { TDevicePushData } from '../ts_interfaces/devices.js';
3
+ import type { IApnsCredential } from './classes.pushsettings.js';
4
+ import {
5
+ apnsHosts,
6
+ isPushVendorReason,
7
+ pushRequestTimeoutMs,
8
+ pushServiceEndpoints,
9
+ retryAfterMs,
10
+ type IPushEndpoints,
11
+ type IPushSender,
12
+ type IPushSendTarget,
13
+ type TApnsHost,
14
+ type TPushSendResult,
15
+ } from './interfaces.push.js';
16
+
17
+ /**
18
+ * Apple's push service, spoken directly (AGL-1639; Apple's "Sending notification requests to APNs", "Establishing a
19
+ * token-based connection to APNs" and "Handling notification responses from APNs"): HTTP/2 to api.push.apple.com or
20
+ * api.sandbox.push.apple.com by the device token's environment, `POST /3/device/<token>`, a provider token (an ES256
21
+ * JWT with the key id and the team id) in `authorization`, the bundle id as `apns-topic`.
22
+ */
23
+
24
+ /** Apple's limit for a notification's JSON payload (not VoIP). */
25
+ export const apnsPayloadMaximumBytes = 4096;
26
+ /** Apple's limit for `apns-collapse-id`. */
27
+ export const apnsCollapseIdMaximumBytes = 64;
28
+
29
+ /**
30
+ * Apple: a provider token is refreshed no more than once every 20 minutes and no less than once every 60 minutes, and a
31
+ * token older than an hour is refused (`ExpiredProviderToken`). This client signs a new one after 50 minutes.
32
+ */
33
+ export const apnsProviderTokenTimings = Object.freeze({ refreshMs: 50 * 60_000, minimumAgeMs: 20 * 60_000 });
34
+
35
+ /**
36
+ * A kept session without a request for `idleMs` is asked for a PING answer before the next request goes on it: a NAT or
37
+ * firewall may have dropped the connection without a word, and a request on it would wait the whole request timeout. A
38
+ * session that does not answer within `pingTimeoutMs` is destroyed and the request goes on a new one.
39
+ */
40
+ export const apnsLivenessTimings = Object.freeze({ idleMs: 60_000, pingTimeoutMs: 3_000 });
41
+
42
+ /** Apple: reuse a connection for hours; this client opens a new one after an hour without a request. */
43
+ const sessionIdleMs = 60 * 60_000;
44
+ /** An APNs answer is a small JSON object; anything past this is not read. */
45
+ const maximumAnswerBytes = 16 * 1024;
46
+
47
+ export interface IApnsRequest {
48
+ headers: Record<string, string>;
49
+ body: Buffer;
50
+ }
51
+
52
+ const badgeOf = (valueArg: string): number | undefined => (/^\d{1,9}$/u.test(valueArg) ? Number(valueArg) : undefined);
53
+
54
+ /**
55
+ * The APNs request for a notification: an alert push with `aps` (the alert, `thread-id` inbox or reports,
56
+ * `interruption-level` active or passive, the default sound except for a report's result, the badge where the payload
57
+ * carries one) for `inbox`, `summary`, `report` and `test`, a background push (`content-available`, priority 5) for `clear`, and the payload itself under `agl`. The
58
+ * payload's key is `apns-collapse-id`, so a notification sent again replaces the one shown. None when the payload breaks
59
+ * Apple's limits.
60
+ */
61
+ export const apnsRequest = (topicArg: string, payloadArg: TDevicePushData, expiresAtArg: number): IApnsRequest | undefined => {
62
+ const alert = (bodyArg: string, titleArg?: string) => (titleArg === undefined ? { body: bodyArg } : { title: titleArg, body: bodyArg });
63
+ let aps: Record<string, unknown>;
64
+ switch (payloadArg.type) {
65
+ case 'inbox': {
66
+ const badge = badgeOf(payloadArg.badge);
67
+ if (badge === undefined) return undefined;
68
+ aps = { alert: alert(payloadArg.body, payloadArg.title), badge, sound: 'default', 'thread-id': 'inbox', 'interruption-level': 'active' };
69
+ break;
70
+ }
71
+ case 'summary': {
72
+ const badge = badgeOf(payloadArg.badge);
73
+ if (badge === undefined) return undefined;
74
+ aps = { alert: alert(payloadArg.body), badge, sound: 'default', 'thread-id': 'inbox', 'interruption-level': 'active' };
75
+ break;
76
+ }
77
+ case 'report':
78
+ aps = { alert: alert(payloadArg.body, payloadArg.title), 'thread-id': 'reports', 'interruption-level': 'passive' };
79
+ break;
80
+ case 'test':
81
+ aps = { alert: alert(payloadArg.body), sound: 'default', 'thread-id': 'inbox', 'interruption-level': 'active' };
82
+ break;
83
+ case 'clear':
84
+ // A background push: the aps dictionary holds only content-available; the app sets its badge from the payload.
85
+ aps = { 'content-available': 1 };
86
+ break;
87
+ default:
88
+ return undefined;
89
+ }
90
+ const body = Buffer.from(JSON.stringify({ aps, agl: payloadArg }), 'utf8');
91
+ const collapseId = payloadArg.type === 'clear' ? undefined : payloadArg.key;
92
+ if (body.byteLength > apnsPayloadMaximumBytes
93
+ || (collapseId !== undefined && (collapseId.length === 0 || Buffer.byteLength(collapseId, 'utf8') > apnsCollapseIdMaximumBytes))) {
94
+ return undefined;
95
+ }
96
+ const background = payloadArg.type === 'clear';
97
+ return {
98
+ headers: {
99
+ 'apns-topic': topicArg,
100
+ 'apns-push-type': background ? 'background' : 'alert',
101
+ // Apple: a background push is always priority 5; an alert that waits for nobody (a report's result) too.
102
+ 'apns-priority': background || payloadArg.type === 'report' ? '5' : '10',
103
+ 'apns-expiration': String(Math.max(0, Math.floor(expiresAtArg / 1000))),
104
+ 'apns-id': plugins.crypto.randomUUID(),
105
+ ...(collapseId === undefined ? {} : { 'apns-collapse-id': collapseId }),
106
+ 'content-type': 'application/json',
107
+ },
108
+ body,
109
+ };
110
+ };
111
+
112
+ /** APNs reasons that refuse the host's credential (its key, team or topic): nothing is sent until the owner sets it again. */
113
+ const credentialReasons = new Set([
114
+ 'InvalidProviderToken', 'MissingProviderToken', 'BadEnvironmentKeyIdInToken', 'BadCertificate', 'BadCertificateEnvironment',
115
+ 'Forbidden', 'BadTopic', 'TopicDisallowed',
116
+ ]);
117
+ /** APNs reasons that end the connection's usefulness: the next send opens a new one. */
118
+ const connectionReasons = new Set(['UnrelatedKeyIdInToken', 'IdleTimeout', 'Shutdown']);
119
+
120
+ /**
121
+ * What an APNs answer means for the send (Apple's status and `reason` tables). `ExpiredProviderToken` is the host's
122
+ * clock or the token's age, never the credential: the client signs again once the token may be replaced.
123
+ */
124
+ export const apnsResult = (statusArg: number, reasonArg: string | undefined, retryAfterArg?: number): TPushSendResult => {
125
+ const vendorReason = isPushVendorReason(reasonArg) ? { vendorReason: reasonArg } : {};
126
+ const retry = retryAfterArg === undefined ? {} : { retryAfterMs: retryAfterArg };
127
+ if (statusArg === 200) return { outcome: 'delivered' };
128
+ if (statusArg === 410 || (statusArg === 400 && reasonArg === 'BadDeviceToken')) return { outcome: 'unregistered', ...vendorReason };
129
+ if (reasonArg !== undefined && (connectionReasons.has(reasonArg) || reasonArg === 'ExpiredProviderToken')) {
130
+ return { outcome: 'service_failed', ...vendorReason, ...retry };
131
+ }
132
+ if (statusArg === 403 || (reasonArg !== undefined && credentialReasons.has(reasonArg))) return { outcome: 'credential_refused', ...vendorReason };
133
+ if (statusArg === 429) return { outcome: 'rate_limited', ...vendorReason, ...retry };
134
+ if (statusArg === 400 || statusArg === 404 || statusArg === 405 || statusArg === 413) return { outcome: 'refused', ...vendorReason };
135
+ return { outcome: 'service_failed', ...vendorReason, ...retry };
136
+ };
137
+
138
+ interface ISessionEntry {
139
+ session: plugins.http2.ClientHttp2Session;
140
+ lastUsedAt: number;
141
+ /** The PING a request after `apnsLivenessTimings.idleMs` waits for; every request then waits for the same one. */
142
+ checking?: Promise<void>;
143
+ }
144
+
145
+ /**
146
+ * How a request ended: an answer, or no answer; `refusedStream` when the server refused the stream unprocessed (a GOAWAY
147
+ * reached the session first), which is safe to send again on a new session.
148
+ */
149
+ type TAnswer = { status: number; reason?: string; retryAfter?: number } | { failed: 'unreachable'; refusedStream?: true };
150
+
151
+ const expiredProviderToken = (answerArg: TAnswer): boolean => (
152
+ 'status' in answerArg && answerArg.status === 403 && answerArg.reason === 'ExpiredProviderToken'
153
+ );
154
+
155
+ export interface IApnsClientOptions {
156
+ credential: IApnsCredential;
157
+ /** Where the sessions connect; Apple's hosts when absent. For tests. */
158
+ endpoints?: IPushEndpoints;
159
+ now?: () => number;
160
+ }
161
+
162
+ /**
163
+ * One APNs credential's sender: an HTTP/2 session per host, opened on the first send and kept for the next ones, asked
164
+ * for a PING answer before a request after a minute without one, opened anew after a GOAWAY (a stream the server refused
165
+ * unprocessed is sent once more on the new one), an error, a timeout, an unanswered PING or an hour without a request,
166
+ * and destroyed by `close`; one provider token for every session, signed again after 50 minutes, or once at least 20
167
+ * minutes old when Apple calls it expired.
168
+ */
169
+ export class ApnsClient implements IPushSender {
170
+ private readonly sessions = new Map<TApnsHost, ISessionEntry>();
171
+ /** Sessions no longer used for new requests, until they close. */
172
+ private readonly retired = new Set<plugins.http2.ClientHttp2Session>();
173
+ private providerToken?: { value: string; issuedAt: number };
174
+ private closed = false;
175
+
176
+ constructor(private readonly options: IApnsClientOptions) {}
177
+
178
+ private now(): number {
179
+ return this.options.now?.() ?? Date.now();
180
+ }
181
+
182
+ public async send(targetArg: IPushSendTarget, payloadArg: TDevicePushData, expiresAtArg: number, signalArg: AbortSignal): Promise<TPushSendResult> {
183
+ if (this.closed || signalArg.aborted) return { outcome: 'unreachable' };
184
+ const request = apnsRequest(this.options.credential.topic, payloadArg, expiresAtArg);
185
+ // A token outside the device token's alphabet never reaches a request path.
186
+ if (!request || targetArg.environment === undefined || !/^[0-9a-f]{2,200}$/u.test(targetArg.token)) return { outcome: 'refused' };
187
+ const host = apnsHosts[targetArg.environment];
188
+ let token = this.currentProviderToken();
189
+ let answer = await this.post(host, targetArg.token, request, token.value, signalArg);
190
+ // The server's GOAWAY reached the session before the stream: nothing was processed, so it goes once more on a new one.
191
+ if ('failed' in answer && answer.refusedStream) answer = await this.post(host, targetArg.token, request, token.value, signalArg);
192
+ // Apple calls the token stale: a token old enough to be replaced (or one from the future, after the clock went back)
193
+ // is signed again once.
194
+ if (expiredProviderToken(answer) && !this.younger(token)) {
195
+ this.providerToken = undefined;
196
+ token = this.currentProviderToken();
197
+ answer = await this.post(host, targetArg.token, request, token.value, signalArg);
198
+ }
199
+ if ('failed' in answer) return { outcome: 'unreachable' };
200
+ if (expiredProviderToken(answer)) {
201
+ // A token younger than 20 minutes called stale: the host's clock is off, or was before a VM resumed. Not the
202
+ // credential: the send waits until the token may be signed again, so Apple's 20-minute rule holds, and heals
203
+ // once the clock is right.
204
+ return {
205
+ outcome: 'service_failed', vendorReason: 'ExpiredProviderToken',
206
+ retryAfterMs: Math.max(0, apnsProviderTokenTimings.minimumAgeMs - (this.now() - token.issuedAt)),
207
+ };
208
+ }
209
+ return apnsResult(answer.status, answer.reason, answer.retryAfter);
210
+ }
211
+
212
+ /** Whether the token is younger than Apple lets a token be replaced; a token from the future is not. */
213
+ private younger(tokenArg: { issuedAt: number }): boolean {
214
+ const age = this.now() - tokenArg.issuedAt;
215
+ return age >= 0 && age < apnsProviderTokenTimings.minimumAgeMs;
216
+ }
217
+
218
+ /**
219
+ * Destroys every session; a request still running ends as unreachable. A session a GOAWAY closed gracefully ends its
220
+ * connection once the server closes it, as Apple does after a GOAWAY.
221
+ */
222
+ public async close(): Promise<void> {
223
+ this.closed = true;
224
+ const sessions = [...[...this.sessions.values()].map((entryArg) => entryArg.session), ...this.retired];
225
+ this.sessions.clear();
226
+ this.retired.clear();
227
+ for (const session of sessions) if (!session.destroyed) session.destroy();
228
+ }
229
+
230
+ /** Whether the client holds no session: every one it opened is destroyed or closing. */
231
+ public idle(): boolean {
232
+ return this.sessions.size === 0 && this.retired.size === 0;
233
+ }
234
+
235
+ /** The provider token: the held one while younger than 50 minutes, else a new one. */
236
+ private currentProviderToken(): { value: string; issuedAt: number } {
237
+ const now = this.now();
238
+ if (this.providerToken && now - this.providerToken.issuedAt < apnsProviderTokenTimings.refreshMs) return this.providerToken;
239
+ const { keyId, teamId, key } = this.options.credential;
240
+ const encode = (valueArg: object) => Buffer.from(JSON.stringify(valueArg), 'utf8').toString('base64url');
241
+ const input = `${encode({ alg: 'ES256', kid: keyId })}.${encode({ iss: teamId, iat: Math.floor(now / 1000) })}`;
242
+ const signature = plugins.crypto.sign('sha256', Buffer.from(input, 'utf8'), { key, dsaEncoding: 'ieee-p1363' });
243
+ this.providerToken = { value: `${input}.${signature.toString('base64url')}`, issuedAt: now };
244
+ return this.providerToken;
245
+ }
246
+
247
+ /**
248
+ * The open session to `hostArg`, or a new one. A session without a request for a minute answers a PING first, or is
249
+ * destroyed and replaced.
250
+ */
251
+ private async session(hostArg: TApnsHost): Promise<ISessionEntry> {
252
+ for (;;) {
253
+ const held = this.sessions.get(hostArg);
254
+ if (!held || held.session.closed || held.session.destroyed || this.now() - held.lastUsedAt >= sessionIdleMs) break;
255
+ if (held.checking === undefined && this.now() - held.lastUsedAt < apnsLivenessTimings.idleMs) {
256
+ held.lastUsedAt = this.now();
257
+ return held;
258
+ }
259
+ held.checking ??= this.ping(hostArg, held).finally(() => { held.checking = undefined; held.lastUsedAt = this.now(); });
260
+ await held.checking;
261
+ if (this.closed) throw new Error('The APNs client is closed.');
262
+ }
263
+ return this.open(hostArg);
264
+ }
265
+
266
+ /** Waits for the session's PING answer; a session that gives none in time, or fails, is destroyed. */
267
+ private ping(hostArg: TApnsHost, entryArg: ISessionEntry): Promise<void> {
268
+ return new Promise<void>((resolve) => {
269
+ const timer = setTimeout(() => { this.retire(hostArg, entryArg, 'destroy'); resolve(); }, apnsLivenessTimings.pingTimeoutMs);
270
+ const answered = (errorArg: Error | null): void => {
271
+ clearTimeout(timer);
272
+ if (errorArg) this.retire(hostArg, entryArg, 'destroy');
273
+ resolve();
274
+ };
275
+ try {
276
+ if (!entryArg.session.ping(answered)) answered(new Error('The PING was not sent.'));
277
+ } catch (errorArg) {
278
+ answered(errorArg as Error);
279
+ }
280
+ });
281
+ }
282
+
283
+ /** A new session to `hostArg`, replacing the held one: after an hour without a request it may be gone without a word. */
284
+ private open(hostArg: TApnsHost): ISessionEntry {
285
+ const now = this.now();
286
+ const held = this.sessions.get(hostArg);
287
+ if (held) this.retire(hostArg, held, 'destroy');
288
+ const session = plugins.http2.connect((this.options.endpoints ?? pushServiceEndpoints).apns(hostArg));
289
+ const entry: ISessionEntry = { session, lastUsedAt: now };
290
+ // A GOAWAY ends the session for new requests (Node closes it once its streams end); an error ends it at once.
291
+ session.on('goaway', () => this.retire(hostArg, entry, 'close'));
292
+ session.on('error', () => this.retire(hostArg, entry, 'destroy'));
293
+ session.on('close', () => {
294
+ this.retired.delete(session);
295
+ if (this.sessions.get(hostArg) === entry) this.sessions.delete(hostArg);
296
+ });
297
+ this.sessions.set(hostArg, entry);
298
+ return entry;
299
+ }
300
+
301
+ /**
302
+ * Takes a session out of use: `close` lets its streams end (a GOAWAY, or a reason Apple gives for the connection),
303
+ * `destroy` ends it at once (an error, a stream that failed or timed out, an hour idle).
304
+ */
305
+ private retire(hostArg: TApnsHost, entryArg: ISessionEntry, howArg: 'close' | 'destroy'): void {
306
+ if (this.sessions.get(hostArg) === entryArg) this.sessions.delete(hostArg);
307
+ if (entryArg.session.destroyed) return;
308
+ if (howArg === 'destroy') {
309
+ this.retired.delete(entryArg.session);
310
+ entryArg.session.destroy();
311
+ return;
312
+ }
313
+ this.retired.add(entryArg.session);
314
+ if (!entryArg.session.closed) entryArg.session.close();
315
+ }
316
+
317
+ private async post(hostArg: TApnsHost, deviceTokenArg: string, requestArg: IApnsRequest, providerTokenArg: string, signalArg: AbortSignal): Promise<TAnswer> {
318
+ if (this.closed || signalArg.aborted) return { failed: 'unreachable' };
319
+ let entry: ISessionEntry;
320
+ try {
321
+ entry = await this.session(hostArg);
322
+ } catch {
323
+ return { failed: 'unreachable' };
324
+ }
325
+ if (this.closed || signalArg.aborted) return { failed: 'unreachable' };
326
+ let stream: plugins.http2.ClientHttp2Stream;
327
+ try {
328
+ stream = entry.session.request({
329
+ ':method': 'POST',
330
+ ':authority': hostArg,
331
+ ':path': `/3/device/${deviceTokenArg}`,
332
+ authorization: `bearer ${providerTokenArg}`,
333
+ ...requestArg.headers,
334
+ });
335
+ } catch {
336
+ this.retire(hostArg, entry, 'destroy');
337
+ return { failed: 'unreachable' };
338
+ }
339
+ return await new Promise<TAnswer>((resolve) => {
340
+ let settled = false;
341
+ let status = 0;
342
+ let retryAfter: number | undefined;
343
+ const chunks: Buffer[] = [];
344
+ let size = 0;
345
+ const finish = (answerArg: TAnswer): void => {
346
+ if (settled) return;
347
+ settled = true;
348
+ clearTimeout(timer);
349
+ signalArg.removeEventListener('abort', abort);
350
+ if ('failed' in answerArg && !answerArg.refusedStream) {
351
+ if (!stream.closed && !stream.destroyed) stream.close(plugins.http2.constants.NGHTTP2_CANCEL);
352
+ // A session that timed out or failed a stream may be dead: the next send opens a new one.
353
+ this.retire(hostArg, entry, 'destroy');
354
+ }
355
+ resolve(answerArg);
356
+ };
357
+ const abort = (): void => finish({ failed: 'unreachable' });
358
+ const timer = setTimeout(abort, pushRequestTimeoutMs);
359
+ signalArg.addEventListener('abort', abort, { once: true });
360
+ stream.on('response', (headersArg) => {
361
+ status = Number(headersArg[':status']);
362
+ retryAfter = retryAfterMs(headersArg['retry-after'], this.now());
363
+ });
364
+ stream.on('data', (chunkArg: Buffer) => {
365
+ size += chunkArg.byteLength;
366
+ if (size <= maximumAnswerBytes) chunks.push(chunkArg);
367
+ });
368
+ // The close that follows says why the stream ended.
369
+ stream.on('error', () => undefined);
370
+ stream.on('close', () => {
371
+ if (!status) {
372
+ finish(stream.rstCode === plugins.http2.constants.NGHTTP2_REFUSED_STREAM
373
+ ? { failed: 'unreachable', refusedStream: true } : { failed: 'unreachable' });
374
+ return;
375
+ }
376
+ let reason: string | undefined;
377
+ if (status !== 200 && size <= maximumAnswerBytes) {
378
+ try {
379
+ const answer = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { reason?: unknown };
380
+ reason = isPushVendorReason(answer?.reason) ? answer.reason : undefined;
381
+ } catch { /* An answer without a readable reason is judged by its status. */ }
382
+ }
383
+ if (reason !== undefined && connectionReasons.has(reason)) this.retire(hostArg, entry, 'close');
384
+ finish({ status, ...(reason === undefined ? {} : { reason }), ...(retryAfter === undefined ? {} : { retryAfter }) });
385
+ });
386
+ stream.end(requestArg.body);
387
+ });
388
+ }
389
+ }