@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
package/src/core/hub.ts
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge's process-wide connection registry and its claims on
|
|
3
|
+
* `approval/request` and `user-questions/request`.
|
|
4
|
+
*
|
|
5
|
+
* The hub is what makes "phone not answering equals refusal" true: a question
|
|
6
|
+
* is claimed only while at least one paired device is connected, the publish
|
|
7
|
+
* has to actually reach someone, and every other path (timeout, agent
|
|
8
|
+
* cancellation, the last phone leaving) delegates to the next answerer, which
|
|
9
|
+
* the Host normalizes to `'unavailable'`.
|
|
10
|
+
*
|
|
11
|
+
* The claim on `user-questions/request` follows the same two rules, with two
|
|
12
|
+
* differences that belong to the host's own semantics: delegating is not a
|
|
13
|
+
* refusal, because only a phone that declares `questions.v1` is ever shown the
|
|
14
|
+
* question; and a question is named on the wire even when the host named none,
|
|
15
|
+
* because a blocking ask carries no call id and the phone still needs a handle
|
|
16
|
+
* to answer with.
|
|
17
|
+
* @module dsh-remote-bridge/core/hub
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval'
|
|
21
|
+
import type { PendingPromptView } from './approvals.ts'
|
|
22
|
+
import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts'
|
|
23
|
+
import { BridgeConnection } from './connection.ts'
|
|
24
|
+
import { CAP_APPROVALS, CAP_QUESTIONS, TOPIC_APPROVAL_REQUEST, TOPIC_QUESTION_REQUEST } from './protocol.ts'
|
|
25
|
+
import type { ClaimedQuestionView, QuestionAnswer, QuestionRequestPayload, QuestionState, UserQuestionRequestLike } from './questions.ts'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The fields of an approval question this bridge reads. Structural on purpose:
|
|
29
|
+
* the event's own type is not exported from the package root, and only these
|
|
30
|
+
* fields are ever touched.
|
|
31
|
+
*/
|
|
32
|
+
export interface ApprovalRequestLike {
|
|
33
|
+
/** The agent asking; its id IS the session id (the event carries no session field). */
|
|
34
|
+
readonly agent: { readonly id: string }
|
|
35
|
+
readonly toolName: string
|
|
36
|
+
readonly displayReason?: { readonly en: string; readonly [locale: string]: string }
|
|
37
|
+
readonly signal?: AbortSignal
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The summary line a phone shows for one question. */
|
|
41
|
+
export function approvalSummary(request: ApprovalRequestLike): string {
|
|
42
|
+
return request.displayReason?.zh ?? request.displayReason?.en ?? request.toolName
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The `approval.request` payload one claim is published with. */
|
|
46
|
+
export interface ApprovalRequestPayload {
|
|
47
|
+
readonly sessionId: string
|
|
48
|
+
readonly id: string
|
|
49
|
+
readonly summary: string
|
|
50
|
+
readonly toolName: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The `approval.request` payload for one claim.
|
|
55
|
+
*
|
|
56
|
+
* The first broadcast and the replay of a still-open claim go through this one
|
|
57
|
+
* function, so the card a phone was originally shown and the same card handed to
|
|
58
|
+
* it again after a reconnect cannot drift apart.
|
|
59
|
+
* @param prompt - the claim being published.
|
|
60
|
+
*/
|
|
61
|
+
function approvalPayload(prompt: PendingPromptView): ApprovalRequestPayload {
|
|
62
|
+
return { sessionId: prompt.sessionId, id: prompt.id, summary: prompt.summary, toolName: prompt.toolName }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The `question.request` payload for one claim.
|
|
67
|
+
*
|
|
68
|
+
* `expiresAt` appears only once the claim learned the host's own deadline from
|
|
69
|
+
* its wait subscription, and it is the host's deadline unchanged: the bridge
|
|
70
|
+
* invents none, because a bridge-invented deadline would be a timeout of the
|
|
71
|
+
* bridge's own — the exact thing this channel must not have. A blocking ask
|
|
72
|
+
* therefore publishes no such key at all, rather than an empty or null one.
|
|
73
|
+
* @param state - whether the foreground ask still holds the question.
|
|
74
|
+
* @param question - the claim being published.
|
|
75
|
+
*/
|
|
76
|
+
function questionPayload(state: QuestionState, question: ClaimedQuestionView): QuestionRequestPayload {
|
|
77
|
+
return {
|
|
78
|
+
sessionId: question.sessionId,
|
|
79
|
+
callId: question.callId,
|
|
80
|
+
state,
|
|
81
|
+
questions: question.questions,
|
|
82
|
+
...(question.expiresAt === undefined ? {} : { expiresAt: question.expiresAt }),
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The bridge's live connections plus the answerer it composes onto the approval chain. */
|
|
87
|
+
export class BridgeHub {
|
|
88
|
+
readonly #options: BridgeConnectionOptions
|
|
89
|
+
readonly #connections = new Set<BridgeConnection>()
|
|
90
|
+
|
|
91
|
+
constructor(options: BridgeConnectionOptions) {
|
|
92
|
+
this.#options = options
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @returns how many paired devices could answer a question right now. */
|
|
96
|
+
get pairedClients(): number {
|
|
97
|
+
let count = 0
|
|
98
|
+
for (const connection of this.#connections) if (connection.paired) count += 1
|
|
99
|
+
return count
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Register one accepted socket.
|
|
104
|
+
* @param transport - the carrier the connection writes through.
|
|
105
|
+
* @param auth - the device the upgrade proved, when it carried a valid token.
|
|
106
|
+
*/
|
|
107
|
+
attach(transport: BridgeTransport, auth?: ConnectionAuth): BridgeConnection {
|
|
108
|
+
// The replay hook is wired here rather than by the caller: a phone that
|
|
109
|
+
// reconnects mid-question was not there for the broadcast, and every
|
|
110
|
+
// construction path has to hand it the live claims — the approval ones and
|
|
111
|
+
// the user-question ones alike.
|
|
112
|
+
const connection = new BridgeConnection(
|
|
113
|
+
{
|
|
114
|
+
...this.#options,
|
|
115
|
+
onDeclare: (fresh) => {
|
|
116
|
+
this.replayQuestions(fresh)
|
|
117
|
+
this.replayApprovals(fresh)
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
transport,
|
|
121
|
+
auth,
|
|
122
|
+
)
|
|
123
|
+
this.#connections.add(connection)
|
|
124
|
+
connection.startHeartbeat()
|
|
125
|
+
if (auth !== undefined) void this.#options.roster.touch(auth.deviceId).catch(() => undefined)
|
|
126
|
+
this.#options.log(`connection open (${auth === undefined ? 'unpaired' : `device ${auth.deviceId}`})`)
|
|
127
|
+
return connection
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Forget one connection and abort everything it owns. When it was the last
|
|
132
|
+
* paired device, every pending question is withdrawn: nobody left can answer.
|
|
133
|
+
*/
|
|
134
|
+
detach(connection: BridgeConnection): void {
|
|
135
|
+
this.#connections.delete(connection)
|
|
136
|
+
connection.dispose()
|
|
137
|
+
if (this.pairedClients > 0) return
|
|
138
|
+
const withdrawn = this.#options.approvals.abandonAll()
|
|
139
|
+
if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`)
|
|
140
|
+
// A user question is delegated rather than refused: the next answerer in the
|
|
141
|
+
// host's chain decides, and the question's own deadline still holds.
|
|
142
|
+
const released = this.#options.questions.withdrawAll()
|
|
143
|
+
if (released > 0) this.#options.log(`${released} user question(s) released: no paired device is connected`)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Publish one event to every paired device.
|
|
148
|
+
* @returns how many connections actually took the frame.
|
|
149
|
+
*/
|
|
150
|
+
broadcast(topic: string, payload: unknown): number {
|
|
151
|
+
let delivered = 0
|
|
152
|
+
for (const connection of this.#connections) {
|
|
153
|
+
if (!connection.paired) continue
|
|
154
|
+
if (connection.emit(topic, payload)) delivered += 1
|
|
155
|
+
}
|
|
156
|
+
return delivered
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Hand one freshly declared connection the questions it can now answer.
|
|
161
|
+
*
|
|
162
|
+
* Without this, a question raised while the phone was reconnecting stays on the
|
|
163
|
+
* host with no card anywhere on the phone: the original broadcast was addressed
|
|
164
|
+
* to clients that had already announced the channel.
|
|
165
|
+
*/
|
|
166
|
+
replayQuestions(connection: BridgeConnection): void {
|
|
167
|
+
if (!connection.paired || !connection.declares(CAP_QUESTIONS)) return
|
|
168
|
+
for (const claim of this.#options.questions.openClaims()) {
|
|
169
|
+
connection.emit(TOPIC_QUESTION_REQUEST, questionPayload('open', claim))
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Hand one freshly declared connection the approvals it can now answer.
|
|
175
|
+
*
|
|
176
|
+
* The same shape as {@link replayQuestions} and for the same reason: the first
|
|
177
|
+
* `approval.request` of a question was broadcast to the phones that were
|
|
178
|
+
* connected at that instant, so a phone that reconnected — or a session screen
|
|
179
|
+
* opened after the fact — holds no card and has no other way to learn the
|
|
180
|
+
* question exists. Only unsettled questions are in the registry, so one that
|
|
181
|
+
* was answered, one the bridge timed out and one withdrawn with the last phone
|
|
182
|
+
* cannot be replayed.
|
|
183
|
+
*
|
|
184
|
+
* The replay emits a frame and nothing else: the claim keeps the deadline it
|
|
185
|
+
* was opened with, so re-handing a question never lengthens how long the agent
|
|
186
|
+
* waits for it.
|
|
187
|
+
* @param connection - the connection that just declared its capabilities.
|
|
188
|
+
*/
|
|
189
|
+
replayApprovals(connection: BridgeConnection): void {
|
|
190
|
+
if (!connection.paired || !connection.declares(CAP_APPROVALS)) return
|
|
191
|
+
for (const prompt of this.#options.approvals.openPrompts()) {
|
|
192
|
+
connection.emit(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt))
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Publish one event to every paired device that announced a capability.
|
|
198
|
+
* @returns how many connections actually took the frame.
|
|
199
|
+
*/
|
|
200
|
+
broadcastTo(capability: string, topic: string, payload: unknown): number {
|
|
201
|
+
let delivered = 0
|
|
202
|
+
for (const connection of this.#connections) {
|
|
203
|
+
if (!connection.paired || !connection.declares(capability)) continue
|
|
204
|
+
if (connection.emit(topic, payload)) delivered += 1
|
|
205
|
+
}
|
|
206
|
+
return delivered
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The body of this plugin's `approval/request` listener.
|
|
211
|
+
* @param request - the pending question.
|
|
212
|
+
* @param next - the rest of the answerer chain.
|
|
213
|
+
* @returns a claimed decision, or whatever the next answerer says.
|
|
214
|
+
*/
|
|
215
|
+
async approve(request: ApprovalRequestLike, next: () => Promise<ApprovalOutcome>): Promise<ApprovalOutcome> {
|
|
216
|
+
if (this.pairedClients === 0) return await next()
|
|
217
|
+
const sessionId = request.agent.id
|
|
218
|
+
const prompt = this.#options.approvals.open({
|
|
219
|
+
sessionId,
|
|
220
|
+
toolName: request.toolName,
|
|
221
|
+
summary: approvalSummary(request),
|
|
222
|
+
...(request.signal === undefined ? {} : { signal: request.signal }),
|
|
223
|
+
})
|
|
224
|
+
const delivered = this.broadcast(TOPIC_APPROVAL_REQUEST, approvalPayload(prompt))
|
|
225
|
+
// A question nobody could receive is withdrawn immediately instead of
|
|
226
|
+
// waiting out the phone's timeout with the agent blocked on it.
|
|
227
|
+
if (delivered === 0) this.#options.approvals.abandon([prompt.id])
|
|
228
|
+
const answer = await prompt.answer
|
|
229
|
+
return answer === undefined ? await next() : answer
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* The body of this plugin's `user-questions/request` listener.
|
|
234
|
+
*
|
|
235
|
+
* Claimed only while a paired device is connected and the ask names an agent:
|
|
236
|
+
* the payload has no session field of its own, and a question nobody can be
|
|
237
|
+
* told about is not one this bridge may hold. The wire id is the host's own
|
|
238
|
+
* when the ask is timed, and minted here when it is blocking and the host
|
|
239
|
+
* assigned none — either way the phone answers the id it was shown. A claim
|
|
240
|
+
* nobody received is withdrawn at once instead of holding the agent until the
|
|
241
|
+
* host's deadline. For a timed ask the host's own remaining wait travels with
|
|
242
|
+
* the first frame as `expiresAt`, and every later move of that deadline is
|
|
243
|
+
* re-published under the same call id.
|
|
244
|
+
* @param request - the pending question batch.
|
|
245
|
+
* @param next - the rest of the answerer chain.
|
|
246
|
+
* @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
|
|
247
|
+
*/
|
|
248
|
+
async question(request: UserQuestionRequestLike, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer> {
|
|
249
|
+
const sessionId = request.agent?.id
|
|
250
|
+
if (sessionId === undefined) return await next()
|
|
251
|
+
if (this.pairedClients === 0) return await next()
|
|
252
|
+
// A blocking ask carries no `wait`: the host has no call id for it, but the
|
|
253
|
+
// phone needs a handle to answer with, so one is minted in this bridge's own
|
|
254
|
+
// namespace. Resolving the promise held here needs no host identity.
|
|
255
|
+
const hosted = request.wait?.callId
|
|
256
|
+
const callId = hosted ?? this.#options.questions.mintCallId()
|
|
257
|
+
const claim = this.#options.questions.open({
|
|
258
|
+
sessionId,
|
|
259
|
+
callId,
|
|
260
|
+
hosted: hosted !== undefined,
|
|
261
|
+
questions: request.questions,
|
|
262
|
+
next,
|
|
263
|
+
...(request.signal === undefined ? {} : { signal: request.signal }),
|
|
264
|
+
onSettled: (question): void => {
|
|
265
|
+
// The phone's card has to go when the desktop answered it, or the phone
|
|
266
|
+
// keeps offering a question that no longer exists.
|
|
267
|
+
this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('settled', question))
|
|
268
|
+
},
|
|
269
|
+
onContinued: (question): void => {
|
|
270
|
+
// The foreground wait ended, but the question is still answerable: the
|
|
271
|
+
// phone is told which state it is in instead of losing the question.
|
|
272
|
+
this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('continued', question))
|
|
273
|
+
},
|
|
274
|
+
onDeadline: (question): void => {
|
|
275
|
+
// The host moved its deadline. Re-publishing the open state under the same
|
|
276
|
+
// call id updates the card the phone already holds instead of opening a
|
|
277
|
+
// second one.
|
|
278
|
+
this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', question))
|
|
279
|
+
},
|
|
280
|
+
})
|
|
281
|
+
if (claim === undefined) return await next()
|
|
282
|
+
// The host's own first wait frame is folded into this same frame: a phone is
|
|
283
|
+
// handed the question and how long it has together, rather than a card that a
|
|
284
|
+
// second update then races. A claim with no frame publishes no deadline,
|
|
285
|
+
// which is exactly the payload from before this channel existed.
|
|
286
|
+
const expiresAt = await claim.deadline
|
|
287
|
+
// The host's own lifetime can end while the first wait frame is still being
|
|
288
|
+
// awaited — its signal aborts, so the claim is expired or already continued.
|
|
289
|
+
// Publishing now would hand the phone a card nobody can retract, so that case
|
|
290
|
+
// goes straight to the claim's own outcome: the host's reason, or its answer.
|
|
291
|
+
if (this.#options.questions.stateOf(callId) !== 'open') return await claim.answer
|
|
292
|
+
const delivered = this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload('open', expiresAt === undefined ? claim : { ...claim, expiresAt }))
|
|
293
|
+
// A client that cannot receive this is not going to receive it later: the claim
|
|
294
|
+
// must not be left holding the host's ask with no card anywhere. A client that
|
|
295
|
+
// *can* receive it but was reconnecting is a different case — it is handed the
|
|
296
|
+
// live claims by `onDeclare` when it comes back.
|
|
297
|
+
if (delivered === 0) this.#options.questions.withdraw([callId])
|
|
298
|
+
return await claim.answer
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Close every connection and withdraw every question. Idempotent. */
|
|
302
|
+
dispose(): void {
|
|
303
|
+
for (const connection of [...this.#connections]) {
|
|
304
|
+
this.#connections.delete(connection)
|
|
305
|
+
connection.dispose()
|
|
306
|
+
}
|
|
307
|
+
this.#options.approvals.abandonAll()
|
|
308
|
+
this.#options.questions.withdrawAll()
|
|
309
|
+
}
|
|
310
|
+
}
|
package/src/core/jobs.ts
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge's read-only window on the host's background jobs: one minimal
|
|
3
|
+
* projection per job, and the change notification a phone's navigation bar
|
|
4
|
+
* needs to keep a count honest.
|
|
5
|
+
*
|
|
6
|
+
* There is exactly one source of truth here and it is the host's own job
|
|
7
|
+
* registry (`ctx.jobs`, the service the `dsh-api-job-controller` Remote
|
|
8
|
+
* namespace is itself a projection of). This module adds no second store, no
|
|
9
|
+
* polling loop and no invented status vocabulary: it reads `list()`, publishes
|
|
10
|
+
* the host's own `kind` and `status` strings verbatim, and hears changes from
|
|
11
|
+
* the registry's own event stream.
|
|
12
|
+
*
|
|
13
|
+
* Two shapes of the host's API matter to what a phone can be shown:
|
|
14
|
+
*
|
|
15
|
+
* - `list(caller)` is owner-fenced. Naming a session returns that session's own
|
|
16
|
+
* jobs plus every job no session owns; naming no session returns only the
|
|
17
|
+
* unowned jobs. Those are TWO truthful scopes, not one global view, and the
|
|
18
|
+
* host has no global view to offer: a job list is never "every job in the
|
|
19
|
+
* process" unless every job in the process happens to be unowned.
|
|
20
|
+
* - The event stream reports `output` appends as well as lifecycle commits. An
|
|
21
|
+
* append says nothing about the SET, so it is dropped here: this channel
|
|
22
|
+
* never publishes per output byte, which is the whole reason the roster is
|
|
23
|
+
* not a projection of `job/follow`.
|
|
24
|
+
*
|
|
25
|
+
* The types below mirror `@deepseek-ai/dsh-jobs` field for field. That package
|
|
26
|
+
* is the host's, not this one's, so the contract is declared structurally
|
|
27
|
+
* instead of imported — the same rule `questions.ts` and `wire.ts` follow, and
|
|
28
|
+
* what keeps a test double down to the two members actually called.
|
|
29
|
+
* @module dsh-remote-bridge/core/jobs
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { failureText } from './gateway-errors.ts'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The slice of the host's `JobView` this bridge reads.
|
|
36
|
+
*
|
|
37
|
+
* Deliberately not the whole view: `output` (the ring's offsets and spill
|
|
38
|
+
* paths), `progress`, `detail` and `outputLimitBytes` are host bookkeeping a
|
|
39
|
+
* phone neither shows nor needs, and a projection that read them would tempt a
|
|
40
|
+
* later change into publishing bytes.
|
|
41
|
+
*/
|
|
42
|
+
export interface JobViewLike {
|
|
43
|
+
readonly id: string
|
|
44
|
+
readonly kind: string
|
|
45
|
+
readonly label: string
|
|
46
|
+
/** Owning session; absent for an unowned job, which every caller can see. */
|
|
47
|
+
readonly owner?: string
|
|
48
|
+
readonly status: string
|
|
49
|
+
/** Epoch milliseconds. */
|
|
50
|
+
readonly startedAt: number
|
|
51
|
+
/** Epoch milliseconds; absent while the job is live. */
|
|
52
|
+
readonly finishedAt?: number
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** One lifecycle event of the host's event stream, as far as this bridge reads it. */
|
|
56
|
+
export interface JobEventLike {
|
|
57
|
+
/** `output` is the one type this bridge drops without reading further. */
|
|
58
|
+
readonly type: string
|
|
59
|
+
/** The job's projection after the commit; absent on an `output` append. */
|
|
60
|
+
readonly job?: JobViewLike
|
|
61
|
+
/** Owning session, carried by `output` events, which carry no projection. */
|
|
62
|
+
readonly owner?: string
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Who a subscription hears about. `all` is what a bridge serving every session asks for. */
|
|
66
|
+
export type JobEventFilterLike = { readonly owners: 'all' | 'scope' } | { readonly owner: string }
|
|
67
|
+
|
|
68
|
+
/** The host registry's event stream. */
|
|
69
|
+
export interface JobEventsFace {
|
|
70
|
+
subscribe(filter: JobEventFilterLike, listener: (event: JobEventLike) => void): () => void
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The slice of `ctx.jobs` this package reads.
|
|
75
|
+
*
|
|
76
|
+
* Optional in the plugin's faces for the reason the metadata faces are: the
|
|
77
|
+
* registry is not in this plugin's `inject` list, and a host that composes no
|
|
78
|
+
* job plugin answers `jobs-unavailable` instead of failing to start.
|
|
79
|
+
*/
|
|
80
|
+
export interface JobRegistryFace {
|
|
81
|
+
list(caller?: string): readonly JobViewLike[]
|
|
82
|
+
readonly events: JobEventsFace
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Which truthful scope one roster answer covers. */
|
|
86
|
+
export type JobScope = 'session' | 'unowned'
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* One job in protocol v1 vocabulary: the minimal, stable view.
|
|
90
|
+
*
|
|
91
|
+
* `kind` and `status` are the host's own strings, verbatim — this protocol
|
|
92
|
+
* publishes no enum of its own, so a producer kind or a lifecycle status added
|
|
93
|
+
* in the host crosses unchanged instead of being flattened into a guess.
|
|
94
|
+
* Every optional key is omitted when the host omitted it, never filled in.
|
|
95
|
+
*/
|
|
96
|
+
export interface JobRow {
|
|
97
|
+
readonly id: string
|
|
98
|
+
readonly kind: string
|
|
99
|
+
readonly status: string
|
|
100
|
+
/** The host's `label`: its own one-line description, the field a phone renders as the job's title. */
|
|
101
|
+
readonly label?: string
|
|
102
|
+
/** The host's `owner`, verbatim, under a name that cannot be read as an object. */
|
|
103
|
+
readonly ownerSessionId?: string
|
|
104
|
+
readonly startedAt?: number
|
|
105
|
+
readonly finishedAt?: number
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The body of one `jobs.list` answer and of one `jobs.changed` event.
|
|
110
|
+
*
|
|
111
|
+
* One box for both, so a client parses its navigation-bar count out of the same
|
|
112
|
+
* shape it refreshes through, and so a client holding two scopes open can tell
|
|
113
|
+
* whose set moved. `sessionId` is present exactly when the scope is `session`.
|
|
114
|
+
*/
|
|
115
|
+
export interface JobsPayload {
|
|
116
|
+
readonly sessionId?: string
|
|
117
|
+
readonly scope: JobScope
|
|
118
|
+
readonly jobs: readonly JobRow[]
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Coalescing window of one roster publish, in milliseconds.
|
|
123
|
+
*
|
|
124
|
+
* The host registry announces every commit synchronously, so a job that
|
|
125
|
+
* registers, reports progress and settles in one turn is three events for one
|
|
126
|
+
* fact a phone renders as one row. This window folds a burst into a single
|
|
127
|
+
* whole-set read, which is why the topic can never turn into a stream of
|
|
128
|
+
* frames. It matches the job controller's own `observeFlushMs` default, so a
|
|
129
|
+
* browser and a phone watching the same set refresh at the same cadence.
|
|
130
|
+
*/
|
|
131
|
+
export const JOBS_FLUSH_MS = 100
|
|
132
|
+
|
|
133
|
+
/** Largest number of job rows one payload carries before it risks the frame budget. */
|
|
134
|
+
export const JOBS_MAX_ROWS = 200
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Project one host job into the protocol's own fields.
|
|
138
|
+
*
|
|
139
|
+
* Explicitly field by field: an unknown key the host adds later must not reach
|
|
140
|
+
* the wire, and a value of the wrong type is dropped rather than coerced — the
|
|
141
|
+
* key is simply absent, which a client already has to handle.
|
|
142
|
+
* @param job - the host's projection.
|
|
143
|
+
* @returns the minimal row, or undefined when the host gave no usable id.
|
|
144
|
+
*/
|
|
145
|
+
export function projectJob(job: JobViewLike): JobRow | undefined {
|
|
146
|
+
if (typeof job.id !== 'string' || job.id === '') return undefined
|
|
147
|
+
return {
|
|
148
|
+
id: job.id,
|
|
149
|
+
kind: typeof job.kind === 'string' ? job.kind : '',
|
|
150
|
+
status: typeof job.status === 'string' ? job.status : '',
|
|
151
|
+
...(typeof job.label === 'string' && job.label !== '' ? { label: job.label } : {}),
|
|
152
|
+
...(typeof job.owner === 'string' && job.owner !== '' ? { ownerSessionId: job.owner } : {}),
|
|
153
|
+
...(Number.isFinite(job.startedAt) ? { startedAt: job.startedAt } : {}),
|
|
154
|
+
...(Number.isFinite(job.finishedAt) ? { finishedAt: job.finishedAt } : {}),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Project a whole host roster.
|
|
160
|
+
* @param jobs - the host's projections.
|
|
161
|
+
* @returns the rows, in the host's own order, bounded by {@link JOBS_MAX_ROWS}.
|
|
162
|
+
*/
|
|
163
|
+
export function projectJobs(jobs: readonly JobViewLike[]): readonly JobRow[] {
|
|
164
|
+
const rows: JobRow[] = []
|
|
165
|
+
for (const job of jobs) {
|
|
166
|
+
const row = projectJob(job)
|
|
167
|
+
if (row !== undefined) rows.push(row)
|
|
168
|
+
if (rows.length >= JOBS_MAX_ROWS) break
|
|
169
|
+
}
|
|
170
|
+
return rows
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The key one scope is subscribed and deduplicated under. */
|
|
174
|
+
export function scopeKey(sessionId?: string): string {
|
|
175
|
+
return sessionId === undefined ? 'unowned' : `session:${sessionId}`
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Whether one job belongs in one scope's visible set.
|
|
180
|
+
*
|
|
181
|
+
* This is the host's own fence, restated for routing events: a session sees its
|
|
182
|
+
* own jobs plus every unowned one, and the unowned scope sees exactly the jobs
|
|
183
|
+
* no session owns.
|
|
184
|
+
* @param owner - the job's owning session, when it has one.
|
|
185
|
+
* @param sessionId - the scope's session; omitted for the unowned scope.
|
|
186
|
+
*/
|
|
187
|
+
export function inScope(owner: string | undefined, sessionId?: string): boolean {
|
|
188
|
+
if (sessionId === undefined) return owner === undefined
|
|
189
|
+
return owner === undefined || owner === sessionId
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** One watched scope and everything published for it. */
|
|
193
|
+
interface ScopeWatch {
|
|
194
|
+
readonly sessionId: string | undefined
|
|
195
|
+
readonly key: string
|
|
196
|
+
/** One listener per connection that asked for this scope. */
|
|
197
|
+
readonly listeners: Set<(payload: JobsPayload) => void>
|
|
198
|
+
/** Set while a burst is waiting for its coalescing window to elapse. */
|
|
199
|
+
timer: NodeJS.Timeout | undefined
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Everything one mount's roster was built with. */
|
|
203
|
+
export interface JobRosterOptions {
|
|
204
|
+
/** Resolves the host registry now; called per read, never captured once, so a registry that mounts later is still picked up. */
|
|
205
|
+
readonly faces: () => { readonly jobs?: JobRegistryFace | undefined }
|
|
206
|
+
readonly log: (message: string) => void
|
|
207
|
+
/** Coalescing window; the default is {@link JOBS_FLUSH_MS}. */
|
|
208
|
+
readonly flushMs?: number
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The bridge's background-job reads and change notifications.
|
|
213
|
+
*
|
|
214
|
+
* One instance is built per host mount and shared by every connection, because
|
|
215
|
+
* a job is a fact about the host, not about the device that asked. Scopes are
|
|
216
|
+
* reference-counted by their listeners: a scope nobody watches holds no timer,
|
|
217
|
+
* and the registry subscription itself exists only while at least one scope
|
|
218
|
+
* does. That is what makes "a connection that never asked receives nothing"
|
|
219
|
+
* structural rather than a filter someone has to remember to apply.
|
|
220
|
+
*/
|
|
221
|
+
export class JobRoster {
|
|
222
|
+
readonly #options: JobRosterOptions
|
|
223
|
+
readonly #flushMs: number
|
|
224
|
+
readonly #watches = new Map<string, ScopeWatch>()
|
|
225
|
+
#unsubscribe: (() => void) | undefined
|
|
226
|
+
#disposed = false
|
|
227
|
+
|
|
228
|
+
constructor(options: JobRosterOptions) {
|
|
229
|
+
this.#options = options
|
|
230
|
+
this.#flushMs = options.flushMs ?? JOBS_FLUSH_MS
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** @returns whether this host composes a job registry at all. */
|
|
234
|
+
get available(): boolean {
|
|
235
|
+
return this.#face() !== undefined
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Read one scope's visible set.
|
|
240
|
+
*
|
|
241
|
+
* Synchronous, because the host registry projects in memory: no stream is
|
|
242
|
+
* opened and no socket is waited on, which is what makes this cheap enough to
|
|
243
|
+
* answer on request and again after every coalesced burst.
|
|
244
|
+
* @param sessionId - the scope's session; omitted for the unowned scope.
|
|
245
|
+
* @returns the payload, or undefined when this host has no job registry.
|
|
246
|
+
*/
|
|
247
|
+
read(sessionId?: string): JobsPayload | undefined {
|
|
248
|
+
const face = this.#face()
|
|
249
|
+
if (face === undefined) return undefined
|
|
250
|
+
try {
|
|
251
|
+
const jobs = face.list(sessionId)
|
|
252
|
+
return {
|
|
253
|
+
...(sessionId === undefined ? {} : { sessionId }),
|
|
254
|
+
scope: sessionId === undefined ? 'unowned' : 'session',
|
|
255
|
+
jobs: projectJobs(Array.isArray(jobs) ? jobs : []),
|
|
256
|
+
}
|
|
257
|
+
} catch (error) {
|
|
258
|
+
// The registry is in-process and synchronous, so a throw is a defect in it
|
|
259
|
+
// rather than a transient outage. It still must not fail the method for
|
|
260
|
+
// every other scope: an unreadable set is answered as an empty one below,
|
|
261
|
+
// and the read is retried on the next call.
|
|
262
|
+
this.#options.log(`the background job roster could not be read: ${failureText(error)}`)
|
|
263
|
+
return undefined
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Watch one scope, and publish each coalesced change to every watcher of it.
|
|
269
|
+
*
|
|
270
|
+
* Watching is what a `jobs.list` call earns: a scope nobody listed is never
|
|
271
|
+
* read again, so a phone that declared the capability and asked for nothing
|
|
272
|
+
* receives no `jobs.changed` — the requirement that keeps N open sessions
|
|
273
|
+
* from becoming N sets streaming at a phone that asked for none.
|
|
274
|
+
* @param sessionId - the scope's session; omitted for the unowned scope.
|
|
275
|
+
* @param listener - receives one whole-set payload per coalesced change.
|
|
276
|
+
* @returns the disposer, or undefined when this host has no job registry.
|
|
277
|
+
*/
|
|
278
|
+
watch(sessionId: string | undefined, listener: (payload: JobsPayload) => void): (() => void) | undefined {
|
|
279
|
+
if (this.#disposed || this.#face() === undefined) return undefined
|
|
280
|
+
const key = scopeKey(sessionId)
|
|
281
|
+
let watch = this.#watches.get(key)
|
|
282
|
+
if (watch === undefined) {
|
|
283
|
+
watch = { sessionId, key, listeners: new Set(), timer: undefined }
|
|
284
|
+
this.#watches.set(key, watch)
|
|
285
|
+
}
|
|
286
|
+
watch.listeners.add(listener)
|
|
287
|
+
this.#subscribe()
|
|
288
|
+
return () => { this.#unwatch(watch, listener) }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Stop every watch and clear every timer. Idempotent. */
|
|
292
|
+
dispose(): void {
|
|
293
|
+
if (this.#disposed) return
|
|
294
|
+
this.#disposed = true
|
|
295
|
+
for (const watch of this.#watches.values()) {
|
|
296
|
+
if (watch.timer !== undefined) clearTimeout(watch.timer)
|
|
297
|
+
watch.timer = undefined
|
|
298
|
+
}
|
|
299
|
+
this.#watches.clear()
|
|
300
|
+
this.#unsubscribe?.()
|
|
301
|
+
this.#unsubscribe = undefined
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Resolve the host registry now, or undefined when this host mounts none. */
|
|
305
|
+
#face(): JobRegistryFace | undefined {
|
|
306
|
+
if (this.#disposed) return undefined
|
|
307
|
+
try {
|
|
308
|
+
return this.#options.faces().jobs
|
|
309
|
+
} catch (error) {
|
|
310
|
+
this.#options.log(`the background job registry could not be resolved: ${failureText(error)}`)
|
|
311
|
+
return undefined
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Subscribe to the registry's event stream once, while any scope is watched. */
|
|
316
|
+
#subscribe(): void {
|
|
317
|
+
if (this.#unsubscribe !== undefined) return
|
|
318
|
+
const face = this.#face()
|
|
319
|
+
if (face === undefined) return
|
|
320
|
+
try {
|
|
321
|
+
// `all` on purpose: the bridge serves every session of this host, and a
|
|
322
|
+
// scope filter here would silently hide another preset's jobs from a
|
|
323
|
+
// phone that is allowed to read them through `list()`.
|
|
324
|
+
this.#unsubscribe = face.events.subscribe({ owners: 'all' }, (event) => { this.#onEvent(event) })
|
|
325
|
+
} catch (error) {
|
|
326
|
+
this.#options.log(`the background job event stream could not be subscribed: ${failureText(error)}`)
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Route one registry event to the scopes it can change. */
|
|
331
|
+
#onEvent(event: JobEventLike): void {
|
|
332
|
+
// An output append moves no row. Dropping it here is the reason this channel
|
|
333
|
+
// can never degrade into one frame per byte of job output.
|
|
334
|
+
if (event.type === 'output') return
|
|
335
|
+
const owner = event.job?.owner ?? event.owner
|
|
336
|
+
for (const watch of this.#watches.values()) {
|
|
337
|
+
if (inScope(owner, watch.sessionId)) this.#schedule(watch)
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Arm one scope's coalescing window; a burst inside it publishes once. */
|
|
342
|
+
#schedule(watch: ScopeWatch): void {
|
|
343
|
+
if (watch.timer !== undefined) return
|
|
344
|
+
const timer = setTimeout(() => {
|
|
345
|
+
watch.timer = undefined
|
|
346
|
+
this.#publish(watch)
|
|
347
|
+
}, this.#flushMs)
|
|
348
|
+
timer.unref?.()
|
|
349
|
+
watch.timer = timer
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Read one scope again and hand its whole set to every watcher. */
|
|
353
|
+
#publish(watch: ScopeWatch): void {
|
|
354
|
+
if (this.#disposed || this.#watches.get(watch.key) !== watch) return
|
|
355
|
+
const payload = this.read(watch.sessionId)
|
|
356
|
+
if (payload === undefined) return
|
|
357
|
+
for (const listener of watch.listeners) listener(payload)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Drop one listener, and its scope with it when it was the last. */
|
|
361
|
+
#unwatch(watch: ScopeWatch, listener: (payload: JobsPayload) => void): void {
|
|
362
|
+
if (this.#watches.get(watch.key) !== watch) return
|
|
363
|
+
watch.listeners.delete(listener)
|
|
364
|
+
if (watch.listeners.size > 0) return
|
|
365
|
+
if (watch.timer !== undefined) clearTimeout(watch.timer)
|
|
366
|
+
watch.timer = undefined
|
|
367
|
+
this.#watches.delete(watch.key)
|
|
368
|
+
if (this.#watches.size > 0) return
|
|
369
|
+
this.#unsubscribe?.()
|
|
370
|
+
this.#unsubscribe = undefined
|
|
371
|
+
}
|
|
372
|
+
}
|