@linxin666/dsh-remote-bridge 0.4.7 → 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.
@@ -10,6 +10,7 @@ export const METHOD_SESSION_LIST = 'session.list'
10
10
  export const METHOD_SESSION_TITLES = 'session.titles'
11
11
  export const METHOD_SESSION_SNAPSHOT = 'session.snapshot'
12
12
  export const METHOD_SESSION_HISTORY = 'session.history'
13
+ export const METHOD_SESSION_HISTORY_DEEP = 'session.history.deep'
13
14
  export const METHOD_SESSION_PROMPT = 'session.prompt'
14
15
  export const METHOD_SESSION_INTERRUPT = 'session.interrupt'
15
16
  export const METHOD_SESSION_ATTACHMENT = 'session.attachment'
@@ -17,15 +18,20 @@ export const METHOD_SESSION_PERMISSIONS = 'session.permissions'
17
18
  export const METHOD_SESSION_SET_PERMISSION = 'session.setPermission'
18
19
  export const METHOD_SESSION_MODELS = 'session.models'
19
20
  export const METHOD_SESSION_SET_MODEL = 'session.setModel'
21
+ export const METHOD_SESSION_CREATE = 'session.create'
22
+ export const METHOD_SESSION_FORK = 'session.fork'
23
+ export const METHOD_PRESETS_LIST = 'presets.list'
20
24
  export const METHOD_PAIR_BEGIN = 'pair.begin'
21
25
  export const METHOD_PAIR_FINISH = 'pair.finish'
22
26
  export const METHOD_APPROVAL_RESOLVE = 'approval.resolve'
23
27
  export const METHOD_QUESTION_ANSWER = 'question.answer'
28
+ export const METHOD_JOBS_LIST = 'jobs.list'
24
29
 
25
30
  /** Server-pushed topics of protocol v1. */
26
31
  export const TOPIC_SESSION_DELTA = 'session.delta'
27
32
  export const TOPIC_APPROVAL_REQUEST = 'approval.request'
28
33
  export const TOPIC_QUESTION_REQUEST = 'question.request'
34
+ export const TOPIC_JOBS_CHANGED = 'jobs.changed'
29
35
 
30
36
  /**
31
37
  * Capability a client declares in `hello`'s `cap` array to ask for a trimmed
@@ -45,6 +51,26 @@ export const CAP_SESSION_SNAPSHOT_TRIM = 'session.snapshot.trim.v1'
45
51
  */
46
52
  export const CAP_SESSION_SNAPSHOT_PAGE = 'session.snapshot.page.v1'
47
53
 
54
+ /**
55
+ * Capability a client declares in `hello`'s `cap` array to have
56
+ * `session.snapshot` answer a reconnect with only what it missed.
57
+ *
58
+ * The declaration and the request's `sinceSeq` are what it takes together: a
59
+ * snapshot that carries no `sinceSeq` is answered, byte for byte, the body
60
+ * protocol v1 always served, whether or not the client declared this. Behind
61
+ * both, the client names the durable `lastSeq` of a snapshot it already holds
62
+ * and the answer is either that same reply in an incremental form —
63
+ * `{turns, lastSeq, mode:"since", reset:false}` carrying only the entries above
64
+ * that watermark — or a full baseline with `mode:"full"` and `reset:true`,
65
+ * which is the one answer that tells a client to throw its copy away. The
66
+ * estimate is only served when the bridge can PROVE nothing was lost: the
67
+ * current follow window's oldest entry must sit at or below `sinceSeq + 1`, so a
68
+ * window that has already scrolled past the watermark answers the baseline
69
+ * instead of a delta with a hole in it. It exists because a reconnect on the
70
+ * phone re-paid 0.86-1.06 s of baseline five times in one measured run.
71
+ */
72
+ export const CAP_SESSION_SNAPSHOT_SINCE = 'session.snapshot.since.v1'
73
+
48
74
  /**
49
75
  * Capability a client declares in `hello`'s `cap` array to be shown the
50
76
  * host's pending user questions and to answer them with `question.answer`.
@@ -57,6 +83,157 @@ export const CAP_SESSION_SNAPSHOT_PAGE = 'session.snapshot.page.v1'
57
83
  */
58
84
  export const CAP_QUESTIONS = 'questions.v1'
59
85
 
