@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.
Files changed (81) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +277 -2
  4. package/README.zh.md +276 -0
  5. package/cordis.patch.yml +17 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +1830 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +5789 -0
  10. package/lib/types/client/PairEntry.d.ts +16 -0
  11. package/lib/types/client/PairPanel.d.ts +55 -0
  12. package/lib/types/client/icons.d.ts +18 -0
  13. package/lib/types/client/index.d.ts +35 -0
  14. package/lib/types/client/locales.d.ts +42 -0
  15. package/lib/types/client/pair-token.d.ts +73 -0
  16. package/lib/types/client/semantic.d.ts +28 -0
  17. package/lib/types/core/approvals.d.ts +99 -0
  18. package/lib/types/core/connection.d.ts +170 -0
  19. package/lib/types/core/crypto.d.ts +48 -0
  20. package/lib/types/core/delta.d.ts +101 -0
  21. package/lib/types/core/devices.d.ts +72 -0
  22. package/lib/types/core/dsh-frames.d.ts +332 -0
  23. package/lib/types/core/envelope.d.ts +132 -0
  24. package/lib/types/core/extension.d.ts +144 -0
  25. package/lib/types/core/gateway-errors.d.ts +49 -0
  26. package/lib/types/core/hub.d.ts +127 -0
  27. package/lib/types/core/jobs.d.ts +204 -0
  28. package/lib/types/core/loopback.d.ts +35 -0
  29. package/lib/types/core/owner-peer.d.ts +49 -0
  30. package/lib/types/core/pairing.d.ts +61 -0
  31. package/lib/types/core/protocol.d.ts +319 -0
  32. package/lib/types/core/questions.d.ts +294 -0
  33. package/lib/types/core/session-meta.d.ts +105 -0
  34. package/lib/types/core/session-permissions.d.ts +134 -0
  35. package/lib/types/core/wire.d.ts +115 -0
  36. package/lib/types/core/ws-frames.d.ts +72 -0
  37. package/lib/types/host/dsh-home.d.ts +16 -0
  38. package/lib/types/host/pair-origin.d.ts +44 -0
  39. package/lib/types/host/routes.d.ts +27 -0
  40. package/lib/types/host/websocket.d.ts +111 -0
  41. package/lib/types/index.d.ts +55 -0
  42. package/lib/types/mount-once.d.ts +55 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +93 -3
  47. package/src/client/PairEntry.tsx +151 -0
  48. package/src/client/PairPanel.tsx +183 -0
  49. package/src/client/icons.tsx +72 -0
  50. package/src/client/index.ts +81 -0
  51. package/src/client/locales.ts +72 -0
  52. package/src/client/pair-token.ts +104 -0
  53. package/src/client/panel.module.css +344 -0
  54. package/src/client/semantic.ts +37 -0
  55. package/src/core/approvals.ts +173 -0
  56. package/src/core/connection.ts +1906 -0
  57. package/src/core/crypto.ts +113 -0
  58. package/src/core/delta.ts +204 -0
  59. package/src/core/devices.ts +209 -0
  60. package/src/core/dsh-frames.ts +843 -0
  61. package/src/core/envelope.ts +219 -0
  62. package/src/core/extension.ts +197 -0
  63. package/src/core/gateway-errors.ts +92 -0
  64. package/src/core/hub.ts +310 -0
  65. package/src/core/jobs.ts +372 -0
  66. package/src/core/loopback.ts +60 -0
  67. package/src/core/owner-peer.ts +70 -0
  68. package/src/core/pairing.ts +113 -0
  69. package/src/core/protocol.ts +381 -0
  70. package/src/core/questions.ts +630 -0
  71. package/src/core/session-meta.ts +176 -0
  72. package/src/core/session-permissions.ts +266 -0
  73. package/src/core/wire.ts +159 -0
  74. package/src/core/ws-frames.ts +139 -0
  75. package/src/css-modules.d.ts +6 -0
  76. package/src/host/dsh-home.ts +42 -0
  77. package/src/host/pair-origin.ts +77 -0
  78. package/src/host/routes.ts +85 -0
  79. package/src/host/websocket.ts +359 -0
  80. package/src/index.ts +257 -0
  81. package/src/mount-once.ts +142 -0
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Process-local session metadata the roster rows carry beyond the gateway's own
3
+ * summary, and the cache that keeps a phone's title lookups off the title
4
+ * service's hot path.
5
+ *
6
+ * Every read here goes to a service of the host process the bridge already runs
7
+ * in, so nothing in this module opens a follow stream, waits on a socket or
8
+ * touches persistence: a title is a synchronous read like a map lookup, which
9
+ * is what makes a batch of them cheap enough to serve on request.
10
+ *
11
+ * The services are reached through structural faces rather than the SDK's own
12
+ * service types, for the reason `wire.ts` states for the gateway: the live
13
+ * objects carry far more than this package calls, and a face keeps a test
14
+ * double down to what is actually read.
15
+ * @module dsh-remote-bridge/core/session-meta
16
+ */
17
+
18
+ import { failureText } from './gateway-errors.ts'
19
+
20
+ /** One live session, as far as the title service needs to see it. */
21
+ export interface LiveSessionFace {
22
+ readonly id: string
23
+ }
24
+
25
+ /** The slice of `ctx.sessions` this package reads: the live session for an id. */
26
+ export interface SessionStoreFace {
27
+ get(id: string): LiveSessionFace | undefined
28
+ }
29
+
30
+ /** The slice of `ctx.sessionTitle` this package reads. */
31
+ export interface SessionTitleFace {
32
+ get(session: LiveSessionFace): { readonly title: string } | undefined
33
+ }
34
+
35
+ /** The slice of `ctx.workspaceRegistry` this package reads: the host's archive set. */
36
+ export interface ArchiveSetFace {
37
+ readonly archivedSessionIds: readonly string[]
38
+ }
39
+
40
+ /**
41
+ * The in-process services one metadata read may use.
42
+ *
43
+ * Every field is optional on purpose. The bridge does not require the title or
44
+ * workspace plugins to be installed — the protocol's roster and title methods
45
+ * stay answerable with them absent, and a field that is missing degrades one
46
+ * key of one row instead of failing a method.
47
+ */
48
+ export interface SessionMetaFaces {
49
+ readonly sessions?: SessionStoreFace | undefined
50
+ readonly titles?: SessionTitleFace | undefined
51
+ readonly archive?: ArchiveSetFace | undefined
52
+ }
53
+
54
+ /** Largest id batch one `session.titles` call accepts. */
55
+ export const TITLES_MAX_IDS = 100
56
+ /** How long one resolved title is served before the service is asked again. */
57
+ export const TITLE_CACHE_TTL_MS = 10_000
58
+ /** How many ids the title cache remembers before the oldest entry is dropped. */
59
+ export const TITLE_CACHE_LIMIT = 512
60
+
61
+ /** One cached title and when it was read. */
62
+ interface CacheEntry {
63
+ readonly title: string
64
+ readonly at: number
65
+ }
66
+
67
+ /**
68
+ * The bridge's session-metadata reads: live titles with a bounded cache, and
69
+ * the host's archive set.
70
+ *
71
+ * One instance is built per host mount and shared by every connection, because
72
+ * a title is a fact about the host's session, not about the device that asked.
73
+ *
74
+ * The cache is time-bounded rather than event-invalidated: a title change is a
75
+ * `session/title` *log* event, which no cordis event announces, so an
76
+ * invalidation hook would mean plumbing a listener into every live session. A
77
+ * short TTL bounds how stale a served title can be while keeping the read off
78
+ * the service for every repeat, and each batch call is itself a refresh point.
79
+ */
80
+ export class SessionMeta {
81
+ readonly #faces: () => SessionMetaFaces
82
+ readonly #now: () => number
83
+ readonly #log: (message: string) => void
84
+ readonly #ttlMs: number
85
+ readonly #titles = new Map<string, CacheEntry>()
86
+
87
+ /**
88
+ * @param faces - resolves the host services now; called per read, never captured once, so a service that mounts later is still picked up.
89
+ * @param now - the clock the cache window is measured on.
90
+ * @param log - where a failed metadata read is reported.
91
+ * @param ttlMs - cache window; the default is {@link TITLE_CACHE_TTL_MS}.
92
+ */
93
+ constructor(faces: () => SessionMetaFaces, now: () => number, log: (message: string) => void, ttlMs = TITLE_CACHE_TTL_MS) {
94
+ this.#faces = faces
95
+ this.#now = now
96
+ this.#log = log
97
+ this.#ttlMs = ttlMs
98
+ }
99
+
100
+ /**
101
+ * Latest title this host knows for one session.
102
+ *
103
+ * Synchronous by construction: the title service folds titles out of the
104
+ * session log it already holds. An id that is not live here, a session whose
105
+ * title has not landed yet, and a host without the title service all answer
106
+ * `""`, which is the protocol's "no title" value rather than a failure.
107
+ * @param id - session to read.
108
+ * @returns the title, or an empty string when there is none to read.
109
+ */
110
+ title(id: string): string {
111
+ const now = this.#now()
112
+ const cached = this.#titles.get(id)
113
+ if (cached !== undefined && now - cached.at < this.#ttlMs) return cached.title
114
+ const title = this.#resolve(id)
115
+ this.#titles.delete(id)
116
+ this.#titles.set(id, { title, at: now })
117
+ this.#evict()
118
+ return title
119
+ }
120
+
121
+ /**
122
+ * The title already resolved for one id, without reading any service.
123
+ *
124
+ * `session.list` uses this to fill a row it can fill for free; a roster must
125
+ * not put one title read on the path of every row it lists.
126
+ * @param id - session to look up.
127
+ * @returns the cached title while the cache window is open, else undefined.
128
+ */
129
+ cachedTitle(id: string): string | undefined {
130
+ const cached = this.#titles.get(id)
131
+ if (cached === undefined || this.#now() - cached.at >= this.#ttlMs) return undefined
132
+ return cached.title
133
+ }
134
+
135
+ /**
136
+ * The host's archive set, or undefined when it cannot be read.
137
+ *
138
+ * Reading it is the only way a row can carry `archived`: the key is omitted
139
+ * rather than guessed when the workspace registry is not mounted, so a client
140
+ * never reads "not archived" out of a bridge that simply could not tell.
141
+ * @returns the archived session ids, or undefined when the registry is unavailable.
142
+ */
143
+ archiveSet(): ReadonlySet<string> | undefined {
144
+ try {
145
+ const ids = this.#faces().archive?.archivedSessionIds
146
+ return ids === undefined ? undefined : new Set(ids)
147
+ } catch (error) {
148
+ this.#log(`the session archive set could not be read: ${failureText(error)}`)
149
+ return undefined
150
+ }
151
+ }
152
+
153
+ /** Resolve one title through the host services, degrading to `""` on any failure. */
154
+ #resolve(id: string): string {
155
+ try {
156
+ const faces = this.#faces()
157
+ const session = faces.sessions?.get(id)
158
+ if (session === undefined) return ''
159
+ return faces.titles?.get(session)?.title ?? ''
160
+ } catch (error) {
161
+ // One unreadable title must not fail the batch around it, and must not
162
+ // reach the client as an error: the id has no title, which is a value.
163
+ this.#log(`the title of session "${id}" could not be read: ${failureText(error)}`)
164
+ return ''
165
+ }
166
+ }
167
+
168
+ /** Drop the oldest ids until the cache is back inside its bound. */
169
+ #evict(): void {
170
+ while (this.#titles.size > TITLE_CACHE_LIMIT) {
171
+ const oldest = this.#titles.keys().next()
172
+ if (oldest.done === true) return
173
+ this.#titles.delete(oldest.value)
174
+ }
175
+ }
176
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The host's permission presets, projected into the shape `session.permissions`
3
+ * and `session.setPermission` publish.
4
+ *
5
+ * The services are reached through structural faces for the reason
6
+ * `session-meta.ts` states: the live objects carry far more than this package
7
+ * calls, and a face keeps a test double down to what is actually read.
8
+ *
9
+ * Two facts of the real service shape this module:
10
+ *
11
+ * - `current` and `set` take the LIVE `Session` object, never an id, so a
12
+ * session this host process does not hold — a cold, disk-only roster entry —
13
+ * has no truthful answer at all. That case is refused by name instead of
14
+ * being reported as an empty or defaulted mode.
15
+ * - `custom` is DERIVED state, never a switch target: it can be the current
16
+ * value and must never be offered as an option.
17
+ * @module dsh-remote-bridge/core/session-permissions
18
+ */
19
+
20
+ import { errorCodeOf, failureText } from './gateway-errors.ts'
21
+ import { CODE_INTERNAL, CODE_INVALID_ARGS, CODE_UNKNOWN_METHOD } from './protocol.ts'
22
+ import type { LiveSessionFace, SessionStoreFace } from './session-meta.ts'
23
+
24
+ /** The permission service's name for "no preset matches the two knobs". */
25
+ export const CUSTOM_PRESET = 'custom'
26
+
27
+ /**
28
+ * The code the harness raises for a session it has no live instance of.
29
+ * Verbatim from the harness's own error table, not a bridge-invented one.
30
+ */
31
+ export const CODE_SESSION_NOT_FOUND = 'session/not-found'
32
+
33
+ /** One preset as the permission service advertises it. */
34
+ export interface PresetOptionFace {
35
+ /** The switch target's stable value. */
36
+ readonly value: string
37
+ /** The label a client shows. */
38
+ readonly name: string
39
+ readonly description?: string
40
+ }
41
+
42
+ /** The slice of `ctx.permissionPresets` this package reads and writes. */
43
+ export interface PermissionPresetsFace {
44
+ catalog(): { readonly options: readonly PresetOptionFace[] } | undefined
45
+ /** The preset matching the session's folded knobs, or `custom`. */
46
+ current(session: LiveSessionFace): string
47
+ /** Switch one live session; unknown names throw. */
48
+ set(session: LiveSessionFace, name: string): void
49
+ /** The client option for a preset or the derived `custom`. */
50
+ optionOf(name: string): PresetOptionFace
51
+ }
52
+
53
+ /** The slice of `ctx.sandboxPolicy` this package reads. */
54
+ export interface SandboxPolicyFace {
55
+ /** The deployment default a session inherits without its own override. */
56
+ readonly defaultMode?: string
57
+ /** The session's own last logged mode, or undefined without one. */
58
+ overrideOf(session: LiveSessionFace): string | undefined
59
+ }
60
+
61
+ /** The slice of `ctx.approval` this package reads. */
62
+ export interface ApprovalPolicyFace {
63
+ /** The deployment's configured default policy. */
64
+ readonly config?: { readonly policy?: string }
65
+ /** The session's own last logged policy, or undefined without one. */
66
+ overrideOf(session: LiveSessionFace): string | undefined
67
+ }
68
+
69
+ /**
70
+ * The in-process services one permission read may use.
71
+ *
72
+ * Every field is optional on purpose: on a host that does not compose the
73
+ * permission plugin the method answers `unknown-method`, which is the signal a
74
+ * client already uses to disable the control instead of offering a dead switch.
75
+ */
76
+ export interface PermissionFaces {
77
+ readonly sessions?: SessionStoreFace | undefined
78
+ readonly presets?: PermissionPresetsFace | undefined
79
+ readonly sandbox?: SandboxPolicyFace | undefined
80
+ readonly approval?: ApprovalPolicyFace | undefined
81
+ }
82
+
83
+ /** One selectable preset, in the protocol's own field names. */
84
+ export interface PermissionOption {
85
+ readonly id: string
86
+ readonly name: string
87
+ readonly description?: string
88
+ }
89
+
90
+ /** The session's current permission mode. */
91
+ export interface PermissionCurrent {
92
+ readonly id: string
93
+ readonly name: string
94
+ /** The effective sandbox knob; present only while {@link PermissionCurrent.id} is `custom`. */
95
+ readonly sandbox?: string
96
+ /** The effective approval knob; present only while {@link PermissionCurrent.id} is `custom`. */
97
+ readonly approval?: string
98
+ }
99
+
100
+ /** One `session.permissions` answer. */
101
+ export interface PermissionsAnswer {
102
+ readonly current: PermissionCurrent
103
+ readonly options: readonly PermissionOption[]
104
+ readonly custom: boolean
105
+ }
106
+
107
+ /** One permission refusal, in the shape the dispatcher answers with. */
108
+ export interface PermissionRefusal {
109
+ readonly code: string
110
+ readonly msg: string
111
+ }
112
+
113
+ /** One live session plus the service that can describe and switch it. */
114
+ interface LivePresets {
115
+ readonly presets: PermissionPresetsFace
116
+ readonly session: LiveSessionFace
117
+ }
118
+
119
+ /**
120
+ * Read one knob's effective value: the session's own fold, else the deployment
121
+ * default.
122
+ * @returns the value, or undefined when neither could be read.
123
+ */
124
+ function knobOf(read: () => string | undefined, fallback: string | undefined): string | undefined {
125
+ try {
126
+ return read() ?? fallback
127
+ } catch {
128
+ // A knob the host cannot read is omitted rather than guessed: a client shows
129
+ // "unknown" for a missing value, which is true, and a fabricated mode is not.
130
+ return fallback
131
+ }
132
+ }
133
+
134
+ /**
135
+ * The bridge's permission reads and writes.
136
+ *
137
+ * One instance is built per host mount and shared by every connection, because a
138
+ * preset table is a fact about the deployment, not about the device that asked.
139
+ */
140
+ export class SessionPermissions {
141
+ readonly #faces: () => PermissionFaces
142
+ readonly #log: (message: string) => void
143
+
144
+ /**
145
+ * @param faces - resolves the host services now; called per read, never captured once, so a service that mounts later is still picked up.
146
+ * @param log - where an unreadable preset state is reported.
147
+ */
148
+ constructor(faces: () => PermissionFaces, log: (message: string) => void) {
149
+ this.#faces = faces
150
+ this.#log = log
151
+ }
152
+
153
+ /**
154
+ * Describe one session's permission modes.
155
+ *
156
+ * `current` is the service's own folded value: the preset the session's two
157
+ * knobs currently match, or `custom` with both knobs' real values. It is never
158
+ * the deployment default dressed up as the current mode.
159
+ * @param sessionId - the session the client is looking at.
160
+ */
161
+ describe(sessionId: string): PermissionsAnswer | PermissionRefusal {
162
+ const live = this.#live(sessionId)
163
+ if ('code' in live) return live
164
+ return this.#answer(live.presets, live.session)
165
+ }
166
+
167
+ /**
168
+ * Switch one session to a preset this host offers.
169
+ *
170
+ * The id is validated against the same option list `describe` publishes before
171
+ * the service is touched at all, so an unknown id changes nothing — the switch
172
+ * appends durable events and must never run on a rejected argument.
173
+ * @param sessionId - the session to switch.
174
+ * @param id - one of `describe(sessionId).options`' ids.
175
+ */
176
+ set(sessionId: string, id: string): PermissionsAnswer | PermissionRefusal {
177
+ const live = this.#live(sessionId)
178
+ if ('code' in live) return live
179
+ const before = this.#answer(live.presets, live.session)
180
+ if ('code' in before) return before
181
+ if (!before.options.some(option => option.id === id)) {
182
+ return { code: CODE_INVALID_ARGS, msg: `session.setPermission requires an id this host offers, not "${id}"` }
183
+ }
184
+ try {
185
+ live.presets.set(live.session, id)
186
+ } catch (error) {
187
+ this.#log(`the permission of one session could not be switched: ${failureText(error)}`)
188
+ return { code: errorCodeOf(error, CODE_INTERNAL), msg: failureText(error) }
189
+ }
190
+ return this.#answer(live.presets, live.session)
191
+ }
192
+
193
+ /** Resolve the service and the live session one call is about. */
194
+ #live(sessionId: string): LivePresets | PermissionRefusal {
195
+ const faces = this.#faces()
196
+ const presets = faces.presets
197
+ if (presets === undefined || typeof presets.catalog !== 'function' || typeof presets.current !== 'function') {
198
+ return { code: CODE_UNKNOWN_METHOD, msg: 'this host does not compose permissionPresets' }
199
+ }
200
+ const session = faces.sessions?.get(sessionId)
201
+ if (session === undefined) {
202
+ return { code: CODE_SESSION_NOT_FOUND, msg: `session ${sessionId} is not live in this host process` }
203
+ }
204
+ return { presets, session }
205
+ }
206
+
207
+ /** Build one answer out of the service's own folded state. */
208
+ #answer(presets: PermissionPresetsFace, session: LiveSessionFace): PermissionsAnswer | PermissionRefusal {
209
+ let current: string
210
+ try {
211
+ current = presets.current(session)
212
+ } catch (error) {
213
+ this.#log(`the permission preset of one session could not be read: ${failureText(error)}`)
214
+ return { code: errorCodeOf(error, CODE_INTERNAL), msg: failureText(error) }
215
+ }
216
+ const custom = current === CUSTOM_PRESET
217
+ const name = this.#labelOf(presets, current)
218
+ const head: PermissionCurrent = custom
219
+ ? { id: current, name, ...this.#knobs(session) }
220
+ : { id: current, name }
221
+ return { current: head, options: this.#options(presets), custom }
222
+ }
223
+
224
+ /**
225
+ * The switchable presets, in the service's own order.
226
+ *
227
+ * The catalog already advertises only presets that can be selected right now,
228
+ * so this only drops the derived value: `custom` is a state, not a target.
229
+ */
230
+ #options(presets: PermissionPresetsFace): PermissionOption[] {
231
+ let catalog: ReturnType<PermissionPresetsFace['catalog']>
232
+ try {
233
+ catalog = presets.catalog()
234
+ } catch (error) {
235
+ this.#log(`the permission catalog could not be read: ${failureText(error)}`)
236
+ return []
237
+ }
238
+ const options: PermissionOption[] = []
239
+ for (const option of catalog?.options ?? []) {
240
+ if (option === undefined || typeof option.value !== 'string' || option.value === '' || option.value === CUSTOM_PRESET) continue
241
+ const name = typeof option.name === 'string' && option.name !== '' ? option.name : option.value
242
+ options.push({ id: option.value, name, ...(option.description === undefined ? {} : { description: option.description }) })
243
+ }
244
+ return options
245
+ }
246
+
247
+ /** The label for one current value, falling back to the value itself. */
248
+ #labelOf(presets: PermissionPresetsFace, name: string): string {
249
+ try {
250
+ const option = presets.optionOf(name)
251
+ if (typeof option?.name === 'string' && option.name !== '') return option.name
252
+ } catch {
253
+ // A derived value the catalog does not label is still a value the client
254
+ // can show; the raw name is what the protocol's `id` already carries.
255
+ }
256
+ return name
257
+ }
258
+
259
+ /** The two knobs' effective values, for a session whose state matches no preset. */
260
+ #knobs(session: LiveSessionFace): { readonly sandbox?: string; readonly approval?: string } {
261
+ const faces = this.#faces()
262
+ const sandbox = knobOf(() => faces.sandbox?.overrideOf(session), faces.sandbox?.defaultMode)
263
+ const approval = knobOf(() => faces.approval?.overrideOf(session), faces.approval?.config?.policy ?? 'ask')
264
+ return { ...(sandbox === undefined ? {} : { sandbox }), ...(approval === undefined ? {} : { approval }) }
265
+ }
266
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The exact `args` layout of every DSH Remote endpoint this package may call.
3
+ *
4
+ * A descriptor declares one parameter name per wire key, and the gateway
5
+ * asserts the argument object is EXACTLY that set — one extra or one missing
6
+ * key throws `gateway/arguments-invalid`. The asymmetry is real and belongs to
7
+ * the endpoint owners, so it is tabulated here instead of guessed at the call
8
+ * site:
9
+ *
10
+ * - `session/list` is the only endpoint whose single parameter is named
11
+ * `_request` (the underscore is part of the wire name);
12
+ * - four endpoints take NO parameters at all and must be called with `{}`;
13
+ * - every other endpoint names its single parameter `request`.
14
+ * @module dsh-remote-bridge/core/wire
15
+ */
16
+
17
+ import type { InvokeRemoteRequest } from '@deepseek-ai/dsh-api-gateway'
18
+
19
+ /**
20
+ * The peer every gateway request names: derived from the public
21
+ * `InvokeRemoteRequest` type so this package needs no direct dependency on
22
+ * `@deepseek-ai/dsh-typert-protocol` for the shape.
23
+ */
24
+ export type GatewayPeer = InvokeRemoteRequest['peer']
25
+
26
+ /** One Remote call after the carrier has decoded its envelope. */
27
+ export interface GatewayInvokeRequest {
28
+ readonly namespace: string
29
+ readonly method: string
30
+ readonly args: Readonly<Record<string, unknown>>
31
+ /**
32
+ * The caller this call speaks for. The bridge mints this peer in-process
33
+ * (`core/owner-peer.ts`) and attaches it to every gateway call itself; no
34
+ * field of a client frame is ever read into it.
35
+ */
36
+ readonly peer: GatewayPeer
37
+ readonly signal?: AbortSignal
38
+ }
39
+
40
+ /**
41
+ * The subset of `ctx.typertGateway` this package consumes. Structural on
42
+ * purpose: the live service also carries the wire-stream adapter and the
43
+ * forwarded-event registry, none of which the bridge uses, so a test fake only
44
+ * has to implement what is called.
45
+ */
46
+ export interface BridgeGateway {
47
+ invoke(request: GatewayInvokeRequest): Promise<unknown>
48
+ stream(request: GatewayInvokeRequest): Promise<AsyncIterable<unknown>>
49
+ }
50
+
51
+ /**
52
+ * Durable identity of one ordinary Session or one direct subagent child.
53
+ *
54
+ * `session/follow` and `session/page` take this instead of a bare id, and the
55
+ * harness refuses a delegated child addressed as an ordinary session with
56
+ * `session/agent-busy` — "subagent Sessions require their durable parent
57
+ * address" — so the bridge must send the child's own kind for those sessions.
58
+ */
59
+ export type SessionAddress = {
60
+ readonly kind: 'session'
61
+ readonly sessionId: string
62
+ } | {
63
+ readonly kind: 'subagent'
64
+ readonly parentSessionId: string
65
+ readonly childSessionId: string
66
+ readonly mode: SubagentMode
67
+ }
68
+
69
+ /** How long a delegated child may be continued; `unknown` is checked against nothing. */
70
+ export type SubagentMode = 'one-shot' | 'continuable' | 'unknown'
71
+
72
+ /** The durable address of one ordinary session. */
73
+ export function sessionAddress(sessionId: string): SessionAddress {
74
+ return { kind: 'session', sessionId }
75
+ }
76
+
77
+ /**
78
+ * The durable address of one delegated child.
79
+ *
80
+ * The mode is always `unknown`: the bridge has no reliable way to read a
81
+ * child's mode before the call, and the harness accepts `unknown` for every
82
+ * child while checking a claimed mode against the descriptor.
83
+ */
84
+ export function subagentAddress(parentSessionId: string, childSessionId: string): SessionAddress {
85
+ return { kind: 'subagent', parentSessionId, childSessionId, mode: 'unknown' }
86
+ }
87
+
88
+ /** The failure code the harness raises for a child addressed as an ordinary session. */
89
+ export const CODE_SUBAGENT_ADDRESS_REQUIRED = 'session/agent-busy'
90
+
91
+ /**
92
+ * One endpoint's declared argument names: the name of its single parameter, the
93
+ * empty declaration of a parameterless endpoint, or the exact names of an
94
+ * endpoint that takes several.
95
+ */
96
+ export type WireName = 'request' | '_request' | 'none' | { readonly names: readonly string[] }
97
+
98
+ /** One endpoint's declared wire layout. */
99
+ export interface WireRow {
100
+ readonly namespace: string
101
+ readonly method: string
102
+ readonly wire: WireName
103
+ }
104
+
105
+ /**
106
+ * Every endpoint of the frozen mapping table, in the order the parent card
107
+ * lists them. Rows whose endpoint no method of protocol v1 exposes yet
108
+ * (`pluginInventory/list`, `pluginManager/listPlugins`) stay in the table: they
109
+ * are the layout a future method must not get wrong, and the table is the
110
+ * single place it is written.
111
+ */
112
+ export const WIRE_TABLE: readonly WireRow[] = [
113
+ { namespace: 'session', method: 'list', wire: '_request' },
114
+ { namespace: 'session', method: 'create', wire: 'request' },
115
+ { namespace: 'session', method: 'fork', wire: 'request' },
116
+ { namespace: 'session', method: 'page', wire: 'request' },
117
+ { namespace: 'session', method: 'follow', wire: 'request' },
118
+ { namespace: 'session', method: 'prompt', wire: 'request' },
119
+ { namespace: 'session', method: 'cancel', wire: 'request' },
120
+ { namespace: 'session', method: 'attachment', wire: 'request' },
121
+ { namespace: 'session', method: 'projections', wire: 'request' },
122
+ { namespace: 'session', method: 'modelCatalog', wire: 'none' },
123
+ { namespace: 'session', method: 'selectModel', wire: 'request' },
124
+ { namespace: 'agentPresets', method: 'list', wire: 'none' },
125
+ { namespace: 'userQuestions', method: 'answer', wire: { names: ['agentId', 'callId', 'answer'] } },
126
+ { namespace: 'userQuestions', method: 'attachWait', wire: { names: ['agentId', 'callId'] } },
127
+ { namespace: 'pluginInventory', method: 'list', wire: 'none' },
128
+ { namespace: 'pluginManager', method: 'listPlugins', wire: 'none' },
129
+ ]
130
+
131
+ /** @returns the declared row for an endpoint, or undefined when it is not tabulated. */
132
+ export function wireRowFor(namespace: string, method: string): WireRow | undefined {
133
+ return WIRE_TABLE.find(row => row.namespace === namespace && row.method === method)
134
+ }
135
+
136
+ /**
137
+ * Build the `args` object for one endpoint.
138
+ *
139
+ * An untabulated endpoint falls back to `{ request }`: that is the layout of
140
+ * every tabulated endpoint but a few, and a wrong guess fails loudly at the
141
+ * gateway with `arguments-invalid` rather than silently invoking the wrong
142
+ * shape. A multi-parameter endpoint carries one key per declared name, and a
143
+ * name the caller left out stays out — the gateway refuses it by name, which is
144
+ * the failure a caller should see.
145
+ * @param namespace - Remote namespace.
146
+ * @param method - Service method name.
147
+ * @param request - the endpoint's request payload.
148
+ * @returns the exact named-argument object.
149
+ */
150
+ export function wireArgs(namespace: string, method: string, request: Readonly<Record<string, unknown>> = {}): Record<string, unknown> {
151
+ const wire = wireRowFor(namespace, method)?.wire ?? 'request'
152
+ if (wire === 'none') return {}
153
+ if (typeof wire === 'object') {
154
+ const named: Record<string, unknown> = {}
155
+ for (const name of wire.names) if (Object.hasOwn(request, name)) named[name] = request[name]
156
+ return named
157
+ }
158
+ return { [wire]: request }
159
+ }