@linxin666/dsh-remote-bridge 0.4.12 → 0.4.14

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 (65) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +53 -11
  3. package/README.zh.md +53 -11
  4. package/lib/client.js +112 -90
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18800 -334
  7. package/lib/types/client/PairPanel.d.ts +7 -0
  8. package/lib/types/client/locales.d.ts +13 -10
  9. package/lib/types/core/connection.d.ts +50 -0
  10. package/lib/types/core/devices.d.ts +80 -6
  11. package/lib/types/core/liveactivity.d.ts +7 -0
  12. package/lib/types/core/model-efforts.d.ts +83 -0
  13. package/lib/types/core/protocol.d.ts +24 -0
  14. package/lib/types/core/push.d.ts +70 -3
  15. package/lib/types/host/firewall.d.ts +74 -0
  16. package/lib/types/host/host-bind-capability.d.ts +90 -0
  17. package/lib/types/host/ingress-gate.d.ts +59 -0
  18. package/lib/types/host/ingress-sync.d.ts +429 -0
  19. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  20. package/lib/types/host/lan-bind.d.ts +106 -0
  21. package/lib/types/host/lan-forward.d.ts +112 -0
  22. package/lib/types/host/lan.d.ts +61 -0
  23. package/lib/types/host/pair-origin.d.ts +34 -19
  24. package/lib/types/host/relay-bridge-connector.d.ts +234 -0
  25. package/lib/types/host/relay-connector.d.ts +156 -0
  26. package/lib/types/host/relay-control.d.ts +195 -0
  27. package/lib/types/host/relay-registry.d.ts +123 -0
  28. package/lib/types/host/relay-secondary.d.ts +209 -0
  29. package/lib/types/host/relay.d.ts +170 -0
  30. package/lib/types/host/routes.d.ts +29 -1
  31. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  32. package/lib/types/host/tunnel-plan.d.ts +41 -0
  33. package/lib/types/host/tunnel.d.ts +289 -0
  34. package/lib/types/index.d.ts +488 -1
  35. package/package.json +4 -2
  36. package/src/client/PairPanel.tsx +21 -0
  37. package/src/client/locales.ts +19 -15
  38. package/src/client/panel.module.css +48 -1
  39. package/src/core/connection.ts +316 -11
  40. package/src/core/devices.ts +165 -16
  41. package/src/core/hub.ts +17 -5
  42. package/src/core/liveactivity.ts +16 -2
  43. package/src/core/model-efforts.ts +223 -0
  44. package/src/core/protocol.ts +27 -0
  45. package/src/core/push.ts +90 -5
  46. package/src/host/firewall.ts +230 -0
  47. package/src/host/host-bind-capability.ts +249 -0
  48. package/src/host/ingress-gate.ts +203 -0
  49. package/src/host/ingress-sync.ts +1074 -0
  50. package/src/host/lan-bind-plan.ts +134 -0
  51. package/src/host/lan-bind.ts +250 -0
  52. package/src/host/lan-forward.ts +321 -0
  53. package/src/host/lan.ts +142 -0
  54. package/src/host/pair-origin.ts +44 -38
  55. package/src/host/relay-bridge-connector.ts +849 -0
  56. package/src/host/relay-connector.ts +324 -0
  57. package/src/host/relay-control.ts +315 -0
  58. package/src/host/relay-registry.ts +275 -0
  59. package/src/host/relay-secondary.ts +478 -0
  60. package/src/host/relay.ts +294 -0
  61. package/src/host/routes.ts +57 -3
  62. package/src/host/tunnel-orphan.ts +325 -0
  63. package/src/host/tunnel-plan.ts +58 -0
  64. package/src/host/tunnel.ts +688 -0
  65. package/src/index.ts +1516 -23
@@ -24,13 +24,16 @@ 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; 4 adds the
29
+ * optional `relay` block beside it, the tier grant the phone handed over and when
30
+ * this bridge received it. Every step is additive, so an older file reads as-is:
31
+ * no row loses a field, every paired phone stays paired, and the file is rewritten
32
+ * as the current version the next time anything is written. The reader therefore
33
+ * accepts any version whose row table validates rather than quarantining a file it
34
+ * merely does not recognise — a downgrade must never un-pair every phone.
32
35
  */
33
- export const ROSTER_VERSION = 2
36
+ export const ROSTER_VERSION = 4
34
37
 
