@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,702 @@
1
+ import { Schema as S } from "effect";
2
+ import { AuthEvent } from "./auth";
3
+ import { RelayCommandLifecycleFrame } from "./control-channel";
4
+ import { DaemonCommand, DaemonCommandAck } from "./daemon";
5
+ import { ReplaySessionId } from "./replay-session";
6
+ import { TEAM_GRANT_B64_MAX } from "./team-grant";
7
+
8
+ // ─── Daemon relay (push over a Sandbox WebSocket, in-memory routing) ──
9
+ //
10
+ // A persistent WebSocket each end (daemon AND browser) holds to a relay
11
+ // running in a Vercel Sandbox. The relay routes commands IN MEMORY: a
12
+ // watcher's `enqueue` is forwarded straight to the matching daemon socket
13
+ // and the daemon's terminal `ack` rides back as a live `command_lifecycle`
14
+ // frame — there is no `daemon_commands` mailbox and no Neon CDC. The one
15
+ // durable write the relay keeps is `api_key_activity` presence/status, read
16
+ // by the stateless `/v1/*` proxy + a cold dashboard load. See
17
+ // `docs/proposals/daemon-owned-state-stateless-relay.md`.
18
+
19
+ /** Which end a connect ticket authorizes. A `daemon` socket receives
20
+ * commands for its `key_id` and sends acks/status; a `watcher` socket
21
+ * (a dashboard tab) enqueues commands for keys its `user_id` owns and
22
+ * receives status/presence pushes. */
23
+ /** `origin` is the cloud `/v1/*` proxy dialing in as a FLEET consumer
24
+ * (origin-side tunneling): it may only open mux channels, and the relay
25
+ * stamps its channels `consumer:"daemon"` exactly like a peer daemon's. */
26
+ export const RelayRole = S.Literals(["daemon", "watcher", "origin"]);
27
+ export type TRelayRole = S.Schema.Type<typeof RelayRole>;
28
+
29
+ /** Bounded, open-vocabulary capability advertisement limits. */
30
+ export const RELAY_CAP_MAX_ITEMS = 32;
31
+ export const RELAY_CAP_MAX_LENGTH = 64;
32
+ const RelayCapability = S.String.check(
33
+ S.isMinLength(1),
34
+ S.isMaxLength(RELAY_CAP_MAX_LENGTH),
35
+ );
36
+ const RelayCapabilities = S.Array(RelayCapability).check(
37
+ S.isMaxLength(RELAY_CAP_MAX_ITEMS),
38
+ );
39
+
40
+ /**
41
+ * Channel ids are the mux envelope's canonical UUID in text form —
42
+ * RFC 4122 lowercase hex with variant nibble `8|9|a|b` (matches
43
+ * `@openllmsh/sdk/tunnel` `isChannelId` / `CHANNEL_ID_PATTERN`).
44
+ */
45
+ const CHANNEL_ID_PATTERN =
46
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
47
+ export const ChannelId = S.String.check(S.isPattern(CHANNEL_ID_PATTERN));
48
+ export type TChannelId = S.Schema.Type<typeof ChannelId>;
49
+
50
+ /** Bounded open-vocabulary peer errors and refusal reasons. */
51
+ const RelayFreeString = S.String.check(S.isMinLength(1), S.isMaxLength(200));
52
+
53
+ /** The port the in-sandbox WS server listens on — declared in `ports` at
54
+ * `Sandbox.getOrCreate` (cloud) and bound by the relay. A fixed internal
55
+ * constant (the public surface is the sandbox's own domain), shared so the
56
+ * provisioner's `sandbox.domain(port)` and the relay's listener agree. */
57
+ export const RELAY_PORT = 8080;
58
+
59
+ export type TRelayDatabaseTarget = "pre-production" | "production";
60
+
61
+ /**
62
+ * The relay identity (sandbox name + TTL class) for the current deployment,
63
+ * derived from `VERCEL_ENV` — the only remaining discriminator now that a
64
+ * single `DATABASE_URL_UNPOOLED` selects the Neon database per environment
65
+ * (Vercel injects the matching value in each env; local dev points it at the
66
+ * dev branch). `production` only on the Vercel production deployment;
67
+ * everything else (preview, `vercel dev`, plain `next dev`, tests) is
68
+ * `pre-production`. Pure (a function of its input) so the DB client, the cloud
69
+ * provisioner, and the in-sandbox relay all agree from the same signal.
70
+ */
71
+ export const resolveDatabaseTarget = (
72
+ vercelEnv: string | undefined,
73
+ ): TRelayDatabaseTarget =>
74
+ vercelEnv === "production" ? "production" : "pre-production";
75
+
76
+ /** The name of the retired daemon-relay logical-replication slot. The relay no
77
+ * longer subscribes it (commands route in memory) — this is kept ONLY so
78
+ * `packages/db/migrate.ts` can DROP a leftover slot on deploy (Phase 5
79
+ * demolition). The matching `daemon_relay_pub` publication is dropped by
80
+ * `migrations/0007_chunky_expediter.sql` using its literal name. */
81
+ export const RELAY_SLOT = "daemon_relay_slot";
82
+
83
+ /** The per-environment relay identity — just the sandbox name now (the
84
+ * publication/slot the CDC era carried are gone). Pure derivation (no env, no
85
+ * I/O) so the cloud provisioner and the relay agree. */
86
+ export type TRelayNames = {
87
+ readonly relayName: string;
88
+ };
89
+
90
+ export const relayNamesFor = (target: TRelayDatabaseTarget): TRelayNames => ({
91
+ relayName: `daemon-relay-${target}`,
92
+ });
93
+
94
+ // ─── Sandbox origin tags (deprovisioning) ─────────────────────────────
95
+ //
96
+ // The provisioner tags each relay sandbox with the stable ORIGIN that uses it
97
+ // — the deployment "place" (production URL / preview branch URL / local
98
+ // hostname) — plus a freshness timestamp, refreshed on healthy channel
99
+ // fetches. The cleanup cron groups boxes by origin and gracefully stops a
100
+ // superseded box (same origin, older freshness, different bundle hash) —
101
+ // see `lib/relay-sandbox-cleanup.ts`.
102
+
103
+ /** Tag key: the sanitized stable origin that provisioned/uses this box. */
104
+ export const RELAY_TAG_ORIGIN = "origin";
105
+ /** Tag key: unix-ms (decimal string) of the origin's last claim/refresh. */
106
+ export const RELAY_TAG_ORIGIN_AT = "origin-at";
107
+
108
+ /** The env signals the origin is derived from. `localHostname` is caller-
109
+ * provided (`os.hostname()`) so this stays pure and testable. */
110
+ export type TRelayOriginInputs = {
111
+ readonly vercelEnv: string | undefined;
112
+ readonly projectProductionUrl: string | undefined;
113
+ readonly branchUrl: string | undefined;
114
+ readonly deploymentUrl: string | undefined;
115
+ readonly localHostname: string | undefined;
116
+ };
117
+
118
+ /** Sandbox tag values must be short, plain tokens. Lowercase, strip the
119
+ * protocol + trailing slash, squash anything outside [a-z0-9._-], cap at 64.
120
+ * Returns null when nothing usable remains so the caller can fall back. */
121
+ const sanitizeOriginTag = (raw: string | undefined): string | null => {
122
+ if (raw === undefined) return null;
123
+ const cleaned = raw
124
+ .toLowerCase()
125
+ .replace(/^https?:\/\//, "")
126
+ .replace(/\/+$/, "")
127
+ .replace(/[^a-z0-9._-]/g, "-")
128
+ .slice(0, 64);
129
+ return cleaned === "" ? null : cleaned;
130
+ };
131
+
132
+ /**
133
+ * The STABLE origin identity for sandbox tagging — stable across deploys of
134
+ * the same "place", so the cleanup cron's per-origin change detection fires:
135
+ * production → the project production URL (not the per-deploy VERCEL_URL);
136
+ * preview → the branch URL (stable per git branch), falling back to the
137
+ * per-deploy URL only when the branch URL is absent;
138
+ * local/test → `local-<hostname>` so two developers never supersede each
139
+ * other's boxes.
140
+ * Pure (a function of its inputs) per the convention above.
141
+ */
142
+ export const resolveRelayOrigin = (inputs: TRelayOriginInputs): string => {
143
+ if (inputs.vercelEnv === "production") {
144
+ return sanitizeOriginTag(inputs.projectProductionUrl) ?? "production";
145
+ }
146
+ if (inputs.vercelEnv === "preview") {
147
+ return (
148
+ sanitizeOriginTag(inputs.branchUrl) ??
149
+ sanitizeOriginTag(inputs.deploymentUrl) ??
150
+ "preview"
151
+ );
152
+ }
153
+ const host = sanitizeOriginTag(inputs.localHostname);
154
+ return host === null ? "local" : `local-${host}`;
155
+ };
156
+
157
+ /**
158
+ * The decoded claims of a connect ticket. The cloud (`/api/daemon/channel`)
159
+ * mints these after validating the caller (`sk-llm` key → `daemon`, Neon
160
+ * Auth session → `watcher`) and Ed25519-signs them; the relay verifies with
161
+ * the corresponding public key only (it does NO DB-side auth in the
162
+ * Sandbox and cannot mint tickets). `key_id` is present iff
163
+ * `role === "daemon"`. `exp` is a unix-ms deadline kept short (~60s) so a
164
+ * leaked ticket is near-useless. `aud` binds the ticket to a specific relay
165
+ * sandbox name; `jti` is a one-shot nonce consumed by the relay.
166
+ */
167
+ export const RelayTicketClaims = S.Struct({
168
+ role: RelayRole,
169
+ user_id: S.String,
170
+ key_id: S.optional(S.String),
171
+ exp: S.Number,
172
+ /** Relay sandbox audience, e.g. `daemon-relay-production`. */
173
+ aud: S.String.check(S.isMinLength(1), S.isMaxLength(128)),
174
+ /** Unique ticket id (base64url) — single-use within the TTL window. */
175
+ jti: S.String.check(S.isMinLength(16), S.isMaxLength(64)),
176
+ });
177
+ export type TRelayTicketClaims = S.Schema.Type<typeof RelayTicketClaims>;
178
+
179
+ /**
180
+ * Domain-separation label for the Ed25519 seed derivation. Shared by the
181
+ * cloud signer and the verifier so both derive the same keypair from
182
+ * `NEON_AUTH_COOKIE_SECRET`. The sandbox receives only the public half.
183
+ */
184
+ export const RELAY_TICKET_SEED_LABEL = "openllm-relay-ticket-ed25519-seed-v1";
185
+
186
+ /** One ICE server entry (STUN or TURN) on the channel handshake — mirrors
187
+ * `RTCIceServer` so browser and daemon feed it to their peer connections
188
+ * verbatim. */
189
+ export const IceServer = S.Struct({
190
+ urls: S.Union([S.String, S.Array(S.String)]),
191
+ username: S.optional(S.String),
192
+ credential: S.optional(S.String),
193
+ });
194
+ export type TIceServer = S.Schema.Type<typeof IceServer>;
195
+
196
+ /** GET /api/daemon/channel → the live relay WSS URL + a connect ticket. Both
197
+ * daemon and browser dial `wss_url`, presenting `ticket` in their first
198
+ * `hello` frame. The URL is the sandbox's own domain (`wss://<sandbox-host>`);
199
+ * it can rotate when the relay cycles, so clients re-fetch this on every
200
+ * (re)connect rather than caching the host. `ice_servers` is the optional
201
+ * cloud-served ICE config (from `OPENLLM_RTC_ICE_SERVERS`) — absent, both
202
+ * ends fall back to their default STUN. */
203
+ export const RelayChannelResponse = S.Struct({
204
+ wss_url: S.String,
205
+ /** Short-lived Ed25519-signed connect ticket
206
+ * (opaque `<b64url(claims)>.<b64url(sig)>`). */
207
+ ticket: S.String,
208
+ /** Optional cloud-served ICE servers (STUN/TURN) for RTC peers. */
209
+ ice_servers: S.optional(S.Array(IceServer)),
210
+ });
211
+ export type TRelayChannelResponse = S.Schema.Type<typeof RelayChannelResponse>;
212
+
213
+ // ─── WebSocket frame envelope ────────────────────────────────────────
214
+ //
215
+ // One tagged union shared by all four parties. Each variant documents its
216
+ // direction; a given end only emits the subset it owns and ignores the
217
+ // rest. JSON over text frames.
218
+
219
+ /** client → relay (first frame). A daemon may piggyback its initial
220
+ * status snapshot; a watcher sends ticket only. */
221
+ export const RelayHelloFrame = S.Struct({
222
+ type: S.Literal("hello"),
223
+ ticket: S.String,
224
+ /** Daemon protocol capability; absent daemons retain legacy compatibility. */
225
+ protocol_version: S.optional(S.Number),
226
+ /** Open-vocabulary peer capability list.
227
+ * Unknown capabilities preserve forward compatibility. */
228
+ caps: S.optional(RelayCapabilities),
229
+ /** Daemon only: initial per-provider `TDaemonStatus` snapshot, folded
230
+ * into `api_key_activity.daemon_status_json` on connect. */
231
+ status: S.optional(S.Unknown),
232
+ });
233
+ export type TRelayHelloFrame = S.Schema.Type<typeof RelayHelloFrame>;
234
+
235
+ /** relay → client. Handshake accepted; carries the current presence snapshot so
236
+ * a freshly-attached dashboard paints immediately. */
237
+ export const RelayWelcomeFrame = S.Struct({
238
+ type: S.Literal("welcome"),
239
+ /** Watcher only: the AUTHORITATIVE set of the user's key ids that have a live
240
+ * daemon socket on the relay right now, from its in-memory registry. The
241
+ * dashboard treats membership as presence — keys absent here are offline by
242
+ * authority of the relay that owns every socket — so a stale-`true`
243
+ * `api_key_activity` row (ungraceful relay death) is corrected the instant a
244
+ * watcher (re)connects. Live status keeps flowing via `status_push`. */
245
+ snapshot: S.optional(S.Array(S.String)),
246
+ /** Daemon only: relay-assigned connection epoch for ordered snapshots. */
247
+ daemon_session_id: S.optional(S.String),
248
+ daemon_session_started_at_ms: S.optional(S.Number),
249
+ protocol_version: S.optional(S.Number),
250
+ /** Relay capabilities. */
251
+ caps: S.optional(RelayCapabilities),
252
+ /** Per-serving-daemon capability snapshots, parallel to `snapshot`. */
253
+ snapshot_caps: S.optional(S.Record(S.String, RelayCapabilities)),
254
+ });
255
+ export type TRelayWelcomeFrame = S.Schema.Type<typeof RelayWelcomeFrame>;
256
+
257
+ /** relay → daemon. One command to run, routed in memory the instant the watcher
258
+ * enqueues it (no durable mailbox). `id` is a relay-generated uuid. */
259
+ export const RelayCommandFrame = S.Struct({
260
+ type: S.Literal("command"),
261
+ command: DaemonCommand,
262
+ });
263
+ export type TRelayCommandFrame = S.Schema.Type<typeof RelayCommandFrame>;
264
+
265
+ /** daemon → relay. A terminal command result; the relay forwards it to the
266
+ * originating watcher as a `command_lifecycle` frame (no `daemon_commands`
267
+ * row to update). */
268
+ export const RelayAckFrame = S.Struct({
269
+ type: S.Literal("ack"),
270
+ ack: DaemonCommandAck,
271
+ });
272
+ export type TRelayAckFrame = S.Schema.Type<typeof RelayAckFrame>;
273
+
274
+ /** Planned-downtime reason on a graceful `active:false` status beacon.
275
+ * Absent ⇒ real offline / legacy beacon (CERTAIN death). */
276
+ export const RelayStatusRestartReason = S.Literal("restarting");
277
+ export type TRelayStatusRestartReason = S.Schema.Type<
278
+ typeof RelayStatusRestartReason
279
+ >;
280
+
281
+ /** daemon → relay. Heartbeat + per-provider snapshot. `active:false` is the
282
+ * graceful-exit beacon. The relay folds the snapshot into
283
+ * `api_key_activity.daemon_status_json` (durable, read by the proxy + a cold
284
+ * HTTP load) and fans it out to the user's watchers (`status_push`).
285
+ *
286
+ * Planned restarts send `active:false` WITH `reason:"restarting"` (and an
287
+ * optional `expect_back_ms` hint) so the relay keeps the row routable —
288
+ * `daemon_active` stays true and `last_seen` stays fresh — while origin's
289
+ * presence grace absorbs the brief gap. A bare `active:false` remains a
290
+ * CERTAIN death (`daemon_active=false`). See
291
+ * `docs/audit/2026-10-20-deploy-zero-downtime.md` fix #2. */
292
+ export const RelayStatusFrame = S.Struct({
293
+ type: S.Literal("status"),
294
+ active: S.optional(S.Boolean),
295
+ status: S.optional(S.Unknown),
296
+ /** Present for protocol-v2 daemon status snapshots. */
297
+ daemon_session_id: S.optional(S.String),
298
+ status_seq: S.optional(S.Number),
299
+ acks: S.optional(S.Array(DaemonCommandAck)),
300
+ /** Planned downtime; absent ⇒ real offline / legacy beacon. */
301
+ reason: S.optional(RelayStatusRestartReason),
302
+ /** Hint for origin grace / UI: ms until this key should be back. */
303
+ expect_back_ms: S.optional(S.Number),
304
+ });
305
+ export type TRelayStatusFrame = S.Schema.Type<typeof RelayStatusFrame>;
306
+
307
+ /** watcher → relay. The dashboard enqueues a control command for one of the
308
+ * user's keys. The relay authorizes it by REGISTRY MEMBERSHIP — a watcher may
309
+ * address `key_id` K iff a daemon socket for K is connected with the same
310
+ * `user_id` (off that daemon's ticket) — then routes it to that socket in
311
+ * memory. `req_id` correlates the relay's `enqueue_ack`; omit it for
312
+ * fire-and-forget. */
313
+ export const RelayEnqueueFrame = S.Struct({
314
+ type: S.Literal("enqueue"),
315
+ req_id: S.optional(S.String),
316
+ key_id: S.String,
317
+ kind: S.String,
318
+ payload: S.optional(S.Unknown),
319
+ replay_session_id: S.optional(ReplaySessionId),
320
+ });
321
+ export type TRelayEnqueueFrame = S.Schema.Type<typeof RelayEnqueueFrame>;
322
+
323
+ /** relay → watcher. The result of an `enqueue` carrying a `req_id`: the
324
+ * relay-generated command id on success, or an error (`daemon_offline` /
325
+ * `invalid_command`). */
326
+ export const RelayEnqueueAckFrame = S.Struct({
327
+ type: S.Literal("enqueue_ack"),
328
+ req_id: S.String,
329
+ ok: S.Boolean,
330
+ id: S.optional(S.String),
331
+ error: S.optional(S.String),
332
+ });
333
+ export type TRelayEnqueueAckFrame = S.Schema.Type<typeof RelayEnqueueAckFrame>;
334
+
335
+ /** relay → watcher. A daemon's status snapshot for one key landed; push it
336
+ * to the dashboard. */
337
+ export const RelayStatusPushFrame = S.Struct({
338
+ type: S.Literal("status_push"),
339
+ key_id: S.String,
340
+ status: S.Unknown,
341
+ daemon_session_id: S.optional(S.String),
342
+ daemon_session_started_at_ms: S.optional(S.Number),
343
+ status_seq: S.optional(S.Number),
344
+ });
345
+ export type TRelayStatusPushFrame = S.Schema.Type<typeof RelayStatusPushFrame>;
346
+
347
+ /** relay → watcher. A key's daemon presence flipped (socket open/close). */
348
+ export const RelayPresenceFrame = S.Struct({
349
+ type: S.Literal("presence"),
350
+ key_id: S.String,
351
+ active: S.Boolean,
352
+ /** Present when an active daemon advertises capabilities. */
353
+ caps: S.optional(RelayCapabilities),
354
+ });
355
+ export type TRelayPresenceFrame = S.Schema.Type<typeof RelayPresenceFrame>;
356
+
357
+ // ─── Subscription tunnel + device sessions (mux-only) ────────────────
358
+ //
359
+ // A consumer (browser watcher socket, or another daemon's socket) opens a
360
+ // mux stream through the relay to a SERVING daemon (over the relay binary
361
+ // mux or a direct RTC data channel), which dispatches the request against
362
+ // its own local `/v1/*` data plane and streams the response back. Device
363
+ // PTY sessions ride the same mux. Same-user only (registry-membership auth,
364
+ // exactly like `enqueue`); the vendor subscription token never crosses —
365
+ // only OpenLLM-wire bytes do. The relay never decodes mux payloads. The
366
+ // legacy JSON `tunnel_*` / `session_*` splice frames have been removed.
367
+ // See `docs/features/sub-tunnel-and-chat-sessions.md`.
368
+
369
+ /**
370
+ * Max base64 length of a seed-gated device-grant envelope on open frames.
371
+ * Real envelopes are a few hundred bytes (JSON of nonce/ts/key_id/cid/aud +
372
+ * Ed25519 sig, then base64); 4 KiB is generous headroom so a peer cannot
373
+ * push an unbounded string through Schema re-encode into the daemon.
374
+ *
375
+ * Canonical owner for the wire cap. `@openllmsh/sdk/tunnel/device-grant` re-exports
376
+ * the same value so decode stays aligned with Schema maxLength.
377
+ */
378
+ export const DEVICE_GRANT_B64_MAX = 4 * 1024;
379
+
380
+ /**
381
+ * Internal hop marker: the serving daemon stamps this on every request it
382
+ * dispatches from a tunnel open so a fleet-peer walker can refuse to
383
+ * re-tunnel (loop guard). Not a client-facing API.
384
+ */
385
+ export const TUNNELED_REQUEST_HEADER = "x-openllm-tunneled";
386
+
387
+ /** Response header naming the device key that served a tunneled request. */
388
+ export const SERVED_BY_DEVICE_HEADER = "x-openllm-served-by-device";
389
+
390
+ /**
391
+ * Request header pinning a follow-up to the device that served an earlier
392
+ * call (a video job lives on ONE device's vendor account; its id does not
393
+ * name the device). Any client may echo back {@link SERVED_BY_DEVICE_HEADER}
394
+ * here. Honoured only if that key is one of the caller's own serving
395
+ * devices — it reorders the candidates, never widens them.
396
+ */
397
+ export const TARGET_DEVICE_HEADER = "x-openllm-target-device";
398
+ export const TUNNELED_REQUEST_VALUE = "1";
399
+
400
+ // ─── Mux channels (consumer ⇄ relay ⇄ serving daemon) ─────────────────
401
+
402
+ /** consumer → relay → serving daemon. Auth runs once when opening this
403
+ * channel; after acceptance, all subsequent binary frames on both sockets
404
+ * belong to this channel. */
405
+ export const RelayChannelOpenFrame = S.Struct({
406
+ type: S.Literal("channel_open"),
407
+ channel_id: ChannelId,
408
+ key_id: S.String,
409
+ /**
410
+ * Who is opening the channel. The relay stamps this from the authenticated
411
+ * socket role before forward (`watcher` → `browser`, `daemon` → `daemon`) —
412
+ * clients may set it but the relay overwrites. `daemon` marks a fleet peer
413
+ * hop so the serving daemon skips seedgate (no vault DEK on the consumer).
414
+ * Omitted / `browser` is the default seed-gated path.
415
+ */
416
+ consumer: S.optional(S.Literals(["browser", "daemon"])),
417
+ /**
418
+ * Seed-gated device grant (base64 envelope). Present when the serving
419
+ * daemon advertises `seedgate1`. Relay re-encodes via Schema — must be
420
+ * on the schema so it survives forward; never verified by the relay.
421
+ * Bounded so a peer cannot ship an arbitrarily large grant past re-encode.
422
+ */
423
+ grant: S.optional(S.String.check(S.isMaxLength(DEVICE_GRANT_B64_MAX))),
424
+ /**
425
+ * Origin-signed team grant (base64 envelope). Required for cross-user
426
+ * admission: the relay admits when non-empty (it does NOT verify — the
427
+ * contributor daemon re-checks with its bootstrap `team_grant_key`).
428
+ * Same-user opens omit it. Opaque to the payload path; bounded like
429
+ * {@link DEVICE_GRANT_B64_MAX}.
430
+ */
431
+ team_grant: S.optional(S.String.check(S.isMaxLength(TEAM_GRANT_B64_MAX))),
432
+ /** Authenticated consumer user id. The relay replaces client input. */
433
+ peer_user_id: S.optional(S.String),
434
+ });
435
+ export type TRelayChannelOpenFrame = S.Schema.Type<
436
+ typeof RelayChannelOpenFrame
437
+ >;
438
+
439
+ /** Relay-to-daemon form of {@link RelayChannelOpenFrame}. The relay stamps
440
+ * `peer_user_id`; daemons never accept an unstamped open as same-user. */
441
+ export const RelayStampedChannelOpenFrame = S.Struct({
442
+ type: S.Literal("channel_open"),
443
+ channel_id: ChannelId,
444
+ key_id: S.String,
445
+ consumer: S.optional(S.Literals(["browser", "daemon"])),
446
+ grant: S.optional(S.String.check(S.isMaxLength(DEVICE_GRANT_B64_MAX))),
447
+ team_grant: S.optional(S.String.check(S.isMaxLength(TEAM_GRANT_B64_MAX))),
448
+ peer_user_id: S.String,
449
+ });
450
+ export type TRelayStampedChannelOpenFrame = S.Schema.Type<
451
+ typeof RelayStampedChannelOpenFrame
452
+ >;
453
+
454
+ /** serving daemon → relay → consumer. The relay mints failure acknowledgements;
455
+ * an accepting daemon's acknowledgement is echoed verbatim. */
456
+ export const RelayChannelOpenAckFrame = S.Struct({
457
+ type: S.Literal("channel_open_ack"),
458
+ channel_id: ChannelId,
459
+ ok: S.Boolean,
460
+ /**
461
+ * Free-string on the wire so newer daemon failures remain decodable by
462
+ * older relay peers. Known values live in {@link ChannelOpenError}.
463
+ */
464
+ error: S.optional(RelayFreeString),
465
+ });
466
+ export type TRelayChannelOpenAckFrame = S.Schema.Type<
467
+ typeof RelayChannelOpenAckFrame
468
+ >;
469
+
470
+ /** Either side / relay-minted. `relay_restart` is a drain signal: consumers
471
+ * reset in-flight streams and re-open the channel on the successor relay. */
472
+ export const RelayChannelCloseFrame = S.Struct({
473
+ type: S.Literal("channel_close"),
474
+ channel_id: ChannelId,
475
+ /** Free-string on the wire; known values live in ChannelCloseReason. */
476
+ reason: S.optional(RelayFreeString),
477
+ });
478
+ export type TRelayChannelCloseFrame = S.Schema.Type<
479
+ typeof RelayChannelCloseFrame
480
+ >;
481
+
482
+ // ─── WebRTC signaling (consumer ⇄ relay ⇄ serving daemon) ──────────────
483
+ //
484
+ // SDP + trickle ICE for a direct browser⇄daemon RTCDataChannel. The relay is
485
+ // signaling-only: same-user registry-membership auth on `rtc_offer`, then
486
+ // verbatim forward of offer/answer/ice between the paired endpoints. Payload
487
+ // bytes never touch the relay once the data channel is up. `fingerprint_proof`
488
+ // is sealed-box ciphertext from `@openllmsh/sdk/tunnel` rtc-auth (DTLS fingerprint
489
+ // bound to the daemon-minted grant) — the relay never inspects it.
490
+ //
491
+ // `candidate` is a JSON string of an `RTCIceCandidateInit` (or the werift
492
+ // equivalent) so browser and daemon peers share one serialization without
493
+ // inventing a side-car candidate schema.
494
+
495
+ /**
496
+ * Soft upper bound for an SDP blob on the signaling plane. Real offers/
497
+ * answers are a few KB; 64 KiB leaves headroom while staying well under a
498
+ * typical WebSocket frame budget (~1 MiB on Cloudflare / PartySocket).
499
+ */
500
+ export const RTC_SDP_MAX = 64 * 1024;
501
+
502
+ /**
503
+ * Soft upper bound for a base64 sealed fingerprint proof. Sealed-box
504
+ * ciphertext for the offer/answer inner is well under 2 KiB even with a
505
+ * nested device grant; 8 KiB is a conservative ceiling.
506
+ */
507
+ export const RTC_FINGERPRINT_PROOF_B64_MAX = 8 * 1024;
508
+
509
+ /**
510
+ * Soft upper bound for a JSON-serialized `RTCIceCandidateInit`. A single
511
+ * candidate line + mid/mline fields is typically < 512 B; 4 KiB is generous.
512
+ */
513
+ export const RTC_ICE_CANDIDATE_MAX = 4 * 1024;
514
+
515
+ /** consumer → relay → serving daemon. Open an RTC signaling session aimed at
516
+ * the daemon serving `key_id`. The consumer mints `channel_id` (uuid); the
517
+ * relay authorizes by registry membership and registers the pair so later
518
+ * `rtc_answer` / `rtc_ice` frames route by `channel_id`. */
519
+ export const RelayRtcOfferFrame = S.Struct({
520
+ type: S.Literal("rtc_offer"),
521
+ channel_id: ChannelId,
522
+ key_id: S.String,
523
+ sdp: S.String.check(S.isMaxLength(RTC_SDP_MAX)),
524
+ fingerprint_proof: S.String.check(
525
+ S.isMaxLength(RTC_FINGERPRINT_PROOF_B64_MAX),
526
+ ),
527
+ /** Opaque origin-signed grant required for cross-user RTC admission. */
528
+ team_grant: S.optional(S.String.check(S.isMaxLength(TEAM_GRANT_B64_MAX))),
529
+ /** Authenticated consumer id. The relay replaces client input. */
530
+ peer_user_id: S.optional(S.String),
531
+ /** Authenticated consumer kind. The relay replaces client input. */
532
+ consumer: S.optional(S.Literals(["browser", "daemon"])),
533
+ });
534
+ export type TRelayRtcOfferFrame = S.Schema.Type<typeof RelayRtcOfferFrame>;
535
+
536
+ /** Relay-to-daemon form of {@link RelayRtcOfferFrame}. The relay stamps both
537
+ * identity fields; an unstamped offer is rejected as an outdated relay. */
538
+ export const RelayStampedRtcOfferFrame = S.Struct({
539
+ type: S.Literal("rtc_offer"),
540
+ channel_id: ChannelId,
541
+ key_id: S.String,
542
+ sdp: S.String.check(S.isMaxLength(RTC_SDP_MAX)),
543
+ fingerprint_proof: S.String.check(
544
+ S.isMaxLength(RTC_FINGERPRINT_PROOF_B64_MAX),
545
+ ),
546
+ team_grant: S.optional(S.String.check(S.isMaxLength(TEAM_GRANT_B64_MAX))),
547
+ peer_user_id: S.String,
548
+ consumer: S.Literals(["browser", "daemon"]),
549
+ });
550
+ export type TRelayStampedRtcOfferFrame = S.Schema.Type<
551
+ typeof RelayStampedRtcOfferFrame
552
+ >;
553
+
554
+ /** serving daemon → relay → consumer. Answer the offer for `channel_id`. */
555
+ export const RelayRtcAnswerFrame = S.Struct({
556
+ type: S.Literal("rtc_answer"),
557
+ channel_id: ChannelId,
558
+ sdp: S.String.check(S.isMaxLength(RTC_SDP_MAX)),
559
+ fingerprint_proof: S.String.check(
560
+ S.isMaxLength(RTC_FINGERPRINT_PROOF_B64_MAX),
561
+ ),
562
+ });
563
+ export type TRelayRtcAnswerFrame = S.Schema.Type<typeof RelayRtcAnswerFrame>;
564
+
565
+ /** Both directions. One trickle ICE candidate for `channel_id`. `candidate` is
566
+ * a JSON-serialized `RTCIceCandidateInit` object (stringified by the sender,
567
+ * `JSON.parse`'d by the receiver) — preferred over a raw SDP candidate line
568
+ * for browser/werift field parity (`candidate`/`sdpMid`/`sdpMLineIndex`/…). */
569
+ export const RelayRtcIceFrame = S.Struct({
570
+ type: S.Literal("rtc_ice"),
571
+ channel_id: ChannelId,
572
+ candidate: S.String.check(S.isMaxLength(RTC_ICE_CANDIDATE_MAX)),
573
+ });
574
+ export type TRelayRtcIceFrame = S.Schema.Type<typeof RelayRtcIceFrame>;
575
+
576
+ /** Why a serving daemon refused an `rtc_offer`. `seedgate` = the vault DEK is
577
+ * locked (retry after unlock); `overloaded` = transient session cap (retry
578
+ * soon); `disabled` / `not_capable` / `handshake_failed` = daemon posture or
579
+ * a failed pre-mux handshake (cache the failure — it will not recover on this
580
+ * immediate retry). `proof_open_failed` means the offer was sealed to a stale
581
+ * daemon X25519 key; consumers should refresh the cloud identity projection.
582
+ * `daemon_outdated` means a relay or daemon omitted a required current stamp. */
583
+ export const RtcNackReason = S.Literals([
584
+ "seedgate",
585
+ "overloaded",
586
+ "disabled",
587
+ "not_capable",
588
+ "handshake_failed",
589
+ "proof_open_failed",
590
+ "daemon_outdated",
591
+ ]);
592
+ export type TRtcNackReason = S.Schema.Type<typeof RtcNackReason>;
593
+
594
+ /** Normalize a forward-compatible peer refusal to a generic retryable refusal. */
595
+ export const normalizeRtcNackReason = (reason: string): TRtcNackReason => {
596
+ switch (reason) {
597
+ case "seedgate":
598
+ case "overloaded":
599
+ case "disabled":
600
+ case "not_capable":
601
+ case "handshake_failed":
602
+ case "proof_open_failed":
603
+ case "daemon_outdated":
604
+ return reason;
605
+ default:
606
+ return "overloaded";
607
+ }
608
+ };
609
+
610
+ /** serving daemon or relay → consumer. Refuse the offer for `channel_id` —
611
+ * the explicit non-silent reject so the offerer fails fast instead of
612
+ * waiting out the signaling/ICE timeout. */
613
+ export const RelayRtcNackFrame = S.Struct({
614
+ type: S.Literal("rtc_nack"),
615
+ channel_id: ChannelId,
616
+ /**
617
+ * Free-string on the wire so a newer daemon refusal stays decodable. Known
618
+ * values live in {@link RtcNackReason}; unrecognized values are generic,
619
+ * non-cacheable refusals to consumers.
620
+ */
621
+ reason: RelayFreeString,
622
+ });
623
+ export type TRelayRtcNackFrame = S.Schema.Type<typeof RelayRtcNackFrame>;
624
+
625
+ /** relay → every client. This box is superseded (a newer relay deploy is
626
+ * accepting): move to the box `/api/daemon/channel` now returns. The box
627
+ * admits no new work, finishes in-flight channels, then closes each socket
628
+ * with {@link RELAY_MOVED_CLOSE_CODE}. Old clients drop the unknown frame and
629
+ * move on that close. See `docs/plans/relay-handover.md`. */
630
+ export const RelayMovedFrame = S.Struct({ type: S.Literal("relay_moved") });
631
+ export type TRelayMovedFrame = S.Schema.Type<typeof RelayMovedFrame>;
632
+
633
+ /** Close code of a retired box's socket: reconnect immediately (no backoff).
634
+ * Distinct from 4000 `superseded`, so it never triggers daemon stand-down. */
635
+ export const RELAY_MOVED_CLOSE_CODE = 4010;
636
+
637
+ /** Keepalive (both directions). The relay pings below Cloudflare's
638
+ * proxied-WS idle bound; a missed pong is the relay's dead-peer signal. */
639
+ export const RelayPingFrame = S.Struct({ type: S.Literal("ping") });
640
+ export type TRelayPingFrame = S.Schema.Type<typeof RelayPingFrame>;
641
+
642
+ export const RelayPongFrame = S.Struct({ type: S.Literal("pong") });
643
+ export type TRelayPongFrame = S.Schema.Type<typeof RelayPongFrame>;
644
+
645
+ /**
646
+ * daemon → relay → watcher. Explicit subscription-auth FSM (`auth.ts`).
647
+ *
648
+ * Same `type: "auth"` from both roles so `parseFrame` accepts it the way
649
+ * `status` is accepted from the daemon (there is no separate DaemonToRelay
650
+ * union). Frame-level `key_id` is the routing key; the inner event also
651
+ * carries `key_id` (and `flow_id` except on `auth.session.lost`).
652
+ *
653
+ * Old relays that predate this member fail-decode the frame and drop it
654
+ * (`parseFrame` → null) — the designed unknown-type tolerance. New relays
655
+ * parse it even before they route it.
656
+ */
657
+ export const RelayAuthFrame = S.Struct({
658
+ type: S.Literal("auth"),
659
+ key_id: S.String,
660
+ auth: AuthEvent,
661
+ });
662
+ export type TRelayAuthFrame = S.Schema.Type<typeof RelayAuthFrame>;
663
+
664
+ // NOTE: older daemon binaries also sent `received` (a per-command delivery
665
+ // receipt) and `resync` (a periodic "re-push my pending rows" floor). Both are
666
+ // retired — there is no durable mailbox to redeliver from anymore — so neither
667
+ // has a consumer. They are deliberately NOT in the union; an old daemon's frames
668
+ // fail decode and are silently dropped (`parseFrame` → null), the designed
669
+ // legacy tolerance. The same silent-drop applies to any unknown `type` (e.g. a
670
+ // future `rtc_*` peer talking to an older relay, or vice versa).
671
+
672
+ /** The full frame union, discriminated on `type`. `command_lifecycle` (relay →
673
+ * watcher) is the stateless-relay command receipt: the relay forwards the
674
+ * daemon's terminal `ack` to the originating watcher as a live lifecycle
675
+ * update, so the dashboard releases an optimistic button off the socket — no
676
+ * DB `command_seq` cursor. See `control-channel.ts` +
677
+ * `docs/proposals/daemon-owned-state-stateless-relay.md`. `auth` (daemon →
678
+ * relay → watcher) is the subscription-login FSM; it is not a CommandState. */
679
+ export const RelayFrame = S.Union([
680
+ RelayHelloFrame,
681
+ RelayWelcomeFrame,
682
+ RelayCommandFrame,
683
+ RelayAckFrame,
684
+ RelayStatusFrame,
685
+ RelayEnqueueFrame,
686
+ RelayEnqueueAckFrame,
687
+ RelayStatusPushFrame,
688
+ RelayPresenceFrame,
689
+ RelayCommandLifecycleFrame,
690
+ RelayAuthFrame,
691
+ RelayChannelOpenFrame,
692
+ RelayChannelOpenAckFrame,
693
+ RelayChannelCloseFrame,
694
+ RelayRtcOfferFrame,
695
+ RelayRtcAnswerFrame,
696
+ RelayRtcIceFrame,
697
+ RelayRtcNackFrame,
698
+ RelayMovedFrame,
699
+ RelayPingFrame,
700
+ RelayPongFrame,
701
+ ]);
702
+ export type TRelayFrame = S.Schema.Type<typeof RelayFrame>;