86
+ /**
87
+ * Capability a client declares in `hello`'s `cap` array to be handed the
88
+ * approval questions this bridge is already holding for it.
89
+ *
90
+ * Unlike every channel capability beside it, this one gates a second delivery
91
+ * rather than the channel: `approval.request` still reaches every paired
92
+ * connection the moment a tool asks, exactly as it did before this name
93
+ * existed, because gating the first broadcast would take approvals away from
94
+ * every client written before the capability. What the declaration buys is the
95
+ * replay — after a reconnect, or on a session screen opened late, the client is
96
+ * handed the questions that are still waiting instead of a card it never saw.
97
+ * Only a live claim is replayed: a question that was answered, that the bridge
98
+ * timed out, or that was withdrawn with the last phone is gone from the claim
99
+ * registry before the replay reads it.
100
+ *
101
+ * It is deliberately absent from {@link SERVED_CAPABILITIES}: that list is what
102
+ * `hello` advertises as served, advertising a capability is a minor-version
103
+ * addition (see {@link MINOR}), and this channel changes nothing a client can
104
+ * observe in the handshake — no answer, no field and no method behind it. The
105
+ * declaration is the whole switch, and the name reaches a client through this
106
+ * bridge's own protocol documentation.
107
+ */
108
+ export const CAP_APPROVALS = 'approvals.v1'
109
+
110
+ /**
111
+ * Capability a client declares in `hello`'s `cap` array to be told where a
112
+ * message came from and that an agent spawned a child session.
113
+ *
114
+ * Declaring it is what makes the `subagent` delta part of that client's
115
+ * protocol: a client that does not declare it — including every client written
116
+ * before this channel existed — receives no such event, exactly as that frame
117
+ * was dropped before. The `actor` of a `user-message` is not gated: it is an
118
+ * additive field a client that does not read it ignores.
119
+ */
120
+ export const CAP_SUBAGENT_THREAD = 'subagent.thread.v1'
121
+
122
+ /**
123
+ * Capability a client declares in `hello`'s `cap` array to see the host's
124
+ * background jobs and to be told when the set changes.
125
+ *
126
+ * Declaring it is what makes `jobs.list` reachable, and `jobs.list` is the only
127
+ * thing that opens a roster: a connection that declares this capability but
128
+ * never asks for a scope receives no `jobs.changed` at all. A client that does
129
+ * not declare it — including every client written before this channel existed —
130
+ * receives no such event, and its `jobs.list` is refused as an unknown method,
131
+ * exactly as that frame was refused before.
132
+ */
133
+ export const CAP_JOBS = 'jobs.v1'
134
+
135
+ /**
136
+ * Capability a client declares in `hello`'s `cap` array to read the host's
137
+ * Agent presets and to instantiate one as a session.
138
+ *
139
+ * Declaring it is what makes `presets.list` and `session.create` part of that
140
+ * client's protocol at all: a client that does not declare it — including every
141
+ * client written before this channel existed — is refused both as unknown
142
+ * methods, exactly as those frames were refused before. Neither method is
143
+ * called on a connection's behalf either, so a client that never asks sends the
144
+ * host no request.
145
+ */
146
+ export const CAP_AGENTS = 'agents.v1'
147
+
148
+ /**
149
+ * Capability a client declares in `hello`'s `cap` array to be answered with
150
+ * byte-level increments instead of the whole roster or the whole board.
151
+ *
152
+ * Behind it, `session.list` and `board.snapshot` (the latter through the board
153
+ * plugin, §15) accept an opaque `since` token and answer either the whole set
154
+ * (`mode:"reset"`) or only what changed since the set that token names. A
155
+ * client that does not declare it — including every client written before this
156
+ * channel existed — is answered today's body plus the ignorable `mode` and
157
+ * `token` keys, with `mode` always `"reset"`.
158
+ */
159
+ export const CAP_DELTA = 'delta.v1'
160
+
161
+ /**
162
+ * Capability a client declares in `hello`'s `cap` array to be told that an
163
+ * archived session is not in the roster at all.
164
+ *
165
+ * Unlike every capability beside it this one negotiates nothing: the bridge
166
+ * never transfers an archived session, whether or not a client declares it, so
167
+ * an older client simply receives the shorter roster it would have hidden
168
+ * anyway. The name is an announcement of that fact, so a client can stop
169
+ * filtering for itself: behind it, no `session.list` row is a session the
170
+ * host's archive set names, a row that does survive still carries
171
+ * `archived: false` under the same schema, and a live child of an archived
172
+ * parent still crosses with its `parentSessionId` — the parent id, not the
173
+ * parent row.
174
+ */
175
+ export const CAP_ROSTER_OMITS_ARCHIVED = 'session.list.omit-archived.v1'
176
+
177
+ /**
178
+ * Capability a client declares in `hello`'s `cap` array to be answered a
179
+ * compact roster it can page.
180
+ *
181
+ * The declaration alone changes nothing: a listing that carries none of the
182
+ * compact parameters (`cwd`, `maxRows`, `after`) is answered exactly the body
183
+ * protocol v1 always served, so a client can opt into the name before it
184
+ * relies on any of it. Behind the parameters, a row drops its absolute `cwd`
185
+ * unless the request asks for it, drops its `updatedAt` when this connection
186
+ * already sent that id the same value, and a `maxRows`/`after` pair cuts the
187
+ * roster into pages ordered most recent first. The roster is the most repeated
188
+ * large reply on the link, so this is what lets a reconnect pay for the newest
189
+ * screenful plus a cursor instead of the whole list again.
190
+ */
191
+ export const CAP_ROSTER_COMPACT = 'session.list.compact.v1'
192
+
193
+ /**
194
+ * Capability a client declares in `hello`'s `cap` array to be told that this
195
+ * bridge can page a session's durable history down to its oldest entry.
196
+ *
197
+ * The capability is an announcement and nothing more. `session.history.deep` is
198
+ * open to every paired connection, exactly as `session.history` is, because it
199
+ * is a pure read of the session store that costs no other client anything;
200
+ * declaring the capability is how a client learns the method exists, and a
201
+ * client that does not declare it loses only that knowledge.
202
+ */
203
+ export const CAP_SESSION_DEEP_HISTORY = 'session.deep-history.v1'
204
+
205
+ /**
206
+ * Capability a client declares in `hello`'s `cap` array to fork a session.
207
+ *
208
+ * Declaring it is what makes `session.fork` part of that client's protocol at
209
+ * all: a client that does not declare it — including every client written
210
+ * before this channel existed — is refused `unknown-method`, and no fork is
211
+ * asked of the host on its behalf. Behind the name the bridge forwards one
212
+ * `SessionForkRequest` to the host's `session/fork` and hands back the host's
213
+ * own `SessionForkValue`, so what a fork point means stays the host's: an
214
+ * `atSeq` is the source event seq the fork includes, an omitted one is the
215
+ * newest finished turn, and a cut the host opens itself is closed by the host's
216
+ * own synthetic finishing event. Nothing about a fork is modelled or
217
+ * re-derived here.
218
+ */
219
+ export const CAP_SESSION_FORK = 'session.fork.v1'
220
+
221
+ /**
222
+ * Capability a client declares in `hello`'s `cap` array to be sent frames
223
+ * compressed instead of as plain text.
224
+ *
225
+ * Declaring it is what allows the host to compress at all: a frame whose JSON
226
+ * text is at least 1024 UTF-8 bytes crosses as one WebSocket binary frame
227
+ * carrying raw DEFLATE (RFC 1951) of exactly that text, and a frame that does
228
+ * not get smaller still crosses as the text frame it always was. A client that
229
+ * does not declare it — including every client written before this capability
230
+ * existed — receives byte for byte the text frames protocol v1 always wrote.
231
+ *
232
+ * The direction is one way: a client still sends text frames only, and the
233
+ * 10 MiB frame cap stays measured on the text, before inflation.
234
+ */
235
+ export const CAP_FRAME_DEFLATE = 'frame.deflate.v1'
236
+
60
237
  /**
61
238
  * Methods an unpaired connection may still call: the handshake itself and the
62
239
  * two pairing steps. Everything else answers `unpaired` — a caller can pair
@@ -75,6 +252,7 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
75
252
  METHOD_SESSION_TITLES,
76
253
  METHOD_SESSION_SNAPSHOT,
77
254
  METHOD_SESSION_HISTORY,
255
+ METHOD_SESSION_HISTORY_DEEP,
78
256
  METHOD_SESSION_PROMPT,
79
257
  METHOD_SESSION_INTERRUPT,
80
258
  METHOD_SESSION_ATTACHMENT,
@@ -86,6 +264,10 @@ export const KNOWN_METHODS: ReadonlySet<string> = new Set([
86
264
  METHOD_PAIR_FINISH,
87
265
  METHOD_APPROVAL_RESOLVE,
88
266
  METHOD_QUESTION_ANSWER,
267
+ METHOD_JOBS_LIST,
268
+ METHOD_PRESETS_LIST,
269
+ METHOD_SESSION_CREATE,
270
+ METHOD_SESSION_FORK,
89
271
  ])
90
272
 
91
273
  /** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
@@ -103,14 +285,93 @@ export const CODE_APPROVAL_UNKNOWN = 'approval-unknown'
103
285
  * failures crossing this method keep their own codes instead.
104
286
  */
