@linxin666/dsh-remote-bridge 0.4.12 → 0.4.13

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 (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -8
  3. package/README.zh.md +45 -8
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18031 -373
  7. package/lib/types/core/connection.d.ts +9 -0
  8. package/lib/types/core/devices.d.ts +27 -6
  9. package/lib/types/core/liveactivity.d.ts +7 -0
  10. package/lib/types/core/model-efforts.d.ts +83 -0
  11. package/lib/types/core/protocol.d.ts +2 -0
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/host/firewall.d.ts +74 -0
  14. package/lib/types/host/host-bind-capability.d.ts +90 -0
  15. package/lib/types/host/ingress-gate.d.ts +59 -0
  16. package/lib/types/host/ingress-sync.d.ts +429 -0
  17. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  18. package/lib/types/host/lan-bind.d.ts +106 -0
  19. package/lib/types/host/lan-forward.d.ts +112 -0
  20. package/lib/types/host/lan.d.ts +61 -0
  21. package/lib/types/host/pair-origin.d.ts +34 -19
  22. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  23. package/lib/types/host/relay-connector.d.ts +152 -0
  24. package/lib/types/host/relay-control.d.ts +124 -0
  25. package/lib/types/host/relay-registry.d.ts +114 -0
  26. package/lib/types/host/relay.d.ts +170 -0
  27. package/lib/types/host/routes.d.ts +24 -1
  28. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  29. package/lib/types/host/tunnel-plan.d.ts +41 -0
  30. package/lib/types/host/tunnel.d.ts +289 -0
  31. package/lib/types/index.d.ts +426 -1
  32. package/package.json +4 -2
  33. package/src/client/panel.module.css +16 -1
  34. package/src/core/connection.ts +206 -11
  35. package/src/core/devices.ts +31 -6
  36. package/src/core/hub.ts +17 -5
  37. package/src/core/liveactivity.ts +16 -2
  38. package/src/core/model-efforts.ts +223 -0
  39. package/src/core/protocol.ts +3 -0
  40. package/src/core/push.ts +70 -4
  41. package/src/host/firewall.ts +230 -0
  42. package/src/host/host-bind-capability.ts +249 -0
  43. package/src/host/ingress-gate.ts +203 -0
  44. package/src/host/ingress-sync.ts +1074 -0
  45. package/src/host/lan-bind-plan.ts +134 -0
  46. package/src/host/lan-bind.ts +250 -0
  47. package/src/host/lan-forward.ts +321 -0
  48. package/src/host/lan.ts +142 -0
  49. package/src/host/pair-origin.ts +44 -38
  50. package/src/host/relay-bridge-connector.ts +783 -0
  51. package/src/host/relay-connector.ts +317 -0
  52. package/src/host/relay-control.ts +224 -0
  53. package/src/host/relay-registry.ts +263 -0
  54. package/src/host/relay.ts +294 -0
  55. package/src/host/routes.ts +47 -3
  56. package/src/host/tunnel-orphan.ts +325 -0
  57. package/src/host/tunnel-plan.ts +58 -0
  58. package/src/host/tunnel.ts +688 -0
  59. package/src/index.ts +1280 -22
@@ -26,6 +26,7 @@ import type { RemoteBridgeMethodResult, RemoteBridgeRegistry } from './extension
26
26
  import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
27
27
  import { scopeKey, type JobRoster, type JobsPayload } from './jobs.ts'
28
28
  import type { LiveActivityNotifier } from './liveactivity.ts'
29
+ import type { ModelEffortPreferences } from './model-efforts.ts'
29
30
  import type { PairingService } from './pairing.ts'
30
31
  import type { PushNotifier } from './push.ts'
31
32
  import { pushEventOfTurnEnd } from './push.ts'
@@ -97,6 +98,7 @@ import {
97
98
  METHOD_SESSION_PIN,
98
99
  METHOD_SESSION_PROMPT,
99
100
  METHOD_SESSION_RENAME,
101
+ METHOD_SESSION_SET_EFFORT,
100
102
  METHOD_SESSION_SET_MODEL,
101
103
  METHOD_SESSION_SET_PERMISSION,
102
104
  METHOD_SESSION_SNAPSHOT,
@@ -207,6 +209,14 @@ export interface BridgeConnectionOptions {
207
209
  readonly usage: UsageService
208
210
  /** Host-process permission presets, read and switched through their real service objects. */
209
211
  readonly permissions: SessionPermissions
212
+ /**
213
+ * 每个模型自己的思考档偏好表(`core/model-efforts.ts`)。
214
+ *
215
+ * 一个宿主一份、所有连接与所有会话共享:它记的是这个模型在这台机器上被选过
216
+ * 哪一档,与哪条会话无关(契约 §4)。它与宿主自己的 `reasoning.defaultEffort`
217
+ * 是两件事,`session.models` 用另一个键名 `preferredEffort` 公布它。
218
+ */
219
+ readonly modelEfforts: ModelEffortPreferences
210
220
  /**
211
221
  * The in-process owner peer every gateway call speaks for, minted by the
212
222
  * bridge itself (`core/owner-peer.ts`). Dispatch refuses unpaired
@@ -609,6 +619,66 @@ export function modelSelectionOf(value: unknown): { readonly next?: ModelSelecti
609
619
  }
610
620
  }
611
621
 
622
+ /**
623
+ * The effort ids one catalog row offers, for the model a preference names.
624
+ *
625
+ * Read out of the catalog's own `reasoning.efforts`, which is the only list this
626
+ * bridge may validate against: an effort no row advertises is not a level of
627
+ * that model, and answering `ok` for it would store a value the next
628
+ * `selectModel` has to refuse.
629
+ * @param groups - the catalog's `groups`, exactly as the harness published them.
630
+ * @param provider - provider id, matched against a group's own `id`.
631
+ * @param model - model id, matched against a row's own `id`.
632
+ * @returns the ids the model offers, or undefined when no such model exists —
633
+ * a host that never heard of a pair is a different answer from a model that
634
+ * offers no level at all, and the two refusals say so.
635
+ */
636
+ function effortIdsOf(groups: unknown, provider: string, model: string): readonly string[] | undefined {
637
+ if (!Array.isArray(groups)) return undefined
638
+ for (const group of groups) {
639
+ if (!isRecord(group) || optionalText(group.id) !== provider || !Array.isArray(group.models)) continue
640
+ for (const row of group.models) {
641
+ if (!isRecord(row) || optionalText(row.id) !== model) continue
642
+ const reasoning = row.reasoning
643
+ if (!isRecord(reasoning) || !Array.isArray(reasoning.efforts)) return []
644
+ return reasoning.efforts
645
+ .map(effort => (isRecord(effort) ? optionalText(effort.id) : undefined))
646
+ .filter((id): id is string => id !== undefined)
647
+ }
648
+ }
649
+ return undefined
650
+ }
651
+
652
+ /**
653
+ * The catalog's groups with this host's remembered level beside every model.
654
+ *
655
+ * A row this table has nothing for crosses UNCHANGED — no `preferredEffort`, not
656
+ * even a null one: the key means "the host remembers a level for this model", and
657
+ * a client that showed a level for a model nobody ever chose would be showing the
658
+ * catalog's default under the wrong name. Every other key, and the order of the
659
+ * rows, stays exactly as the harness wrote it.
660
+ * @param groups - the catalog's `groups`, exactly as the harness published them.
661
+ * @param efforts - the host's preference table.
662
+ * @returns the rows to publish, with the remembered levels injected.
663
+ */
664
+ function withPreferredEfforts(groups: unknown, efforts: ModelEffortPreferences): readonly unknown[] {
665
+ if (!Array.isArray(groups)) return []
666
+ return groups.map(group => {
667
+ if (!isRecord(group) || !Array.isArray(group.models)) return group
668
+ const provider = optionalText(group.id)
669
+ if (provider === undefined) return group
670
+ return {
671
+ ...group,
672
+ models: group.models.map(row => {
673
+ if (!isRecord(row)) return row
674
+ const model = optionalText(row.id)
675
+ const preferred = model === undefined ? undefined : efforts.effortOf(provider, model)
676
+ return preferred === undefined ? row : { ...row, preferredEffort: preferred }
677
+ }),
678
+ }
679
+ })
680
+ }
681
+
612
682
  /** One prompt attachment, already projected to the harness's image content part. */
613
683
  type PromptAttachment = Readonly<Record<string, unknown>>
614
684
 
@@ -980,6 +1050,7 @@ export class BridgeConnection {
980
1050
  case METHOD_SESSION_SET_PERMISSION: return this.#sessionSetPermission(frame.p)
981
1051
  case METHOD_SESSION_MODELS: return await this.#sessionModels(frame.p)
982
1052
  case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p)
1053
+ case METHOD_SESSION_SET_EFFORT: return await this.#sessionSetEffort(frame.p)
983
1054
  case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p)
984
1055
  case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p)
985
1056
  case METHOD_QUESTION_LIST: return this.#questionList(frame.p)
@@ -1726,7 +1797,10 @@ export class BridgeConnection {
1726
1797
  * `current` is the session's FOLD — next, else last used, else the catalog
1727
1798
  * default — and never the default on its own: a phone that showed the default
1728
1799
  * while another model was in force would name the wrong model for the next
1729
- * turn. The catalog's groups, failures and default cross unchanged.
1800
+ * turn. The catalog's failures and default cross unchanged, and every row
1801
+ * carries this host's remembered level as `preferredEffort` when it has one:
1802
+ * that key is the table's, deliberately not the row's own
1803
+ * `reasoning.defaultEffort`, which stays the catalog's property.
1730
1804
  * @param payload - `{sessionId}`.
1731
1805
  */
1732
1806
  async #sessionModels(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
@@ -1735,28 +1809,55 @@ export class BridgeConnection {
1735
1809
  const catalog = await this.#unary('session', 'modelCatalog')
1736
1810
  if (!catalog.ok) return catalog
1737
1811
  if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no catalog')
1738
- const fallback = selectionOf(catalog.value.default)
1739
- if (fallback === undefined) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no default model')
1740
- const projections = await this.#unary('session', 'projections', { sessionId })
1741
- if (!projections.ok) return projections
1742
- const folded = modelSelectionOf(projections.value)
1812
+ const folded = await this.#sessionCurrent(sessionId, catalog.value)
1813
+ if (!folded.ok) return folded
1814
+ await this.#options.modelEfforts.load()
1743
1815
  return {
1744
1816
  ok: true,
1745
1817
  r: {
1746
- current: folded.next ?? folded.lastUsed ?? fallback,
1747
- default: fallback,
1748
- groups: catalog.value.groups ?? [],
1818
+ current: folded.current,
1819
+ default: folded.fallback,
1820
+ groups: withPreferredEfforts(catalog.value.groups, this.#options.modelEfforts),
1749
1821
  failures: catalog.value.failures ?? [],
1750
1822
  },
1751
1823
  }
1752
1824
  }
1753
1825
 
1826
+ /**
1827
+ * The selection one session folds to: the pending next choice, else the last
1828
+ * one used, else the catalog default.
1829
+ *
1830
+ * One fold shared by `session.models`, `session.setModel` and
1831
+ * `session.setEffort`, so no two of them can name a different model for the
1832
+ * same session.
1833
+ * @param sessionId - the session whose projection is read.
1834
+ * @param catalog - the catalog the fold falls back into.
1835
+ */
1836
+ async #sessionCurrent(
1837
+ sessionId: string,
1838
+ catalog: Readonly<Record<string, unknown>>,
1839
+ ): Promise<{ readonly ok: true; readonly current: ModelSelection; readonly fallback: ModelSelection } | CallFailure> {
1840
+ const fallback = selectionOf(catalog.default)
1841
+ if (fallback === undefined) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no default model')
1842
+ const projections = await this.#unary('session', 'projections', { sessionId })
1843
+ if (!projections.ok) return projections
1844
+ const folded = modelSelectionOf(projections.value)
1845
+ return { ok: true, current: folded.next ?? folded.lastUsed ?? fallback, fallback }
1846
+ }
1847
+
1754
1848
  /**
1755
1849
  * Answer `session.setModel`: register the next turn's selection.
1756
1850
  *
1757
1851
  * The harness only records the choice for the NEXT request, so the answer
1758
1852
  * echoes the `selected` selection it accepted and nothing here claims the
1759
1853
  * running turn changed.
1854
+ *
1855
+ * A request with no effort of its own is answered with the level this host
1856
+ * remembers for that model: a phone that picked "high" for a model once means
1857
+ * it on the next switch too, and sending nothing would silently reset the
1858
+ * model to the harness's own default. A model this table has nothing for is
1859
+ * sent exactly as before — no `reasoningEffort` key at all. The remembered
1860
+ * level is proven against the catalog first; see {@link #rememberedEffort}.
1760
1861
  * @param payload - `{sessionId, provider, model, effort?}`.
1761
1862
  */
1762
1863
  async #sessionSetModel(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
@@ -1766,7 +1867,9 @@ export class BridgeConnection {
1766
1867
  if (sessionId === undefined || provider === undefined || model === undefined) {
1767
1868
  return refusal(CODE_INVALID_ARGS, 'session.setModel requires sessionId, provider and model')
1768
1869
  }
1769
- const effort = optionalText(payload.effort)
1870
+ await this.#options.modelEfforts.load()
1871
+ const named = optionalText(payload.effort)
1872
+ const effort = named ?? await this.#rememberedEffort(provider, model)
1770
1873
  const call = await this.#unary('session', 'selectModel', {
1771
1874
  sessionId,
1772
1875
  provider,
@@ -1779,6 +1882,90 @@ export class BridgeConnection {
1779
1882
  return { ok: true, r: { ok: true, current: selected } }
1780
1883
  }
1781
1884
 
1885
+ /**
1886
+ * The level this host remembers for one model, proven against the catalog.
1887
+ *
1888
+ * A remembered level is a fact about the past: the harness can change a model's
1889
+ * offered ladder under it, and sending a level the model no longer publishes
1890
+ * makes `selectModel` refuse — which leaves that model unswitchable, with the
1891
+ * slider (which only writes the session's current model) unable to heal it. So
1892
+ * the backfill asks the catalog first and withholds a level the model does not
1893
+ * offer, dropping the stale row on the way: one catalog read for the stale
1894
+ * switch, then the row is gone and the next switch costs nothing.
1895
+ * @param provider - provider id.
1896
+ * @param model - model id.
1897
+ * @returns the level to send, or undefined when there is none this host can prove.
1898
+ */
1899
+ async #rememberedEffort(provider: string, model: string): Promise<string | undefined> {
1900
+ const remembered = this.#options.modelEfforts.effortOf(provider, model)
1901
+ if (remembered === undefined) return undefined
1902
+ const catalog = await this.#unary('session', 'modelCatalog')
1903
+ // A catalog this call cannot read is not evidence the level went stale: the
1904
+ // stored value crosses exactly as it did before this check existed.
1905
+ if (!catalog.ok || !isRecord(catalog.value)) return remembered
1906
+ const offered = effortIdsOf(catalog.value.groups, provider, model)
1907
+ // A model this answer leaves out is NOT evidence its level went stale: a
1908
+ // provider that failed to enumerate this time is reported under the catalog's
1909
+ // own `failures`, and one transient absence must never erase a level the user
1910
+ // set. The level is withheld for this switch and the row is kept. Only a model
1911
+ // that IS published, with a ladder that does not contain this level, is a
1912
+ // level no selection can ever accept.
1913
+ if (offered === undefined) return undefined
1914
+ if (offered.includes(remembered)) return remembered
1915
+ await this.#options.modelEfforts.forget(provider, model, remembered, `the catalog no longer offers it: ${offered.join(', ') || 'no levels'}`)
1916
+ .catch((error: unknown) => {
1917
+ this.#options.log(`could not drop the stale remembered effort for ${provider}/${model}: ${failureText(error)}`)
1918
+ })
1919
+ return undefined
1920
+ }
1921
+
1922
+ /**
1923
+ * Answer `session.setEffort`: remember one model's reasoning level.
1924
+ *
1925
+ * The table is the host's — keyed by provider and model, shared by every
1926
+ * session — so this writes a PREFERENCE and switches no model. The harness is
1927
+ * asked for a selection only when the pair is already this session's folded
1928
+ * choice, where the new level has to reach the next turn; for any other model
1929
+ * `session/selectModel` is never called and the answer echoes the fold
1930
+ * unchanged. A model the catalog does not publish, and a level that model does
1931
+ * not offer, are refused as `invalid-args` before anything is written.
1932
+ * @param payload - `{sessionId, provider, model, effort}`.
1933
+ */
1934
+ async #sessionSetEffort(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1935
+ const sessionId = stringArg(payload, 'sessionId')
1936
+ const provider = stringArg(payload, 'provider')
1937
+ const model = stringArg(payload, 'model')
1938
+ const effort = stringArg(payload, 'effort')
1939
+ if (sessionId === undefined || provider === undefined || model === undefined || effort === undefined) {
1940
+ return refusal(CODE_INVALID_ARGS, 'session.setEffort requires sessionId, provider, model and effort')
1941
+ }
1942
+ // Read before any write: the table is rewritten whole, so a save must never
1943
+ // overwrite rows this process has not read yet.
1944
+ await this.#options.modelEfforts.load()
1945
+ const catalog = await this.#unary('session', 'modelCatalog')
1946
+ if (!catalog.ok) return catalog
1947
+ if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no catalog')
1948
+ const offered = effortIdsOf(catalog.value.groups, provider, model)
1949
+ if (offered === undefined) {
1950
+ return refusal(CODE_INVALID_ARGS, `session.setEffort: this host publishes no model ${provider}/${model}`)
1951
+ }
1952
+ if (!offered.includes(effort)) {
1953
+ return refusal(CODE_INVALID_ARGS, `session.setEffort: ${effort} is not a reasoning effort of ${provider}/${model}`)
1954
+ }
1955
+ const folded = await this.#sessionCurrent(sessionId, catalog.value)
1956
+ if (!folded.ok) return folded
1957
+ await this.#options.modelEfforts.save(provider, model, effort)
1958
+ const saved = { provider, model, effort }
1959
+ if (folded.current.provider !== provider || folded.current.model !== model) {
1960
+ return { ok: true, r: { ok: true, saved, current: folded.current } }
1961
+ }
1962
+ const call = await this.#unary('session', 'selectModel', { sessionId, provider, model, reasoningEffort: effort })
1963
+ if (!call.ok) return call
1964
+ const selected = isRecord(call.value) ? selectionOf(call.value.selected) : undefined
1965
+ if (selected === undefined) return refusal(CODE_INTERNAL, 'session/selectModel returned no selected model')
1966
+ return { ok: true, r: { ok: true, saved, current: selected } }
1967
+ }
1968
+
1782
1969
  /**
1783
1970
  * Answer `presets.list`: the host's Agent-preset roster, forwarded verbatim.
1784
1971
  *
@@ -2242,7 +2429,7 @@ export class BridgeConnection {
2242
2429
  * accept the token, and a field claiming it did would be a lie a client might
2243
2430
  * render. A bridge with no signing key answers identically — a client has no
2244
2431
  * second code path for that difference.
2245
- * @param payload - `{deviceToken, environment, bundle, liveActivityTokens?, locale?}`.
2432
+ * @param payload - `{deviceToken, environment, bundle, liveActivityTokens?, locale?, relayToken?}`.
2246
2433
  */
2247
2434
  async #pushRegister(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2248
2435
  const deviceToken = payload.deviceToken
@@ -2256,6 +2443,13 @@ export class BridgeConnection {
2256
2443
  }
2257
2444
  if (typeof bundle !== 'string' || bundle === '') return refusal(CODE_INVALID_ARGS, 'bundle must be a non-empty string')
2258
2445
  const locale = optionalText(payload.locale)
2446
+ // The relay credential (§28 over the hosted service). Optional and opaque: the
2447
+ // bridge never mints, parses or reissues it — it is the App's, scoped to this
2448
+ // pairing's fingerprint, and this row is the only place it is kept.
2449
+ const relayToken = payload.relayToken
2450
+ if (relayToken !== undefined && (typeof relayToken !== 'string' || relayToken === '')) {
2451
+ return refusal(CODE_INVALID_ARGS, 'relayToken must be the non-empty string the account service issued')
2452
+ }
2259
2453
  let liveActivityTokens: readonly PushLiveActivityToken[] | undefined
2260
2454
  if (payload.liveActivityTokens !== undefined) {
2261
2455
  const raw = payload.liveActivityTokens
@@ -2288,6 +2482,7 @@ export class BridgeConnection {
2288
2482
  bundle,
2289
2483
  ...(locale === undefined ? {} : { locale }),
2290
2484
  ...(liveActivityTokens === undefined ? {} : { liveActivityTokens }),
2485
+ ...(relayToken === undefined ? {} : { relayToken }),
2291
2486
  registeredAt: this.#options.now(),
2292
2487
  }
2293
2488
  try {
@@ -24,13 +24,15 @@ export const DEVICE_ID_BYTES = 12
24
24
  * On-disk schema version of the roster file.
25
25
  *
26
26
  * 1 carried the six identity fields only; 2 adds the optional `push` block per
27
- * row (§28). The difference is additive, so a version-1 file reads as-is: no row
28
- * loses a field, every paired phone stays paired, and the file is rewritten as
29
- * version 2 the next time anything is written. The reader therefore accepts any
30
- * version whose row table validates rather than quarantining a file it merely
31
- * does not recognise — a downgrade must never un-pair every phone.
27
+ * row (§28); 3 adds the optional `relayToken` inside that block, the credential the
28
+ * hosted relay signs a delivery for instead of a local Apple key. Every step is
29
+ * additive, so an older file reads as-is: no row loses a field, every paired phone
30
+ * stays paired, and the file is rewritten as the current version the next time
31
+ * anything is written. The reader therefore accepts any version whose row table
32
+ * validates rather than quarantining a file it merely does not recognise — a
33
+ * downgrade must never un-pair every phone.
32
34
  */
33
- export const ROSTER_VERSION = 2
35
+ export const ROSTER_VERSION = 3
34
36
 
35
37
  /** The APNs environments a device may register for. */
36
38
  export type PushEnvironment = 'sandbox' | 'production'
@@ -67,6 +69,16 @@ export interface PushRegistration {
67
69
  readonly bundle: string
68
70
  readonly locale?: string
69
71
  readonly liveActivityTokens?: readonly PushLiveActivityToken[]
72
+ /**
73
+ * The bearer the hosted relay accepts for this device's fingerprint.
74
+ *
75
+ * The App obtains it from the account service, scoped to `(userId, fingerprint)`
76
+ * and valid for 90 days, and hands it to this bridge through `push.register`. It
77
+ * is what lets a machine with no Apple signing key still deliver §28's events: the
78
+ * relay signs them with the key that never leaves the service. Absent is a phone
79
+ * whose only route is this machine's own key, which is the pre-relay behaviour.
80
+ */
81
+ readonly relayToken?: string
70
82
  readonly registeredAt: number
71
83
  }
72
84
 
@@ -161,6 +173,7 @@ function pushOf(value: unknown, log: (message: string) => void): PushRegistratio
161
173
  bundle: row.bundle,
162
174
  ...(typeof row.locale === 'string' && row.locale !== '' ? { locale: row.locale } : {}),
163
175
  ...(liveActivityTokens === undefined ? {} : { liveActivityTokens }),
176
+ ...(typeof row.relayToken === 'string' && row.relayToken !== '' ? { relayToken: row.relayToken } : {}),
164
177
  registeredAt: typeof row.registeredAt === 'number' ? row.registeredAt : 0,
165
178
  }
166
179
  }
@@ -383,6 +396,18 @@ export class DeviceRoster {
383
396
  return targets
384
397
  }
385
398
 
399
+ /**
400
+ * @returns every paired device that holds a relay token.
401
+ *
402
+ * The relay path's own reachability question: a row that registered an APNs
403
+ * token before the relay existed is a phone this machine cannot notify without a
404
+ * local key, so counting {@link pushTargets} there would claim a delivery that
405
+ * has no route at all.
406
+ */
407
+ relayTargets(): readonly PushTargetView[] {
408
+ return this.pushTargets().filter(({ push }) => push.relayToken !== undefined)
409
+ }
410
+
386
411
  /**
387
412
  * Collapse what earlier enrollments left behind, in memory.
388
413
  *
package/src/core/hub.ts CHANGED
@@ -590,10 +590,17 @@ export class BridgeHub {
590
590
  // one can be shown a card, and a claim held for the phone that was never there
591
591
  // would make the agent wait out a window for a decision nobody can give.
592
592
  if (this.pairedClients > 0) return 'nobody'
593
- // No key, no sender: an alert that cannot be sent is not a delivery, so the
594
- // question is not claimed for a phone that would never learn it exists.
595
- if (this.#options.push?.enabled !== true) return 'nobody'
596
- return this.#options.roster.pushTargets().length > 0 ? 'offline' : 'nobody'
593
+ // No key and no relay token, no sender: an alert that cannot be sent is not a
594
+ // delivery, so the question is not claimed for a phone that would never learn
595
+ // it exists.
596
+ const push = this.#options.push
597
+ if (push?.enabled !== true) return 'nobody'
598
+ // Which rows count as reachable is the route's own question. Over the relay a
599
+ // registration without a relay token is a phone this machine cannot tell
600
+ // anything — the token is the whole credential there — while on the direct
601
+ // route the APNs token on the same row is.
602
+ const targets = push.mode === 'relay' ? this.#options.roster.relayTargets() : this.#options.roster.pushTargets()
603
+ return targets.length > 0 ? 'offline' : 'nobody'
597
604
  }
598
605
 
599
606
  /**
@@ -640,7 +647,12 @@ export class BridgeHub {
640
647
  if (dead.length === 0) return
641
648
  // The roster still lists these rows — the cleanup is a file write — so they are
642
649
  // subtracted here rather than waited out: a claim decision may not block on a disk.
643
- const survivors = this.#options.roster.pushTargets().filter(({ push }) => !dead.includes(push.deviceToken))
650
+ // Counted on the same road the question was claimed on, so a row that never held
651
+ // the relay's token cannot outlive the only registration it had.
652
+ const reachable = this.#options.push?.mode === 'relay'
653
+ ? this.#options.roster.relayTargets()
654
+ : this.#options.roster.pushTargets()
655
+ const survivors = reachable.filter(({ push }) => !dead.includes(push.deviceToken))
644
656
  void this.#forgetDeadTokens(dead)
645
657
  if (survivors.length > 0) return
646
658
  this.#releaseOfflineClaim(callId, 'APNs refused every device token on the roster')
@@ -262,6 +262,8 @@ export interface LiveActivityAddress {
262
262
  readonly environment: 'sandbox' | 'production'
263
263
  /** The app bundle id; the topic is this bundle plus the Live Activity suffix. */
264
264
  readonly bundle: string
265
+ /** The relay credential this card's device row holds, when the bridge stands on the relay. */
266
+ readonly relayToken?: string
265
267
  }