35
38
  /** The APNs environments a device may register for. */
36
39
  export type PushEnvironment = 'sandbox' | 'production'
@@ -67,9 +70,40 @@ export interface PushRegistration {
67
70
  readonly bundle: string
68
71
  readonly locale?: string
69
72
  readonly liveActivityTokens?: readonly PushLiveActivityToken[]
73
+ /**
74
+ * The bearer the hosted relay accepts for this device's fingerprint.
75
+ *
76
+ * The App obtains it from the account service, scoped to `(userId, fingerprint)`
77
+ * and valid for 90 days, and hands it to this bridge through `push.register`. It
78
+ * is what lets a machine with no Apple signing key still deliver §28's events: the
79
+ * relay signs them with the key that never leaves the service. Absent is a phone
80
+ * whose only route is this machine's own key, which is the pre-relay behaviour.
81
+ */
82
+ readonly relayToken?: string
70
83
  readonly registeredAt: number
71
84
  }
72
85
 
86
+ /**
87
+ * One device's relay tier grant (schema 4).
88
+ *
89
+ * The App obtains it from the account service and hands it over through
90
+ * `relay.grant`. This bridge never mints, parses or reissues it: it keeps the text
91
+ * and presents it in its next claim to the second meeting point, which decides the
92
+ * entitlement out of band and answers the host with a lease or a refusal. Nothing
93
+ * about the account crosses the wire back — the host learns "admitted" or "not",
94
+ * never who the phone is.
95
+ *
96
+ * It is a fact about the phone that gave it, so it lives in that phone's row and
97
+ * disappears with the row when the phone is revoked; it never becomes a second
98
+ * identity of the bridge's own.
99
+ */
100
+ export interface RelayGrant {
101
+ /** The grant text, exactly as the account service issued it. */
102
+ readonly grant: string
103
+ /** When this bridge received it, in epoch seconds. */
104
+ readonly receivedAt: number
105
+ }
106
+
73
107
  /** One device a notification can be addressed to. */
74
108
  export interface PushTargetView {
75
109
  readonly deviceId: string
@@ -91,6 +125,14 @@ export interface DeviceRecord {
91
125
  * every phone that predates the channel.
92
126
  */
93
127
  readonly push?: PushRegistration
128
+ /**
129
+ * The device's relay tier grant, absent until it calls `relay.grant`.
130
+ *
131
+ * A row without it is a phone whose host may still claim the second meeting
132
+ * point — a bridged lease needs no grant at the market edge — it just cannot be
133
+ * admitted to a tier that requires one.
134
+ */
135
+ readonly relay?: RelayGrant
94
136
  }
95
137
 
96
138
  /** A roster row plus the one field that never leaves the file. */
@@ -161,10 +203,38 @@ function pushOf(value: unknown, log: (message: string) => void): PushRegistratio
161
203
  bundle: row.bundle,
162
204
  ...(typeof row.locale === 'string' && row.locale !== '' ? { locale: row.locale } : {}),
163
205
  ...(liveActivityTokens === undefined ? {} : { liveActivityTokens }),
206
+ ...(typeof row.relayToken === 'string' && row.relayToken !== '' ? { relayToken: row.relayToken } : {}),
164
207
  registeredAt: typeof row.registeredAt === 'number' ? row.registeredAt : 0,
165
208
  }
166
209
  }
167
210
 