105
287
  export const CODE_QUESTION_UNKNOWN = 'question-unknown'
288
+ /**
289
+ * The named session is a delegated child whose durable parent is not a session
290
+ * this connection may read. The bridge follows an addressable child and refuses
291
+ * an unaddressable one, rather than reading it blind.
292
+ */
293
+ export const CODE_SESSION_NOT_FOLLOWABLE = 'session-not-followable'
106
294
  export const CODE_SNAPSHOT_UNAVAILABLE = 'snapshot-unavailable'
295
+ /**
296
+ * This host composes no job registry, so it has no background jobs to publish.
297
+ * The capability stays advertised — it is a fact about this bridge, not about
298
+ * what a particular host mounts — and only a call that needs the registry fails.
299
+ */
300
+ export const CODE_JOBS_UNAVAILABLE = 'jobs-unavailable'
107
301
  export const CODE_SNAPSHOT_TOO_LARGE = 'snapshot-too-large'
108
302
  export const CODE_INTERNAL = 'internal'
109
303
 
110
304
  /** Protocol version this package speaks. */
111
305
  export const PROTO = 1
112
- /** Minor version this package speaks. */
113
- export const MINOR = 0
306
+ /**
307
+ * Minor version this package speaks.
308
+ *
309
+ * 11 when the fork channel shipped: behind {@link CAP_SESSION_FORK} a client may
310
+ * call {@link METHOD_SESSION_FORK} and receive the host's own fork answer, so a
311
+ * phone branches a session that inherits the context of the one it forked. This
312
+ * is the second of two appends cut from 9 — the snapshot-`since` channel took
313
+ * 10 on the integration branch first — so the number steps over the one already
314
+ * on `dev`: the minor counts additions to this protocol, and a later landing
315
+ * steps over the earlier one instead of reusing its number.
316
+ * 10 when the snapshot became incremental on request: behind
317
+ * {@link CAP_SESSION_SNAPSHOT_SINCE} a `session.snapshot` that names `sinceSeq`
318
+ * is answered either the entries above that watermark or a full baseline
319
+ * carrying `mode` and `reset`, so a client reads a new reply shape off the
320
+ * wire and the number rises with it.
321
+ * 9 when the compact roster shipped: behind {@link CAP_ROSTER_COMPACT} a
322
+ * `session.list` that names one of the compact parameters is answered a
323
+ * shorter row and may be cut into pages, so a client reads a new row schema
324
+ * off the wire and the number rises with it.
325
+ * 8 when the outbound frame form became a capability: behind
326
+ * {@link CAP_FRAME_DEFLATE} a declaring client may be answered in binary
327
+ * frames carrying raw DEFLATE of the text, so the minor is raised for a change
328
+ * a client reads off the wire rather than for a name alone.
329
+ * 7 when the two channels met: the agent channel and the durable history
330
+ * channel each raised 5 to 6 on its own branch, so the protocol that carries
331
+ * both is 7. 6 when the agent channel shipped: behind {@link CAP_AGENTS}
332
+ * `presets.list` forwards the host's Agent-preset roster and `session.create`
333
+ * hands the host one creation request, both verbatim. 6 was also the durable
334
+ * history channel on its own: behind {@link CAP_SESSION_DEEP_HISTORY} a client
335
+ * may call {@link METHOD_SESSION_HISTORY_DEEP} and walk a session's store back
336
+ * to its oldest entry, below the follow window `session.history` slices. 5 when
337
+ * the roster stopped carrying archived sessions: behind
338
+ * {@link CAP_ROSTER_OMITS_ARCHIVED} `session.list` names no session the host's
339
+ * archive set holds, so a session archived between two listings arrives as a
340
+ * removal and one restored as a change. 4 when byte-level increments shipped:
341
+ * behind {@link CAP_DELTA} `session.list` and `board.snapshot` answer a reset
342
+ * or a delta against a `since` token. 3 was
343
+ * the background-job channel — behind {@link CAP_JOBS} a client may call
344
+ * `jobs.list` and receive `jobs.changed`. 2 was the subagent thread —
345
+ * a `user-message` delta may carry an `actor` and a `subagent` delta exists
346
+ * behind {@link CAP_SUBAGENT_THREAD}. 1 was the extension seam — a mounted
347
+ * plugin may answer methods outside {@link KNOWN_METHODS} once the client
348
+ * declares the capability that plugin requires. No addition changed the major
349
+ * version, a frozen field, or an existing method or topic name.
350
+ */
351
+ export const MINOR = 11
352
+
353
+ /**
354
+ * The capabilities this bridge itself serves, as `hello` advertises them.
355
+ *
356
+ * A capability a mounted plugin adds is not listed here: the bridge cannot know
357
+ * what it is not the author of. A client learns such a capability from the
358
+ * plugin's own documentation, exactly as it did before this list existed.
359
+ */
360
+ export const SERVED_CAPABILITIES: readonly string[] = [
361
+ CAP_SESSION_SNAPSHOT_TRIM,
362
+ CAP_SESSION_SNAPSHOT_PAGE,
363
+ CAP_QUESTIONS,
364
+ CAP_SUBAGENT_THREAD,
365
+ CAP_JOBS,
366
+ CAP_AGENTS,
367
+ CAP_DELTA,
368
+ CAP_ROSTER_OMITS_ARCHIVED,
369
+ CAP_SESSION_DEEP_HISTORY,
370
+ CAP_FRAME_DEFLATE,
371
+ CAP_ROSTER_COMPACT,
372
+ CAP_SESSION_SNAPSHOT_SINCE,
373
+ CAP_SESSION_FORK,
374
+ ]
114
375
  /** `server` field of the hello response. */
