@openllmsh/sdk 0.0.0-stage → 2.10.12-alpha.0

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 (245) hide show
  1. package/ARCHITECTURE.md +43 -0
  2. package/LICENSE +202 -0
  3. package/README.md +142 -2
  4. package/assets/openllm-light.svg +18 -0
  5. package/assets/openllm.svg +18 -0
  6. package/client/chat.ts +140 -0
  7. package/client/devices.ts +269 -0
  8. package/client/http.ts +72 -0
  9. package/client/index.ts +129 -0
  10. package/client/relay-mux.ts +547 -0
  11. package/client/types.ts +51 -0
  12. package/client/vault.ts +239 -0
  13. package/connect/chat.ts +58 -0
  14. package/connect/client.ts +240 -0
  15. package/connect/config.ts +47 -0
  16. package/connect/errors.ts +121 -0
  17. package/connect/index.ts +23 -0
  18. package/connect/oauth.ts +265 -0
  19. package/connect/routes.ts +234 -0
  20. package/connect/store.ts +107 -0
  21. package/mcp/handle.ts +24 -0
  22. package/mcp/index.ts +76 -0
  23. package/mcp/server.ts +319 -0
  24. package/mcp/tools/marketplace.ts +439 -0
  25. package/mcp/tools/memory-client.ts +297 -0
  26. package/mcp/tools/memory-config.ts +32 -0
  27. package/mcp/tools/memory.ts +369 -0
  28. package/mcp/tools/model-priority.ts +88 -0
  29. package/mcp/tools/openllm.ts +883 -0
  30. package/mcp/types.ts +28 -0
  31. package/openapi/call.ts +90 -0
  32. package/openapi/index.ts +8 -0
  33. package/openapi/openapi.json +80213 -0
  34. package/openapi/operations.ts +2075 -0
  35. package/package.json +39 -4
  36. package/protocol/CONTRIBUTING.md +21 -0
  37. package/protocol/README.md +134 -0
  38. package/protocol/access.ts +186 -0
  39. package/protocol/agent-prompt-text.ts +32 -0
  40. package/protocol/agent.ts +991 -0
  41. package/protocol/api-key-syntax.ts +105 -0
  42. package/protocol/assets/openllm-light.svg +18 -0
  43. package/protocol/assets/openllm.svg +18 -0
  44. package/protocol/audio.ts +29 -0
  45. package/protocol/auth.ts +142 -0
  46. package/protocol/changelog.ts +155 -0
  47. package/protocol/chat.ts +458 -0
  48. package/protocol/client-registry.ts +356 -0
  49. package/protocol/config.ts +345 -0
  50. package/protocol/control-channel.ts +115 -0
  51. package/protocol/cooldown-reason.ts +78 -0
  52. package/protocol/cost.ts +10 -0
  53. package/protocol/daemon-port.ts +31 -0
  54. package/protocol/daemon.ts +1524 -0
  55. package/protocol/default-chains.ts +66 -0
  56. package/protocol/device-state.ts +85 -0
  57. package/protocol/doctor-report-local.ts +443 -0
  58. package/protocol/doctor-report-policy.ts +119 -0
  59. package/protocol/doctor-report.ts +947 -0
  60. package/protocol/errors.ts +14 -0
  61. package/protocol/execution-selection.ts +141 -0
  62. package/protocol/hop-grant.ts +33 -0
  63. package/protocol/image-edit-parse.ts +263 -0
  64. package/protocol/images.ts +298 -0
  65. package/protocol/index.ts +74 -0
  66. package/protocol/inference-headers.ts +3 -0
  67. package/protocol/keepalive.ts +69 -0
  68. package/protocol/local-auth.ts +300 -0
  69. package/protocol/local-device-control.ts +133 -0
  70. package/protocol/local-provider.ts +288 -0
  71. package/protocol/local-session.ts +118 -0
  72. package/protocol/marketplace.ts +187 -0
  73. package/protocol/media-attempt.ts +81 -0
  74. package/protocol/media-bytes.ts +28 -0
  75. package/protocol/media-default.ts +357 -0
  76. package/protocol/media-dimensions.ts +132 -0
  77. package/protocol/media-input.ts +61 -0
  78. package/protocol/media-model.ts +142 -0
  79. package/protocol/media-option-issue.ts +90 -0
  80. package/protocol/media-types.ts +70 -0
  81. package/protocol/model-match.ts +1051 -0
  82. package/protocol/model-settings.ts +327 -0
  83. package/protocol/models.ts +767 -0
  84. package/protocol/mux.ts +722 -0
  85. package/protocol/plan-surface.ts +59 -0
  86. package/protocol/provider-models.ts +16 -0
  87. package/protocol/provider-status.ts +206 -0
  88. package/protocol/provider-tier.ts +67 -0
  89. package/protocol/provider-usage.ts +263 -0
  90. package/protocol/providers.ts +901 -0
  91. package/protocol/public-usage-index.ts +354 -0
  92. package/protocol/realtime-generated.ts +31 -0
  93. package/protocol/realtime.ts +324 -0
  94. package/protocol/registry-pointer.ts +118 -0
  95. package/protocol/relay.ts +702 -0
  96. package/protocol/replay-session.ts +11 -0
  97. package/protocol/responses.ts +280 -0
  98. package/protocol/semver.ts +182 -0
  99. package/protocol/setup-mode.ts +22 -0
  100. package/protocol/sha256-hex.ts +98 -0
  101. package/protocol/stats.ts +406 -0
  102. package/protocol/streaming.ts +19 -0
  103. package/protocol/subscription-daemon-floors.ts +33 -0
  104. package/protocol/subscription-provider-compat.ts +104 -0
  105. package/protocol/subscription-provider.ts +32 -0
  106. package/protocol/team-grant.ts +17 -0
  107. package/protocol/team-shareable.ts +61 -0
  108. package/protocol/transcription-encoding.ts +76 -0
  109. package/protocol/url-locality-dns.ts +37 -0
  110. package/protocol/url-locality.ts +288 -0
  111. package/protocol/usage-snapshots.ts +9 -0
  112. package/protocol/vendor-cli-install.ts +29 -0
  113. package/protocol/video-job-plan.ts +50 -0
  114. package/protocol/videos.ts +227 -0
  115. package/tsconfig.json +14 -0
  116. package/tunnel/ARCHITECTURE.md +111 -0
  117. package/tunnel/LICENSE +33 -0
  118. package/tunnel/README.md +45 -0
  119. package/tunnel/assets/openllm-light.svg +18 -0
  120. package/tunnel/assets/openllm.svg +18 -0
  121. package/tunnel/channel-envelope.ts +139 -0
  122. package/tunnel/codec.ts +191 -0
  123. package/tunnel/device-anchor.ts +229 -0
  124. package/tunnel/device-control.ts +118 -0
  125. package/tunnel/device-grant.ts +173 -0
  126. package/tunnel/fleet.ts +77 -0
  127. package/tunnel/index.ts +22 -0
  128. package/tunnel/mux.ts +580 -0
  129. package/tunnel/peer-link.ts +390 -0
  130. package/tunnel/rtc-auth.ts +415 -0
  131. package/tunnel/rtc-duplex.ts +187 -0
  132. package/tunnel/rtc-ice.ts +136 -0
  133. package/tunnel/secure.ts +1298 -0
  134. package/tunnel/stream-reset-error.ts +14 -0
  135. package/tunnel/streams.ts +1430 -0
  136. package/tunnel/team-grant.ts +302 -0
  137. package/tunnel/wire-bytes.ts +102 -0
  138. package/vault/ARCHITECTURE.md +470 -0
  139. package/vault/LICENSE +33 -0
  140. package/vault/api-key.ts +190 -0
  141. package/vault/argon2.ts +106 -0
  142. package/vault/cli-auth-seal.ts +157 -0
  143. package/vault/cred-seal.ts +146 -0
  144. package/vault/credential.ts +55 -0
  145. package/vault/crypto.ts +210 -0
  146. package/vault/daemon-attest.ts +229 -0
  147. package/vault/derive.ts +113 -0
  148. package/vault/device-access.ts +87 -0
  149. package/vault/device-anchor.ts +185 -0
  150. package/vault/device-control.ts +174 -0
  151. package/vault/handoff.ts +396 -0
  152. package/vault/index.ts +21 -0
  153. package/vault/passkey.ts +243 -0
  154. package/vault/phrase.ts +65 -0
  155. package/vault/pin.ts +153 -0
  156. package/vault/public-key-seal.ts +131 -0
  157. package/vault/seed.ts +272 -0
  158. package/vault/team.ts +355 -0
  159. package/vault/vault-item.ts +131 -0
  160. package/vault/vault-migrate-digest.ts +29 -0
  161. package/vault/wrapped.ts +77 -0
  162. package/wire/ARCHITECTURE.md +90 -0
  163. package/wire/CONTRIBUTING.md +19 -0
  164. package/wire/LICENSE +33 -0
  165. package/wire/README.md +51 -0
  166. package/wire/adapters/messages/anthropic-map.ts +37 -0
  167. package/wire/adapters/messages/index.ts +7 -0
  168. package/wire/adapters/messages/reasoning-from-items.ts +38 -0
  169. package/wire/adapters/messages/reasoning-signature.ts +243 -0
  170. package/wire/adapters/messages/request.ts +574 -0
  171. package/wire/adapters/messages/response.ts +215 -0
  172. package/wire/adapters/messages/streaming.ts +1027 -0
  173. package/wire/adapters/messages/usage.ts +43 -0
  174. package/wire/adapters/responses/index.ts +3 -0
  175. package/wire/adapters/responses/request.ts +395 -0
  176. package/wire/adapters/responses/response.ts +88 -0
  177. package/wire/adapters/responses/streaming.ts +344 -0
  178. package/wire/assets/openllm-light.svg +18 -0
  179. package/wire/assets/openllm.svg +18 -0
  180. package/wire/features/account-rank.ts +166 -0
  181. package/wire/features/compaction/compact-request.ts +862 -0
  182. package/wire/features/compaction/compaction-text.ts +43 -0
  183. package/wire/features/context-demote.ts +47 -0
  184. package/wire/features/context-overflow-strategy.ts +26 -0
  185. package/wire/features/context-skip.ts +170 -0
  186. package/wire/features/conversation-affinity.ts +144 -0
  187. package/wire/features/max-tokens-backfill.ts +141 -0
  188. package/wire/features/model-caps.ts +53 -0
  189. package/wire/features/model-settings.ts +24 -0
  190. package/wire/features/output-limit-clamp.ts +64 -0
  191. package/wire/features/quota-gate.ts +85 -0
  192. package/wire/index.ts +44 -0
  193. package/wire/lib/attempt-outcome.ts +43 -0
  194. package/wire/lib/canonical/content-part.ts +38 -0
  195. package/wire/lib/canonical/count-tokens-capability.ts +138 -0
  196. package/wire/lib/canonical/encoding-select.ts +82 -0
  197. package/wire/lib/canonical/image-signature.ts +202 -0
  198. package/wire/lib/canonical/image-sse.ts +216 -0
  199. package/wire/lib/canonical/message.ts +43 -0
  200. package/wire/lib/canonical/token-estimate.ts +266 -0
  201. package/wire/lib/encrypted-content.ts +66 -0
  202. package/wire/lib/error-class.ts +154 -0
  203. package/wire/lib/error-envelope.ts +56 -0
  204. package/wire/lib/forwarded-headers.ts +180 -0
  205. package/wire/lib/provider-error-rules.ts +48 -0
  206. package/wire/lib/refusal.ts +38 -0
  207. package/wire/lib/responses-apply-patch.ts +104 -0
  208. package/wire/lib/responses-namespace.ts +53 -0
  209. package/wire/lib/secret-scrub.ts +101 -0
  210. package/wire/lib/streaming/accumulate.ts +221 -0
  211. package/wire/lib/streaming/finish-reason.ts +33 -0
  212. package/wire/lib/streaming/peek.ts +154 -0
  213. package/wire/lib/streaming/provider-decode.ts +259 -0
  214. package/wire/lib/streaming/response-stream.ts +71 -0
  215. package/wire/lib/streaming/sse.ts +699 -0
  216. package/wire/lib/streaming/strip-tool-calls.ts +95 -0
  217. package/wire/lib/streaming/upstream-error.ts +58 -0
  218. package/wire/lib/strip-subagent-isolation.ts +284 -0
  219. package/wire/lib/thinking-signature.ts +156 -0
  220. package/wire/lib/token-ruler/bpe-core.ts +426 -0
  221. package/wire/lib/token-ruler/index.ts +2 -0
  222. package/wire/lib/token-ruler/ruler.ts +79 -0
  223. package/wire/lib/token-ruler/vocab/claude-ranks.ts +16 -0
  224. package/wire/lib/token-ruler/vocab/claude.ts +22 -0
  225. package/wire/lib/token-ruler/vocab/o200k-ranks.ts +18 -0
  226. package/wire/lib/token-ruler/vocab/o200k.ts +19 -0
  227. package/wire/lib/tool-name-map.ts +271 -0
  228. package/wire/lib/tool-schema.ts +353 -0
  229. package/wire/lib/usage-observer.ts +125 -0
  230. package/wire/providers/anthropic/adaptive-thinking.ts +291 -0
  231. package/wire/providers/anthropic/beta-headers.ts +165 -0
  232. package/wire/providers/anthropic/index.ts +10 -0
  233. package/wire/providers/anthropic/request.ts +607 -0
  234. package/wire/providers/anthropic/response.ts +155 -0
  235. package/wire/providers/anthropic/streaming.ts +315 -0
  236. package/wire/providers/anthropic/web-search-domains.ts +49 -0
  237. package/wire/providers/chatgpt/common.ts +136 -0
  238. package/wire/providers/chatgpt/index.ts +9 -0
  239. package/wire/providers/chatgpt/request.ts +959 -0
  240. package/wire/providers/chatgpt/streaming.ts +1007 -0
  241. package/wire/providers/chatgpt/web-search.ts +63 -0
  242. package/wire/providers/grok/web-search.ts +87 -0
  243. package/wire/providers/kimi/web-search.ts +145 -0
  244. package/wire/providers/upstream-deny.ts +355 -0
  245. package/wire/providers/upstream-request.ts +619 -0
