@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
@@ -0,0 +1,233 @@
1
+ /**
2
+ * The `ui.present` model tool: the agent hands one self-contained page to the
3
+ * clients paired with this host, and the user's first action comes back as that
4
+ * same tool call's result (protocol §35).
5
+ *
6
+ * The tool owns its own vocabulary and nothing else. The page is the argument,
7
+ * the cards are the hub's claims, and the result is one sentence plus the
8
+ * presentation payload the desktop renders from (`meta.ui`, §35.10) — the phone
9
+ * still reads `ui.request` and `ui.list`, so this payload is never its second
10
+ * source of truth.
11
+ *
12
+ * Both caps are enforced here, on the originating side (§35.2): an oversized page
13
+ * is refused `invalid-args` before a frame is written and without a
14
+ * presentation payload, because a refusal on the client would leave the agent
15
+ * waiting for a card that never comes.
16
+ * @module dsh-remote-bridge/host/ui-tools
17
+ */
18
+
19
+ import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'
20
+ import type { UiPresentReply } from '../core/hub.ts'
21
+ import { UI_HTML_MAX_BYTES, UI_PAYLOAD_MAX_BYTES, uiHtmlFits, uiKey } from '../core/ui.ts'
22
+ import type { JsonValue, UiCardView, UiRefusalReason, UiState } from '../core/ui.ts'
23
+
24
+ /**
25
+ * The one thing this tool needs from the hub.
26
+ *
27
+ * Structural on purpose, and the seam a suite drives: the tool decides nothing
28
+ * about delivery, deadlines or the grace window, so a test can hand it any host
29
+ * that presents a page.
30
+ */
31
+ export interface UiToolHost {
32
+ /** Present one page and wait for the user's first action (§35.2). */
33
+ present(card: UiCardView, signal?: AbortSignal): Promise<UiPresentReply>
34
+ }
35
+
36
+ /** The card as the desktop renders it from a tool result (§35.10). */
37
+ export interface UiPresentationMeta {
38
+ /** {@link uiKey}: the same `"<sessionId>/<callId>"` a `ui.list` row carries. */
39
+ readonly key: string
40
+ readonly title?: string
41
+ /** The whole page, byte for byte the document that crossed as `html`. */
42
+ readonly html: string
43
+ readonly height?: number
44
+ readonly state: UiState
45
+ }
46
+
47
+ /**
48
+ * What the model is told before it writes a single page.
49
+ *
50
+ * Every clause here is one of §35.2's or §35.7's rules restated where the model
51
+ * can act on it: the page is a whole document, it cannot navigate, its external
52
+ * subresources are `https:`, its only way back is the named message channel, and
53
+ * the two caps are the host's. The blocking lifetime is stated last, because it is
54
+ * what a model most often assumes wrong: one action ends this call.
55
+ */
56
+ export const UI_PRESENT_DESCRIPTION = [
57
+ 'Present one whole self-contained HTML page to the clients paired with this host, and wait for the user to act inside it.',
58
+ "The call blocks until the user's FIRST action arrives; that action ({type, payload?}) is this call's result, and the card then stops accepting actions — present again if the page should keep taking them.",
59
+ 'Write a complete document starting with <!doctype html> and keep it within 256 KiB of UTF-8. Inline the CSS, the scripts and every image you can (data:), because external subresources must be https:; http:, ws: and file: are refused.',
60
+ 'The page cannot navigate: no top-level navigation, no window.open, no target=_blank, no cross-document jump. A link that leaves the card is dead by construction.',
61
+ 'Report an action with webkit.messageHandlers.dshui.postMessage({type, payload}) on iOS and postMessage({type, payload}) on desktop. type is your own name for the action (for example "submit", "choose" or "run"); payload is optional JSON within 8 KiB.',
62
+ 'Answers "unavailable" when no paired client announced the capability, and "invalid-args" when the page is over the cap — in both cases no frame is sent and nothing is shown.',
63
+ ].join(' ')
64
+
65
+ /**
66
+ * The canonical result body, as the output schema declares it.
67
+ *
68
+ * Three shapes and no more: the action that settled the card, the release of a
69
+ * card that did reach a screen, and a refusal that never got that far. Only the
70
+ * first two carry the card identity, which is what decides whether a presentation
71
+ * payload rides the result (§35.10).
72
+ */
73
+ export type UiPresentValue =
74
+ | {
75
+ readonly ok: true
76
+ readonly key: string
77
+ readonly delivered: number
78
+ readonly type: string
79
+ readonly payload?: JsonValue
80
+ }
81
+ | {
82
+ readonly ok: false
83
+ readonly reason: 'timeout' | 'cancelled'
84
+ readonly key: string
85
+ readonly delivered: number
86
+ }
87
+ | { readonly ok: false; readonly reason: 'unavailable' | 'invalid-args' }
88
+
89
+ /** The canonical result body: one sentence, never the page itself. */
90
+ function describe(value: unknown): string {
91
+ if (typeof value !== 'object' || value === null) return 'ui.present finished'
92
+ const record = value as { ok?: unknown; reason?: unknown; type?: unknown; delivered?: unknown }
93
+ if (record.ok === true) {
94
+ const delivered = typeof record.delivered === 'number' ? record.delivered : 0
95
+ const type = typeof record.type === 'string' ? record.type : 'an action'
96
+ return `presented to ${delivered} paired client(s); settled by the operator with "${type}"`
97
+ }
98
+ const reason = typeof record.reason === 'string' ? record.reason : 'unknown'
99
+ if (reason === 'timeout' || reason === 'cancelled') {
100
+ const delivered = typeof record.delivered === 'number' ? record.delivered : 0
101
+ return `presented to ${delivered} paired client(s); the card was released without an action (${reason})`
102
+ }
103
+ return `ui.present was refused: ${reason}`
104
+ }
105
+
106
+ /**
107
+ * The presentation payload a transcript-rendering client reads (§35.10).
108
+ *
109
+ * Present exactly when the page really reached the wire — which is the same fact
110
+ * as the result carrying a `key` — so a refused or oversized call leaves no card
111
+ * for the desktop to draw. `state` is the card's ending, and a blocking
112
+ * presentation only ever ends one way: it is settled by the time this call
113
+ * returns, so the shape's `open` is what a host that answers before its first
114
+ * event would publish, which §35.3 rules out here.
115
+ * @param args - the arguments the model sent.
116
+ * @param value - the canonical result body.
117
+ * @returns the `meta` object, or `{}` when no card crossed.
118
+ */
119
+ function presentationOf(args: { html: string; title?: string; height?: number }, value: unknown): Record<string, JsonValue> {
120
+ if (typeof value !== 'object' || value === null) return {}
121
+ const key = (value as { key?: unknown }).key
122
+ if (typeof key !== 'string') return {}
123
+ const ui: UiPresentationMeta = {
124
+ key,
125
+ ...(args.title === undefined ? {} : { title: args.title }),
126
+ html: args.html,
127
+ ...(args.height === undefined ? {} : { height: args.height }),
128
+ state: 'settled',
129
+ }
130
+ return { ui: { ...ui } }
131
+ }
132
+
133
+ /**
134
+ * Build the one card tool.
135
+ * @param host - the hub, as this tool needs it.
136
+ * @returns a registry-ready definition for `ctx.tools.register`.
137
+ */
138
+ export function createUiPresentTool(host: UiToolHost): ToolDefinition {
139
+ return defineTool({
140
+ name: 'ui.present',
141
+ description: UI_PRESENT_DESCRIPTION,
142
+ parameters: {
143
+ html: {
144
+ type: 'string',
145
+ required: true,
146
+ description: `The whole page as one document, starting with <!doctype html>. At most ${UI_HTML_MAX_BYTES} bytes of UTF-8; inline what you can, external subresources are https: only.`,
147
+ },
148
+ title: {
149
+ type: 'string',
150
+ description: 'One header line for the card. Omit it and the header shows the state alone.',
151
+ },
152
+ height: {
153
+ type: 'integer',
154
+ description: 'Your suggested initial height in points. The client still measures the page and its own measurement wins.',
155
+ },
156
+ },
157
+ output: {
158
+ schema: {
159
+ oneOf: [
160
+ {
161
+ type: 'object',
162
+ additionalProperties: false,
163
+ properties: {
164
+ ok: { type: 'boolean', const: true },
165
+ key: { type: 'string', required: true, description: 'The card identity: "<sessionId>/<callId>".' },
166
+ delivered: { type: 'integer', required: true, description: 'How many paired connections took the page.' },
167
+ type: { type: 'string', required: true, description: 'The action name the page reported.' },
168
+ payload: { type: 'json', description: 'The action payload, carried verbatim, within 8 KiB.' },
169
+ },
170
+ },
171
+ {
172
+ type: 'object',
173
+ additionalProperties: false,
174
+ properties: {
175
+ ok: { type: 'boolean', const: false },
176
+ reason: { type: 'string', required: true, enum: ['timeout', 'cancelled'] },
177
+ key: { type: 'string', required: true, description: 'The card that was presented and then released.' },
178
+ delivered: { type: 'integer', required: true, description: 'How many paired connections took the page.' },
179
+ },
180
+ },
181
+ {
182
+ type: 'object',
183
+ additionalProperties: false,
184
+ properties: {
185
+ ok: { type: 'boolean', const: false },
186
+ reason: { type: 'string', required: true, enum: ['unavailable', 'invalid-args'] },
187
+ },
188
+ },
189
+ ],
190
+ },
191
+ render: (_args, value) => [{ type: 'text', text: describe(value) }],
192
+ presentationMeta: (args, value) => presentationOf(args, value),
193
+ },
194
+ async execute(args, exec): Promise<UiPresentValue> {
195
+ // The cap is checked before anything is announced: a page over it is refused
196
+ // as invalid-args with no frame, no card and no presentation payload.
197
+ if (!uiHtmlFits(args.html)) return { ok: false, reason: 'invalid-args' }
198
+ const sessionId = exec.agent?.id
199
+ // A presentation needs a session to hang the card on, and the caller supplies
200
+ // it: without one this bridge cannot name the card, so nothing is presented.
201
+ if (sessionId === undefined) return { ok: false, reason: 'unavailable' }
202
+ const key = uiKey(String(sessionId), String(exec.callId))
203
+ const reply: UiPresentReply = await host.present({
204
+ sessionId: String(sessionId),
205
+ callId: String(exec.callId),
206
+ html: args.html,
207
+ ...(args.title === undefined ? {} : { title: args.title }),
208
+ ...(args.height === undefined ? {} : { height: args.height }),
209
+ }, exec.signal)
210
+ if (reply.ok) {
211
+ return {
212
+ ok: true,
213
+ key,
214
+ delivered: reply.delivered,
215
+ type: reply.type,
216
+ ...(reply.payload === undefined ? {} : { payload: reply.payload }),
217
+ }
218
+ }
219
+ // A card that reached a screen carries its identity into the result even when
220
+ // the wait ended in a refusal: the desktop's row must be able to say the page
221
+ // is over (§35.10). A call that never got that far carries no key at all.
222
+ switch (reply.reason) {
223
+ case 'timeout':
224
+ case 'cancelled':
225
+ return { ok: false, reason: reply.reason, key, delivered: reply.delivered }
226
+ case 'invalid-args':
227
+ return { ok: false, reason: 'invalid-args' }
228
+ default:
229
+ return { ok: false, reason: 'unavailable' }
230
+ }
231
+ },
232
+ })
233
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * 宿主上 `dsh-usage` 插件的两条路由,按 `usage.stats` 需要的那一格读出来。
3
+ *
4
+ * 那个插件把台账挂在**同一个** web 服务上(`/api/dsh-usage/overview` 与
5
+ * `/api/dsh-usage/day`,见它的 `host/routes.ts`),所以这里不去进程里找它的服务
6
+ * ——它不发布任何 cordis 服务——而是对本机回环 origin 发一次真正的 GET。路径在这
7
+ * 里重写一遍而不是 import 过来:本包不依赖任何别的插件,能跨过来的只有冻结的路径
8
+ * 字符串。
9
+ *
10
+ * 端口从哪来:先问宿主自己的 `webServer.getOrigin()`(那是它已经绑定的地址,含
11
+ * 协议与端口,也是 `dsh-agents` 那一格用的同一条路);拿不到时退回
12
+ * `${protocol}//127.0.0.1:${port}` 的监听端口探测。后者只在这台宿主把监听绑在
13
+ * 回环地址上时才连得通,绑到别的网卡上会连不上——那时答案是 `probe-failed`,
14
+ * 而不是一个编出来的读数。
15
+ *
16
+ * 一次读的三种结局:答了、路由不存在、这次没读到。第三种带一句短原因。**404 是
17
+ * 第二种**:那台宿主没挂这个插件,是一件事实;而连接被拒、超时、非 200、读不出
18
+ * JSON 都是第三种。
19
+ * @module dsh-remote-bridge/host/usage-stats
20
+ */
21
+
22
+ import type { UsageStatsOutcome, UsageStatsTransport } from '../core/usage-stats.ts'
23
+
24
+ /**
25
+ * 那个插件挂的两条路由;按它的 `USAGE_API_PREFIX` 拼出来。
26
+ */
27
+ export const USAGE_OVERVIEW_PATH = '/api/dsh-usage/overview'
28
+ export const USAGE_DAY_PATH = '/api/dsh-usage/day'
29
+
30
+ /** 一次回环读的超时。那个插件从内存里答,这个时限只是不让一次卡住拖住连接。 */
31
+ export const USAGE_PROBE_TIMEOUT_MS = 5_000
32
+
33
+ /** 宿主 web 服务在这条路上要的那两格;结构读取,不导入它的类型。 */
34
+ export interface WebServerAddress {
35
+ /** 已经绑定的 origin,形如 `http://127.0.0.1:3080`;监听之前会抛。 */
36
+ getOrigin?(): string
37
+ /** 监听器说的协议,随配置而不是随请求。 */
38
+ readonly protocol?: string
39
+ /** 实际监听的端口(端口写 0 时是系统分配的那个);绑定之前是 undefined。 */
40
+ readonly port?: number
41
+ }
42
+
43
+ /** 构造 {@link LoopbackUsage} 的全部输入。 */
44
+ export interface LoopbackUsageOptions {
45
+ /** 每次读数都重新解析一次:这一行挂载时监听器可能还没有端口。 */
46
+ readonly origin: () => string | undefined
47
+ /** 出站调用的接缝;生产默认是本进程的 `fetch`。 */
48
+ readonly fetch?: typeof fetch
49
+ /** 一次读的超时;默认 {@link USAGE_PROBE_TIMEOUT_MS}。 */
50
+ readonly timeoutMs?: number
51
+ readonly log: (message: string) => void
52
+ }
53
+
54
+ /**
55
+ * 本机 web 服务的 origin。
56
+ *
57
+ * 先问宿主给的那个(它知道自己的绑定地址),拿不到就退回 127.0.0.1 上的监听端口。
58
+ * 两条都不成立时回 undefined,调用方据此答 `probe-failed`。
59
+ * @param server - 宿主 web 服务,可能还没挂载。
60
+ * @returns origin,或者 undefined。
61
+ */
62
+ export function hostWebOrigin(server: WebServerAddress | undefined): string | undefined {
63
+ if (server === undefined) return undefined
64
+ try {
65
+ const origin = typeof server.getOrigin === 'function' ? server.getOrigin() : undefined
66
+ if (typeof origin === 'string' && origin !== '') return origin
67
+ } catch {
68
+ // 监听还没绑定:getOrigin() 会抛,落回下面的端口探测。
69
+ }
70
+ const port = server.port
71
+ if (typeof port !== 'number' || !Number.isInteger(port) || port <= 0) return undefined
72
+ return `${server.protocol === 'https:' ? 'https:' : 'http:'}//127.0.0.1:${port}`
73
+ }
74
+
75
+ /** 宿主那两条路由,走本机回环。 */
76
+ export class LoopbackUsage implements UsageStatsTransport {
77
+ readonly #options: LoopbackUsageOptions
78
+
79
+ /**
80
+ * @param options - origin 解析函数、出站调用与超时。
81
+ */
82
+ constructor(options: LoopbackUsageOptions) {
83
+ this.#options = options
84
+ }
85
+
86
+ /**
87
+ * `GET /api/dsh-usage/overview`。
88
+ * @returns 宿主答的那份聚合,或者为什么没读到。
89
+ */
90
+ overview(): Promise<UsageStatsOutcome> {
91
+ return this.#read(USAGE_OVERVIEW_PATH)
92
+ }
93
+
94
+ /**
95
+ * `GET /api/dsh-usage/day?date=<day>`。
96
+ * @param day - 本地日期键 `YYYY-MM-DD`。
97
+ * @returns 那一天的台账,或者为什么没读到。
98
+ */
99
+ day(day: string): Promise<UsageStatsOutcome> {
100
+ return this.#read(`${USAGE_DAY_PATH}?date=${encodeURIComponent(day)}`)
101
+ }
102
+
103
+ /**
104
+ * 读一条路由。
105
+ *
106
+ * 没有 origin 是「这台宿主没有可寻址的 web 服务」,与插件没挂是两件事,所以它
107
+ * 落在 `failed` 上;只有 404 才落在 `missing` 上。
108
+ * @param path - 以 `/` 开头的路径,含查询串。
109
+ * @returns 读到的那一格。
110
+ */
111
+ async #read(path: string): Promise<UsageStatsOutcome> {
112
+ const origin = this.#origin()
113
+ if (origin === undefined) return { kind: 'failed', reason: 'this host has no web server origin' }
114
+ const call = this.#options.fetch ?? globalThis.fetch
115
+ try {
116
+ const response = await call(`${origin}${path}`, {
117
+ headers: { accept: 'application/json' },
118
+ signal: AbortSignal.timeout(this.#timeout()),
119
+ })
120
+ // 路由不存在 = 那台宿主没挂这个插件。这是关于宿主的实施事实,不是错误。
121
+ if (response.status === 404) return { kind: 'missing' }
122
+ if (!response.ok) return { kind: 'failed', reason: `HTTP ${response.status}` }
123
+ const body: unknown = await response.json().catch(() => undefined)
124
+ return body === undefined ? { kind: 'failed', reason: 'unrecognized response shape' } : { kind: 'answer', body }
125
+ } catch (error) {
126
+ return { kind: 'failed', reason: shortReason(error) }
127
+ }
128
+ }
129
+
130
+ /** 这一次读要用的 origin;解析本身抛错按「没有 origin」处理。 */
131
+ #origin(): string | undefined {
132
+ try {
133
+ return this.#options.origin()
134
+ } catch (error) {
135
+ this.#options.log(`the host web origin could not be resolved: ${shortReason(error)}`)
136
+ return undefined
137
+ }
138
+ }
139
+
140
+ /** 一次读的超时。 */
141
+ #timeout(): number {
142
+ return this.#options.timeoutMs ?? USAGE_PROBE_TIMEOUT_MS
143
+ }
144
+ }
145
+
146
+ /**
147
+ * 一句短原因:过线的只有「这次为什么没读到」,不是一整条堆栈。
148
+ * @param error - 抛出来的东西。
149
+ * @returns 至多 120 个字符的一行。
150
+ */
151
+ function shortReason(error: unknown): string {
152
+ const text = error instanceof Error ? error.message : String(error)
153
+ const line = text.split('\n')[0] ?? text
154
+ return line.length > 120 ? `${line.slice(0, 117)}...` : line
155
+ }
@@ -0,0 +1,296 @@
1
+ /**
2
+ * The bridge's own follow streams: one per session that holds a live card.
3
+ *
4
+ * §28 and §29 both describe things this bridge must report while it is the only
5
+ * party still awake, and everything that reports them used to hang off a
6
+ * client's own stream: a turn end was observed only while this bridge was
7
+ * draining a follow stream for a connected phone. A suspended app has no such
8
+ * stream — its socket is closed and the subscription is aborted with the
9
+ * connection — so the card frozen on its lock screen kept saying "running" long
10
+ * after the turn was over, and no APNs delivery ever failed, because nothing was
11
+ * ever sent.
12
+ *
13
+ * A standing watcher is that missing party: for one session with at least one
14
+ * registered live-activity token this bridge opens its OWN follow stream, under
15
+ * the same in-process owner peer every other gateway call speaks for, and turns
16
+ * the one frame it cares about — `turn/end` — into the two things a card needs:
17
+ * §28's notification and §29's card end, each addressed to that session alone.
18
+ *
19
+ * Five rules keep that from becoming a second, unaccountable scheduler:
20
+ *
21
+ * - a watcher exists exactly while its session holds a card token, reconciled by
22
+ * {@link StandingWatchers.sync} from the roster rather than from any client
23
+ * frame;
24
+ * - at most {@link WATCHER_LIMIT} streams are open at once; past that a session
25
+ * is logged once and left unwatched, so a card on a session that never ends
26
+ * cannot grow the set without bound;
27
+ * - dedupe is inherited, not added: a client that is also following the same
28
+ * session sees the same turn end, and the two reports collapse in the layers
29
+ * that already own that rule — §28.5's `(sessionId, event)` window and §29's
30
+ * identical-content key. No third window is introduced here;
31
+ * - a stream that ends on its own is re-armed after {@link WATCHER_REOPEN_MS},
32
+ * because the next turn is the next thing a card has to show;
33
+ * - nothing a watcher does can reach a client frame: every failure is one log
34
+ * line, and a stream that cannot be opened is dropped rather than retried in a
35
+ * tight loop.
36
+ * @module dsh-remote-bridge/host/watchers
37
+ */
38
+
39
+ import { isTurnStartDelta, SNAPSHOT_MAX_MESSAGES } from '../core/connection.ts'
40
+ import { deltaOfFollowFrame, MessageIndex, readFollowBaseline, SpawnCallIndex, ToolCallIndex } from '../core/dsh-frames.ts'
41
+ import { failureText, withServiceUnavailableRetry } from '../core/gateway-errors.ts'
42
+ import type { LiveActivityNotifier } from '../core/liveactivity.ts'
43
+ import { pushEventOfTurnEnd, type PushNotifier } from '../core/push.ts'
44
+ import type { TurnEndQuietGate } from '../core/turn-end-quiet.ts'
45
+ import { sessionAddress, wireArgs, type BridgeGateway, type GatewayPeer } from '../core/wire.ts'
46
+
47
+ /** Most standing streams this bridge keeps open at once. */
48
+ export const WATCHER_LIMIT = 64
49
+ /** How long a watcher waits before re-opening a stream that ended on its own. */
50
+ export const WATCHER_REOPEN_MS = 1_000
51
+
52
+ export interface StandingWatcherOptions {
53
+ /** The host's gateway, the same one the connections speak through. */
54
+ readonly gateway: BridgeGateway
55
+ /** The in-process owner peer every call of this bridge speaks for. */
56
+ readonly peer: GatewayPeer
57
+ /**
58
+ * Sessions that currently hold at least one registered live-activity token,
59
+ * read from the roster on every reconcile.
60
+ */
61
+ readonly sessions: () => readonly string[]
62
+ /** The card path of §29; absent is a bridge with no signing key. */
63
+ readonly liveActivity?: LiveActivityNotifier
64
+ /** The notification path of §28; absent for the same reason. */
65
+ readonly push?: PushNotifier
66
+ /**
67
+ * The gate both channels announce a finished turn through, so a card and a
68
+ * notification wait for the same quiet session. Absent is a watcher set built
69
+ * without one — a suite — and then both report at the frame.
70
+ */
71
+ readonly turnEndQuiet?: TurnEndQuietGate
72
+ readonly log: (message: string) => void
73
+ readonly limit?: number
74
+ readonly reopenMs?: number
75
+ readonly maxMessages?: number
76
+ }
77
+
78
+ /** One open stream, and the handle that closes it. */
79
+ interface Watching {
80
+ readonly controller: AbortController
81
+ }
82
+
83
+ /**
84
+ * The bridge's stand-in for a client that is no longer there.
85
+ *
86
+ * Deliberately inert when neither push path is configured: {@link sync} returns
87
+ * without opening anything, so a bridge without an Apple signing key keeps the
88
+ * exact stream count it had before this module existed.
89
+ */
90
+ export class StandingWatchers {
91
+ readonly #options: StandingWatcherOptions
92
+ /** Open streams by session id. */
93
+ readonly #open = new Map<string, Watching>()
94
+ /** Sessions a reconcile had to refuse for the cap, so each is logged once. */
95
+ readonly #refused = new Set<string>()
96
+ /** Pending re-arm timers, cleared on dispose. */
97
+ readonly #timers = new Set<NodeJS.Timeout>()
98
+ #disposed = false
99
+
100
+ constructor(options: StandingWatcherOptions) {
101
+ this.#options = options
102
+ }
103
+
104
+ /** @returns how many standing streams are open right now. */
105
+ get size(): number {
106
+ return this.#open.size
107
+ }
108
+
109
+ /** @returns whether this bridge has any path worth opening a stream for. */
110
+ get enabled(): boolean {
111
+ return this.#options.liveActivity !== undefined || this.#options.push !== undefined
112
+ }
113
+
114
+ /**
115
+ * Reconcile the open streams with the sessions that hold a card right now.
116
+ *
117
+ * Called when the roster changes (a registration arrived, a dead token was
118
+ * retired) and when a stream ends. Idempotent, and safe to call before the
119
+ * roster has been read: no session with a token means nothing to watch.
120
+ */
121
+ sync(): void {
122
+ if (this.#disposed || !this.enabled) return
123
+ let wanted: readonly string[]
124
+ try {
125
+ wanted = this.#options.sessions()
126
+ } catch (error) {
127
+ this.#options.log(`watcher reconcile failed: ${failureText(error)}`)
128
+ return
129
+ }
130
+ const desired = new Set(wanted)
131
+ for (const [sessionId, watching] of this.#open) {
132
+ if (desired.has(sessionId)) continue
133
+ this.#open.delete(sessionId)
134
+ watching.controller.abort()
135
+ this.#options.log(`watcher close session=${sessionId} reason=cards-gone`)
136
+ }
137
+ const limit = this.#options.limit ?? WATCHER_LIMIT
138
+ for (const sessionId of desired) {
139
+ if (this.#open.has(sessionId)) continue
140
+ if (this.#open.size >= limit) {
141
+ if (!this.#refused.has(sessionId)) {
142
+ this.#refused.add(sessionId)
143
+ this.#options.log(`watcher refused session=${sessionId} reason=limit(${String(limit)})`)
144
+ }
145
+ continue
146
+ }
147
+ this.#watch(sessionId)
148
+ }
149
+ }
150
+
151
+ /** Close every stream and drop every pending re-arm. Idempotent. */
152
+ dispose(): void {
153
+ if (this.#disposed) return
154
+ this.#disposed = true
155
+ for (const timer of this.#timers) clearTimeout(timer)
156
+ this.#timers.clear()
157
+ for (const watching of this.#open.values()) watching.controller.abort()
158
+ this.#open.clear()
159
+ }
160
+
161
+ /** Open one session's stream and start consuming it. */
162
+ #watch(sessionId: string): void {
163
+ const watching: Watching = { controller: new AbortController() }
164
+ this.#open.set(sessionId, watching)
165
+ this.#options.log(`watcher open session=${sessionId} reason=cards`)
166
+ void this.#run(sessionId, watching).catch((error: unknown) => {
167
+ // A watch that cannot even be started is one line: the caller is this
168
+ // bridge itself, and there is no frame to fail.
169
+ this.#options.log(`watcher failed session=${sessionId}: ${failureText(error)}`)
170
+ })
171
+ }
172
+
173
+ /** Consume one session's stream until it ends or is aborted. */
174
+ async #run(sessionId: string, watching: Watching): Promise<void> {
175
+ const signal = watching.controller.signal
176
+ let iterator: AsyncIterator<unknown>
177
+ try {
178
+ const stream = await withServiceUnavailableRetry(() => this.#options.gateway.stream({
179
+ namespace: 'session',
180
+ method: 'follow',
181
+ args: wireArgs('session', 'follow', {
182
+ address: sessionAddress(sessionId),
183
+ // The shape a connection opens: one stream per session carries both
184
+ // the baseline and the process-local deltas. The watcher needs no
185
+ // baseline — attaching is what makes it a party.
186
+ assistantStream: true,
187
+ maxMessages: this.#options.maxMessages ?? SNAPSHOT_MAX_MESSAGES,
188
+ }),
189
+ peer: this.#options.peer,
190
+ signal,
191
+ }))
192
+ iterator = stream[Symbol.asyncIterator]()
193
+ } catch (error) {
194
+ this.#options.log(`watcher stream refused session=${sessionId}: ${failureText(error)}`)
195
+ // Not re-armed: a stream the host refuses would be refused again on every
196
+ // retry, and the next roster change is the honest trigger to try once more.
197
+ this.#settle(sessionId, watching, false)
198
+ return
199
+ }
200
+ const toolCalls = new ToolCallIndex()
201
+ const messages = new MessageIndex()
202
+ // No capability gate here: a watcher publishes no frame, so the thread kind
203
+ // of a delta is none of its business.
204
+ const memory = { subagentThread: false, spawnCalls: new SpawnCallIndex() }
205
+ try {
206
+ const first = await iterator.next()
207
+ if (first.done === true || readFollowBaseline(first.value) === undefined) {
208
+ this.#options.log(`watcher stream unusable session=${sessionId}`)
209
+ await iterator.return?.()
210
+ this.#settle(sessionId, watching, false)
211
+ return
212
+ }
213
+ for (;;) {
214
+ const next = await iterator.next()
215
+ if (next.done === true) break
216
+ if (signal.aborted) break
217
+ const delta = deltaOfFollowFrame(next.value, toolCalls, messages, memory)
218
+ if (delta === undefined) continue
219
+ // Only an increment that proves this session's own work proves a new turn; a
220
+ // settled child, a usage count and a catalog change all arrive here without
221
+ // meaning the user prompted again.
222
+ if (delta.kind !== 'turn-end') {
223
+ if (isTurnStartDelta(delta)) this.#options.turnEndQuiet?.noteTurnStarted(sessionId)
224
+ continue
225
+ }
226
+ this.#turnEnded(sessionId, delta.reason)
227
+ }
228
+ } catch (error) {
229
+ if (!signal.aborted) this.#options.log(`watcher stream ended session=${sessionId}: ${failureText(error)}`)
230
+ } finally {
231
+ this.#settle(sessionId, watching)
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Report one turn end to both channels that need it.
237
+ *
238
+ * Both, on purpose: §28's notification is what wakes a phone that is not
239
+ * holding a socket, and §29's card end is what clears a lock screen. Reporting
240
+ * only one of them leaves the other surface stale, which is the exact state
241
+ * this module exists to end. Both go through the shared gate, so a watcher and
242
+ * a client that followed the same session announce it at the same instant — when
243
+ * the session is quiet — and never at the frame.
244
+ */
245
+ #turnEnded(sessionId: string, reason: string): void {
246
+ try {
247
+ const gate = this.#options.turnEndQuiet
248
+ if (gate !== undefined) {
249
+ gate.noteTurnEnd(sessionId, reason)
250
+ // Nothing has been sent at this point, so the line says what really
251
+ // happened: the end is held, and the gate's own line reports the send.
252
+ this.#options.log(`watcher turn-end session=${sessionId} reason=${reason} held=quiet-gate`)
253
+ return
254
+ }
255
+ this.#options.push?.notify(pushEventOfTurnEnd(reason), sessionId)
256
+ this.#options.liveActivity?.noteTurnEnd(sessionId, reason)
257
+ const pushed = this.#options.liveActivity?.enabled === true ? 'card' : 'notification-only'
258
+ this.#options.log(`watcher turn-end session=${sessionId} reason=${reason} pushed=${pushed}`)
259
+ } catch (error) {
260
+ this.#options.log(`watcher turn-end session=${sessionId} failed: ${failureText(error)}`)
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Forget one stream's handle, and re-arm it when that is the right answer.
266
+ * @param sessionId - the session whose stream is over.
267
+ * @param watching - the exact stream being settled, so a newer one is untouched.
268
+ * @param rearm - whether a stream that was open and then ended should come back.
269
+ */
270
+ #settle(sessionId: string, watching: Watching, rearm = true): void {
271
+ watching.controller.abort()
272
+ if (this.#open.get(sessionId) === watching) this.#open.delete(sessionId)
273
+ if (rearm) this.#rearm(sessionId)
274
+ }
275
+
276
+ /**
277
+ * Schedule one reconcile, so a session still holding a card gets its stream
278
+ * back after the stream it was on ended.
279
+ */
280
+ #rearm(sessionId: string): void {
281
+ if (this.#disposed || this.#open.has(sessionId)) return
282
+ let wanted = false
283
+ try {
284
+ wanted = this.#options.sessions().includes(sessionId)
285
+ } catch {
286
+ wanted = false
287
+ }
288
+ if (!wanted) return
289
+ const timer = setTimeout(() => {
290
+ this.#timers.delete(timer)
291
+ this.sync()
292
+ }, this.#options.reopenMs ?? WATCHER_REOPEN_MS)
293
+ timer.unref?.()
294
+ this.#timers.add(timer)
295
+ }
296
+ }