115
376
  export const SERVER_ID = 'dsh-remote-bridge'
116
377
 
@@ -30,6 +30,13 @@
30
30
  * delegated to `next()`, never answered with a decision the operator did not
31
31
  * make.
32
32
  *
33
+ * A timed ask's deadline is read back from the host itself
34
+ * (`userQuestions/attachWait`) and published as `expiresAt`, so the phone can
35
+ * count down the wait the host is actually serving. Holding that subscription
36
+ * parks the host's own deadline timer, so this module also has to let go at the
37
+ * instant the deadline it learned has passed: only then does the host raise
38
+ * `ASK_TIMED_OUT` and hand the claim its `continued` state.
39
+ *
33
40
  * The types below mirror `@deepseek-ai/dsh-user-questions` field for field. The
34
41
  * package is not a dependency of this one (it is the host's, not the bridge's),
35
42
  * so the contract is declared locally instead of imported.
@@ -110,12 +117,30 @@ export interface ClaimedQuestionView {
110
117
  readonly sessionId: string
111
118
  readonly callId: string
112
119
  readonly questions: readonly QuestionItem[]
120
+ /**
121
+ * Epoch milliseconds at which the host's own deadline falls — the absolute
122
+ * form of the remaining wait the host reported through `attachWait`.
123
+ *
124
+ * Absent when the host said nothing: a blocking ask has no deadline at all,
125
+ * and a timed one is only known once a wait frame arrived.
126
+ */
127
+ readonly expiresAt?: number
113
128
  }
