@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,105 @@
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
+ /** One live session, as far as the title service needs to see it. */
18
+ export interface LiveSessionFace {
19
+ readonly id: string;
20
+ }
21
+ /** The slice of `ctx.sessions` this package reads: the live session for an id. */
22
+ export interface SessionStoreFace {
23
+ get(id: string): LiveSessionFace | undefined;
24
+ }
25
+ /** The slice of `ctx.sessionTitle` this package reads. */
26
+ export interface SessionTitleFace {
27
+ get(session: LiveSessionFace): {
28
+ readonly title: string;
29
+ } | undefined;
30
+ }
31
+ /** The slice of `ctx.workspaceRegistry` this package reads: the host's archive set. */
32
+ export interface ArchiveSetFace {
33
+ readonly archivedSessionIds: readonly string[];
34
+ }
35
+ /**
36
+ * The in-process services one metadata read may use.
37
+ *
38
+ * Every field is optional on purpose. The bridge does not require the title or
39
+ * workspace plugins to be installed — the protocol's roster and title methods
40
+ * stay answerable with them absent, and a field that is missing degrades one
41
+ * key of one row instead of failing a method.
42
+ */
43
+ export interface SessionMetaFaces {
44
+ readonly sessions?: SessionStoreFace | undefined;
45
+ readonly titles?: SessionTitleFace | undefined;
46
+ readonly archive?: ArchiveSetFace | undefined;
47
+ }
48
+ /** Largest id batch one `session.titles` call accepts. */
49
+ export declare const TITLES_MAX_IDS = 100;
50
+ /** How long one resolved title is served before the service is asked again. */
51
+ export declare const TITLE_CACHE_TTL_MS = 10000;
52
+ /** How many ids the title cache remembers before the oldest entry is dropped. */
53
+ export declare const TITLE_CACHE_LIMIT = 512;
54
+ /**
55
+ * The bridge's session-metadata reads: live titles with a bounded cache, and
56
+ * the host's archive set.
57
+ *
58
+ * One instance is built per host mount and shared by every connection, because
59
+ * a title is a fact about the host's session, not about the device that asked.
60
+ *
61
+ * The cache is time-bounded rather than event-invalidated: a title change is a
62
+ * `session/title` *log* event, which no cordis event announces, so an
63
+ * invalidation hook would mean plumbing a listener into every live session. A
64
+ * short TTL bounds how stale a served title can be while keeping the read off
65
+ * the service for every repeat, and each batch call is itself a refresh point.
66
+ */
67
+ export declare class SessionMeta {
68
+ #private;
69
+ /**
70
+ * @param faces - resolves the host services now; called per read, never captured once, so a service that mounts later is still picked up.
71
+ * @param now - the clock the cache window is measured on.
72
+ * @param log - where a failed metadata read is reported.
73
+ * @param ttlMs - cache window; the default is {@link TITLE_CACHE_TTL_MS}.
74
+ */
75
+ constructor(faces: () => SessionMetaFaces, now: () => number, log: (message: string) => void, ttlMs?: number);
76
+ /**
77
+ * Latest title this host knows for one session.
78
+ *
79
+ * Synchronous by construction: the title service folds titles out of the
80
+ * session log it already holds. An id that is not live here, a session whose
81
+ * title has not landed yet, and a host without the title service all answer
82
+ * `""`, which is the protocol's "no title" value rather than a failure.
83
+ * @param id - session to read.
84
+ * @returns the title, or an empty string when there is none to read.
85
+ */
86
+ title(id: string): string;
87
+ /**
88
+ * The title already resolved for one id, without reading any service.
89
+ *
90
+ * `session.list` uses this to fill a row it can fill for free; a roster must
91
+ * not put one title read on the path of every row it lists.
92
+ * @param id - session to look up.
93
+ * @returns the cached title while the cache window is open, else undefined.
94
+ */
95
+ cachedTitle(id: string): string | undefined;
96
+ /**
97
+ * The host's archive set, or undefined when it cannot be read.
98
+ *
99
+ * Reading it is the only way a row can carry `archived`: the key is omitted
100
+ * rather than guessed when the workspace registry is not mounted, so a client
101
+ * never reads "not archived" out of a bridge that simply could not tell.
102
+ * @returns the archived session ids, or undefined when the registry is unavailable.
103
+ */
104
+ archiveSet(): ReadonlySet<string> | undefined;
105
+ }
@@ -0,0 +1,134 @@
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
+ import type { LiveSessionFace, SessionStoreFace } from './session-meta.ts';
20
+ /** The permission service's name for "no preset matches the two knobs". */
21
+ export declare const CUSTOM_PRESET = "custom";
22
+ /**
23
+ * The code the harness raises for a session it has no live instance of.
24
+ * Verbatim from the harness's own error table, not a bridge-invented one.
25
+ */
26
+ export declare const CODE_SESSION_NOT_FOUND = "session/not-found";
27
+ /** One preset as the permission service advertises it. */
28
+ export interface PresetOptionFace {
29
+ /** The switch target's stable value. */
30
+ readonly value: string;
31
+ /** The label a client shows. */
32
+ readonly name: string;
33
+ readonly description?: string;
34
+ }
35
+ /** The slice of `ctx.permissionPresets` this package reads and writes. */
36
+ export interface PermissionPresetsFace {
37
+ catalog(): {
38
+ readonly options: readonly PresetOptionFace[];
39
+ } | undefined;
40
+ /** The preset matching the session's folded knobs, or `custom`. */
41
+ current(session: LiveSessionFace): string;
42
+ /** Switch one live session; unknown names throw. */
43
+ set(session: LiveSessionFace, name: string): void;
44
+ /** The client option for a preset or the derived `custom`. */
45
+ optionOf(name: string): PresetOptionFace;
46
+ }
47
+ /** The slice of `ctx.sandboxPolicy` this package reads. */
48
+ export interface SandboxPolicyFace {
49
+ /** The deployment default a session inherits without its own override. */
50
+ readonly defaultMode?: string;
51
+ /** The session's own last logged mode, or undefined without one. */
52
+ overrideOf(session: LiveSessionFace): string | undefined;
53
+ }
54
+ /** The slice of `ctx.approval` this package reads. */
55
+ export interface ApprovalPolicyFace {
56
+ /** The deployment's configured default policy. */
57
+ readonly config?: {
58
+ readonly policy?: string;
59
+ };
60
+ /** The session's own last logged policy, or undefined without one. */
61
+ overrideOf(session: LiveSessionFace): string | undefined;
62
+ }
63
+ /**
64
+ * The in-process services one permission read may use.
65
+ *
66
+ * Every field is optional on purpose: on a host that does not compose the
67
+ * permission plugin the method answers `unknown-method`, which is the signal a
68
+ * client already uses to disable the control instead of offering a dead switch.
69
+ */
70
+ export interface PermissionFaces {
71
+ readonly sessions?: SessionStoreFace | undefined;
72
+ readonly presets?: PermissionPresetsFace | undefined;
73
+ readonly sandbox?: SandboxPolicyFace | undefined;
74
+ readonly approval?: ApprovalPolicyFace | undefined;
75
+ }
76
+ /** One selectable preset, in the protocol's own field names. */
77
+ export interface PermissionOption {
78
+ readonly id: string;
79
+ readonly name: string;
80
+ readonly description?: string;
81
+ }
82
+ /** The session's current permission mode. */
83
+ export interface PermissionCurrent {
84
+ readonly id: string;
85
+ readonly name: string;
86
+ /** The effective sandbox knob; present only while {@link PermissionCurrent.id} is `custom`. */
87
+ readonly sandbox?: string;
88
+ /** The effective approval knob; present only while {@link PermissionCurrent.id} is `custom`. */
89
+ readonly approval?: string;
90
+ }
91
+ /** One `session.permissions` answer. */
92
+ export interface PermissionsAnswer {
93
+ readonly current: PermissionCurrent;
94
+ readonly options: readonly PermissionOption[];
95
+ readonly custom: boolean;
96
+ }
97
+ /** One permission refusal, in the shape the dispatcher answers with. */
98
+ export interface PermissionRefusal {
99
+ readonly code: string;
100
+ readonly msg: string;
101
+ }
102
+ /**
103
+ * The bridge's permission reads and writes.
104
+ *
105
+ * One instance is built per host mount and shared by every connection, because a
106
+ * preset table is a fact about the deployment, not about the device that asked.
107
+ */
108
+ export declare class SessionPermissions {
109
+ #private;
110
+ /**
111
+ * @param faces - resolves the host services now; called per read, never captured once, so a service that mounts later is still picked up.
112
+ * @param log - where an unreadable preset state is reported.
113
+ */
114
+ constructor(faces: () => PermissionFaces, log: (message: string) => void);
115
+ /**
116
+ * Describe one session's permission modes.
117
+ *
118
+ * `current` is the service's own folded value: the preset the session's two
119
+ * knobs currently match, or `custom` with both knobs' real values. It is never
120
+ * the deployment default dressed up as the current mode.
121
+ * @param sessionId - the session the client is looking at.
122
+ */
123
+ describe(sessionId: string): PermissionsAnswer | PermissionRefusal;
124
+ /**
125
+ * Switch one session to a preset this host offers.
126
+ *
127
+ * The id is validated against the same option list `describe` publishes before
128
+ * the service is touched at all, so an unknown id changes nothing — the switch
129
+ * appends durable events and must never run on a rejected argument.
130
+ * @param sessionId - the session to switch.
131
+ * @param id - one of `describe(sessionId).options`' ids.
132
+ */
133
+ set(sessionId: string, id: string): PermissionsAnswer | PermissionRefusal;
134
+ }
@@ -0,0 +1,115 @@
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
+ import type { InvokeRemoteRequest } from '@deepseek-ai/dsh-api-gateway';
17
+ /**
18
+ * The peer every gateway request names: derived from the public
19
+ * `InvokeRemoteRequest` type so this package needs no direct dependency on
20
+ * `@deepseek-ai/dsh-typert-protocol` for the shape.
21
+ */
22
+ export type GatewayPeer = InvokeRemoteRequest['peer'];
23
+ /** One Remote call after the carrier has decoded its envelope. */
24
+ export interface GatewayInvokeRequest {
25
+ readonly namespace: string;
26
+ readonly method: string;
27
+ readonly args: Readonly<Record<string, unknown>>;
28
+ /**
29
+ * The caller this call speaks for. The bridge mints this peer in-process
30
+ * (`core/owner-peer.ts`) and attaches it to every gateway call itself; no
31
+ * field of a client frame is ever read into it.
32
+ */
33
+ readonly peer: GatewayPeer;
34
+ readonly signal?: AbortSignal;
35
+ }
36
+ /**
37
+ * The subset of `ctx.typertGateway` this package consumes. Structural on
38
+ * purpose: the live service also carries the wire-stream adapter and the
39
+ * forwarded-event registry, none of which the bridge uses, so a test fake only
40
+ * has to implement what is called.
41
+ */
42
+ export interface BridgeGateway {
43
+ invoke(request: GatewayInvokeRequest): Promise<unknown>;
44
+ stream(request: GatewayInvokeRequest): Promise<AsyncIterable<unknown>>;
45
+ }
46
+ /**
47
+ * Durable identity of one ordinary Session or one direct subagent child.
48
+ *
49
+ * `session/follow` and `session/page` take this instead of a bare id, and the
50
+ * harness refuses a delegated child addressed as an ordinary session with
51
+ * `session/agent-busy` — "subagent Sessions require their durable parent
52
+ * address" — so the bridge must send the child's own kind for those sessions.
53
+ */
54
+ export type SessionAddress = {
55
+ readonly kind: 'session';
56
+ readonly sessionId: string;
57
+ } | {
58
+ readonly kind: 'subagent';
59
+ readonly parentSessionId: string;
60
+ readonly childSessionId: string;
61
+ readonly mode: SubagentMode;
62
+ };
63
+ /** How long a delegated child may be continued; `unknown` is checked against nothing. */
64
+ export type SubagentMode = 'one-shot' | 'continuable' | 'unknown';
65
+ /** The durable address of one ordinary session. */
66
+ export declare function sessionAddress(sessionId: string): SessionAddress;
67
+ /**
68
+ * The durable address of one delegated child.
69
+ *
70
+ * The mode is always `unknown`: the bridge has no reliable way to read a
71
+ * child's mode before the call, and the harness accepts `unknown` for every
72
+ * child while checking a claimed mode against the descriptor.
73
+ */
74
+ export declare function subagentAddress(parentSessionId: string, childSessionId: string): SessionAddress;
75
+ /** The failure code the harness raises for a child addressed as an ordinary session. */
76
+ export declare const CODE_SUBAGENT_ADDRESS_REQUIRED = "session/agent-busy";
77
+ /**
78
+ * One endpoint's declared argument names: the name of its single parameter, the
79
+ * empty declaration of a parameterless endpoint, or the exact names of an
80
+ * endpoint that takes several.
81
+ */
82
+ export type WireName = 'request' | '_request' | 'none' | {
83
+ readonly names: readonly string[];
84
+ };
85
+ /** One endpoint's declared wire layout. */
86
+ export interface WireRow {
87
+ readonly namespace: string;
88
+ readonly method: string;
89
+ readonly wire: WireName;
90
+ }
91
+ /**
92
+ * Every endpoint of the frozen mapping table, in the order the parent card
93
+ * lists them. Rows whose endpoint no method of protocol v1 exposes yet
94
+ * (`pluginInventory/list`, `pluginManager/listPlugins`) stay in the table: they
95
+ * are the layout a future method must not get wrong, and the table is the
96
+ * single place it is written.
97
+ */
98
+ export declare const WIRE_TABLE: readonly WireRow[];
99
+ /** @returns the declared row for an endpoint, or undefined when it is not tabulated. */
100
+ export declare function wireRowFor(namespace: string, method: string): WireRow | undefined;
101
+ /**
102
+ * Build the `args` object for one endpoint.
103
+ *
104
+ * An untabulated endpoint falls back to `{ request }`: that is the layout of
105
+ * every tabulated endpoint but a few, and a wrong guess fails loudly at the
106
+ * gateway with `arguments-invalid` rather than silently invoking the wrong
107
+ * shape. A multi-parameter endpoint carries one key per declared name, and a
108
+ * name the caller left out stays out — the gateway refuses it by name, which is
109
+ * the failure a caller should see.
110
+ * @param namespace - Remote namespace.
111
+ * @param method - Service method name.
112
+ * @param request - the endpoint's request payload.
113
+ * @returns the exact named-argument object.
114
+ */
115
+ export declare function wireArgs(namespace: string, method: string, request?: Readonly<Record<string, unknown>>): Record<string, unknown>;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * RFC 6455 server-side framing, kept as pure functions so the length, mask and
3
+ * opcode rules are unit-tested without a socket.
4
+ *
5
+ * Only what a server must accept is implemented: client frames are always
6
+ * masked, one logical message may arrive as a text frame or as a fragmented
7
+ * sequence, and anything the protocol forbids answers with the close code that
8
+ * names the violation instead of being ignored.
9
+ * @module dsh-remote-bridge/core/ws-frames
10
+ */
11
+ /** The magic GUID every WebSocket handshake is keyed with. */
12
+ export declare const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
13
+ export declare const OPCODE_CONTINUATION = 0;
14
+ export declare const OPCODE_TEXT = 1;
15
+ export declare const OPCODE_BINARY = 2;
16
+ export declare const OPCODE_CLOSE = 8;
17
+ export declare const OPCODE_PING = 9;
18
+ export declare const OPCODE_PONG = 10;
19
+ /** Close code for a protocol violation. */
20
+ export declare const CLOSE_PROTOCOL_ERROR = 1002;
21
+ /** Close code for a message this bridge will not carry. */
22
+ export declare const CLOSE_UNSUPPORTED_DATA = 1003;
23
+ /** Close code for a message past the size this bridge will carry. */
24
+ export declare const CLOSE_TOO_LARGE = 1009;
25
+ /**
26
+ * Close code for a peer that stopped answering: a liveness ping went out and no
27
+ * frame at all came back before its deadline.
28
+ *
29
+ * It is an application-range code (4000-4999), so a client can tell a peer that
30
+ * went silent from a protocol fault, from a frame this bridge will not carry,
31
+ * and from the ordinary 1001 teardown of a bridge that is unloading.
32
+ */
33
+ export declare const CLOSE_LIVENESS_TIMEOUT = 4000;
34
+ /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
35
+ export declare function webSocketAccept(secWebSocketKey: string): string;
36
+ /** One decoded frame header plus its payload. */
37
+ export interface DecodedFrame {
38
+ readonly fin: boolean;
39
+ readonly opcode: number;
40
+ readonly payload: Buffer;
41
+ /** Bytes this frame occupies in the stream. */
42
+ readonly consumed: number;
43
+ }
44
+ export type FrameParseOutcome = {
45
+ readonly status: 'incomplete';
46
+ } | {
47
+ readonly status: 'frame';
48
+ readonly frame: DecodedFrame;
49
+ } | {
50
+ readonly status: 'fault';
51
+ readonly closeCode: number;
52
+ readonly reason: string;
53
+ };
54
+ /**
55
+ * Decode one frame from the head of a buffer.
56
+ * @param buffer - the bytes received so far.
57
+ * @param maxBytes - largest payload this bridge accepts.
58
+ */
59
+ export declare function parseClientFrame(buffer: Buffer, maxBytes: number): FrameParseOutcome;
60
+ /**
61
+ * Encode one server frame. Server frames are never masked.
62
+ * @param opcode - the frame opcode.
63
+ * @param payload - already-serialized payload bytes.
64
+ * @param fin - whether this frame completes the message.
65
+ */
66
+ export declare function encodeServerFrame(opcode: number, payload: Buffer, fin?: boolean): Buffer;
67
+ /** Encode one text message. */
68
+ export declare function encodeTextFrame(text: string): Buffer;
69
+ /** Encode one binary message: already-encoded payload bytes, never a text frame. */
70
+ export declare function encodeBinaryFrame(payload: Buffer): Buffer;
71
+ /** Encode one close frame with a code and a short reason. */
72
+ export declare function encodeCloseFrame(code: number, reason: string): Buffer;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
3
+ * environment override wins, the platform home fallback follows. Mirrors
4
+ * what dsh-pet and dsh-liangshen each used to implement locally.
5
+ */
6
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
7
+ export declare function expandHome(path: string, home?: string): string;
8
+ /**
9
+ * Resolve the DSH home directory.
10
+ * @param env - process environment to read DSH_HOME from.
11
+ * @param home - platform home directory fallback (test seam).
12
+ * @returns the absolute DSH home path.
13
+ */
14
+ export declare function resolveDshHome(env?: NodeJS.ProcessEnv, home?: string): string;
15
+ /** Resolve the DSH home directory from the live environment. */
16
+ export declare function dshHome(): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The public origin a phone should dial, discovered rather than asked for.
3
+ *
4
+ * A pairing code is far better when it carries the address too: the phone then
5
+ * needs one scan and no typing. This module is where that address comes from,
6
+ * in the order the family already trusts:
7
+ *
8
+ * 1. `DSH_REMOTE_PUBLIC_BASE_URL` — the same environment contract
9
+ * `dsh-remote-web-ui` reads for its own public base.
10
+ * 2. The relay registry row `$DSH_HOME/remote-web-ui-registry/<profile>.json`,
11
+ * whose `id` is the stable `<id>.<relay>` subdomain that plugin registers
12
+ * for this profile (see its `relay-registry.ts`). Reading that row is a
13
+ * deliberate, documented data dependency: it is one small JSON file per
14
+ * profile, it is written by the machine itself, and a missing or unreadable
15
+ * row simply means "no origin known" rather than an error.
16
+ *
17
+ * Nothing here reaches the network, and nothing here mints or spends anything.
18
+ * @module dsh-remote-bridge/host/pair-origin
19
+ */
20
+ /** The relay's worker domain; a profile's stable origin is `<id>.<this>`. */
21
+ export declare const RELAY_DOMAIN = "dsh-market.com";
22
+ /** The registry directory `dsh-remote-web-ui` keeps its per-profile row in. */
23
+ export declare const RELAY_REGISTRY_DIR = "remote-web-ui-registry";
24
+ /** One discovered origin and the fact that produced it. */
25
+ export interface PairOriginFacts {
26
+ /** Origin only, no path: `wss://<id>.dsh-market.com`. */
27
+ readonly origin: string;
28
+ /** Where the answer came from, for the panel and the log. */
29
+ readonly source: 'env' | 'registry';
30
+ }
31
+ export interface DiscoverPairOriginOptions {
32
+ /** Environment to read; defaults to `process.env`. */
33
+ readonly env?: NodeJS.ProcessEnv;
34
+ /** DSH home to look in; defaults to `resolveDshHome(env)`. */
35
+ readonly home?: string;
36
+ /** Profile whose registry row to read; defaults to `$DSH_PROFILE` or `desktop`. */
37
+ readonly profile?: string;
38
+ }
39
+ /**
40
+ * Discover the public origin of this instance.
41
+ * @param options - environment, home and profile seams for tests.
42
+ * @returns the origin and its source, or `undefined` when nothing is known.
43
+ */
44
+ export declare function discoverPairOrigin(options?: DiscoverPairOriginOptions): PairOriginFacts | undefined;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The bootstrap token endpoint an operator reaches from the Host itself.
3
+ *
4
+ * It is a named route on the host web server at one exact path, and it is the
5
+ * only place a bootstrap token is ever minted. Admission is the two-condition
6
+ * loopback gate in `core/loopback.ts` (socket address AND Host header); the
7
+ * token itself is one-shot with a 30 s lifetime, and the same link is printed
8
+ * to the Host log so an operator can open it from the machine.
9
+ * @module dsh-remote-bridge/host/routes
10
+ */
11
+ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver';
12
+ import type { PairingService } from '../core/pairing.ts';
13
+ import { type PairOriginFacts } from './pair-origin.ts';
14
+ export interface PairTokenRouteDeps {
15
+ readonly pairing: PairingService;
16
+ readonly log: (message: string) => void;
17
+ /** Origin discovery seam; defaults to {@link discoverPairOrigin}. */
18
+ readonly pairOrigin?: () => PairOriginFacts | undefined;
19
+ }
20
+ /**
21
+ * Build the handler for `GET /remote-bridge/pair/token`.
22
+ * @param deps - the pairing service that mints the token, plus the Host log.
23
+ * @returns the handler; the caller owns route registration.
24
+ */
25
+ export declare function makePairTokenHandler(deps: PairTokenRouteDeps): WebRoute['handler'];
26
+ /** The route as the host web server takes it: one exact path, no trailing slash. */
27
+ export declare function makePairTokenRoute(deps: PairTokenRouteDeps): WebRoute;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The WebSocket carrier of `/ios/v1`: RFC 6455 negotiation plus the frame loop.
3
+ *
4
+ * This is the only WebSocket in the family that terminates the protocol
5
+ * itself — the other remote plugin proxies its upgrades to the host mux — so
6
+ * the framing rules are implemented here against `core/ws-frames.ts` and every
7
+ * socket failure funnels into one teardown path that the hub observes exactly
8
+ * once.
9
+ * @module dsh-remote-bridge/host/websocket
10
+ */
11
+ import type { IncomingMessage } from 'node:http';
12
+ import type { Duplex } from 'node:stream';
13
+ import type { BridgeTransport, ConnectionAuth } from '../core/connection.ts';
14
+ import type { BridgeHub } from '../core/hub.ts';
15
+ /**
16
+ * Messages one carrier buffers while no handler is registered. The mounted
17
+ * wiring registers one synchronously, so this only ever absorbs bytes that were
18
+ * handed over before the handler existed; past it the socket is closed instead of
19
+ * buffering a conversation nobody is reading.
20
+ */
21
+ export declare const PENDING_MESSAGE_LIMIT = 32;
22
+ /** @returns whether this request asks for a WebSocket upgrade. */
23
+ export declare function isWebSocketUpgrade(req: IncomingMessage): boolean;
24
+ /** @returns the client's `Sec-WebSocket-Key`, or undefined when the handshake is incomplete. */
25
+ export declare function readSecWebSocketKey(req: IncomingMessage): string | undefined;
26
+ /** @returns the device token on `Authorization: Bearer …`, if the client sent one. */
27
+ export declare function bearerTokenOf(req: IncomingMessage): string | undefined;
28
+ /**
29
+ * @returns the token on `?token=…`, the fallback for clients whose handshake
30
+ * cannot set a header (share sheets, `wscat`, plain scripts).
31
+ */
32
+ export declare function queryTokenOf(requestUrl: string | undefined): string | undefined;
33
+ /**
34
+ * @returns the token this upgrade presents: the header first, then the query.
35
+ * A bootstrap token presented here is simply not a device token, which leaves
36
+ * the connection unpaired — the state `pair.begin` needs.
37
+ */
38
+ export declare function presentedTokenOf(req: IncomingMessage): string | undefined;
39
+ /**
40
+ * Answer an upgrade this endpoint will not take, and close the write side.
41
+ *
42
+ * The refusal rides `end()`, which flushes the response before the FIN. Writing
43
+ * and then destroying in the same tick aborts the in-flight write on Linux, and
44
+ * that abort surfaces as the socket's own `error` event - which nothing on a
45
+ * refused socket listens for, because the carrier's subscriptions only exist
46
+ * once an upgrade is accepted. One malformed upgrade therefore reached the host
47
+ * as an uncaught exception. The listener absorbs the transport's own failures: a
48
+ * peer that vanished mid-refusal is the client's problem, never the host's.
49
+ */
50
+ export declare function refuseUpgrade(socket: Duplex, status: number, reason: string): void;
51
+ /**
52
+ * One accepted upgrade handed to the bridge.
53
+ */
54
+ export interface UpgradeHandoff {
55
+ /** The upgraded socket; the carrier both reads from and writes to it. */
56
+ readonly socket: Duplex;
57
+ /** The client's `Sec-WebSocket-Key`, already read from the handshake. */
58
+ readonly secWebSocketKey: string;
59
+ /** Bytes that arrived with the upgrade request itself. */
60
+ readonly head: Buffer;
61
+ readonly hub: BridgeHub;
62
+ /** The device the handshake token proved, when it proved one. */
63
+ readonly auth?: ConnectionAuth;
64
+ }
65
+ /**
66
+ * Hand one accepted upgrade to the hub, in the one order that is correct.
67
+ *
68
+ * Every step here is synchronous, which is what makes the carrier's own
69
+ * pre-handler buffer unnecessary in practice — and the buffer is there anyway,
70
+ * so the bytes of `head` (and anything that beats the handler) are delivered
71
+ * instead of dropped. The order is the point of this function: reading the
72
+ * socket without a handler, or attaching a connection whose carrier is never
73
+ * written to, both end in a client that waits forever.
74
+ * @param handoff - the socket, its handshake facts, and the hub to join.
75
+ * @returns the carrier, for a caller that needs to observe it.
76
+ */
77
+ export declare function serveUpgrade(handoff: UpgradeHandoff): WebSocketCarrier;
78
+ /**
79
+ * One accepted socket, framed.
80
+ *
81
+ * Frames are buffered until a whole one has arrived; a fragmented message is
82
+ * reassembled up to {@link MAX_FRAME_BYTES} and anything larger closes the
83
+ * socket with the code that names the violation. The carrier is inert until
84
+ * {@link handshake} runs, so a caller can refuse a connection without having
85
+ * written a byte of the protocol.
86
+ */
87
+ export declare class WebSocketCarrier implements BridgeTransport {
88
+ #private;
89
+ constructor(socket: Duplex);
90
+ /** Write the 101 handshake carrying the accept value for the client's key. */
91
+ handshake(secWebSocketKey: string): void;
92
+ /** Register the handler for every complete text message. */
93
+ onMessage(handler: (text: string) => void): void;
94
+ /** Register the one teardown hook; it runs exactly once. */
95
+ onClose(handler: () => void): void;
96
+ /** Feed raw bytes from the socket into the frame loop. */
97
+ feed(chunk: Buffer): void;
98
+ /**
99
+ * Record the peer's `frame.deflate.v1` declaration, as `hello` reported it.
100
+ *
101
+ * It defaults to off, so a connection that never declares the capability keeps
102
+ * the text frame this carrier always wrote, byte for byte.
103
+ */
104
+ frameDeflate(declared: boolean): void;
105
+ /** Send one frame: the text itself, or raw DEFLATE of it as a binary frame. */
106
+ send(text: string): void;
107
+ /** Send a close frame and end the socket. Idempotent. */
108
+ close(code: number, reason: string): void;
109
+ /** @returns whether the carrier has been torn down. */
110
+ get closed(): boolean;
111
+ }