211
+ /**
212
+ * Read one row's `relay` block.
213
+ *
214
+ * Dropped rather than quarantined for the reason `pushOf` is: one unreadable grant
215
+ * is not a reason to un-pair every phone, and the row keeps its identity and simply
216
+ * carries no admission. The two fields are the whole block — a grant text and the
217
+ * epoch second it arrived in — so anything else on that object is discarded instead
218
+ * of being handed on to a claim body.
219
+ * @param value - the raw `relay` field of a row.
220
+ * @param log - where a dropped block is reported.
221
+ * @returns the grant, or undefined when there is none to read.
222
+ */
223
+ function relayOf(value: unknown, log: (message: string) => void): RelayGrant | undefined {
224
+ if (value === undefined) return undefined
225
+ if (typeof value !== 'object' || value === null) {
226
+ log('a device row carries an unreadable relay block; ignoring it and keeping the row')
227
+ return undefined
228
+ }
229
+ const row = value as Record<string, unknown>
230
+ if (typeof row.grant !== 'string' || row.grant === ''
231
+ || typeof row.receivedAt !== 'number' || !Number.isFinite(row.receivedAt)) {
232
+ log('a device row carries an unreadable relay block; ignoring it and keeping the row')
233
+ return undefined
234
+ }
235
+ return { grant: row.grant, receivedAt: row.receivedAt }
236
+ }
237
+
168
238
  function isStoredDevice(value: unknown): value is StoredDevice {
169
239
  if (typeof value !== 'object' || value === null) return false
170
240
  const row = value as Record<string, unknown>
@@ -321,6 +391,52 @@ export class DeviceRoster {
321
391
  return false
322
392
  }
323
393
 
394
+ /**
395
+ * Record the relay grant one device just handed over (schema 4).
396
+ *
397
+ * A grant the phone resends replaces the one on the row: the account service
398
+ * reissues them periodically, and the newest text is the one the second meeting
399
+ * point will verify against the current plan. Nothing else on the row moves, so a
400
+ * grant that arrives between two reconnects cannot disturb a push registration.
401
+ * @param deviceId - the device that sent `relay.grant`.
402
+ * @param grant - the grant text as the account service issued it.
403
+ * @returns false when no such device is paired.
404
+ */
405
+ async setRelayGrant(deviceId: string, grant: string): Promise<boolean> {
406
+ // Epoch seconds, not milliseconds: the block crosses to the phone as the
407
+ // protocol's own timestamps do, and a reader comparing it with a claim time
408
+ // would otherwise disagree by three orders of magnitude.
409
+ const receivedAt = Math.floor(this.#now() / 1000)
410
+ for (const [hash, row] of this.#devices) {
411
+ if (row.deviceId !== deviceId) continue
412
+ this.#devices.set(hash, { ...row, relay: { grant, receivedAt } })
413
+ await this.#persist()
414
+ return true
415
+ }
416
+ return false
417
+ }
418
+
419
+ /**
420
+ * @returns the relay grant this bridge claims with, or undefined when no row
421
+ * holds one.
422
+ *
423
+ * The newest one wins, because one host holds one lease at the second meeting
424
+ * point and the phone that most recently handed a grant over is the one whose
425
+ * subscription is being claimed. A pairing with several phones of mixed tiers is
426
+ * then the accepted asymmetry the design names: the host is admitted while at
427
+ * least one paired phone holds a tier that is, and the free-tier phone simply
428
+ * keeps using the market edge.
429
+ */
430
+ relayGrant(): RelayGrant | undefined {
431
+ let newest: RelayGrant | undefined
432
+ for (const row of this.#devices.values()) {
433
+ const held = row.relay
434
+ if (held === undefined) continue
435
+ if (newest === undefined || held.receivedAt > newest.receivedAt) newest = held
436
+ }
437
+ return newest
438
+ }
439
+
324
440
  /**
325
441
  * Forget one Live Activity token the phone no longer holds.
326
442
  *
@@ -365,8 +481,10 @@ export class DeviceRoster {
365
481
  for (const [hash, row] of this.#devices) {
366
482
  const registration = row.push
367
483
  if (registration === undefined || registration.deviceToken !== deviceToken) continue
368
- const { tokenHash, deviceId, pubKey, fingerprint, createdAt, lastSeenAt } = row
369
- this.#devices.set(hash, { tokenHash, deviceId, pubKey, fingerprint, createdAt, lastSeenAt })
484
+ // Only the push block goes: a dead APNs token says nothing about the relay
485
+ // grant the same phone handed over, which rides its own block on this row.
486
+ const { push: _dropped, ...rest } = row
487
+ this.#devices.set(hash, rest)
370
488
  await this.#persist()
371
489
  return true
372
490
  }
@@ -383,6 +501,18 @@ export class DeviceRoster {
383
501
  return targets
384
502
  }
385
503
 
504
+ /**
505
+ * @returns every paired device that holds a relay token.
506
+ *
507
+ * The relay path's own reachability question: a row that registered an APNs
508
+ * token before the relay existed is a phone this machine cannot notify without a
509
+ * local key, so counting {@link pushTargets} there would claim a delivery that
510
+ * has no route at all.
511
+ */
512
+ relayTargets(): readonly PushTargetView[] {
513
+ return this.pushTargets().filter(({ push }) => push.relayToken !== undefined)
514
+ }
515
+
386
516
  /**
387
517
  * Collapse what earlier enrollments left behind, in memory.
388
518
  *
@@ -412,15 +542,25 @@ export class DeviceRoster {
412
542
  this.#devices.delete(row.tokenHash)
413
543
  rows += 1
414
544
  }
415
- if (survivor.push !== undefined) continue
416
545
  // A survivor that never registered takes the newest registration one of
417
- // its dropped rows carried: same phone, same install, same tokens.
546
+ // its dropped rows carried: same phone, same install, same tokens. The
547
+ // relay grant follows the same rule for the same reason — collapsing rows
548
+ // must not withdraw an admission the phone already handed over.
418
549
  let newest: PushRegistration | undefined
550
+ let newestGrant: RelayGrant | undefined
419
551
  for (const row of held) {
420
- if (row === survivor || row.push === undefined) continue
421
- if (newest === undefined || row.push.registeredAt > newest.registeredAt) newest = row.push
552
+ if (row === survivor) continue
553
+ if (row.push !== undefined && (newest === undefined || row.push.registeredAt > newest.registeredAt)) newest = row.push
554
+ if (row.relay !== undefined && (newestGrant === undefined || row.relay.receivedAt > newestGrant.receivedAt)) newestGrant = row.relay
422
555
  }
423
- if (newest !== undefined) this.#devices.set(survivor.tokenHash, { ...survivor, push: newest })
556
+ const push = survivor.push ?? newest
557
+ const relay = survivor.relay ?? newestGrant
558
+ if (push === survivor.push && relay === survivor.relay) continue
559
+ this.#devices.set(survivor.tokenHash, {
560
+ ...survivor,
561
+ ...(push === undefined ? {} : { push }),
562
+ ...(relay === undefined ? {} : { relay }),
563
+ })
424
564
  }
425
565
  const holders = new Map<string, StoredDevice[]>()
426
566
  for (const row of this.#devices.values()) {
@@ -486,10 +626,19 @@ export class DeviceRoster {
486
626
  for (const row of rows) {
487
627
  // The raw block is re-read per row instead of trusted from the guard, so a
488
628
  // row that carries an unreadable token keeps its identity and loses only
489
- // its notification.
490
- const { push: raw, ...rest } = row as StoredDevice & { readonly push?: unknown }
629
+ // its notification. The relay grant takes the same route: a block this
630
+ // reader cannot trust costs the row its admission, never its pairing.
631
+ const { push: raw, relay: rawRelay, ...rest } = row as StoredDevice & {
632
+ readonly push?: unknown
633
+ readonly relay?: unknown
634
+ }
491
635
  const push = pushOf(raw, this.#log)
492
- this.#devices.set(row.tokenHash, push === undefined ? rest : { ...rest, push })
636
+ const relay = relayOf(rawRelay, this.#log)
637
+ this.#devices.set(row.tokenHash, {
638
+ ...rest,
639
+ ...(push === undefined ? {} : { push }),
640
+ ...(relay === undefined ? {} : { relay }),
641
+ })
493
642
  }
494
643
  this.#log(`device roster ${this.#file}: ${rows.length} paired device(s)`)
495
644
  const compacted = this.#compact()
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
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The host's per-model reasoning-effort preferences:
3
+ * `$DSH_HOME/remote-bridge/model-efforts.json`.
4
+ *
5
+ * A preference belongs to a MODEL, not to a session or a device: the phone picks
6
+ * a level for one model once, and every session on this host that later selects
7
+ * that model is handed the same level. The table therefore has exactly one scope
8
+ * — the whole host — and nothing expires an entry when a session ends.
9
+ *
10
+ * It is deliberately not the catalog's `reasoning.defaultEffort`: that is what
11
+ * the harness publishes for a model, this is what the user chose here, and the
12
+ * two disagree the moment somebody picks a level the catalog does not call the
13
+ * default. The wire keeps them apart too (`session.models` rows carry this one
14
+ * as `preferredEffort`, beside the catalog's own `reasoning`).
15
+ * @module dsh-remote-bridge/core/model-efforts
16
+ */
17
+
18
+ import { chmod, mkdir, open, readFile, rename } from 'node:fs/promises'
19
+ import { dirname } from 'node:path'
20
+
21
+ /** The schema version this build writes; an older file is read as the table it is. */
22
+ export const EFFORT_TABLE_VERSION = 1
23
+
24
+ /** One remembered choice: the model it belongs to and the level it was given. */
25
+ export interface EffortPreference {
26
+ readonly provider: string
27
+ readonly model: string
28
+ readonly effort: string
29
+ }
30
+
31
+ export interface ModelEffortPreferencesOptions {
32
+ /** Absolute path of the preference file. */
33
+ readonly file: string
34
+ readonly log?: (message: string) => void
35
+ }
36
+
37
+ /**
38
+ * The key one model is remembered under: a provider id and a model id, which are
39
+ * only unique together.
40
+ * @param provider - provider id, as the catalog's group id spells it.
41
+ * @param model - model id, as the catalog's row id spells it.
42
+ * @returns the table key of that pair.
43
+ */
44
+ function keyOf(provider: string, model: string): string {
45
+ return `${provider}\u0000${model}`
46
+ }
47
+
48
+ /** @returns whether a row read from the file is a preference this build can use. */
49
+ function isPreference(value: unknown): value is EffortPreference {
50
+ if (typeof value !== 'object' || value === null) return false
51
+ const row = value as Record<string, unknown>
52
+ return typeof row.provider === 'string' && row.provider !== ''
53
+ && typeof row.model === 'string' && row.model !== ''
54
+ && typeof row.effort === 'string' && row.effort !== ''
55
+ }
56
+
57
+ /**
58
+ * The persisted effort table, shared by every connection of one host.
59
+ *
60
+ * Read once per process and written atomically: a corrupt file is an EMPTY table
61
+ * with one log line, never a failed mount — a phone must still be able to read
62
+ * the catalog and pick a model on a host whose preference file went bad, and the
63
+ * next write replaces the file rather than writing into the damage.
64
+ */
65
+ export class ModelEffortPreferences {
66
+ readonly #file: string
67
+ readonly #log: (message: string) => void
68
+ readonly #rows = new Map<string, EffortPreference>()
69
+ #loaded: Promise<void> | undefined
70
+ #writeQueue: Promise<void> = Promise.resolve()
71
+
72
+ constructor(options: ModelEffortPreferencesOptions) {
73
+ this.#file = options.file
74
+ this.#log = options.log ?? (() => undefined)
75
+ }
76
+
77
+ /**
78
+ * Read the table once. A missing file is an empty table, and an unreadable or
79
+ * malformed one is reported and then read as empty.
80
+ * @returns when the in-memory table reflects the file.
81
+ */
82
+ load(): Promise<void> {
83
+ this.#loaded ??= this.#read()
84
+ return this.#loaded
85
+ }
86
+
87
+ /**
88
+ * @param provider - provider id.
89
+ * @param model - model id.
90
+ * @returns the level remembered for that model, or undefined when the table has none.
91
+ */
92
+ effortOf(provider: string, model: string): string | undefined {
93
+ return this.#rows.get(keyOf(provider, model))?.effort
94
+ }
95
+
96
+ /**
97
+ * Remember one level and persist it before answering.
98
+ *
99
+ * The write is what the caller is told succeeded, so the memory copy is set
100
+ * first only for the duration of it: a failed write rejects, and the answer
101
+ * the client sees is the failure rather than a level this host never stored.
102
+ * @param provider - provider id.
103
+ * @param model - model id.
104
+ * @param effort - the level chosen for that model.
105
+ */
106
+ async save(provider: string, model: string, effort: string): Promise<void> {
107
+ const key = keyOf(provider, model)
108
+ const previous = this.#rows.get(key)
109
+ const written: EffortPreference = { provider, model, effort }
110
+ this.#rows.set(key, written)
111
+ try {
112
+ await this.#persist()
113
+ } catch (error) {
114
+ // Only this call's own value is rolled back: a later save that already
115
+ // replaced it in memory is the newer truth, and restoring the older level
116
+ // here would silently undo a choice nothing failed on.
117
+ if (this.#rows.get(key) === written) {
118
+ if (previous === undefined) this.#rows.delete(key)
119
+ else this.#rows.set(key, previous)
120
+ }
121
+ throw error
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Drop the remembered level for one model, but only the one judged stale.
127
+ *
128
+ * A level a model stopped publishing is worse than none at all: the backfill in
129
+ * `session.setModel` would send it, the harness would refuse, and the model
130
+ * would become unswitchable — and because that backfill is the only writer, the
131
+ * row could never heal itself. Dropping it makes the next switch plain.
132
+ *
133
+ * The `staleEffort` argument is what keeps that cure from being worse than the
134
+ * disease: an awaited catalog read sits between judging a level stale and
135
+ * arriving here, and frames of one connection are dispatched concurrently, so
136
+ * the user may have typed a NEW level in that window. A row that no longer holds
137
+ * the level this caller judged is a newer choice, and it survives.
138
+ * @param provider - provider id.
139
+ * @param model - model id.
140
+ * @param staleEffort - the level this caller found the catalog no longer offers.
141
+ * @param reason - why it is being dropped, for the log line.
142
+ */
143
+ async forget(provider: string, model: string, staleEffort: string, reason: string): Promise<void> {
144
+ const key = keyOf(provider, model)
145
+ const previous = this.#rows.get(key)
146
+ if (previous === undefined || previous.effort !== staleEffort) return
147
+ this.#rows.delete(key)
148
+ try {
149
+ await this.#persist()
150
+ } catch (error) {
151
+ // Same rule on the way back: a row that appeared while the write failed is
152
+ // a newer choice, and restoring the stale one would undo it.
153
+ if (this.#rows.get(key) === undefined) this.#rows.set(key, previous)
154
+ throw error
155
+ }
156
+ this.#log(`model effort table: dropped ${provider}/${model} = ${previous.effort} (${reason})`)
157
+ }
158
+
159
+ async #read(): Promise<void> {
160
+ let text: string
161
+ try {
162
+ text = await readFile(this.#file, 'utf8')
163
+ } catch (error) {
164
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
165
+ this.#log(`model effort table ${this.#file} is unreadable (${String(error)}); continuing with an empty table`)
166
+ return
167
+ }
168
+ let parsed: unknown
169
+ try {
170
+ parsed = JSON.parse(text)
171
+ } catch {
172
+ this.#log(`model effort table ${this.#file} is not JSON; continuing with an empty table`)
173
+ return
174
+ }
175
+ const rows = (parsed as { efforts?: unknown } | null)?.efforts
176
+ if (!Array.isArray(rows)) {
177
+ this.#log(`model effort table ${this.#file} has no effort table; continuing with an empty table`)
178
+ return
179
+ }
180
+ // One unreadable row is not a reason to lose the rest: the table is written
181
+ // WHOLE on the next save, so every row dropped here would be erased by that
182
+ // write. Keeping everything this build can read is what makes that write
183
+ // preserve the user's other choices.
184
+ let dropped = 0
185
+ for (const row of rows) {
186
+ if (!isPreference(row)) {
187
+ dropped += 1
188
+ continue
189
+ }
190
+ this.#rows.set(keyOf(row.provider, row.model), { provider: row.provider, model: row.model, effort: row.effort })
191
+ }
192
+ if (dropped > 0) this.#log(`model effort table ${this.#file}: dropped ${dropped} unreadable row(s)`)
193
+ this.#log(`model effort table ${this.#file}: ${rows.length - dropped} remembered model(s)`)
194
+ }
195
+
196
+ /**
197
+ * Write the table atomically: same directory, 0600 from creation, flushed
198
+ * before the rename so a crash cannot leave a truncated file in place.
199
+ * Writes are serialized so two sessions choosing the same model cannot race
200
+ * the replacement.
201
+ */
202
+ async #persist(): Promise<void> {
203
+ const pending = this.#writeQueue.then(() => this.#write())
204
+ this.#writeQueue = pending.catch(() => undefined)
205
+ return pending
206
+ }
207
+
208
+ async #write(): Promise<void> {
209
+ const directory = dirname(this.#file)
210
+ await mkdir(directory, { recursive: true, mode: 0o700 })
211
+ const payload = JSON.stringify({ version: EFFORT_TABLE_VERSION, efforts: [...this.#rows.values()] }, null, 2)
212
+ const temporary = `${this.#file}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`
213
+ const handle = await open(temporary, 'w', 0o600)
214
+ try {
215
+ await handle.writeFile(payload, 'utf8')
216
+ await handle.sync()
217
+ } finally {
218
+ await handle.close()
219
+ }
220
+ await rename(temporary, this.#file)
221
+ await chmod(this.#file, 0o600)
222
+ }
223
+ }
@@ -18,6 +18,8 @@ export const METHOD_SESSION_PERMISSIONS = 'session.permissions'
18
18
  export const METHOD_SESSION_SET_PERMISSION = 'session.setPermission'
19
19
  export const METHOD_SESSION_MODELS = 'session.models'
20
20
  export const METHOD_SESSION_SET_MODEL = 'session.setModel'
21
+ /** Remember one model's reasoning level, without switching the session's model. */
22
+ export const METHOD_SESSION_SET_EFFORT = 'session.setEffort'
21
23
  export const METHOD_SESSION_CREATE = 'session.create'
22
24
  export const METHOD_SESSION_FORK = 'session.fork'
23
25
  export const METHOD_SESSION_COMMANDS = 'session.commands'
@@ -47,6 +49,14 @@ export const METHOD_USAGE_STATS = 'usage.stats'
47
49
  // 协议 §35 追加的两个方法:一条卡上的动作回来,以及一张全局卡表的对账读。
48
50
  export const METHOD_UI_EVENT = 'ui.event'
49
51
  export const METHOD_UI_LIST = 'ui.list'
52
+ /**
53
+ * 一条配对连接把手机从账号服务换到的中继授权交给宿主。
54
+ *
55
+ * 它是这条通道唯一的写动作:授权落进那台设备自己的名册行,随后宿主拿它去第二
56
+ * 会合点申领租约。宿主不认识账号——它只会看到「准了」或「不准」,绝不会从这一帧
57
+ * 里读出用户是谁。只在配了第二会合点的宿主上是这个方法(见 {@link CAP_RELAY_TIER})。
58
+ */
59
+ export const METHOD_RELAY_GRANT = 'relay.grant'
50
60
 
51
61
  /** Server-pushed topics of protocol v1. */
52
62
  export const TOPIC_SESSION_DELTA = 'session.delta'
@@ -280,6 +290,21 @@ export const CAP_UI = 'ui.v1'
280
290
  */
281
291
  export const CAP_UI_LIST = 'ui.list.v1'
282
292
 
293
+ /**
294
+ * 宿主配了第二会合点时,在 `hello` 的 `capabilities` 里公告的能力名。
295
+ *
296
+ * 它是这条通道的全部门槛,而且门槛落在宿主这一侧:一个配了第二会合点的宿主才
297
+ * 公告这个名字、才收 {@link METHOD_RELAY_GRANT},客户端读到它之后才把授权发过来。
298
+ * 不配第二会合点的宿主——也就是缺省配置的每一台——公告表里没有这个名字,
299
+ * `relay.grant` 对它仍是 `unknown-method`,名册里也不会因此多出一个块:缺省
300
+ * 宿主的握手与名册与这条通道出现之前逐字相同。
301
+ *
302
+ * 正因为它是**条件**公告,{@link MINOR} 不随它抬格:minor 描述的是这个协议本身,
303
+ * 而缺省宿主在线路上读不到任何新东西(设计冻结在 21)。客户端因此按名字判断而不是
304
+ * 按 minor 判断:读不到这个名字就什么都不发。
305
+ */
306
+ export const CAP_RELAY_TIER = 'relay.tier.v1'
307
+
283
308
  /**
284
309
  * Capability a client declares in `hello`'s `cap` array to be answered with
285
310
  * byte-level increments instead of the whole roster or the whole board.
@@ -455,6 +480,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
455
480
  METHOD_SESSION_SET_PERMISSION,
456
481
  METHOD_SESSION_MODELS,
457
482
  METHOD_SESSION_SET_MODEL,
483
+ METHOD_SESSION_SET_EFFORT,
458
484
  METHOD_PAIR_BEGIN,
459
485
  METHOD_PAIR_FINISH,
460
486
  METHOD_APPROVAL_RESOLVE,
@@ -483,6 +509,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
483
509
  METHOD_USAGE_STATS,
484
510
  METHOD_UI_EVENT,
485
511
  METHOD_UI_LIST,
512
+ METHOD_RELAY_GRANT,
486
513
  ])
487
514
 
488
515
  /** Refusal codes the bridge itself raises (DSH failures cross as their own code). */