114
129
 
115
130
  /** One claim the hub holds while the host's ask is still open. */
116
131
  export interface ClaimedQuestion extends ClaimedQuestionView {
117
132
  /** The host's ask: the phone's answer, or whatever the next answerer says. */
118
133
  readonly answer: Promise<QuestionAnswer>
134
+ /**
135
+ * Epoch milliseconds at which the host's own deadline falls, from the first
136
+ * wait frame of this claim.
137
+ *
138
+ * Resolves undefined when there is no deadline to publish — a blocking ask, a
139
+ * failed subscription, or a stream that ended before its first frame — and
140
+ * never rejects: a phone must be shown the question whether or not the host
141
+ * would say how long it has.
142
+ */
143
+ readonly deadline: Promise<number | undefined>
119
144
  }
120
145
 
121
146
  /** What one `question.answer` produced: acknowledgement, or the refusal to send. */
@@ -134,6 +159,15 @@ export const QUESTION_TIMED_OUT_CODE = 'ASK_TIMED_OUT'
134
159
  export const MINTED_CALL_ID_PREFIX = 'bridge:'
135
160
  /** Entropy of one minted call id. */
136
161
  export const MINTED_CALL_ID_BYTES = 16
162
+ /**
163
+ * How often at most a phone is told that the host's deadline moved, in
164
+ * milliseconds.
165
+ *
166
+ * The host re-reports its remaining wait on every touch of the wait, which can
167
+ * be far more often than a countdown needs; one update per second keeps the
168
+ * wire quiet without the phone ever showing a stale second.
169
+ */
170
+ export const QUESTION_WAIT_BROADCAST_MIN_INTERVAL_MS = 1000
137
171
 