266
268
 
267
269
  /** Whatever actually reaches a card; the APNs client implements this. */
@@ -291,6 +293,11 @@ export interface LiveActivityNotifierOptions {
291
293
  readonly targets: () => readonly LiveActivityAddress[]
292
294
  /** The sender; absent is a bridge with no signing key, and then nothing happens. */
293
295
  readonly sender?: LiveActivitySender
296
+ /**
297
+ * Whether the configured route is reachable right now; the same probe the alert
298
+ * channel beside it reads, so a bridge with neither route sends no card either.
299
+ */
300
+ readonly available?: () => boolean
294
301
  readonly now?: () => number
295
302
  readonly log?: (message: string) => void
296
303
  /**
@@ -345,7 +352,14 @@ export class LiveActivityNotifier {
345
352
 
346
353
  /** @returns whether this bridge will actually deliver anything. */
347
354
  get enabled(): boolean {
348
- return this.#options.sender !== undefined
355
+ if (this.#options.sender === undefined) return false
356
+ const available = this.#options.available
357
+ if (available === undefined) return true
358
+ try {
359
+ return available()
360
+ } catch {
361
+ return false
362
+ }
349
363
  }
350
364
 
351
365
  /**
@@ -647,7 +661,7 @@ export class LiveActivityNotifier {
647
661
  #failed(target: LiveActivityAddress, event: LiveActivityEvent, result: PushSendResult): void {
648
662
  const reason = result.reason ?? ''
649
663
  this.#log(`live activity ${event} for ${target.activityId} was not delivered (${result.status ?? '-'} ${reason === '' ? 'no reason' : reason})`)
650
- const dead = result.status === 410 || reason === 'Unregistered' || reason === 'BadDeviceToken'
664
+ const dead = result.dead === true || result.status === 410 || reason === 'Unregistered' || reason === 'BadDeviceToken'
651
665
  if (!dead) return
652
666
  const retire = this.#options.retire
653
667
  if (retire === undefined) return