@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.
Files changed (78) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +93 -26
  3. package/README.zh.md +91 -26
  4. package/icon.svg +3 -0
  5. package/lib/client.js +274 -253
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +8891 -2433
  8. package/lib/types/client/PairEntry.d.ts +2 -2
  9. package/lib/types/client/PairPanel.d.ts +10 -2
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/locales.d.ts +10 -14
  12. package/lib/types/client/semantic.d.ts +9 -5
  13. package/lib/types/core/approvals.d.ts +24 -0
  14. package/lib/types/core/commands.d.ts +59 -0
  15. package/lib/types/core/connection.d.ts +124 -5
  16. package/lib/types/core/delta.d.ts +101 -0
  17. package/lib/types/core/devices.d.ts +98 -2
  18. package/lib/types/core/dsh-frames.d.ts +155 -4
  19. package/lib/types/core/envelope.d.ts +34 -0
  20. package/lib/types/core/extension.d.ts +144 -0
  21. package/lib/types/core/hub.d.ts +96 -20
  22. package/lib/types/core/jobs.d.ts +204 -0
  23. package/lib/types/core/liveactivity.d.ts +324 -0
  24. package/lib/types/core/protocol.d.ts +491 -2
  25. package/lib/types/core/push.d.ts +178 -0
  26. package/lib/types/core/questions.d.ts +109 -9
  27. package/lib/types/core/session-meta.d.ts +55 -1
  28. package/lib/types/core/squads.d.ts +130 -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/core/wire.d.ts +1 -1
  32. package/lib/types/core/ws-frames.d.ts +11 -0
  33. package/lib/types/host/apns.d.ts +151 -0
  34. package/lib/types/host/squads-ledger.d.ts +39 -0
  35. package/lib/types/host/squads.d.ts +77 -0
  36. package/lib/types/host/usage-stats.d.ts +75 -0
  37. package/lib/types/host/watchers.d.ts +88 -0
  38. package/lib/types/host/websocket.d.ts +8 -1
  39. package/lib/types/index.d.ts +34 -3
  40. package/lib/types/mount-once.d.ts +55 -0
  41. package/locale/en.json +6 -0
  42. package/locale/ru.json +6 -0
  43. package/locale/zh.json +6 -0
  44. package/package.json +20 -14
  45. package/src/client/PairEntry.tsx +58 -31
  46. package/src/client/PairPanel.tsx +181 -97
  47. package/src/client/icons.tsx +17 -60
  48. package/src/client/locales.ts +15 -23
  49. package/src/client/panel.module.css +239 -186
  50. package/src/client/semantic.ts +10 -6
  51. package/src/core/approvals.ts +32 -1
  52. package/src/core/commands.ts +95 -0
  53. package/src/core/connection.ts +1483 -31
  54. package/src/core/delta.ts +204 -0
  55. package/src/core/devices.ts +221 -3
  56. package/src/core/dsh-frames.ts +365 -8
  57. package/src/core/envelope.ts +46 -0
  58. package/src/core/extension.ts +197 -0
  59. package/src/core/hub.ts +441 -49
  60. package/src/core/jobs.ts +372 -0
  61. package/src/core/liveactivity.ts +833 -0
  62. package/src/core/protocol.ts +556 -2
  63. package/src/core/push.ts +354 -0
  64. package/src/core/questions.ts +264 -17
  65. package/src/core/session-meta.ts +73 -1
  66. package/src/core/squads.ts +345 -0
  67. package/src/core/usage-stats.ts +424 -0
  68. package/src/core/usage.ts +937 -0
  69. package/src/core/wire.ts +13 -1
  70. package/src/core/ws-frames.ts +14 -0
  71. package/src/host/apns.ts +320 -0
  72. package/src/host/squads-ledger.ts +105 -0
  73. package/src/host/squads.ts +206 -0
  74. package/src/host/usage-stats.ts +155 -0
  75. package/src/host/watchers.ts +272 -0
  76. package/src/host/websocket.ts +37 -3
  77. package/src/index.ts +310 -9
  78. package/src/mount-once.ts +142 -0
