@linxin666/dsh-remote-bridge 0.4.8 → 0.4.10

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 (72) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +75 -18
  3. package/README.zh.md +74 -18
  4. package/lib/client.js +783 -260
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +15849 -2913
  7. package/lib/types/client/PairEntry.d.ts +2 -2
  8. package/lib/types/client/PairPanel.d.ts +10 -2
  9. package/lib/types/client/UiPresentRow.d.ts +13 -0
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/index.d.ts +4 -0
  12. package/lib/types/client/locales.d.ts +24 -15
  13. package/lib/types/client/semantic.d.ts +9 -5
  14. package/lib/types/client/toolview-slot.d.ts +68 -0
  15. package/lib/types/client/ui-card.d.ts +160 -0
  16. package/lib/types/core/commands.d.ts +59 -0
  17. package/lib/types/core/connection.d.ts +106 -0
  18. package/lib/types/core/devices.d.ts +102 -2
  19. package/lib/types/core/extension.d.ts +13 -0
  20. package/lib/types/core/hub.d.ts +129 -15
  21. package/lib/types/core/liveactivity.d.ts +324 -0
  22. package/lib/types/core/protocol.d.ts +328 -5
  23. package/lib/types/core/push.d.ts +186 -0
  24. package/lib/types/core/questions.d.ts +61 -9
  25. package/lib/types/core/session-meta.d.ts +55 -1
  26. package/lib/types/core/squads.d.ts +130 -0
  27. package/lib/types/core/turn-end-quiet.d.ts +135 -0
  28. package/lib/types/core/ui.d.ts +238 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/host/apns.d.ts +151 -0
  32. package/lib/types/host/squads-ledger.d.ts +39 -0
  33. package/lib/types/host/squads.d.ts +77 -0
  34. package/lib/types/host/ui-tools.d.ts +80 -0
  35. package/lib/types/host/usage-stats.d.ts +75 -0
  36. package/lib/types/host/watchers.d.ts +95 -0
  37. package/lib/types/index.d.ts +47 -3
  38. package/package.json +15 -14
  39. package/src/client/PairEntry.tsx +58 -31
  40. package/src/client/PairPanel.tsx +181 -97
  41. package/src/client/UiPresentRow.tsx +149 -0
  42. package/src/client/icons.tsx +17 -60
  43. package/src/client/index.ts +11 -0
  44. package/src/client/locales.ts +36 -24
  45. package/src/client/panel.module.css +239 -186
  46. package/src/client/semantic.ts +10 -6
  47. package/src/client/toolview-slot.ts +84 -0
  48. package/src/client/ui-card.ts +368 -0
  49. package/src/client/ui-present.module.css +87 -0
  50. package/src/core/commands.ts +95 -0
  51. package/src/core/connection.ts +811 -12
  52. package/src/core/devices.ts +337 -5
  53. package/src/core/extension.ts +20 -0
  54. package/src/core/hub.ts +518 -43
  55. package/src/core/liveactivity.ts +833 -0
  56. package/src/core/protocol.ts +370 -5
  57. package/src/core/push.ts +385 -0
  58. package/src/core/questions.ts +81 -10
  59. package/src/core/session-meta.ts +73 -1
  60. package/src/core/squads.ts +345 -0
  61. package/src/core/turn-end-quiet.ts +388 -0
  62. package/src/core/ui.ts +398 -0
  63. package/src/core/usage-stats.ts +424 -0
  64. package/src/core/usage.ts +937 -0
  65. package/src/core/wire.ts +8 -0
  66. package/src/host/apns.ts +320 -0
  67. package/src/host/squads-ledger.ts +105 -0
  68. package/src/host/squads.ts +206 -0
  69. package/src/host/ui-tools.ts +233 -0
  70. package/src/host/usage-stats.ts +155 -0
  71. package/src/host/watchers.ts +296 -0
  72. package/src/index.ts +327 -10
package/src/index.ts CHANGED
@@ -13,11 +13,20 @@
13
13
  * - `approval/request` is claimed in-process while a paired device is connected,
14
14
  * and delegated (`next()`) in every other case, which the Host normalizes to
15
15
  * the fail-closed `'unavailable'`.
