@linxin666/dsh-remote-bridge 0.4.11 → 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 (61) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +47 -10
  3. package/README.zh.md +47 -10
  4. package/lib/client.js +1 -1
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +18238 -416
  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 +3 -1
  12. package/lib/types/core/push.d.ts +51 -2
  13. package/lib/types/core/turn-end-quiet.d.ts +104 -40
  14. package/lib/types/host/firewall.d.ts +74 -0
  15. package/lib/types/host/host-bind-capability.d.ts +90 -0
  16. package/lib/types/host/ingress-gate.d.ts +59 -0
  17. package/lib/types/host/ingress-sync.d.ts +429 -0
  18. package/lib/types/host/lan-bind-plan.d.ts +96 -0
  19. package/lib/types/host/lan-bind.d.ts +106 -0
  20. package/lib/types/host/lan-forward.d.ts +112 -0
  21. package/lib/types/host/lan.d.ts +61 -0
  22. package/lib/types/host/pair-origin.d.ts +34 -19
  23. package/lib/types/host/relay-bridge-connector.d.ts +215 -0
  24. package/lib/types/host/relay-connector.d.ts +152 -0
  25. package/lib/types/host/relay-control.d.ts +124 -0
  26. package/lib/types/host/relay-registry.d.ts +114 -0
  27. package/lib/types/host/relay.d.ts +170 -0
  28. package/lib/types/host/routes.d.ts +24 -1
  29. package/lib/types/host/tunnel-orphan.d.ts +145 -0
  30. package/lib/types/host/tunnel-plan.d.ts +41 -0
  31. package/lib/types/host/tunnel.d.ts +289 -0
  32. package/lib/types/index.d.ts +440 -11
  33. package/package.json +4 -2
  34. package/src/client/panel.module.css +16 -1
  35. package/src/core/connection.ts +244 -13
  36. package/src/core/devices.ts +31 -6
  37. package/src/core/hub.ts +17 -5
  38. package/src/core/liveactivity.ts +16 -2
  39. package/src/core/model-efforts.ts +223 -0
  40. package/src/core/protocol.ts +4 -1
  41. package/src/core/push.ts +70 -4
  42. package/src/core/turn-end-quiet.ts +281 -98
  43. package/src/host/firewall.ts +230 -0
  44. package/src/host/host-bind-capability.ts +249 -0
  45. package/src/host/ingress-gate.ts +203 -0
  46. package/src/host/ingress-sync.ts +1074 -0
  47. package/src/host/lan-bind-plan.ts +134 -0
  48. package/src/host/lan-bind.ts +250 -0
  49. package/src/host/lan-forward.ts +321 -0
  50. package/src/host/lan.ts +142 -0
  51. package/src/host/pair-origin.ts +44 -38
  52. package/src/host/relay-bridge-connector.ts +783 -0
  53. package/src/host/relay-connector.ts +317 -0
  54. package/src/host/relay-control.ts +224 -0
  55. package/src/host/relay-registry.ts +263 -0
  56. package/src/host/relay.ts +294 -0
  57. package/src/host/routes.ts +47 -3
  58. package/src/host/tunnel-orphan.ts +325 -0
  59. package/src/host/tunnel-plan.ts +58 -0
  60. package/src/host/tunnel.ts +688 -0
  61. package/src/index.ts +1303 -39
@@ -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'
@@ -455,6 +457,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
455
457
  METHOD_SESSION_SET_PERMISSION,
456
458
  METHOD_SESSION_MODELS,
457
459
  METHOD_SESSION_SET_MODEL,
460
+ METHOD_SESSION_SET_EFFORT,
458
461
  METHOD_PAIR_BEGIN,
459
462
  METHOD_PAIR_FINISH,
460
463
  METHOD_APPROVAL_RESOLVE,
@@ -560,7 +563,7 @@ export const CODE_COMMANDS_UNAVAILABLE = 'commands-unavailable'
560
563
  * it is a fact about this bridge, not about what a particular host mounts — and
561
564
  * only a call that needs the domain fails. A refusal the `dsh-agents` plugin
562
565
  * itself raised crosses with the plugin's own code instead (`team-not-found`,
563
- * `member-not-found`, `preset-unknown`, `workspace-required` and their
566
+ * `member-not-found`, `preset-unknown`, `workspace-unavailable` and their
564
567
  * neighbours).
565
568
  */
566
569
  export const CODE_SQUADS_UNAVAILABLE = 'squads-unavailable'
package/src/core/push.ts CHANGED
@@ -30,6 +30,17 @@ import { basename } from 'node:path'
30
30
  /** One thing a notification can be about. */
31
31
  export type PushEvent = 'turn-end' | 'turn-error' | 'question' | 'approval'
32
32
 
33
+ /**
34
+ * Which way this bridge delivers a notification.
35
+ *
36
+ * `direct` signs for APNs with this machine's own Apple key, `relay` asks the
37
+ * hosted service to sign with the one key no deployment may hold, and `off` is a
38
+ * bridge with neither route — the channel's original shape, byte for byte. The two
39
+ * routes are exclusive rather than a fallback chain: a machine holding a key keeps
40
+ * using it, so a developer's delivery never travels through the service.
41
+ */
42
+ export type PushRoute = 'direct' | 'relay' | 'off'
43
+
33
44
  /** Window inside which the same `(sessionId, event)` is one notification. */
34
45
  export const PUSH_DEDUPE_MS = 30_000
35
46
  /** Shortest gap between two notifications about the same session. */
