@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,144 @@
1
+ /**
2
+ * The bridge's extension seam: the one place another plugin adds methods and
3
+ * events to protocol v1 without the bridge learning what they mean.
4
+ *
5
+ * The bridge publishes this seam as the cordis service
6
+ * {@link REMOTE_BRIDGE_SERVICE}. A plugin registers a table of methods plus the
7
+ * capability a client must declare before those methods exist for it, and
8
+ * publishes events to the clients that declared the capability it names.
9
+ * Nothing here carries protocol vocabulary of its own: method names, payloads,
10
+ * topics and refusal codes belong to the registering plugin, which is why this
11
+ * module never appears in `KNOWN_METHODS` and never reads a payload.
12
+ *
13
+ * A connection dispatches an extension method only after the protocol's own
14
+ * gates: an unregistered name, a plugin that is not mounted, and a client that
15
+ * never declared the capability all answer `unknown-method` — the method is
16
+ * absent from that client's protocol, not refused by it.
17
+ * @module dsh-remote-bridge/core/extension
18
+ */
19
+ import type { RemoteBridgeDeltas } from './delta.ts';
20
+ /** Cordis service this seam is published under. */
21
+ export declare const REMOTE_BRIDGE_SERVICE = "remoteBridge";
22
+ /**
23
+ * Who is calling one extension method.
24
+ *
25
+ * The bridge exposes no device or session identity here on purpose: what an
26
+ * extension keys by connection is its own decision.
27
+ */
28
+ export interface RemoteBridgeCall {
29
+ /**
30
+ * Stable identity of the calling connection, unique within this bridge
31
+ * process. Two calls from one socket carry the same id; a reconnected socket
32
+ * carries a new one, because nothing proves it is the same peer.
33
+ */
34
+ readonly connectionId: string;
35
+ /**
36
+ * @param capability - one capability name of this protocol or of the calling
37
+ * extension.
38
+ * @returns whether this connection announced it in `hello`.
39
+ *
40
+ * The seam hands handlers the same predicate the bridge itself gates on, so
41
+ * an extension can gate behind a bridge capability (§15's `delta.v1`) without
42
+ * holding a copy of the client's declaration.
43
+ */
44
+ declares(capability: string): boolean;
45
+ /**
46
+ * This connection's delta windows, released with the connection.
47
+ *
48
+ * The mechanism of §15 lives once, in this bridge, and an extension borrows it
49
+ * per connection: the difference is always computed where the last answer is
50
+ * already held, and a dropped connection takes its base with it instead of
51
+ * leaving one to be expired by a second registry.
52
+ */
53
+ readonly deltas: RemoteBridgeDeltas;
54
+ }
55
+ /**
56
+ * What one extension method answers: the response body, or a refusal stated in
57
+ * the extension's own code vocabulary. The bridge forwards either verbatim —
58
+ * it holds no table of extension codes and invents none.
59
+ */
60
+ export type RemoteBridgeMethodResult = {
61
+ readonly ok: true;
62
+ readonly r?: unknown;
63
+ } | {
64
+ readonly ok: false;
65
+ readonly code: string;
66
+ readonly msg: string;
67
+ };
68
+ /** One client-callable method an extension owns. */
69
+ export type RemoteBridgeMethodHandler = (payload: Readonly<Record<string, unknown>>, call: RemoteBridgeCall) => RemoteBridgeMethodResult | Promise<RemoteBridgeMethodResult>;
70
+ /** A table of methods and the capability that admits a client to them. */
71
+ export interface RemoteBridgeMethods {
72
+ /**
73
+ * Capability a client declares in `hello`'s `cap` array before these methods
74
+ * are part of its protocol. Absent means every paired connection may call
75
+ * them; an unpaired connection never may, whatever it declared.
76
+ */
77
+ readonly capability?: string;
78
+ /** Method name to handler; the name is the extension's, not the bridge's. */
79
+ readonly methods: Readonly<Record<string, RemoteBridgeMethodHandler>>;
80
+ }
81
+ /** The seam, exactly as published on {@link REMOTE_BRIDGE_SERVICE}. */
82
+ export interface RemoteBridgeFace {
83
+ /**
84
+ * Add methods to the protocol surface.
85
+ * @returns the disposer withdrawing them; afterwards they answer `unknown-method` again.
86
+ */
87
+ registerMethods(table: RemoteBridgeMethods): () => void;
88
+ /**
89
+ * Publish one event to the connections that are paired — and, when a
90
+ * capability is named, have declared it.
91
+ * @returns how many connections took the frame.
92
+ */
93
+ broadcast(topic: string, payload: unknown, capability?: string): number;
94
+ }
95
+ /** The fan-out the seam publishes through; `BridgeHub` satisfies it. */
96
+ export interface RemoteBridgeFanout {
97
+ broadcast(topic: string, payload: unknown): number;
98
+ broadcastTo(capability: string, topic: string, payload: unknown): number;
99
+ }
100
+ /**
101
+ * The methods extensions registered, and the capability each one needs.
102
+ *
103
+ * Every connection consults this registry; nothing else holds extension state,
104
+ * so unmounting one plugin withdraws exactly its own methods.
105
+ */
106
+ export declare class RemoteBridgeRegistry {
107
+ #private;
108
+ /**
109
+ * Register one table of methods, all or nothing: a table naming a protocol
110
+ * method, an empty name or a name already taken is refused before any of its
111
+ * methods becomes callable.
112
+ * @param table - the methods and the capability they require.
113
+ * @returns the disposer withdrawing this table; idempotent.
114
+ */
115
+ registerMethods(table: RemoteBridgeMethods): () => void;
116
+ /**
117
+ * @param method - the method name a client asked for.
118
+ * @returns whether any plugin registered it, whatever capability it requires.
119
+ */
120
+ has(method: string): boolean;
121
+ /**
122
+ * @param method - the method name a client asked for.
123
+ * @param declares - whether the calling connection declared a capability.
124
+ * @returns the handler when the caller may use the method, else undefined.
125
+ */
126
+ handlerFor(method: string, declares: (capability: string) => boolean): RemoteBridgeMethodHandler | undefined;
127
+ }
128
+ /**
129
+ * Compose the published seam over a registry and a fan-out.
130
+ * @param methods - the registry this bridge owns.
131
+ * @param fanout - the hub's broadcast pair.
132
+ * @returns the face a plugin resolves from {@link REMOTE_BRIDGE_SERVICE}.
133
+ */
134
+ export declare function createRemoteBridgeFace(methods: RemoteBridgeRegistry, fanout: RemoteBridgeFanout): RemoteBridgeFace;
135
+ declare module '@deepseek-ai/cordis' {
136
+ interface Context {
137
+ /**
138
+ * The bridge's extension seam, while this package serves protocol v1. A
139
+ * plugin resolves it structurally at use time: requiring it would let the
140
+ * bridge's absence take the registering plugin's start down with it.
141
+ */
142
+ remoteBridge: RemoteBridgeFace;
143
+ }
144
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Bounded retry for the DSH service-activation window.
3
+ *
4
+ * The gateway raises its activation failures as `error.code`, never as an
5
+ * `instanceof` identity, and two generations of code strings coexist: the
6
+ * namespace-qualified `gateway/service-unavailable` and the bare
7
+ * `service-unavailable`. Both are recognized, verbatim from the family's
8
+ * task-board runner, so a provider that is merely slow to activate is retried
9
+ * rather than reported to the phone as a broken deployment.
10
+ * @module dsh-remote-bridge/core/gateway-errors
11
+ */
12
+ /** Tries one unary call may consume while the target service is activating. */
13
+ export declare const SERVICE_UNAVAILABLE_ATTEMPTS = 5;
14
+ /** Wait between those tries. */
15
+ export declare const SERVICE_UNAVAILABLE_BACKOFF_MS = 2000;
16
+ /**
17
+ * Whether a failure means the target service has not finished activating.
18
+ * This is the one failure worth retrying: the same call succeeds moments later.
19
+ */
20
+ export declare function isServiceUnavailable(error: unknown): boolean;
21
+ /**
22
+ * Whether the running gateway does not serve this endpoint at all (the cohort
23
+ * changed under this plugin). Retrying cannot help; the caller reports it.
24
+ */
25
+ export declare function isInvocationUnavailable(error: unknown): boolean;
26
+ /** Whether the endpoint exists but its strict definition was withdrawn by the running gateway. */
27
+ export declare function isDefinitionWithdrawn(error: unknown): boolean;
28
+ /** Whether the call's named arguments did not match the descriptor. */
29
+ export declare function isArgumentsInvalid(error: unknown): boolean;
30
+ /** One-line text of a failure, for a decideable reason the phone can show. */
31
+ export declare function failureText(error: unknown): string;
32
+ /**
33
+ * The failure's own code, for the response envelope. The gateway's codes cross
34
+ * to the phone unchanged (`gateway/arguments-invalid` and friends) so the client
35
+ * can tell "this deployment cannot" from "this build is wrong"; anything
36
+ * without a string code is `internal`.
37
+ */
38
+ export declare function errorCodeOf(error: unknown, fallback: string): string;
39
+ /**
40
+ * Run one unary call, retrying only the service-activation window.
41
+ * @param run - the call to attempt.
42
+ * @param options.attempts - total tries (default {@link SERVICE_UNAVAILABLE_ATTEMPTS}).
43
+ * @param options.backoffMs - wait between tries (default {@link SERVICE_UNAVAILABLE_BACKOFF_MS}).
44
+ * @returns the call's own result or failure; the failure is never swallowed.
45
+ */
46
+ export declare function withServiceUnavailableRetry<T>(run: () => Promise<T>, options?: {
47
+ attempts?: number;
48
+ backoffMs?: number;
49
+ }): Promise<T>;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The bridge's process-wide connection registry and its claims on
3
+ * `approval/request` and `user-questions/request`.
4
+ *
5
+ * The hub is what makes "phone not answering equals refusal" true: a question
6
+ * is claimed only while at least one paired device is connected, the publish
7
+ * has to actually reach someone, and every other path (timeout, agent
8
+ * cancellation, the last phone leaving) delegates to the next answerer, which
9
+ * the Host normalizes to `'unavailable'`.
10
+ *
11
+ * The claim on `user-questions/request` follows the same two rules, with two
12
+ * differences that belong to the host's own semantics: delegating is not a
13
+ * refusal, because only a phone that declares `questions.v1` is ever shown the
14
+ * question; and a question is named on the wire even when the host named none,
15
+ * because a blocking ask carries no call id and the phone still needs a handle
16
+ * to answer with.
17
+ * @module dsh-remote-bridge/core/hub
18
+ */
19
+ import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval';
20
+ import type { BridgeConnectionOptions, BridgeTransport, ConnectionAuth } from './connection.ts';
21
+ import { BridgeConnection } from './connection.ts';
22
+ import type { QuestionAnswer, UserQuestionRequestLike } from './questions.ts';
23
+ /**
24
+ * The fields of an approval question this bridge reads. Structural on purpose:
25
+ * the event's own type is not exported from the package root, and only these
26
+ * fields are ever touched.
27
+ */
28
+ export interface ApprovalRequestLike {
29
+ /** The agent asking; its id IS the session id (the event carries no session field). */
30
+ readonly agent: {
31
+ readonly id: string;
32
+ };
33
+ readonly toolName: string;
34
+ readonly displayReason?: {
35
+ readonly en: string;
36
+ readonly [locale: string]: string;
37
+ };
38
+ readonly signal?: AbortSignal;
39
+ }
40
+ /** The summary line a phone shows for one question. */
41
+ export declare function approvalSummary(request: ApprovalRequestLike): string;
42
+ /** The `approval.request` payload one claim is published with. */
43
+ export interface ApprovalRequestPayload {
44
+ readonly sessionId: string;
45
+ readonly id: string;
46
+ readonly summary: string;
47
+ readonly toolName: string;
48
+ }
49
+ /** The bridge's live connections plus the answerer it composes onto the approval chain. */
50
+ export declare class BridgeHub {
51
+ #private;
52
+ constructor(options: BridgeConnectionOptions);
53
+ /** @returns how many paired devices could answer a question right now. */
54
+ get pairedClients(): number;
55
+ /**
56
+ * Register one accepted socket.
57
+ * @param transport - the carrier the connection writes through.
58
+ * @param auth - the device the upgrade proved, when it carried a valid token.
59
+ */
60
+ attach(transport: BridgeTransport, auth?: ConnectionAuth): BridgeConnection;
61
+ /**
62
+ * Forget one connection and abort everything it owns. When it was the last
63
+ * paired device, every pending question is withdrawn: nobody left can answer.
64
+ */
65
+ detach(connection: BridgeConnection): void;
66
+ /**
67
+ * Publish one event to every paired device.
68
+ * @returns how many connections actually took the frame.
69
+ */
70
+ broadcast(topic: string, payload: unknown): number;
71
+ /**
72
+ * Hand one freshly declared connection the questions it can now answer.
73
+ *
74
+ * Without this, a question raised while the phone was reconnecting stays on the
75
+ * host with no card anywhere on the phone: the original broadcast was addressed
76
+ * to clients that had already announced the channel.
77
+ */
78
+ replayQuestions(connection: BridgeConnection): void;
79
+ /**
80
+ * Hand one freshly declared connection the approvals it can now answer.
81
+ *
82
+ * The same shape as {@link replayQuestions} and for the same reason: the first
83
+ * `approval.request` of a question was broadcast to the phones that were
84
+ * connected at that instant, so a phone that reconnected — or a session screen
85
+ * opened after the fact — holds no card and has no other way to learn the
86
+ * question exists. Only unsettled questions are in the registry, so one that
87
+ * was answered, one the bridge timed out and one withdrawn with the last phone
88
+ * cannot be replayed.
89
+ *
90
+ * The replay emits a frame and nothing else: the claim keeps the deadline it
91
+ * was opened with, so re-handing a question never lengthens how long the agent
92
+ * waits for it.
93
+ * @param connection - the connection that just declared its capabilities.
94
+ */
95
+ replayApprovals(connection: BridgeConnection): void;
96
+ /**
97
+ * Publish one event to every paired device that announced a capability.
98
+ * @returns how many connections actually took the frame.
99
+ */
100
+ broadcastTo(capability: string, topic: string, payload: unknown): number;
101
+ /**
102
+ * The body of this plugin's `approval/request` listener.
103
+ * @param request - the pending question.
104
+ * @param next - the rest of the answerer chain.
105
+ * @returns a claimed decision, or whatever the next answerer says.
106
+ */
107
+ approve(request: ApprovalRequestLike, next: () => Promise<ApprovalOutcome>): Promise<ApprovalOutcome>;
108
+ /**
109
+ * The body of this plugin's `user-questions/request` listener.
110
+ *
111
+ * Claimed only while a paired device is connected and the ask names an agent:
112
+ * the payload has no session field of its own, and a question nobody can be
113
+ * told about is not one this bridge may hold. The wire id is the host's own
114
+ * when the ask is timed, and minted here when it is blocking and the host
115
+ * assigned none — either way the phone answers the id it was shown. A claim
116
+ * nobody received is withdrawn at once instead of holding the agent until the
117
+ * host's deadline. For a timed ask the host's own remaining wait travels with
118
+ * the first frame as `expiresAt`, and every later move of that deadline is
119
+ * re-published under the same call id.
120
+ * @param request - the pending question batch.
121
+ * @param next - the rest of the answerer chain.
122
+ * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
123
+ */
124
+ question(request: UserQuestionRequestLike, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer>;
125
+ /** Close every connection and withdraw every question. Idempotent. */
126
+ dispose(): void;
127
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * The bridge's read-only window on the host's background jobs: one minimal
3
+ * projection per job, and the change notification a phone's navigation bar
4
+ * needs to keep a count honest.
5
+ *
6
+ * There is exactly one source of truth here and it is the host's own job
7
+ * registry (`ctx.jobs`, the service the `dsh-api-job-controller` Remote
8
+ * namespace is itself a projection of). This module adds no second store, no
9
+ * polling loop and no invented status vocabulary: it reads `list()`, publishes
10
+ * the host's own `kind` and `status` strings verbatim, and hears changes from
11
+ * the registry's own event stream.
12
+ *
13
+ * Two shapes of the host's API matter to what a phone can be shown:
14
+ *
15
+ * - `list(caller)` is owner-fenced. Naming a session returns that session's own
16
+ * jobs plus every job no session owns; naming no session returns only the
17
+ * unowned jobs. Those are TWO truthful scopes, not one global view, and the
18
+ * host has no global view to offer: a job list is never "every job in the
19
+ * process" unless every job in the process happens to be unowned.
20
+ * - The event stream reports `output` appends as well as lifecycle commits. An
21
+ * append says nothing about the SET, so it is dropped here: this channel
22
+ * never publishes per output byte, which is the whole reason the roster is
23
+ * not a projection of `job/follow`.
24
+ *
25
+ * The types below mirror `@deepseek-ai/dsh-jobs` field for field. That package
26
+ * is the host's, not this one's, so the contract is declared structurally
27
+ * instead of imported — the same rule `questions.ts` and `wire.ts` follow, and
28
+ * what keeps a test double down to the two members actually called.
29
+ * @module dsh-remote-bridge/core/jobs
30
+ */
31
+ /**
32
+ * The slice of the host's `JobView` this bridge reads.
33
+ *
34
+ * Deliberately not the whole view: `output` (the ring's offsets and spill
35
+ * paths), `progress`, `detail` and `outputLimitBytes` are host bookkeeping a
36
+ * phone neither shows nor needs, and a projection that read them would tempt a
37
+ * later change into publishing bytes.
38
+ */
39
+ export interface JobViewLike {
40
+ readonly id: string;
41
+ readonly kind: string;
42
+ readonly label: string;
43
+ /** Owning session; absent for an unowned job, which every caller can see. */
44
+ readonly owner?: string;
45
+ readonly status: string;
46
+ /** Epoch milliseconds. */
47
+ readonly startedAt: number;
48
+ /** Epoch milliseconds; absent while the job is live. */
49
+ readonly finishedAt?: number;
50
+ }
51
+ /** One lifecycle event of the host's event stream, as far as this bridge reads it. */
52
+ export interface JobEventLike {
53
+ /** `output` is the one type this bridge drops without reading further. */
54
+ readonly type: string;
55
+ /** The job's projection after the commit; absent on an `output` append. */
56
+ readonly job?: JobViewLike;
57
+ /** Owning session, carried by `output` events, which carry no projection. */
58
+ readonly owner?: string;
59
+ }
60
+ /** Who a subscription hears about. `all` is what a bridge serving every session asks for. */
61
+ export type JobEventFilterLike = {
62
+ readonly owners: 'all' | 'scope';
63
+ } | {
64
+ readonly owner: string;
65
+ };
66
+ /** The host registry's event stream. */
67
+ export interface JobEventsFace {
68
+ subscribe(filter: JobEventFilterLike, listener: (event: JobEventLike) => void): () => void;
69
+ }
70
+ /**
71
+ * The slice of `ctx.jobs` this package reads.
72
+ *
73
+ * Optional in the plugin's faces for the reason the metadata faces are: the
74
+ * registry is not in this plugin's `inject` list, and a host that composes no
75
+ * job plugin answers `jobs-unavailable` instead of failing to start.
76
+ */
77
+ export interface JobRegistryFace {
78
+ list(caller?: string): readonly JobViewLike[];
79
+ readonly events: JobEventsFace;
80
+ }
81
+ /** Which truthful scope one roster answer covers. */
82
+ export type JobScope = 'session' | 'unowned';
83
+ /**
84
+ * One job in protocol v1 vocabulary: the minimal, stable view.
85
+ *
86
+ * `kind` and `status` are the host's own strings, verbatim — this protocol
87
+ * publishes no enum of its own, so a producer kind or a lifecycle status added
88
+ * in the host crosses unchanged instead of being flattened into a guess.
89
+ * Every optional key is omitted when the host omitted it, never filled in.
90
+ */
91
+ export interface JobRow {
92
+ readonly id: string;
93
+ readonly kind: string;
94
+ readonly status: string;
95
+ /** The host's `label`: its own one-line description, the field a phone renders as the job's title. */
96
+ readonly label?: string;
97
+ /** The host's `owner`, verbatim, under a name that cannot be read as an object. */
98
+ readonly ownerSessionId?: string;
99
+ readonly startedAt?: number;
100
+ readonly finishedAt?: number;
101
+ }
102
+ /**
103
+ * The body of one `jobs.list` answer and of one `jobs.changed` event.
104
+ *
105
+ * One box for both, so a client parses its navigation-bar count out of the same
106
+ * shape it refreshes through, and so a client holding two scopes open can tell
107
+ * whose set moved. `sessionId` is present exactly when the scope is `session`.
108
+ */
109
+ export interface JobsPayload {
110
+ readonly sessionId?: string;
111
+ readonly scope: JobScope;
112
+ readonly jobs: readonly JobRow[];
113
+ }
114
+ /**
115
+ * Coalescing window of one roster publish, in milliseconds.
116
+ *
117
+ * The host registry announces every commit synchronously, so a job that
118
+ * registers, reports progress and settles in one turn is three events for one
119
+ * fact a phone renders as one row. This window folds a burst into a single
120
+ * whole-set read, which is why the topic can never turn into a stream of
121
+ * frames. It matches the job controller's own `observeFlushMs` default, so a
122
+ * browser and a phone watching the same set refresh at the same cadence.
123
+ */
124
+ export declare const JOBS_FLUSH_MS = 100;
125
+ /** Largest number of job rows one payload carries before it risks the frame budget. */
126
+ export declare const JOBS_MAX_ROWS = 200;
127
+ /**
128
+ * Project one host job into the protocol's own fields.
129
+ *
130
+ * Explicitly field by field: an unknown key the host adds later must not reach
131
+ * the wire, and a value of the wrong type is dropped rather than coerced — the
132
+ * key is simply absent, which a client already has to handle.
133
+ * @param job - the host's projection.
134
+ * @returns the minimal row, or undefined when the host gave no usable id.
135
+ */
136
+ export declare function projectJob(job: JobViewLike): JobRow | undefined;
137
+ /**
138
+ * Project a whole host roster.
139
+ * @param jobs - the host's projections.
140
+ * @returns the rows, in the host's own order, bounded by {@link JOBS_MAX_ROWS}.
141
+ */
142
+ export declare function projectJobs(jobs: readonly JobViewLike[]): readonly JobRow[];
143
+ /** The key one scope is subscribed and deduplicated under. */
144
+ export declare function scopeKey(sessionId?: string): string;
145
+ /**
146
+ * Whether one job belongs in one scope's visible set.
147
+ *
148
+ * This is the host's own fence, restated for routing events: a session sees its
149
+ * own jobs plus every unowned one, and the unowned scope sees exactly the jobs
150
+ * no session owns.
151
+ * @param owner - the job's owning session, when it has one.
152
+ * @param sessionId - the scope's session; omitted for the unowned scope.
153
+ */
154
+ export declare function inScope(owner: string | undefined, sessionId?: string): boolean;
155
+ /** Everything one mount's roster was built with. */
156
+ export interface JobRosterOptions {
157
+ /** Resolves the host registry now; called per read, never captured once, so a registry that mounts later is still picked up. */
158
+ readonly faces: () => {
159
+ readonly jobs?: JobRegistryFace | undefined;
160
+ };
161
+ readonly log: (message: string) => void;
162
+ /** Coalescing window; the default is {@link JOBS_FLUSH_MS}. */
163
+ readonly flushMs?: number;
164
+ }
165
+ /**
166
+ * The bridge's background-job reads and change notifications.
167
+ *
168
+ * One instance is built per host mount and shared by every connection, because
169
+ * a job is a fact about the host, not about the device that asked. Scopes are
170
+ * reference-counted by their listeners: a scope nobody watches holds no timer,
171
+ * and the registry subscription itself exists only while at least one scope
172
+ * does. That is what makes "a connection that never asked receives nothing"
173
+ * structural rather than a filter someone has to remember to apply.
174
+ */
175
+ export declare class JobRoster {
176
+ #private;
177
+ constructor(options: JobRosterOptions);
178
+ /** @returns whether this host composes a job registry at all. */
179
+ get available(): boolean;
180
+ /**
181
+ * Read one scope's visible set.
182
+ *
183
+ * Synchronous, because the host registry projects in memory: no stream is
184
+ * opened and no socket is waited on, which is what makes this cheap enough to
185
+ * answer on request and again after every coalesced burst.
186
+ * @param sessionId - the scope's session; omitted for the unowned scope.
187
+ * @returns the payload, or undefined when this host has no job registry.
188
+ */
189
+ read(sessionId?: string): JobsPayload | undefined;
190
+ /**
191
+ * Watch one scope, and publish each coalesced change to every watcher of it.
192
+ *
193
+ * Watching is what a `jobs.list` call earns: a scope nobody listed is never
194
+ * read again, so a phone that declared the capability and asked for nothing
195
+ * receives no `jobs.changed` — the requirement that keeps N open sessions
196
+ * from becoming N sets streaming at a phone that asked for none.
197
+ * @param sessionId - the scope's session; omitted for the unowned scope.
198
+ * @param listener - receives one whole-set payload per coalesced change.
199
+ * @returns the disposer, or undefined when this host has no job registry.
200
+ */
201
+ watch(sessionId: string | undefined, listener: (payload: JobsPayload) => void): (() => void) | undefined;
202
+ /** Stop every watch and clear every timer. Idempotent. */
203
+ dispose(): void;
204
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The gate in front of the bootstrap token endpoint.
3
+ *
4
+ * The socket address alone is NOT a loopback proof on this deployment: a
5
+ * request that arrives over a public tunnel is terminated by the tunnel client
6
+ * on the same machine, so cloudflared connects to the origin from loopback and
7
+ * `req.socket.remoteAddress` reads `127.0.0.1` for a request the whole internet
8
+ * can reach. The reliable discriminator is the `Host` header, which both the
9
+ * market relay and a plain tunnel rewrite to the public hostname before the
10
+ * origin sees the request (`market/worker/src/relay.js:263` sets it to the
11
+ * registered tunnel host). Both conditions must hold, so a forged
12
+ * `remoteAddress` in a test — or a proxy that forgets to rewrite `Host` — still
13
+ * cannot mint a pairing token.
14
+ * @module dsh-remote-bridge/core/loopback
15
+ */
16
+ import type { IncomingMessage } from 'node:http';
17
+ /** Socket addresses that count as "this machine". */
18
+ export declare const LOOPBACK_ADDRESSES: ReadonlySet<string>;
19
+ /** Host header values that count as "this machine". */
20
+ export declare const LOOPBACK_HOSTS: ReadonlySet<string>;
21
+ /** @returns whether a socket's remote address is this machine. */
22
+ export declare function isLoopbackAddress(remoteAddress: string | undefined): boolean;
23
+ /**
24
+ * @returns whether a `Host` header names this machine. The port is ignored;
25
+ * anything that is not a loopback literal — including a public tunnel
26
+ * hostname — is refused.
27
+ */
28
+ export declare function isLoopbackHost(host: string | undefined): boolean;
29
+ /**
30
+ * Why this request may not reach the bootstrap token endpoint, or undefined
31
+ * when it may.
32
+ * @param req - the incoming request.
33
+ * @returns a one-line reason, or undefined.
34
+ */
35
+ export declare function loopbackDenialOf(req: IncomingMessage): string | undefined;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The in-process owner peer every gateway call of this bridge speaks for.
3
+ *
4
+ * The 0.2.1 gateway made `peer` mandatory on every request, and the
5
+ * authorization layer reads only `peer.principal`: `{ kind: 'owner' }` is how
6
+ * host-local code states that the call IS the local user driving their own
7
+ * Host, so the gateway answers it directly instead of running a remote-access
8
+ * decision (only non-owner principals are judged).
9
+ * @module dsh-remote-bridge/core/owner-peer
10
+ */
11
+ import type { Context } from '@deepseek-ai/cordis';
12
+ import type { GatewayPeer } from './wire.ts';
13
+ /**
14
+ * Mint the in-process owner peer this bridge's Host calls speak for.
15
+ *
16
+ * The bridge's security model states that pairing is a full-control
17
+ * credential: a paired device reaches the harness in-process — sessions,
18
+ * prompts, approvals. Protocol v1 is therefore deliberately paired with the
19
+ * one principal that preserves the pre-0.2.1 capability of the bridge's own
20
+ * in-process calls: the owner. That claim is safe only because of WHERE this
21
+ * peer is attached:
22
+ *
23
+ * - Every gateway call a connection can trigger sits behind the bridge's own
24
+ * pairing gate: dispatch answers `unpaired` before any session, approval or
25
+ * roster work, and the three unpaired methods (`hello`, `pair.begin`,
26
+ * `pair.finish`) never invoke the gateway at all. The owner peer crosses to
27
+ * the harness only after a connection proved a device token (or just
28
+ * enrolled one), never for an unpaired one.
29
+ * - No wire field can set a principal: the connection never reads a `peer`
30
+ * or `principal` (or any identity) out of a client frame. The peer is minted
31
+ * here, in-process, fixed at `{ kind: 'owner' }`, and a client that names
32
+ * one in its payload is ignored — the call still speaks for this peer.
33
+ *
34
+ * `interactions` stays `'none'`: the bridge only invokes unary methods and
35
+ * opens the `session/follow` business stream. The gateway's interactions
36
+ * check gates exactly the forwarded-event endpoints (opening an event stream,
37
+ * answering a waterfall), which this caller never touches; an `'answer'`
38
+ * peer would additionally receive forwarded Host events, a capability the
39
+ * bridge neither needs nor wants — approvals reach devices through this
40
+ * plugin's own `approval/request` listener and the protocol's own events, not
41
+ * through a Typert forwarded-event subscription.
42
+ *
43
+ * The peer's signal aborts once `ctx` disposes, so calls and streams opened
44
+ * for it end with the plugin fiber, and `dispose()` is idempotent with racing
45
+ * calls sharing one completion. The id carries no credential — the protocol
46
+ * fixes `principal` as the only identity persisted in a session log — so a
47
+ * fresh unique id per mount is sufficient.
48
+ */
49
+ export declare function createOwnerPeer(ctx: Context): GatewayPeer;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * In-memory bootstrap tokens and pairing nonces.
3
+ *
4
+ * Both are one-shot and short-lived, and neither is ever persisted: a token an
5
+ * operator reads off the Host log is only useful while its 30 s window is open,
6
+ * and a restart invalidating every pending pairing is the desired behavior.
7
+ * @module dsh-remote-bridge/core/pairing
8
+ */
9
+ /** Lifetime of one bootstrap token handed to the operator's phone. */
10
+ export declare const BOOTSTRAP_TOKEN_TTL_MS = 30000;
11
+ /** Lifetime of one pairing nonce, from `pair.begin` to `pair.finish`. */
12
+ export declare const PAIR_NONCE_TTL_MS = 60000;
13
+ /** Entropy of one bootstrap token. */
14
+ export declare const BOOTSTRAP_TOKEN_BYTES = 32;
15
+ /** Entropy of one pairing nonce. */
16
+ export declare const PAIR_NONCE_BYTES = 16;
17
+ /** A minted one-shot secret and the instant it stops being accepted. */
18
+ export interface PairingTicket {
19
+ readonly value: string;
20
+ readonly expiresAt: number;
21
+ }
22
+ export interface PairingServiceOptions {
23
+ /** Clock, injectable so expiry is tested without sleeping. */
24
+ readonly now?: () => number;
25
+ readonly tokenTtlMs?: number;
26
+ readonly nonceTtlMs?: number;
27
+ /** Secret source, injectable so a test can pin the value it will present. */
28
+ readonly random?: (byteLength: number) => string;
29
+ }
30
+ /**
31
+ * The two one-shot secrets of the pairing handshake.
32
+ *
33
+ * `issueToken` is called by the loopback-only route an operator reaches from
34
+ * the Host itself; `beginPairing` consumes that token and mints the nonce the
35
+ * phone signs; `consumeNonce` closes the handshake. Consumption happens BEFORE
36
+ * any signature check in the caller, so a wrong signature still burns the
37
+ * nonce: a brute-force loop cannot reuse one challenge.
38
+ */
39
+ export declare class PairingService {
40
+ #private;
41
+ constructor(options?: PairingServiceOptions);
42
+ /** Mint one bootstrap token, valid until its own expiry. */
43
+ issueToken(): PairingTicket;
44
+ /**
45
+ * Consume one bootstrap token.
46
+ * @returns whether the token was live; a consumed or expired token is gone.
47
+ */
48
+ consumeToken(token: string): boolean;
49
+ /** Mint one pairing nonce for a connection that just consumed a valid token. */
50
+ issueNonce(): PairingTicket;
51
+ /**
52
+ * Consume one pairing nonce.
53
+ * @returns whether the nonce was live; a consumed or expired nonce is gone.
54
+ */
55
+ consumeNonce(nonce: string): boolean;
56
+ /** @returns how many tokens and nonces are currently acceptable, for tests and diagnostics. */
57
+ get pending(): {
58
+ tokens: number;
59
+ nonces: number;
60
+ };
61
+ }