16
+ * - `ui.present` is this bridge's own model tool (protocol §35): one whole
17
+ * self-contained page is announced as `ui.request` to the paired clients that
18
+ * declared `ui.v1`, and the user's first action inside it comes back as that
19
+ * tool call's result. `ui.event` settles it, `ui.list` reads the cards still
20
+ * held. No paired client that declared the channel means the call answers
21
+ * `unavailable` at once instead of holding the agent.
16
22
  * - `user-questions/request` is claimed the same way and published as
17
23
  * `question.request` to the devices that declared `questions.v1`; their
18
24
  * `question.answer` settles the host's own ask while it is open, or reaches a
19
- * continued question through the host's Remote `answer`. Every other case
20
- * delegates, and the question keeps the Host's own deadline.
25
+ * continued question through the host's Remote `answer`. With no paired
26
+ * connection on the wire the claim is still made when a roster device registered
27
+ * for notifications, which is reached by the alert and holds the question for one
28
+ * window before it goes back to the host's chain (§11.3, §32). Every other case
29
+ * delegates, and a timed question keeps the Host's own deadline.
21
30
  *
22
31
  * The browser half lives in `src/client/` and is declared by `dsh.client`: one
23
32
  * sidebar-foot panel that reads the same loopback-gated token route over a
@@ -34,33 +43,92 @@ import type { Context } from '@deepseek-ai/cordis'
34
43
  import type {} from '@deepseek-ai/dsh-api-gateway'
35
44
  import type {} from '@deepseek-ai/dsh-host-webserver'
36
45
  import type {} from '@deepseek-ai/dsh-session'
46
+ import type {} from '@deepseek-ai/dsh-tools'
37
47
  import type {} from '@deepseek-ai/dsh-user-approval'
38
48
  import { ApprovalRegistry } from './core/approvals.ts'
39
49
  import type { ConnectionAuth } from './core/connection.ts'
40
50
  import { DeviceRoster } from './core/devices.ts'
41
51
  import { createRemoteBridgeFace, RemoteBridgeRegistry, REMOTE_BRIDGE_SERVICE } from './core/extension.ts'
42
52
  import { JobRoster, type JobRegistryFace } from './core/jobs.ts'
43
- import { BridgeHub } from './core/hub.ts'
53
+ import { BridgeHub, OFFLINE_QUESTION_CLAIM_TTL_MS } from './core/hub.ts'
44
54
  import { createOwnerPeer } from './core/owner-peer.ts'
45
55
  import { PairingService } from './core/pairing.ts'
56
+ import { LiveActivityNotifier } from './core/liveactivity.ts'
57
+ import { PushNotifier } from './core/push.ts'
46
58
  import { QuestionClaims } from './core/questions.ts'
59
+ import { UiCards } from './core/ui.ts'
47
60
  import { WS_PATH } from './core/protocol.ts'
48
- import { SessionMeta, type ArchiveSetFace, type SessionStoreFace, type SessionTitleFace } from './core/session-meta.ts'
61
+ import { SessionMeta, type SessionStoreFace, type SessionTitleFace, type WorkspacesFace } from './core/session-meta.ts'
62
+ import { sessionQuietProbe, TURN_END_QUIET_MAX_MS, TurnEndQuietGate } from './core/turn-end-quiet.ts'
49
63
  import { SessionPermissions, type ApprovalPolicyFace, type PermissionPresetsFace, type SandboxPolicyFace } from './core/session-permissions.ts'
64
+ import { selectionOf, modelSelectionOf } from './core/connection.ts'
65
+ import { UsageService, type CredentialStoreFace, type SessionRosterFace, type SessionRouteFace, type SettingsFace } from './core/usage.ts'
66
+ import { UsageStatsReader } from './core/usage-stats.ts'
67
+ import { wireArgs, type GatewayPeer } from './core/wire.ts'
50
68
  import { dshHome } from './host/dsh-home.ts'
69
+ import { ApnsSender, apnsConfigFromEnv } from './host/apns.ts'
70
+ import { StandingWatchers } from './host/watchers.ts'
71
+ import { LoopbackSquads } from './host/squads.ts'
51
72
  import { mountOnce } from './mount-once.ts'
52
73
  import { makePairTokenRoute } from './host/routes.ts'
74
+ import { createUiPresentTool } from './host/ui-tools.ts'
75
+ import { hostWebOrigin, LoopbackUsage } from './host/usage-stats.ts'
53
76
  import { isWebSocketUpgrade, presentedTokenOf, readSecWebSocketKey, refuseUpgrade, serveUpgrade } from './host/websocket.ts'
