@linxin666/dsh-remote-bridge 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +75 -18
  3. package/README.zh.md +74 -18
  4. package/lib/client.js +783 -260
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +15849 -2913
  7. package/lib/types/client/PairEntry.d.ts +2 -2
  8. package/lib/types/client/PairPanel.d.ts +10 -2
  9. package/lib/types/client/UiPresentRow.d.ts +13 -0
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/index.d.ts +4 -0
  12. package/lib/types/client/locales.d.ts +24 -15
  13. package/lib/types/client/semantic.d.ts +9 -5
  14. package/lib/types/client/toolview-slot.d.ts +68 -0
  15. package/lib/types/client/ui-card.d.ts +160 -0
  16. package/lib/types/core/commands.d.ts +59 -0
  17. package/lib/types/core/connection.d.ts +106 -0
  18. package/lib/types/core/devices.d.ts +102 -2
  19. package/lib/types/core/extension.d.ts +13 -0
  20. package/lib/types/core/hub.d.ts +129 -15
  21. package/lib/types/core/liveactivity.d.ts +324 -0
  22. package/lib/types/core/protocol.d.ts +328 -5
  23. package/lib/types/core/push.d.ts +186 -0
  24. package/lib/types/core/questions.d.ts +61 -9
  25. package/lib/types/core/session-meta.d.ts +55 -1
  26. package/lib/types/core/squads.d.ts +130 -0
  27. package/lib/types/core/turn-end-quiet.d.ts +135 -0
  28. package/lib/types/core/ui.d.ts +238 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/host/apns.d.ts +151 -0
  32. package/lib/types/host/squads-ledger.d.ts +39 -0
  33. package/lib/types/host/squads.d.ts +77 -0
  34. package/lib/types/host/ui-tools.d.ts +80 -0
  35. package/lib/types/host/usage-stats.d.ts +75 -0
  36. package/lib/types/host/watchers.d.ts +95 -0
  37. package/lib/types/index.d.ts +47 -3
  38. package/package.json +15 -14
  39. package/src/client/PairEntry.tsx +58 -31
  40. package/src/client/PairPanel.tsx +181 -97
  41. package/src/client/UiPresentRow.tsx +149 -0
  42. package/src/client/icons.tsx +17 -60
  43. package/src/client/index.ts +11 -0
  44. package/src/client/locales.ts +36 -24
  45. package/src/client/panel.module.css +239 -186
  46. package/src/client/semantic.ts +10 -6
  47. package/src/client/toolview-slot.ts +84 -0
  48. package/src/client/ui-card.ts +368 -0
  49. package/src/client/ui-present.module.css +87 -0
  50. package/src/core/commands.ts +95 -0
  51. package/src/core/connection.ts +811 -12
  52. package/src/core/devices.ts +337 -5
  53. package/src/core/extension.ts +20 -0
  54. package/src/core/hub.ts +518 -43
  55. package/src/core/liveactivity.ts +833 -0
  56. package/src/core/protocol.ts +370 -5
  57. package/src/core/push.ts +385 -0
  58. package/src/core/questions.ts +81 -10
  59. package/src/core/session-meta.ts +73 -1
  60. package/src/core/squads.ts +345 -0
  61. package/src/core/turn-end-quiet.ts +388 -0
  62. package/src/core/ui.ts +398 -0
  63. package/src/core/usage-stats.ts +424 -0
  64. package/src/core/usage.ts +937 -0
  65. package/src/core/wire.ts +8 -0
  66. package/src/host/apns.ts +320 -0
  67. package/src/host/squads-ledger.ts +105 -0
  68. package/src/host/squads.ts +206 -0
  69. package/src/host/ui-tools.ts +233 -0
  70. package/src/host/usage-stats.ts +155 -0
  71. package/src/host/watchers.ts +296 -0
  72. package/src/index.ts +327 -10