@@ -0,0 +1,206 @@
1
+ /**
2
+ * The squad domain as this Host reaches it: the `dsh-agents` HTTP routes over
3
+ * this machine's own loopback origin, with its ledger as a read-only fallback.
4
+ *
5
+ * The plugin's routes are the preferred source because they are the live one: a
6
+ * definition the user just saved and a run that is still settling are both in the
7
+ * plugin's own process state, while the ledger is the last committed write. So the
8
+ * read is `GET /dsh-agents/api/state` and the two launches are POSTs, all
9
+ * addressed at the origin `webServer` already serves and all carrying the `origin`
10
+ * header the plugin's browser fence reads as its same-origin signal.
11
+ *
12
+ * A loopback call that cannot connect at all — nothing bound, a refused
13
+ * connection, or a deadline — is what makes the fallback necessary: the
14
+ * definitions are then read from the plugin's ledger, read-only, and the two run
15
+ * commands fail closed with `squads-run-unavailable` instead of answering a run
16
+ * that never started. An answer of any status is NOT a fallback: it is the plugin
17
+ * speaking, and its refusal crosses with its own code.
18
+ * @module dsh-remote-bridge/host/squads
19
+ */
20
+
21
+ import { CODE_SQUADS_RUN_UNAVAILABLE, CODE_SQUADS_UNAVAILABLE } from '../core/protocol.ts'
22
+ import { SquadRefusal, type SquadMemberRunRequest, type SquadRunRequest, type SquadTransport } from '../core/squads.ts'
23
+ import { readSquadLedger } from './squads-ledger.ts'
24
+
25
+ /**
26
+ * The three routes this channel drives, restated from the plugin's own
27
+ * `DSH_AGENTS_ROUTE_PATHS`. They are spelled here rather than imported: this
28
+ * package depends on no other plugin, so a frozen path is the only thing that can
29
+ * cross between them.
30
+ */
31
+ export const SQUADS_STATE_PATH = '/dsh-agents/api/state'
32
+ export const SQUADS_RUN_MEMBER_PATH = '/dsh-agents/api/run'
33
+ export const SQUADS_RUN_SQUAD_PATH = '/dsh-agents/api/squad/run'
34
+
35
+ /** Deadline behind one loopback read: the plugin answers a state read from memory. */
36
+ export const SQUADS_LOOPBACK_TIMEOUT_MS = 5_000
37
+ /**
38
+ * Deadline behind one launch. A launch composes a session, restores it when it is
39
+ * cold and may queue a first message, so it is allowed far longer than a read; the
40
+ * bound exists to keep one stuck call from holding a connection open, not to time
41
+ * the plugin's work.
42
+ */
43
+ export const SQUADS_RUN_TIMEOUT_MS = 60_000
44
+
45
+ /** What one loopback call produced: the host's answer, or no connection at all. */
46
+ type LoopbackOutcome =
47
+ | { readonly kind: 'answer'; readonly status: number; readonly body: unknown }
48
+ | { readonly kind: 'unreachable'; readonly reason: string }
49
+
50
+ /** The answer half of {@link LoopbackOutcome}. */
51
+ type LoopbackAnswer = Extract<LoopbackOutcome, { kind: 'answer' }>
52
+
53
+ /** Construction options; the origin and the ledger directory are resolved per call. */
54
+ export interface LoopbackSquadsOptions {
55
+ /** The origin this host's own web server listens on, or undefined before it binds. */
56
+ readonly origin: () => string | undefined
57
+ /** The plugin-owned directory `dsh-agents` keeps its ledger in. */
58
+ readonly ledgerDirectory: () => string
59
+ /** Outbound call seam; the production default is the process's own fetch. */
60
+ readonly fetch?: typeof fetch
61
+ /** Deadline behind one read; the default is {@link SQUADS_LOOPBACK_TIMEOUT_MS}. */
62
+ readonly timeoutMs?: number
63
+ /** Deadline behind one launch; the default is {@link SQUADS_RUN_TIMEOUT_MS}. */
64
+ readonly runTimeoutMs?: number
65
+ readonly log: (message: string) => void
66
+ }
67
+
68
+ function record(value: unknown): Record<string, unknown> | undefined {
69
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : undefined
70
+ }
71
+
72
+ function messageOf(error: unknown): string {
73
+ return error instanceof Error ? error.message : String(error)
74
+ }
75
+
76
+ function parseJson(text: string): unknown {
77
+ try {
78
+ return JSON.parse(text)
79
+ } catch {
80
+ return undefined
81
+ }
82
+ }
83
+
84
+ /** The squad domain over loopback, with the ledger as its read-only fallback. */
85
+ export class LoopbackSquads implements SquadTransport {
86
+ readonly #options: LoopbackSquadsOptions
87
+
88
+ constructor(options: LoopbackSquadsOptions) {
89
+ this.#options = options
90
+ }
91
+
92
+ /**
93
+ * Read the definitions and runs.
94
+ *
95
+ * A loopback call that connects answers for the domain, its refusals included.
96
+ * A call that cannot connect at all falls back to the ledger, and a ledger that
97
+ * is missing or unreadable refuses the read rather than answering an empty
98
+ * board.
99
+ */
100
+ async state(): Promise<unknown> {
101
+ const call = await this.#request('GET', SQUADS_STATE_PATH)
102
+ if (call.kind === 'unreachable') {
103
+ this.#options.log('squad state read fell back to the ledger: ' + call.reason)
104
+ return await readSquadLedger(this.#options.ledgerDirectory())
105
+ }
106
+ return this.#bodyOf(call, SQUADS_STATE_PATH)
107
+ }
108
+
109
+ /**
110
+ * Launch one member session through the plugin's own run route.
111
+ * @param request - the squad, the member and the optional first message.
112
+ */
113
+ async runMember(request: SquadMemberRunRequest): Promise<unknown> {
114
+ const call = await this.#request('POST', SQUADS_RUN_MEMBER_PATH, {
115
+ teamId: request.squadId,
116
+ memberId: request.memberId,
117
+ ...(request.firstMessage === undefined ? {} : { firstMessage: request.firstMessage }),
118
+ }, this.#options.runTimeoutMs ?? SQUADS_RUN_TIMEOUT_MS)
119
+ if (call.kind === 'unreachable') throw this.#runUnavailable(call.reason)
120
+ return this.#bodyOf(call, SQUADS_RUN_MEMBER_PATH)
121
+ }
122
+
123
+ /**
124
+ * Launch the Lead session of one whole squad through the plugin's own squad run
125
+ * route.
126
+ * @param request - the squad and the optional goal its Lead is given.
127
+ */
128
+ async runSquad(request: SquadRunRequest): Promise<unknown> {
129
+ const call = await this.#request('POST', SQUADS_RUN_SQUAD_PATH, {
130
+ teamId: request.squadId,
131
+ ...(request.goal === undefined ? {} : { goal: request.goal }),
132
+ }, this.#options.runTimeoutMs ?? SQUADS_RUN_TIMEOUT_MS)
133
+ if (call.kind === 'unreachable') throw this.#runUnavailable(call.reason)
134
+ return this.#bodyOf(call, SQUADS_RUN_SQUAD_PATH)
135
+ }
136
+
137
+ /**
138
+ * The refusal behind a launch this host cannot perform.
139
+ * @param reason - why the loopback call produced no connection.
140
+ */
141
+ #runUnavailable(reason: string): SquadRefusal {
142
+ return new SquadRefusal(CODE_SQUADS_RUN_UNAVAILABLE, 'this host reached no dsh-agents run route over loopback (' + reason + '), and the read-only ledger cannot launch a session')
143
+ }
144
+
145
+ /**
146
+ * Read the body of an answer, or refuse with the code the plugin wrote.
147
+ *
148
+ * A non-2xx body carrying the plugin's `{ok:false, code, error}` crosses with
149
+ * that code and that sentence; any other status means this host does not serve
150
+ * the route at all, which is the one refusal this bridge names itself.
151
+ * @param answer - the connected answer.
152
+ * @param path - the route the answer came from, named in the refusal.
153
+ */
154
+ #bodyOf(answer: LoopbackAnswer, path: string): Record<string, unknown> {
155
+ const body = record(answer.body)
156
+ if (answer.status >= 200 && answer.status < 300) {
157
+ if (body === undefined) {
158
+ throw new SquadRefusal(CODE_SQUADS_UNAVAILABLE, 'the dsh-agents route ' + path + ' answered a body this bridge cannot read')
159
+ }
160
+ return body
161
+ }
162
+ if (body?.ok === false && typeof body.code === 'string') {
163
+ const text = typeof body.error === 'string' && body.error !== '' ? body.error : 'the dsh-agents host refused ' + path
164
+ throw new SquadRefusal(body.code, text)
165
+ }
166
+ throw new SquadRefusal(CODE_SQUADS_UNAVAILABLE, 'this host does not serve ' + path + ': it answered ' + String(answer.status))
167
+ }
168
+
169
+ /**
170
+ * One loopback call against this host's own origin.
171
+ * @param method - the route's own method.
172
+ * @param path - the route's exact path.
173
+ * @param body - the JSON body, for the two POST routes.
174
+ * @param timeoutMs - the deadline behind this one call.
175
+ * @returns the answer, or the reason no connection was made.
176
+ */
177
+ async #request(
178
+ method: 'GET' | 'POST',
179
+ path: string,
180
+ body?: Readonly<Record<string, unknown>>,
181
+ timeoutMs: number = this.#options.timeoutMs ?? SQUADS_LOOPBACK_TIMEOUT_MS,
182
+ ): Promise<LoopbackOutcome> {
183
+ const origin = this.#options.origin()
184
+ if (origin === undefined) return { kind: 'unreachable', reason: 'this host has bound no web server port' }
185
+ const call = this.#options.fetch ?? fetch
186
+ try {
187
+ const response = await call(origin + path, {
188
+ method,
189
+ // The plugin's fence admits this machine's own browser only: the socket has
190
+ // to be loopback and a same-origin signal has to be present, and an origin
191
+ // header naming this host is that signal.
192
+ headers: {
193
+ origin,
194
+ accept: 'application/json',
195
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
196
+ },
197
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
198
+ signal: AbortSignal.timeout(timeoutMs),
199
+ })
200
+ const text = await response.text()
201
+ return { kind: 'answer', status: response.status, body: parseJson(text) }
202
+ } catch (error) {
203
+ return { kind: 'unreachable', reason: messageOf(error) }
204
+ }
205
+ }
206
+ }
@@ -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,272 @@
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 { 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 { sessionAddress, wireArgs, type BridgeGateway, type GatewayPeer } from '../core/wire.ts'
45
+
46
+ /** Most standing streams this bridge keeps open at once. */
47
+ export const WATCHER_LIMIT = 64
48
+ /** How long a watcher waits before re-opening a stream that ended on its own. */
49
+ export const WATCHER_REOPEN_MS = 1_000
50
+
51
+ export interface StandingWatcherOptions {
52
+ /** The host's gateway, the same one the connections speak through. */
53
+ readonly gateway: BridgeGateway
54
+ /** The in-process owner peer every call of this bridge speaks for. */
55
+ readonly peer: GatewayPeer
56
+ /**
57
+ * Sessions that currently hold at least one registered live-activity token,
58
+ * read from the roster on every reconcile.
59
+ */
60
+ readonly sessions: () => readonly string[]
61
+ /** The card path of §29; absent is a bridge with no signing key. */
62
+ readonly liveActivity?: LiveActivityNotifier
63
+ /** The notification path of §28; absent for the same reason. */
64
+ readonly push?: PushNotifier
65
+ readonly log: (message: string) => void
66
+ readonly limit?: number
67
+ readonly reopenMs?: number
68
+ readonly maxMessages?: number
69
+ }
70
+
71
+ /** One open stream, and the handle that closes it. */
72
+ interface Watching {
73
+ readonly controller: AbortController
74
+ }
75
+
76
+ /**
77
+ * The bridge's stand-in for a client that is no longer there.
78
+ *
79
+ * Deliberately inert when neither push path is configured: {@link sync} returns
80
+ * without opening anything, so a bridge without an Apple signing key keeps the
81
+ * exact stream count it had before this module existed.
82
+ */
83
+ export class StandingWatchers {
84
+ readonly #options: StandingWatcherOptions
85
+ /** Open streams by session id. */
86
+ readonly #open = new Map<string, Watching>()
87
+ /** Sessions a reconcile had to refuse for the cap, so each is logged once. */
88
+ readonly #refused = new Set<string>()
89
+ /** Pending re-arm timers, cleared on dispose. */
90
+ readonly #timers = new Set<NodeJS.Timeout>()
91
+ #disposed = false
92
+
93
+ constructor(options: StandingWatcherOptions) {
94
+ this.#options = options
95
+ }
96
+
97
+ /** @returns how many standing streams are open right now. */
98
+ get size(): number {
99
+ return this.#open.size
100
+ }
101
+
102
+ /** @returns whether this bridge has any path worth opening a stream for. */
103
+ get enabled(): boolean {
104
+ return this.#options.liveActivity !== undefined || this.#options.push !== undefined
105
+ }
106
+
107
+ /**
108
+ * Reconcile the open streams with the sessions that hold a card right now.
109
+ *
110
+ * Called when the roster changes (a registration arrived, a dead token was
111
+ * retired) and when a stream ends. Idempotent, and safe to call before the
112
+ * roster has been read: no session with a token means nothing to watch.
113
+ */
114
+ sync(): void {
115
+ if (this.#disposed || !this.enabled) return
116
+ let wanted: readonly string[]
117
+ try {
118
+ wanted = this.#options.sessions()
119
+ } catch (error) {
120
+ this.#options.log(`watcher reconcile failed: ${failureText(error)}`)
121
+ return
122
+ }
123
+ const desired = new Set(wanted)
124
+ for (const [sessionId, watching] of this.#open) {
125
+ if (desired.has(sessionId)) continue
126
+ this.#open.delete(sessionId)
127
+ watching.controller.abort()
128
+ this.#options.log(`watcher close session=${sessionId} reason=cards-gone`)
129
+ }
130
+ const limit = this.#options.limit ?? WATCHER_LIMIT
131
+ for (const sessionId of desired) {
132
+ if (this.#open.has(sessionId)) continue
133
+ if (this.#open.size >= limit) {
134
+ if (!this.#refused.has(sessionId)) {
135
+ this.#refused.add(sessionId)
136
+ this.#options.log(`watcher refused session=${sessionId} reason=limit(${String(limit)})`)
137
+ }
138
+ continue
139
+ }
140
+ this.#watch(sessionId)
141
+ }
142
+ }
143
+
144
+ /** Close every stream and drop every pending re-arm. Idempotent. */
145
+ dispose(): void {
146
+ if (this.#disposed) return
147
+ this.#disposed = true
148
+ for (const timer of this.#timers) clearTimeout(timer)
149
+ this.#timers.clear()
150
+ for (const watching of this.#open.values()) watching.controller.abort()
151
+ this.#open.clear()
152
+ }
153
+
154
+ /** Open one session's stream and start consuming it. */
155
+ #watch(sessionId: string): void {
156
+ const watching: Watching = { controller: new AbortController() }
157
+ this.#open.set(sessionId, watching)
158
+ this.#options.log(`watcher open session=${sessionId} reason=cards`)
159
+ void this.#run(sessionId, watching).catch((error: unknown) => {
160
+ // A watch that cannot even be started is one line: the caller is this
161
+ // bridge itself, and there is no frame to fail.
162
+ this.#options.log(`watcher failed session=${sessionId}: ${failureText(error)}`)
163
+ })
164
+ }
165
+
166
+ /** Consume one session's stream until it ends or is aborted. */
167
+ async #run(sessionId: string, watching: Watching): Promise<void> {
168
+ const signal = watching.controller.signal
169
+ let iterator: AsyncIterator<unknown>
170
+ try {
171
+ const stream = await withServiceUnavailableRetry(() => this.#options.gateway.stream({
172
+ namespace: 'session',
173
+ method: 'follow',
174
+ args: wireArgs('session', 'follow', {
175
+ address: sessionAddress(sessionId),
176
+ // The shape a connection opens: one stream per session carries both
177
+ // the baseline and the process-local deltas. The watcher needs no
178
+ // baseline — attaching is what makes it a party.
179
+ assistantStream: true,
180
+ maxMessages: this.#options.maxMessages ?? SNAPSHOT_MAX_MESSAGES,
181
+ }),
182
+ peer: this.#options.peer,
183
+ signal,
184
+ }))
185
+ iterator = stream[Symbol.asyncIterator]()
186
+ } catch (error) {
187
+ this.#options.log(`watcher stream refused session=${sessionId}: ${failureText(error)}`)
188
+ // Not re-armed: a stream the host refuses would be refused again on every
189
+ // retry, and the next roster change is the honest trigger to try once more.
190
+ this.#settle(sessionId, watching, false)
191
+ return
192
+ }
193
+ const toolCalls = new ToolCallIndex()
194
+ const messages = new MessageIndex()
195
+ // No capability gate here: a watcher publishes no frame, so the thread kind
196
+ // of a delta is none of its business.
197
+ const memory = { subagentThread: false, spawnCalls: new SpawnCallIndex() }
198
+ try {
199
+ const first = await iterator.next()
200
+ if (first.done === true || readFollowBaseline(first.value) === undefined) {
201
+ this.#options.log(`watcher stream unusable session=${sessionId}`)
202
+ await iterator.return?.()
203
+ this.#settle(sessionId, watching, false)
204
+ return
205
+ }
206
+ for (;;) {
207
+ const next = await iterator.next()
208
+ if (next.done === true) break
209
+ if (signal.aborted) break
210
+ const delta = deltaOfFollowFrame(next.value, toolCalls, messages, memory)
211
+ if (delta === undefined || delta.kind !== 'turn-end') continue
212
+ this.#turnEnded(sessionId, delta.reason)
213
+ }
214
+ } catch (error) {
215
+ if (!signal.aborted) this.#options.log(`watcher stream ended session=${sessionId}: ${failureText(error)}`)
216
+ } finally {
217
+ this.#settle(sessionId, watching)
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Report one turn end to both channels that need it.
223
+ *
224
+ * Both, on purpose: §28's notification is what wakes a phone that is not
225
+ * holding a socket, and §29's card end is what clears a lock screen. Reporting
226
+ * only one of them leaves the other surface stale, which is the exact state
227
+ * this module exists to end.
228
+ */
229
+ #turnEnded(sessionId: string, reason: string): void {
230
+ try {
231
+ this.#options.push?.notify(pushEventOfTurnEnd(reason), sessionId)
232
+ this.#options.liveActivity?.noteTurnEnd(sessionId, reason)
233
+ const pushed = this.#options.liveActivity?.enabled === true ? 'card' : 'notification-only'
234
+ this.#options.log(`watcher turn-end session=${sessionId} reason=${reason} pushed=${pushed}`)
235
+ } catch (error) {
236
+ this.#options.log(`watcher turn-end session=${sessionId} failed: ${failureText(error)}`)
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Forget one stream's handle, and re-arm it when that is the right answer.
242
+ * @param sessionId - the session whose stream is over.
243
+ * @param watching - the exact stream being settled, so a newer one is untouched.
244
+ * @param rearm - whether a stream that was open and then ended should come back.
245
+ */
246
+ #settle(sessionId: string, watching: Watching, rearm = true): void {
247
+ watching.controller.abort()
248
+ if (this.#open.get(sessionId) === watching) this.#open.delete(sessionId)
249
+ if (rearm) this.#rearm(sessionId)
250
+ }
251
+
252
+ /**
253
+ * Schedule one reconcile, so a session still holding a card gets its stream
254
+ * back after the stream it was on ended.
255
+ */
256
+ #rearm(sessionId: string): void {
257
+ if (this.#disposed || this.#open.has(sessionId)) return
258
+ let wanted = false
259
+ try {
260
+ wanted = this.#options.sessions().includes(sessionId)
261
+ } catch {
262
+ wanted = false
263
+ }
264
+ if (!wanted) return
265
+ const timer = setTimeout(() => {
266
+ this.#timers.delete(timer)
267
+ this.sync()
268
+ }, this.#options.reopenMs ?? WATCHER_REOPEN_MS)
269
+ timer.unref?.()
270
+ this.#timers.add(timer)
271
+ }
272
+ }