54
77
 
55
78
  /** Loader row identity of this plugin. */
56
79
  export const name = 'remote-bridge'
57
80
 
58
- /** The Host services this plugin cannot run without. */
59
- export const inject = ['typertGateway', 'webServer']
81
+ /**
82
+ * The Host services this plugin cannot run without.
83
+ *
84
+ * `tools` is what protocol §35 added: this bridge contributes one model tool of
85
+ * its own (`ui.present`), so a host that composes no tool registry is a host where
86
+ * the card channel has no caller — the row simply does not mount here.
87
+ */
88
+ export const inject = ['typertGateway', 'webServer', 'tools']
60
89
 
61
90
  /** Where the paired-device roster lives inside the DSH home. */
62
91
  export const ROSTER_PATH = 'remote-bridge/devices.json'
63
92
 
93
+ /** The environment variable that moves the offline claim window (§32.2). */
94
+ export const OFFLINE_CLAIM_TTL_ENV = 'DSH_REMOTE_BRIDGE_OFFLINE_CLAIM_TTL_MS'
95
+
96
+ /**
97
+ * The offline claim window this process runs with.
98
+ *
99
+ * The window is the bridge's own constant and never a host fact, so a deployment
100
+ * moves it here. A value that is missing, unreadable or not positive falls back to
101
+ * the constant instead of closing the window: a zero window would silently switch
102
+ * the channel off, and an operator who wanted that would be turning off push.
103
+ * @param env - the process environment, injectable for a suite.
104
+ * @returns the window in milliseconds.
105
+ */
106
+ export function offlineClaimTtl(env: NodeJS.ProcessEnv = process.env): number {
107
+ const configured = Number(env[OFFLINE_CLAIM_TTL_ENV])
108
+ return Number.isFinite(configured) && configured > 0 ? configured : OFFLINE_QUESTION_CLAIM_TTL_MS
109
+ }
110
+
111
+ /** The environment variable that moves how long a finished turn waits for its session to go quiet (§28). */
112
+ export const TURN_END_QUIET_MAX_ENV = 'DSH_REMOTE_BRIDGE_TURN_END_QUIET_MAX_MS'
113
+
114
+ /**
115
+ * The quiet-wait budget this process runs with.
116
+ *
117
+ * The budget is the bridge's own constant and never a host fact, so a deployment
118
+ * moves it here. A value that is missing, unreadable or not positive falls back to
119
+ * the constant instead of closing the window: a zero budget would announce every
120
+ * turn end at its frame, and an operator who wanted that would be turning push
121
+ * off. The budget only bounds the wait — a session that does fall quiet inside it
122
+ * is announced then, and one that does not is announced at the end with the
123
+ * reason it was still busy.
124
+ * @param env - the process environment, injectable for a suite.
125
+ * @returns the budget in milliseconds.
126
+ */
127
+ export function turnEndQuietMaxWait(env: NodeJS.ProcessEnv = process.env): number {
128
+ const configured = Number(env[TURN_END_QUIET_MAX_ENV])
129
+ return Number.isFinite(configured) && configured > 0 ? configured : TURN_END_QUIET_MAX_MS
130
+ }
131
+
64
132
  /** This machine's IANA time zone, or undefined when the platform has none. */