@@ -61,6 +72,14 @@ export interface PushAddress {
61
72
  readonly environment: 'sandbox' | 'production'
62
73
  readonly bundle: string
63
74
  readonly locale?: string
75
+ /**
76
+ * The relay credential that same row registered, when it registered one.
77
+ *
78
+ * Present on the address rather than looked up by the sender so the two routes
79
+ * stay one decision: a row carries the token only in relay mode, and the sender
80
+ * that reads it is the only one this bridge built.
81
+ */
82
+ readonly relayToken?: string
64
83
  }
65
84
 
66
85
  /** The request body one APNs delivery carries (protocol §28.4). */
@@ -79,10 +98,19 @@ export interface PushNotification {
79
98
  /** What one delivery attempt reported. */
80
99
  export interface PushSendResult {
81
100
  readonly ok: boolean
82
- /** The status APNs answered, when it answered at all. */
101
+ /** The status APNs answered, or the relay did, when it answered at all. */
83
102
  readonly status?: number
84
103
  /** The reason APNs named, or this bridge's own note. */
85
104
  readonly reason?: string
105
+ /**
106
+ * Whether the answer said this registration will never work again.
107
+ *
108
+ * APNs says it in a status and a reason this module can read; the relay says it
109
+ * in a count of tokens it just retired, which names no status of its own. The
110
+ * sender that learned it reports the fact here instead of borrowing an APNs
111
+ * status it did not receive.
112
+ */
113
+ readonly dead?: boolean
86
114
  }
87
115
 
88
116
  /** One delivery a sender refused, in the words the bridge needs to read it. */
@@ -93,6 +121,8 @@ export interface PushDeliveryFailure {
93
121
  readonly status?: number
94
122
  /** The reason APNs named, or this bridge's own note. */
95
123
  readonly reason?: string
124
+ /** Whether this failure was final about the registration behind it. */
125
+ readonly dead?: boolean
96
126
  }
97
127
 
98
128
  /** What one {@link PushNotifier.notify} ended up doing, once every attempt settled. */
@@ -114,6 +144,7 @@ export interface PushDeliveryReport {
114
144
  * a claim held for it is a claim held for a phone that cannot come back.
115
145
  */
116
146
  export function isDeadPushToken(failure: PushDeliveryFailure): boolean {
147
+ if (failure.dead === true) return true
117
148
  const reason = failure.reason ?? ''
118
149
  if (reason === 'Unregistered' || reason === 'BadDeviceToken') return true
119
150
  return failure.status === 410
@@ -141,6 +172,18 @@ export interface PushNotifierOptions {
141
172
  readonly targets: () => readonly PushAddress[]
142
173
  /** The sender; absent is a bridge with no signing key, and then nothing happens. */
143
174
  readonly sender?: PushSender
175
+ /**
176
+ * Whether the configured route can reach a phone right now.
177
+ *
178
+ * Absent means "the sender is reason enough", which is what a machine holding its
179
+ * own Apple key is: the key is configured or it is not. The relay has a second
180
+ * fact in front of the credential — some paired row must still hold a relay
181
+ * token — and reading it per event is what keeps a bridge with neither route
182
+ * exactly as inert as one with no key at all.
183
+ */
184
+ readonly available?: () => boolean
185
+ /** Which route this notifier stands on; `direct` by default, as before the relay existed. */
186
+ readonly mode?: PushRoute
144
187
  /** The session's own title (§26's source), read per event. */
145
188
  readonly titles?: (sessionId: string) => string | undefined
146
189
  readonly now?: () => number
@@ -232,9 +275,31 @@ export class PushNotifier {
232
275
  this.#log = options.log ?? (() => undefined)
233
276
  }
234
277
 
235
- /** @returns whether this bridge will actually deliver anything. */
278
+ /**
279
+ * @returns whether this bridge will actually deliver anything.
280
+ *
281
+ * Read by every entrance — a delta path, a claim, a watcher — so a bridge whose
282
+ * route is not armed is indistinguishable from one that never had a channel: no
283
+ * target is read, no clock is consulted and no timer is armed.
284
+ */
236
285
  get enabled(): boolean {
237
- return this.#options.sender !== undefined
286
+ return this.#available() && this.#options.sender !== undefined
287
+ }
288
+
289
+ /** @returns which road a delivery would take: this machine's key or the hosted relay. */
290
+ get mode(): PushRoute {
291
+ return this.#options.mode ?? 'direct'
292
+ }
293
+
294
+ /** @returns whether the route in front of the sender is reachable; a throwing probe reaches nothing. */
295
+ #available(): boolean {
296
+ const available = this.#options.available
297
+ if (available === undefined) return true
298
+ try {
299
+ return available()
300
+ } catch {
301
+ return false
302
+ }
238
303
  }
239
304
 
240
305
  /**
@@ -279,7 +344,7 @@ export class PushNotifier {
279
344
  * was attempted: no sender, no target, or a rate limit that dropped this event.
280
345
  */
281
346
  notify(event: PushEvent, sessionId: string, onReport?: (report: PushDeliveryReport) => void): void {
282
- if (this.#options.sender === undefined) return
347
+ if (!this.enabled) return
283
348
  try {
284
349
  this.#announce(event, sessionId, onReport)
285
350
  } catch (error) {
@@ -330,6 +395,7 @@ export class PushNotifier {
330
395
  deviceToken: target.deviceToken,
331
396
  ...(result.status === undefined ? {} : { status: result.status }),
332
397
  ...(result.reason === undefined ? {} : { reason: result.reason }),
398
+ ...(result.dead === true ? { dead: true } : {}),
333
399
  })
334
400
  })
335
401
  .catch((error: unknown) => {