@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.
- package/README.i18n.yaml +2 -2
- package/README.md +75 -18
- package/README.zh.md +74 -18
- package/lib/client.js +783 -260
- package/lib/client.js.map +1 -1
- package/lib/index.js +15849 -2913
- package/lib/types/client/PairEntry.d.ts +2 -2
- package/lib/types/client/PairPanel.d.ts +10 -2
- package/lib/types/client/UiPresentRow.d.ts +13 -0
- package/lib/types/client/icons.d.ts +5 -13
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/locales.d.ts +24 -15
- package/lib/types/client/semantic.d.ts +9 -5
- package/lib/types/client/toolview-slot.d.ts +68 -0
- package/lib/types/client/ui-card.d.ts +160 -0
- package/lib/types/core/commands.d.ts +59 -0
- package/lib/types/core/connection.d.ts +106 -0
- package/lib/types/core/devices.d.ts +102 -2
- package/lib/types/core/extension.d.ts +13 -0
- package/lib/types/core/hub.d.ts +129 -15
- package/lib/types/core/liveactivity.d.ts +324 -0
- package/lib/types/core/protocol.d.ts +328 -5
- package/lib/types/core/push.d.ts +186 -0
- package/lib/types/core/questions.d.ts +61 -9
- package/lib/types/core/session-meta.d.ts +55 -1
- package/lib/types/core/squads.d.ts +130 -0
- package/lib/types/core/turn-end-quiet.d.ts +135 -0
- package/lib/types/core/ui.d.ts +238 -0
- package/lib/types/core/usage-stats.d.ts +160 -0
- package/lib/types/core/usage.d.ts +294 -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/ui-tools.d.ts +80 -0
- package/lib/types/host/usage-stats.d.ts +75 -0
- package/lib/types/host/watchers.d.ts +95 -0
- package/lib/types/index.d.ts +47 -3
- package/package.json +15 -14
- package/src/client/PairEntry.tsx +58 -31
- package/src/client/PairPanel.tsx +181 -97
- package/src/client/UiPresentRow.tsx +149 -0
- package/src/client/icons.tsx +17 -60
- package/src/client/index.ts +11 -0
- package/src/client/locales.ts +36 -24
- package/src/client/panel.module.css +239 -186
- package/src/client/semantic.ts +10 -6
- package/src/client/toolview-slot.ts +84 -0
- package/src/client/ui-card.ts +368 -0
- package/src/client/ui-present.module.css +87 -0
- package/src/core/commands.ts +95 -0
- package/src/core/connection.ts +811 -12
- package/src/core/devices.ts +337 -5
- package/src/core/extension.ts +20 -0
- package/src/core/hub.ts +518 -43
- package/src/core/liveactivity.ts +833 -0
- package/src/core/protocol.ts +370 -5
- package/src/core/push.ts +385 -0
- package/src/core/questions.ts +81 -10
- package/src/core/session-meta.ts +73 -1
- package/src/core/squads.ts +345 -0
- package/src/core/turn-end-quiet.ts +388 -0
- package/src/core/ui.ts +398 -0
- package/src/core/usage-stats.ts +424 -0
- package/src/core/usage.ts +937 -0
- package/src/core/wire.ts +8 -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/ui-tools.ts +233 -0
- package/src/host/usage-stats.ts +155 -0
- package/src/host/watchers.ts +296 -0
- package/src/index.ts +327 -10
package/src/core/hub.ts
CHANGED
|
@@ -2,18 +2,35 @@
|
|
|
2
2
|
* The bridge's process-wide connection registry and its claims on
|
|
3
3
|
* `approval/request` and `user-questions/request`.
|
|
4
4
|
*
|
|
5
|
-
* The hub is what makes "phone not answering equals refusal" true:
|
|
6
|
-
* is claimed only while at least one paired device is connected, the publish
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
5
|
+
* The hub is what makes "phone not answering equals refusal" true: an approval
|
|
6
|
+
* is claimed only while at least one paired device is connected, the publish has
|
|
7
|
+
* to actually reach someone, and every other path (timeout, agent cancellation,
|
|
8
|
+
* the last phone leaving) delegates to the next answerer, which the Host
|
|
9
|
+
* normalizes to `'unavailable'`.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
11
|
+
* A user question adds the one case where "reach someone" is the notification
|
|
12
|
+
* rather than the socket: with no paired connection on the wire but a device on
|
|
13
|
+
* the roster that registered for pushes, the question is claimed for that phone
|
|
14
|
+
* and the alert is its delivery (§11.3, §32). One predicate decides it — "can a
|
|
15
|
+
* device that is reachable right now receive a question card" — and it is asked
|
|
16
|
+
* again every time a connection finishes its hello, because a client that never
|
|
17
|
+
* declares `questions.v1` going online turns that answer into no.
|
|
18
|
+
*
|
|
19
|
+
* The claim on `user-questions/request` follows the same rules, with three
|
|
12
20
|
* differences that belong to the host's own semantics: delegating is not a
|
|
13
21
|
* refusal, because only a phone that declares `questions.v1` is ever shown the
|
|
14
|
-
* question;
|
|
22
|
+
* question; a question is named on the wire even when the host named none,
|
|
15
23
|
* because a blocking ask carries no call id and the phone still needs a handle
|
|
16
|
-
* to answer with
|
|
24
|
+
* to answer with; and the claim outlives the last paired device by a grace
|
|
25
|
+
* window, because a phone whose app the system suspended has refused nothing.
|
|
26
|
+
*
|
|
27
|
+
* A presented page (`ui.present`, protocol §35) is the second claim that takes a
|
|
28
|
+
* grace window, and it takes the same one: the tool call it blocks is the agent's
|
|
29
|
+
* own wait, the card is the only place its answer can come from, and a phone that
|
|
30
|
+
* was suspended has refused nothing either. It differs in one direction only —
|
|
31
|
+
* there is no "next answerer" to hand a card back to, so a window that runs out
|
|
32
|
+
* ends the tool call as a refusal (§35.5: the host side reads it as a timeout)
|
|
33
|
+
* rather than starting another answerer.
|
|
17
34
|
* @module dsh-remote-bridge/core/hub
|
|
18
35
|
*/
|
|
19
36
|
|
|
@@ -21,8 +38,12 @@ import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
|
|
|
21
38
|
import type { PendingPromptView } from './approvals.ts'
|
|
22
39
|
import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts'
|
|
23
40
|
import { BridgeConnection } from './connection.ts'
|
|
24
|
-
import { CAP_APPROVALS, CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
|
|
25
|
-
import
|
|
41
|
+
import { CAP_APPROVALS, CAP_QUESTIONS, CAP_UI, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST, TOPIC_UI_REQUEST } from './protocol.ts'
|
|
42
|
+
import { questionPayload } from './questions.ts'
|
|
43
|
+
import type { ClaimedQuestion, QuestionAnswer, UserQuestionRequestLike } from './questions.ts'
|
|
44
|
+
import { isDeadPushToken, type PushDeliveryReport } from './push.ts'
|
|
45
|
+
import { uiPayload } from './ui.ts'
|
|
46
|
+
import type { JsonValue, UiCardView, UiPresentOutcome, UiRefusalReason } from './ui.ts'
|
|
26
47
|
|
|
27
48
|
/**
|
|
28
49
|
* The fields of an approval question this bridge reads. Structural on purpose:
|
|
@@ -63,32 +84,105 @@ function approvalPayload(prompt: PendingPromptView): ApprovalRequestPayload {
|
|
|
63
84
|
}
|
|
64
85
|
|
|
65
86
|
/**
|
|
66
|
-
*
|
|
87
|
+
* How long a user question outlives the last paired device, in milliseconds.
|
|
67
88
|
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
89
|
+
* A push notification carries a session link and nothing else: the phone can
|
|
90
|
+
* draw a question card only while this bridge still holds the claim, and it has
|
|
91
|
+
* to reconnect before it can read one. A phone whose app was suspended is gone
|
|
92
|
+
* for tens of seconds, so releasing the claim the instant its socket drops
|
|
93
|
+
* decides the question for it — the ask went back to the host's own answerer
|
|
94
|
+
* chain, the Mac showed the card, and the tap that arrived afterwards opened a
|
|
95
|
+
* session with nothing in it (measured 2026-10-23). The window is that reconnect
|
|
96
|
+
* budget, not a second deadline: a claim no phone came back for is released on
|
|
97
|
+
* expiry exactly as it was before.
|
|
75
98
|
*/
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
99
|
+
export const QUESTION_CLAIM_GRACE_MS = 60_000
|
|
100
|
+
|
|
101
|
+
// 同一个窗口也覆盖 §35 的整页卡:卡片同样只在「最后一次配对设备离开」时启动,只在
|
|
102
|
+
// 确有卡片被持有时启动,桥卸载时立即释放。窗口长度不新造旋钮——手机回来答题的时间
|
|
103
|
+
// 预算对提问与对卡片是同一件事,两处各写一个六万毫秒的常量只会让它们漂开。
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* How long a user question is held for a phone this bridge reached by
|
|
107
|
+
* notification only, in milliseconds (§32.2).
|
|
108
|
+
*
|
|
109
|
+
* Inside this window the question exists only on the phone's side: the alert is
|
|
110
|
+
* out, no socket has it, and the host's own answerer chain has not been started.
|
|
111
|
+
* When it runs out the claim is withdrawn and delegated, so the agent behind a
|
|
112
|
+
* timed ask waits at most this long past its own deadline and the agent behind a
|
|
113
|
+
* blocking ask (no call id, no deadline) waits at most this long in total — an
|
|
114
|
+
* accepted cost, because the alternative is a question that vanished while the
|
|
115
|
+
* phone was asleep. The window is the bridge's own constant and not the host's:
|
|
116
|
+
* a deployment overrides it, the host never sees it.
|
|
117
|
+
*/
|
|
118
|
+
export const OFFLINE_QUESTION_CLAIM_TTL_MS = 600_000
|
|
119
|
+
|
|
120
|
+
// Those two windows are different timers and never one. QUESTION_CLAIM_GRACE_MS
|
|
121
|
+
// is a grace on the way OUT: a phone was on the wire, it left, and the window is
|
|
122
|
+
// that phone's reconnect budget before the held claim is delegated.
|
|
123
|
+
// OFFLINE_QUESTION_CLAIM_TTL_MS is the whole lifetime of a claim that never had a
|
|
124
|
+
// phone on the wire at all. One claim can be covered by both in turn — claimed for
|
|
125
|
+
// the absent phone, handed to the phone that then declared the channel, left by
|
|
126
|
+
// that phone again — and whichever is due first releases it. The release is
|
|
127
|
+
// idempotent (the claim is deleted before it is delegated and the chain it starts
|
|
128
|
+
// is memoized), so the later timer finds no claim and the host's own answerer is
|
|
129
|
+
// started at most once.
|
|
130
|
+
|
|
131
|
+
/** Which path a user question takes right now (§11.3). */
|
|
132
|
+
type QuestionMode = 'online' | 'offline' | 'nobody'
|
|
133
|
+
|
|
134
|
+
/** What the hub is built with: the bridge's shared options plus the windows it owns. */
|
|
135
|
+
export interface BridgeHubOptions extends BridgeConnectionOptions {
|
|
136
|
+
/**
|
|
137
|
+
* The offline claim window, in milliseconds.
|
|
138
|
+
*
|
|
139
|
+
* Defaults to {@link OFFLINE_QUESTION_CLAIM_TTL_MS}; a deployment knob, and the
|
|
140
|
+
* seam a suite uses to move the window instead of waiting it out.
|
|
141
|
+
*/
|
|
142
|
+
readonly offlineClaimTtlMs?: number
|
|
84
143
|
}
|
|
85
144
|
|
|
145
|
+
/**
|
|
146
|
+
* What one `ui.present` call ended as, with the count of connections that took
|
|
147
|
+
* the first frame.
|
|
148
|
+
*
|
|
149
|
+
* The count is here rather than in the card registry because it is a fact about
|
|
150
|
+
* delivery: the registry owns the claim, the hub owns the fan-out, and a client
|
|
151
|
+
* count read back out of the claim would be a second answer to the same question.
|
|
152
|
+
* It rides the tool result so the desktop can say how many screens the page
|
|
153
|
+
* reached (§35.10).
|
|
154
|
+
*/
|
|
155
|
+
export type UiPresentReply =
|
|
156
|
+
| { readonly ok: true; readonly delivered: number; readonly type: string; readonly payload?: JsonValue }
|
|
157
|
+
| { readonly ok: false; readonly delivered: number; readonly reason: UiRefusalReason }
|
|
158
|
+
|
|
86
159
|
/** The bridge's live connections plus the answerer it composes onto the approval chain. */
|
|
87
160
|
export class BridgeHub {
|
|
88
|
-
readonly #options:
|
|
161
|
+
readonly #options: BridgeHubOptions
|
|
89
162
|
readonly #connections = new Set<BridgeConnection>()
|
|
163
|
+
/**
|
|
164
|
+
* The release this hub has scheduled for the user questions no paired device
|
|
165
|
+
* can answer any more. The claim table is global, so one timer covers every
|
|
166
|
+
* claim and there is never more than one of them.
|
|
167
|
+
*/
|
|
168
|
+
#questionReleaseTimer: NodeJS.Timeout | undefined
|
|
169
|
+
/**
|
|
170
|
+
* The offline claims still waiting on a phone, by wire call id, each with the
|
|
171
|
+
* timer that holds it for its window.
|
|
172
|
+
*
|
|
173
|
+
* A question leaves this table the moment the phone takes it over, answers it,
|
|
174
|
+
* or the window releases it, so a call id in here is a question no reachable
|
|
175
|
+
* device has been shown — which is exactly what {@link #reviewOfflineClaims}
|
|
176
|
+
* withdraws when a hello makes that permanent.
|
|
177
|
+
*/
|
|
178
|
+
readonly #offlineClaims = new Map<string, NodeJS.Timeout>()
|
|
179
|
+
/**
|
|
180
|
+
* 整页卡(§35)的那一个释放窗口。卡表是全局的,所以一个定时器覆盖每一张卡,
|
|
181
|
+
* 同一时刻只可能有一个;它与 {@link #questionReleaseTimer} 各管各的通道。
|
|
182
|
+
*/
|
|
183
|
+
#uiReleaseTimer: NodeJS.Timeout | undefined
|
|
90
184
|
|
|
91
|
-
constructor(options:
|
|
185
|
+
constructor(options: BridgeHubOptions) {
|
|
92
186
|
this.#options = options
|
|
93
187
|
}
|
|
94
188
|
|
|
@@ -115,6 +209,8 @@ export class BridgeHub {
|
|
|
115
209
|
onDeclare: (fresh) => {
|
|
116
210
|
this.replayQuestions(fresh)
|
|
117
211
|
this.replayApprovals(fresh)
|
|
212
|
+
this.replayUi(fresh)
|
|
213
|
+
this.#reviewOfflineClaims()
|
|
118
214
|
},
|
|
119
215
|
},
|
|
120
216
|
transport,
|
|
@@ -122,6 +218,9 @@ export class BridgeHub {
|
|
|
122
218
|
)
|
|
123
219
|
this.#connections.add(connection)
|
|
124
220
|
connection.startHeartbeat()
|
|
221
|
+
// A paired device is the phone the window was being held open for: it is
|
|
222
|
+
// here now, so the release it was waiting out is no longer due.
|
|
223
|
+
if (connection.paired) this.#cancelQuestionRelease()
|
|
125
224
|
if (auth !== undefined) void this.#options.roster.touch(auth.deviceId).catch(() => undefined)
|
|
126
225
|
this.#options.log(`connection open (${auth === undefined ? 'unpaired' : `device ${auth.deviceId}`})`)
|
|
127
226
|
return connection
|
|
@@ -129,18 +228,23 @@ export class BridgeHub {
|
|
|
129
228
|
|
|
130
229
|
/**
|
|
131
230
|
* Forget one connection and abort everything it owns. When it was the last
|
|
132
|
-
* paired device, every pending
|
|
231
|
+
* paired device, every pending approval is withdrawn at once and every pending
|
|
232
|
+
* user question is released when its grace window ends.
|
|
133
233
|
*/
|
|
134
234
|
detach(connection: BridgeConnection): void {
|
|
135
235
|
this.#connections.delete(connection)
|
|
136
236
|
connection.dispose()
|
|
137
237
|
if (this.pairedClients > 0) return
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
//
|
|
142
|
-
|
|
143
|
-
|
|
238
|
+
// An approval takes no window: the tool behind it is the agent's own wait,
|
|
239
|
+
// and a card no connected phone can answer must not hold it a second longer.
|
|
240
|
+
this.#abandonApprovals()
|
|
241
|
+
// A user question is delegated rather than refused, so the next answerer in
|
|
242
|
+
// the host's chain decides and the question's own deadline still holds — but
|
|
243
|
+
// only once the window in which the phone can come back for it has run out.
|
|
244
|
+
if (this.#options.questions.size > 0) this.#armQuestionRelease()
|
|
245
|
+
// 一张已经被手机看到的整页卡拿同一个窗口(§35.5),理由与提问逐字相同:那条
|
|
246
|
+
// 工具调用唯一的答案通道就是这张卡,手机在系统挂起它的时候什么都没拒绝。
|
|
247
|
+
if (this.#options.ui.size > 0) this.#armUiRelease()
|
|
144
248
|
}
|
|
145
249
|
|
|
146
250
|
/**
|
|
@@ -165,8 +269,17 @@ export class BridgeHub {
|
|
|
165
269
|
*/
|
|
166
270
|
replayQuestions(connection: BridgeConnection): void {
|
|
167
271
|
if (!connection.paired || !connection.declares(CAP_QUESTIONS)) return
|
|
168
|
-
|
|
169
|
-
|
|
272
|
+
// A phone that can take a card is on the wire: the windows that held these
|
|
273
|
+
// claims for nobody are over. The claims themselves are handed over below
|
|
274
|
+
// rather than released — they are this phone's to answer now.
|
|
275
|
+
this.#cancelOfflineClaims()
|
|
276
|
+
// The claim's own state, not `open` for every claim: a question whose
|
|
277
|
+
// foreground wait the host already ended is `continued`, and replaying it as
|
|
278
|
+
// open tells the phone to wait on an agent that has already moved on. The
|
|
279
|
+
// held set is read the way `question.list` publishes it, so the replayed card
|
|
280
|
+
// and the row the phone reads back stay one shape.
|
|
281
|
+
for (const held of this.#options.questions.listed()) {
|
|
282
|
+
connection.emit(TOPIC_QUESTION_REQUEST, held.payload)
|
|
170
283
|
}
|
|
171
284
|
}
|
|
172
285
|
|
|
@@ -193,6 +306,29 @@ export class BridgeHub {
|
|
|
193
306
|
}
|
|
194
307
|
}
|
|
195
308
|
|
|
309
|
+
/**
|
|
310
|
+
* Hand one freshly declared connection the cards this bridge still holds (§35.5).
|
|
311
|
+
*
|
|
312
|
+
* Without this, a presentation raised while the phone was reconnecting stays on
|
|
313
|
+
* the host with no page anywhere on the phone: the first `ui.request` was
|
|
314
|
+
* addressed to the clients that had already announced the channel. The replay
|
|
315
|
+
* emits a frame and nothing else — it claims no card and moves no deadline, so
|
|
316
|
+
* re-handing a page never lengthens how long the agent waits for it.
|
|
317
|
+
*
|
|
318
|
+
* A phone that can take a card is on the wire, so the window that held those
|
|
319
|
+
* cards for nobody is over: it is cancelled here rather than at attach, because
|
|
320
|
+
* only a connection that DECLARED the channel can actually receive one (§11.5's
|
|
321
|
+
* own judgement, which §35.5 reuses).
|
|
322
|
+
* @param connection - the connection that just declared its capabilities.
|
|
323
|
+
*/
|
|
324
|
+
replayUi(connection: BridgeConnection): void {
|
|
325
|
+
if (!connection.paired || !connection.declares(CAP_UI)) return
|
|
326
|
+
this.#cancelUiRelease()
|
|
327
|
+
for (const held of this.#options.ui.listed()) {
|
|
328
|
+
connection.emit(TOPIC_UI_REQUEST, held.payload)
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
196
332
|
/**
|
|
197
333
|
* Publish one event to every paired device that announced a capability.
|
|
198
334
|
* @returns how many connections actually took the frame.
|
|
@@ -225,6 +361,15 @@ export class BridgeHub {
|
|
|
225
361
|
// A question nobody could receive is withdrawn immediately instead of
|
|
226
362
|
// waiting out the phone's timeout with the agent blocked on it.
|
|
227
363
|
if (delivered === 0) this.#options.approvals.abandon([prompt.id])
|
|
364
|
+
// Only a claim that reached someone is worth a notification: the question a
|
|
365
|
+
// withdrawn claim stood for can no longer be answered by any phone, and a
|
|
366
|
+
// notification about it would be a card with nothing behind it (§28.5).
|
|
367
|
+
else {
|
|
368
|
+
this.#options.push?.notify('approval', sessionId)
|
|
369
|
+
// The card is not a second answerer: it only says a tool is blocked, with
|
|
370
|
+
// the fixed line and none of the tool's own reason text (§29).
|
|
371
|
+
this.#options.liveActivity?.noteApproval(sessionId)
|
|
372
|
+
}
|
|
228
373
|
const answer = await prompt.answer
|
|
229
374
|
return answer === undefined ? await next() : answer
|
|
230
375
|
}
|
|
@@ -232,11 +377,13 @@ export class BridgeHub {
|
|
|
232
377
|
/**
|
|
233
378
|
* The body of this plugin's `user-questions/request` listener.
|
|
234
379
|
*
|
|
235
|
-
* Claimed only while a
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
239
|
-
*
|
|
380
|
+
* Claimed only while a device that is reachable right now can be shown the
|
|
381
|
+
* card: a paired connection that declared `questions.v1`, or — with no phone on
|
|
382
|
+
* the wire — a roster device that registered for notifications, which the alert
|
|
383
|
+
* reaches instead of a frame (§11.3, §32). The payload has no session field of
|
|
384
|
+
* its own, so an ask that names no agent is delegated either. The wire id is the
|
|
385
|
+
* host's own when the ask is timed, and minted here when it is blocking and the
|
|
386
|
+
* host assigned none — either way the phone answers the id it was shown. A claim
|
|
240
387
|
* nobody received is withdrawn at once instead of holding the agent until the
|
|
241
388
|
* host's deadline. For a timed ask the host's own remaining wait travels with
|
|
242
389
|
* the first frame as `expiresAt`, and every later move of that deadline is
|
|
@@ -248,7 +395,14 @@ export class BridgeHub {
|
|
|
248
395
|
async question(request: UserQuestionRequestLike, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer> {
|
|
249
396
|
const sessionId = request.agent?.id
|
|
250
397
|
if (sessionId === undefined) return await next()
|
|
251
|
-
|
|
398
|
+
// With no phone on the wire the roster decides, and reading it is the file the
|
|
399
|
+
// mount already loaded: awaiting the memoized load keeps the first question of
|
|
400
|
+
// a process from being delegated only because that read had not finished.
|
|
401
|
+
if (this.pairedClients === 0) await this.#options.roster.load()
|
|
402
|
+
const mode = this.#questionMode()
|
|
403
|
+
// Nobody reachable can be shown this question: it belongs to the next answerer,
|
|
404
|
+
// exactly as it did before the offline window existed.
|
|
405
|
+
if (mode === 'nobody') return await next()
|
|
252
406
|
// A blocking ask carries no `wait`: the host has no call id for it, but the
|
|
253
407
|
// phone needs a handle to answer with, so one is minted in this bridge's own
|
|
254
408
|
// namespace. Resolving the promise held here needs no host identity.
|
|
@@ -265,6 +419,9 @@ export class BridgeHub {
|
|
|
265
419
|
// The phone's card has to go when the desktop answered it, or the phone
|
|
266
420
|
// keeps offering a question that no longer exists.
|
|
267
421
|
this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('settled', question))
|
|
422
|
+
// The lock-screen card says the same thing: a card still asking for an
|
|
423
|
+
// answer nobody owes any more is the one state it must never show.
|
|
424
|
+
this.#options.liveActivity?.noteSettled(sessionId)
|
|
268
425
|
},
|
|
269
426
|
onContinued: (question): void => {
|
|
270
427
|
// The foreground wait ended, but the question is still answerable: the
|
|
@@ -279,6 +436,7 @@ export class BridgeHub {
|
|
|
279
436
|
},
|
|
280
437
|
})
|
|
281
438
|
if (claim === undefined) return await next()
|
|
439
|
+
if (mode === 'offline') return await this.#holdOfflineClaim(sessionId, callId, claim)
|
|
282
440
|
// The host's own first wait frame is folded into this same frame: a phone is
|
|
283
441
|
// handed the question and how long it has together, rather than a card that a
|
|
284
442
|
// second update then races. A claim with no frame publishes no deadline,
|
|
@@ -295,16 +453,333 @@ export class BridgeHub {
|
|
|
295
453
|
// *can* receive it but was reconnecting is a different case — it is handed the
|
|
296
454
|
// live claims by `onDeclare` when it comes back.
|
|
297
455
|
if (delivered === 0) this.#options.questions.withdraw([callId])
|
|
456
|
+
// Same rule as the approval above: a question this bridge could not hand to
|
|
457
|
+
// a connected phone is withdrawn at once, so a notification would announce
|
|
458
|
+
// something already gone.
|
|
459
|
+
else {
|
|
460
|
+
this.#options.push?.notify('question', sessionId)
|
|
461
|
+
// Only the first question's header and at most two option labels reach that
|
|
462
|
+
// session's card: they are the choices the App can offer (§29.7: the card has
|
|
463
|
+
// no controls of its own). The questions themselves stay on the wire, exactly
|
|
464
|
+
// as the alert channel keeps them out of its body.
|
|
465
|
+
const first = request.questions[0]
|
|
466
|
+
this.#options.liveActivity?.noteQuestion(sessionId, {
|
|
467
|
+
...(first?.header === undefined ? {} : { header: first.header }),
|
|
468
|
+
...(first?.options === undefined ? {} : { optionLabels: first.options.map(option => option.label) }),
|
|
469
|
+
})
|
|
470
|
+
}
|
|
298
471
|
return await claim.answer
|
|
299
472
|
}
|
|
300
473
|
|
|
474
|
+
/**
|
|
475
|
+
* Present one page to the clients that declared `ui.v1` and wait for the user's
|
|
476
|
+
* first action (§35).
|
|
477
|
+
*
|
|
478
|
+
* The body of the `ui.present` tool call. Claimed only while a paired
|
|
479
|
+
* connection that declared the channel is on the wire: with none, a page would
|
|
480
|
+
* reach nobody, so the call answers `unavailable` at once instead of holding the
|
|
481
|
+
* agent on a wait no screen can end (§35.6 — the same judgement as §11.3's claim
|
|
482
|
+
* exclusivity). A frame no connection took is not held either, for the same
|
|
483
|
+
* reason.
|
|
484
|
+
*
|
|
485
|
+
* The card is announced `open` here and announced `settled` from the claim's own
|
|
486
|
+
* notice, so both frames come out of one payload builder and the page a phone was
|
|
487
|
+
* originally handed cannot drift from the one it reads back out of `ui.list`.
|
|
488
|
+
* @param card - the page, under the host's own `ToolCallId`.
|
|
489
|
+
* @param signal - the tool call's cancellation lifetime.
|
|
490
|
+
* @returns the user's action, or the refusal that ended the wait.
|
|
491
|
+
*/
|
|
492
|
+
async present(card: UiCardView, signal?: AbortSignal): Promise<UiPresentReply> {
|
|
493
|
+
if (signal?.aborted === true) return { ok: false, delivered: 0, reason: 'cancelled' }
|
|
494
|
+
if (!this.#uiReachable()) return { ok: false, delivered: 0, reason: 'unavailable' }
|
|
495
|
+
const claim = this.#options.ui.open({
|
|
496
|
+
...card,
|
|
497
|
+
...(signal === undefined ? {} : { signal }),
|
|
498
|
+
onSettled: (settled): void => {
|
|
499
|
+
// The one notice every ending path uses: the client's card is over, whichever
|
|
500
|
+
// side ended it — the user answering, the grace window, a cancelled turn.
|
|
501
|
+
this.broadcastTo(CAP_UI, TOPIC_UI_REQUEST, uiPayload('settled', settled))
|
|
502
|
+
},
|
|
503
|
+
})
|
|
504
|
+
if (claim === undefined) return { ok: false, delivered: 0, reason: 'unavailable' }
|
|
505
|
+
const delivered = this.broadcastTo(CAP_UI, TOPIC_UI_REQUEST, uiPayload('open', claim))
|
|
506
|
+
// A page nobody took is not kept: the agent must not wait for a card that no
|
|
507
|
+
// screen is holding, and the claim is withdrawn rather than left open.
|
|
508
|
+
if (delivered === 0) {
|
|
509
|
+
this.#options.ui.withdraw([card.callId], 'unavailable')
|
|
510
|
+
return { ok: false, delivered: 0, reason: 'unavailable' }
|
|
511
|
+
}
|
|
512
|
+
const outcome: UiPresentOutcome = await claim.outcome
|
|
513
|
+
return outcome.ok
|
|
514
|
+
? {
|
|
515
|
+
ok: true,
|
|
516
|
+
delivered,
|
|
517
|
+
type: outcome.type,
|
|
518
|
+
...(outcome.payload === undefined ? {} : { payload: outcome.payload }),
|
|
519
|
+
}
|
|
520
|
+
: { ok: false, delivered, reason: outcome.reason }
|
|
521
|
+
}
|
|
522
|
+
|
|
301
523
|
/** Close every connection and withdraw every question. Idempotent. */
|
|
302
524
|
dispose(): void {
|
|
525
|
+
// Unloading is not a phone going away: nothing can come back for these
|
|
526
|
+
// claims, so every window is dropped and the release happens right here — the
|
|
527
|
+
// offline ones through their own entry, so this route also starts the host's
|
|
528
|
+
// chain at most once.
|
|
529
|
+
this.#releaseOfflineClaims('the bridge unloaded')
|
|
530
|
+
this.#cancelQuestionRelease()
|
|
531
|
+
// 卸载不是「手机离开了」:这些卡再也等不到动作,所以窗口立刻作废,释放就在
|
|
532
|
+
// 这里发生(§35.5「桥卸载立即释放」),不留定时器。
|
|
533
|
+
this.#cancelUiRelease()
|
|
303
534
|
for (const connection of [...this.#connections]) {
|
|
304
535
|
this.#connections.delete(connection)
|
|
305
536
|
connection.dispose()
|
|
306
537
|
}
|
|
307
538
|
this.#options.approvals.abandonAll()
|
|
308
539
|
this.#options.questions.withdrawAll()
|
|
540
|
+
const cards = this.#options.ui.withdrawAll()
|
|
541
|
+
if (cards > 0) this.#options.log(`${cards} presented page(s) released: the bridge unloaded`)
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Arm the one release of the user questions no paired device can answer.
|
|
546
|
+
*
|
|
547
|
+
* A second departure while a window is already running must not extend it, so
|
|
548
|
+
* an armed timer is left alone: every claim it covers is released at the one
|
|
549
|
+
* instant it was scheduled for.
|
|
550
|
+
*/
|
|
551
|
+
#armQuestionRelease(): void {
|
|
552
|
+
if (this.#questionReleaseTimer !== undefined) return
|
|
553
|
+
const timer = setTimeout(() => {
|
|
554
|
+
this.#questionReleaseTimer = undefined
|
|
555
|
+
// Exactly what an immediate release does, approvals included: whatever is
|
|
556
|
+
// still held when nobody is paired goes back to the host's own answerers.
|
|
557
|
+
this.#abandonApprovals()
|
|
558
|
+
this.#releaseQuestions()
|
|
559
|
+
}, QUESTION_CLAIM_GRACE_MS)
|
|
560
|
+
// A held question must never keep the host process alive, exactly like the
|
|
561
|
+
// deadline timer one claim arms.
|
|
562
|
+
timer.unref?.()
|
|
563
|
+
this.#questionReleaseTimer = timer
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** Drop the pending window, if there is one. The claims it would release stay held. */
|
|
567
|
+
#cancelQuestionRelease(): void {
|
|
568
|
+
if (this.#questionReleaseTimer === undefined) return
|
|
569
|
+
clearTimeout(this.#questionReleaseTimer)
|
|
570
|
+
this.#questionReleaseTimer = undefined
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Which path a user question takes right now (§11.3).
|
|
575
|
+
*
|
|
576
|
+
* The one entry, read twice: when a question arrives, and again when a paired
|
|
577
|
+
* connection finishes its hello while an offline claim is still held. Both
|
|
578
|
+
* moments ask the same thing — can a device that is reachable right now receive
|
|
579
|
+
* a question card — and answering it in two places is how two answers drift
|
|
580
|
+
* apart.
|
|
581
|
+
* @returns `online` for the ordinary claim-and-broadcast path, `offline` for a
|
|
582
|
+
* claim held for a phone reached by notification, and `nobody` when the question
|
|
583
|
+
* has to go straight to the next answerer.
|
|
584
|
+
*/
|
|
585
|
+
#questionMode(): QuestionMode {
|
|
586
|
+
for (const connection of this.#connections) {
|
|
587
|
+
if (connection.paired && connection.declares(CAP_QUESTIONS)) return 'online'
|
|
588
|
+
}
|
|
589
|
+
// A paired connection is on the wire and none of them declared the channel: no
|
|
590
|
+
// one can be shown a card, and a claim held for the phone that was never there
|
|
591
|
+
// would make the agent wait out a window for a decision nobody can give.
|
|
592
|
+
if (this.pairedClients > 0) return 'nobody'
|
|
593
|
+
// No key, no sender: an alert that cannot be sent is not a delivery, so the
|
|
594
|
+
// question is not claimed for a phone that would never learn it exists.
|
|
595
|
+
if (this.#options.push?.enabled !== true) return 'nobody'
|
|
596
|
+
return this.#options.roster.pushTargets().length > 0 ? 'offline' : 'nobody'
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Hold one question for a phone that is not on the wire (§32).
|
|
601
|
+
*
|
|
602
|
+
* No socket is paired, so this claim's own first frame would reach nobody: the
|
|
603
|
+
* notification IS its delivery, and it is sent whether or not a broadcast would
|
|
604
|
+
* have landed. Inside the window the question exists only on the phone's side;
|
|
605
|
+
* the phone that comes back is handed the card by the replay in `onDeclare`,
|
|
606
|
+
* and the phone that answers settles it through the ordinary path.
|
|
607
|
+
* @param sessionId - the session that asked.
|
|
608
|
+
* @param callId - the wire id the phone will answer under.
|
|
609
|
+
* @param claim - the claim this bridge just opened.
|
|
610
|
+
* @returns the phone's answer, or whatever the next answerer says.
|
|
611
|
+
*/
|
|
612
|
+
async #holdOfflineClaim(sessionId: string, callId: string, claim: ClaimedQuestion): Promise<QuestionAnswer> {
|
|
613
|
+
this.#armOfflineClaim(callId)
|
|
614
|
+
// The report is the only way this bridge learns that the phone it claimed for
|
|
615
|
+
// is gone for good: a frame would have carried that fact, an alert does not.
|
|
616
|
+
this.#options.push?.notify('question', sessionId, (report) => { this.#onQuestionPushed(callId, report) })
|
|
617
|
+
try {
|
|
618
|
+
return await claim.answer
|
|
619
|
+
} finally {
|
|
620
|
+
// Every path that ends this claim — answered, delegated, expired by the host
|
|
621
|
+
// — drops its window here, so no timer outlives the question it was armed for.
|
|
622
|
+
this.#cancelOfflineClaim(callId)
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Read one alert's delivery report (§32.5).
|
|
628
|
+
*
|
|
629
|
+
* Three APNs answers are final about a registration: 410 with `Unregistered`, or
|
|
630
|
+
* `Unregistered`/`BadDeviceToken` on any status. The device is cleaned off the
|
|
631
|
+
* roster, and the claim is kept only while some other registered device is still
|
|
632
|
+
* there to be told; when the last one is gone the question cannot reach a phone
|
|
633
|
+
* at all, so it goes back to the host's chain now instead of at the end of a
|
|
634
|
+
* window nobody is left to use.
|
|
635
|
+
* @param callId - the offline claim this notification was about.
|
|
636
|
+
* @param report - how the announcement ended.
|
|
637
|
+
*/
|
|
638
|
+
#onQuestionPushed(callId: string, report: PushDeliveryReport): void {
|
|
639
|
+
const dead = report.failures.filter(failure => isDeadPushToken(failure)).map(failure => failure.deviceToken)
|
|
640
|
+
if (dead.length === 0) return
|
|
641
|
+
// The roster still lists these rows — the cleanup is a file write — so they are
|
|
642
|
+
// subtracted here rather than waited out: a claim decision may not block on a disk.
|
|
643
|
+
const survivors = this.#options.roster.pushTargets().filter(({ push }) => !dead.includes(push.deviceToken))
|
|
644
|
+
void this.#forgetDeadTokens(dead)
|
|
645
|
+
if (survivors.length > 0) return
|
|
646
|
+
this.#releaseOfflineClaim(callId, 'APNs refused every device token on the roster')
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** Drop each dead registration from the roster, then let the watchers settle. */
|
|
650
|
+
async #forgetDeadTokens(tokens: readonly string[]): Promise<void> {
|
|
651
|
+
try {
|
|
652
|
+
let dropped = false
|
|
653
|
+
for (const token of tokens) dropped = (await this.#options.roster.removePush(token)) || dropped
|
|
654
|
+
// A row that lost the card tokens of its install may have lost its last
|
|
655
|
+
// watcher with them, and a watcher is a follow stream this bridge keeps open.
|
|
656
|
+
if (dropped) this.#options.onPushRegistered?.()
|
|
657
|
+
} catch (error) {
|
|
658
|
+
this.#options.log(`a dead push registration could not be cleaned up: ${String(error)}`)
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* End every offline claim the wire has just made unreachable (§11.3).
|
|
664
|
+
*
|
|
665
|
+
* A hello that leaves no paired connection able to take a card — the client
|
|
666
|
+
* written before `questions.v1` going online — is the same fact the claim point
|
|
667
|
+
* reads, so it releases the claim at once instead of at the end of its window.
|
|
668
|
+
*/
|
|
669
|
+
#reviewOfflineClaims(): void {
|
|
670
|
+
if (this.#offlineClaims.size === 0) return
|
|
671
|
+
if (this.#questionMode() === 'offline') return
|
|
672
|
+
this.#releaseOfflineClaims('no paired connection on the wire can receive a question')
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Arm the window that holds one offline claim.
|
|
677
|
+
*
|
|
678
|
+
* Deliberately a second timer beside {@link #armQuestionRelease}, never the same
|
|
679
|
+
* one: that window is the reconnect budget of a phone that just left, this one is
|
|
680
|
+
* the whole lifetime of a claim no phone ever had, and one claim can be governed
|
|
681
|
+
* by both in turn. Whichever is due first releases it, and the release is
|
|
682
|
+
* idempotent, so the later one finds no claim.
|
|
683
|
+
* @param callId - the claim to hold.
|
|
684
|
+
*/
|
|
685
|
+
#armOfflineClaim(callId: string): void {
|
|
686
|
+
if (this.#offlineClaims.has(callId)) return
|
|
687
|
+
const ttl = this.#options.offlineClaimTtlMs ?? OFFLINE_QUESTION_CLAIM_TTL_MS
|
|
688
|
+
const timer = setTimeout(() => {
|
|
689
|
+
this.#releaseOfflineClaim(callId, 'the offline claim window ended')
|
|
690
|
+
}, Math.max(0, ttl))
|
|
691
|
+
// A question held for a phone must never keep the host process alive.
|
|
692
|
+
timer.unref?.()
|
|
693
|
+
this.#offlineClaims.set(callId, timer)
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/** Drop one claim's window. The claim itself keeps whatever state it has. */
|
|
697
|
+
#cancelOfflineClaim(callId: string): void {
|
|
698
|
+
const timer = this.#offlineClaims.get(callId)
|
|
699
|
+
if (timer === undefined) return
|
|
700
|
+
clearTimeout(timer)
|
|
701
|
+
this.#offlineClaims.delete(callId)
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/** Drop every offline window: a phone is on the wire for those claims now, or they are about to be released. */
|
|
705
|
+
#cancelOfflineClaims(): void {
|
|
706
|
+
for (const timer of this.#offlineClaims.values()) clearTimeout(timer)
|
|
707
|
+
this.#offlineClaims.clear()
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* Release one offline claim back to the host's own chain.
|
|
712
|
+
*
|
|
713
|
+
* The one entry every route uses — the window ending, a roster whose tokens are
|
|
714
|
+
* all dead, a hello that left nobody able to receive, the bridge unloading — so
|
|
715
|
+
* "the host's chain is started at most once" is a property of this entry rather
|
|
716
|
+
* than of its callers: `withdraw` deletes the claim before it delegates, and the
|
|
717
|
+
* chain a claim starts is memoized, so a second route releases nothing and starts
|
|
718
|
+
* nothing, and no notification is sent for a question that already left.
|
|
719
|
+
* @param callId - the claim to release.
|
|
720
|
+
* @param reason - why, logged once when something really was released.
|
|
721
|
+
*/
|
|
722
|
+
#releaseOfflineClaim(callId: string, reason: string): void {
|
|
723
|
+
this.#cancelOfflineClaim(callId)
|
|
724
|
+
const released = this.#options.questions.withdraw([callId])
|
|
725
|
+
if (released > 0) this.#options.log(`an offline-claimed user question was released: ${reason}`)
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/** Release every offline claim through {@link #releaseOfflineClaim}. */
|
|
729
|
+
#releaseOfflineClaims(reason: string): void {
|
|
730
|
+
for (const callId of [...this.#offlineClaims.keys()]) this.#releaseOfflineClaim(callId, reason)
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** Abandon every approval: no paired device is left to answer one. */
|
|
734
|
+
#abandonApprovals(): void {
|
|
735
|
+
const withdrawn = this.#options.approvals.abandonAll()
|
|
736
|
+
if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`)
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** Release every user question to the next answerer. */
|
|
740
|
+
#releaseQuestions(): void {
|
|
741
|
+
const released = this.#options.questions.withdrawAll()
|
|
742
|
+
if (released > 0) this.#options.log(`${released} user question(s) released: no paired device is connected`)
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* @returns whether a reachable right now connection can be shown a page (§35.6).
|
|
747
|
+
*
|
|
748
|
+
* The one predicate `ui.present` reads before it claims anything, and the reason
|
|
749
|
+
* a call with nobody on the wire answers `unavailable` without holding the agent:
|
|
750
|
+
* announcing a capability is the whole of what makes a client able to receive one.
|
|
751
|
+
*/
|
|
752
|
+
#uiReachable(): boolean {
|
|
753
|
+
for (const connection of this.#connections) {
|
|
754
|
+
if (connection.paired && connection.declares(CAP_UI)) return true
|
|
755
|
+
}
|
|
756
|
+
return false
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Arm the one release of the presented pages no paired device can answer.
|
|
761
|
+
*
|
|
762
|
+
* The same shape as {@link #armQuestionRelease} and the same window: a second
|
|
763
|
+
* departure while a window is already running must not extend it, so an armed
|
|
764
|
+
* timer is left alone. Its expiry ends those tool calls as a refusal, which is
|
|
765
|
+
* what §35.5 calls the host side reading the release as a timeout.
|
|
766
|
+
*/
|
|
767
|
+
#armUiRelease(): void {
|
|
768
|
+
if (this.#uiReleaseTimer !== undefined) return
|
|
769
|
+
const timer = setTimeout(() => {
|
|
770
|
+
this.#uiReleaseTimer = undefined
|
|
771
|
+
const released = this.#options.ui.withdrawAll()
|
|
772
|
+
if (released > 0) this.#options.log(`${released} presented page(s) released: the grace window ended`)
|
|
773
|
+
}, QUESTION_CLAIM_GRACE_MS)
|
|
774
|
+
// A held page must never keep the host process alive.
|
|
775
|
+
timer.unref?.()
|
|
776
|
+
this.#uiReleaseTimer = timer
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/** Drop the pending card window, if there is one. The cards it would release stay held. */
|
|
780
|
+
#cancelUiRelease(): void {
|
|
781
|
+
if (this.#uiReleaseTimer === undefined) return
|
|
782
|
+
clearTimeout(this.#uiReleaseTimer)
|
|
783
|
+
this.#uiReleaseTimer = undefined
|
|
309
784
|
}
|
|
310
785
|
}
|