@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.8
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/LICENSE +202 -0
- package/README.i18n.yaml +6 -0
- package/README.md +277 -2
- package/README.zh.md +276 -0
- package/cordis.patch.yml +17 -0
- package/icon.svg +3 -0
- package/lib/client.js +1830 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +5789 -0
- package/lib/types/client/PairEntry.d.ts +16 -0
- package/lib/types/client/PairPanel.d.ts +55 -0
- package/lib/types/client/icons.d.ts +18 -0
- package/lib/types/client/index.d.ts +35 -0
- package/lib/types/client/locales.d.ts +42 -0
- package/lib/types/client/pair-token.d.ts +73 -0
- package/lib/types/client/semantic.d.ts +28 -0
- package/lib/types/core/approvals.d.ts +99 -0
- package/lib/types/core/connection.d.ts +170 -0
- package/lib/types/core/crypto.d.ts +48 -0
- package/lib/types/core/delta.d.ts +101 -0
- package/lib/types/core/devices.d.ts +72 -0
- package/lib/types/core/dsh-frames.d.ts +332 -0
- package/lib/types/core/envelope.d.ts +132 -0
- package/lib/types/core/extension.d.ts +144 -0
- package/lib/types/core/gateway-errors.d.ts +49 -0
- package/lib/types/core/hub.d.ts +127 -0
- package/lib/types/core/jobs.d.ts +204 -0
- package/lib/types/core/loopback.d.ts +35 -0
- package/lib/types/core/owner-peer.d.ts +49 -0
- package/lib/types/core/pairing.d.ts +61 -0
- package/lib/types/core/protocol.d.ts +319 -0
- package/lib/types/core/questions.d.ts +294 -0
- package/lib/types/core/session-meta.d.ts +105 -0
- package/lib/types/core/session-permissions.d.ts +134 -0
- package/lib/types/core/wire.d.ts +115 -0
- package/lib/types/core/ws-frames.d.ts +72 -0
- package/lib/types/host/dsh-home.d.ts +16 -0
- package/lib/types/host/pair-origin.d.ts +44 -0
- package/lib/types/host/routes.d.ts +27 -0
- package/lib/types/host/websocket.d.ts +111 -0
- package/lib/types/index.d.ts +55 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +93 -3
- package/src/client/PairEntry.tsx +151 -0
- package/src/client/PairPanel.tsx +183 -0
- package/src/client/icons.tsx +72 -0
- package/src/client/index.ts +81 -0
- package/src/client/locales.ts +72 -0
- package/src/client/pair-token.ts +104 -0
- package/src/client/panel.module.css +344 -0
- package/src/client/semantic.ts +37 -0
- package/src/core/approvals.ts +173 -0
- package/src/core/connection.ts +1906 -0
- package/src/core/crypto.ts +113 -0
- package/src/core/delta.ts +204 -0
- package/src/core/devices.ts +209 -0
- package/src/core/dsh-frames.ts +843 -0
- package/src/core/envelope.ts +219 -0
- package/src/core/extension.ts +197 -0
- package/src/core/gateway-errors.ts +92 -0
- package/src/core/hub.ts +310 -0
- package/src/core/jobs.ts +372 -0
- package/src/core/loopback.ts +60 -0
- package/src/core/owner-peer.ts +70 -0
- package/src/core/pairing.ts +113 -0
- package/src/core/protocol.ts +381 -0
- package/src/core/questions.ts +630 -0
- package/src/core/session-meta.ts +176 -0
- package/src/core/session-permissions.ts +266 -0
- package/src/core/wire.ts +159 -0
- package/src/core/ws-frames.ts +139 -0
- package/src/css-modules.d.ts +6 -0
- package/src/host/dsh-home.ts +42 -0
- package/src/host/pair-origin.ts +77 -0
- package/src/host/routes.ts +85 -0
- package/src/host/websocket.ts +359 -0
- package/src/index.ts +257 -0
- package/src/mount-once.ts +142 -0
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge's claims on `user-questions/request`: which questions a phone may
|
|
3
|
+
* answer, and the one path an answer travels back into the host.
|
|
4
|
+
*
|
|
5
|
+
* The host asks in two shapes, and they are two shapes of the SAME channel:
|
|
6
|
+
*
|
|
7
|
+
* - a timed ask (`askTimed`, the tool schema that declares a `timeout`) rides
|
|
8
|
+
* the waterfall with a `wait.callId`. While it is open the bridge HOLDS the
|
|
9
|
+
* host's promise, so the answer is that promise's resolution — exactly what an
|
|
10
|
+
* in-process answerer does, and the only way an open question can be answered
|
|
11
|
+
* at all (`ctx.userQuestions.answer` refuses an open question by returning
|
|
12
|
+
* false). Once the host's own deadline released the model, the ask is gone and
|
|
13
|
+
* the question can only be answered through the host's Remote `answer`, which
|
|
14
|
+
* steers the reply into the agent as a queued user message.
|
|
15
|
+
* - a blocking ask (the schema without `timeout`, which is the `ask_user_question`
|
|
16
|
+
* a phone actually shows) carries NO `wait` at all, and the host assigns no
|
|
17
|
+
* call id. It is still claimed, and the bridge mints its own opaque id for the
|
|
18
|
+
* wire — resolving the promise it holds needs no host identity at all. Such a
|
|
19
|
+
* question is only ever `open`: the host has no deadline for it, so it never
|
|
20
|
+
* becomes `continued` and never takes the Remote `answer` path.
|
|
21
|
+
*
|
|
22
|
+
* Every claim is one record keyed by the id published on the wire, so an answer
|
|
23
|
+
* that arrives late still lands, and an answer for an id this bridge never
|
|
24
|
+
* claimed is refused instead of being forwarded to the host blindly.
|
|
25
|
+
*
|
|
26
|
+
* The bridge invents no deadline, for either shape: a timed ask's deadline is
|
|
27
|
+
* the host's own and is only propagated here, and a blocking ask simply has
|
|
28
|
+
* none — a phone that never answers leaves it open for as long as the asker
|
|
29
|
+
* waits. It also never fabricates a refusal: a question nobody can answer is
|
|
30
|
+
* delegated to `next()`, never answered with a decision the operator did not
|
|
31
|
+
* make.
|
|
32
|
+
*
|
|
33
|
+
* A timed ask's deadline is read back from the host itself
|
|
34
|
+
* (`userQuestions/attachWait`) and published as `expiresAt`, so the phone can
|
|
35
|
+
* count down the wait the host is actually serving. Holding that subscription
|
|
36
|
+
* parks the host's own deadline timer, so this module also has to let go at the
|
|
37
|
+
* instant the deadline it learned has passed: only then does the host raise
|
|
38
|
+
* `ASK_TIMED_OUT` and hand the claim its `continued` state.
|
|
39
|
+
*
|
|
40
|
+
* The types below mirror `@deepseek-ai/dsh-user-questions` field for field. The
|
|
41
|
+
* package is not a dependency of this one (it is the host's, not the bridge's),
|
|
42
|
+
* so the contract is declared locally instead of imported.
|
|
43
|
+
* @module dsh-remote-bridge/core/questions
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
import { randomBase64Url } from './crypto.ts'
|
|
47
|
+
import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
|
|
48
|
+
import { CODE_INTERNAL, CODE_QUESTION_UNKNOWN } from './protocol.ts'
|
|
49
|
+
import { wireArgs, type BridgeGateway, type GatewayPeer } from './wire.ts'
|
|
50
|
+
|
|
51
|
+
/** One selectable answer offered by the asker. */
|
|
52
|
+
export interface QuestionOption {
|
|
53
|
+
readonly label: string
|
|
54
|
+
readonly description?: string
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** One question, in the field names protocol v1 publishes. */
|
|
58
|
+
export interface QuestionItem {
|
|
59
|
+
readonly id: string
|
|
60
|
+
readonly question: string
|
|
61
|
+
readonly header?: string
|
|
62
|
+
readonly detail?: string
|
|
63
|
+
readonly options?: readonly QuestionOption[]
|
|
64
|
+
readonly multiSelect?: boolean
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One item of the answer batch. */
|
|
68
|
+
export interface QuestionAnswerItem {
|
|
69
|
+
readonly id: string
|
|
70
|
+
readonly selected: readonly string[]
|
|
71
|
+
readonly custom?: string
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The whole answer batch the host's ask is settled with. */
|
|
75
|
+
export interface QuestionAnswer {
|
|
76
|
+
readonly answers: readonly QuestionAnswerItem[]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Whether a question still holds the foreground ask, or only its late reply. */
|
|
80
|
+
/**
|
|
81
|
+
* `open` while the ask is still waiting, `continued` once the host's foreground
|
|
82
|
+
* wait ended but a late answer can still be steered in, and `settled` as the
|
|
83
|
+
* one-way notice that the phone's card is over — the host's own UI answered it or
|
|
84
|
+
* the last paired client left. `settled` is published, never held.
|
|
85
|
+
*/
|
|
86
|
+
export type QuestionState = 'open' | 'continued' | 'settled'
|
|
87
|
+
|
|
88
|
+
/** `question.request`'s payload, as frozen by the contract. */
|
|
89
|
+
export interface QuestionRequestPayload {
|
|
90
|
+
readonly sessionId: string
|
|
91
|
+
readonly callId: string
|
|
92
|
+
readonly state: QuestionState
|
|
93
|
+
readonly questions: readonly QuestionItem[]
|
|
94
|
+
/** Epoch milliseconds; absent when the host published no readable deadline. */
|
|
95
|
+
readonly expiresAt?: number
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The fields of a host question request this bridge reads.
|
|
100
|
+
*
|
|
101
|
+
* Structural on purpose, for the reason the approval listener is: the event's
|
|
102
|
+
* own type is not reachable from here, and only these fields are ever touched.
|
|
103
|
+
* `wait` is the host's own field for the timed schema — it is what carries the
|
|
104
|
+
* call id, and it is absent for a legacy blocking ask, which this bridge
|
|
105
|
+
* therefore delegates rather than claims.
|
|
106
|
+
*/
|
|
107
|
+
export interface UserQuestionRequestLike {
|
|
108
|
+
readonly questions: readonly QuestionItem[]
|
|
109
|
+
/** The agent asking; its id IS the session id (the event carries no session field). */
|
|
110
|
+
readonly agent?: { readonly id: string }
|
|
111
|
+
readonly signal?: AbortSignal
|
|
112
|
+
readonly wait?: { readonly callId?: string; readonly timed?: boolean }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The identity and content of one claim, as the hub publishes it. */
|
|
116
|
+
export interface ClaimedQuestionView {
|
|
117
|
+
readonly sessionId: string
|
|
118
|
+
readonly callId: string
|
|
119
|
+
readonly questions: readonly QuestionItem[]
|
|
120
|
+
/**
|
|
121
|
+
* Epoch milliseconds at which the host's own deadline falls — the absolute
|
|
122
|
+
* form of the remaining wait the host reported through `attachWait`.
|
|
123
|
+
*
|
|
124
|
+
* Absent when the host said nothing: a blocking ask has no deadline at all,
|
|
125
|
+
* and a timed one is only known once a wait frame arrived.
|
|
126
|
+
*/
|
|
127
|
+
readonly expiresAt?: number
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** One claim the hub holds while the host's ask is still open. */
|
|
131
|
+
export interface ClaimedQuestion extends ClaimedQuestionView {
|
|
132
|
+
/** The host's ask: the phone's answer, or whatever the next answerer says. */
|
|
133
|
+
readonly answer: Promise<QuestionAnswer>
|
|
134
|
+
/**
|
|
135
|
+
* Epoch milliseconds at which the host's own deadline falls, from the first
|
|
136
|
+
* wait frame of this claim.
|
|
137
|
+
*
|
|
138
|
+
* Resolves undefined when there is no deadline to publish — a blocking ask, a
|
|
139
|
+
* failed subscription, or a stream that ended before its first frame — and
|
|
140
|
+
* never rejects: a phone must be shown the question whether or not the host
|
|
141
|
+
* would say how long it has.
|
|
142
|
+
*/
|
|
143
|
+
readonly deadline: Promise<number | undefined>
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** What one `question.answer` produced: acknowledgement, or the refusal to send. */
|
|
147
|
+
export type QuestionReply = { readonly ok: true } | { readonly ok: false; readonly code: string; readonly msg: string }
|
|
148
|
+
|
|
149
|
+
/** The code the host raises when its own foreground deadline ends the ask. */
|
|
150
|
+
export const QUESTION_TIMED_OUT_CODE = 'ASK_TIMED_OUT'
|
|
151
|
+
/**
|
|
152
|
+
* Prefix of a call id this bridge minted for a question the host never named.
|
|
153
|
+
*
|
|
154
|
+
* A blocking ask has no host call id, but the phone still needs one opaque
|
|
155
|
+
* handle to answer with. The prefix keeps that handle in a namespace of its own,
|
|
156
|
+
* so a minted id can never be mistaken for a host `ToolCallId` — by this bridge
|
|
157
|
+
* or by anything reading the wire.
|
|
158
|
+
*/
|
|
159
|
+
export const MINTED_CALL_ID_PREFIX = 'bridge:'
|
|
160
|
+
/** Entropy of one minted call id. */
|
|
161
|
+
export const MINTED_CALL_ID_BYTES = 16
|
|
162
|
+
/**
|
|
163
|
+
* How often at most a phone is told that the host's deadline moved, in
|
|
164
|
+
* milliseconds.
|
|
165
|
+
*
|
|
166
|
+
* The host re-reports its remaining wait on every touch of the wait, which can
|
|
167
|
+
* be far more often than a countdown needs; one update per second keeps the
|
|
168
|
+
* wire quiet without the phone ever showing a stale second.
|
|
169
|
+
*/
|
|
170
|
+
export const QUESTION_WAIT_BROADCAST_MIN_INTERVAL_MS = 1000
|
|
171
|
+
|
|
172
|
+
export interface OpenQuestionInput {
|
|
173
|
+
readonly sessionId: string
|
|
174
|
+
/** The id published on the wire: the host's own, or one this bridge minted. */
|
|
175
|
+
readonly callId: string
|
|
176
|
+
/**
|
|
177
|
+
* Whether `callId` is the host's own tool call identity.
|
|
178
|
+
*
|
|
179
|
+
* Only a hosted claim can ever be `continued`: the state is what a host
|
|
180
|
+
* deadline produces, and the late-answer path needs a real call id to address.
|
|
181
|
+
*/
|
|
182
|
+
readonly hosted: boolean
|
|
183
|
+
readonly questions: readonly QuestionItem[]
|
|
184
|
+
/** The rest of the answerer chain, used when the bridge withdraws. */
|
|
185
|
+
readonly next: () => Promise<QuestionAnswer>
|
|
186
|
+
/** The host's own cancellation lifetime for this ask. */
|
|
187
|
+
readonly signal?: AbortSignal
|
|
188
|
+
/** Called once when the host's deadline released the model but the question stayed answerable. */
|
|
189
|
+
readonly onContinued?: (question: ClaimedQuestionView) => void
|
|
190
|
+
/**
|
|
191
|
+
* Called when a later wait frame moved the host's deadline, so a phone that
|
|
192
|
+
* already holds the card can update it in place.
|
|
193
|
+
*
|
|
194
|
+
* The first frame is not reported here: it is what {@link ClaimedQuestion.deadline}
|
|
195
|
+
* hands the hub for the question's own first broadcast, so reporting it would
|
|
196
|
+
* publish the same deadline twice.
|
|
197
|
+
*/
|
|
198
|
+
readonly onDeadline?: (question: ClaimedQuestionView) => void
|
|
199
|
+
/**
|
|
200
|
+
* Called when the claim leaves this bridge without the phone answering it — the
|
|
201
|
+
* host's own UI answered first, or the last paired client went away. The phone
|
|
202
|
+
* still holds a card for it and has to be told, or it keeps offering a question
|
|
203
|
+
* that no longer exists.
|
|
204
|
+
*/
|
|
205
|
+
readonly onSettled?: (question: ClaimedQuestionView) => void
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** One live claim, with every path that settles it. */
|
|
209
|
+
interface Claim {
|
|
210
|
+
readonly sessionId: string
|
|
211
|
+
readonly callId: string
|
|
212
|
+
readonly hosted: boolean
|
|
213
|
+
readonly questions: readonly QuestionItem[]
|
|
214
|
+
state: QuestionState
|
|
215
|
+
readonly settle: (answer: QuestionAnswer) => void
|
|
216
|
+
readonly fail: (reason: unknown) => void
|
|
217
|
+
readonly delegate: () => void
|
|
218
|
+
readonly detach: () => void
|
|
219
|
+
readonly onContinued: ((question: ClaimedQuestionView) => void) | undefined
|
|
220
|
+
/** Tells the phone its card is over; set from the input's `onSettled`. */
|
|
221
|
+
readonly notifySettled: () => void
|
|
222
|
+
/** Epoch milliseconds of the host's deadline, once a wait frame reported one. */
|
|
223
|
+
expiresAt: number | undefined
|
|
224
|
+
/** End the wait subscription and its timer. Idempotent. */
|
|
225
|
+
readonly stopWait: () => void
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export interface QuestionClaimsOptions {
|
|
229
|
+
readonly gateway: BridgeGateway
|
|
230
|
+
/** The in-process owner peer every gateway call speaks for; the bridge never derives it from a client frame. */
|
|
231
|
+
readonly peer: GatewayPeer
|
|
232
|
+
readonly log: (message: string) => void
|
|
233
|
+
/** Id source, injectable so a test can answer the exact id it was given. */
|
|
234
|
+
readonly random?: (byteLength: number) => string
|
|
235
|
+
/**
|
|
236
|
+
* Clock the deadline bookkeeping reads, injectable so a suite can move the
|
|
237
|
+
* remaining wait instead of sleeping through it.
|
|
238
|
+
*/
|
|
239
|
+
readonly now?: () => number
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** @returns whether a failure is the host's own foreground deadline. */
|
|
243
|
+
function isTimedOut(reason: unknown): boolean {
|
|
244
|
+
return (reason as { code?: unknown } | null | undefined)?.code === QUESTION_TIMED_OUT_CODE
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The publishable view of one claim.
|
|
249
|
+
*
|
|
250
|
+
* The deadline key is spread in rather than set to undefined: a blocking ask has
|
|
251
|
+
* no expiry at all, and the phone must see no such field instead of a null one.
|
|
252
|
+
* @param record - the live claim.
|
|
253
|
+
* @returns the claim's fields as the hub publishes them.
|
|
254
|
+
*/
|
|
255
|
+
function viewOf(record: Claim): ClaimedQuestionView {
|
|
256
|
+
return {
|
|
257
|
+
sessionId: record.sessionId,
|
|
258
|
+
callId: record.callId,
|
|
259
|
+
questions: record.questions,
|
|
260
|
+
...(record.expiresAt === undefined ? {} : { expiresAt: record.expiresAt }),
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Read the remaining wait out of one `attachWait` frame.
|
|
266
|
+
* @param frame - the frame as the gateway delivered it.
|
|
267
|
+
* @returns the remaining milliseconds, or undefined when the frame is not usable.
|
|
268
|
+
*/
|
|
269
|
+
function remainingOf(frame: unknown): number | undefined {
|
|
270
|
+
const remaining = (frame as { remainingMs?: unknown } | null | undefined)?.remainingMs
|
|
271
|
+
if (typeof remaining !== 'number' || !Number.isFinite(remaining) || remaining < 0) return undefined
|
|
272
|
+
return remaining
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Project a host question into the contract's own fields.
|
|
277
|
+
*
|
|
278
|
+
* Explicitly field by field: the host's items carry presentation intents this
|
|
279
|
+
* protocol does not publish, and a payload that grew a key the contract does
|
|
280
|
+
* not declare would be a wire change nobody agreed to.
|
|
281
|
+
* @param items - the host's question batch.
|
|
282
|
+
* @returns the same questions in protocol vocabulary.
|
|
283
|
+
*/
|
|
284
|
+
export function projectQuestions(items: readonly QuestionItem[]): readonly QuestionItem[] {
|
|
285
|
+
return items.map(item => ({
|
|
286
|
+
id: item.id,
|
|
287
|
+
question: item.question,
|
|
288
|
+
...(item.header === undefined ? {} : { header: item.header }),
|
|
289
|
+
...(item.detail === undefined ? {} : { detail: item.detail }),
|
|
290
|
+
...(item.options === undefined
|
|
291
|
+
? {}
|
|
292
|
+
: {
|
|
293
|
+
options: item.options.map(option => ({
|
|
294
|
+
label: option.label,
|
|
295
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
296
|
+
})),
|
|
297
|
+
}),
|
|
298
|
+
...(item.multiSelect === undefined ? {} : { multiSelect: item.multiSelect }),
|
|
299
|
+
}))
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Pending questions of one bridge process.
|
|
304
|
+
*
|
|
305
|
+
* One record per id published on the wire — the host's own, or one minted here
|
|
306
|
+
* for a blocking ask — and one settle for every path (answer, the host's
|
|
307
|
+
* deadline, the last phone leaving, bridge unload), so a question can never be
|
|
308
|
+
* settled twice and a withdrawn claim leaves no abort listener behind.
|
|
309
|
+
*/
|
|
310
|
+
export class QuestionClaims {
|
|
311
|
+
readonly #gateway: BridgeGateway
|
|
312
|
+
readonly #peer: GatewayPeer
|
|
313
|
+
readonly #log: (message: string) => void
|
|
314
|
+
readonly #random: (byteLength: number) => string
|
|
315
|
+
readonly #now: () => number
|
|
316
|
+
readonly #claims = new Map<string, Claim>()
|
|
317
|
+
|
|
318
|
+
constructor(options: QuestionClaimsOptions) {
|
|
319
|
+
this.#gateway = options.gateway
|
|
320
|
+
this.#peer = options.peer
|
|
321
|
+
this.#log = options.log
|
|
322
|
+
this.#random = options.random ?? randomBase64Url
|
|
323
|
+
this.#now = options.now ?? Date.now
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** @returns how many questions this bridge currently holds. */
|
|
327
|
+
get size(): number {
|
|
328
|
+
return this.#claims.size
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Mint the opaque wire id of a question the host never named.
|
|
333
|
+
* @returns an id in this bridge's own namespace.
|
|
334
|
+
*/
|
|
335
|
+
mintCallId(): string {
|
|
336
|
+
return `${MINTED_CALL_ID_PREFIX}${this.#random(MINTED_CALL_ID_BYTES)}`
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** @returns the state of one claimed call, or undefined when it is not claimed. */
|
|
340
|
+
stateOf(callId: string): QuestionState | undefined {
|
|
341
|
+
return this.#claims.get(callId)?.state
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Claim one question.
|
|
346
|
+
* @param input - session identity, wire call id and its provenance, questions, the rest of the chain, and the host's lifetime.
|
|
347
|
+
* @returns the claim the hub publishes, or undefined when this call id is already claimed.
|
|
348
|
+
*/
|
|
349
|
+
open(input: OpenQuestionInput): ClaimedQuestion | undefined {
|
|
350
|
+
if (this.#claims.has(input.callId)) return undefined
|
|
351
|
+
let settle: (answer: QuestionAnswer) => void = () => undefined
|
|
352
|
+
let fail: (reason: unknown) => void = () => undefined
|
|
353
|
+
const answer = new Promise<QuestionAnswer>((resolve, reject) => {
|
|
354
|
+
settle = resolve
|
|
355
|
+
fail = reject
|
|
356
|
+
})
|
|
357
|
+
const signal = input.signal
|
|
358
|
+
const onAbort = (): void => { this.#expire(input.callId, signal?.reason) }
|
|
359
|
+
// The rest of the answerer chain is the host's own UI, and it must keep
|
|
360
|
+
// showing the question: claiming here used to swallow it. Started once, at
|
|
361
|
+
// claim time, so both surfaces display it and the first answer settles it.
|
|
362
|
+
// A rejection is not a verdict — the phone may still answer — so it is
|
|
363
|
+
// remembered for a later withdraw instead of failing the claim now.
|
|
364
|
+
let nextStarted: Promise<QuestionAnswer> | undefined
|
|
365
|
+
const startNext = (): Promise<QuestionAnswer> => {
|
|
366
|
+
if (nextStarted === undefined) {
|
|
367
|
+
try {
|
|
368
|
+
nextStarted = input.next()
|
|
369
|
+
} catch (error) {
|
|
370
|
+
nextStarted = Promise.reject(error)
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return nextStarted
|
|
374
|
+
}
|
|
375
|
+
// The host parks its own deadline timer while a waiter is attached, so this
|
|
376
|
+
// subscription must let go at the instant the deadline it reported has
|
|
377
|
+
// passed: only then does the host raise ASK_TIMED_OUT, which is what turns
|
|
378
|
+
// the claim into today's `continued` one. Every settling path stops it.
|
|
379
|
+
const wait = new AbortController()
|
|
380
|
+
let waitTimer: NodeJS.Timeout | undefined
|
|
381
|
+
let stopped = false
|
|
382
|
+
// The resolver is installed by the executor below; a claim that closes before
|
|
383
|
+
// the first frame needs calling it early, and that early call must be a no-op.
|
|
384
|
+
const deferred: { resolve?: (deadline: number | undefined) => void } = {}
|
|
385
|
+
const deadline = new Promise<number | undefined>((resolve) => { deferred.resolve = resolve })
|
|
386
|
+
const resolveDeadline = (value: number | undefined): void => { deferred.resolve?.(value) }
|
|
387
|
+
const stopWait = (): void => {
|
|
388
|
+
if (stopped) return
|
|
389
|
+
stopped = true
|
|
390
|
+
if (waitTimer !== undefined) {
|
|
391
|
+
clearTimeout(waitTimer)
|
|
392
|
+
waitTimer = undefined
|
|
393
|
+
}
|
|
394
|
+
wait.abort()
|
|
395
|
+
// A claim that closes before the host said anything must not leave the hub
|
|
396
|
+
// awaiting a first frame that will never come.
|
|
397
|
+
resolveDeadline(undefined)
|
|
398
|
+
}
|
|
399
|
+
const record: Claim = {
|
|
400
|
+
sessionId: input.sessionId,
|
|
401
|
+
callId: input.callId,
|
|
402
|
+
hosted: input.hosted,
|
|
403
|
+
questions: projectQuestions(input.questions),
|
|
404
|
+
state: 'open',
|
|
405
|
+
expiresAt: undefined,
|
|
406
|
+
notifySettled: (): void => { input.onSettled?.(viewOf(record)) },
|
|
407
|
+
settle,
|
|
408
|
+
fail,
|
|
409
|
+
delegate: (): void => {
|
|
410
|
+
void startNext().then(settle, fail)
|
|
411
|
+
},
|
|
412
|
+
detach: (): void => { signal?.removeEventListener('abort', onAbort) },
|
|
413
|
+
onContinued: input.onContinued,
|
|
414
|
+
stopWait,
|
|
415
|
+
}
|
|
416
|
+
/** Arm the timer that lets go of the wait when the host's own deadline is due. */
|
|
417
|
+
const armDeadline = (expiresAt: number): void => {
|
|
418
|
+
if (waitTimer !== undefined) clearTimeout(waitTimer)
|
|
419
|
+
waitTimer = setTimeout(() => { stopWait() }, Math.max(0, expiresAt - this.#now()))
|
|
420
|
+
// A question waiting on a phone must never keep the host process alive.
|
|
421
|
+
waitTimer.unref?.()
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Follow the host's own remaining wait and report it when it moves.
|
|
425
|
+
*
|
|
426
|
+
* A failure here is not a verdict on the question: the phone can answer it
|
|
427
|
+
* without ever knowing the deadline, so every error only ends the
|
|
428
|
+
* subscription instead of failing the claim.
|
|
429
|
+
*/
|
|
430
|
+
const trackWait = async (): Promise<void> => {
|
|
431
|
+
if (stopped) return
|
|
432
|
+
let frames = 0
|
|
433
|
+
let lastBroadcast = 0
|
|
434
|
+
try {
|
|
435
|
+
const stream = await this.#gateway.stream({
|
|
436
|
+
namespace: 'userQuestions',
|
|
437
|
+
method: 'attachWait',
|
|
438
|
+
args: wireArgs('userQuestions', 'attachWait', { agentId: input.sessionId, callId: input.callId }),
|
|
439
|
+
peer: this.#peer,
|
|
440
|
+
signal: wait.signal,
|
|
441
|
+
})
|
|
442
|
+
const iterator = stream[Symbol.asyncIterator]()
|
|
443
|
+
try {
|
|
444
|
+
for (;;) {
|
|
445
|
+
const next = await iterator.next()
|
|
446
|
+
if (next.done === true) return
|
|
447
|
+
const remaining = remainingOf(next.value)
|
|
448
|
+
if (remaining === undefined) continue
|
|
449
|
+
const at = this.#now()
|
|
450
|
+
const expiresAt = at + remaining
|
|
451
|
+
record.expiresAt = expiresAt
|
|
452
|
+
armDeadline(expiresAt)
|
|
453
|
+
// The first frame IS the deadline: the hub is already awaiting it for
|
|
454
|
+
// the question's own broadcast, so only later frames move a card.
|
|
455
|
+
if (frames === 0) {
|
|
456
|
+
frames = 1
|
|
457
|
+
lastBroadcast = at
|
|
458
|
+
resolveDeadline(expiresAt)
|
|
459
|
+
continue
|
|
460
|
+
}
|
|
461
|
+
if (at - lastBroadcast < QUESTION_WAIT_BROADCAST_MIN_INTERVAL_MS) continue
|
|
462
|
+
lastBroadcast = at
|
|
463
|
+
input.onDeadline?.(viewOf(record))
|
|
464
|
+
}
|
|
465
|
+
} finally {
|
|
466
|
+
await iterator.return?.()
|
|
467
|
+
}
|
|
468
|
+
} catch (error) {
|
|
469
|
+
// Releasing the wait on purpose — its deadline arrived, the claim settled —
|
|
470
|
+
// aborts the stream, and the gateway reports an aborted Remote stream as a
|
|
471
|
+
// failed read of its own (`gateway/cancelled`). That is the normal path,
|
|
472
|
+
// not a fault, so only an end nobody asked for is logged.
|
|
473
|
+
if (!stopped) this.#log(`userQuestions/attachWait failed: ${failureText(error)}`)
|
|
474
|
+
} finally {
|
|
475
|
+
// No frame, no deadline: the hub publishes the question without one
|
|
476
|
+
// instead of waiting on a wait the host never reported. A no-op once a
|
|
477
|
+
// frame already settled it.
|
|
478
|
+
resolveDeadline(undefined)
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
this.#claims.set(input.callId, record)
|
|
482
|
+
// The rest of the chain is NOT started here. A connected phone takes the
|
|
483
|
+
// question on its own, and the host's own panel would otherwise stay open
|
|
484
|
+
// after the phone answered it — the bridge has no way to close that panel.
|
|
485
|
+
// A phone that is absent, or a claim that is withdrawn, still delegates.
|
|
486
|
+
if (signal?.aborted === true) onAbort()
|
|
487
|
+
else signal?.addEventListener('abort', onAbort, { once: true })
|
|
488
|
+
if (input.hosted) void trackWait()
|
|
489
|
+
// A blocking ask carries no host deadline at all: nothing to follow, nothing to publish.
|
|
490
|
+
else resolveDeadline(undefined)
|
|
491
|
+
return { ...viewOf(record), answer, deadline }
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Answer one claimed question.
|
|
496
|
+
*
|
|
497
|
+
* An open claim is settled by resolving the host's own ask; a continued one
|
|
498
|
+
* only through the host's Remote `answer`, whose result and failures cross
|
|
499
|
+
* unchanged.
|
|
500
|
+
* @param sessionId - the session the client believes owns the question.
|
|
501
|
+
* @param callId - the wire call id the client was shown.
|
|
502
|
+
* @param answer - the complete answer batch.
|
|
503
|
+
*/
|
|
504
|
+
async answer(sessionId: string, callId: string, answer: QuestionAnswer): Promise<QuestionReply> {
|
|
505
|
+
const record = this.#claims.get(callId)
|
|
506
|
+
if (record === undefined || record.sessionId !== sessionId) {
|
|
507
|
+
return { ok: false, code: CODE_QUESTION_UNKNOWN, msg: 'the question is unknown, already answered or not this bridge\'s to answer' }
|
|
508
|
+
}
|
|
509
|
+
if (record.state === 'open') {
|
|
510
|
+
this.#claims.delete(callId)
|
|
511
|
+
record.detach()
|
|
512
|
+
record.stopWait()
|
|
513
|
+
record.settle({ answers: answer.answers })
|
|
514
|
+
return { ok: true }
|
|
515
|
+
}
|
|
516
|
+
// Unreachable today: only a host deadline marks a claim continued, and only a
|
|
517
|
+
// hosted claim can reach one. Kept as the invariant an answer path must hold.
|
|
518
|
+
if (!record.hosted) {
|
|
519
|
+
return { ok: false, code: CODE_QUESTION_UNKNOWN, msg: 'the question is not one the host can take a late answer for' }
|
|
520
|
+
}
|
|
521
|
+
return await this.#forward(sessionId, callId, answer)
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Every claim still waiting on an answer.
|
|
526
|
+
*
|
|
527
|
+
* A phone that connects after the question was raised never saw the original
|
|
528
|
+
* broadcast, so it has to be handed the live claims again — otherwise the
|
|
529
|
+
* question sits on the host with an answerable card nowhere.
|
|
530
|
+
*/
|
|
531
|
+
openClaims(): readonly ClaimedQuestionView[] {
|
|
532
|
+
return [...this.#claims.values()].map(viewOf)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Withdraw the named questions, delegating each to the next answerer.
|
|
537
|
+
* @returns how many were still open and therefore delegated.
|
|
538
|
+
*/
|
|
539
|
+
withdraw(callIds: readonly string[]): number {
|
|
540
|
+
let withdrawn = 0
|
|
541
|
+
for (const callId of callIds) {
|
|
542
|
+
const record = this.#claims.get(callId)
|
|
543
|
+
if (record === undefined) continue
|
|
544
|
+
this.#claims.delete(callId)
|
|
545
|
+
record.detach()
|
|
546
|
+
record.stopWait()
|
|
547
|
+
record.notifySettled()
|
|
548
|
+
if (record.state !== 'open') continue
|
|
549
|
+
record.delegate()
|
|
550
|
+
withdrawn += 1
|
|
551
|
+
}
|
|
552
|
+
return withdrawn
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Withdraw every claim, delegating each open question to the next answerer.
|
|
557
|
+
* Called when the last paired phone goes away and when the bridge unloads: a
|
|
558
|
+
* question nobody can answer must not hold the agent until its own deadline.
|
|
559
|
+
* @returns how many questions were still open.
|
|
560
|
+
*/
|
|
561
|
+
withdrawAll(): number {
|
|
562
|
+
return this.withdraw([...this.#claims.keys()])
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Ask the host to steer one continued answer into its agent.
|
|
567
|
+
*
|
|
568
|
+
* A host that answers `false` no longer holds the question; it is reported,
|
|
569
|
+
* not swallowed, and the claim is kept so a client that answered a beat too
|
|
570
|
+
* early can retry once the host has folded the pending result.
|
|
571
|
+
*/
|
|
572
|
+
async #forward(sessionId: string, callId: string, answer: QuestionAnswer): Promise<QuestionReply> {
|
|
573
|
+
try {
|
|
574
|
+
const accepted = await withServiceUnavailableRetry(() => this.#gateway.invoke({
|
|
575
|
+
namespace: 'userQuestions',
|
|
576
|
+
method: 'answer',
|
|
577
|
+
args: wireArgs('userQuestions', 'answer', { agentId: sessionId, callId, answer: { answers: answer.answers } }),
|
|
578
|
+
peer: this.#peer,
|
|
579
|
+
}))
|
|
580
|
+
if (accepted !== true) {
|
|
581
|
+
return { ok: false, code: CODE_QUESTION_UNKNOWN, msg: 'the host does not hold this question as answerable yet' }
|
|
582
|
+
}
|
|
583
|
+
const record = this.#claims.get(callId)
|
|
584
|
+
this.#claims.delete(callId)
|
|
585
|
+
// The late answer is the end of this ask: nothing is left to count down.
|
|
586
|
+
record?.stopWait()
|
|
587
|
+
return { ok: true }
|
|
588
|
+
} catch (error) {
|
|
589
|
+
this.#log(`userQuestions/answer failed: ${failureText(error)}`)
|
|
590
|
+
return { ok: false, code: errorCodeOf(error, CODE_INTERNAL), msg: failureText(error) }
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Settle one open claim from the host's own cancellation lifetime.
|
|
596
|
+
*
|
|
597
|
+
* The reason is propagated verbatim, so the host's deadline still maps to its
|
|
598
|
+
* pending result. Only a deadline keeps the claim: every other abort means
|
|
599
|
+
* the ask itself is gone.
|
|
600
|
+
*/
|
|
601
|
+
#expire(callId: string, reason: unknown): void {
|
|
602
|
+
const record = this.#claims.get(callId)
|
|
603
|
+
if (record === undefined || record.state !== 'open') return
|
|
604
|
+
record.detach()
|
|
605
|
+
record.stopWait()
|
|
606
|
+
record.fail(reason)
|
|
607
|
+
// Only a host deadline keeps a claim answerable, and only for an id the host
|
|
608
|
+
// itself assigned: a minted one has no host question behind it, so nothing
|
|
609
|
+
// could ever take a late answer.
|
|
610
|
+
if (!record.hosted || !isTimedOut(reason)) {
|
|
611
|
+
this.#claims.delete(callId)
|
|
612
|
+
return
|
|
613
|
+
}
|
|
614
|
+
record.state = 'continued'
|
|
615
|
+
record.onContinued?.(viewOf(record))
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
declare module '@deepseek-ai/cordis' {
|
|
620
|
+
interface Events {
|
|
621
|
+
/**
|
|
622
|
+
* Ask composed answerers for structured user input; the bridge claims it
|
|
623
|
+
* while a paired phone is connected, and delegates every other case. The
|
|
624
|
+
* parameters are the ones this package reads — the host's own declaration
|
|
625
|
+
* is not reachable from here.
|
|
626
|
+
* @mode waterfall
|
|
627
|
+
*/
|
|
628
|
+
'user-questions/request'(this: unknown, request: UserQuestionRequestLike, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer>
|
|
629
|
+
}
|
|
630
|
+
}
|