@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
@@ -17,38 +17,60 @@
17
17
  */
18
18
 
19
19
  import type { ApprovalRegistry } from './approvals.ts'
20
- import type { DeviceRoster } from './devices.ts'
20
+ import { commandItems, commandsUnavailable } from './commands.ts'
21
+ import type { DeviceRoster, PushEnvironment, PushLiveActivityToken, PushRegistration } from './devices.ts'
21
22
  import { ROSTER_DELTA_MAX_ROWS, RemoteBridgeDeltas, type DeltaRow } from './delta.ts'
22
23
  import { deltaOfFollowFrame, MessageIndex, oldestEntrySeq, pageTurns, readFollowBaseline, SpawnCallIndex, ToolCallIndex, trimUnrenderedEntries, turnsAbove, turnsOfRecords, type FollowBaseline, type SnapshotTurn } from './dsh-frames.ts'
23
24
  import { EventSequence, FRAME_TOO_LARGE, MAX_FRAME_BYTES, decodeClientFrame, encodeFrame, errorFrame, responseFrame, type ReqFrame, type ServerFrame } from './envelope.ts'
24
25
  import type { RemoteBridgeMethodResult, RemoteBridgeRegistry } from './extension.ts'
25
26
  import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
26
27
  import { scopeKey, type JobRoster, type JobsPayload } from './jobs.ts'
28
+ import type { LiveActivityNotifier } from './liveactivity.ts'
27
29
  import type { PairingService } from './pairing.ts'