@@ -0,0 +1,1430 @@
1
+ import type {
2
+ TAgentCommand,
3
+ TAgentEvent,
4
+ TAgentStreamOpenPayload,
5
+ TRealtimeClientEvent,
6
+ TRealtimeModel,
7
+ TRealtimeProvider,
8
+ TRealtimeServerEvent,
9
+ TRealtimeStreamOpenPayload,
10
+ TRealtimeVoice,
11
+ TStreamResetCode,
12
+ TTunnelForwardHeaders,
13
+ TTunnelResponseHeaders,
14
+ TTunnelStreamOpenPayload,
15
+ TTunnelSurface,
16
+ } from "@openllmsh/sdk/protocol";
17
+ import {
18
+ AGENT_MAX_LINE_BYTES,
19
+ applyTunnelResponseHeadersToHttp,
20
+ createAgentLineSplitter,
21
+ decodeAgentLine,
22
+ decodeRealtimeLine,
23
+ encodeAgentLine,
24
+ encodeRealtimeEventLine,
25
+ parseAgentCommand,
26
+ parseAgentEvent,
27
+ parseRealtimeServerEvent,
28
+ parseStreamCtrlPayload,
29
+ parseStreamOpenPayload,
30
+ parseStreamResetPayload,
31
+ REALTIME_HEARTBEAT_INTERVAL_MS,
32
+ REALTIME_HEARTBEAT_TIMEOUT_MS,
33
+ REALTIME_SESSION_MAX_LIFETIME_MS,
34
+ RETIRED_STREAM_KIND_RESET,
35
+ RETIRED_STREAM_KINDS,
36
+ StreamResetCode,
37
+ splitRealtimeLines,
38
+ streamOpenKindOf,
39
+ TUNNEL_MEDIA_MAX_BODY_BYTES,
40
+ } from "@openllmsh/sdk/protocol";
41
+ import { Schema } from "effect";
42
+ import {
43
+ decodeJsonPayload,
44
+ encodeJsonPayload,
45
+ MAX_PAYLOAD_BYTES,
46
+ } from "./codec";
47
+ import type { TMuxChannel, TMuxStream } from "./mux";
48
+ import type { TNoiseStaticKey } from "./secure";
49
+ import { secureMuxStream } from "./secure";
50
+ import { StreamResetError } from "./stream-reset-error";
51
+
52
+ /** Domain prefix of the Noise prologue for an agent stream on the relay mux. */
53
+ export const AGENT_SECURE_PROLOGUE_INFO = "openllm-agent-secure-v1";
54
+
55
+ /**
56
+ * Noise prologue for one relay-mux agent stream:
57
+ * UTF-8 `openllm-agent-secure-v1|<channel_id>|<stream_id>`. Both ends must
58
+ * use the same value (browser initiator + daemon responder), so a relay
59
+ * cannot move a handshake onto another channel or stream.
60
+ */
61
+ export const agentSecurePrologue = (
62
+ channelId: string,
63
+ streamId: number,
64
+ ): Uint8Array =>
65
+ new TextEncoder().encode(
66
+ `${AGENT_SECURE_PROLOGUE_INFO}|${channelId}|${streamId}`,
67
+ );
68
+
69
+ /** Default wait for the serving end's `res_head` CTRL (matches legacy tunnel). */
70
+ export const TUNNEL_RESPONSE_HEAD_TIMEOUT_MS = 120_000;
71
+
72
+ export { TUNNEL_MEDIA_MAX_BODY_BYTES };
73
+
74
+ /**
75
+ * Concatenate a request body under a hard byte cap. Honors abort. Used when
76
+ * FormData/Blob must become mux DATA frames without UTF-8 round-trips.
77
+ */
78
+ export const collectBoundedBytes = async (
79
+ body: ReadableStream<Uint8Array> | Uint8Array | null,
80
+ maxBytes: number = TUNNEL_MEDIA_MAX_BODY_BYTES,
81
+ signal?: AbortSignal,
82
+ ): Promise<Uint8Array> => {
83
+ if (body === null) return new Uint8Array();
84
+ if (body instanceof Uint8Array) {
85
+ if (body.byteLength > maxBytes) {
86
+ throw new Error("tunnel request body too large");
87
+ }
88
+ return body;
89
+ }
90
+ const reader = body.getReader();
91
+ const chunks: Uint8Array[] = [];
92
+ let total = 0;
93
+ const onAbort = (): void => {
94
+ void reader.cancel().catch(() => {});
95
+ };
96
+ if (signal?.aborted) {
97
+ onAbort();
98
+ reader.releaseLock();
99
+ throw new DOMException("Aborted", "AbortError");
100
+ }
101
+ signal?.addEventListener("abort", onAbort, { once: true });
102
+ try {
103
+ for (;;) {
104
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
105
+ const next = await reader.read();
106
+ if (next.done) {
107
+ // `onAbort`'s `reader.cancel()` resolves a PENDING read as done —
108
+ // indistinguishable from a natural end of stream unless we re-check
109
+ // here. Without this, an abort racing an in-flight `read()` silently
110
+ // returns the bytes collected so far instead of rejecting.
111
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
112
+ break;
113
+ }
114
+ total += next.value.byteLength;
115
+ if (total > maxBytes) {
116
+ throw new Error("tunnel request body too large");
117
+ }
118
+ chunks.push(next.value);
119
+ }
120
+ } finally {
121
+ signal?.removeEventListener("abort", onAbort);
122
+ reader.releaseLock();
123
+ }
124
+ if (chunks.length === 0) return new Uint8Array();
125
+ if (chunks.length === 1) {
126
+ const only = chunks[0];
127
+ return only === undefined ? new Uint8Array() : only;
128
+ }
129
+ const out = new Uint8Array(total);
130
+ let offset = 0;
131
+ for (const chunk of chunks) {
132
+ out.set(chunk, offset);
133
+ offset += chunk.byteLength;
134
+ }
135
+ return out;
136
+ };
137
+
138
+ const streamReset = (code: TStreamResetCode, message?: string): Uint8Array =>
139
+ encodeJsonPayload({ code, ...(message === undefined ? {} : { message }) });
140
+
141
+ const resetCode = (payload: Uint8Array): TStreamResetCode | null => {
142
+ const decoded = parseStreamResetPayload(decodeJsonPayload(payload));
143
+ return decoded?.code ?? null;
144
+ };
145
+
146
+ /**
147
+ * Classify a RESET payload. Empty / unparseable bytes are expected peer or
148
+ * channel teardown (`peer_gone`), never a default `protocol_error` — abrupt
149
+ * mux/RTC close mass-resets live streams with `new Uint8Array()`.
150
+ */
151
+ export const unknownReset = (payload: Uint8Array): StreamResetError => {
152
+ const parsed = parseStreamResetPayload(decodeJsonPayload(payload));
153
+ return new StreamResetError(
154
+ parsed?.code ?? "peer_gone",
155
+ parsed?.message ?? parsed?.code ?? "stream reset",
156
+ );
157
+ };
158
+
159
+ const isStreamResetCode = (value: unknown): value is TStreamResetCode =>
160
+ Schema.is(StreamResetCode)(value);
161
+
162
+ /**
163
+ * True when an `AbortSignal`'s `.reason` is TIMEOUT-shaped rather than a
164
+ * genuine caller cancellation — mirrors the `name`/message heuristic
165
+ * `packages/cli/daemon/src/net-error.ts`'s `classifyOriginThrow` already uses
166
+ * for origin-fetch failures (kept as a small local copy, not an import: the
167
+ * dependency graph is `daemon → tunnel`, never the reverse). Recognizes
168
+ * `AbortSignal.timeout(ms)`'s own `TimeoutError`-named reason, so a signal
169
+ * built as `AbortSignal.any([callerSignal, AbortSignal.timeout(ms)])` — the
170
+ * shape `openRealtimeVoiceOverMux`'s per-rung budget uses — still resolves
171
+ * correctly to "timeout" when the internal timer is what actually fired,
172
+ * even though `realtimeStream` only ever sees the ONE merged signal.
173
+ */
174
+ const isTimeoutAbortReason = (reason: unknown): boolean => {
175
+ if (typeof reason !== "object" || reason === null) return false;
176
+ const name = (reason as { name?: unknown }).name;
177
+ if (name === "TimeoutError") return true;
178
+ if (name === "AbortError") {
179
+ const message = (reason as { message?: unknown }).message;
180
+ const lower = typeof message === "string" ? message.toLowerCase() : "";
181
+ return lower.includes("timeout") || lower.includes("timed out");
182
+ }
183
+ return false;
184
+ };
185
+
186
+ /**
187
+ * Build the rejection for a genuine caller-driven abort (NOT a
188
+ * timeout-shaped reason — see {@link isTimeoutAbortReason}), carrying the
189
+ * ORIGINAL abort reason when the signal provides one. This is what lets a
190
+ * caller — or a retry policy like `openOverMuxLadder` — tell "I cancelled
191
+ * this" apart from "this genuinely timed out" instead of both surfacing as
192
+ * an identical `StreamResetError("timeout", ...)`.
193
+ */
194
+ const callerAbortError = (signal: AbortSignal | undefined): Error => {
195
+ const reason: unknown = signal?.reason;
196
+ if (reason instanceof Error) return reason;
197
+ if (typeof reason === "object" && reason !== null) {
198
+ const message = (reason as { message?: unknown }).message;
199
+ const name = (reason as { name?: unknown }).name;
200
+ if (typeof message === "string") {
201
+ return new DOMException(
202
+ message,
203
+ typeof name === "string" ? name : "AbortError",
204
+ );
205
+ }
206
+ }
207
+ return new DOMException("Aborted", "AbortError");
208
+ };
209
+
210
+ /**
211
+ * Mirror a mux stream as a ReadableStream. Cancelling a response body RESETs
212
+ * the remote stream so the peer can abort its work. Request-body cancellation
213
+ * only detaches the local reader: the peer may already have sent a response.
214
+ */
215
+ /**
216
+ * Soft cap on ReadableStream-queued body bytes that still auto-return mux
217
+ * WINDOW credit. Below this, credit is returned on enqueue (keeps BDP full
218
+ * under pull lag); above it, credit waits for `pull` so memory stays bounded.
219
+ */
220
+ const BODY_STREAM_SOFT_BUFFER_BYTES = 512 * 1024;
221
+
222
+ const bodyFromStream = (
223
+ stream: TMuxStream,
224
+ onReset?: () => void,
225
+ resetOnCancel = true,
226
+ ): ReadableStream<Uint8Array> => {
227
+ let offData: (() => void) | undefined;
228
+ let offEnd: (() => void) | undefined;
229
+ let offReset: (() => void) | undefined;
230
+ const delivered: Array<{
231
+ readonly bytes: number;
232
+ readonly deferred: boolean;
233
+ }> = [];
234
+ let queuedBytes = 0;
235
+ let controller: ReadableStreamDefaultController<Uint8Array> | undefined;
236
+ const cleanup = (): void => {
237
+ offData?.();
238
+ offEnd?.();
239
+ offReset?.();
240
+ offData = undefined;
241
+ offEnd = undefined;
242
+ offReset = undefined;
243
+ };
244
+ return new ReadableStream<Uint8Array>({
245
+ start(nextController) {
246
+ controller = nextController;
247
+ offData = stream.onData((bytes) => {
248
+ const nextQueued = queuedBytes + bytes.byteLength;
249
+ // Defer credit only once the soft buffer would be exceeded — otherwise
250
+ // auto-consume so WINDOW returns without waiting on downstream pull lag.
251
+ const defer = nextQueued > BODY_STREAM_SOFT_BUFFER_BYTES;
252
+ delivered.push({ bytes: bytes.byteLength, deferred: defer });
253
+ queuedBytes = nextQueued;
254
+ nextController.enqueue(bytes);
255
+ return defer ? false : undefined;
256
+ });
257
+ offEnd = stream.onEnd(() => {
258
+ cleanup();
259
+ nextController.close();
260
+ });
261
+ offReset = stream.onReset((payload) => {
262
+ cleanup();
263
+ onReset?.();
264
+ controller?.error(unknownReset(payload));
265
+ });
266
+ },
267
+ pull() {
268
+ const item = delivered.shift();
269
+ if (item === undefined) return;
270
+ queuedBytes = Math.max(0, queuedBytes - item.bytes);
271
+ if (item.deferred) stream.consume(item.bytes);
272
+ },
273
+ cancel() {
274
+ cleanup();
275
+ if (resetOnCancel) {
276
+ stream.reset(streamReset("peer_gone", "consumer cancelled"));
277
+ }
278
+ },
279
+ });
280
+ };
281
+
282
+ const pumpBody = async (
283
+ stream: TMuxStream,
284
+ body: ReadableStream<Uint8Array> | Uint8Array | null,
285
+ signal?: AbortSignal,
286
+ ): Promise<void> => {
287
+ if (body === null) {
288
+ stream.end();
289
+ return;
290
+ }
291
+ if (body instanceof Uint8Array) {
292
+ if (signal?.aborted) {
293
+ stream.reset(streamReset("peer_gone", "aborted"));
294
+ return;
295
+ }
296
+ // Brief write window — still honor abort so a pre-end cancel reaches the peer.
297
+ const onAbort = (): void => {
298
+ stream.reset(streamReset("peer_gone", "aborted"));
299
+ };
300
+ signal?.addEventListener("abort", onAbort, { once: true });
301
+ try {
302
+ if (body.byteLength > 0) await stream.write(body);
303
+ if (!signal?.aborted) stream.end();
304
+ } catch (error) {
305
+ stream.reset(
306
+ streamReset(
307
+ "peer_gone",
308
+ error instanceof Error ? error.message : undefined,
309
+ ),
310
+ );
311
+ } finally {
312
+ signal?.removeEventListener("abort", onAbort);
313
+ }
314
+ return;
315
+ }
316
+ const reader = body.getReader();
317
+ // Cancel the reader on abort so a pending read() unblocks and finally runs.
318
+ const onAbort = (): void => {
319
+ stream.reset(streamReset("peer_gone", "aborted"));
320
+ void reader.cancel().catch(() => {});
321
+ };
322
+ if (signal?.aborted) {
323
+ onAbort();
324
+ reader.releaseLock();
325
+ return;
326
+ }
327
+ signal?.addEventListener("abort", onAbort, { once: true });
328
+ try {
329
+ for (;;) {
330
+ if (signal?.aborted) return;
331
+ const next = await reader.read();
332
+ if (next.done) break;
333
+ if (next.value.byteLength > 0) await stream.write(next.value);
334
+ }
335
+ if (!signal?.aborted) stream.end();
336
+ } catch (error) {
337
+ stream.reset(
338
+ streamReset(
339
+ "peer_gone",
340
+ error instanceof Error ? error.message : undefined,
341
+ ),
342
+ );
343
+ } finally {
344
+ signal?.removeEventListener("abort", onAbort);
345
+ reader.releaseLock();
346
+ }
347
+ };
348
+
349
+ export type TTunnelStreamOptions = {
350
+ readonly surface: TTunnelSurface;
351
+ readonly headers?: TTunnelForwardHeaders;
352
+ readonly body: ReadableStream<Uint8Array> | Uint8Array | null;
353
+ readonly signal?: AbortSignal;
354
+ /**
355
+ * Max wait for the serving end's `res_head` CTRL before rejecting with
356
+ * `"tunnel response timed out"` and RESETing the stream. Defaults to
357
+ * {@link TUNNEL_RESPONSE_HEAD_TIMEOUT_MS} (legacy tunnel parity).
358
+ */
359
+ readonly headTimeoutMs?: number;
360
+ /**
361
+ * Who opened this stream. Daemon fleet hops set `"daemon"` so the serving
362
+ * end can stamp the walker loop-guard (`x-openllm-tunneled`). Browser
363
+ * omits this (or sets `"browser"`) so the selected device may still
364
+ * `tryFleetTunnel` once. See browser-selected-device-tunnel-contract.
365
+ */
366
+ readonly consumer?: "browser" | "daemon";
367
+ };
368
+
369
+ export type TTunnelStreamResult = {
370
+ readonly status: number;
371
+ readonly headers: Headers;
372
+ readonly body: ReadableStream<Uint8Array>;
373
+ };
374
+
375
+ /** Open a request stream and begin writing the body before the serving head arrives. */
376
+ export const tunnelStream = (
377
+ channel: TMuxChannel,
378
+ options: TTunnelStreamOptions,
379
+ ): Promise<TTunnelStreamResult> =>
380
+ new Promise<TTunnelStreamResult>((resolve, reject) => {
381
+ const stream = channel.openStream(
382
+ encodeJsonPayload({
383
+ kind: "tunnel",
384
+ method: "POST",
385
+ surface: options.surface,
386
+ ...(options.headers === undefined ? {} : { headers: options.headers }),
387
+ ...(options.consumer === undefined
388
+ ? {}
389
+ : { consumer: options.consumer }),
390
+ }),
391
+ );
392
+ let settled = false;
393
+ let offCtrl = (): void => {};
394
+ let offReset = (): void => {};
395
+ const headTimeoutMs =
396
+ options.headTimeoutMs ?? TUNNEL_RESPONSE_HEAD_TIMEOUT_MS;
397
+
398
+ const settle = (result: TTunnelStreamResult | Error): void => {
399
+ if (settled) return;
400
+ settled = true;
401
+ clearTimeout(headTimer);
402
+ options.signal?.removeEventListener("abort", onAbort);
403
+ offCtrl();
404
+ offReset();
405
+ if (result instanceof Error) reject(result);
406
+ else resolve(result);
407
+ };
408
+
409
+ // Settle FIRST so the local onReset from stream.reset() cannot
410
+ // overwrite AbortError / timeout with unknownReset(payload).
411
+ const onAbort = (): void => {
412
+ settle(new DOMException("Aborted", "AbortError"));
413
+ stream.reset(streamReset("peer_gone", "aborted"));
414
+ };
415
+
416
+ const headTimer = setTimeout(() => {
417
+ settle(new Error("tunnel response timed out"));
418
+ stream.reset(streamReset("timeout", "tunnel response timed out"));
419
+ }, headTimeoutMs);
420
+
421
+ offCtrl = stream.onCtrl((payload) => {
422
+ const ctrl = parseStreamCtrlPayload(decodeJsonPayload(payload));
423
+ if (ctrl?.t !== "res_head") return;
424
+ const headers = new Headers();
425
+ if (ctrl.res_headers !== undefined) {
426
+ applyTunnelResponseHeadersToHttp(headers, ctrl.res_headers);
427
+ }
428
+ settle({ status: ctrl.status, headers, body: bodyFromStream(stream) });
429
+ });
430
+ offReset = stream.onReset((payload) => settle(unknownReset(payload)));
431
+
432
+ // Arm abort before pumping the body so AbortError wins the settle race
433
+ // against pumpBody's own reset → onReset(unknownReset) path.
434
+ if (options.signal?.aborted) {
435
+ onAbort();
436
+ return;
437
+ }
438
+ options.signal?.addEventListener("abort", onAbort, { once: true });
439
+ void pumpBody(stream, options.body, options.signal);
440
+ });
441
+
442
+ /**
443
+ * Wrap a mux stream's DATA channel as an NDJSON realtime-event pump: each
444
+ * inbound chunk is split on `\n` (carrying a remainder across calls), every
445
+ * complete line is decoded + schema-validated by `parse`, and mux receive
446
+ * credit is replenished immediately (events are consumed synchronously here,
447
+ * never deferred). An oversized/never-terminated line calls `onOverflow`
448
+ * instead of growing the buffer — the caller decides how to RESET.
449
+ *
450
+ * Shared by the CONSUMER side (`realtimeStream` below) and the SERVING side
451
+ * (a daemon's `kind:"realtime"` dispatch), so both directions get the same
452
+ * framing and the same bounded-line behavior.
453
+ */
454
+ export const pumpRealtimeEvents = <T>(
455
+ stream: TMuxStream,
456
+ parse: (value: unknown) => T | null,
457
+ onEvent: (event: T) => void,
458
+ onOverflow: () => void,
459
+ ): (() => void) => {
460
+ let remainder: Uint8Array = new Uint8Array(0);
461
+ return stream.onData((bytes) => {
462
+ const split = splitRealtimeLines(remainder, bytes);
463
+ if (split === null) {
464
+ onOverflow();
465
+ return;
466
+ }
467
+ remainder = split.remainder;
468
+ // Events are decoded + dispatched synchronously in this callback, so
469
+ // receive credit is safe to replenish immediately (never deferred to a
470
+ // later `consume()`).
471
+ stream.consume(bytes.byteLength);
472
+ for (const line of split.lines) {
473
+ if (line.byteLength === 0) continue;
474
+ const decoded = decodeRealtimeLine(line);
475
+ const event = decoded === undefined ? null : parse(decoded);
476
+ if (event !== null) onEvent(event);
477
+ }
478
+ return false;
479
+ });
480
+ };
481
+
482
+ /** A single realtime event, JSON-encoded + newline-terminated, written to the
483
+ * stream's DATA channel. Returns the underlying `write()` promise so a
484
+ * SERVING-side caller can track backpressure (a CONSUMER-side caller may
485
+ * ignore it — `realtimeStream`'s `send` does). Silently drops an event that
486
+ * fails to encode (oversized/non-serializable) rather than desyncing the
487
+ * NDJSON framing with a truncated line. */
488
+ export const sendRealtimeEvent = (
489
+ stream: TMuxStream,
490
+ event: unknown,
491
+ ): Promise<void> => {
492
+ const line = encodeRealtimeEventLine(event);
493
+ if (line === null) return Promise.resolve();
494
+ return stream.write(line).catch(() => {});
495
+ };
496
+
497
+ export type TRealtimeStreamOptions = {
498
+ readonly provider: TRealtimeProvider;
499
+ readonly model: TRealtimeModel;
500
+ readonly voice: TRealtimeVoice;
501
+ readonly signal?: AbortSignal;
502
+ /**
503
+ * Max wait for the serving end's `open_ack` CTRL before rejecting and
504
+ * RESETing the stream with `timeout`. Defaults to
505
+ * {@link TUNNEL_RESPONSE_HEAD_TIMEOUT_MS} — mirrors `tunnelStream`'s own
506
+ * `headTimeoutMs` default and, like it, applies UNCONDITIONALLY: an
507
+ * absent `options.signal` must not leave a peer that never acks hanging
508
+ * forever.
509
+ */
510
+ readonly headTimeoutMs?: number;
511
+ /** Test/override seams — production defaults to the shared protocol bounds. */
512
+ readonly heartbeatIntervalMs?: number;
513
+ readonly heartbeatTimeoutMs?: number;
514
+ readonly maxLifetimeMs?: number;
515
+ };
516
+
517
+ export type TRealtimeStreamResult = {
518
+ readonly send: (event: TRealtimeClientEvent) => void;
519
+ readonly onServerEvent: (
520
+ handler: (event: TRealtimeServerEvent) => void,
521
+ ) => () => void;
522
+ readonly close: () => void;
523
+ readonly closed: Promise<TStreamResetCode | "done">;
524
+ };
525
+
526
+ /**
527
+ * Open a realtime duplex session over a mux channel (the browser/fleet
528
+ * CONSUMER side). Resolves once the serving daemon acks (`open_ack`);
529
+ * rejects with the nack code/message when refused (`realtime_refused`,
530
+ * `realtime_busy`, `realtime_unsupported`).
531
+ *
532
+ * Events ride NDJSON-framed over the stream's flow-controlled DATA channel
533
+ * (real mux backpressure, unlike CTRL) via `pumpRealtimeEvents` /
534
+ * `sendRealtimeEvent`. A `{t:"heartbeat"}` CTRL keeps the session alive
535
+ * through natural silence; missing ALL inbound traffic for
536
+ * `heartbeatTimeoutMs`, or exceeding `maxLifetimeMs` total, RESETs with
537
+ * `timeout`. Callers MUST check `hasRealtimeDuplexCap` on the peer's
538
+ * capabilities before calling this — an old peer that doesn't understand
539
+ * `kind:"realtime"` should never receive the OPEN in the first place.
540
+ */
541
+ export const realtimeStream = (
542
+ channel: TMuxChannel,
543
+ options: TRealtimeStreamOptions,
544
+ ): Promise<TRealtimeStreamResult> => {
545
+ const stream = channel.openStream(
546
+ encodeJsonPayload({
547
+ kind: "realtime",
548
+ provider: options.provider,
549
+ model: options.model,
550
+ voice: options.voice,
551
+ }),
552
+ );
553
+ const heartbeatIntervalMs =
554
+ options.heartbeatIntervalMs ?? REALTIME_HEARTBEAT_INTERVAL_MS;
555
+ const heartbeatTimeoutMs =
556
+ options.heartbeatTimeoutMs ?? REALTIME_HEARTBEAT_TIMEOUT_MS;
557
+ const maxLifetimeMs =
558
+ options.maxLifetimeMs ?? REALTIME_SESSION_MAX_LIFETIME_MS;
559
+ const headTimeoutMs =
560
+ options.headTimeoutMs ?? TUNNEL_RESPONSE_HEAD_TIMEOUT_MS;
561
+
562
+ const serverEventHandlers = new Set<(event: TRealtimeServerEvent) => void>();
563
+ let resolveClosed: (result: TStreamResetCode | "done") => void = () => {};
564
+ const closed = new Promise<TStreamResetCode | "done">((resolve) => {
565
+ resolveClosed = resolve;
566
+ });
567
+ let closedResult = false;
568
+ const finish = (result: TStreamResetCode | "done"): void => {
569
+ if (closedResult) return;
570
+ closedResult = true;
571
+ resolveClosed(result);
572
+ };
573
+
574
+ let lastInboundAt = Date.now();
575
+ let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
576
+ let lifetimeTimer: ReturnType<typeof setTimeout> | undefined;
577
+ const stopTimers = (): void => {
578
+ if (heartbeatTimer !== undefined) clearInterval(heartbeatTimer);
579
+ if (lifetimeTimer !== undefined) clearTimeout(lifetimeTimer);
580
+ heartbeatTimer = undefined;
581
+ lifetimeTimer = undefined;
582
+ };
583
+
584
+ return new Promise<TRealtimeStreamResult>((resolve, reject) => {
585
+ let settled = false;
586
+ const settleReject = (error: Error): void => {
587
+ if (settled) return;
588
+ settled = true;
589
+ clearTimeout(headTimer);
590
+ options.signal?.removeEventListener("abort", onAbort);
591
+ reject(error);
592
+ };
593
+ const onAbort = (): void => {
594
+ // `options.signal` may itself be a MERGED signal (e.g. the mux ladder's
595
+ // `AbortSignal.any([callerSignal, AbortSignal.timeout(rungBudgetMs)])`)
596
+ // — a timeout-shaped reason keeps producing the exact same
597
+ // `StreamResetError("timeout", ...)` as before (so `isTransportFailure`
598
+ // keeps treating it as retryable and rung failover is unaffected), but
599
+ // any OTHER reason is a genuine caller cancellation and must reject as
600
+ // a distinguishable AbortError, never mislabeled as a timeout.
601
+ //
602
+ // Settle FIRST, exactly like `tunnelStream`'s own `onAbort` — a
603
+ // `stream.reset()` below can synchronously fire this SAME stream's
604
+ // local `onReset` handler, which would otherwise overwrite the
605
+ // AbortError / distinguishing timeout rejection below with a generic
606
+ // `unknownReset(payload)` (`settleReject` is a no-op once `settled`).
607
+ if (isTimeoutAbortReason(options.signal?.reason)) {
608
+ finish("timeout");
609
+ settleReject(
610
+ new StreamResetError("timeout", "realtime session open timed out"),
611
+ );
612
+ stream.reset(streamReset("timeout", "realtime session open timed out"));
613
+ return;
614
+ }
615
+ // No dedicated "cancelled" code exists in the closed `StreamResetCode`
616
+ // wire vocabulary (adding one is a protocol change, out of scope here)
617
+ // — "timeout" is still the peer-facing teardown signal, but the LOCAL
618
+ // rejection below (what `openOverMuxLadder`/callers actually observe)
619
+ // is a real AbortError carrying the original abort reason, so it can
620
+ // never be confused with a genuine internal timeout.
621
+ finish("timeout");
622
+ settleReject(callerAbortError(options.signal));
623
+ stream.reset(
624
+ streamReset("timeout", "realtime session aborted by caller"),
625
+ );
626
+ };
627
+ // Handshake budget, independent of `options.signal`: a caller that opens
628
+ // with no signal at all (or one that never fires) must not wait forever
629
+ // on a peer that swallows the OPEN and never sends `open_ack` — mirrors
630
+ // `tunnelStream`'s own unconditional `headTimer`.
631
+ const headTimer = setTimeout(() => {
632
+ stream.reset(streamReset("timeout", "realtime session open timed out"));
633
+ finish("timeout");
634
+ settleReject(
635
+ new StreamResetError("timeout", "realtime session open timed out"),
636
+ );
637
+ }, headTimeoutMs);
638
+ const offReset = stream.onReset((payload) => {
639
+ stopTimers();
640
+ const code = resetCode(payload) ?? "peer_gone";
641
+ finish(code);
642
+ settleReject(unknownReset(payload));
643
+ });
644
+ const offEnd = stream.onEnd(() => {
645
+ stopTimers();
646
+ finish("done");
647
+ // A stream that ends before `open_ack` ever arrived must REJECT the
648
+ // opening promise, not leave it pending forever — `settleReject` is a
649
+ // no-op once `open_ack` already resolved it, so this is safe to call
650
+ // unconditionally on every END.
651
+ settleReject(
652
+ new StreamResetError("peer_gone", "stream ended before open_ack"),
653
+ );
654
+ });
655
+ const offData = pumpRealtimeEvents(
656
+ stream,
657
+ (value) => {
658
+ // Any successfully decoded JSON line is inbound traffic — refresh
659
+ // BEFORE schema parse so unrecognized vendor events still keep the
660
+ // heartbeat alive. Silence (no DATA / CTRL) still times out.
661
+ lastInboundAt = Date.now();
662
+ return parseRealtimeServerEvent(value);
663
+ },
664
+ (event) => {
665
+ for (const handler of serverEventHandlers) handler(event);
666
+ },
667
+ () =>
668
+ stream.reset(streamReset("lagging", "realtime event line too large")),
669
+ );
670
+ const offCtrl = stream.onCtrl((payload) => {
671
+ const ctrl = parseStreamCtrlPayload(decodeJsonPayload(payload));
672
+ if (ctrl === null) return;
673
+ if (ctrl.t === "heartbeat") {
674
+ lastInboundAt = Date.now();
675
+ return;
676
+ }
677
+ if (ctrl.t !== "open_ack" || settled) return;
678
+ if (!ctrl.ok) {
679
+ const detail =
680
+ (typeof ctrl.message === "string" && ctrl.message.length > 0
681
+ ? ctrl.message
682
+ : undefined) ??
683
+ (typeof ctrl.error === "string" && ctrl.error.length > 0
684
+ ? ctrl.error
685
+ : undefined) ??
686
+ "realtime session refused";
687
+ const nackCode = isStreamResetCode(ctrl.error)
688
+ ? ctrl.error
689
+ : "protocol_error";
690
+ settleReject(new StreamResetError(nackCode, detail));
691
+ stream.reset(streamReset("protocol_error", detail));
692
+ finish("protocol_error");
693
+ return;
694
+ }
695
+ settled = true;
696
+ clearTimeout(headTimer);
697
+ lastInboundAt = Date.now();
698
+ options.signal?.removeEventListener("abort", onAbort);
699
+ lifetimeTimer = setTimeout(() => {
700
+ stream.reset(
701
+ streamReset("timeout", "realtime session max lifetime reached"),
702
+ );
703
+ }, maxLifetimeMs);
704
+ heartbeatTimer = setInterval(() => {
705
+ if (Date.now() - lastInboundAt > heartbeatTimeoutMs) {
706
+ stream.reset(streamReset("timeout", "realtime heartbeat timed out"));
707
+ return;
708
+ }
709
+ stream.sendCtrl(encodeJsonPayload({ t: "heartbeat" }));
710
+ }, heartbeatIntervalMs);
711
+ resolve({
712
+ send: (event) => {
713
+ void sendRealtimeEvent(stream, event);
714
+ },
715
+ onServerEvent: (handler) => {
716
+ serverEventHandlers.add(handler);
717
+ return () => serverEventHandlers.delete(handler);
718
+ },
719
+ close: () => {
720
+ stopTimers();
721
+ stream.end();
722
+ finish("done");
723
+ },
724
+ closed,
725
+ });
726
+ });
727
+ if (options.signal?.aborted) {
728
+ onAbort();
729
+ } else {
730
+ options.signal?.addEventListener("abort", onAbort, { once: true });
731
+ }
732
+ void offReset;
733
+ void offEnd;
734
+ void offData;
735
+ void offCtrl;
736
+ });
737
+ };
738
+
739
+ /** Default wait for the serving daemon's agent `open_ack`. */
740
+ export const AGENT_OPEN_TIMEOUT_MS = 30_000;
741
+
742
+ /** Consumer liveness heartbeat cadence on an open agent stream. */
743
+ export const AGENT_HEARTBEAT_INTERVAL_MS = 15_000;
744
+
745
+ /** Events held for a consumer that has not subscribed yet (then `lagging`). */
746
+ export const AGENT_MAX_BUFFERED_EVENTS = 1024;
747
+
748
+ /**
749
+ * Feed a mux stream's DATA as agent NDJSON lines: split (bounded by
750
+ * {@link AGENT_MAX_LINE_BYTES}), decode, `parse`, dispatch. Receive credit is
751
+ * replenished immediately — lines are consumed synchronously here. Shared by
752
+ * the consumer ({@link agentStream}) and serving ({@link pumpAgentCommands})
753
+ * sides so both get identical framing.
754
+ */
755
+ const pumpAgentLines = <T>(
756
+ stream: TMuxStream,
757
+ parse: (value: unknown) => T | null,
758
+ handlers: {
759
+ readonly onValue: (value: T) => void;
760
+ readonly onInvalid?: (value: unknown) => void;
761
+ readonly onOverflow: () => void;
762
+ },
763
+ ): (() => void) => {
764
+ const splitter = createAgentLineSplitter(AGENT_MAX_LINE_BYTES);
765
+ return stream.onData((bytes) => {
766
+ const lines = splitter.push(bytes);
767
+ stream.consume(bytes.byteLength);
768
+ if (lines === null) {
769
+ handlers.onOverflow();
770
+ return false;
771
+ }
772
+ for (const line of lines) {
773
+ if (line.byteLength === 0) continue;
774
+ const decoded = decodeAgentLine(line);
775
+ const value = decoded === undefined ? null : parse(decoded);
776
+ if (value === null) handlers.onInvalid?.(decoded);
777
+ else handlers.onValue(value);
778
+ }
779
+ return false;
780
+ });
781
+ };
782
+
783
+ /** Write one NDJSON line; false when it does not encode/fit or the write fails. */
784
+ const writeAgentLine = async (
785
+ stream: TMuxStream,
786
+ value: unknown,
787
+ ): Promise<boolean> => {
788
+ const line = encodeAgentLine(value);
789
+ if (line === null) return false;
790
+ try {
791
+ // The mux splits a write into frames under its negotiated payload cap.
792
+ await stream.write(line);
793
+ return true;
794
+ } catch {
795
+ return false;
796
+ }
797
+ };
798
+
799
+ /** Serving side: acknowledge an admitted agent OPEN. */
800
+ export const acceptAgentStream = (stream: TMuxStream): void => {
801
+ stream.sendCtrl(encodeJsonPayload({ t: "open_ack", ok: true }));
802
+ };
803
+
804
+ /**
805
+ * Serving side: dispatch each valid command line to `onCommand`. A line that
806
+ * is not a valid {@link TAgentCommand} goes to `onInvalid` (answer with a
807
+ * `runtime.error`); an over-long line RESETs `protocol_error`.
808
+ */
809
+ export const pumpAgentCommands = (
810
+ stream: TMuxStream,
811
+ onCommand: (command: TAgentCommand) => void,
812
+ onInvalid?: (value: unknown) => void,
813
+ ): (() => void) =>
814
+ pumpAgentLines(stream, parseAgentCommand, {
815
+ onValue: onCommand,
816
+ ...(onInvalid === undefined ? {} : { onInvalid }),
817
+ onOverflow: () =>
818
+ stream.reset(streamReset("protocol_error", "agent command too large")),
819
+ });
820
+
821
+ /**
822
+ * Serving side: write one event line. Resolves false when the event does not
823
+ * fit one line (truncate tool output and retry) or the stream is gone.
824
+ * Awaiting it applies mux backpressure to the engine adapter.
825
+ */
826
+ export const sendAgentEvent = (
827
+ stream: TMuxStream,
828
+ event: TAgentEvent,
829
+ ): Promise<boolean> => writeAgentLine(stream, event);
830
+
831
+ /**
832
+ * Initiator-side Noise_IK wrap for a relay-mux agent stream. Prefer this over
833
+ * a hand-rolled {@link TAgentStreamOptions.prepareStream} when the caller
834
+ * already has `remoteStatic` (`dpk`), the matching {@link agentSecurePrologue},
835
+ * and a fresh grant as `payload`. The RTC rung leaves this unset (DTLS is
836
+ * already E2E).
837
+ */
838
+ export type TAgentStreamSecureOptions = {
839
+ /** Responder static key (`dpk`): raw 32 bytes or SPKI DER base64. */
840
+ readonly remoteStatic: Uint8Array | string;
841
+ /** Must equal {@link agentSecurePrologue}(channelId, stream.id). */
842
+ readonly prologue: Uint8Array;
843
+ /** Message-1 payload — a fresh device grant (UTF-8 envelope). */
844
+ readonly payload?: Uint8Array;
845
+ /** Defaults to a fresh per-session key. */
846
+ readonly localStatic?: TNoiseStaticKey;
847
+ };
848
+
849
+ export type TAgentStreamOptions = {
850
+ readonly signal?: AbortSignal;
851
+ /** Max wait for `open_ack`; defaults to {@link AGENT_OPEN_TIMEOUT_MS}. */
852
+ readonly headTimeoutMs?: number;
853
+ /** CTRL heartbeat cadence; `0` disables. Defaults to {@link AGENT_HEARTBEAT_INTERVAL_MS}. */
854
+ readonly heartbeatIntervalMs?: number;
855
+ /** RESET `timeout` after this long with no inbound traffic. Off when omitted:
856
+ * an agent session may idle for hours waiting on the user. */
857
+ readonly heartbeatTimeoutMs?: number;
858
+ /** Defaults to {@link AGENT_MAX_BUFFERED_EVENTS}. */
859
+ readonly maxBufferedEvents?: number;
860
+ /**
861
+ * Optional wrapper run after OPEN is sent and before waiting for `open_ack`.
862
+ * The relay-mux agent path uses this (or {@link secure}) to run Noise_IK
863
+ * (initiator) so DATA/CTRL are E2E-encrypted; the RTC rung leaves it unset
864
+ * (DTLS is already E2E). Must subscribe to the stream synchronously before
865
+ * any `await`. Wins over {@link secure} when both are set.
866
+ */
867
+ readonly prepareStream?: (stream: TMuxStream) => Promise<TMuxStream>;
868
+ /**
869
+ * Convenience Noise_IK initiator wrap. Equivalent to a `prepareStream` that
870
+ * calls {@link secureMuxStream} with `role:"initiator"`. Ignored when
871
+ * {@link prepareStream} is also set.
872
+ */
873
+ readonly secure?: TAgentStreamSecureOptions;
874
+ };
875
+
876
+ export type TAgentCloseResult = TStreamResetCode | "done" | "detach";
877
+
878
+ export type TAgentStreamResult = {
879
+ /** Write one command line. Rejects when it does not fit a line or the
880
+ * stream is gone. */
881
+ readonly send: (command: TAgentCommand) => Promise<void>;
882
+ /** Subscribe to events. The FIRST subscriber also receives every event
883
+ * that arrived before it registered (e.g. right after `open_ack`). */
884
+ readonly onEvent: (handler: (event: TAgentEvent) => void) => () => void;
885
+ /** Fires once when an attach replay finishes (`replay_done` CTRL). Latched. */
886
+ readonly onReplayDone: (callback: () => void) => () => void;
887
+ /** Browser device-session focus controls; old daemons ignore these CTRLs. */
888
+ readonly focus: () => void;
889
+ readonly blur: () => void;
890
+ /** End the stream, leaving the engine session running for a later attach. */
891
+ readonly detach: () => void;
892
+ /** Send `close` (end the engine session), then end the stream. */
893
+ readonly close: () => void;
894
+ readonly closed: Promise<TAgentCloseResult>;
895
+ };
896
+
897
+ /**
898
+ * Open a `kind:"agent"` stream over a mux channel (browser consumer side) —
899
+ * RTC first, relay mux fallback, same helper either way. Resolves once the
900
+ * serving daemon acks (`open_ack`); rejects with the RESET / nack code
901
+ * (`unauthorized` for a channel without a device grant, `agent_unavailable`,
902
+ * `agent_busy`, `pty_unsupported` never applies here).
903
+ *
904
+ * Commands and events ride NDJSON lines over the flow-controlled DATA channel.
905
+ * Callers MUST check `hasAgentCap` on the peer's caps before calling this —
906
+ * an old daemon resets an unknown kind as an invalid OPEN.
907
+ */
908
+ export const agentStream = (
909
+ channel: TMuxChannel,
910
+ options: TAgentStreamOptions = {},
911
+ ): Promise<TAgentStreamResult> => {
912
+ const rawStream = channel.openStream(encodeJsonPayload({ kind: "agent" }));
913
+ const headTimeoutMs = options.headTimeoutMs ?? AGENT_OPEN_TIMEOUT_MS;
914
+ const heartbeatIntervalMs =
915
+ options.heartbeatIntervalMs ?? AGENT_HEARTBEAT_INTERVAL_MS;
916
+ const maxBufferedEvents =
917
+ options.maxBufferedEvents ?? AGENT_MAX_BUFFERED_EVENTS;
918
+
919
+ const eventHandlers = new Set<(event: TAgentEvent) => void>();
920
+ const buffered: TAgentEvent[] = [];
921
+ const replayHandlers = new Set<() => void>();
922
+ let replayDoneSeen = false;
923
+
924
+ let resolveClosed: (result: TAgentCloseResult) => void = () => {};
925
+ const closed = new Promise<TAgentCloseResult>((resolve) => {
926
+ resolveClosed = resolve;
927
+ });
928
+ let closedResult = false;
929
+ let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
930
+ let lastInboundAt = Date.now();
931
+ const stopTimers = (): void => {
932
+ if (heartbeatTimer !== undefined) clearInterval(heartbeatTimer);
933
+ heartbeatTimer = undefined;
934
+ };
935
+ const finish = (result: TAgentCloseResult): void => {
936
+ stopTimers();
937
+ if (closedResult) return;
938
+ closedResult = true;
939
+ resolveClosed(result);
940
+ };
941
+
942
+ const bindAgentStream = (
943
+ stream: TMuxStream,
944
+ resolve: (result: TAgentStreamResult) => void,
945
+ reject: (error: Error) => void,
946
+ ): void => {
947
+ const deliver = (event: TAgentEvent): void => {
948
+ lastInboundAt = Date.now();
949
+ if (eventHandlers.size === 0) {
950
+ if (buffered.length >= maxBufferedEvents) {
951
+ stream.reset(streamReset("lagging", "agent events not consumed"));
952
+ finish("lagging");
953
+ return;
954
+ }
955
+ buffered.push(event);
956
+ return;
957
+ }
958
+ for (const handler of eventHandlers) handler(event);
959
+ };
960
+
961
+ let settled = false;
962
+ const settleReject = (error: Error): void => {
963
+ if (settled) return;
964
+ settled = true;
965
+ clearTimeout(headTimer);
966
+ options.signal?.removeEventListener("abort", onAbort);
967
+ reject(error);
968
+ };
969
+ const onAbort = (): void => {
970
+ // Settle first: the local onReset from stream.reset() must not replace
971
+ // the AbortError / timeout rejection with unknownReset(payload).
972
+ if (isTimeoutAbortReason(options.signal?.reason)) {
973
+ finish("timeout");
974
+ settleReject(
975
+ new StreamResetError("timeout", "agent session open timed out"),
976
+ );
977
+ stream.reset(streamReset("timeout", "agent session open timed out"));
978
+ return;
979
+ }
980
+ finish("timeout");
981
+ settleReject(callerAbortError(options.signal));
982
+ stream.reset(streamReset("timeout", "agent session aborted by caller"));
983
+ };
984
+ const headTimer = setTimeout(() => {
985
+ finish("timeout");
986
+ settleReject(
987
+ new StreamResetError("timeout", "agent session open timed out"),
988
+ );
989
+ stream.reset(streamReset("timeout", "agent session open timed out"));
990
+ }, headTimeoutMs);
991
+
992
+ const offReset = stream.onReset((payload) => {
993
+ finish(resetCode(payload) ?? "peer_gone");
994
+ settleReject(unknownReset(payload));
995
+ });
996
+ const offEnd = stream.onEnd(() => {
997
+ finish("done");
998
+ settleReject(
999
+ new StreamResetError("peer_gone", "stream ended before open_ack"),
1000
+ );
1001
+ });
1002
+ const offData = pumpAgentLines(stream, parseAgentEvent, {
1003
+ onValue: deliver,
1004
+ // Unknown (newer) event types are dropped, but still count as traffic.
1005
+ onInvalid: () => {
1006
+ lastInboundAt = Date.now();
1007
+ },
1008
+ onOverflow: () => {
1009
+ stream.reset(streamReset("lagging", "agent event line too large"));
1010
+ finish("lagging");
1011
+ },
1012
+ });
1013
+ const offCtrl = stream.onCtrl((payload) => {
1014
+ lastInboundAt = Date.now();
1015
+ const ctrl = parseStreamCtrlPayload(decodeJsonPayload(payload));
1016
+ if (ctrl === null) return;
1017
+ if (ctrl.t === "replay_done") {
1018
+ if (replayDoneSeen) return;
1019
+ replayDoneSeen = true;
1020
+ for (const handler of replayHandlers) handler();
1021
+ return;
1022
+ }
1023
+ if (ctrl.t !== "open_ack" || settled) return;
1024
+ if (!ctrl.ok) {
1025
+ const detail =
1026
+ (typeof ctrl.message === "string" && ctrl.message.length > 0
1027
+ ? ctrl.message
1028
+ : undefined) ??
1029
+ (typeof ctrl.error === "string" && ctrl.error.length > 0
1030
+ ? ctrl.error
1031
+ : undefined) ??
1032
+ "agent session refused";
1033
+ const nackCode = isStreamResetCode(ctrl.error)
1034
+ ? ctrl.error
1035
+ : "protocol_error";
1036
+ // Finish before reset: a synchronous local onReset must not settle
1037
+ // `closed` with the peer-facing protocol_error instead of nackCode.
1038
+ settleReject(new StreamResetError(nackCode, detail));
1039
+ finish(nackCode);
1040
+ stream.reset(streamReset("protocol_error", detail));
1041
+ return;
1042
+ }
1043
+ settled = true;
1044
+ clearTimeout(headTimer);
1045
+ options.signal?.removeEventListener("abort", onAbort);
1046
+ if (heartbeatIntervalMs > 0) {
1047
+ heartbeatTimer = setInterval(() => {
1048
+ const timeoutMs = options.heartbeatTimeoutMs;
1049
+ if (
1050
+ timeoutMs !== undefined &&
1051
+ Date.now() - lastInboundAt > timeoutMs
1052
+ ) {
1053
+ stream.reset(streamReset("timeout", "agent heartbeat timed out"));
1054
+ finish("timeout");
1055
+ return;
1056
+ }
1057
+ stream.sendCtrl(encodeJsonPayload({ t: "heartbeat" }));
1058
+ }, heartbeatIntervalMs);
1059
+ }
1060
+ resolve({
1061
+ send: async (command) => {
1062
+ if (closedResult) throw new Error("agent stream closed");
1063
+ if (!(await writeAgentLine(stream, command))) {
1064
+ throw new Error("agent command not sent");
1065
+ }
1066
+ },
1067
+ onEvent: (handler) => {
1068
+ const first = eventHandlers.size === 0;
1069
+ eventHandlers.add(handler);
1070
+ if (first && buffered.length > 0) {
1071
+ for (const event of buffered.splice(0)) handler(event);
1072
+ }
1073
+ return () => {
1074
+ eventHandlers.delete(handler);
1075
+ };
1076
+ },
1077
+ onReplayDone: (callback) => {
1078
+ if (replayDoneSeen) {
1079
+ callback();
1080
+ return () => {};
1081
+ }
1082
+ replayHandlers.add(callback);
1083
+ return () => {
1084
+ replayHandlers.delete(callback);
1085
+ };
1086
+ },
1087
+ focus: () => {
1088
+ if (!closedResult) stream.sendCtrl(encodeJsonPayload({ t: "focus" }));
1089
+ },
1090
+ blur: () => {
1091
+ if (!closedResult) stream.sendCtrl(encodeJsonPayload({ t: "blur" }));
1092
+ },
1093
+ detach: () => {
1094
+ stream.end();
1095
+ finish("detach");
1096
+ },
1097
+ close: () => {
1098
+ void writeAgentLine(stream, { type: "close" }).finally(() => {
1099
+ stream.end();
1100
+ });
1101
+ finish("done");
1102
+ },
1103
+ closed,
1104
+ });
1105
+ });
1106
+ if (options.signal?.aborted) {
1107
+ onAbort();
1108
+ } else {
1109
+ options.signal?.addEventListener("abort", onAbort, { once: true });
1110
+ }
1111
+ void offReset;
1112
+ void offEnd;
1113
+ void offData;
1114
+ void offCtrl;
1115
+ };
1116
+
1117
+ const prepareStream =
1118
+ options.prepareStream ??
1119
+ (options.secure === undefined
1120
+ ? undefined
1121
+ : (stream: TMuxStream): Promise<TMuxStream> => {
1122
+ const secure = options.secure;
1123
+ if (secure === undefined) {
1124
+ return Promise.resolve(stream);
1125
+ }
1126
+ return secureMuxStream(stream, {
1127
+ role: "initiator",
1128
+ remoteStatic: secure.remoteStatic,
1129
+ prologue: secure.prologue,
1130
+ ...(secure.payload === undefined
1131
+ ? {}
1132
+ : { payload: secure.payload }),
1133
+ ...(secure.localStatic === undefined
1134
+ ? {}
1135
+ : { localStatic: secure.localStatic }),
1136
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
1137
+ });
1138
+ });
1139
+
1140
+ if (prepareStream === undefined) {
1141
+ return new Promise<TAgentStreamResult>((resolve, reject) => {
1142
+ bindAgentStream(rawStream, resolve, reject);
1143
+ });
1144
+ }
1145
+
1146
+ // Capture a peer RESET that lands during preparation so we surface the
1147
+ // peer's code instead of overwriting it with our own unauthorized reset.
1148
+ // Local resets from prepareStream (e.g. secureMuxStream.fail → stream.reset)
1149
+ // must NOT count as peer-originated: wrap `reset` so those are ignored here.
1150
+ // bindAgentStream failures must NOT enter this handler (two-arg then), or
1151
+ // a post-open nack would trigger a second reset on the already-closed stream.
1152
+ let peerResetPayload: Uint8Array | null = null;
1153
+ let resettingLocally = false;
1154
+ const offPrepareReset = rawStream.onReset((payload) => {
1155
+ if (resettingLocally) return;
1156
+ peerResetPayload = payload;
1157
+ });
1158
+ const prepareInput: TMuxStream = {
1159
+ id: rawStream.id,
1160
+ write: (bytes) => rawStream.write(bytes),
1161
+ end: () => {
1162
+ rawStream.end();
1163
+ },
1164
+ reset: (payload) => {
1165
+ resettingLocally = true;
1166
+ try {
1167
+ rawStream.reset(payload);
1168
+ } finally {
1169
+ resettingLocally = false;
1170
+ }
1171
+ },
1172
+ sendCtrl: (payload) => {
1173
+ rawStream.sendCtrl(payload);
1174
+ },
1175
+ consume: (bytes) => {
1176
+ rawStream.consume(bytes);
1177
+ },
1178
+ onData: (handler) => rawStream.onData(handler),
1179
+ onEnd: (handler) => rawStream.onEnd(handler),
1180
+ onReset: (handler) => rawStream.onReset(handler),
1181
+ onCtrl: (handler) => rawStream.onCtrl(handler),
1182
+ };
1183
+
1184
+ return prepareStream(prepareInput).then(
1185
+ (prepared) => {
1186
+ offPrepareReset();
1187
+ return new Promise<TAgentStreamResult>((resolve, reject) => {
1188
+ bindAgentStream(prepared, resolve, reject);
1189
+ });
1190
+ },
1191
+ (err: unknown) => {
1192
+ offPrepareReset();
1193
+ // Caller abort / timeout wins over any RESET captured during prepare —
1194
+ // secureMuxStream may locally RESET on abort, and that must not replace
1195
+ // AbortError with unknownReset(local payload). Still RESET the raw
1196
+ // stream so a custom prepareStream that rejected without resetting
1197
+ // does not leak the OPEN on the peer.
1198
+ if (options.signal?.aborted === true) {
1199
+ try {
1200
+ resettingLocally = true;
1201
+ rawStream.reset(
1202
+ streamReset(
1203
+ isTimeoutAbortReason(options.signal.reason)
1204
+ ? "timeout"
1205
+ : "peer_gone",
1206
+ isTimeoutAbortReason(options.signal.reason)
1207
+ ? "agent session open timed out"
1208
+ : "aborted",
1209
+ ),
1210
+ );
1211
+ } catch {
1212
+ // already closed
1213
+ } finally {
1214
+ resettingLocally = false;
1215
+ }
1216
+ if (isTimeoutAbortReason(options.signal.reason)) {
1217
+ finish("timeout");
1218
+ return Promise.reject(
1219
+ new StreamResetError("timeout", "agent session open timed out"),
1220
+ );
1221
+ }
1222
+ finish("timeout");
1223
+ return Promise.reject(callerAbortError(options.signal));
1224
+ }
1225
+ const peerPayload = peerResetPayload;
1226
+ if (peerPayload !== null) {
1227
+ const peerErr = unknownReset(peerPayload);
1228
+ finish(peerErr.code);
1229
+ return Promise.reject(peerErr);
1230
+ }
1231
+ // Handshake / wrap failed with no peer RESET — RESET the raw stream
1232
+ // so the peer tears down.
1233
+ try {
1234
+ resettingLocally = true;
1235
+ rawStream.reset(
1236
+ streamReset(
1237
+ "unauthorized",
1238
+ err instanceof Error ? err.message : "secure handshake failed",
1239
+ ),
1240
+ );
1241
+ } catch {
1242
+ // already closed
1243
+ } finally {
1244
+ resettingLocally = false;
1245
+ }
1246
+ finish("unauthorized");
1247
+ return Promise.reject(
1248
+ err instanceof Error
1249
+ ? err
1250
+ : new StreamResetError("unauthorized", "secure handshake failed"),
1251
+ );
1252
+ },
1253
+ );
1254
+ };
1255
+
1256
+ export type TServeTunnelResponse = {
1257
+ readonly status: number;
1258
+ readonly headers?: TTunnelResponseHeaders;
1259
+ readonly body: ReadableStream<Uint8Array> | Uint8Array | null;
1260
+ /** Runs after the response body completes, errors, or the peer resets. */
1261
+ readonly onComplete?: () => void;
1262
+ };
1263
+
1264
+ export type TServeTunnel = (
1265
+ open: TTunnelStreamOpenPayload,
1266
+ body: ReadableStream<Uint8Array>,
1267
+ signal: AbortSignal,
1268
+ ) => Promise<TServeTunnelResponse>;
1269
+
1270
+ /** Serving-side `kind:"agent"` dispatch — given the raw stream, the handler
1271
+ * owns admission (nack via `stream.reset`), the `open_ack` CTRL
1272
+ * ({@link acceptAgentStream}), and the NDJSON exchange
1273
+ * ({@link pumpAgentCommands} / {@link sendAgentEvent}). The seed gate runs
1274
+ * BEFORE this is reached (daemon mux-host / RTC offer). */
1275
+ export type TServeAgent = (
1276
+ stream: TMuxStream,
1277
+ open: TAgentStreamOpenPayload,
1278
+ ) => void | Promise<void>;
1279
+
1280
+ /** Serving-side `kind:"realtime"` dispatch — given the raw stream, the
1281
+ * handler owns admission (nack via `stream.reset`), the `open_ack` CTRL,
1282
+ * and pumping events both ways (typically via `pumpRealtimeEvents` /
1283
+ * `sendRealtimeEvent`). Mirrors `TServeAgent`'s shape: unlike
1284
+ * `TServeTunnel` (one request/response), a realtime session is long-lived
1285
+ * and duplex. */
1286
+ export type TServeRealtime = (
1287
+ stream: TMuxStream,
1288
+ open: TRealtimeStreamOpenPayload,
1289
+ ) => void | Promise<void>;
1290
+
1291
+ export type TServeStreamsOptions = {
1292
+ readonly tunnel: TServeTunnel;
1293
+ /** Absent → a `kind:"agent"` OPEN resets `agent_unavailable`. */
1294
+ readonly agent?: TServeAgent;
1295
+ readonly realtime?: TServeRealtime;
1296
+ /** Reject a valid tunnel OPEN before dispatch, using host-specific wire semantics. */
1297
+ readonly admitTunnel?: (
1298
+ open: TTunnelStreamOpenPayload,
1299
+ ) => TStreamResetCode | null;
1300
+ /** Hosts that preserve a legacy malformed-OPEN code can override the default. */
1301
+ readonly invalidOpenCode?: TStreamResetCode;
1302
+ };
1303
+
1304
+ const sendResponse = async (
1305
+ stream: TMuxStream,
1306
+ response: TServeTunnelResponse,
1307
+ signal: AbortSignal,
1308
+ ): Promise<void> => {
1309
+ try {
1310
+ if (signal.aborted) return;
1311
+ stream.sendCtrl(
1312
+ encodeJsonPayload({
1313
+ t: "res_head",
1314
+ status: response.status,
1315
+ ...(response.headers === undefined
1316
+ ? {}
1317
+ : { res_headers: response.headers }),
1318
+ }),
1319
+ );
1320
+ if (response.body instanceof Uint8Array) {
1321
+ if (response.body.byteLength > 0 && !signal.aborted) {
1322
+ await stream.write(response.body);
1323
+ }
1324
+ } else if (response.body !== null) {
1325
+ const reader = response.body.getReader();
1326
+ const cancel = (): void => {
1327
+ void reader.cancel().catch(() => {});
1328
+ };
1329
+ signal.addEventListener("abort", cancel, { once: true });
1330
+ try {
1331
+ for (;;) {
1332
+ const next = await reader.read();
1333
+ if (next.done || signal.aborted) break;
1334
+ for (
1335
+ let offset = 0;
1336
+ offset < next.value.byteLength;
1337
+ offset += MAX_PAYLOAD_BYTES
1338
+ ) {
1339
+ if (signal.aborted) break;
1340
+ await stream.write(
1341
+ next.value.subarray(offset, offset + MAX_PAYLOAD_BYTES),
1342
+ );
1343
+ }
1344
+ }
1345
+ } finally {
1346
+ signal.removeEventListener("abort", cancel);
1347
+ reader.releaseLock();
1348
+ }
1349
+ }
1350
+ if (!signal.aborted) stream.end();
1351
+ } finally {
1352
+ response.onComplete?.();
1353
+ }
1354
+ };
1355
+
1356
+ /** Bind application-level OPEN payloads to a serving mux channel. */
1357
+ export const serveStreams = (
1358
+ channel: TMuxChannel,
1359
+ options: TServeStreamsOptions,
1360
+ ): (() => void) => channel.onStream(serveStream(options));
1361
+
1362
+ /** Application handler for `createChannel({ onStream })`, exported for hosts. */
1363
+ export const serveStream =
1364
+ (
1365
+ options: TServeStreamsOptions,
1366
+ ): ((stream: TMuxStream, payload: Uint8Array) => void) =>
1367
+ (stream, payload) => {
1368
+ const decoded = decodeJsonPayload(payload);
1369
+ const rawKind = streamOpenKindOf(decoded);
1370
+ if (rawKind !== null && RETIRED_STREAM_KINDS.has(rawKind)) {
1371
+ // A pre-agent browser still opening PTY `kind:"session"`: a clear,
1372
+ // decodable code instead of a generic invalid-OPEN.
1373
+ stream.reset(
1374
+ streamReset(
1375
+ RETIRED_STREAM_KIND_RESET.code,
1376
+ RETIRED_STREAM_KIND_RESET.message,
1377
+ ),
1378
+ );
1379
+ return;
1380
+ }
1381
+ const open = parseStreamOpenPayload(decoded);
1382
+ if (open === null) {
1383
+ stream.reset(
1384
+ streamReset(
1385
+ options.invalidOpenCode ?? "protocol_error",
1386
+ "invalid OPEN payload",
1387
+ ),
1388
+ );
1389
+ return;
1390
+ }
1391
+ if (open.kind === "agent") {
1392
+ if (options.agent === undefined) {
1393
+ stream.reset(streamReset("agent_unavailable"));
1394
+ return;
1395
+ }
1396
+ // Defer invoke so both sync throws and rejected promises hit the same
1397
+ // catch (Promise.resolve(fn()) does not catch sync throws from fn).
1398
+ const dispatch = options.agent;
1399
+ void (async () => dispatch(stream, open))().catch(() => {
1400
+ stream.reset(streamReset("dispatch_failed"));
1401
+ });
1402
+ return;
1403
+ }
1404
+ if (open.kind === "realtime") {
1405
+ if (options.realtime === undefined) {
1406
+ stream.reset(streamReset("realtime_unsupported"));
1407
+ return;
1408
+ }
1409
+ const dispatch = options.realtime;
1410
+ void (async () => dispatch(stream, open))().catch(() => {
1411
+ stream.reset(streamReset("dispatch_failed"));
1412
+ });
1413
+ return;
1414
+ }
1415
+ const rejected = options.admitTunnel?.(open);
1416
+ if (rejected !== undefined && rejected !== null) {
1417
+ stream.reset(streamReset(rejected));
1418
+ return;
1419
+ }
1420
+ const abort = new AbortController();
1421
+ const offReset = stream.onReset(() => abort.abort());
1422
+ const body = bodyFromStream(stream, () => abort.abort(), false);
1423
+ void options
1424
+ .tunnel(open, body, abort.signal)
1425
+ .then((response) => sendResponse(stream, response, abort.signal))
1426
+ .catch(() => {
1427
+ if (!abort.signal.aborted) stream.reset(streamReset("dispatch_failed"));
1428
+ })
1429
+ .finally(offReset);
1430
+ };