65
133
  function localTimeZone(): string | undefined {
66
134
  try {
@@ -115,20 +183,130 @@ function makeUpgradeHandler(hub: BridgeHub, roster: DeviceRoster, log: (message:
115
183
  /**
116
184
  * Resolve the host services session metadata is read from, now.
117
185
  *
118
- * All three are read per call rather than captured at mount: none of them is in
119
- * this plugin's `inject` list, because requiring them would let the title or
186
+ * All of them are read per call rather than captured at mount: none is in this
187
+ * plugin's `inject` list, because requiring them would let the title or
120
188
  * workspace plugin's absence take the whole bridge down with it. An unmounted
121
189
  * service simply reads as undefined, and the protocol degrades one key of one
122
190
  * row instead of failing a method. The faces are structural — this package
123
191
  * imports no part of those services' own types.
192
+ *
193
+ * One registry answers two faces: `archive` is the slice a roster row reads and
194
+ * `workspaces` the wider slice `workspace.list` publishes, so a single lookup
195
+ * serves both and a host either composes a registry or composes none.
124
196
  * @param ctx - the plugin's context.
125
197
  * @returns the metadata faces as they stand right now.
126
198
  */
127
199
  function sessionMetaFaces(ctx: Context) {
200
+ const registry = ctx.get('workspaceRegistry') as WorkspacesFace | undefined
128
201
  return {
129
202
  sessions: ctx.get('sessions') as SessionStoreFace | undefined,
130
203
  titles: ctx.get('sessionTitle') as SessionTitleFace | undefined,
131
- archive: ctx.get('workspaceRegistry') as ArchiveSetFace | undefined,
204
+ archive: registry,
205
+ workspaces: registry,
206
+ }
207
+ }
208
+
209
+ /**
210
+ * 宿主自己的会话名册,按 `usage.session` 需要的那一格读出来。
211
+ *
212
+ * 走的是 `session.list` 服务的同一个端点(`session/list`),也就是手机名册的
213
+ * 来源:它名下既有活的会话,也有本进程没观察过、当前也不 live 的会话,因此
214
+ * 那类会话不会被说成不存在。`ctx.sessions.list()` 答不了这一问——它只列已经
215
+ * 进入存储的会话。读失败或答不出 item 表就回 undefined,「不知道名册」由用量
216
+ * 服务退回活会话存储与事件折叠两条证词。
217
+ * @param ctx - 插件的上下文,携带网关。
218
+ * @param peer - 本桥自己的 owner peer,每次调用都以它发声。
219
+ * @param log - 读不到名册时的落点。
220
+ * @returns 名册 face。
221
+ */
222
+ function sessionRoster(ctx: Context, peer: GatewayPeer, log: (message: string) => void): SessionRosterFace {
223
+ return {
224
+ ids: async (): Promise<readonly string[] | undefined> => {
225
+ try {
226
+ const value = await ctx.typertGateway.invoke({
227
+ namespace: 'session',
228
+ method: 'list',
229
+ args: wireArgs('session', 'list', {}),
230
+ peer,
231
+ })
232
+ const items = typeof value === 'object' && value !== null ? (value as { items?: unknown }).items : undefined
233
+ if (!Array.isArray(items)) return undefined
234
+ const ids: string[] = []
235
+ for (const item of items) {
236
+ const id = typeof item === 'object' && item !== null ? (item as { sessionId?: unknown }).sessionId : undefined
237
+ if (typeof id === 'string' && id !== '') ids.push(id)
238
+ }
239
+ return ids
240
+ } catch (error) {
241
+ log(`the host session roster could not be read: ${String(error)}`)
242
+ return undefined
243
+ }
244
+ },
245
+ }
246
+ }
247
+
248
+ /**
249
+ * 一条会话此刻的路由,按 `usage.session` 的模型窗口那一档读出来。
250
+ *
251
+ * 折叠与 `session.models` 的 `current` 逐字一致:下一步的选择、其次是用过的那个、
252
+ * 最后才是目录默认。两个方法读同一个折叠,就不可能出现「模型选择器说 A、模型窗口
253
+ * 按 B 算」这种事。每次读都走本桥自己的 owner peer;读不到任何一档就回 undefined,
254
+ * 那一档读数(`modelContextWindow`)因此根本不出现,而不是补一个默认值。
255
+ * @param ctx - 插件的上下文,携带网关。
256
+ * @param peer - 本桥自己的 owner peer,每次调用都以它发声。
257
+ * @param log - 读不到时记一行日志。
258
+ * @returns 路由 face。
259
+ */
260
+ function sessionRoute(ctx: Context, peer: GatewayPeer, log: (message: string) => void): SessionRouteFace {
261
+ const invoke = async (method: string, args: Readonly<Record<string, unknown>>): Promise<unknown> => await ctx.typertGateway.invoke({
262
+ namespace: 'session',
263
+ method,
264
+ args: wireArgs('session', method, args),
265
+ peer,
266
+ })
267
+ return {
268
+ current: async (sessionId: string) => {
269
+ try {
270
+ const folded = modelSelectionOf(await invoke('projections', { sessionId }))
271
+ const selected = folded.next ?? folded.lastUsed
272
+ // 还没选过模型的会话在目录默认上——它下一步就会用那个,也正是
273
+ // `session.models` 对同一条会话给出的答案。
274
+ const fallback = selected === undefined ? selectionOf(catalogDefaultOf(await invoke('modelCatalog', {}))) : undefined
275
+ const answer = selected ?? fallback
276
+ return answer === undefined ? undefined : { provider: answer.provider, model: answer.model }
277
+ } catch (error) {
278
+ log(`the route of session ${sessionId} could not be read: ${String(error)}`)
279
+ return undefined
280
+ }
281
+ },
282
+ }
283
+ }
284
+
285
+ /** `session/modelCatalog` 里的 `default` 一格。 */
286
+ function catalogDefaultOf(value: unknown): unknown {
287
+ return typeof value === 'object' && value !== null ? (value as { default?: unknown }).default : undefined
288
+ }
289
+
290
+ /**
291
+ * 解析 `usage.v1` 要读的宿主服务,现在就解析一次。
292
+ *
293
+ * 与元数据的三个 face 同一条理由:四者都不在本插件的 `inject` 里,缺一个不该
294
+ * 让整个桥起不来。缺活会话存储,`usage.session` 就只能靠名册与本进程观察过的
295
+ * 事件判断会话是否存在;缺凭据服务,`usage.balance` 回 `no-credential`;缺设置
296
+ * 服务,路由的 `baseURL` 与 `apiKeyEnv` 读不到,origin 判定与凭据回退都退回
297
+ * 官方默认值。face 是结构化的:本包不导入这些服务自己的类型。
298
+ * @param ctx - 插件的上下文。
299
+ * @param peer - 本桥自己的 owner peer,名册读取以它发声。
300
+ * @param log - 读不到名册时的落点。
301
+ * @returns 这些 face 此刻的样子。
302
+ */
303
+ function usageFaces(ctx: Context, peer: GatewayPeer, log: (message: string) => void) {
304
+ return {
305
+ sessions: ctx.get('sessions') as SessionStoreFace | undefined,
306
+ roster: sessionRoster(ctx, peer, log),
307
+ credentials: ctx.get('credentials') as CredentialStoreFace | undefined,
308
+ settings: ctx.get('settings') as SettingsFace | undefined,
309
+ route: sessionRoute(ctx, peer, log),
132
310
  }
133
311
  }
134
312
 
@@ -191,15 +369,123 @@ function applyImpl(ctx: Context): void {
191
369
  // it is gated by the bridge's own pairing check (see core/owner-peer.ts).
192
370
  const ownerPeer = createOwnerPeer(ctx)
193
371
  const questions = new QuestionClaims({ gateway: ctx.typertGateway, peer: ownerPeer, log })
372
+ // 整页卡(§35):一张宿主级的卡表,所有连接共享——一条动作只属于发起它的那个
373
+ // 工具调用,与它从哪台设备回来无关。
374
+ const ui = new UiCards()
194
375
  // One roster per mount, shared by every connection: a background job is a fact
195
376
  // about the host, not about the device that asked about it.
196
377
  const jobs = new JobRoster({ faces: () => jobFaces(ctx), log })
197
378
  const sessionMeta = new SessionMeta(() => sessionMetaFaces(ctx), () => Date.now(), log)
379
+ // 用量读数:一条会话的窗口与组成靠宿主广播的事件折出来,余额靠宿主自己的
380
+ // 凭据与设置查出来。一个宿主一份、所有连接共享——两台手机重复问,上游也只
381
+ // 该收到一次请求(core/usage.ts)。
382
+ // 台账聚合读的是宿主上 dsh-usage 插件的两条 HTTP 路由,走本机回环 origin:那个
383
+ // 插件不发布任何 cordis 服务,端口从 `webServer` 来(先 getOrigin(),拿不到再退回
384
+ // 监听端口)。没有它时 `usage.stats` 答 no-usage-plugin,其余读数一概不变。
385
+ const usageRoutes = new LoopbackUsage({ origin: () => hostWebOrigin(ctx.webServer), log })
386
+ const usageStats = new UsageStatsReader({ transport: () => usageRoutes, now: () => Date.now(), log })
387
+ const usage = new UsageService({ faces: () => usageFaces(ctx, ownerPeer, log), now: () => Date.now(), stats: usageStats, log })
388
+ // The push channel is OFF unless this machine holds an Apple signing key: no
389
+ // key, no sender, and every notification path is a no-op — which is what keeps
390
+ // the protocol byte-identical for every deployment that has none (§28).
391
+ const apns = apnsConfigFromEnv()
392
+ // One client for both channels: an APNs provider token is minted per key and
393
+ // then reused, so a second client would only double the mint rate Apple
394
+ // throttles (core/push.ts, host/apns.ts).
395
+ const apnsSender = apns === undefined ? undefined : new ApnsSender({ config: apns, log })
396
+ const push = new PushNotifier({
397
+ targets: () => roster.pushTargets().map(({ push: registration }) => ({
398
+ deviceToken: registration.deviceToken,
399
+ environment: registration.environment,
400
+ bundle: registration.bundle,
401
+ ...(registration.locale === undefined ? {} : { locale: registration.locale }),
402
+ })),
403
+ ...(apnsSender === undefined ? {} : { sender: apnsSender }),
404
+ titles: id => sessionMeta.title(id),
405
+ now: () => Date.now(),
406
+ log,
407
+ })
408
+ // The lock-screen card path (§29). It reads the same roster, through the same
409
+ // client, and is inert for exactly the same reason: no key, no sender, no card.
410
+ // A token APNs reports dead is dropped from its device row here, which is the
411
+ // whole of the recovery — the next card registers a fresh one.
412
+ const liveActivity = new LiveActivityNotifier({
413
+ targets: () => roster.pushTargets().flatMap(({ push: registration }) => (registration.liveActivityTokens ?? []).map(({ activityId, token, sessionId }) => ({
414
+ activityId,
415
+ token,
416
+ // The session is the card's address (§29.9). A registration written before
417
+ // that field existed simply has none, and its card is never pushed to.
418
+ ...(sessionId === undefined ? {} : { sessionId }),
419
+ environment: registration.environment,
420
+ bundle: registration.bundle,
421
+ }))),
422
+ ...(apnsSender === undefined ? {} : { sender: apnsSender }),
423
+ now: () => Date.now(),
424
+ log,
425
+ retire: async (activityId, token) => {
426
+ const dropped = await roster.removeLiveActivityToken(activityId, token)
427
+ // A dead token is a roster change like any other: the session it named may
428
+ // have just lost its last card, and a watcher for it must close.
429
+ if (dropped) watchers.sync()
430
+ return dropped
431
+ },
432
+ })
433
+ // The quiet gate both channels announce a finished turn through: §28's
434
+ // notification and §29's card end wait for the host's own answer that nothing is
435
+ // left running under that session — its own agent, any descendant, and any job
436
+ // the host attributes to either. Inert while no key is configured, because both
437
+ // channels are then off and no timer is worth arming.
438
+ const turnEndQuiet = new TurnEndQuietGate({
439
+ push,
440
+ liveActivity,
441
+ probe: sessionQuietProbe({ gateway: ctx.typertGateway, peer: ownerPeer, jobs }),
442
+ maxWaitMs: turnEndQuietMaxWait(),
443
+ log,
444
+ })
445
+ // The bridge's own follow streams (§28/§29): a suspended phone has no socket,
446
+ // so the turn end its card has to show would otherwise be seen by nobody. One
447
+ // watcher per session that still holds a card token, armed from the roster and
448
+ // never from a client frame.
449
+ const watchedSessions = (): readonly string[] => {
450
+ const sessions = new Set<string>()
451
+ for (const { push: registration } of roster.pushTargets()) {
452
+ for (const token of registration.liveActivityTokens ?? []) {
453
+ if (token.sessionId !== undefined) sessions.add(token.sessionId)
454
+ }
455
+ }
456
+ return [...sessions]
457
+ }
458
+ const watchers = new StandingWatchers({
459
+ gateway: ctx.typertGateway,
460
+ peer: ownerPeer,
461
+ sessions: watchedSessions,
462
+ ...(apnsSender === undefined ? {} : { liveActivity, push }),
463
+ turnEndQuiet,
464
+ log,
465
+ })
198
466
  const permissions = new SessionPermissions(() => permissionFaces(ctx), log)
199
467
  // The extension seam publishes no protocol vocabulary of its own: another
200
468
  // plugin registers the method names, payloads and topics it owns, and this
201
469
  // package only dispatches and fans out what it was handed.
470
+ // The squad domain of the `dsh-agents` plugin is read over this host's own
471
+ // loopback origin: that plugin serves its routes on the very web server this
472
+ // bridge already injects. Both the origin and the ledger directory are resolved
473
+ // per call — the listener may not have bound a port when this row mounts, and a
474
+ // DSH home is not a fact to capture once.
475
+ const squads = new LoopbackSquads({
476
+ origin: () => {
477
+ try {
478
+ return ctx.webServer.getOrigin()
479
+ } catch {
480
+ return undefined
481
+ }
482
+ },
483
+ ledgerDirectory: () => join(dshHome(), 'dsh-agents'),
484
+ log,
485
+ })
202
486
  const extensions = new RemoteBridgeRegistry()
487
+ // 离线认领的窗口归桥所有,宿主从不认识它(§32.2):常量是默认值,部署可用环境变量覆盖。
488
+ const offlineClaimTtlMs = offlineClaimTtl()
203
489
  const hub = new BridgeHub({
204
490
  extensions,
205
491
  gateway: ctx.typertGateway,
@@ -207,10 +493,18 @@ function applyImpl(ctx: Context): void {
207
493
  roster,
208
494
  approvals,
209
495
  questions,
496
+ ui,
210
497
  jobs,
211
498
  sessionMeta,
499
+ usage,
212
500
  permissions,
213
501
  ownerPeer,
502
+ squads,
503
+ push,
504
+ liveActivity,
505
+ turnEndQuiet,
506
+ offlineClaimTtlMs,
507
+ onPushRegistered: () => { watchers.sync() },
214
508
  now: () => Date.now(),
215
509
  clientTimeZone: localTimeZone,
216
510
  log,
@@ -224,21 +518,44 @@ function applyImpl(ctx: Context): void {
224
518
  }
225
519
 
226
520
  ctx.effect(() => {
227
- void roster.load()
521
+ // A registration that arrived before this row mounted is still on disk: the
522
+ // watchers are reconciled from what the roster holds, not from what a live
523
+ // connection happened to send.
524
+ void roster.load().then(() => { watchers.sync() }).catch(() => undefined)
228
525
  const disposeUpgrade = ctx.webServer.registerUpgrade({
229
526
  path: WS_PATH,
230
527
  handler: makeUpgradeHandler(hub, roster, log),
231
528
  })
232
529
  const disposeRoute = ctx.webServer.register(makePairTokenRoute({ pairing, log }))
233
530
  log(`protocol v1 listening on ${WS_PATH}`)
531
+ log(apns === undefined
532
+ ? `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)`
533
+ : `push: on (APNs key ${apns.keyId} of team ${apns.teamId})`)
234
534
  return () => {
235
535
  disposeUpgrade()
236
536
  disposeRoute()
537
+ watchers.dispose()
538
+ turnEndQuiet.dispose()
237
539
  hub.dispose()
238
540
  jobs.dispose()
239
541
  }
240
542
  }, 'remote-bridge: protocol v1 routes')
241
543
 
544
+ // §35 的模型工具:`ui.present` 把 agent 写的整页交给已配对的客户端,并在用户
545
+ // 动作时把结构化事件作为它自己的返回值交回。注册在 `ctx.effect` 里、返回
546
+ // disposer,所以插件卸载时工具名随行消失,宿主工具表不会留下一根指向空实现的
547
+ // 指针;`execute` 把 `exec.signal` 一路传到认领表,回合被取消时那张卡立刻结算。
548
+ ctx.effect(() => {
549
+ const disposeTool = ctx.tools.register(createUiPresentTool({
550
+ present: async (card, signal) => await hub.present(card, signal),
551
+ }))
552
+ log('model tool ui.present registered')
553
+ return () => { disposeTool() }
554
+ }, 'remote-bridge: ui.present tool')
555
+
556
+ // 会话事件是 `usage.session` 唯一的来源:桥不读会话日志、也不回填历史,所以
557
+ // 这个监听器挂上之前广播的事件不会有读数,宿主没广播过的窗口也不会被编出来。
558
+ ctx.on('session/event', (session, event) => { usage.record(session.id, event) })
242
559
  ctx.on('approval/request', (request, next) => hub.approve(request, next))
243
560
  // Prepended: the host's waterfall is first-come, and the desktop client's own
244
561
  // answerer would otherwise claim every question before this listener is