package/src/core/ui.ts ADDED
@@ -0,0 +1,398 @@
1
+ /**
2
+ * The bridge's claims on `ui.request` (§35): which self-contained pages a phone
3
+ * or the desktop may show, and the one path a user's action travels back into the
4
+ * tool call that presented it.
5
+ *
6
+ * A card belongs to exactly one tool call and ends at the user's FIRST action:
7
+ * the first `ui.event` settles it and becomes that call's result, so a card that
8
+ * should keep taking actions is a second presentation rather than a second event
9
+ * (§35.3, §35.8). Every claim is one record keyed by the call id published on the
10
+ * wire, so an event that arrives late still lands, and one naming a call id this
11
+ * bridge never claimed is refused instead of being handed to a tool that is not
12
+ * waiting for it.
13
+ *
14
+ * The bridge invents no deadline: the tool schema declares no `timeout`, so a
15
+ * card carries no `expiresAt` and stays open until the user acts, the agent's own
16
+ * turn is cancelled, or the last paired device has been gone long enough for the
17
+ * hub's grace window (§35.5). It also fabricates no event: a card nobody answered
18
+ * is released as a refusal, never as a decision the operator did not make.
19
+ *
20
+ * Both caps are enforced on this side rather than the client's (§35.2, §35.3): a
21
+ * client that refused an oversized page would leave the agent waiting for a card
22
+ * that never comes, so the call is refused as `invalid-args` before any frame is
23
+ * written.
24
+ * @module dsh-remote-bridge/core/ui
25
+ */
26
+
27
+ import { CODE_UI_SETTLED, CODE_UI_UNKNOWN } from './protocol.ts'
28
+
29
+ /** Upper bound of one card's document, in UTF-8 bytes (§35.2). */
30
+ export const UI_HTML_MAX_BYTES = 262_144
31
+
32
+ /** Upper bound of one `ui.event` payload, in UTF-8 bytes (§35.3). */
33
+ export const UI_PAYLOAD_MAX_BYTES = 8192
34
+
35
+ /**
36
+ * How many settled call ids this bridge remembers, so a repeated tap is answered
37
+ * `ui-settled` instead of `ui-unknown` (§35.3).
38
+ *
39
+ * The promise is already settled and the card is already gone by then; the only
40
+ * reason to remember the id is that a client which tapped twice must be able to
41
+ * tell "already done" from "never mine". A phone holds no more live cards than it
42
+ * rendered, so the bound costs one short string per presentation and never grows
43
+ * with the process's uptime.
44
+ */
45
+ export const UI_SETTLED_MEMORY = 256
46
+
47
+ /** Whether a card still holds the tool call, or is only a notice now. */
48
+ export type UiState = 'open' | 'settled'
49
+
50
+ /** One lossless JSON value, as the wire carries it inside an event payload. */
51
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }
52
+
53
+ /** The action a user took inside one card, in the presenter's own closed set. */
54
+ export interface UiEvent {
55
+ readonly type: string
56
+ readonly payload?: JsonValue
57
+ }
58
+
59
+ /**
60
+ * The `ui.request` payload for one claim, and the `payload` of every `ui.list`
61
+ * entry.
62
+ *
63
+ * One function for both so the card a client was handed and the card it reads back
64
+ * out of a list cannot drift apart: an absent `title` or `height` is an absent key
65
+ * rather than an empty or null one, exactly as §35.2 froze it. `expiresAt` is never
66
+ * written: a presentation whose tool schema declares no `timeout` has no deadline
67
+ * to publish, and a published one would be a promise this bridge does not keep.
68
+ * @param state - whether the card still holds the tool call.
69
+ * @param card - the claim being published.
70
+ * @returns the frozen payload body.
71
+ */
72
+ export function uiPayload(state: UiState, card: UiCardView): UiRequestPayload {
73
+ return {
74
+ sessionId: card.sessionId,
75
+ callId: card.callId,
76
+ state,
77
+ ...(card.title === undefined ? {} : { title: card.title }),
78
+ html: card.html,
79
+ ...(card.height === undefined ? {} : { height: card.height }),
80
+ }
81
+ }
82
+
83
+ /**
84
+ * The identity a client knows one card by (`"<sessionId>/<callId>"`, §35.4).
85
+ *
86
+ * The same pair a `ui.list` row carries, so the card a tool presented and the row
87
+ * a client reconciles it against are compared as one name instead of two fields
88
+ * that could be recombined differently on each side.
89
+ * @param sessionId - the session whose agent presented the card.
90
+ * @param callId - the tool call id it is held under.
91
+ * @returns the card key.
92
+ */
93
+ export function uiKey(sessionId: string, callId: string): string {
94
+ return sessionId + '/' + callId
95
+ }
96
+
97
+ /** @returns the UTF-8 byte length of one string. */
98
+ function utf8Bytes(text: string): number {
99
+ return new TextEncoder().encode(text).length
100
+ }
101
+
102
+ /** @returns whether one card document is within {@link UI_HTML_MAX_BYTES}. */
103
+ export function uiHtmlFits(html: string): boolean {
104
+ return utf8Bytes(html) <= UI_HTML_MAX_BYTES
105
+ }
106
+
107
+ /**
108
+ * Read one `ui.event` body out of a decoded frame.
109
+ *
110
+ * The event's `type` is the presenter's own closed set: this bridge carries it and
111
+ * never interprets the value, so the only shape it enforces is the one the frame
112
+ * declares (§35.3). An absent and an explicit `null` payload are different
113
+ * things — the payload key is kept exactly when the client sent one.
114
+ * @param raw - the `event` field as it crossed the wire.
115
+ * @returns the event, or undefined when the frame is not one.
116
+ */
117
+ export function uiEventOf(raw: unknown): UiEvent | undefined {
118
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
119
+ const record = raw as Record<string, unknown>
120
+ const type = record.type
121
+ if (typeof type !== 'string' || type === '') return undefined
122
+ return record.payload === undefined ? { type } : { type, payload: record.payload as JsonValue }
123
+ }
124
+
125
+ /** @returns whether one event's payload is within {@link UI_PAYLOAD_MAX_BYTES}. */
126
+ export function uiEventFits(event: UiEvent): boolean {
127
+ return event.payload === undefined || utf8Bytes(JSON.stringify(event.payload)) <= UI_PAYLOAD_MAX_BYTES
128
+ }
129
+
130
+ /** One card this bridge still holds, as `ui.list` publishes it (§35.4). */
131
+ export interface ListedCard {
132
+ /** {@link uiKey}: the identity the client holds it under. */
133
+ readonly key: string
134
+ readonly sessionId: string
135
+ /** `open` or `settled`; a settled card is not held and never listed. */
136
+ readonly state: UiState
137
+ /** The `ui.request` payload, byte for byte the shape §35.2 froze. */
138
+ readonly payload: UiRequestPayload
139
+ }
140
+
141
+ /**
142
+ * The body of one `ui.list` answer.
143
+ *
144
+ * `complete` is what a client is allowed to act on: only a COMPLETE list may
145
+ * retire a card it does not carry (§35.5, §24.3), so a bridge that could answer
146
+ * only part of the set must say `false` rather than let the difference read as
147
+ * "the card is over".
148
+ */
149
+ export interface UiListPayload {
150
+ readonly cards: readonly ListedCard[]
151
+ readonly complete: boolean
152
+ }
153
+
154
+ /** `ui.request`'s payload, as §35.2 froze it. */
155
+ export interface UiRequestPayload {
156
+ readonly sessionId: string
157
+ readonly callId: string
158
+ readonly state: UiState
159
+ /** One header line; absent when the presenter named none. */
160
+ readonly title?: string
161
+ /** A whole self-contained document, `<!doctype html>` first, within {@link UI_HTML_MAX_BYTES}. */
162
+ readonly html: string
163
+ /** The presenter's suggested initial height in points; the client still measures. */
164
+ readonly height?: number
165
+ /**
166
+ * Epoch milliseconds of this bridge's own deadline for the card; absent, always,
167
+ * for a presentation whose tool schema declares no `timeout` (§35.2).
168
+ */
169
+ readonly expiresAt?: number
170
+ }
171
+
172
+ /** The identity and content of one claim, as the hub publishes it. */
173
+ export interface UiCardView {
174
+ readonly sessionId: string
175
+ readonly callId: string
176
+ readonly html: string
177
+ readonly title?: string
178
+ readonly height?: number
179
+ }
180
+
181
+ /** Why one presentation ended without a user action, in the wire's own vocabulary. */
182
+ export type UiRefusalReason = 'unavailable' | 'invalid-args' | 'timeout' | 'cancelled'
183
+
184
+ /** What one presentation ended as: the user's action, or the refusal to wait for one. */
185
+ export type UiPresentOutcome =
186
+ | { readonly ok: true; readonly type: string; readonly payload?: JsonValue }
187
+ | { readonly ok: false; readonly reason: UiRefusalReason }
188
+
189
+ /** What one `ui.event` produced: acknowledgement, or the refusal to accept it. */
190
+ export type UiEventReply = { readonly ok: true } | { readonly ok: false; readonly code: string; readonly msg: string }
191
+
192
+ export interface OpenCardInput {
193
+ readonly sessionId: string
194
+ /** The id published on the wire, which is the host's own `ToolCallId`. */
195
+ readonly callId: string
196
+ readonly html: string
197
+ readonly title?: string
198
+ readonly height?: number
199
+ /** The agent's own cancellation lifetime for this call. */
200
+ readonly signal?: AbortSignal
201
+ /**
202
+ * Called when the card leaves this bridge — the user's event, the grace window,
203
+ * a cancelled turn, the bridge unloading. The client still holds a card for it
204
+ * and has to be told, or it keeps showing a page whose actions go nowhere.
205
+ */
206
+ readonly onSettled?: (card: UiCardView) => void
207
+ }
208
+
209
+ /** The presentation one `ui.present` call is waiting on, as the hub publishes it. */
210
+ export interface ClaimedCard extends UiCardView {
211
+ /** The user's action, or the refusal that ended the card. Never rejects. */
212
+ readonly outcome: Promise<UiPresentOutcome>
213
+ }
214
+
215
+ /** One live claim, with every path that ends it. */
216
+ interface Claim {
217
+ readonly sessionId: string
218
+ readonly callId: string
219
+ readonly html: string
220
+ readonly title: string | undefined
221
+ readonly height: number | undefined
222
+ readonly finish: (outcome: UiPresentOutcome) => void
223
+ readonly detach: () => void
224
+ /** Tells the client its card is over; set from the input's `onSettled`. */
225
+ readonly notifySettled: () => void
226
+ }
227
+
228
+ /**
229
+ * The publishable view of one claim.
230
+ * @param record - the live claim.
231
+ * @returns the card's fields as the hub publishes them.
232
+ */
233
+ function viewOf(record: Claim): UiCardView {
234
+ return {
235
+ sessionId: record.sessionId,
236
+ callId: record.callId,
237
+ html: record.html,
238
+ ...(record.title === undefined ? {} : { title: record.title }),
239
+ ...(record.height === undefined ? {} : { height: record.height }),
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Pending cards of one bridge process.
245
+ *
246
+ * One record per call id published on the wire and one settle for every path
247
+ * (the user's event, the agent's cancellation, the grace window, bridge unload),
248
+ * so a card can never be settled twice and a released claim leaves no abort
249
+ * listener behind.
250
+ */
251
+ export class UiCards {
252
+ readonly #cards = new Map<string, Claim>()
253
+ /** Call ids a user's own event settled, oldest first, bounded by {@link UI_SETTLED_MEMORY}. */
254
+ readonly #settled = new Set<string>()
255
+
256
+ /** @returns how many cards this bridge currently holds. */
257
+ get size(): number {
258
+ return this.#cards.size
259
+ }
260
+
261
+ /**
262
+ * @param callId - one wire call id.
263
+ * @returns `open` while it holds a tool call, `settled` once a user's event
264
+ * settled it, and undefined when this bridge never claimed it — which is how a
265
+ * listener tells `ui-settled` from `ui-unknown` (§35.3).
266
+ */
267
+ stateOf(callId: string): UiState | undefined {
268
+ if (this.#cards.has(callId)) return 'open'
269
+ return this.#settled.has(callId) ? 'settled' : undefined
270
+ }
271
+
272
+ /**
273
+ * Claim one card.
274
+ * @param input - session identity, wire call id, the page, and the host's lifetime.
275
+ * @returns the claim the hub publishes, or undefined when there is nothing to publish.
276
+ */
277
+ open(input: OpenCardInput): ClaimedCard | undefined {
278
+ // A call whose own lifetime already ended has no card to publish: announcing one
279
+ // would hand the client a page that can never be settled.
280
+ if (input.signal?.aborted === true) return undefined
281
+ if (this.#cards.has(input.callId) || this.#settled.has(input.callId)) return undefined
282
+ let finish: (outcome: UiPresentOutcome) => void = () => undefined
283
+ const outcome = new Promise<UiPresentOutcome>((resolve) => { finish = resolve })
284
+ const signal = input.signal
285
+ const onAbort = (): void => { this.#cancel(input.callId) }
286
+ const record: Claim = {
287
+ sessionId: input.sessionId,
288
+ callId: input.callId,
289
+ html: input.html,
290
+ title: input.title,
291
+ height: input.height,
292
+ finish,
293
+ detach: (): void => { signal?.removeEventListener('abort', onAbort) },
294
+ notifySettled: (): void => { input.onSettled?.(viewOf(record)) },
295
+ }
296
+ this.#cards.set(input.callId, record)
297
+ signal?.addEventListener('abort', onAbort, { once: true })
298
+ return { ...viewOf(record), outcome }
299
+ }
300
+
301
+ /**
302
+ * Settle one card from the client's first event (§35.3).
303
+ *
304
+ * The event is the tool call's result and its only result: the card leaves the
305
+ * held table in the same step, so a second event finds it settled rather than
306
+ * settling the call twice.
307
+ * @param sessionId - the session the client believes owns the card.
308
+ * @param callId - the wire call id the client was shown.
309
+ * @param event - the user's action, carried verbatim.
310
+ */
311
+ settle(sessionId: string, callId: string, event: UiEvent): UiEventReply {
312
+ const record = this.#cards.get(callId)
313
+ if (record === undefined) {
314
+ return this.#settled.has(callId)
315
+ ? { ok: false, code: CODE_UI_SETTLED, msg: 'this card is already settled' }
316
+ : { ok: false, code: CODE_UI_UNKNOWN, msg: 'the card is unknown or was settled elsewhere' }
317
+ }
318
+ if (record.sessionId !== sessionId) {
319
+ return { ok: false, code: CODE_UI_UNKNOWN, msg: 'the card is unknown or was settled elsewhere' }
320
+ }
321
+ this.#cards.delete(callId)
322
+ this.#remember(callId)
323
+ record.detach()
324
+ record.notifySettled()
325
+ record.finish(event.payload === undefined ? { ok: true, type: event.type } : { ok: true, type: event.type, payload: event.payload })
326
+ return { ok: true }
327
+ }
328
+
329
+ /**
330
+ * Every card this bridge still holds, as `ui.list` publishes it (§35.4).
331
+ *
332
+ * The claim registry IS the answer: a card leaves it the moment the user settles
333
+ * it, the grace window releases it, or the bridge unloads, so a card missing from
334
+ * this list is one no action can reach any more. Only `open` is ever listed —
335
+ * `settled` is the one-way notice, never a held row.
336
+ * @returns one entry per held card, in claim order.
337
+ */
338
+ listed(): readonly ListedCard[] {
339
+ return [...this.#cards.values()].map(record => ({
340
+ key: uiKey(record.sessionId, record.callId),
341
+ sessionId: record.sessionId,
342
+ state: 'open',
343
+ payload: uiPayload('open', viewOf(record)),
344
+ }))
345
+ }
346
+
347
+ /**
348
+ * Withdraw the named cards, ending each tool call with a refusal.
349
+ * @param callIds - the cards to release.
350
+ * @param reason - why; carried into the tool result as it stands.
351
+ * @returns how many were still open and therefore released.
352
+ */
353
+ withdraw(callIds: readonly string[], reason: UiRefusalReason = 'timeout'): number {
354
+ let withdrawn = 0
355
+ for (const callId of callIds) {
356
+ const record = this.#cards.get(callId)
357
+ if (record === undefined) continue
358
+ this.#cards.delete(callId)
359
+ record.detach()
360
+ record.notifySettled()
361
+ record.finish({ ok: false, reason })
362
+ withdrawn += 1
363
+ }
364
+ return withdrawn
365
+ }
366
+
367
+ /**
368
+ * Withdraw every claim.
369
+ * @param reason - why; carried into every released tool call.
370
+ * @returns how many cards were still open.
371
+ */
372
+ withdrawAll(reason: UiRefusalReason = 'timeout'): number {
373
+ return this.withdraw([...this.#cards.keys()], reason)
374
+ }
375
+
376
+ /**
377
+ * End one card from the agent's own cancellation lifetime.
378
+ *
379
+ * The tool call is going away, so nothing can settle it later: the promise is
380
+ * resolved with the refusal instead of being left pending, and the client is told
381
+ * its page is over rather than left with a card whose actions go nowhere.
382
+ */
383
+ #cancel(callId: string): void {
384
+ this.withdraw([callId], 'cancelled')
385
+ }
386
+
387
+ /**
388
+ * Remember one call id a user's event settled, dropping the oldest once the bound
389
+ * is reached — a repeated tap is answered `ui-settled` while the id is here, and
390
+ * `ui-unknown` afterwards.
391
+ */
392
+ #remember(callId: string): void {
393
+ this.#settled.add(callId)
394
+ if (this.#settled.size <= UI_SETTLED_MEMORY) return
395
+ const oldest = this.#settled.values().next().value
396
+ if (oldest !== undefined) this.#settled.delete(oldest)
397
+ }
398
+ }