28
- import type { QuestionAnswerItem, QuestionClaims } from './questions.ts'
30
+ import type { PushNotifier } from './push.ts'
31
+ import { pushEventOfTurnEnd } from './push.ts'
32
+ import type { ListedQuestion, QuestionAnswerItem, QuestionClaims, QuestionListPayload } from './questions.ts'
33
+ import type { TurnEndQuietGate } from './turn-end-quiet.ts'
34
+ import { uiEventFits, uiEventOf } from './ui.ts'
35
+ import type { ListedCard, UiCards, UiListPayload } from './ui.ts'
29
36
  import {
30
37
  CAP_AGENTS,
38
+ CAP_COMMANDS,
31
39
  CAP_DELTA,
32
40
  CAP_FRAME_DEFLATE,
33
41
  CAP_JOBS,
42
+ CAP_PUSH,
34
43
  CAP_QUESTIONS,
44
+ CAP_QUESTION_LIST,
35
45
  CAP_ROSTER_COMPACT,
46
+ CAP_SESSION_ADMIN,
36
47
  CAP_SESSION_FORK,
37
48
  CAP_SESSION_SNAPSHOT_PAGE,
38
49
  CAP_SESSION_SNAPSHOT_SINCE,
39
50
  CAP_SESSION_SNAPSHOT_TRIM,
51
+ CAP_SQUADS,
40
52
  CAP_SUBAGENT_THREAD,
53
+ CAP_UI,
54
+ CAP_UI_LIST,
55
+ CAP_USAGE,
56
+ CAP_USAGE_STATS,
57
+ CAP_WORKSPACE,
41
58
  CODE_APPROVAL_UNKNOWN,
59
+ CODE_COMMANDS_UNAVAILABLE,
42
60
  CODE_INTERNAL,
43
61
  CODE_INVALID_ARGS,
44
62
  CODE_JOBS_UNAVAILABLE,
45
63
  CODE_NONCE_INVALID,
46
64
  CODE_PROTO_UNSUPPORTED,
65
+ CODE_QUESTION_LIST_UNAVAILABLE,
47
66
  CODE_SESSION_NOT_FOLLOWABLE,
48
67
  CODE_SNAPSHOT_TOO_LARGE,
49
68
  CODE_SNAPSHOT_UNAVAILABLE,
69
+ CODE_SQUADS_UNAVAILABLE,
50
70
  CODE_TOKEN_INVALID,
71
+ CODE_UI_LIST_UNAVAILABLE,
51
72
  CODE_UNKNOWN_METHOD,
73
+ CODE_UNKNOWN_SESSION,
52
74
  CODE_UNPAIRED,
53
75
  KNOWN_METHODS,
54
76
  METHOD_APPROVAL_RESOLVE,
@@ -57,8 +79,13 @@ import {
57
79
  METHOD_PAIR_BEGIN,
58
80
  METHOD_PAIR_FINISH,
59
81
  METHOD_PRESETS_LIST,
82
+ METHOD_PUSH_REGISTER,
60
83
  METHOD_QUESTION_ANSWER,
84
+ METHOD_QUESTION_LIST,
85
+ METHOD_SESSION_ARCHIVE,
61
86
  METHOD_SESSION_ATTACHMENT,
87
+ METHOD_SESSION_COMMAND,
88
+ METHOD_SESSION_COMMANDS,
62
89
  METHOD_SESSION_CREATE,
63
90
  METHOD_SESSION_FORK,
64
91
  METHOD_SESSION_HISTORY,
@@ -67,11 +94,26 @@ import {
67
94
  METHOD_SESSION_LIST,
68
95
  METHOD_SESSION_MODELS,
69
96
  METHOD_SESSION_PERMISSIONS,
97
+ METHOD_SESSION_PIN,
70
98
  METHOD_SESSION_PROMPT,
99
+ METHOD_SESSION_RENAME,
71
100
  METHOD_SESSION_SET_MODEL,
72
101
  METHOD_SESSION_SET_PERMISSION,
73
102
  METHOD_SESSION_SNAPSHOT,
74
103
  METHOD_SESSION_TITLES,
104
+ METHOD_SESSION_UNARCHIVE,
105
+ METHOD_UI_EVENT,
106
+ METHOD_UI_LIST,
107
+ METHOD_SESSION_UNPIN,
108
+ METHOD_SQUADS_LIST,
109
+ METHOD_SQUADS_RUNS,
110
+ METHOD_SQUADS_RUN_MEMBER,
111
+ METHOD_SQUADS_RUN_SQUAD,
112
+ METHOD_SQUADS_STATE,
113
+ METHOD_USAGE_BALANCE,
114
+ METHOD_USAGE_SESSION,
115
+ METHOD_USAGE_STATS,
116
+ METHOD_WORKSPACE_LIST,
75
117
  MINOR,
76
118
  PROTO,
77
119
  SERVED_CAPABILITIES,
@@ -81,8 +123,10 @@ import {
81
123
  UNPAIRED_METHODS,
82
124
  } from './protocol.ts'
83
125
  import { base64UrlDecode, verifyEs256 } from './crypto.ts'
126
+ import { isSquadRefusal, parseSquadMemberRun, parseSquadRun, squadRunOf, SQUAD_METHODS, squadsStateOf, type SquadTransport, type SquadsState } from './squads.ts'
84
127
  import { TITLES_MAX_IDS, type SessionMeta } from './session-meta.ts'
85
128
  import type { SessionPermissions } from './session-permissions.ts'
129
+ import { USAGE_METHODS, type UsageService } from './usage.ts'
86
130
  import type { BridgeGateway, GatewayPeer } from './wire.ts'
87
131
  import { CODE_SUBAGENT_ADDRESS_REQUIRED, sessionAddress, subagentAddress, wireArgs, type SessionAddress } from './wire.ts'
88
132
  import { CLOSE_LIVENESS_TIMEOUT } from './ws-frames.ts'
@@ -146,10 +190,21 @@ export interface BridgeConnectionOptions {
146
190
  readonly approvals: ApprovalRegistry
147
191
  /** Pending user questions: the claims this bridge holds and the answer path back to the host. */
148
192
  readonly questions: QuestionClaims
193
+ /**
194
+ * 整页卡(§35):`ui.present` 持有的每一张卡,`ui.event` 结算它们,`ui.list`
195
+ * 把它们念回去。与提问表平级、各自认领各自结算——两条通道互不改形状(§35.8)。
196
+ */
197
+ readonly ui: UiCards
149
198
  /** The host's background jobs: the read-only projection and the scopes this connection watches. */
150
199
  readonly jobs: JobRoster
151
200
  /** Process-local session metadata: live titles and the host's archive set. */
152
201
  readonly sessionMeta: SessionMeta
202
+ /**
203
+ * `usage.v1` 背后两半读数:一条会话的上下文窗口与请求组成估算,以及某条
204
+ * provider 路由背后账户的余额。两者都是宿主侧的事实而不是某个设备的事实,
205
+ * 所以一个宿主一份、所有连接共享(见 `core/usage.ts`)。
206
+ */
207
+ readonly usage: UsageService
153
208
  /** Host-process permission presets, read and switched through their real service objects. */
154
209
  readonly permissions: SessionPermissions
155
210
  /**
@@ -176,6 +231,47 @@ export interface BridgeConnectionOptions {
176
231
  * `KNOWN_METHODS` answers `unknown-method`.
177
232
  */
178
233
  readonly extensions?: RemoteBridgeRegistry
234
+ /**
235
+ * The host's squad domain, behind the `squads.v1` channel. Absent is a host
236
+ * that serves no `dsh-agents` domain: the capability stays advertised and only
237
+ * a call that needs the domain answers `squads-unavailable`.
238
+ */
239
+ readonly squads?: SquadTransport
240
+ /**
241
+ * The outbound notification path, behind the `push.v1` channel. Absent is a
242
+ * bridge that sends nothing: `push.register` still answers `ok:true` (the
243
+ * device row is written either way), and no notification is ever built. That
244
+ * is the default, because a sender needs an Apple signing key this bridge is
245
+ * not shipped with.
246
+ */
247
+ readonly push?: PushNotifier
248
+ /**
249
+ * The lock-screen card path, behind the same `push.v1` channel. Absent — and it
250
+ * is absent whenever no APNs key is configured — is a bridge that never builds a
251
+ * card: the roster is still served and a question is still answered, because
252
+ * registering the phone's tokens and pushing to them are two different things
253
+ * (§28.3, §29).
254
+ */
255
+ readonly liveActivity?: LiveActivityNotifier
256
+ /**
257
+ * The gate a finished turn is announced through (§28, §29).
258
+ *
259
+ * Absent is a bridge assembled without one — a suite, or an embedder — and then
260
+ * both channels report at the frame, exactly as they did before the gate
261
+ * existed. The mount always hands one, because it is the only assembly that can
262
+ * read the host's own answer.
263
+ */
264
+ readonly turnEndQuiet?: TurnEndQuietGate
265
+ /**
266
+ * Called after a registration changed the device table.
267
+ *
268
+ * A session's first live-activity token is what asks this bridge to keep a
269
+ * follow stream of its own open for that session (`host/watchers.ts`), so the
270
+ * roster is the trigger. The hook is guarded at the call site: a standing
271
+ * watcher is this bridge's own background work and may never turn a
272
+ * `push.register` into a failure.
273
+ */
274
+ readonly onPushRegistered?: () => void
179
275
  }
180
276
 
181
277
  /** A device the connection proved itself to be, resolved from the upgrade request. */
@@ -183,6 +279,39 @@ export interface ConnectionAuth {
183
279
  readonly deviceId: string
184
280
  }
185
281
 
282
+ /**
283
+ * Whether one follow increment proves its session is working again.
284
+ *
285
+ * Deliberately narrow, and never "anything that is not a turn end": a parent's
286
+ * stream also carries a settled child's message (`source.kind` `subagent-settled`
287
+ * or `agent-message`, which the frames read as an agent actor), the usage count the
288
+ * host publishes as an assistant message finishes, and the catalog changes of the
289
+ * threads that session spawned. Reading any of those as a new turn would drop the
290
+ * turn end a waiting phone has not been told about yet — the one whose session is
291
+ * still busy with a running child, which is the case §28's gate exists for.
292
+ *
293
+ * One shared rule on purpose: this connection's own drain and the standing watchers
294
+ * both read it, so the two paths cannot disagree about what a new turn looks like.
295
+ * @param delta - one increment of a follow stream.
296
+ * @returns whether assistant work is streaming, or this session's own user wrote.
297
+ */
298
+ export function isTurnStartDelta(delta: { readonly kind: string; readonly actor?: { readonly kind?: string } }): boolean {
299
+ switch (delta.kind) {
300
+ case 'text':
301
+ case 'reasoning':
302
+ case 'tool-call':
303
+ case 'tool-result':
304
+ return true
305
+ case 'user-message':
306
+ // A message with no actor is not evidence: a durable log written before
307
+ // sources existed carries none, and guessing "human" there would drop a real
308
+ // announcement.
309
+ return delta.actor?.kind === 'human'
310
+ default:
311
+ return false
312
+ }
313
+ }
314
+
186
315
  /** The answer of a subscription's opening frame: a baseline, or why there is none. */
187
316
  type Opening = { readonly ok: true; readonly baseline: FollowBaseline } | { readonly ok: false; readonly code: string; readonly msg: string }
188
317
 
@@ -285,6 +414,31 @@ function optionalText(value: unknown): string | undefined {
285
414
  return typeof value === 'string' && value !== '' ? value : undefined
286
415
  }
287
416
 
417
+ /**
418
+ * One roster row's own title, as the host's projection carries it.
419
+ *
420
+ * `SessionSummary` has no top-level `title` — which is why this bridge once read
421
+ * its own live-title cache and nothing else. Every row nevertheless carries
422
+ * `projections.values.title`: the host folds that out of its projection cache
423
+ * synchronously for a cold session as well as a live one, with no log read and no
424
+ * follow stream, and its own desktop list renders exactly that field. Reading it
425
+ * costs no call, because it is already inside the listing the bridge just paid
426
+ * for.
427
+ *
428
+ * The guard is the one every optional field here takes: a `projections` block
429
+ * that is not an object, a `values` member that is not one, and a `title` that is
430
+ * not a non-empty string are all simply absent, so an answer of another shape
431
+ * costs a row its title rather than failing the listing.
432
+ * @param item - one row of the host's `session/list` answer.
433
+ * @returns the projected title, or undefined when the row carries none.
434
+ */
435
+ function projectedTitleOf(item: Readonly<Record<string, unknown>>): string | undefined {
436
+ const projections = isRecord(item.projections) ? item.projections : undefined
437
+ if (projections === undefined) return undefined
438
+ const values = isRecord(projections.values) ? projections.values : undefined
439
+ return values === undefined ? undefined : optionalText(values.title)
440
+ }
441
+
288
442
  /** @returns a non-negative safe integer page argument, or undefined. */
289
443
  function pageNumber(value: unknown): number | undefined {
290
444
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined
@@ -405,15 +559,23 @@ function answersOf(value: unknown): readonly QuestionAnswerItem[] | undefined {
405
559
  return answers
406
560
  }
407
561
 
408
- /** One model selection, in the field names the protocol publishes. */
409
- type ModelSelection = {
562
+ /**
563
+ * One model selection, in the field names the protocol publishes.
564
+ *
565
+ * Exported beside {@link selectionOf} and {@link modelSelectionOf} because the
566
+ * host half resolves a session's current route for `usage.stats`'s neighbour
567
+ * key `usage.session`/`modelContextWindow` with exactly this fold: two readings
568
+ * of "which model is this session on" would let the two methods name different
569
+ * routes for the same session.
570
+ */
571
+ export type ModelSelection = {
410
572
  readonly provider: string
411
573
  readonly model: string
412
574
  readonly reasoningEffort?: string
413
575
  }
414
576
 
415
577
  /** @returns the selection this value describes, or undefined when it describes none. */
416
- function selectionOf(value: unknown): ModelSelection | undefined {
578
+ export function selectionOf(value: unknown): ModelSelection | undefined {
417
579
  if (!isRecord(value)) return undefined
418
580
  const provider = optionalText(value.provider)
419
581
  const model = optionalText(value.model)
@@ -428,7 +590,7 @@ function selectionOf(value: unknown): ModelSelection | undefined {
428
590
  * Both halves stay optional: a session that never ran has neither, and the
429
591
  * catalog default is then the only truthful current value.
430
592
  */
431
- function modelSelectionOf(value: unknown): { readonly next?: ModelSelection; readonly lastUsed?: ModelSelection } {
593
+ export function modelSelectionOf(value: unknown): { readonly next?: ModelSelection; readonly lastUsed?: ModelSelection } {
432
594
  if (!isRecord(value) || !isRecord(value.values)) return {}
433
595
  const selection = value.values.modelSelection
434
596
  if (!isRecord(selection)) return {}
@@ -704,6 +866,12 @@ export class BridgeConnection {
704
866
  if (frame.m === METHOD_QUESTION_ANSWER && !this.declares(CAP_QUESTIONS)) {
705
867
  return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
706
868
  }
869
+ // `question.list` is its own channel capability, declared by the client and
870
+ // announced by the bridge: a client that never declared it is told what it was
871
+ // told before the method existed, and no claim registry is read on its behalf.
872
+ if (frame.m === METHOD_QUESTION_LIST && !this.declares(CAP_QUESTION_LIST)) {
873
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
874
+ }
707
875
  // `jobs.list` is the whole of the job channel: without the capability the
708
876
  // method does not exist, and without the method no scope is ever watched, so
709
877
  // a client that never declared it can receive no `jobs.changed` either.
@@ -722,6 +890,65 @@ export class BridgeConnection {
722
890
  if (frame.m === METHOD_SESSION_FORK && !this.declares(CAP_SESSION_FORK)) {
723
891
  return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
724
892
  }
893
+ // The command channel is one capability: without `commands.v1` neither the
894
+ // directory nor the dispatch is part of this client's protocol, so no
895
+ // registry and no skill catalog is read on a client's behalf that never
896
+ // asked for either.
897
+ if ((frame.m === METHOD_SESSION_COMMANDS || frame.m === METHOD_SESSION_COMMAND) && !this.declares(CAP_COMMANDS)) {
898
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
899
+ }
900
+ // Reading workspaces is its own capability, apart from the five writes beside
901
+ // it: a client may ask what this host has and where without ever renaming,
902
+ // pinning or archiving anything, so the reading half is declared on its own
903
+ // and a client that declared only the writing half reads no registry.
904
+ if (frame.m === METHOD_WORKSPACE_LIST && !this.declares(CAP_WORKSPACE)) {
905
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
906
+ }
907
+ // The session-admin writes are one capability: without it none of the five is
908
+ // part of this client's protocol, so no title is written and no set is
909
+ // mutated on behalf of a client that predates the channel.
910
+ if (!this.declares(CAP_SESSION_ADMIN)
911
+ && (frame.m === METHOD_SESSION_RENAME
912
+ || frame.m === METHOD_SESSION_PIN
913
+ || frame.m === METHOD_SESSION_UNPIN
914
+ || frame.m === METHOD_SESSION_ARCHIVE
915
+ || frame.m === METHOD_SESSION_UNARCHIVE)) {
916
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
917
+ }
918
+ // The squads channel is one capability: without `squads.v1` none of the five
919
+ // commands is part of this client's protocol, so no squad domain is read and
920
+ // no session is launched on behalf of a client that never asked to drive one.
921
+ if (SQUAD_METHODS.has(frame.m) && !this.declares(CAP_SQUADS)) {
922
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
923
+ }
924
+ // Registering an APNs token is its own capability: without `push.v1` the
925
+ // method does not exist for this client, and no device row is written on its
926
+ // behalf. The capability gates the WRITE only — whether a notification ever
927
+ // leaves this process is a deployment fact the wire cannot express (§28.3).
928
+ if (frame.m === METHOD_PUSH_REGISTER && !this.declares(CAP_PUSH)) {
929
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
930
+ }
931
+ // 用量通道是一个能力:不宣告 `usage.v1` 的客户端看到的仍是它从前看到的
932
+ // `unknown-method`,本桥也不会替它折一条会话事件、更不会替它打一次上游
933
+ // 余额端点。
934
+ if (USAGE_METHODS.has(frame.m) && !this.declares(CAP_USAGE)) {
935
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
936
+ }
937
+ // 台账聚合是另一个能力,因为它读的是另一个插件挂在这个宿主上的路由:不宣告
938
+ // `usage.stats.v1` 的客户端看不到这个方法,本桥也不会替它去读那两条路由。
939
+ if (frame.m === METHOD_USAGE_STATS && !this.declares(CAP_USAGE_STATS)) {
940
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
941
+ }
942
+ // 整页卡是 §35 的一条通道、一个能力:不宣告 `ui.v1` 的客户端看到的仍是它从前
943
+ // 看到的 `unknown-method`,本桥也不会替它把一条动作交给某个工具调用。
944
+ if (frame.m === METHOD_UI_EVENT && !this.declares(CAP_UI)) {
945
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
946
+ }
947
+ // 对账读是它自己的能力,与 §24 同一判据:不宣告 `ui.list.v1` 的客户端读不到卡表,
948
+ // 本桥也不会替它翻一遍认领表。
949
+ if (frame.m === METHOD_UI_LIST && !this.declares(CAP_UI_LIST)) {
950
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
951
+ }
725
952
  // Unconditional: a loopback Host buys nothing here. Without a device token
726
953
  // only the handshake and the two pairing steps run.
727
954
  if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, 'this connection is not paired')
@@ -748,10 +975,30 @@ export class BridgeConnection {
748
975
  case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p)
749
976
  case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p)
750
977
  case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p)
978
+ case METHOD_QUESTION_LIST: return this.#questionList(frame.p)
979
+ case METHOD_UI_EVENT: return this.#uiEvent(frame.p)
980
+ case METHOD_UI_LIST: return this.#uiList(frame.p)
981
+ case METHOD_PUSH_REGISTER: return await this.#pushRegister(frame.p)
982
+ case METHOD_USAGE_SESSION: return await this.#usageSession(frame.p)
983
+ case METHOD_USAGE_BALANCE: return await this.#usageBalance(frame.p)
984
+ case METHOD_USAGE_STATS: return await this.#usageStats(frame.p)
751
985
  case METHOD_JOBS_LIST: return await this.#jobsList(frame.p)
752
986
  case METHOD_PRESETS_LIST: return await this.#presetsList()
753
987
  case METHOD_SESSION_CREATE: return await this.#sessionCreate(frame.p)
754
988
  case METHOD_SESSION_FORK: return await this.#sessionFork(frame.p)
989
+ case METHOD_SESSION_COMMANDS: return await this.#sessionCommands(frame.p)
990
+ case METHOD_SESSION_COMMAND: return await this.#sessionCommand(frame.p)
991
+ case METHOD_SQUADS_STATE: return await this.#squadsState()
992
+ case METHOD_SQUADS_LIST: return await this.#squadsProjection('squads')
993
+ case METHOD_SQUADS_RUNS: return await this.#squadsProjection('runs')
994
+ case METHOD_SQUADS_RUN_MEMBER: return await this.#squadsRunMember(frame.p)
995
+ case METHOD_SQUADS_RUN_SQUAD: return await this.#squadsRunSquad(frame.p)
996
+ case METHOD_WORKSPACE_LIST: return this.#workspaceList()
997
+ case METHOD_SESSION_RENAME: return await this.#sessionRename(frame.p)
998
+ case METHOD_SESSION_PIN: return await this.#sessionSetWrite(METHOD_SESSION_PIN, 'pinSession', frame.p)
999
+ case METHOD_SESSION_UNPIN: return await this.#sessionSetWrite(METHOD_SESSION_UNPIN, 'unpinSession', frame.p)
1000
+ case METHOD_SESSION_ARCHIVE: return await this.#sessionArchive(frame.p)
1001
+ case METHOD_SESSION_UNARCHIVE: return await this.#sessionSetWrite(METHOD_SESSION_UNARCHIVE, 'unarchiveSession', frame.p)
755
1002
  default: return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
756
1003
  }
757
1004
  }
@@ -786,7 +1033,29 @@ export class BridgeConnection {
786
1033
  }
787
1034
  }
788
1035
 
789
- #hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome { const proto = payload.proto
1036
+ /**
1037
+ * The capabilities this greeting advertises: the protocol's own, and every
1038
+ * capability a mounted extension currently requires a client to declare.
1039
+ *
1040
+ * Computed per greeting rather than held once, because a plugin may register
1041
+ * its table after this bridge was built — a name frozen at build time would
1042
+ * leave that surface invisible to every phone that ever connects. The
1043
+ * protocol's own names come first and keep their order, so a bridge with no
1044
+ * extension mounted advertises exactly the list it always did; extension
1045
+ * names follow in their registry's order. A name both halves know is listed
1046
+ * once.
1047
+ * @returns the served capabilities, one name each.
1048
+ */
1049
+ #servedCapabilities(): string[] {
1050
+ const capabilities = [...SERVED_CAPABILITIES]
1051
+ for (const capability of this.#options.extensions?.capabilities() ?? []) {
1052
+ if (!capabilities.includes(capability)) capabilities.push(capability)
1053
+ }
1054
+ return capabilities
1055
+ }
1056
+
1057
+ #hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1058
+ const proto = payload.proto
790
1059
  if (proto !== PROTO) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol ${PROTO}`)
791
1060
  this.#capabilities = capabilitiesOf(payload.cap)
792
1061
  // The frame form is decided where the frame is written, so the carrier is
@@ -801,7 +1070,7 @@ export class BridgeConnection {
801
1070
  proto: PROTO,
802
1071
  minor: MINOR,
803
1072
  server: SERVER_ID,
804
- capabilities: [...SERVED_CAPABILITIES],
1073
+ capabilities: this.#servedCapabilities(),
805
1074
  resume: 'snapshot',
806
1075
  auth: this.paired ? 'paired' : 'unpaired',
807
1076
  },
@@ -928,10 +1197,13 @@ export class BridgeConnection {
928
1197
  const parentSessionId = optionalText(item.parentSessionId)
929
1198
  sessions.push({
930
1199
  id: item.sessionId,
931
- // The roster itself carries no title: `SessionSummary` has none. The
932
- // connection fills in whatever `session.titles` already resolved for
933
- // this id and never looks one up here, so listing stays one call.
934
- title: this.#options.sessionMeta.cachedTitle(item.sessionId) ?? '',
1200
+ // The row's own title. `SessionSummary` has no top-level `title`, but the
1201
+ // projection block beside it does — `projections.values.title` — and the
1202
+ // host answers that synchronously for a cold session too, which is the
1203
+ // field its own desktop list renders. The live-title cache is the
1204
+ // fallback for a row whose projection carries none, and no lookup is
1205
+ // spent here, so listing stays one call either way.
1206
+ title: projectedTitleOf(item) ?? this.#options.sessionMeta.cachedTitle(item.sessionId) ?? '',
935
1207
  updatedAt: typeof item.updatedAt === 'number' ? item.updatedAt : 0,
936
1208
  agentRunning: item.running === true,
937
1209
  ...(cwd === undefined ? {} : { cwd }),
@@ -945,6 +1217,15 @@ export class BridgeConnection {
945
1217
  // child's durable parent is on its own row, so a client that lists before it
946
1218
  // opens a session never costs a second read to address that session.
947
1219
  this.#rememberLineage(sessions)
1220
+ // The workspace short name a notification carries is picked up from a roster
1221
+ // this bridge just served, because the alternative is a gateway read on the
1222
+ // notification path. Best effort by construction: a session never listed
1223
+ // simply produces a payload without `w`.
1224
+ this.#options.push?.noteSessions(sessions)
1225
+ // The same roster answers how many sessions are running, which is what a card
1226
+ // reports; the call returns before any delivery starts, so listing pays no
1227
+ // APNs round trip.
1228
+ this.#options.liveActivity?.noteRoster(sessions)
948
1229
  return { ok: true, rows: sessions }
949
1230
  }
950
1231
 
@@ -1543,6 +1824,282 @@ export class BridgeConnection {
1543
1824
  return call.ok ? { ok: true, r: call.value } : call
1544
1825
  }
1545
1826
 
1827
+ /**
1828
+ * Answer `squads.state`: the host's squad domain as this deployment publishes
1829
+ * it.
1830
+ *
1831
+ * The read is the `dsh-agents` plugin's own `{teams, runs, host, presets?}`
1832
+ * document — reached over loopback, or read out of its ledger when loopback
1833
+ * cannot answer — mapped onto the frozen body: a definition keeps its identity,
1834
+ * its pins and its members, a run names the squad it belongs to, and both lose
1835
+ * the bookkeeping fields this channel does not publish. A body this build cannot
1836
+ * read is refused rather than repaired, and a host that serves no domain answers
1837
+ * `squads-unavailable` instead of an empty board.
1838
+ */
1839
+ async #squadsState(): Promise<DispatchOutcome> {
1840
+ const read = await this.#squadState()
1841
+ return read.ok ? { ok: true, r: read.state } : read
1842
+ }
1843
+
1844
+ /**
1845
+ * Answer `squads.list` or `squads.runs`: one half of the same read.
1846
+ *
1847
+ * Both commands read the domain once, exactly as `squads.state` does, and
1848
+ * publish the half they are named after. There is no second source: a squad
1849
+ * listing and a run listing can never disagree about a definition a launch
1850
+ * touched, because both are cut from one answer.
1851
+ * @param half - the body key this command publishes.
1852
+ */
1853
+ async #squadsProjection(half: 'squads' | 'runs'): Promise<DispatchOutcome> {
1854
+ const read = await this.#squadState()
1855
+ if (!read.ok) return read
1856
+ return { ok: true, r: { [half]: read.state[half] } }
1857
+ }
1858
+
1859
+ /**
1860
+ * Read the squad domain once.
1861
+ *
1862
+ * The transport answers the plugin's rows unread and this bridge maps them
1863
+ * here, so the ledger fallback and the loopback route are the same answer as far
1864
+ * as a client can tell.
1865
+ */
1866
+ async #squadState(): Promise<{ readonly ok: true; readonly state: SquadsState } | CallFailure> {
1867
+ const transport = this.#options.squads
1868
+ if (transport === undefined) {
1869
+ return refusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain')
1870
+ }
1871
+ try {
1872
+ return { ok: true, state: squadsStateOf(await transport.state()) }
1873
+ } catch (error) {
1874
+ return this.#squadFailure(error)
1875
+ }
1876
+ }
1877
+
1878
+ /**
1879
+ * Answer `squads.runMember`: launch one member session.
1880
+ *
1881
+ * Only the two names the command needs are read here. Which preset, permission,
1882
+ * model and brief that session is composed from is the definition's own, and
1883
+ * whether this host can launch at all is the transport's: an unknown squad or
1884
+ * member, an unusable preset and a squad that pins no workspace all cross as the
1885
+ * plugin's own code.
1886
+ * @param payload - `{squadId, memberId, firstMessage?}`.
1887
+ */
1888
+ async #squadsRunMember(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1889
+ const transport = this.#options.squads
1890
+ if (transport === undefined) {
1891
+ return refusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain')
1892
+ }
1893
+ const request = parseSquadMemberRun(payload)
1894
+ if (request === undefined) return refusal(CODE_INVALID_ARGS, 'squads.runMember requires squadId and memberId')
1895
+ try {
1896
+ return { ok: true, r: { run: squadRunOf(await transport.runMember(request)) } }
1897
+ } catch (error) {
1898
+ return this.#squadFailure(error)
1899
+ }
1900
+ }
1901
+
1902
+ /**
1903
+ * Answer `squads.runSquad`: launch the Lead session of one whole squad.
1904
+ *
1905
+ * The goal travels as the plugin's own `goal` — it becomes part of the Lead's
1906
+ * system-prompt context rather than its first user message — so nothing about
1907
+ * what the squad must achieve is modelled here.
1908
+ * @param payload - `{squadId, goal?}`.
1909
+ */
1910
+ async #squadsRunSquad(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1911
+ const transport = this.#options.squads
1912
+ if (transport === undefined) {
1913
+ return refusal(CODE_SQUADS_UNAVAILABLE, 'this host serves no dsh-agents squad domain')
1914
+ }
1915
+ const request = parseSquadRun(payload)
1916
+ if (request === undefined) return refusal(CODE_INVALID_ARGS, 'squads.runSquad requires squadId')
1917
+ try {
1918
+ return { ok: true, r: { run: squadRunOf(await transport.runSquad(request)) } }
1919
+ } catch (error) {
1920
+ return this.#squadFailure(error)
1921
+ }
1922
+ }
1923
+
1924
+ /**
1925
+ * Convert whatever the squad transport raised into a refusal that names a code.
1926
+ *
1927
+ * A refusal the transport built keeps its own code — that is how a domain
1928
+ * refusal and this bridge's two capability codes stay distinguishable. Anything
1929
+ * else is a host failure this channel could not attribute, and it is refused as
1930
+ * an unreachable domain rather than as an internal error: no squad answer was
1931
+ * read, which is exactly what `squads-unavailable` says.
1932
+ */
1933
+ #squadFailure(error: unknown): CallFailure {
1934
+ if (isSquadRefusal(error)) return refusal(error.code, error.message)
1935
+ this.#options.log(`squad domain read failed: ${failureText(error)}`)
1936
+ return refusal(CODE_SQUADS_UNAVAILABLE, failureText(error))
1937
+ }
1938
+
1939
+ /**
1940
+ * Answer `workspace.list`: the host's workspaces and its two global sets.
1941
+ *
1942
+ * A pure in-process read: `list()` answers a fresh array in registry order and
1943
+ * both sets are synchronous getters, so nothing here awaits, subscribes or
1944
+ * touches persistence, and a write this bridge forwarded a moment ago is
1945
+ * visible to the very next call. Nothing is sorted — the registry's own order
1946
+ * is the display order — and no row carries a workspace's `sessionIds`: the
1947
+ * roster already carries every session's `cwd`, a client groups for itself, and
1948
+ * that account would make one frame grow with the session count.
1949
+ *
1950
+ * A host that composes no registry is refused rather than answered with an
1951
+ * empty list: an empty list says "this host has no workspaces", which is a
1952
+ * different sentence from "there is nothing here to ask".
1953
+ */
1954
+ #workspaceList(): DispatchOutcome {
1955
+ const listed = this.#options.sessionMeta.workspaceList()
1956
+ if (listed === undefined) return refusal(CODE_INTERNAL, 'this host composes no workspaceRegistry service')
1957
+ return { ok: true, r: listed }
1958
+ }
1959
+
1960
+ /**
1961
+ * Answer `session.rename`: forward one `SessionRenameRequest` and hand back
1962
+ * the host's own `SessionRenameValue`.
1963
+ *
1964
+ * The write goes through the gateway — `session/rename`, never the title
1965
+ * service this process holds — because that endpoint restores a cold session
1966
+ * before it writes, so a client needs no resume path of its own. The title is
1967
+ * required and is text: an empty string is not a name anyone could have meant,
1968
+ * and it is refused here instead of being written. Everything after that is
1969
+ * the host's: the normalized title, the durable seq that committed it, and a
1970
+ * refusal such as `session/not-found` cross verbatim.
1971
+ * @param payload - `{sessionId, title}`.
1972
+ */
1973
+ async #sessionRename(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1974
+ const sessionId = stringArg(payload, 'sessionId')
1975
+ const title = stringArg(payload, 'title')
1976
+ if (sessionId === undefined || title === undefined) {
1977
+ return refusal(CODE_INVALID_ARGS, 'session.rename requires sessionId and title')
1978
+ }
1979
+ const call = await this.#unary('session', 'rename', { sessionId, title })
1980
+ return call.ok ? { ok: true, r: call.value } : call
1981
+ }
1982
+
1983
+ /**
1984
+ * Forward one registry set mutation and answer `{ok:true}`.
1985
+ *
1986
+ * Three of the five session-admin writes are the same call under a different
1987
+ * endpoint name, so they share one body: `{sessionId}` in, one decided answer
1988
+ * out. Nothing is branched on — pin, unpin and unarchive take no second
1989
+ * argument to branch on — and the host's own set answer
1990
+ * (`WorkspacePinValue` / `WorkspaceArchiveValue`) is deliberately not
1991
+ * republished: a client that wants the new set reads `workspace.list`, the one
1992
+ * read that serves both. An archive's optional `stopActivity` is
1993
+ * `#sessionArchive`'s own concern.
1994
+ * @param method - the protocol method being answered, named in the refusal.
1995
+ * @param endpoint - the `workspace` registry method behind it.
1996
+ * @param payload - `{sessionId}`.
1997
+ */
1998
+ async #sessionSetWrite(method: string, endpoint: string, payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1999
+ const sessionId = stringArg(payload, 'sessionId')
2000
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, `${method} requires sessionId`)
2001
+ const call = await this.#unary('workspace', endpoint, { sessionId })
2002
+ return call.ok ? { ok: true, r: { ok: true } } : call
2003
+ }
2004
+
2005
+ /**
2006
+ * Answer `session.archive`, whose request may ask the host to stop the
2007
+ * session's running work first.
2008
+ *
2009
+ * `stopActivity` is the host's own choice and only a boolean may cross: sent
2010
+ * without it, a session that is still running is refused by the host as
2011
+ * `workspace/session-active`; sent as `true`, the archive is written and that
2012
+ * work is stopped. Archiving is a session-level act — it never touches the
2013
+ * workspace the session belongs to — and the archived session keeps its slot,
2014
+ * so `session.unarchive` puts it back where it was. None of that is modelled
2015
+ * here.
2016
+ * @param payload - `{sessionId, stopActivity?}`.
2017
+ */
2018
+ async #sessionArchive(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2019
+ const sessionId = stringArg(payload, 'sessionId')
2020
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.archive requires sessionId')
2021
+ const stopActivity = payload.stopActivity
2022
+ if (stopActivity !== undefined && typeof stopActivity !== 'boolean') {
2023
+ return refusal(CODE_INVALID_ARGS, 'session.archive stopActivity must be a boolean when present')
2024
+ }
2025
+ const call = await this.#unary('workspace', 'archiveSession', { sessionId, ...(stopActivity === undefined ? {} : { stopActivity }) })
2026
+ return call.ok ? { ok: true, r: { ok: true } } : call
2027
+ }
2028
+
2029
+ /**
2030
+ * Answer `session.commands`: one session's slash commands and skills, in one
2031
+ * directory.
2032
+ *
2033
+ * Both catalogs are read live and neither is modelled here: `commands/list`
2034
+ * is the host registry's own effective view for this Agent — a command
2035
+ * registered through an Agent-scoped child shadows the global one — and
2036
+ * `skills/list` is the catalog this session's cwd and preset select, so what
2037
+ * a phone lists is what the desktop composer would offer that same session. A
2038
+ * row crosses with the name and the summary the host publishes for it, plus
2039
+ * the whole draft line that invokes it, separator space included.
2040
+ *
2041
+ * Nothing is paged, re-sorted or cached: every command first, every skill
2042
+ * after, each in the host's own order, and the next call reads both again.
2043
+ * @param payload - `{sessionId}`.
2044
+ */
2045
+ async #sessionCommands(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2046
+ const sessionId = stringArg(payload, 'sessionId')
2047
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.commands requires sessionId')
2048
+ const commands = await this.#unary('commands', 'list', { agentId: sessionId })
2049
+ if (!commands.ok) return this.#commandsFailure('commands', 'list', commands)
2050
+ if (!Array.isArray(commands.value)) return refusal(CODE_INTERNAL, 'commands/list returned no command directory')
2051
+ const skills = await this.#unary('skills', 'list', { sessionId })
2052
+ if (!skills.ok) return this.#commandsFailure('skills', 'list', skills)
2053
+ if (!isRecord(skills.value) || !Array.isArray(skills.value.skills)) {
2054
+ return refusal(CODE_INTERNAL, 'skills/list returned no skill catalog')
2055
+ }
2056
+ return { ok: true, r: { sessionId, items: commandItems(commands.value, skills.value.skills) } }
2057
+ }
2058
+
2059
+ /**
2060
+ * Answer `session.command`: run one draft line on the host and report whether
2061
+ * the host resolved it.
2062
+ *
2063
+ * The line crosses exactly as the client wrote it, because what a line means
2064
+ * belongs to the host: its parser decides whether the text is a slash command
2065
+ * at all, and its registry decides whether that name is one this Agent has. A
2066
+ * line the host resolves runs — this method does not pre-judge a command,
2067
+ * replay one, or refuse a line it does not recognise — and the answer is then
2068
+ * `matched: true`. A line the host resolves to nothing (no leading slash, an
2069
+ * unknown name, or a skill's `/name` gesture, which is prompt text rather than
2070
+ * a registry entry) answers `matched: false`, and nothing ran.
2071
+ *
2072
+ * A plain invocation carries no attachments: a draft line has none, the
2073
+ * endpoint requires the key, so an empty array is what crosses.
2074
+ * @param payload - `{sessionId, line}`.
2075
+ */
2076
+ async #sessionCommand(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2077
+ const sessionId = stringArg(payload, 'sessionId')
2078
+ const line = stringArg(payload, 'line')
2079
+ if (sessionId === undefined || line === undefined) {
2080
+ return refusal(CODE_INVALID_ARGS, 'session.command requires sessionId and line')
2081
+ }
2082
+ const call = await this.#unary('commands', 'execute', { agentId: sessionId, line, submittedAttachments: [] })
2083
+ if (!call.ok) return this.#commandsFailure('commands', 'execute', call)
2084
+ return { ok: true, r: { matched: call.value !== undefined } }
2085
+ }
2086
+
2087
+ /**
2088
+ * Re-answer one command-channel failure.
2089
+ *
2090
+ * An endpoint this host does not serve at all is this bridge's own
2091
+ * `commands-unavailable`, so a phone stops offering the directory instead of
2092
+ * showing a call that fails every time; a call the host refused, and a channel
2093
+ * that is merely still activating, cross with the failure's own code and text.
2094
+ * @param namespace - the Remote namespace that failed.
2095
+ * @param method - the endpoint that failed.
2096
+ * @param failure - the refusal `#unary` produced.
2097
+ */
2098
+ #commandsFailure(namespace: string, method: string, failure: CallFailure): CallFailure {
2099
+ if (!commandsUnavailable(failure.code)) return failure
2100
+ return refusal(CODE_COMMANDS_UNAVAILABLE, `this host serves no ${namespace}/${method} endpoint`)
2101
+ }
2102
+
1546
2103
  #approvalResolve(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1547