138
172
  export interface OpenQuestionInput {
139
173
  readonly sessionId: string
@@ -153,6 +187,15 @@ export interface OpenQuestionInput {
153
187
  readonly signal?: AbortSignal
154
188
  /** Called once when the host's deadline released the model but the question stayed answerable. */
155
189
  readonly onContinued?: (question: ClaimedQuestionView) => void
190
+ /**
191
+ * Called when a later wait frame moved the host's deadline, so a phone that
192
+ * already holds the card can update it in place.
193
+ *
194
+ * The first frame is not reported here: it is what {@link ClaimedQuestion.deadline}
195
+ * hands the hub for the question's own first broadcast, so reporting it would
196
+ * publish the same deadline twice.
197
+ */
198
+ readonly onDeadline?: (question: ClaimedQuestionView) => void
156
199
  /**
157
200
  * Called when the claim leaves this bridge without the phone answering it — the
158
201
  * host's own UI answered first, or the last paired client went away. The phone
@@ -176,6 +219,10 @@ interface Claim {
176
219
  readonly onContinued: ((question: ClaimedQuestionView) => void) | undefined
177
220
  /** Tells the phone its card is over; set from the input's `onSettled`. */
178
221
  readonly notifySettled: () => void
222
+ /** Epoch milliseconds of the host's deadline, once a wait frame reported one. */
223
+ expiresAt: number | undefined
224
+ /** End the wait subscription and its timer. Idempotent. */
225
+ readonly stopWait: () => void
179
226
  }
180
227
 
181
228
  export interface QuestionClaimsOptions {
@@ -185,6 +232,11 @@ export interface QuestionClaimsOptions {
185
232
  readonly log: (message: string) => void
186
233
  /** Id source, injectable so a test can answer the exact id it was given. */
187
234
  readonly random?: (byteLength: number) => string
235
+ /**
236
+ * Clock the deadline bookkeeping reads, injectable so a suite can move the
237
+ * remaining wait instead of sleeping through it.
238
+ */
239
+ readonly now?: () => number
188
240
  }
189
241
 
190
242
  /** @returns whether a failure is the host's own foreground deadline. */
@@ -192,6 +244,34 @@ function isTimedOut(reason: unknown): boolean {
192
244
  return (reason as { code?: unknown } | null | undefined)?.code === QUESTION_TIMED_OUT_CODE
193
245
  }
194
246
 
247
+ /**
248
+ * The publishable view of one claim.
249
+ *
250
+ * The deadline key is spread in rather than set to undefined: a blocking ask has
251
+ * no expiry at all, and the phone must see no such field instead of a null one.
252
+ * @param record - the live claim.
253
+ * @returns the claim's fields as the hub publishes them.
254
+ */
255
+ function viewOf(record: Claim): ClaimedQuestionView {
256
+ return {
257
+ sessionId: record.sessionId,
258
+ callId: record.callId,
259
+ questions: record.questions,
260
+ ...(record.expiresAt === undefined ? {} : { expiresAt: record.expiresAt }),
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Read the remaining wait out of one `attachWait` frame.
266
+ * @param frame - the frame as the gateway delivered it.
267
+ * @returns the remaining milliseconds, or undefined when the frame is not usable.
268
+ */
269
+ function remainingOf(frame: unknown): number | undefined {
270
+ const remaining = (frame as { remainingMs?: unknown } | null | undefined)?.remainingMs
271
+ if (typeof remaining !== 'number' || !Number.isFinite(remaining) || remaining < 0) return undefined
272
+ return remaining
273
+ }
274
+
195
275
  /**
196
276
  * Project a host question into the contract's own fields.
197
277
  *
@@ -232,6 +312,7 @@ export class QuestionClaims {
232
312
  readonly #peer: GatewayPeer
233
313
  readonly #log: (message: string) => void
234
314
  readonly #random: (byteLength: number) => string
315
+ readonly #now: () => number
235
316
  readonly #claims = new Map<string, Claim>()
236
317
 
237
318
  constructor(options: QuestionClaimsOptions) {
@@ -239,6 +320,7 @@ export class QuestionClaims {
239
320
  this.#peer = options.peer
240
321
  this.#log = options.log
241
322
  this.#random = options.random ?? randomBase64Url
323
+ this.#now = options.now ?? Date.now
242
324
  }
243
325
 
244
326
  /** @returns how many questions this bridge currently holds. */
@@ -290,15 +372,38 @@ export class QuestionClaims {
290
372
  }
291
373
  return nextStarted
292
374
  }
375
+ // The host parks its own deadline timer while a waiter is attached, so this
376
+ // subscription must let go at the instant the deadline it reported has
377
+ // passed: only then does the host raise ASK_TIMED_OUT, which is what turns
378
+ // the claim into today's `continued` one. Every settling path stops it.
379
+ const wait = new AbortController()
380
+ let waitTimer: NodeJS.Timeout | undefined
381
+ let stopped = false
382
+ // The resolver is installed by the executor below; a claim that closes before
383
+ // the first frame needs calling it early, and that early call must be a no-op.
384
+ const deferred: { resolve?: (deadline: number | undefined) => void } = {}
385
+ const deadline = new Promise<number | undefined>((resolve) => { deferred.resolve = resolve })
386
+ const resolveDeadline = (value: number | undefined): void => { deferred.resolve?.(value) }
387
+ const stopWait = (): void => {
388
+ if (stopped) return
389
+ stopped = true
390
+ if (waitTimer !== undefined) {
391
+ clearTimeout(waitTimer)
392
+ waitTimer = undefined
393
+ }
394
+ wait.abort()
395
+ // A claim that closes before the host said anything must not leave the hub
396
+ // awaiting a first frame that will never come.
397
+ resolveDeadline(undefined)
398
+ }
293
399
  const record: Claim = {
294
400
  sessionId: input.sessionId,
295
401
  callId: input.callId,
296
402
  hosted: input.hosted,
297
403
  questions: projectQuestions(input.questions),
298
404
  state: 'open',
299
- notifySettled: (): void => {
300
- input.onSettled?.({ sessionId: input.sessionId, callId: input.callId, questions: projectQuestions(input.questions) })
301
- },
405
+ expiresAt: undefined,
406
+ notifySettled: (): void => { input.onSettled?.(viewOf(record)) },
302
407
  settle,
303
408
  fail,
304
409
  delegate: (): void => {
@@ -306,6 +411,72 @@ export class QuestionClaims {
306
411
  },
307
412
  detach: (): void => { signal?.removeEventListener('abort', onAbort) },
308
413
  onContinued: input.onContinued,
414
+ stopWait,
415
+ }
416
+ /** Arm the timer that lets go of the wait when the host's own deadline is due. */
417
+ const armDeadline = (expiresAt: number): void => {
418
+ if (waitTimer !== undefined) clearTimeout(waitTimer)
419
+ waitTimer = setTimeout(() => { stopWait() }, Math.max(0, expiresAt - this.#now()))
420
+ // A question waiting on a phone must never keep the host process alive.
421
+ waitTimer.unref?.()
422
+ }
423
+ /**
424
+ * Follow the host's own remaining wait and report it when it moves.
425
+ *
426
+ * A failure here is not a verdict on the question: the phone can answer it
427
+ * without ever knowing the deadline, so every error only ends the
428
+ * subscription instead of failing the claim.
429
+ */
430
+ const trackWait = async (): Promise<void> => {
431
+ if (stopped) return
432
+ let frames = 0
433
+ let lastBroadcast = 0
434
+ try {
435
+ const stream = await this.#gateway.stream({
436
+ namespace: 'userQuestions',
437
+ method: 'attachWait',
438
+ args: wireArgs('userQuestions', 'attachWait', { agentId: input.sessionId, callId: input.callId }),
439
+ peer: this.#peer,
440
+ signal: wait.signal,
441
+ })
442
+ const iterator = stream[Symbol.asyncIterator]()
443
+ try {
444
+ for (;;) {
445
+ const next = await iterator.next()
446
+ if (next.done === true) return
447
+ const remaining = remainingOf(next.value)
448
+ if (remaining === undefined) continue
449
+ const at = this.#now()
450
+ const expiresAt = at + remaining
451
+ record.expiresAt = expiresAt
452
+ armDeadline(expiresAt)
453
+ // The first frame IS the deadline: the hub is already awaiting it for
454
+ // the question's own broadcast, so only later frames move a card.
455
+ if (frames === 0) {
456
+ frames = 1
457
+ lastBroadcast = at
458
+ resolveDeadline(expiresAt)
459
+ continue
460
+ }
461
+ if (at - lastBroadcast < QUESTION_WAIT_BROADCAST_MIN_INTERVAL_MS) continue
462
+ lastBroadcast = at
463
+ input.onDeadline?.(viewOf(record))
464
+ }
465
+ } finally {
466
+ await iterator.return?.()
467
+ }
468
+ } catch (error) {
469
+ // Releasing the wait on purpose — its deadline arrived, the claim settled —
470
+ // aborts the stream, and the gateway reports an aborted Remote stream as a
471
+ // failed read of its own (`gateway/cancelled`). That is the normal path,
472
+ // not a fault, so only an end nobody asked for is logged.
473
+ if (!stopped) this.#log(`userQuestions/attachWait failed: ${failureText(error)}`)
474
+ } finally {
475
+ // No frame, no deadline: the hub publishes the question without one
476
+ // instead of waiting on a wait the host never reported. A no-op once a
477
+ // frame already settled it.
478
+ resolveDeadline(undefined)
479
+ }
309
480
  }
310
481
  this.#claims.set(input.callId, record)
311
482
  // The rest of the chain is NOT started here. A connected phone takes the
@@ -314,7 +485,10 @@ export class QuestionClaims {
314
485
  // A phone that is absent, or a claim that is withdrawn, still delegates.
315
486
  if (signal?.aborted === true) onAbort()
316
487
  else signal?.addEventListener('abort', onAbort, { once: true })
317
- return { sessionId: record.sessionId, callId: record.callId, questions: record.questions, answer }
488
+ if (input.hosted) void trackWait()
489
+ // A blocking ask carries no host deadline at all: nothing to follow, nothing to publish.
490
+ else resolveDeadline(undefined)
491
+ return { ...viewOf(record), answer, deadline }
318
492
  }
319
493
 
320
494
  /**
@@ -335,6 +509,7 @@ export class QuestionClaims {
335
509
  if (record.state === 'open') {
336
510
  this.#claims.delete(callId)
337
511
  record.detach()
512
+ record.stopWait()
338
513
  record.settle({ answers: answer.answers })
339
514
  return { ok: true }
340
515
  }
@@ -354,11 +529,7 @@ export class QuestionClaims {
354
529
  * question sits on the host with an answerable card nowhere.
355
530
  */
356
531
  openClaims(): readonly ClaimedQuestionView[] {
357
- return [...this.#claims.values()].map((record) => ({
358
- sessionId: record.sessionId,
359
- callId: record.callId,
360
- questions: record.questions,
361
- }))
532
+ return [...this.#claims.values()].map(viewOf)
362
533
  }
363
534
 
364
535
  /**
@@ -372,6 +543,7 @@ export class QuestionClaims {
372
543
  if (record === undefined) continue
373
544
  this.#claims.delete(callId)
374
545
  record.detach()
546
+ record.stopWait()
375
547
  record.notifySettled()
376
548
  if (record.state !== 'open') continue
377
549
  record.delegate()
@@ -408,7 +580,10 @@ export class QuestionClaims {
408
580
  if (accepted !== true) {
409
581
  return { ok: false, code: CODE_QUESTION_UNKNOWN, msg: 'the host does not hold this question as answerable yet' }
410
582
  }
583
+ const record = this.#claims.get(callId)
411
584
  this.#claims.delete(callId)
585
+ // The late answer is the end of this ask: nothing is left to count down.
586
+ record?.stopWait()
412
587
  return { ok: true }
413
588
  } catch (error) {
414
589
  this.#log(`userQuestions/answer failed: ${failureText(error)}`)
@@ -427,6 +602,7 @@ export class QuestionClaims {
427
602
  const record = this.#claims.get(callId)
428
603
  if (record === undefined || record.state !== 'open') return
429
604
  record.detach()
605
+ record.stopWait()
430
606
  record.fail(reason)
431
607
  // Only a host deadline keeps a claim answerable, and only for an id the host
432
608
  // itself assigned: a minted one has no host question behind it, so nothing
@@ -436,7 +612,7 @@ export class QuestionClaims {
436
612
  return
437
613
  }
438
614
  record.state = 'continued'
439
- record.onContinued?.({ sessionId: record.sessionId, callId: record.callId, questions: record.questions })
615
+ record.onContinued?.(viewOf(record))
440
616
  }
441
617
  }
442
618
 
package/src/core/wire.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * - `session/list` is the only endpoint whose single parameter is named
11
11
  * `_request` (the underscore is part of the wire name);
12
- * - three endpoints take NO parameters at all and must be called with `{}`;
12
+ * - four endpoints take NO parameters at all and must be called with `{}`;
13
13
  * - every other endpoint names its single parameter `request`.
14
14
  * @module dsh-remote-bridge/core/wire
15
15
  */
@@ -111,6 +111,8 @@ export interface WireRow {
111
111
  */
112
112
  export const WIRE_TABLE: readonly WireRow[] = [
113
113
  { namespace: 'session', method: 'list', wire: '_request' },
114
+ { namespace: 'session', method: 'create', wire: 'request' },
115
+ { namespace: 'session', method: 'fork', wire: 'request' },
114
116
  { namespace: 'session', method: 'page', wire: 'request' },
115
117
  { namespace: 'session', method: 'follow', wire: 'request' },
116
118
  { namespace: 'session', method: 'prompt', wire: 'request' },
@@ -119,7 +121,9 @@ export const WIRE_TABLE: readonly WireRow[] = [
119
121
  { namespace: 'session', method: 'projections', wire: 'request' },
120
122
  { namespace: 'session', method: 'modelCatalog', wire: 'none' },
121
123
  { namespace: 'session', method: 'selectModel', wire: 'request' },
124
+ { namespace: 'agentPresets', method: 'list', wire: 'none' },
122
125
  { namespace: 'userQuestions', method: 'answer', wire: { names: ['agentId', 'callId', 'answer'] } },
126
+ { namespace: 'userQuestions', method: 'attachWait', wire: { names: ['agentId', 'callId'] } },
123
127
  { namespace: 'pluginInventory', method: 'list', wire: 'none' },
124
128
  { namespace: 'pluginManager', method: 'listPlugins', wire: 'none' },
125
129
  ]