@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.7
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.
- package/LICENSE +202 -0
- package/README.i18n.yaml +6 -0
- package/README.md +243 -2
- package/README.zh.md +244 -0
- package/cordis.patch.yml +17 -0
- package/lib/client.js +1830 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +3744 -0
- package/lib/types/client/PairEntry.d.ts +16 -0
- package/lib/types/client/PairPanel.d.ts +55 -0
- package/lib/types/client/icons.d.ts +18 -0
- package/lib/types/client/index.d.ts +35 -0
- package/lib/types/client/locales.d.ts +42 -0
- package/lib/types/client/pair-token.d.ts +73 -0
- package/lib/types/client/semantic.d.ts +28 -0
- package/lib/types/core/approvals.d.ts +75 -0
- package/lib/types/core/connection.d.ts +119 -0
- package/lib/types/core/crypto.d.ts +48 -0
- package/lib/types/core/devices.d.ts +72 -0
- package/lib/types/core/dsh-frames.d.ts +181 -0
- package/lib/types/core/envelope.d.ts +98 -0
- package/lib/types/core/gateway-errors.d.ts +49 -0
- package/lib/types/core/hub.d.ts +101 -0
- package/lib/types/core/loopback.d.ts +35 -0
- package/lib/types/core/owner-peer.d.ts +49 -0
- package/lib/types/core/pairing.d.ts +61 -0
- package/lib/types/core/protocol.d.ts +89 -0
- package/lib/types/core/questions.d.ts +246 -0
- package/lib/types/core/session-meta.d.ts +105 -0
- package/lib/types/core/session-permissions.d.ts +134 -0
- package/lib/types/core/wire.d.ts +115 -0
- package/lib/types/core/ws-frames.d.ts +61 -0
- package/lib/types/host/dsh-home.d.ts +16 -0
- package/lib/types/host/pair-origin.d.ts +44 -0
- package/lib/types/host/routes.d.ts +27 -0
- package/lib/types/host/websocket.d.ts +104 -0
- package/lib/types/index.d.ts +40 -0
- package/package.json +87 -3
- package/src/client/PairEntry.tsx +151 -0
- package/src/client/PairPanel.tsx +183 -0
- package/src/client/icons.tsx +72 -0
- package/src/client/index.ts +81 -0
- package/src/client/locales.ts +72 -0
- package/src/client/pair-token.ts +104 -0
- package/src/client/panel.module.css +344 -0
- package/src/client/semantic.ts +37 -0
- package/src/core/approvals.ts +142 -0
- package/src/core/connection.ts +1090 -0
- package/src/core/crypto.ts +113 -0
- package/src/core/devices.ts +209 -0
- package/src/core/dsh-frames.ts +486 -0
- package/src/core/envelope.ts +173 -0
- package/src/core/gateway-errors.ts +92 -0
- package/src/core/hub.ts +238 -0
- package/src/core/loopback.ts +60 -0
- package/src/core/owner-peer.ts +70 -0
- package/src/core/pairing.ts +113 -0
- package/src/core/protocol.ts +120 -0
- package/src/core/questions.ts +454 -0
- package/src/core/session-meta.ts +176 -0
- package/src/core/session-permissions.ts +266 -0
- package/src/core/wire.ts +155 -0
- package/src/core/ws-frames.ts +125 -0
- package/src/css-modules.d.ts +6 -0
- package/src/host/dsh-home.ts +42 -0
- package/src/host/pair-origin.ts +77 -0
- package/src/host/routes.ts +85 -0
- package/src/host/websocket.ts +325 -0
- package/src/index.ts +205 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The frozen protocol surface: method names, topic names, refusal codes, and
|
|
3
|
+
* the one authorization rule the dispatcher enforces before any method runs.
|
|
4
|
+
* @module dsh-remote-bridge/core/protocol
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Client-callable methods of protocol v1. */
|
|
8
|
+
export const METHOD_HELLO = 'hello'
|
|
9
|
+
export const METHOD_SESSION_LIST = 'session.list'
|
|
10
|
+
export const METHOD_SESSION_TITLES = 'session.titles'
|
|
11
|
+
export const METHOD_SESSION_SNAPSHOT = 'session.snapshot'
|
|
12
|
+
export const METHOD_SESSION_HISTORY = 'session.history'
|
|
13
|
+
export const METHOD_SESSION_PROMPT = 'session.prompt'
|
|
14
|
+
export const METHOD_SESSION_INTERRUPT = 'session.interrupt'
|
|
15
|
+
export const METHOD_SESSION_ATTACHMENT = 'session.attachment'
|
|
16
|
+
export const METHOD_SESSION_PERMISSIONS = 'session.permissions'
|
|
17
|
+
export const METHOD_SESSION_SET_PERMISSION = 'session.setPermission'
|
|
18
|
+
export const METHOD_SESSION_MODELS = 'session.models'
|
|
19
|
+
export const METHOD_SESSION_SET_MODEL = 'session.setModel'
|
|
20
|
+
export const METHOD_PAIR_BEGIN = 'pair.begin'
|
|
21
|
+
export const METHOD_PAIR_FINISH = 'pair.finish'
|
|
22
|
+
export const METHOD_APPROVAL_RESOLVE = 'approval.resolve'
|
|
23
|
+
export const METHOD_QUESTION_ANSWER = 'question.answer'
|
|
24
|
+
|
|
25
|
+
/** Server-pushed topics of protocol v1. */
|
|
26
|
+
export const TOPIC_SESSION_DELTA = 'session.delta'
|
|
27
|
+
export const TOPIC_APPROVAL_REQUEST = 'approval.request'
|
|
28
|
+
export const TOPIC_QUESTION_REQUEST = 'question.request'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Capability a client declares in `hello`'s `cap` array to ask for a trimmed
|
|
32
|
+
* `session.snapshot` baseline. A client that does not declare it — including
|
|
33
|
+
* every client written before this capability existed — is served exactly the
|
|
34
|
+
* baseline protocol v1 always served.
|
|
35
|
+
*/
|
|
36
|
+
export const CAP_SESSION_SNAPSHOT_TRIM = 'session.snapshot.trim.v1'
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Capability a client declares in `hello`'s `cap` array to have
|
|
40
|
+
* `session.snapshot` answer with one bounded page instead of the whole opening
|
|
41
|
+
* window. Declaring it is what makes an opening screen cost one page rather
|
|
42
|
+
* than a whole session; a client that does not declare it — including every
|
|
43
|
+
* client written before this capability existed — receives byte for byte the
|
|
44
|
+
* snapshot protocol v1 always served.
|
|
45
|
+
*/
|
|
46
|
+
export const CAP_SESSION_SNAPSHOT_PAGE = 'session.snapshot.page.v1'
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Capability a client declares in `hello`'s `cap` array to be shown the
|
|
50
|
+
* host's pending user questions and to answer them with `question.answer`.
|
|
51
|
+
*
|
|
52
|
+
* Declaring it is what makes `question.request` reachable and what makes the
|
|
53
|
+
* method part of that client's protocol at all: a client that does not declare
|
|
54
|
+
* it — including every client written before this channel existed — receives no
|
|
55
|
+
* such event, and its `question.answer` is refused as an unknown method,
|
|
56
|
+
* exactly as that frame was refused before.
|
|
57
|
+
*/
|
|
58
|
+
export const CAP_QUESTIONS = 'questions.v1'
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Methods an unpaired connection may still call: the handshake itself and the
|
|
62
|
+
* two pairing steps. Everything else answers `unpaired` — a caller can pair
|
|
63
|
+
* without a device token, but cannot touch a session without one.
|
|
64
|
+
*/
|
|
65
|
+
export const UNPAIRED_METHODS: ReadonlySet<string> = new Set([
|
|
66
|
+
METHOD_HELLO,
|
|
67
|
+
METHOD_PAIR_BEGIN,
|
|
68
|
+
METHOD_PAIR_FINISH,
|
|
69
|
+
])
|
|
70
|
+
|
|
71
|
+
/** Every method this protocol version serves. */
|
|
72
|
+
export const KNOWN_METHODS: ReadonlySet<string> = new Set([
|
|
73
|
+
METHOD_HELLO,
|
|
74
|
+
METHOD_SESSION_LIST,
|
|
75
|
+
METHOD_SESSION_TITLES,
|
|
76
|
+
METHOD_SESSION_SNAPSHOT,
|
|
77
|
+
METHOD_SESSION_HISTORY,
|
|
78
|
+
METHOD_SESSION_PROMPT,
|
|
79
|
+
METHOD_SESSION_INTERRUPT,
|
|
80
|
+
METHOD_SESSION_ATTACHMENT,
|
|
81
|
+
METHOD_SESSION_PERMISSIONS,
|
|
82
|
+
METHOD_SESSION_SET_PERMISSION,
|
|
83
|
+
METHOD_SESSION_MODELS,
|
|
84
|
+
METHOD_SESSION_SET_MODEL,
|
|
85
|
+
METHOD_PAIR_BEGIN,
|
|
86
|
+
METHOD_PAIR_FINISH,
|
|
87
|
+
METHOD_APPROVAL_RESOLVE,
|
|
88
|
+
METHOD_QUESTION_ANSWER,
|
|
89
|
+
])
|
|
90
|
+
|
|
91
|
+
/** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
|
|
92
|
+
export const CODE_UNPAIRED = 'unpaired'
|
|
93
|
+
export const CODE_UNKNOWN_METHOD = 'unknown-method'
|
|
94
|
+
export const CODE_INVALID_ARGS = 'invalid-args'
|
|
95
|
+
export const CODE_PROTO_UNSUPPORTED = 'proto-unsupported'
|
|
96
|
+
export const CODE_TOKEN_INVALID = 'token-invalid'
|
|
97
|
+
export const CODE_NONCE_INVALID = 'nonce-invalid'
|
|
98
|
+
export const CODE_SIGNATURE_INVALID = 'signature-invalid'
|
|
99
|
+
export const CODE_APPROVAL_UNKNOWN = 'approval-unknown'
|
|
100
|
+
/**
|
|
101
|
+
* The bridge does not hold the named question: it never claimed that call id, it
|
|
102
|
+
* already answered it, or the host no longer holds it as answerable. Host
|
|
103
|
+
* failures crossing this method keep their own codes instead.
|
|
104
|
+
*/
|
|
105
|
+
export const CODE_QUESTION_UNKNOWN = 'question-unknown'
|
|
106
|
+
export const CODE_SNAPSHOT_UNAVAILABLE = 'snapshot-unavailable'
|
|
107
|
+
export const CODE_SNAPSHOT_TOO_LARGE = 'snapshot-too-large'
|
|
108
|
+
export const CODE_INTERNAL = 'internal'
|
|
109
|
+
|
|
110
|
+
/** Protocol version this package speaks. */
|
|
111
|
+
export const PROTO = 1
|
|
112
|
+
/** Minor version this package speaks. */
|
|
113
|
+
export const MINOR = 0
|
|
114
|
+
/** `server` field of the hello response. */
|
|
115
|
+
export const SERVER_ID = 'dsh-remote-bridge'
|
|
116
|
+
|
|
117
|
+
/** Exact route path of the bridge's WebSocket endpoint. */
|
|
118
|
+
export const WS_PATH = '/ios/v1'
|
|
119
|
+
/** Exact route path of the loopback-only bootstrap token endpoint. */
|
|
120
|
+
export const PAIR_TOKEN_PATH = '/remote-bridge/pair/token'
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge's claims on `user-questions/request`: which questions a phone may
|
|
3
|
+
* answer, and the one path an answer travels back into the host.
|
|
4
|
+
*
|
|
5
|
+
* The host asks in two shapes, and they are two shapes of the SAME channel:
|
|
6
|
+
*
|
|
7
|
+
* - a timed ask (`askTimed`, the tool schema that declares a `timeout`) rides
|
|
8
|
+
* the waterfall with a `wait.callId`. While it is open the bridge HOLDS the
|
|
9
|
+
* host's promise, so the answer is that promise's resolution — exactly what an
|
|
10
|
+
* in-process answerer does, and the only way an open question can be answered
|
|
11
|
+
* at all (`ctx.userQuestions.answer` refuses an open question by returning
|
|
12
|
+
* false). Once the host's own deadline released the model, the ask is gone and
|
|
13
|
+
* the question can only be answered through the host's Remote `answer`, which
|
|
14
|
+
* steers the reply into the agent as a queued user message.
|
|
15
|
+
* - a blocking ask (the schema without `timeout`, which is the `ask_user_question`
|
|
16
|
+
* a phone actually shows) carries NO `wait` at all, and the host assigns no
|
|
17
|
+
* call id. It is still claimed, and the bridge mints its own opaque id for the
|
|
18
|
+
* wire — resolving the promise it holds needs no host identity at all. Such a
|
|
19
|
+
* question is only ever `open`: the host has no deadline for it, so it never
|
|
20
|
+
* becomes `continued` and never takes the Remote `answer` path.
|
|
21
|
+
*
|
|
22
|
+
* Every claim is one record keyed by the id published on the wire, so an answer
|
|
23
|
+
* that arrives late still lands, and an answer for an id this bridge never
|
|
24
|
+
* claimed is refused instead of being forwarded to the host blindly.
|
|
25
|
+
*
|
|
26
|
+
* The bridge invents no deadline, for either shape: a timed ask's deadline is
|
|
27
|
+
* the host's own and is only propagated here, and a blocking ask simply has
|
|
28
|
+
* none — a phone that never answers leaves it open for as long as the asker
|
|
29
|
+
* waits. It also never fabricates a refusal: a question nobody can answer is
|
|
30
|
+
* delegated to `next()`, never answered with a decision the operator did not
|
|
31
|
+
* make.
|
|
32
|
+
*
|
|
33
|
+
* The types below mirror `@deepseek-ai/dsh-user-questions` field for field. The
|
|
34
|
+
* package is not a dependency of this one (it is the host's, not the bridge's),
|
|
35
|
+
* so the contract is declared locally instead of imported.
|
|
36
|
+
* @module dsh-remote-bridge/core/questions
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { randomBase64Url } from './crypto.ts'
|
|
40
|
+
import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
|
|
41
|
+
import { CODE_INTERNAL, CODE_QUESTION_UNKNOWN } from './protocol.ts'
|
|
42
|
+
import { wireArgs, type BridgeGateway, type GatewayPeer } from './wire.ts'
|
|
43
|
+
|
|
44
|
+
/** One selectable answer offered by the asker. */
|
|
45
|
+
export interface QuestionOption {
|
|
46
|
+
readonly label: string
|
|
47
|
+
readonly description?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One question, in the field names protocol v1 publishes. */
|
|
51
|
+
export interface QuestionItem {
|
|
52
|
+
readonly id: string
|
|
53
|
+
readonly question: string
|
|
54
|
+
readonly header?: string
|
|
55
|
+
readonly detail?: string
|
|
56
|
+
readonly options?: readonly QuestionOption[]
|
|
57
|
+
readonly multiSelect?: boolean
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One item of the answer batch. */
|
|
61
|
+
export interface QuestionAnswerItem {
|
|
62
|
+
readonly id: string
|
|
63
|
+
readonly selected: readonly string[]
|
|
64
|
+
readonly custom?: string
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The whole answer batch the host's ask is settled with. */
|
|
68
|
+
export interface QuestionAnswer {
|
|
69
|
+
readonly answers: readonly QuestionAnswerItem[]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether a question still holds the foreground ask, or only its late reply. */
|
|
73
|
+
/**
|
|
74
|
+
* `open` while the ask is still waiting, `continued` once the host's foreground
|
|
75
|
+
* wait ended but a late answer can still be steered in, and `settled` as the
|
|
76
|
+
* one-way notice that the phone's card is over — the host's own UI answered it or
|
|
77
|
+
* the last paired client left. `settled` is published, never held.
|
|
78
|
+
*/
|
|
79
|
+
export type QuestionState = 'open' | 'continued' | 'settled'
|
|
80
|
+
|
|
81
|
+
/** `question.request`'s payload, as frozen by the contract. */
|
|
82
|
+
export interface QuestionRequestPayload {
|
|
83
|
+
readonly sessionId: string
|
|
84
|
+
readonly callId: string
|
|
85
|
+
readonly state: QuestionState
|
|
86
|
+
readonly questions: readonly QuestionItem[]
|
|
87
|
+
/** Epoch milliseconds; absent when the host published no readable deadline. */
|
|
88
|
+
readonly expiresAt?: number
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The fields of a host question request this bridge reads.
|
|
93
|
+
*
|
|
94
|
+
* Structural on purpose, for the reason the approval listener is: the event's
|
|
95
|
+
* own type is not reachable from here, and only these fields are ever touched.
|
|
96
|
+
* `wait` is the host's own field for the timed schema — it is what carries the
|
|
97
|
+
* call id, and it is absent for a legacy blocking ask, which this bridge
|
|
98
|
+
* therefore delegates rather than claims.
|
|
99
|
+
*/
|
|
100
|
+
export interface UserQuestionRequestLike {
|
|
101
|
+
readonly questions: readonly QuestionItem[]
|
|
102
|
+
/** The agent asking; its id IS the session id (the event carries no session field). */
|
|
103
|
+
readonly agent?: { readonly id: string }
|
|
104
|
+
readonly signal?: AbortSignal
|
|
105
|
+
readonly wait?: { readonly callId?: string; readonly timed?: boolean }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The identity and content of one claim, as the hub publishes it. */
|
|
109
|
+
export interface ClaimedQuestionView {
|
|
110
|
+
readonly sessionId: string
|
|
111
|
+
readonly callId: string
|
|
112
|
+
readonly questions: readonly QuestionItem[]
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** One claim the hub holds while the host's ask is still open. */
|
|
116
|
+
export interface ClaimedQuestion extends ClaimedQuestionView {
|
|
117
|
+
/** The host's ask: the phone's answer, or whatever the next answerer says. */
|
|
118
|
+
readonly answer: Promise<QuestionAnswer>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** What one `question.answer` produced: acknowledgement, or the refusal to send. */
|
|
122
|
+
export type QuestionReply = { readonly ok: true } | { readonly ok: false; readonly code: string; readonly msg: string }
|
|
123
|
+
|
|
124
|
+
/** The code the host raises when its own foreground deadline ends the ask. */
|
|
125
|
+
export const QUESTION_TIMED_OUT_CODE = 'ASK_TIMED_OUT'
|
|
126
|
+
/**
|
|
127
|
+
* Prefix of a call id this bridge minted for a question the host never named.
|
|
128
|
+
*
|
|
129
|
+
* A blocking ask has no host call id, but the phone still needs one opaque
|
|
130
|
+
* handle to answer with. The prefix keeps that handle in a namespace of its own,
|
|
131
|
+
* so a minted id can never be mistaken for a host `ToolCallId` — by this bridge
|
|
132
|
+
* or by anything reading the wire.
|
|
133
|
+
*/
|
|
134
|
+
export const MINTED_CALL_ID_PREFIX = 'bridge:'
|
|
135
|
+
/** Entropy of one minted call id. */
|
|
136
|
+
export const MINTED_CALL_ID_BYTES = 16
|
|
137
|
+
|
|
138
|
+
export interface OpenQuestionInput {
|
|
139
|
+
readonly sessionId: string
|
|
140
|
+
/** The id published on the wire: the host's own, or one this bridge minted. */
|
|
141
|
+
readonly callId: string
|
|
142
|
+
/**
|
|
143
|
+
* Whether `callId` is the host's own tool call identity.
|
|
144
|
+
*
|
|
145
|
+
* Only a hosted claim can ever be `continued`: the state is what a host
|
|
146
|
+
* deadline produces, and the late-answer path needs a real call id to address.
|
|
147
|
+
*/
|
|
148
|
+
readonly hosted: boolean
|
|
149
|
+
readonly questions: readonly QuestionItem[]
|
|
150
|
+
/** The rest of the answerer chain, used when the bridge withdraws. */
|
|
151
|
+
readonly next: () => Promise<QuestionAnswer>
|
|
152
|
+
/** The host's own cancellation lifetime for this ask. */
|
|
153
|
+
readonly signal?: AbortSignal
|
|
154
|
+
/** Called once when the host's deadline released the model but the question stayed answerable. */
|
|
155
|
+
readonly onContinued?: (question: ClaimedQuestionView) => void
|
|
156
|
+
/**
|
|
157
|
+
* Called when the claim leaves this bridge without the phone answering it — the
|
|
158
|
+
* host's own UI answered first, or the last paired client went away. The phone
|
|
159
|
+
* still holds a card for it and has to be told, or it keeps offering a question
|
|
160
|
+
* that no longer exists.
|
|
161
|
+
*/
|
|
162
|
+
readonly onSettled?: (question: ClaimedQuestionView) => void
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** One live claim, with every path that settles it. */
|
|
166
|
+
interface Claim {
|
|
167
|
+
readonly sessionId: string
|
|
168
|
+
readonly callId: string
|
|
169
|
+
readonly hosted: boolean
|
|
170
|
+
readonly questions: readonly QuestionItem[]
|
|
171
|
+
state: QuestionState
|
|
172
|
+
readonly settle: (answer: QuestionAnswer) => void
|
|
173
|
+
readonly fail: (reason: unknown) => void
|
|
174
|
+
readonly delegate: () => void
|
|
175
|
+
readonly detach: () => void
|
|
176
|
+
readonly onContinued: ((question: ClaimedQuestionView) => void) | undefined
|
|
177
|
+
/** Tells the phone its card is over; set from the input's `onSettled`. */
|
|
178
|
+
readonly notifySettled: () => void
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface QuestionClaimsOptions {
|
|
182
|
+
readonly gateway: BridgeGateway
|
|
183
|
+
/** The in-process owner peer every gateway call speaks for; the bridge never derives it from a client frame. */
|
|
184
|
+
readonly peer: GatewayPeer
|
|
185
|
+
readonly log: (message: string) => void
|
|
186
|
+
/** Id source, injectable so a test can answer the exact id it was given. */
|
|
187
|
+
readonly random?: (byteLength: number) => string
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** @returns whether a failure is the host's own foreground deadline. */
|
|
191
|
+
function isTimedOut(reason: unknown): boolean {
|
|
192
|
+
return (reason as { code?: unknown } | null | undefined)?.code === QUESTION_TIMED_OUT_CODE
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Project a host question into the contract's own fields.
|
|
197
|
+
*
|
|
198
|
+
* Explicitly field by field: the host's items carry presentation intents this
|
|
199
|
+
* protocol does not publish, and a payload that grew a key the contract does
|
|
200
|
+
* not declare would be a wire change nobody agreed to.
|
|
201
|
+
* @param items - the host's question batch.
|
|
202
|
+
* @returns the same questions in protocol vocabulary.
|
|
203
|
+
*/
|
|
204
|
+
export function projectQuestions(items: readonly QuestionItem[]): readonly QuestionItem[] {
|
|
205
|
+
return items.map(item => ({
|
|
206
|
+
id: item.id,
|
|
207
|
+
question: item.question,
|
|
208
|
+
...(item.header === undefined ? {} : { header: item.header }),
|
|
209
|
+
...(item.detail === undefined ? {} : { detail: item.detail }),
|
|
210
|
+
...(item.options === undefined
|
|
211
|
+
? {}
|
|
212
|
+
: {
|
|
213
|
+
options: item.options.map(option => ({
|
|
214
|
+
label: option.label,
|
|
215
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
216
|
+
})),
|
|
217
|
+
}),
|
|
218
|
+
...(item.multiSelect === undefined ? {} : { multiSelect: item.multiSelect }),
|
|
219
|
+
}))
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Pending questions of one bridge process.
|
|
224
|
+
*
|
|
225
|
+
* One record per id published on the wire — the host's own, or one minted here
|
|
226
|
+
* for a blocking ask — and one settle for every path (answer, the host's
|
|
227
|
+
* deadline, the last phone leaving, bridge unload), so a question can never be
|
|
228
|
+
* settled twice and a withdrawn claim leaves no abort listener behind.
|
|
229
|
+
*/
|
|
230
|
+
export class QuestionClaims {
|
|
231
|
+
readonly #gateway: BridgeGateway
|
|
232
|
+
readonly #peer: GatewayPeer
|
|
233
|
+
readonly #log: (message: string) => void
|
|
234
|
+
readonly #random: (byteLength: number) => string
|
|
235
|
+
readonly #claims = new Map<string, Claim>()
|
|
236
|
+
|
|
237
|
+
constructor(options: QuestionClaimsOptions) {
|
|
238
|
+
this.#gateway = options.gateway
|
|
239
|
+
this.#peer = options.peer
|
|
240
|
+
this.#log = options.log
|
|
241
|
+
this.#random = options.random ?? randomBase64Url
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** @returns how many questions this bridge currently holds. */
|
|
245
|
+
get size(): number {
|
|
246
|
+
return this.#claims.size
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Mint the opaque wire id of a question the host never named.
|
|
251
|
+
* @returns an id in this bridge's own namespace.
|
|
252
|
+
*/
|
|
253
|
+
mintCallId(): string {
|
|
254
|
+
return `${MINTED_CALL_ID_PREFIX}${this.#random(MINTED_CALL_ID_BYTES)}`
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** @returns the state of one claimed call, or undefined when it is not claimed. */
|
|
258
|
+
stateOf(callId: string): QuestionState | undefined {
|
|
259
|
+
return this.#claims.get(callId)?.state
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Claim one question.
|
|
264
|
+
* @param input - session identity, wire call id and its provenance, questions, the rest of the chain, and the host's lifetime.
|
|
265
|
+
* @returns the claim the hub publishes, or undefined when this call id is already claimed.
|
|
266
|
+
*/
|
|
267
|
+
open(input: OpenQuestionInput): ClaimedQuestion | undefined {
|
|
268
|
+
if (this.#claims.has(input.callId)) return undefined
|
|
269
|
+
let settle: (answer: QuestionAnswer) => void = () => undefined
|
|
270
|
+
let fail: (reason: unknown) => void = () => undefined
|
|
271
|
+
const answer = new Promise<QuestionAnswer>((resolve, reject) => {
|
|
272
|
+
settle = resolve
|
|
273
|
+
fail = reject
|
|
274
|
+
})
|
|
275
|
+
const signal = input.signal
|
|
276
|
+
const onAbort = (): void => { this.#expire(input.callId, signal?.reason) }
|
|
277
|
+
// The rest of the answerer chain is the host's own UI, and it must keep
|
|
278
|
+
// showing the question: claiming here used to swallow it. Started once, at
|
|
279
|
+
// claim time, so both surfaces display it and the first answer settles it.
|
|
280
|
+
// A rejection is not a verdict — the phone may still answer — so it is
|
|
281
|
+
// remembered for a later withdraw instead of failing the claim now.
|
|
282
|
+
let nextStarted: Promise<QuestionAnswer> | undefined
|
|
283
|
+
const startNext = (): Promise<QuestionAnswer> => {
|
|
284
|
+
if (nextStarted === undefined) {
|
|
285
|
+
try {
|
|
286
|
+
nextStarted = input.next()
|
|
287
|
+
} catch (error) {
|
|
288
|
+
nextStarted = Promise.reject(error)
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return nextStarted
|
|
292
|
+
}
|
|
293
|
+
const record: Claim = {
|
|
294
|
+
sessionId: input.sessionId,
|
|
295
|
+
callId: input.callId,
|
|
296
|
+
hosted: input.hosted,
|
|
297
|
+
questions: projectQuestions(input.questions),
|
|
298
|
+
state: 'open',
|
|
299
|
+
notifySettled: (): void => {
|
|
300
|
+
input.onSettled?.({ sessionId: input.sessionId, callId: input.callId, questions: projectQuestions(input.questions) })
|
|
301
|
+
},
|
|
302
|
+
settle,
|
|
303
|
+
fail,
|
|
304
|
+
delegate: (): void => {
|
|
305
|
+
void startNext().then(settle, fail)
|
|
306
|
+
},
|
|
307
|
+
detach: (): void => { signal?.removeEventListener('abort', onAbort) },
|
|
308
|
+
onContinued: input.onContinued,
|
|
309
|
+
}
|
|
310
|
+
this.#claims.set(input.callId, record)
|
|
311
|
+
// The rest of the chain is NOT started here. A connected phone takes the
|
|
312
|
+
// question on its own, and the host's own panel would otherwise stay open
|
|
313
|
+
// after the phone answered it — the bridge has no way to close that panel.
|
|
314
|
+
// A phone that is absent, or a claim that is withdrawn, still delegates.
|
|
315
|
+
if (signal?.aborted === true) onAbort()
|
|
316
|
+
else signal?.addEventListener('abort', onAbort, { once: true })
|
|
317
|
+
return { sessionId: record.sessionId, callId: record.callId, questions: record.questions, answer }
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Answer one claimed question.
|
|
322
|
+
*
|
|
323
|
+
* An open claim is settled by resolving the host's own ask; a continued one
|
|
324
|
+
* only through the host's Remote `answer`, whose result and failures cross
|
|
325
|
+
* unchanged.
|
|
326
|
+
* @param sessionId - the session the client believes owns the question.
|
|
327
|
+
* @param callId - the wire call id the client was shown.
|
|
328
|
+
* @param answer - the complete answer batch.
|
|
329
|
+
*/
|
|
330
|
+
async answer(sessionId: string, callId: string, answer: QuestionAnswer): Promise<QuestionReply> {
|
|
331
|
+
const record = this.#claims.get(callId)
|
|
332
|
+
if (record === undefined || record.sessionId !== sessionId) {
|
|
333
|
+
return { ok: false, code: CODE_QUESTION_UNKNOWN, msg: 'the question is unknown, already answered or not this bridge\'s to answer' }
|
|
334
|
+
}
|
|
335
|
+
if (record.state === 'open') {
|
|
336
|
+
this.#claims.delete(callId)
|
|
337
|
+
record.detach()
|
|
338
|
+
record.settle({ answers: answer.answers })
|
|
339
|
+
return { ok: true }
|
|
340
|
+
}
|
|
341
|
+
// Unreachable today: only a host deadline marks a claim continued, and only a
|
|
342
|
+
// hosted claim can reach one. Kept as the invariant an answer path must hold.
|
|
343
|
+
if (!record.hosted) {
|
|
344
|
+
return { ok: false, code: CODE_QUESTION_UNKNOWN, msg: 'the question is not one the host can take a late answer for' }
|
|
345
|
+
}
|
|
346
|
+
return await this.#forward(sessionId, callId, answer)
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Every claim still waiting on an answer.
|
|
351
|
+
*
|
|
352
|
+
* A phone that connects after the question was raised never saw the original
|
|
353
|
+
* broadcast, so it has to be handed the live claims again — otherwise the
|
|
354
|
+
* question sits on the host with an answerable card nowhere.
|
|
355
|
+
*/
|
|
356
|
+
openClaims(): readonly ClaimedQuestionView[] {
|
|
357
|
+
return [...this.#claims.values()].map((record) => ({
|
|
358
|
+
sessionId: record.sessionId,
|
|
359
|
+
callId: record.callId,
|
|
360
|
+
questions: record.questions,
|
|
361
|
+
}))
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Withdraw the named questions, delegating each to the next answerer.
|
|
366
|
+
* @returns how many were still open and therefore delegated.
|
|
367
|
+
*/
|
|
368
|
+
withdraw(callIds: readonly string[]): number {
|
|
369
|
+
let withdrawn = 0
|
|
370
|
+
for (const callId of callIds) {
|
|
371
|
+
const record = this.#claims.get(callId)
|
|
372
|
+
if (record === undefined) continue
|
|
373
|
+
this.#claims.delete(callId)
|
|
374
|
+
record.detach()
|
|
375
|
+
record.notifySettled()
|
|
376
|
+
if (record.state !== 'open') continue
|
|
377
|
+
record.delegate()
|
|
378
|
+
withdrawn += 1
|
|
379
|
+
}
|
|
380
|
+
return withdrawn
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Withdraw every claim, delegating each open question to the next answerer.
|
|
385
|
+
* Called when the last paired phone goes away and when the bridge unloads: a
|
|
386
|
+
* question nobody can answer must not hold the agent until its own deadline.
|
|
387
|
+
* @returns how many questions were still open.
|
|
388
|
+
*/
|
|
389
|
+
withdrawAll(): number {
|
|
390
|
+
return this.withdraw([...this.#claims.keys()])
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Ask the host to steer one continued answer into its agent.
|
|
395
|
+
*
|
|
396
|
+
* A host that answers `false` no longer holds the question; it is reported,
|
|
397
|
+
* not swallowed, and the claim is kept so a client that answered a beat too
|
|
398
|
+
* early can retry once the host has folded the pending result.
|
|
399
|
+
*/
|
|
400
|
+
async #forward(sessionId: string, callId: string, answer: QuestionAnswer): Promise<QuestionReply> {
|
|
401
|
+
try {
|
|
402
|
+
const accepted = await withServiceUnavailableRetry(() => this.#gateway.invoke({
|
|
403
|
+
namespace: 'userQuestions',
|
|
404
|
+
method: 'answer',
|
|
405
|
+
args: wireArgs('userQuestions', 'answer', { agentId: sessionId, callId, answer: { answers: answer.answers } }),
|
|
406
|
+
peer: this.#peer,
|
|
407
|
+
}))
|
|
408
|
+
if (accepted !== true) {
|
|
409
|
+
return { ok: false, code: CODE_QUESTION_UNKNOWN, msg: 'the host does not hold this question as answerable yet' }
|
|
410
|
+
}
|
|
411
|
+
this.#claims.delete(callId)
|
|
412
|
+
return { ok: true }
|
|
413
|
+
} catch (error) {
|
|
414
|
+
this.#log(`userQuestions/answer failed: ${failureText(error)}`)
|
|
415
|
+
return { ok: false, code: errorCodeOf(error, CODE_INTERNAL), msg: failureText(error) }
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Settle one open claim from the host's own cancellation lifetime.
|
|
421
|
+
*
|
|
422
|
+
* The reason is propagated verbatim, so the host's deadline still maps to its
|
|
423
|
+
* pending result. Only a deadline keeps the claim: every other abort means
|
|
424
|
+
* the ask itself is gone.
|
|
425
|
+
*/
|
|
426
|
+
#expire(callId: string, reason: unknown): void {
|
|
427
|
+
const record = this.#claims.get(callId)
|
|
428
|
+
if (record === undefined || record.state !== 'open') return
|
|
429
|
+
record.detach()
|
|
430
|
+
record.fail(reason)
|
|
431
|
+
// Only a host deadline keeps a claim answerable, and only for an id the host
|
|
432
|
+
// itself assigned: a minted one has no host question behind it, so nothing
|
|
433
|
+
// could ever take a late answer.
|
|
434
|
+
if (!record.hosted || !isTimedOut(reason)) {
|
|
435
|
+
this.#claims.delete(callId)
|
|
436
|
+
return
|
|
437
|
+
}
|
|
438
|
+
record.state = 'continued'
|
|
439
|
+
record.onContinued?.({ sessionId: record.sessionId, callId: record.callId, questions: record.questions })
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
declare module '@deepseek-ai/cordis' {
|
|
444
|
+
interface Events {
|
|
445
|
+
/**
|
|
446
|
+
* Ask composed answerers for structured user input; the bridge claims it
|
|
447
|
+
* while a paired phone is connected, and delegates every other case. The
|
|
448
|
+
* parameters are the ones this package reads — the host's own declaration
|
|
449
|
+
* is not reachable from here.
|
|
450
|
+
* @mode waterfall
|
|
451
|
+
*/
|
|
452
|
+
'user-questions/request'(this: unknown, request: UserQuestionRequestLike, next: () => Promise<QuestionAnswer>): Promise<QuestionAnswer>
|
|
453
|
+
}
|
|
454
|
+
}
|