2104
  const id = stringArg(payload, 'id')
1548
2105
  const decision = payload.decision
@@ -1575,6 +2132,221 @@ export class BridgeConnection {
1575
2132
  return reply.ok ? { ok: true, r: { ok: true } } : refusal(reply.code, reply.msg)
1576
2133
  }
1577
2134
 
2135
+ /**
2136
+ * Answer one `question.list`: the questions this bridge is still holding.
2137
+ *
2138
+ * A pure read — it claims nothing, moves no deadline, triggers no `continued`
2139
+ * and writes no host state — because its whole purpose is to let a client that
2140
+ * was disconnected reconcile cards it already holds: a question missing from
2141
+ * this list is one nobody can answer any more, since the bridge withdraws every
2142
+ * claim when the last paired device leaves and the phone is not there to hear
2143
+ * it.
2144
+ *
2145
+ * Only a COMPLETE list may retire a card on the client, so a registry this
2146
+ * bridge cannot read answers `question-list-unavailable` rather than an empty
2147
+ * list: an unreadable set is not an empty one.
2148
+ * @param payload - must be the empty object: the held set is global, not scoped.
2149
+ */
2150
+ #questionList(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
2151
+ if (Object.keys(payload).length > 0) {
2152
+ return refusal(CODE_INVALID_ARGS, 'question.list takes no arguments')
2153
+ }
2154
+ let questions: readonly ListedQuestion[]
2155
+ try {
2156
+ questions = this.#options.questions.listed()
2157
+ } catch (error) {
2158
+ this.#options.log(`question.list could not read the held questions: ${failureText(error)}`)
2159
+ return refusal(CODE_QUESTION_LIST_UNAVAILABLE, 'this bridge could not read the questions it is holding')
2160
+ }
2161
+ const answer: QuestionListPayload = { questions, complete: true }
2162
+ return { ok: true, r: answer }
2163
+ }
2164
+
2165
+ /**
2166
+ * Answer one `ui.event`: the first action a user took inside a presented page
2167
+ * (§35.3).
2168
+ *
2169
+ * The event is carried and never interpreted — `type` is the presenter's own
2170
+ * closed set, so this bridge does not validate its value, refuse an unknown one
2171
+ * or rewrite it. A card this bridge never claimed, or one that was settled
2172
+ * elsewhere, is refused `ui-unknown`; a card whose own first event already
2173
+ * settled it is refused `ui-settled`, because a repeated tap and a nonexistent
2174
+ * card are two different answers. The payload is measured here rather than on the
2175
+ * client: a refusal on that side would leave the agent waiting for a card that
2176
+ * will never settle (§35.2's rule, one channel over).
2177
+ * @param payload - `{sessionId, callId, event:{type, payload?}}`.
2178
+ */
2179
+ #uiEvent(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
2180
+ const sessionId = stringArg(payload, 'sessionId')
2181
+ const callId = stringArg(payload, 'callId')
2182
+ const event = uiEventOf(payload.event)
2183
+ if (sessionId === undefined || callId === undefined || event === undefined) {
2184
+ return refusal(CODE_INVALID_ARGS, 'ui.event requires sessionId, callId and event of {type, payload?}')
2185
+ }
2186
+ if (!uiEventFits(event)) return refusal(CODE_INVALID_ARGS, 'ui.event payload is over the 8 KiB cap')
2187
+ const reply = this.#options.ui.settle(sessionId, callId, event)
2188
+ return reply.ok ? { ok: true, r: { ok: true } } : refusal(reply.code, reply.msg)
2189
+ }
2190
+
2191
+ /**
2192
+ * Answer one `ui.list`: the cards this bridge is still holding (§35.4).
2193
+ *
2194
+ * A pure read — it claims nothing, moves no deadline, triggers no settlement and
2195
+ * writes no host state — because its whole purpose is to let a client that was
2196
+ * disconnected reconcile the cards it already holds. `settled` never appears in
2197
+ * it: the list's definition is "still held", and a settled card is a notice the
2198
+ * host already sent, not a row.
2199
+ *
2200
+ * Only a COMPLETE list may retire a card on the client, so a registry this bridge
2201
+ * cannot read answers `ui-list-unavailable` rather than an empty list: an
2202
+ * unreadable set is not an empty one.
2203
+ * @param payload - must be the empty object: the held set is global, not scoped.
2204
+ */
2205
+ #uiList(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
2206
+ if (Object.keys(payload).length > 0) {
2207
+ return refusal(CODE_INVALID_ARGS, 'ui.list takes no arguments')
2208
+ }
2209
+ let cards: readonly ListedCard[]
2210
+ try {
2211
+ cards = this.#options.ui.listed()
2212
+ } catch (error) {
2213
+ this.#options.log(`ui.list could not read the held cards: ${failureText(error)}`)
2214
+ return refusal(CODE_UI_LIST_UNAVAILABLE, 'this bridge could not read the cards it is holding')
2215
+ }
2216
+ const answer: UiListPayload = { cards, complete: true }
2217
+ return { ok: true, r: answer }
2218
+ }
2219
+
2220
+ /**
2221
+ * The body of `push.register` (protocol §28.3).
2222
+ *
2223
+ * A write, and the only one this channel has: the device's APNs registration
2224
+ * lands in its own row of the roster file, beside the identity it already
2225
+ * proved, so revoking the device revokes its notifications with it and no
2226
+ * second identity or second table exists.
2227
+ *
2228
+ * The answer is `{ok:true}` and nothing else. There is deliberately no echo of
2229
+ * the token and no "ready" flag: this bridge cannot know whether APNs will
2230
+ * accept the token, and a field claiming it did would be a lie a client might
2231
+ * render. A bridge with no signing key answers identically — a client has no
2232
+ * second code path for that difference.
2233
+ * @param payload - `{deviceToken, environment, bundle, liveActivityTokens?, locale?}`.
2234
+ */
2235
+ async #pushRegister(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2236
+ const deviceToken = payload.deviceToken
2237
+ const environment = payload.environment
2238
+ const bundle = payload.bundle
2239
+ if (typeof deviceToken !== 'string' || deviceToken === '' || !/^[0-9a-fA-F]+$/.test(deviceToken)) {
2240
+ return refusal(CODE_INVALID_ARGS, 'deviceToken must be the hex string APNs handed the app')
2241
+ }
2242
+ if (environment !== 'sandbox' && environment !== 'production') {
2243
+ return refusal(CODE_INVALID_ARGS, 'environment must be "sandbox" or "production"')
2244
+ }
2245
+ if (typeof bundle !== 'string' || bundle === '') return refusal(CODE_INVALID_ARGS, 'bundle must be a non-empty string')
2246
+ const locale = optionalText(payload.locale)
2247
+ let liveActivityTokens: readonly PushLiveActivityToken[] | undefined
2248
+ if (payload.liveActivityTokens !== undefined) {
2249
+ const raw = payload.liveActivityTokens
2250
+ if (!Array.isArray(raw)) return refusal(CODE_INVALID_ARGS, 'liveActivityTokens must be an array')
2251
+ const collected: PushLiveActivityToken[] = []
2252
+ for (const entry of raw) {
2253
+ if (!isRecord(entry)) return refusal(CODE_INVALID_ARGS, 'each liveActivityTokens entry needs an activityId and a token')
2254
+ const activityId = entry.activityId
2255
+ const token = entry.token
2256
+ if (typeof activityId !== 'string' || activityId === '' || typeof token !== 'string' || token === '') {
2257
+ return refusal(CODE_INVALID_ARGS, 'each liveActivityTokens entry needs an activityId and a token')
2258
+ }
2259
+ // §29.9: a card names the session it belongs to. The key is optional —
2260
+ // a client that omits it is registered exactly as before — but a value
2261
+ // that is present has to be a session id, because a card carrying a
2262
+ // malformed address would be pushed to nobody while looking registered.
2263
+ const sessionId = entry.sessionId
2264
+ if (sessionId !== undefined && (typeof sessionId !== 'string' || sessionId === '')) {
2265
+ return refusal(CODE_INVALID_ARGS, 'a liveActivityTokens sessionId must be a non-empty string')
2266
+ }
2267
+ collected.push({ activityId, token, ...(sessionId === undefined ? {} : { sessionId }) })
2268
+ }
2269
+ liveActivityTokens = collected
2270
+ }
2271
+ const deviceId = this.#deviceId
2272
+ if (deviceId === undefined) return refusal(CODE_UNPAIRED, 'this connection is not paired')
2273
+ const registration: PushRegistration = {
2274
+ deviceToken,
2275
+ environment: environment as PushEnvironment,
2276
+ bundle,
2277
+ ...(locale === undefined ? {} : { locale }),
2278
+ ...(liveActivityTokens === undefined ? {} : { liveActivityTokens }),
2279
+ registeredAt: this.#options.now(),
2280
+ }
2281
+ try {
2282
+ const stored = await this.#options.roster.registerPush(deviceId, registration)
2283
+ if (!stored) return refusal(CODE_INTERNAL, 'this connection names no paired device')
2284
+ // The roster is the only place a standing watcher is armed from: the
2285
+ // session a card names gets a follow stream of this bridge's own, and it
2286
+ // keeps it until the last token for that session is gone.
2287
+ try {
2288
+ this.#options.onPushRegistered?.()
2289
+ } catch (error) {
2290
+ this.#options.log(`standing watchers could not be reconciled: ${failureText(error)}`)
2291
+ }
2292
+ } catch (error) {
2293
+ // Registration failing has to reach the client: it decides whether to
2294
+ // retry, and a token that never reached the disk is a device that will
2295
+ // never be notified.
2296
+ return refusal(CODE_INTERNAL, `could not write the device roster: ${failureText(error)}`)
2297
+ }
2298
+ return { ok: true, r: { ok: true } }
2299
+ }
2300
+
2301
+ /**
2302
+ * 答一次 `usage.session`:一条会话的上下文窗口与下一次请求的组成估算。
2303
+ *
2304
+ * 两个读数各有自己的来源,也各有自己的缺席方式:`contextWindow` 只在宿主
2305
+ * 广播过 `request/context` 时出现,`composition` 只在观察到任何原文时出现,
2306
+ * 两项都没有就是空对象。会话本身不存在是另一种情况,回的是
2307
+ * `unknown-session`,而不是一个读不到任何东西的空对象;而「存在」由活会话
2308
+ * 存储、本进程观察到的事件与宿主名册三处中任意一处证明(见 `core/usage.ts`)。
2309
+ * @param payload - `{sessionId}`。
2310
+ */
2311
+ async #usageSession(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2312
+ const sessionId = stringArg(payload, 'sessionId')
2313
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'usage.session requires sessionId')
2314
+ const answer = await this.#options.usage.session(sessionId)
2315
+ if (answer === undefined) return refusal(CODE_UNKNOWN_SESSION, `session ${sessionId} does not exist on this host`)
2316
+ return { ok: true, r: answer }
2317
+ }
2318
+
2319
+ /**
2320
+ * 答一次 `usage.balance`:某条 provider 路由背后账户的余额。
2321
+ *
2322
+ * 判定与缓存全在 `core/usage.ts`:不是官方路由、不指向官方 origin、凭据拿
2323
+ * 不到,都不发上游请求,各自的理由按 `unsupported` 的三种取值过线。这里
2324
+ * 只转发,因为余额是账户的事实,本连接既不改写也不补默认值。
2325
+ * @param payload - `{provider}`。
2326
+ */
2327
+ async #usageBalance(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2328
+ const provider = stringArg(payload, 'provider')
2329
+ if (provider === undefined) return refusal(CODE_INVALID_ARGS, 'usage.balance requires provider')
2330
+ return { ok: true, r: await this.#options.usage.balance(provider) }
2331
+ }
2332
+
2333
+ /**
2334
+ * 答一次 `usage.stats`:宿主自己那份按天记的 token 台账的聚合。
2335
+ *
2336
+ * `days` 省略按 14,超出 60 按 60 收——收窗口的是 `core/usage-stats.ts`,不是
2337
+ * 协议:客户端给的天数只是「想看多深」,不该被当成一次分配。这里只拒绝根本
2338
+ * 不是数字的那种值,其余一律转发,包括读不到时那份 `unsupported`,
2339
+ * 因为「这台 Mac 没挂那个插件」不是一次失败。
2340
+ * @param payload - `{days?}`。
2341
+ */
2342
+ async #usageStats(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
2343
+ const days = payload.days
2344
+ if (days !== undefined && (typeof days !== 'number' || !Number.isFinite(days))) {
2345
+ return refusal(CODE_INVALID_ARGS, 'usage.stats requires days to be a number')
2346
+ }
2347
+ return { ok: true, r: await this.#options.usage.stats(days) }
2348
+ }
2349
+
1578
2350
  /**
1579
2351
  * Answer one `jobs.list` and start watching that scope.
1580
2352
  *
@@ -1809,6 +2581,15 @@ export class BridgeConnection {
1809
2581
  const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages, memory)
1810
2582
  if (delta === undefined) continue
1811
2583
  this.#emit(TOPIC_SESSION_DELTA, { sessionId: subscription.sessionId, ...delta })
2584
+ // One turn ended, so a phone that is not holding this socket may want to
2585
+ // know. The call returns before anything is sent and swallows its own
2586
+ // failures: the frame above is already gone, and a notification is not
2587
+ // worth a delayed or aborted stream (protocol §28.5).
2588
+ if (delta.kind === 'turn-end') this.#announceTurnEnd(subscription.sessionId, delta.reason)
2589
+ // Only an increment that proves this session's own work proves a new turn; a
2590
+ // settled child, a usage count and a catalog change all arrive here without
2591
+ // meaning the user prompted again.
2592
+ else if (isTurnStartDelta(delta)) this.#options.turnEndQuiet?.noteTurnStarted(subscription.sessionId)
1812
2593
  }
1813
2594
  } catch (error) {
1814
2595
  if (!subscription.controller.signal.aborted) {
@@ -1819,6 +2600,24 @@ export class BridgeConnection {
1819
2600
  }
1820
2601
  }
1821
2602
 
2603
+ /**
2604
+ * Hand one finished turn to the channel that announces it.
2605
+ *
2606
+ * The gate holds it until the session is quiet (§28, §29); a connection built
2607
+ * without one has no host answer to wait for and reports at the frame.
2608
+ * @param sessionId - the session the turn belonged to.
2609
+ * @param reason - the host's own reason for ending it.
2610
+ */
2611
+ #announceTurnEnd(sessionId: string, reason: string): void {
2612
+ const gate = this.#options.turnEndQuiet
2613
+ if (gate !== undefined) {
2614
+ gate.noteTurnEnd(sessionId, reason)
2615
+ return
2616
+ }
2617
+ this.#options.push?.notify(pushEventOfTurnEnd(reason), sessionId)
2618
+ this.#options.liveActivity?.noteTurnEnd(sessionId, reason)
2619
+ }
2620
+
1822
2621
  /** Await a subscription's opening frame under a bounded wait. */
1823
2622
  async #awaitOpening(subscription: Subscription): Promise<Opening> {
1824
2623
  let timer: NodeJS.Timeout | undefined