@linxin666/dsh-remote-bridge 0.4.7 → 0.4.9
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.
- package/README.i18n.yaml +2 -2
- package/README.md +93 -26
- package/README.zh.md +91 -26
- package/icon.svg +3 -0
- package/lib/client.js +274 -253
- package/lib/client.js.map +1 -1
- package/lib/index.js +8891 -2433
- package/lib/types/client/PairEntry.d.ts +2 -2
- package/lib/types/client/PairPanel.d.ts +10 -2
- package/lib/types/client/icons.d.ts +5 -13
- package/lib/types/client/locales.d.ts +10 -14
- package/lib/types/client/semantic.d.ts +9 -5
- package/lib/types/core/approvals.d.ts +24 -0
- package/lib/types/core/commands.d.ts +59 -0
- package/lib/types/core/connection.d.ts +124 -5
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +98 -2
- package/lib/types/core/dsh-frames.d.ts +155 -4
- package/lib/types/core/envelope.d.ts +34 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/hub.d.ts +96 -20
- package/lib/types/core/jobs.d.ts +204 -0
- package/lib/types/core/liveactivity.d.ts +324 -0
- package/lib/types/core/protocol.d.ts +491 -2
- package/lib/types/core/push.d.ts +178 -0
- package/lib/types/core/questions.d.ts +109 -9
- package/lib/types/core/session-meta.d.ts +55 -1
- package/lib/types/core/squads.d.ts +130 -0
- package/lib/types/core/usage-stats.d.ts +160 -0
- package/lib/types/core/usage.d.ts +294 -0
- package/lib/types/core/wire.d.ts +1 -1
- package/lib/types/core/ws-frames.d.ts +11 -0
- package/lib/types/host/apns.d.ts +151 -0
- package/lib/types/host/squads-ledger.d.ts +39 -0
- package/lib/types/host/squads.d.ts +77 -0
- package/lib/types/host/usage-stats.d.ts +75 -0
- package/lib/types/host/watchers.d.ts +88 -0
- package/lib/types/host/websocket.d.ts +8 -1
- package/lib/types/index.d.ts +34 -3
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +20 -14
- package/src/client/PairEntry.tsx +58 -31
- package/src/client/PairPanel.tsx +181 -97
- package/src/client/icons.tsx +17 -60
- package/src/client/locales.ts +15 -23
- package/src/client/panel.module.css +239 -186
- package/src/client/semantic.ts +10 -6
- package/src/core/approvals.ts +32 -1
- package/src/core/commands.ts +95 -0
- package/src/core/connection.ts +1483 -31
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +221 -3
- package/src/core/dsh-frames.ts +365 -8
- package/src/core/envelope.ts +46 -0
- package/src/core/extension.ts +197 -0
- package/src/core/hub.ts +441 -49
- package/src/core/jobs.ts +372 -0
- package/src/core/liveactivity.ts +833 -0
- package/src/core/protocol.ts +556 -2
- package/src/core/push.ts +354 -0
- package/src/core/questions.ts +264 -17
- package/src/core/session-meta.ts +73 -1
- package/src/core/squads.ts +345 -0
- package/src/core/usage-stats.ts +424 -0
- package/src/core/usage.ts +937 -0
- package/src/core/wire.ts +13 -1
- package/src/core/ws-frames.ts +14 -0
- package/src/host/apns.ts +320 -0
- package/src/host/squads-ledger.ts +105 -0
- package/src/host/squads.ts +206 -0
- package/src/host/usage-stats.ts +155 -0
- package/src/host/watchers.ts +272 -0
- package/src/host/websocket.ts +37 -3
- package/src/index.ts +310 -9
- package/src/mount-once.ts +142 -0
package/src/host/websocket.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import type { IncomingMessage } from 'node:http'
|
|
13
13
|
import type { Duplex } from 'node:stream'
|
|
14
14
|
import type { BridgeTransport, ConnectionAuth } from '../core/connection.ts'
|
|
15
|
-
import { MAX_FRAME_BYTES } from '../core/envelope.ts'
|
|
15
|
+
import { MAX_FRAME_BYTES, outboundPayloadOf } from '../core/envelope.ts'
|
|
16
16
|
import type { BridgeHub } from '../core/hub.ts'
|
|
17
17
|
import {
|
|
18
18
|
CLOSE_PROTOCOL_ERROR,
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
OPCODE_PING,
|
|
25
25
|
OPCODE_PONG,
|
|
26
26
|
OPCODE_TEXT,
|
|
27
|
+
encodeBinaryFrame,
|
|
27
28
|
encodeCloseFrame,
|
|
28
29
|
encodeServerFrame,
|
|
29
30
|
encodeTextFrame,
|
|
@@ -105,6 +106,25 @@ export function refuseUpgrade(socket: Duplex, status: number, reason: string): v
|
|
|
105
106
|
socket.end(`HTTP/1.1 ${status} ${reason}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`)
|
|
106
107
|
}
|
|
107
108
|
|
|
109
|
+
/** The Nagle switch a `net.Socket` carries; the bare duplexes of a suite need not have one. */
|
|
110
|
+
interface DelayableSocket extends Duplex {
|
|
111
|
+
setNoDelay?: (noDelay: boolean) => void
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Ask the kernel to write each frame out as it is handed over.
|
|
116
|
+
*
|
|
117
|
+
* Every frame on this route is already one whole application message, and a
|
|
118
|
+
* phone pays a round trip for each answer, so Nagle's coalescing window only
|
|
119
|
+
* delays bytes that nothing else is waiting to join. It is set on acceptance
|
|
120
|
+
* because that is the last moment the socket is still ours alone: once the
|
|
121
|
+
* upgrade has been answered, a peer's frame can already be on the way.
|
|
122
|
+
*/
|
|
123
|
+
function stopNagleDelay(socket: Duplex): void {
|
|
124
|
+
const delayable: DelayableSocket = socket
|
|
125
|
+
if (typeof delayable.setNoDelay === 'function') delayable.setNoDelay(true)
|
|
126
|
+
}
|
|
127
|
+
|
|
108
128
|
/**
|
|
109
129
|
* One accepted upgrade handed to the bridge.
|
|
110
130
|
*/
|
|
@@ -134,6 +154,7 @@ export interface UpgradeHandoff {
|
|
|
134
154
|
*/
|
|
135
155
|
export function serveUpgrade(handoff: UpgradeHandoff): WebSocketCarrier {
|
|
136
156
|
const { socket, secWebSocketKey, head, hub, auth } = handoff
|
|
157
|
+
stopNagleDelay(socket)
|
|
137
158
|
const carrier = new WebSocketCarrier(socket)
|
|
138
159
|
carrier.handshake(secWebSocketKey)
|
|
139
160
|
const connection = hub.attach(carrier, auth)
|
|
@@ -162,6 +183,8 @@ export class WebSocketCarrier implements BridgeTransport {
|
|
|
162
183
|
#closed = false
|
|
163
184
|
#onMessage: ((text: string) => void) | undefined
|
|
164
185
|
#onClose: (() => void) | undefined
|
|
186
|
+
/** Whether the peer declared it can inflate a compressed frame; see {@link frameDeflate}. */
|
|
187
|
+
#deflate = false
|
|
165
188
|
/** Messages that arrived before a handler was registered; see {@link deliver}. */
|
|
166
189
|
readonly #pending: string[] = []
|
|
167
190
|
|
|
@@ -219,10 +242,21 @@ export class WebSocketCarrier implements BridgeTransport {
|
|
|
219
242
|
}
|
|
220
243
|
}
|
|
221
244
|
|
|
222
|
-
/**
|
|
245
|
+
/**
|
|
246
|
+
* Record the peer's `frame.deflate.v1` declaration, as `hello` reported it.
|
|
247
|
+
*
|
|
248
|
+
* It defaults to off, so a connection that never declares the capability keeps
|
|
249
|
+
* the text frame this carrier always wrote, byte for byte.
|
|
250
|
+
*/
|
|
251
|
+
frameDeflate(declared: boolean): void {
|
|
252
|
+
this.#deflate = declared
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Send one frame: the text itself, or raw DEFLATE of it as a binary frame. */
|
|
223
256
|
send(text: string): void {
|
|
224
257
|
if (this.#closed) return
|
|
225
|
-
this.#
|
|
258
|
+
const payload = outboundPayloadOf(text, this.#deflate)
|
|
259
|
+
this.#socket.write(payload.binary ? encodeBinaryFrame(payload.deflated) : encodeTextFrame(payload.text))
|
|
226
260
|
}
|
|
227
261
|
|
|
228
262
|
/** Send a close frame and end the socket. Idempotent. */
|
package/src/index.ts
CHANGED
|
@@ -16,8 +16,11 @@
|
|
|
16
16
|
* - `user-questions/request` is claimed the same way and published as
|
|
17
17
|
* `question.request` to the devices that declared `questions.v1`; their
|
|
18
18
|
* `question.answer` settles the host's own ask while it is open, or reaches a
|
|
19
|
-
* continued question through the host's Remote `answer`.
|
|
20
|
-
*
|
|
19
|
+
* continued question through the host's Remote `answer`. With no paired
|
|
20
|
+
* connection on the wire the claim is still made when a roster device registered
|
|
21
|
+
* for notifications, which is reached by the alert and holds the question for one
|
|
22
|
+
* window before it goes back to the host's chain (§11.3, §32). Every other case
|
|
23
|
+
* delegates, and a timed question keeps the Host's own deadline.
|
|
21
24
|
*
|
|
22
25
|
* The browser half lives in `src/client/` and is declared by `dsh.client`: one
|
|
23
26
|
* sidebar-foot panel that reads the same loopback-gated token route over a
|
|
@@ -38,15 +41,28 @@ import type {} from '@deepseek-ai/dsh-user-approval'
|
|
|
38
41
|
import { ApprovalRegistry } from './core/approvals.ts'
|
|
39
42
|
import type { ConnectionAuth } from './core/connection.ts'
|
|
40
43
|
import { DeviceRoster } from './core/devices.ts'
|
|
41
|
-
import {
|
|
44
|
+
import { createRemoteBridgeFace, RemoteBridgeRegistry, REMOTE_BRIDGE_SERVICE } from './core/extension.ts'
|
|
45
|
+
import { JobRoster, type JobRegistryFace } from './core/jobs.ts'
|
|
46
|
+
import { BridgeHub, OFFLINE_QUESTION_CLAIM_TTL_MS } from './core/hub.ts'
|
|
42
47
|
import { createOwnerPeer } from './core/owner-peer.ts'
|
|
43
48
|
import { PairingService } from './core/pairing.ts'
|
|
49
|
+
import { LiveActivityNotifier } from './core/liveactivity.ts'
|
|
50
|
+
import { PushNotifier } from './core/push.ts'
|
|
44
51
|
import { QuestionClaims } from './core/questions.ts'
|
|
45
52
|
import { WS_PATH } from './core/protocol.ts'
|
|
46
|
-
import { SessionMeta, type
|
|
53
|
+
import { SessionMeta, type SessionStoreFace, type SessionTitleFace, type WorkspacesFace } from './core/session-meta.ts'
|
|
47
54
|
import { SessionPermissions, type ApprovalPolicyFace, type PermissionPresetsFace, type SandboxPolicyFace } from './core/session-permissions.ts'
|
|
55
|
+
import { selectionOf, modelSelectionOf } from './core/connection.ts'
|
|
56
|
+
import { UsageService, type CredentialStoreFace, type SessionRosterFace, type SessionRouteFace, type SettingsFace } from './core/usage.ts'
|
|
57
|
+
import { UsageStatsReader } from './core/usage-stats.ts'
|
|
58
|
+
import { wireArgs, type GatewayPeer } from './core/wire.ts'
|
|
48
59
|
import { dshHome } from './host/dsh-home.ts'
|
|
60
|
+
import { ApnsSender, apnsConfigFromEnv } from './host/apns.ts'
|
|
61
|
+
import { StandingWatchers } from './host/watchers.ts'
|
|
62
|
+
import { LoopbackSquads } from './host/squads.ts'
|
|
63
|
+
import { mountOnce } from './mount-once.ts'
|
|
49
64
|
import { makePairTokenRoute } from './host/routes.ts'
|
|
65
|
+
import { hostWebOrigin, LoopbackUsage } from './host/usage-stats.ts'
|
|
50
66
|
import { isWebSocketUpgrade, presentedTokenOf, readSecWebSocketKey, refuseUpgrade, serveUpgrade } from './host/websocket.ts'
|
|
51
67
|
|
|
52
68
|
/** Loader row identity of this plugin. */
|
|
@@ -58,6 +74,24 @@ export const inject = ['typertGateway', 'webServer']
|
|
|
58
74
|
/** Where the paired-device roster lives inside the DSH home. */
|
|
59
75
|
export const ROSTER_PATH = 'remote-bridge/devices.json'
|
|
60
76
|
|
|
77
|
+
/** The environment variable that moves the offline claim window (§32.2). */
|
|
78
|
+
export const OFFLINE_CLAIM_TTL_ENV = 'DSH_REMOTE_BRIDGE_OFFLINE_CLAIM_TTL_MS'
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The offline claim window this process runs with.
|
|
82
|
+
*
|
|
83
|
+
* The window is the bridge's own constant and never a host fact, so a deployment
|
|
84
|
+
* moves it here. A value that is missing, unreadable or not positive falls back to
|
|
85
|
+
* the constant instead of closing the window: a zero window would silently switch
|
|
86
|
+
* the channel off, and an operator who wanted that would be turning off push.
|
|
87
|
+
* @param env - the process environment, injectable for a suite.
|
|
88
|
+
* @returns the window in milliseconds.
|
|
89
|
+
*/
|
|
90
|
+
export function offlineClaimTtl(env: NodeJS.ProcessEnv = process.env): number {
|
|
91
|
+
const configured = Number(env[OFFLINE_CLAIM_TTL_ENV])
|
|
92
|
+
return Number.isFinite(configured) && configured > 0 ? configured : OFFLINE_QUESTION_CLAIM_TTL_MS
|
|
93
|
+
}
|
|
94
|
+
|
|
61
95
|
/** This machine's IANA time zone, or undefined when the platform has none. */
|
|
62
96
|
function localTimeZone(): string | undefined {
|
|
63
97
|
try {
|
|
@@ -112,20 +146,130 @@ function makeUpgradeHandler(hub: BridgeHub, roster: DeviceRoster, log: (message:
|
|
|
112
146
|
/**
|
|
113
147
|
* Resolve the host services session metadata is read from, now.
|
|
114
148
|
*
|
|
115
|
-
* All
|
|
116
|
-
*
|
|
149
|
+
* All of them are read per call rather than captured at mount: none is in this
|
|
150
|
+
* plugin's `inject` list, because requiring them would let the title or
|
|
117
151
|
* workspace plugin's absence take the whole bridge down with it. An unmounted
|
|
118
152
|
* service simply reads as undefined, and the protocol degrades one key of one
|
|
119
153
|
* row instead of failing a method. The faces are structural — this package
|
|
120
154
|
* imports no part of those services' own types.
|
|
155
|
+
*
|
|
156
|
+
* One registry answers two faces: `archive` is the slice a roster row reads and
|
|
157
|
+
* `workspaces` the wider slice `workspace.list` publishes, so a single lookup
|
|
158
|
+
* serves both and a host either composes a registry or composes none.
|
|
121
159
|
* @param ctx - the plugin's context.
|
|
122
160
|
* @returns the metadata faces as they stand right now.
|
|
123
161
|
*/
|
|
124
162
|
function sessionMetaFaces(ctx: Context) {
|
|
163
|
+
const registry = ctx.get('workspaceRegistry') as WorkspacesFace | undefined
|
|
125
164
|
return {
|
|
126
165
|
sessions: ctx.get('sessions') as SessionStoreFace | undefined,
|
|
127
166
|
titles: ctx.get('sessionTitle') as SessionTitleFace | undefined,
|
|
128
|
-
archive:
|
|
167
|
+
archive: registry,
|
|
168
|
+
workspaces: registry,
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 宿主自己的会话名册,按 `usage.session` 需要的那一格读出来。
|
|
174
|
+
*
|
|
175
|
+
* 走的是 `session.list` 服务的同一个端点(`session/list`),也就是手机名册的
|
|
176
|
+
* 来源:它名下既有活的会话,也有本进程没观察过、当前也不 live 的会话,因此
|
|
177
|
+
* 那类会话不会被说成不存在。`ctx.sessions.list()` 答不了这一问——它只列已经
|
|
178
|
+
* 进入存储的会话。读失败或答不出 item 表就回 undefined,「不知道名册」由用量
|
|
179
|
+
* 服务退回活会话存储与事件折叠两条证词。
|
|
180
|
+
* @param ctx - 插件的上下文,携带网关。
|
|
181
|
+
* @param peer - 本桥自己的 owner peer,每次调用都以它发声。
|
|
182
|
+
* @param log - 读不到名册时的落点。
|
|
183
|
+
* @returns 名册 face。
|
|
184
|
+
*/
|
|
185
|
+
function sessionRoster(ctx: Context, peer: GatewayPeer, log: (message: string) => void): SessionRosterFace {
|
|
186
|
+
return {
|
|
187
|
+
ids: async (): Promise<readonly string[] | undefined> => {
|
|
188
|
+
try {
|
|
189
|
+
const value = await ctx.typertGateway.invoke({
|
|
190
|
+
namespace: 'session',
|
|
191
|
+
method: 'list',
|
|
192
|
+
args: wireArgs('session', 'list', {}),
|
|
193
|
+
peer,
|
|
194
|
+
})
|
|
195
|
+
const items = typeof value === 'object' && value !== null ? (value as { items?: unknown }).items : undefined
|
|
196
|
+
if (!Array.isArray(items)) return undefined
|
|
197
|
+
const ids: string[] = []
|
|
198
|
+
for (const item of items) {
|
|
199
|
+
const id = typeof item === 'object' && item !== null ? (item as { sessionId?: unknown }).sessionId : undefined
|
|
200
|
+
if (typeof id === 'string' && id !== '') ids.push(id)
|
|
201
|
+
}
|
|
202
|
+
return ids
|
|
203
|
+
} catch (error) {
|
|
204
|
+
log(`the host session roster could not be read: ${String(error)}`)
|
|
205
|
+
return undefined
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 一条会话此刻的路由,按 `usage.session` 的模型窗口那一档读出来。
|
|
213
|
+
*
|
|
214
|
+
* 折叠与 `session.models` 的 `current` 逐字一致:下一步的选择、其次是用过的那个、
|
|
215
|
+
* 最后才是目录默认。两个方法读同一个折叠,就不可能出现「模型选择器说 A、模型窗口
|
|
216
|
+
* 按 B 算」这种事。每次读都走本桥自己的 owner peer;读不到任何一档就回 undefined,
|
|
217
|
+
* 那一档读数(`modelContextWindow`)因此根本不出现,而不是补一个默认值。
|
|
218
|
+
* @param ctx - 插件的上下文,携带网关。
|
|
219
|
+
* @param peer - 本桥自己的 owner peer,每次调用都以它发声。
|
|
220
|
+
* @param log - 读不到时记一行日志。
|
|
221
|
+
* @returns 路由 face。
|
|
222
|
+
*/
|
|
223
|
+
function sessionRoute(ctx: Context, peer: GatewayPeer, log: (message: string) => void): SessionRouteFace {
|
|
224
|
+
const invoke = async (method: string, args: Readonly<Record<string, unknown>>): Promise<unknown> => await ctx.typertGateway.invoke({
|
|
225
|
+
namespace: 'session',
|
|
226
|
+
method,
|
|
227
|
+
args: wireArgs('session', method, args),
|
|
228
|
+
peer,
|
|
229
|
+
})
|
|
230
|
+
return {
|
|
231
|
+
current: async (sessionId: string) => {
|
|
232
|
+
try {
|
|
233
|
+
const folded = modelSelectionOf(await invoke('projections', { sessionId }))
|
|
234
|
+
const selected = folded.next ?? folded.lastUsed
|
|
235
|
+
// 还没选过模型的会话在目录默认上——它下一步就会用那个,也正是
|
|
236
|
+
// `session.models` 对同一条会话给出的答案。
|
|
237
|
+
const fallback = selected === undefined ? selectionOf(catalogDefaultOf(await invoke('modelCatalog', {}))) : undefined
|
|
238
|
+
const answer = selected ?? fallback
|
|
239
|
+
return answer === undefined ? undefined : { provider: answer.provider, model: answer.model }
|
|
240
|
+
} catch (error) {
|
|
241
|
+
log(`the route of session ${sessionId} could not be read: ${String(error)}`)
|
|
242
|
+
return undefined
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** `session/modelCatalog` 里的 `default` 一格。 */
|
|
249
|
+
function catalogDefaultOf(value: unknown): unknown {
|
|
250
|
+
return typeof value === 'object' && value !== null ? (value as { default?: unknown }).default : undefined
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 解析 `usage.v1` 要读的宿主服务,现在就解析一次。
|
|
255
|
+
*
|
|
256
|
+
* 与元数据的三个 face 同一条理由:四者都不在本插件的 `inject` 里,缺一个不该
|
|
257
|
+
* 让整个桥起不来。缺活会话存储,`usage.session` 就只能靠名册与本进程观察过的
|
|
258
|
+
* 事件判断会话是否存在;缺凭据服务,`usage.balance` 回 `no-credential`;缺设置
|
|
259
|
+
* 服务,路由的 `baseURL` 与 `apiKeyEnv` 读不到,origin 判定与凭据回退都退回
|
|
260
|
+
* 官方默认值。face 是结构化的:本包不导入这些服务自己的类型。
|
|
261
|
+
* @param ctx - 插件的上下文。
|
|
262
|
+
* @param peer - 本桥自己的 owner peer,名册读取以它发声。
|
|
263
|
+
* @param log - 读不到名册时的落点。
|
|
264
|
+
* @returns 这些 face 此刻的样子。
|
|
265
|
+
*/
|
|
266
|
+
function usageFaces(ctx: Context, peer: GatewayPeer, log: (message: string) => void) {
|
|
267
|
+
return {
|
|
268
|
+
sessions: ctx.get('sessions') as SessionStoreFace | undefined,
|
|
269
|
+
roster: sessionRoster(ctx, peer, log),
|
|
270
|
+
credentials: ctx.get('credentials') as CredentialStoreFace | undefined,
|
|
271
|
+
settings: ctx.get('settings') as SettingsFace | undefined,
|
|
272
|
+
route: sessionRoute(ctx, peer, log),
|
|
129
273
|
}
|
|
130
274
|
}
|
|
131
275
|
|
|
@@ -150,11 +294,35 @@ function permissionFaces(ctx: Context) {
|
|
|
150
294
|
}
|
|
151
295
|
}
|
|
152
296
|
|
|
297
|
+
/**
|
|
298
|
+
* Resolve the host's job registry, now.
|
|
299
|
+
*
|
|
300
|
+
* Read per call, never captured at mount, for the reason the metadata faces
|
|
301
|
+
* are: `jobs` is not in this plugin's `inject` list, so a host that composes
|
|
302
|
+
* no job plugin still serves protocol v1 — `jobs.list` answers
|
|
303
|
+
* `jobs-unavailable` instead of the bridge failing to start. The face is
|
|
304
|
+
* structural: this package imports no part of the registry's own types.
|
|
305
|
+
* @param ctx - the plugin's context.
|
|
306
|
+
* @returns the job faces as they stand right now.
|
|
307
|
+
*/
|
|
308
|
+
function jobFaces(ctx: Context) {
|
|
309
|
+
return {
|
|
310
|
+
jobs: ctx.get('jobs') as JobRegistryFace | undefined,
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
153
314
|
/**
|
|
154
315
|
* Mount the bridge.
|
|
316
|
+
*
|
|
317
|
+
* Guarded by the family's single-instance rule: the aggregate row
|
|
318
|
+
* (`web-ui-remote-bridge`) and a standalone install of this same package can
|
|
319
|
+
* both be live in one profile, and the second mount would otherwise register
|
|
320
|
+
* `/ios/v1` and the token route a second time. Whichever source mounts first
|
|
321
|
+
* owns the package name; the other is queued and replayed when that owner
|
|
322
|
+
* disposes.
|
|
155
323
|
* @param ctx - the plugin's context, carrying the gateway and web server.
|
|
156
324
|
*/
|
|
157
|
-
|
|
325
|
+
function applyImpl(ctx: Context): void {
|
|
158
326
|
const log = (message: string): void => { console.log(`[remote-bridge] ${message}`) }
|
|
159
327
|
const roster = new DeviceRoster({ file: join(dshHome(), ROSTER_PATH), log })
|
|
160
328
|
const pairing = new PairingService()
|
|
@@ -164,37 +332,162 @@ export function apply(ctx: Context): void {
|
|
|
164
332
|
// it is gated by the bridge's own pairing check (see core/owner-peer.ts).
|
|
165
333
|
const ownerPeer = createOwnerPeer(ctx)
|
|
166
334
|
const questions = new QuestionClaims({ gateway: ctx.typertGateway, peer: ownerPeer, log })
|
|
335
|
+
// One roster per mount, shared by every connection: a background job is a fact
|
|
336
|
+
// about the host, not about the device that asked about it.
|
|
337
|
+
const jobs = new JobRoster({ faces: () => jobFaces(ctx), log })
|
|
167
338
|
const sessionMeta = new SessionMeta(() => sessionMetaFaces(ctx), () => Date.now(), log)
|
|
339
|
+
// 用量读数:一条会话的窗口与组成靠宿主广播的事件折出来,余额靠宿主自己的
|
|
340
|
+
// 凭据与设置查出来。一个宿主一份、所有连接共享——两台手机重复问,上游也只
|
|
341
|
+
// 该收到一次请求(core/usage.ts)。
|
|
342
|
+
// 台账聚合读的是宿主上 dsh-usage 插件的两条 HTTP 路由,走本机回环 origin:那个
|
|
343
|
+
// 插件不发布任何 cordis 服务,端口从 `webServer` 来(先 getOrigin(),拿不到再退回
|
|
344
|
+
// 监听端口)。没有它时 `usage.stats` 答 no-usage-plugin,其余读数一概不变。
|
|
345
|
+
const usageRoutes = new LoopbackUsage({ origin: () => hostWebOrigin(ctx.webServer), log })
|
|
346
|
+
const usageStats = new UsageStatsReader({ transport: () => usageRoutes, now: () => Date.now(), log })
|
|
347
|
+
const usage = new UsageService({ faces: () => usageFaces(ctx, ownerPeer, log), now: () => Date.now(), stats: usageStats, log })
|
|
348
|
+
// The push channel is OFF unless this machine holds an Apple signing key: no
|
|
349
|
+
// key, no sender, and every notification path is a no-op — which is what keeps
|
|
350
|
+
// the protocol byte-identical for every deployment that has none (§28).
|
|
351
|
+
const apns = apnsConfigFromEnv()
|
|
352
|
+
// One client for both channels: an APNs provider token is minted per key and
|
|
353
|
+
// then reused, so a second client would only double the mint rate Apple
|
|
354
|
+
// throttles (core/push.ts, host/apns.ts).
|
|
355
|
+
const apnsSender = apns === undefined ? undefined : new ApnsSender({ config: apns, log })
|
|
356
|
+
const push = new PushNotifier({
|
|
357
|
+
targets: () => roster.pushTargets().map(({ push: registration }) => ({
|
|
358
|
+
deviceToken: registration.deviceToken,
|
|
359
|
+
environment: registration.environment,
|
|
360
|
+
bundle: registration.bundle,
|
|
361
|
+
...(registration.locale === undefined ? {} : { locale: registration.locale }),
|
|
362
|
+
})),
|
|
363
|
+
...(apnsSender === undefined ? {} : { sender: apnsSender }),
|
|
364
|
+
titles: id => sessionMeta.title(id),
|
|
365
|
+
now: () => Date.now(),
|
|
366
|
+
log,
|
|
367
|
+
})
|
|
368
|
+
// The lock-screen card path (§29). It reads the same roster, through the same
|
|
369
|
+
// client, and is inert for exactly the same reason: no key, no sender, no card.
|
|
370
|
+
// A token APNs reports dead is dropped from its device row here, which is the
|
|
371
|
+
// whole of the recovery — the next card registers a fresh one.
|
|
372
|
+
const liveActivity = new LiveActivityNotifier({
|
|
373
|
+
targets: () => roster.pushTargets().flatMap(({ push: registration }) => (registration.liveActivityTokens ?? []).map(({ activityId, token, sessionId }) => ({
|
|
374
|
+
activityId,
|
|
375
|
+
token,
|
|
376
|
+
// The session is the card's address (§29.9). A registration written before
|
|
377
|
+
// that field existed simply has none, and its card is never pushed to.
|
|
378
|
+
...(sessionId === undefined ? {} : { sessionId }),
|
|
379
|
+
environment: registration.environment,
|
|
380
|
+
bundle: registration.bundle,
|
|
381
|
+
}))),
|
|
382
|
+
...(apnsSender === undefined ? {} : { sender: apnsSender }),
|
|
383
|
+
now: () => Date.now(),
|
|
384
|
+
log,
|
|
385
|
+
retire: async (activityId, token) => {
|
|
386
|
+
const dropped = await roster.removeLiveActivityToken(activityId, token)
|
|
387
|
+
// A dead token is a roster change like any other: the session it named may
|
|
388
|
+
// have just lost its last card, and a watcher for it must close.
|
|
389
|
+
if (dropped) watchers.sync()
|
|
390
|
+
return dropped
|
|
391
|
+
},
|
|
392
|
+
})
|
|
393
|
+
// The bridge's own follow streams (§28/§29): a suspended phone has no socket,
|
|
394
|
+
// so the turn end its card has to show would otherwise be seen by nobody. One
|
|
395
|
+
// watcher per session that still holds a card token, armed from the roster and
|
|
396
|
+
// never from a client frame.
|
|
397
|
+
const watchedSessions = (): readonly string[] => {
|
|
398
|
+
const sessions = new Set<string>()
|
|
399
|
+
for (const { push: registration } of roster.pushTargets()) {
|
|
400
|
+
for (const token of registration.liveActivityTokens ?? []) {
|
|
401
|
+
if (token.sessionId !== undefined) sessions.add(token.sessionId)
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return [...sessions]
|
|
405
|
+
}
|
|
406
|
+
const watchers = new StandingWatchers({
|
|
407
|
+
gateway: ctx.typertGateway,
|
|
408
|
+
peer: ownerPeer,
|
|
409
|
+
sessions: watchedSessions,
|
|
410
|
+
...(apnsSender === undefined ? {} : { liveActivity, push }),
|
|
411
|
+
log,
|
|
412
|
+
})
|
|
168
413
|
const permissions = new SessionPermissions(() => permissionFaces(ctx), log)
|
|
414
|
+
// The extension seam publishes no protocol vocabulary of its own: another
|
|
415
|
+
// plugin registers the method names, payloads and topics it owns, and this
|
|
416
|
+
// package only dispatches and fans out what it was handed.
|
|
417
|
+
// The squad domain of the `dsh-agents` plugin is read over this host's own
|
|
418
|
+
// loopback origin: that plugin serves its routes on the very web server this
|
|
419
|
+
// bridge already injects. Both the origin and the ledger directory are resolved
|
|
420
|
+
// per call — the listener may not have bound a port when this row mounts, and a
|
|
421
|
+
// DSH home is not a fact to capture once.
|
|
422
|
+
const squads = new LoopbackSquads({
|
|
423
|
+
origin: () => {
|
|
424
|
+
try {
|
|
425
|
+
return ctx.webServer.getOrigin()
|
|
426
|
+
} catch {
|
|
427
|
+
return undefined
|
|
428
|
+
}
|
|
429
|
+
},
|
|
430
|
+
ledgerDirectory: () => join(dshHome(), 'dsh-agents'),
|
|
431
|
+
log,
|
|
432
|
+
})
|
|
433
|
+
const extensions = new RemoteBridgeRegistry()
|
|
434
|
+
// 离线认领的窗口归桥所有,宿主从不认识它(§32.2):常量是默认值,部署可用环境变量覆盖。
|
|
435
|
+
const offlineClaimTtlMs = offlineClaimTtl()
|
|
169
436
|
const hub = new BridgeHub({
|
|
437
|
+
extensions,
|
|
170
438
|
gateway: ctx.typertGateway,
|
|
171
439
|
pairing,
|
|
172
440
|
roster,
|
|
173
441
|
approvals,
|
|
174
442
|
questions,
|
|
443
|
+
jobs,
|
|
175
444
|
sessionMeta,
|
|
445
|
+
usage,
|
|
176
446
|
permissions,
|
|
177
447
|
ownerPeer,
|
|
448
|
+
squads,
|
|
449
|
+
push,
|
|
450
|
+
liveActivity,
|
|
451
|
+
offlineClaimTtlMs,
|
|
452
|
+
onPushRegistered: () => { watchers.sync() },
|
|
178
453
|
now: () => Date.now(),
|
|
179
454
|
clientTimeZone: localTimeZone,
|
|
180
455
|
log,
|
|
181
456
|
})
|
|
182
457
|
|
|
458
|
+
// A capture-only test context implements no service registry; a Host always
|
|
459
|
+
// does. Without it the bridge still serves protocol v1, minus other plugins'
|
|
460
|
+
// methods, which is exactly what not publishing the seam means.
|
|
461
|
+
if (typeof (ctx as { provide?: unknown }).provide === 'function') {
|
|
462
|
+
ctx.provide(REMOTE_BRIDGE_SERVICE, createRemoteBridgeFace(extensions, hub))
|
|
463
|
+
}
|
|
464
|
+
|
|
183
465
|
ctx.effect(() => {
|
|
184
|
-
|
|
466
|
+
// A registration that arrived before this row mounted is still on disk: the
|
|
467
|
+
// watchers are reconciled from what the roster holds, not from what a live
|
|
468
|
+
// connection happened to send.
|
|
469
|
+
void roster.load().then(() => { watchers.sync() }).catch(() => undefined)
|
|
185
470
|
const disposeUpgrade = ctx.webServer.registerUpgrade({
|
|
186
471
|
path: WS_PATH,
|
|
187
472
|
handler: makeUpgradeHandler(hub, roster, log),
|
|
188
473
|
})
|
|
189
474
|
const disposeRoute = ctx.webServer.register(makePairTokenRoute({ pairing, log }))
|
|
190
475
|
log(`protocol v1 listening on ${WS_PATH}`)
|
|
476
|
+
log(apns === undefined
|
|
477
|
+
? `push: off (set ${'DSH_REMOTE_BRIDGE_APNS_KEY_FILE'}, ${'DSH_REMOTE_BRIDGE_APNS_KEY_ID'} and ${'DSH_REMOTE_BRIDGE_APNS_TEAM_ID'} to enable APNs)`
|
|
478
|
+
: `push: on (APNs key ${apns.keyId} of team ${apns.teamId})`)
|
|
191
479
|
return () => {
|
|
192
480
|
disposeUpgrade()
|
|
193
481
|
disposeRoute()
|
|
482
|
+
watchers.dispose()
|
|
194
483
|
hub.dispose()
|
|
484
|
+
jobs.dispose()
|
|
195
485
|
}
|
|
196
486
|
}, 'remote-bridge: protocol v1 routes')
|
|
197
487
|
|
|
488
|
+
// 会话事件是 `usage.session` 唯一的来源:桥不读会话日志、也不回填历史,所以
|
|
489
|
+
// 这个监听器挂上之前广播的事件不会有读数,宿主没广播过的窗口也不会被编出来。
|
|
490
|
+
ctx.on('session/event', (session, event) => { usage.record(session.id, event) })
|
|
198
491
|
ctx.on('approval/request', (request, next) => hub.approve(request, next))
|
|
199
492
|
// Prepended: the host's waterfall is first-come, and the desktop client's own
|
|
200
493
|
// answerer would otherwise claim every question before this listener is
|
|
@@ -203,3 +496,11 @@ export function apply(ctx: Context): void {
|
|
|
203
496
|
// first answer settles it.
|
|
204
497
|
ctx.on('user-questions/request', (request, next) => hub.question(request, next), { prepend: true })
|
|
205
498
|
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* The plugin's mount point: {@link applyImpl} behind the family's
|
|
502
|
+
* single-instance guard. The name is the npm package identity, which every
|
|
503
|
+
* install source of this plugin shares — the aggregate's `web-ui-remote-bridge`
|
|
504
|
+
* row and the standalone `remote-bridge` row alike.
|
|
505
|
+
*/
|
|
506
|
+
export const apply = mountOnce('@linxin666/dsh-remote-bridge', applyImpl)
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Generated by scripts/sync-shared.mjs from shared/host/mount-once.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
|
|
2
|
+
/**
|
|
3
|
+
* Host single-instance guard shared by the plugin family. The family bundle
|
|
4
|
+
* (dsh-web-all / dsh-skins) namespaces every child row id (web-ui-*), so
|
|
5
|
+
* the loader accepts a standalone install of the same package side by side;
|
|
6
|
+
* without this guard the second instance would still re-register the same
|
|
7
|
+
* webserver routes, tools, settings namespaces, and system-prompt sections
|
|
8
|
+
* and fail the boot. mountOnce makes a mount of an already-mounted package a
|
|
9
|
+
* no-op for as long as the first instance lives (the browser half is already
|
|
10
|
+
* deduped by package name in the client module host).
|
|
11
|
+
*
|
|
12
|
+
* A no-op is only safe while the holder is ALIVE. The holder can be disposed
|
|
13
|
+
* long after the refused mount ran its course: the Host reloads a profile by
|
|
14
|
+
* creating the new loader entries before the old ones are torn down (a
|
|
15
|
+
* plugin-manager enable/disable/install write, a settings-driven row reload,
|
|
16
|
+
* HMR), so the new aggregate shell entry mounts its family plugin while the
|
|
17
|
+
* previous entry still owns the name. Dropping that refused mount lost the
|
|
18
|
+
* plugin for good - the previous entry then disposed its own mount, releasing
|
|
19
|
+
* the name with nobody left to take it, and the family row stayed listed as
|
|
20
|
+
* active while its host routes 404ed (the task-board panel showed
|
|
21
|
+
* "board.hostError.notMounted", no degraded record appeared, and only a Host
|
|
22
|
+
* restart recovered it).
|
|
23
|
+
*
|
|
24
|
+
* The refused mount is therefore QUEUED, not dropped, and replayed the moment
|
|
25
|
+
* the holder releases the name - if the waiting fiber is still alive then. The
|
|
26
|
+
* single-instance guarantee is unchanged: exactly one mount is live per
|
|
27
|
+
* package name, and the replay re-enters the guard so a later mount still
|
|
28
|
+
* dedupes against it.
|
|
29
|
+
*
|
|
30
|
+
* The registry rides a global symbol so two module instances of the same
|
|
31
|
+
* package (npm copy vs repository link) still share one verdict. That symbol
|
|
32
|
+
* is a CROSS-REPOSITORY contract, not this file's private state: the four
|
|
33
|
+
* satellite packages (dsh-skins / dsh-pet / dsh-presets /
|
|
34
|
+
* dsh-community-plugins) are separate repositories carrying their own copy of
|
|
35
|
+
* this guard, rebuilt on their own schedule, so the value under `MOUNTED`
|
|
36
|
+
* must keep the shape every published copy reads (a `Set` of package names
|
|
37
|
+
* with `has`/`add`/`delete`). The wait queues this guard added therefore live
|
|
38
|
+
* under their own additive key, and the registry reads back a `Set` even when
|
|
39
|
+
* some other build left a different value there. Changing `MOUNTED`'s shape
|
|
40
|
+
* in place broke that contract once: a satellite's legacy copy created a
|
|
41
|
+
* `Set`, the family's new copy read it as a `Map`, and every family row
|
|
42
|
+
* mounted after it failed with "claims.get is not a function".
|
|
43
|
+
*
|
|
44
|
+
* cordis `ctx.effect` runs its callback immediately and treats the callback's
|
|
45
|
+
* return value as the fiber disposer, so the unmarker is returned, not run.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
/** Published cross-repository contract: package names currently mounted. */
|
|
49
|
+
const MOUNTED = Symbol.for('dsh-web.mounted-plugins')
|
|
50
|
+
|
|
51
|
+
/** Additive key this guard owns: refused mounts waiting for the name. */
|
|
52
|
+
const WAITERS = Symbol.for('dsh-web.mounted-plugins.waiters')
|
|
53
|
+
|
|
54
|
+
/** The slice of a cordis context this guard touches. */
|
|
55
|
+
interface MountContext {
|
|
56
|
+
effect?: (effect: () => unknown) => unknown
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One mount that was refused while another fiber owned the package name. */
|
|
60
|
+
interface PendingMount {
|
|
61
|
+
/** Replay the refused mount; a no-op once its own fiber has been disposed. */
|
|
62
|
+
run(): void
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface MountRegistry {
|
|
66
|
+
[MOUNTED]?: unknown
|
|
67
|
+
[WAITERS]?: Map<string, PendingMount[]>
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The shared name registry, always a `Set` whatever another build stored here:
|
|
72
|
+
* a foreign value (an interim shape, a hand-written global) must not take every
|
|
73
|
+
* family plugin down with it.
|
|
74
|
+
* @returns the process-wide set of mounted package names.
|
|
75
|
+
*/
|
|
76
|
+
function mountedSet(): Set<string> {
|
|
77
|
+
const registry = globalThis as MountRegistry
|
|
78
|
+
const existing = registry[MOUNTED]
|
|
79
|
+
if (existing instanceof Set) return existing as Set<string>
|
|
80
|
+
const created = new Set<string>()
|
|
81
|
+
registry[MOUNTED] = created
|
|
82
|
+
return created
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Queue per package name for mounts refused while a holder was alive. */
|
|
86
|
+
function mountWaiters(): Map<string, PendingMount[]> {
|
|
87
|
+
const registry = globalThis as MountRegistry
|
|
88
|
+
return (registry[WAITERS] ??= new Map())
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Wrap a cordis plugin apply so the package runs at most once per process.
|
|
93
|
+
* The first mount registers normally and releases the name when its fiber
|
|
94
|
+
* disposes; a mount refused while that name is held waits for the release and
|
|
95
|
+
* then runs, unless its own fiber disposes first.
|
|
96
|
+
* @param packageName - npm package identity shared by every install source.
|
|
97
|
+
* @param fn - the original plugin apply.
|
|
98
|
+
* @returns an apply of the same shape.
|
|
99
|
+
*/
|
|
100
|
+
export function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T {
|
|
101
|
+
const mount = (...args: unknown[]): unknown => {
|
|
102
|
+
const mounted = mountedSet()
|
|
103
|
+
const ctx = args[0] as MountContext | undefined
|
|
104
|
+
if (mounted.has(packageName)) {
|
|
105
|
+
// Another fiber (the aggregate row, a standalone install, or a copy built
|
|
106
|
+
// from an older revision of this guard) owns the name. Queue instead of
|
|
107
|
+
// dropping: dropping lost the plugin for the rest of the process when the
|
|
108
|
+
// holder was disposed by a reload.
|
|
109
|
+
const waiters = mountWaiters()
|
|
110
|
+
const queue = waiters.get(packageName) ?? []
|
|
111
|
+
let alive = true
|
|
112
|
+
const pending: PendingMount = {
|
|
113
|
+
run: () => {
|
|
114
|
+
if (alive) mount(...args)
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
// A fiber that dies while it waits must not be replayed afterwards: its
|
|
118
|
+
// context is disposed and registering effects on it would throw.
|
|
119
|
+
ctx?.effect?.(() => () => {
|
|
120
|
+
alive = false
|
|
121
|
+
const index = queue.indexOf(pending)
|
|
122
|
+
if (index >= 0) queue.splice(index, 1)
|
|
123
|
+
})
|
|
124
|
+
queue.push(pending)
|
|
125
|
+
waiters.set(packageName, queue)
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
mounted.add(packageName)
|
|
129
|
+
ctx?.effect?.(() => () => {
|
|
130
|
+
mounted.delete(packageName)
|
|
131
|
+
const waiters = mountWaiters()
|
|
132
|
+
const queue = waiters.get(packageName)
|
|
133
|
+
if (queue === undefined) return
|
|
134
|
+
waiters.delete(packageName)
|
|
135
|
+
// Defer the handover one microtask so the disposing mount's own effects
|
|
136
|
+
// (routes, ledger, timers) are torn down before the next one registers.
|
|
137
|
+
for (const waiter of queue.splice(0)) queueMicrotask(() => { waiter.run() })
|
|
138
|
+
})
|
|
139
|
+
return fn(...args)
|
|
140
|
+
}
|
|
141
|
+
return mount as T
|
|
142
|
+
}
|