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

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,1524 @@
1
+ import { Schema as S } from "effect";
2
+ import { AuthSessionLostDiagnosticCode } from "./auth";
3
+ import type { TContextOverflowStrategy } from "./config";
4
+ import {
5
+ ContextOverflowStrategy,
6
+ FallbackGroup,
7
+ ModelFallbackBinding,
8
+ } from "./config";
9
+ import { CooldownReason } from "./cooldown-reason";
10
+ import { DaemonReportingPolicy } from "./doctor-report-policy";
11
+ import { ExecutionSelection } from "./execution-selection";
12
+ import { AUTH_OPERATIONS, AUTH_RELAY_WAIT_MAX_MS } from "./local-auth";
13
+ import {
14
+ DeviceAccessPinReport,
15
+ DeviceSessionsReport,
16
+ } from "./local-device-control";
17
+ import { LocalKeyProviderSlug } from "./local-provider";
18
+ import {
19
+ ModelSettingDefinitions,
20
+ ModelSettingsOverrides,
21
+ } from "./model-settings";
22
+ import {
23
+ ModelAudioSupport,
24
+ ModelCaps,
25
+ ModelCapsDefaultRule,
26
+ ProviderModelList,
27
+ SubscriptionMeter,
28
+ } from "./models";
29
+ import {
30
+ DaemonProviderObservation,
31
+ DaemonProviderReasonCode,
32
+ DaemonProviderUpstreamAuthCooldown,
33
+ } from "./provider-status";
34
+ import { ProviderUsageSnapshot } from "./provider-usage";
35
+ import { ReplaySessionId } from "./replay-session";
36
+ import { RequestStatus } from "./stats";
37
+ import { SubscriptionProviderSlug } from "./subscription-provider";
38
+ import { TEAM_GRANT_B64_MAX } from "./team-grant";
39
+ import { VendorCliInstall } from "./vendor-cli-install";
40
+
41
+ // ─── GET /api/daemon/bootstrap (daemon → cloud) ──────────────────────
42
+ //
43
+ // One snapshot with everything the local pipeline needs to resolve a
44
+ // chain + price-free dispatch: the model catalog, the provider prefixes,
45
+ // and the authenticated user's fallback config. Pulled at boot and
46
+ // refreshed on a TTL so the daemon stays in lockstep with cloud config
47
+ // without recompiling.
48
+
49
+ export const DaemonCatalogEntry = S.Struct({
50
+ settings: S.optional(ModelSettingDefinitions),
51
+ model_id: S.String,
52
+ provider: S.String,
53
+ provider_model_id: S.String,
54
+ input_token_limit: S.NullOr(S.Number),
55
+ output_token_limit: S.NullOr(S.Number),
56
+ subscription_meter: S.optional(SubscriptionMeter),
57
+ /**
58
+ * Catalog capabilities for this model. Optional so older clouds keep
59
+ * bootstrapping newer daemons. Absent / empty = unknown (never treated
60
+ * as known-non-vision). The walker vision gate reads this on each hop.
61
+ *
62
+ * Open string array: unknown future literals (e.g. `image_editing`,
63
+ * `realtime`) must not fail the whole bootstrap. Older compiled daemons
64
+ * still decode a closed `ModelCapability` set — cloud encoders should
65
+ * send {@link toBootstrapSafeCapabilities} until those binaries are
66
+ * replaced.
67
+ */
68
+ capabilities: S.optional(S.Array(S.String)),
69
+ /** Catalog-declared final outbound-body constraints for this model. */
70
+ caps: S.optional(ModelCaps),
71
+ /**
72
+ * Catalog-declared audio support (input/output formats, voices,
73
+ * realtime ops). The daemon's audio walker currently re-derives these
74
+ * from the provider slug while the catalog already declares them per
75
+ * model, so the card is the correction channel.
76
+ *
77
+ * Optional, like `caps`: an older cloud omits it and a newer daemon
78
+ * reads absent as UNKNOWN, keeping today's provider-derived defaults.
79
+ * Delivered over the AUTHENTICATED bootstrap, never the signed plan —
80
+ * that payload covers only plan/pmids/origin, so anything appended
81
+ * there would be caller-controllable and unsigned.
82
+ */
83
+ audio_support: S.optional(ModelAudioSupport),
84
+ /** Optional so older clouds keep bootstrapping newer daemons. */
85
+ strip_subagent_isolation: S.optional(S.Boolean),
86
+ });
87
+ export type TDaemonCatalogEntry = S.Schema.Type<typeof DaemonCatalogEntry>;
88
+
89
+ export const DaemonBootstrap = S.Struct({
90
+ catalog: S.Array(DaemonCatalogEntry),
91
+ provider_prefixes: S.Array(S.String),
92
+ /**
93
+ * Catalog-owned caps DEFAULTS for models with no catalog row. The
94
+ * daemon runs the SAME `resolveDefaultModelCaps` matcher the cloud
95
+ * does, so an un-catalogued id resolves identically on both paths and
96
+ * the two cannot drift.
97
+ *
98
+ * Optional: an older cloud omits it and the daemon simply resolves no
99
+ * defaults (absent = unknown = permissive, today's behaviour). Rules
100
+ * are DATA on the authenticated bootstrap — never the signed plan.
101
+ */
102
+ caps_defaults: S.optional(S.Array(ModelCapsDefaultRule)),
103
+ user_fallback_groups: S.Array(FallbackGroup),
104
+ user_model_fallback_bindings: S.Array(ModelFallbackBinding),
105
+ model_settings: S.optional(ModelSettingsOverrides),
106
+ /** Per-user context-window overflow routing preference. Absent means the
107
+ * historical hop-to-larger-context behaviour. */
108
+ context_overflow_strategy: S.optional(ContextOverflowStrategy),
109
+ /**
110
+ * Per-user HMAC key the daemon uses to VERIFY the plan `/api/daemon/plan`
111
+ * returns (the cloud signs with the same key). Lets the daemon reject
112
+ * a plan forged by another local process. Null when the cloud has no
113
+ * signing secret configured (dev) — the daemon then accepts unsigned
114
+ * plans. See `docs/proposals/coreless-daemon-passthrough.md` §9.
115
+ */
116
+ plan_signing_key: S.optional(S.NullOr(S.String)),
117
+ /**
118
+ * Authenticated account id for this bootstrap. Optional/additive so older
119
+ * clouds keep bootstrapping; newer daemons use it to compare relay-stamped
120
+ * `peer_user_id` on `channel_open` (cross-user → require a team grant).
121
+ */
122
+ user_id: S.optional(S.String),
123
+ /**
124
+ * Per-contributor HMAC key for verifying team device grants (same key
125
+ * origin uses to sign for this user). Null/absent when
126
+ * `NEON_AUTH_COOKIE_SECRET` is unset — team device routing is then off
127
+ * (`team_device_unavailable`); the daemon refuses team traffic.
128
+ * See `docs/plan/2026-10-26-teams.md` §16.2.
129
+ */
130
+ team_grant_key: S.optional(S.NullOr(S.String)),
131
+ /**
132
+ * The daemon binary version the cloud currently publishes (bare semver, no
133
+ * leading `v` — matches the daemon's compiled `DAEMON_VERSION`). The daemon
134
+ * compares it against its own and SELF-UPDATES when they differ (converge to
135
+ * published — the cloud is the source of truth, so republishing an older tag
136
+ * rolls daemons back). Null/absent when no release is published yet (or the
137
+ * cloud is too old to advertise it) — the daemon then never self-updates.
138
+ * See `packages/cli/daemon/src/self-update.ts`.
139
+ */
140
+ latest_version: S.optional(S.NullOr(S.String)),
141
+ /**
142
+ * The `openllmc` CLI version the cloud currently publishes (bare semver, no
143
+ * leading `v`). The daemon converges the INSTALLED CLI binary at
144
+ * `~/.openllm/bin/openllmc` to it on the same auto-update tick (and under
145
+ * the same opt-out toggle) as its own self-update — one flow, one toggle.
146
+ * The daemon never installs the CLI: an absent binary is skipped. Null/
147
+ * absent when no CLI release is published yet (or the cloud is too old to
148
+ * advertise it) — the daemon then never touches the CLI.
149
+ * One binary is both CLI and daemon now, so this is the release the daemon
150
+ * converges `~/.openllm/bin/openllm` to. See
151
+ * `packages/cli/daemon/src/updater.ts`.
152
+ */
153
+ latest_cli_version: S.optional(S.NullOr(S.String)),
154
+ /**
155
+ * The cloud's resolved `ACTIVE_SUB_METHOD` global preference — a named
156
+ * execution variant (`stream-json` / `sdk-facade` / `acp` / `app-server` /
157
+ * `msp` / `agent-sdk`, optionally `-capture`) or `handrolled`; see
158
+ * `./execution-selection`. Null = no preference: each hop uses its
159
+ * provider's registry default. Sampled once per request from the cached
160
+ * bootstrap snapshot.
161
+ */
162
+ execution_selection: S.optional(S.NullOr(ExecutionSelection)),
163
+ /**
164
+ * Per-provider overrides layered on top of `execution_selection`
165
+ * (`provider:method` entries of the same env). String-keyed so a newer
166
+ * cloud advertising a slug this daemon predates never fails bootstrap
167
+ * decode.
168
+ */
169
+ execution_selections: S.optional(
170
+ S.NullOr(S.Record(S.String, ExecutionSelection)),
171
+ ),
172
+ /**
173
+ * Cloud-controlled toggle for the daemon's SIGNED-PLAN CACHE
174
+ * (`DAEMON_PLAN_CACHE` on the cloud, default ON — an explicit `0`/`false`
175
+ * disables): when true, a `/v1/*` request that reaches the daemon
176
+ * directly may be served against the most recent
177
+ * cloud-signed plan tuple for the same model alias within a short TTL,
178
+ * skipping the per-request cloud round trip. The signature is still
179
+ * verified per request (the cached tuple is exactly what the cloud
180
+ * signed); staleness is bounded by the TTL. False → the daemon requires
181
+ * a plan on every request; ABSENT (a cloud predating the field) → the
182
+ * daemon also keeps the cache off (the cloud is the one authority). See
183
+ * docs/proposals/sub-method-simplified-execution.md §4.
184
+ */
185
+ plan_cache: S.optional(S.Boolean),
186
+ /**
187
+ * The user's FLEET subscription servers: for each subscription provider
188
+ * connected on some ONLINE daemon of this user, the serving daemon's
189
+ * key id. Computed cloud-side from `api_key_activity` presence + status
190
+ * (serve-by-default policy — every online device qualifies). A consuming
191
+ * daemon with no local credential for a subscription hop tunnels the
192
+ * request to `key_id` over the relay
193
+ * (`docs/features/sub-tunnel-and-chat-sessions.md` §1). String-keyed
194
+ * provider so newer slugs never fail an older daemon's decode; optional
195
+ * so older clouds keep bootstrapping newer daemons.
196
+ */
197
+ fleet_subscriptions: S.optional(
198
+ S.Array(
199
+ S.Struct({
200
+ provider: S.String,
201
+ key_id: S.String,
202
+ /** Serving daemon X25519 SPKI, absent for pre-pubkey peers. */
203
+ pubkey: S.optional(S.String),
204
+ }),
205
+ ),
206
+ ),
207
+ /**
208
+ * SPKI DER (base64) of the account DEVICE-CONTROL public key (Ed25519,
209
+ * derived in the browser from the recovery phrase — never from the DEK, so
210
+ * the cloud cannot sign with it). The daemon first-use pins it UNANCHORED
211
+ * (tunnel only), follows signed rotations, and anchors only from a local
212
+ * root (install anchor / loopback); it verifies
213
+ * browser-signed device grants against it. The
214
+ * field name is historical: before `device_access_kind: "control"` it carried
215
+ * a per-key DEK-derived key ("legacy"). Null when the key is un-provisioned or
216
+ * the caller is session-only / watcher (no owning key). Optional so older
217
+ * clouds keep bootstrapping newer daemons.
218
+ */
219
+ device_access_pubkey: S.optional(S.NullOr(S.String.check(S.isMaxLength(64)))),
220
+ /**
221
+ * `"control"` when {@link device_access_pubkey} is the account control key.
222
+ * Absent = legacy per-key value (the daemon then never upgrades a pin to it
223
+ * and refuses agent sessions with `device_not_anchored`).
224
+ */
225
+ device_access_kind: S.optional(S.Literal("control")),
226
+ /**
227
+ * The control key's generation (`users.device_control_version`, the vault
228
+ * generation it was derived under). A signed rotation must carry a greater
229
+ * `cv` than the daemon's pinned version. Null/absent when unknown.
230
+ */
231
+ device_access_version: S.optional(S.NullOr(S.Number.check(S.isInt()))),
232
+ /**
233
+ * Control-key rotation statements, oldest first (base64 JSON, signed by the
234
+ * PREVIOUS control key — see `@openllmsh/sdk/tunnel` `device-control.ts`). The
235
+ * daemon walks the chain from its own pin to {@link device_access_pubkey}.
236
+ * The cloud cannot forge a step: each is signed by a key only a browser
237
+ * holding the recovery phrase ever derived.
238
+ */
239
+ device_access_rotations: S.optional(
240
+ S.Array(S.String.check(S.isMaxLength(1024))).check(S.isMaxLength(8)),
241
+ ),
242
+ /**
243
+ * Optional reporting policy. Absent on old clouds = off. Expired or
244
+ * `enabled: false` means no upload. See `doctor-report-policy.ts`.
245
+ */
246
+ reporting_policy: S.optional(DaemonReportingPolicy),
247
+ /**
248
+ * Revision of the authenticating key's access policy (models, routes,
249
+ * caps). The daemon drops every cached plan when it changes, so a plan
250
+ * cached under an older policy is never replayed. Null for a session
251
+ * caller with no key. When absent, retain the daemon's known revision.
252
+ */
253
+ key_policy_rev: S.optional(S.NullOr(S.String)),
254
+ });
255
+ export type TDaemonBootstrap = S.Schema.Type<typeof DaemonBootstrap>;
256
+
257
+ /**
258
+ * Wire contracts for the local daemon ⇄ cloud control plane and for the
259
+ * daemon's own localhost control surface.
260
+ *
261
+ * Compliance note: the only daemon→cloud payloads are config pulls and
262
+ * the metadata-only request row below. No subscription token and no
263
+ * prompt/completion content ever crosses this boundary.
264
+ */
265
+
266
+ // ─── POST /api/daemon/requests (daemon → cloud) ──────────────────────
267
+ //
268
+ // One `public.requests` row for a subscription hop the daemon ran
269
+ // locally. `user_id` / `key_id` are deliberately ABSENT: the cloud
270
+ // derives both from the authenticating `sk-llm-...` key, so a daemon can
271
+ // only ever record rows for its own owner.
272
+ //
273
+ // No `cost_usd` either — the daemon reports only TOKEN COUNTS; the cloud
274
+ // is the single pricing source of truth and computes cost from these
275
+ // tokens in `daemonRecordHandler` (`costFor`). Keeping cost off the wire
276
+ // is why no pricing table is duplicated onto the daemon.
277
+ const HOLD_NONCE_PATTERN =
278
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?![\s\S])/i;
279
+ const HoldNonce = S.String.check(S.isPattern(HOLD_NONCE_PATTERN));
280
+
281
+ export const DaemonRecordRequest = S.Struct({
282
+ model: S.String,
283
+ provider: S.String,
284
+ status: RequestStatus,
285
+ /** Canonical prompt tokens — INCLUDES the two cache fields below. */
286
+ tokens_in: S.Number,
287
+ tokens_out: S.Number,
288
+ // The cache split of `tokens_in`. Optional so a daemon built before this
289
+ // field existed still records (its rows just price as all-fresh input, the
290
+ // prior behaviour). Still no `cost_usd`: the cloud prices these tokens.
291
+ cached_tokens: S.optional(S.Number),
292
+ cache_creation_tokens: S.optional(S.Number),
293
+ latency_ms: S.Number,
294
+ idempotency_key: S.optional(S.NullOr(S.String)),
295
+ error: S.optional(S.NullOr(S.String)),
296
+ endpoint: S.optional(S.NullOr(S.String)),
297
+ /** Obscured vendor-account identity of the credential that SERVED this
298
+ * hop — the same `sha256("openllm-account-v1:<provider>:<id>")` digest
299
+ * the status frame reports, computed from the token that ran the
300
+ * request. Lets the usage-calibration estimator attribute this row's
301
+ * cost to the right meter series when a provider has several accounts.
302
+ * Optional so daemons predating the field still record (the cloud
303
+ * stores null → the estimator's conservative null pool). */
304
+ account_hash: S.optional(S.String),
305
+ /**
306
+ * Origin-signed team grant echoed on team hops so the cloud attributes
307
+ * the row to the consumer and settles `team_usage_counters`. Same-user
308
+ * records omit it. Bounded like the mux forward header.
309
+ */
310
+ team_grant: S.optional(S.String.check(S.isMaxLength(TEAM_GRANT_B64_MAX))),
311
+ /**
312
+ * Cap hold this request ran under. Only the hold's TERMINAL record carries
313
+ * it; that record settles the hold at `tokens_in + tokens_out` (may be 0).
314
+ * Accepted only from the device key the hold is bound to.
315
+ */
316
+ hold_nonce: S.optional(HoldNonce),
317
+ /**
318
+ * With `hold_nonce`: tokens reported by this request's earlier attempts
319
+ * (retries, sibling accounts, fallbacks), added to this record's tokens.
320
+ */
321
+ hold_prior_tokens: S.optional(
322
+ S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0)),
323
+ ),
324
+ /**
325
+ * With `hold_nonce`: sends of this request with no usage evidence. The
326
+ * cloud charges each one the hold's full reservation.
327
+ */
328
+ hold_unknown_attempts: S.optional(
329
+ S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0)),
330
+ ),
331
+ cooldown_reason: S.optional(CooldownReason),
332
+ /** Reset instant for reset-aware TTL cap; optional so old daemons omit. */
333
+ reset_at_ms: S.optional(S.Number),
334
+ }).check(
335
+ // A successful hop never cools — a `cooldown_reason` on a `success` record
336
+ // is malformed, so reject it at the schema boundary rather than let the
337
+ // handler mark a cooldown for a model that just served cleanly.
338
+ S.makeFilter(
339
+ (record: TDaemonRecordRequest) =>
340
+ record.status !== "success" || record.cooldown_reason === undefined,
341
+ { message: "cooldown_reason is only valid on a non-success record" },
342
+ ),
343
+ );
344
+ export type TDaemonRecordRequest = S.Schema.Type<typeof DaemonRecordRequest>;
345
+
346
+ // ─── POST /api/daemon/models (daemon → cloud) ────────────────────────
347
+ //
348
+ // The daemon writer for `public.model_cache` (live-provider-model-catalog
349
+ // proposal §4): the live model lists the daemon's CONNECTED delegates
350
+ // report from their vendors' own list endpoints. Metadata only — model
351
+ // ids + optional display/context data, never a credential. `user_id` is
352
+ // deliberately ABSENT (derived from the authenticating `sk-llm-...` key,
353
+ // same posture as `DaemonRecordRequest`), and the handler restricts
354
+ // `provider` to the subscription set so a daemon can never overwrite the
355
+ // cloud-owned API-key rows.
356
+ export const DaemonModelReportEntry = S.Struct({
357
+ provider: S.String.check(S.isMaxLength(64)),
358
+ // Same per-list bound as `ProviderModelList` (defense-in-depth on
359
+ // this authenticated write path).
360
+ models: ProviderModelList,
361
+ /** Vendor CLI version (bare semver) that OBSERVED this list. Some
362
+ * vendors gate model visibility by client version (Codex does), so
363
+ * the cloud uses this to refuse a write that would replace a fresh
364
+ * row produced by a NEWER CLI on another device. Optional so daemons
365
+ * built before the field still report (their writes stay permissive). */
366
+ cli_version: S.optional(S.String.check(S.isMaxLength(64))),
367
+ });
368
+ export type TDaemonModelReportEntry = S.Schema.Type<
369
+ typeof DaemonModelReportEntry
370
+ >;
371
+
372
+ export const DaemonModelReport = S.Struct({
373
+ // One entry per subscription (oauth) provider — the closed set is small;
374
+ // 32 leaves headroom without allowing a bloated report.
375
+ entries: S.Array(DaemonModelReportEntry).check(S.isMaxLength(32)),
376
+ /**
377
+ * Device-discovered local model-server lists, keyed by `local_*` /
378
+ * `local_port_*` provider. Separate from `entries` so an oauth-only
379
+ * maxItems(32) bound cannot crowd out local rows (and vice versa).
380
+ * Absent on older daemons.
381
+ */
382
+ local_entries: S.optional(
383
+ S.Array(DaemonModelReportEntry).check(S.isMaxLength(64)),
384
+ ),
385
+ });
386
+ export type TDaemonModelReport = S.Schema.Type<typeof DaemonModelReport>;
387
+
388
+ /** Probe outcome for one local model server on the daemon's machine. */
389
+ export const LocalServerStatus = S.Literals(["ok", "needs_key", "unreachable"]);
390
+ export type TLocalServerStatus = S.Schema.Type<typeof LocalServerStatus>;
391
+
392
+ /**
393
+ * Live local-server discovery state pushed on `DaemonStatus` (no keys —
394
+ * only `has_key`). Also the result shape of a `local_rescan` command.
395
+ */
396
+ export const LocalServerState = S.Struct({
397
+ /** Preset slug (`local_ollama`, …) or `local_port_<port>` fallback. */
398
+ slug: S.String.check(S.isMinLength(1), S.isMaxLength(64)),
399
+ port: S.Number.check(
400
+ S.isInt(),
401
+ S.isGreaterThanOrEqualTo(1),
402
+ S.isLessThanOrEqualTo(65535),
403
+ ),
404
+ base_url: S.String.check(S.isMinLength(1), S.isMaxLength(512)),
405
+ status: LocalServerStatus,
406
+ has_key: S.Boolean,
407
+ models: ProviderModelList,
408
+ });
409
+ export type TLocalServerState = S.Schema.Type<typeof LocalServerState>;
410
+
411
+ // ─── Daemon control relay (cloud ⇄ daemon over the WebSocket relay) ──
412
+ //
413
+ // The daemon dials OUT and holds ONE WebSocket to the relay (it fetches the
414
+ // channel via `GET /api/daemon/channel`); the dashboard enqueues control
415
+ // commands via its own watcher socket (or `POST /api/daemon/cmd` as a
416
+ // fallback). Commands, acks and status all ride relay frames (see
417
+ // `packages/schema/relay.ts`); the relay writes `api_key_activity` so presence
418
+ // is server-side, no `x-openllm-daemon` header. See
419
+ // `docs/proposals/daemon-relay-websocket-push.md`.
420
+
421
+ export type { TSubscriptionProviderSlug } from "./subscription-provider";
422
+ export { SubscriptionProviderSlug } from "./subscription-provider";
423
+
424
+ // ─── POST /api/daemon/session-lost (daemon → cloud) ──────────────────
425
+ //
426
+ // An authenticated daemon reports a confirmed subscription session loss. The
427
+ // cloud derives the user and source key from the bearer token; neither belongs
428
+ // in this body.
429
+ export const DaemonSessionLost = S.Struct({
430
+ slug: SubscriptionProviderSlug,
431
+ account_hash: S.optional(S.String),
432
+ /** Bounded, non-secret classifier of `conn.detail` — never the raw string. */
433
+ diagnostic_code: S.optional(AuthSessionLostDiagnosticCode),
434
+ });
435
+ export type TDaemonSessionLost = S.Schema.Type<typeof DaemonSessionLost>;
436
+
437
+ export const DaemonQuotaStatusReached = S.Struct({
438
+ slug: SubscriptionProviderSlug,
439
+ status: S.Literals(["allowed_warning", "rejected"]),
440
+ account_hash: S.optional(S.String),
441
+ plan: S.optional(S.String),
442
+ /**
443
+ * Sustaining quota-window reset epoch (unix ms). Optional so older daemons
444
+ * omit it; cloud then falls back to account:status + 24h cooldown.
445
+ */
446
+ reset_at_ms: S.optional(S.Number),
447
+ /**
448
+ * The quota snapshot that produced this transition — display-only, it lets
449
+ * the email list every limit with its usage and reset. Optional so older
450
+ * daemons omit it. The cloud decodes it apart from the fields above and
451
+ * falls back to the plain notice when it is missing, undecodable, not a
452
+ * quota snapshot, or disagrees with `status`.
453
+ */
454
+ usage: S.optional(ProviderUsageSnapshot),
455
+ });
456
+ export type TDaemonQuotaStatusReached = S.Schema.Type<
457
+ typeof DaemonQuotaStatusReached
458
+ >;
459
+
460
+ /** Optional user-visible device-session label (open frames + presence). */
461
+ export const SessionTitleField = S.String.check(S.isMaxLength(80));
462
+ export type TSessionTitleField = S.Schema.Type<typeof SessionTitleField>;
463
+
464
+ /**
465
+ * CLIs the device PTY surface can host: OpenLLM session clients with local
466
+ * history + resume wiring (Claude / Codex / Grok / OpenCode / Hermes), plus a
467
+ * direct login shell. Keep `SubscriptionProviderSlug` for credentials/usage;
468
+ * session frames use this set, while the local-session list uses its narrower
469
+ * canonical set. Kimi and Cursor stay subscription-only for now.
470
+ */
471
+ export const DeviceSessionCli = S.Literals([
472
+ "claude_code",
473
+ "chatgpt",
474
+ "grok",
475
+ "opencode",
476
+ "hermes",
477
+ "shell",
478
+ ]);
479
+ export type TDeviceSessionCli = S.Schema.Type<typeof DeviceSessionCli>;
480
+
481
+ /**
482
+ * CLIs for which `openllm -d <client>` (skip approvals) is meaningful.
483
+ * Canonical set — the picker, session-host, and any consumer import THIS
484
+ * rather than re-declaring their own membership list.
485
+ */
486
+ export const DANGEROUS_SESSION_CLIS: ReadonlySet<TDeviceSessionCli> = new Set([
487
+ "claude_code",
488
+ "chatgpt",
489
+ "grok",
490
+ "hermes",
491
+ ]);
492
+
493
+ /** CLIs with a local history reader on the daemon (v1). Canonical set. */
494
+ export const LISTABLE_SESSION_CLIS: ReadonlySet<TDeviceSessionCli> = new Set([
495
+ "claude_code",
496
+ "chatgpt",
497
+ "grok",
498
+ "opencode",
499
+ "hermes",
500
+ ]);
501
+
502
+ export const supportsDangerousSession = (cli: string): boolean =>
503
+ (DANGEROUS_SESSION_CLIS as ReadonlySet<string>).has(cli);
504
+
505
+ export const isListableSessionCli = (cli: string): boolean =>
506
+ (LISTABLE_SESSION_CLIS as ReadonlySet<string>).has(cli);
507
+
508
+ /**
509
+ * One row from the daemon's local session index (vendor history +
510
+ * `~/.openllm/run/<client>/<pid>/live.json` + in-memory device PTYs).
511
+ * Used by `list_local_sessions` so the picker can attach / cold-resume
512
+ * without scanning disk in the browser.
513
+ */
514
+ export const LocalCliSession = S.Struct({
515
+ /** Vendor session id when known; otherwise a synthetic live-run key. */
516
+ id: S.String.check(S.isMinLength(1), S.isMaxLength(128)),
517
+ title: SessionTitleField,
518
+ cwd: S.NullOr(S.String.check(S.isMaxLength(1024))),
519
+ updated_at_ms: S.Number,
520
+ cli: DeviceSessionCli,
521
+ live: S.Boolean,
522
+ /** Where the live process is hosted, when `live`. */
523
+ host: S.optional(S.NullOr(S.Literals(["local", "device"]))),
524
+ /** OpenLLM device session id when the PTY is already hosted by the daemon. */
525
+ openllm_session_id: S.optional(S.NullOr(S.String.check(S.isMaxLength(64)))),
526
+ /** True when the browser can `mode:"attach"` without spawning a second CLI. */
527
+ attachable: S.Boolean,
528
+ });
529
+ export type TLocalCliSession = S.Schema.Type<typeof LocalCliSession>;
530
+
531
+ /** Payload for `list_local_sessions`. */
532
+ export const ListLocalSessionsPayload = S.Struct({
533
+ cli: DeviceSessionCli,
534
+ /** Max rows (default 30 server-side; hard cap 100). */
535
+ limit: S.optional(
536
+ S.Number.check(
537
+ S.isInt(),
538
+ S.isGreaterThanOrEqualTo(1),
539
+ S.isLessThanOrEqualTo(100),
540
+ ),
541
+ ),
542
+ });
543
+ export type TListLocalSessionsPayload = S.Schema.Type<
544
+ typeof ListLocalSessionsPayload
545
+ >;
546
+
547
+ /** Result blob for `list_local_sessions` (command ack / lifecycle.result). */
548
+ export const ListLocalSessionsResult = S.Struct({
549
+ sessions: S.Array(LocalCliSession),
550
+ });
551
+ export type TListLocalSessionsResult = S.Schema.Type<
552
+ typeof ListLocalSessionsResult
553
+ >;
554
+
555
+ /**
556
+ * Result blob for `refresh_models_due` (command ack / lifecycle.result).
557
+ * Always rides a `done` lifecycle — automatic discovery never surfaces as
558
+ * a user-facing command error. `attempted: false` + `reported: 0` is a
559
+ * quiet TTL/credential skip; `reported: 0` + `failed: true` is a total
560
+ * failure. The dashboard refetches `/v1/models` on `reported > 0`
561
+ * (including partial writes) and also on quiet skips (`failed === false`)
562
+ * so a cached query can pick up a catalog another trigger already POSTed.
563
+ */
564
+ export const RefreshModelsDueResult = S.Struct({
565
+ attempted: S.Boolean,
566
+ reported: S.Number,
567
+ failed: S.Boolean,
568
+ error: S.optional(S.String),
569
+ });
570
+ export type TRefreshModelsDueResult = S.Schema.Type<
571
+ typeof RefreshModelsDueResult
572
+ >;
573
+
574
+ /** Terminal exit reason retained for a dead but resumable device session. */
575
+ export const SessionExitReason = S.Literals([
576
+ "evicted",
577
+ "reaped",
578
+ "done",
579
+ "killed",
580
+ ]);
581
+ export type TSessionExitReason = S.Schema.Type<typeof SessionExitReason>;
582
+
583
+ // Opaque base64 blob (an X25519 sealed box / SPKI public key) — decrypted or
584
+ // parsed by the recipient, never executed. Padding restricted to at most two
585
+ // '=' characters only at the end (valid base64 format).
586
+ const Base64Blob = S.String.check(S.isPattern(/^[A-Za-z0-9+/]+={0,2}$/));
587
+
588
+ /** The closed set of install-time gateway modes: which base URL a client
589
+ * setup bakes — the local daemon (`local`, the default) or the cloud
590
+ * origin. ONE schema for every wire field and TS union that carries it. */
591
+ export const GatewayMode = S.Literals(["local", "cloud"]);
592
+ export type TGatewayMode = S.Schema.Type<typeof GatewayMode>;
593
+
594
+ /** Device-local account slot of a subscription provider (multi-account,
595
+ * `docs/plan/multi-account-subscriptions.md`). Absent ⇒ 0, today's single
596
+ * account. Old daemons strip the field on decode and act on account 0, so
597
+ * senders must only set it when the daemon advertises
598
+ * `features.multi_account`. */
599
+ export const AccountIndex = S.Number.check(
600
+ S.isInt(),
601
+ S.isGreaterThanOrEqualTo(0),
602
+ S.isLessThanOrEqualTo(1023),
603
+ );
604
+ export type TAccountIndex = S.Schema.Type<typeof AccountIndex>;
605
+
606
+ const ProviderPayload = S.Struct({
607
+ slug: SubscriptionProviderSlug,
608
+ account_index: S.optional(AccountIndex),
609
+ });
610
+ /** Add an account slot; the daemon allocates the index and returns it. */
611
+ const AddAccountPayload = S.Struct({
612
+ slug: SubscriptionProviderSlug,
613
+ label: S.optional(S.String.check(S.isMaxLength(64))),
614
+ });
615
+ /** Remove an account slot (n >= 1; account 0 is only logged out). */
616
+ const RemoveAccountPayload = S.Struct({
617
+ slug: SubscriptionProviderSlug,
618
+ account_index: AccountIndex.check(S.isGreaterThanOrEqualTo(1)),
619
+ });
620
+ /** Pin an account first in routing, or clear the pin with `null`. */
621
+ const PinAccountPayload = S.Struct({
622
+ slug: SubscriptionProviderSlug,
623
+ account_index: S.NullOr(AccountIndex),
624
+ });
625
+ /** Cancel an in-flight connect. `flow_id` is optional so old senders keep
626
+ * working; when present the daemon binds the signal to that owner and
627
+ * rejects mismatches. Extra field is additive — old decoders ignore it. */
628
+ const CancelConnectPayload = S.Struct({
629
+ slug: SubscriptionProviderSlug,
630
+ account_index: S.optional(AccountIndex),
631
+ flow_id: S.optional(S.String),
632
+ });
633
+ /** A remote-Claude headless-login code submission: the X25519-sealed OAuth
634
+ * authorization code the user pasted from the hosted callback page. Opened on
635
+ * the target daemon and written to the waiting `claude auth login` stdin. The
636
+ * code is single-use + PKCE-bound (useless without the daemon's in-process
637
+ * verifier); sealed so the cloud relays it blind. See
638
+ * `docs/proposals/headless-claude-login-paste-back.md`. */
639
+ const SubmitLoginCodePayload = S.Struct({
640
+ slug: SubscriptionProviderSlug,
641
+ account_index: S.optional(AccountIndex),
642
+ sealed: Base64Blob,
643
+ });
644
+ /** Set or clear a per-port API key for a local model server. `sealed` is an
645
+ * X25519 sealed box to the daemon's pubkey (same posture as
646
+ * `submit_login_code`); an empty sealed blob clears the stored key. */
647
+ const SetLocalKeyPayload = S.Struct({
648
+ port: S.Number.check(
649
+ S.isInt(),
650
+ S.isGreaterThanOrEqualTo(1),
651
+ S.isLessThanOrEqualTo(65535),
652
+ ),
653
+ sealed: S.Union([Base64Blob, S.Literal("")]),
654
+ });
655
+ /** Add, replace or remove one `local_key` provider key slot. `sealed` is an
656
+ * X25519 sealed box of the API key to the daemon's pubkey; the relay and
657
+ * cloud never see plaintext. `account_index` absent ⇒ allocate a new slot
658
+ * (lowest free index). Present + empty `sealed` ⇒ remove that slot. Present
659
+ * + non-empty ⇒ replace that slot's key. */
660
+ const SetProviderKeyPayload = S.Struct({
661
+ slug: LocalKeyProviderSlug,
662
+ account_index: S.optional(AccountIndex),
663
+ sealed: S.Union([Base64Blob, S.Literal("")]),
664
+ label: S.optional(S.String.check(S.isMaxLength(64))),
665
+ });
666
+ /** Team ids name the daemon's `team-keys/<id>.json`, so the wire admits only
667
+ * a path-safe id (the cloud mints UUIDs). */
668
+ export const TEAM_KEY_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
669
+ const TeamKeyId = S.String.check(S.isPattern(TEAM_KEY_ID_PATTERN));
670
+ const SetTeamKeyPayload = S.Struct({
671
+ team_id: TeamKeyId,
672
+ epoch: S.Int.check(S.isGreaterThanOrEqualTo(0)),
673
+ sealed: Base64Blob,
674
+ });
675
+ const DeleteTeamKeyPayload = S.Struct({ team_id: TeamKeyId });
676
+ const SetAutoUpdatePayload = S.Struct({ enabled: S.Boolean });
677
+ /** Disable device sessions remotely: `statement` is the base64 envelope of
678
+ * `{ v: 1, key_id, ts, nonce, sig }` signed by the account control key
679
+ * (`@openllmsh/sdk/vault` `signDeviceSessionsDisable`). Disable-only — there is no
680
+ * remote enable. The daemon verifies against its ANCHORED pin and blanks
681
+ * `OPENLLM_DEVICE_ANCHOR`; the cloud only relays and cannot forge one. */
682
+ const SetDeviceSessionsPayload = S.Struct({
683
+ statement: S.String.check(
684
+ S.isMinLength(1),
685
+ S.isMaxLength(1024),
686
+ S.isPattern(/^[A-Za-z0-9+/]+={0,2}$/),
687
+ ),
688
+ });
689
+ /** `refresh` re-reads usage for connected providers. Optional `slug` scopes
690
+ * that read to one provider; omitted `slug` means every connected provider
691
+ * (bare `{}` is that whole-daemon read — it does not clear the usage cache).
692
+ * `manual` is the explicit Refresh-usage button only: it may native-refresh
693
+ * an expired stored token. Cache TTL bypass is daemon-internal
694
+ * (`cachedUsage` `force`), never this wire flag. Absent/false is the
695
+ * auto/mount path (stored credential, TTL-respecting). */
696
+ const RefreshPayload = S.Struct({
697
+ slug: S.optional(SubscriptionProviderSlug),
698
+ account_index: S.optional(AccountIndex),
699
+ manual: S.optional(S.Boolean),
700
+ });
701
+ /** One `openllm auth …` request run on the device by the same handler the CLI
702
+ * and MCP reach over loopback (`/local/auth`), so every surface shares one
703
+ * contract and one reply. The paste-back code never travels in clear:
704
+ * `sealed_code` is an X25519 sealed box to the daemon's pubkey. The daemon
705
+ * re-validates the opened request with `parseLocalAuthRequest`. */
706
+ const AuthPayload = S.Struct({
707
+ operation: S.Literals(AUTH_OPERATIONS),
708
+ provider: S.optional(S.String.check(S.isPattern(/^[a-z][a-z0-9_]{0,63}$/))),
709
+ method: S.optional(S.Literals(["browser", "device"])),
710
+ flow_id: S.optional(S.String.check(S.isPattern(/^[a-zA-Z0-9_-]{1,128}$/))),
711
+ account: S.optional(AccountIndex),
712
+ label: S.optional(S.String.check(S.isMinLength(1), S.isMaxLength(64))),
713
+ since: S.optional(S.String.check(S.isPattern(/^[a-f0-9]{1,64}$/))),
714
+ wait_ms: S.optional(
715
+ S.Int.check(
716
+ S.isGreaterThanOrEqualTo(0),
717
+ S.isLessThanOrEqualTo(AUTH_RELAY_WAIT_MAX_MS),
718
+ ),
719
+ ),
720
+ sealed_code: S.optional(Base64Blob),
721
+ });
722
+ export type TAuthPayload = S.Schema.Type<typeof AuthPayload>;
723
+ /** Decoding strips unknown keys, so enqueue boundaries also refuse any raw
724
+ * key outside this set — a plaintext `code` never transits the relay. */
725
+ export const AUTH_PAYLOAD_KEYS: ReadonlySet<string> = new Set(
726
+ Object.keys(AuthPayload.fields),
727
+ );
728
+ export const authPayloadKeysAllowed = (payload: unknown): boolean =>
729
+ payload !== null &&
730
+ typeof payload === "object" &&
731
+ !Array.isArray(payload) &&
732
+ Object.keys(payload).every((key) => AUTH_PAYLOAD_KEYS.has(key));
733
+
734
+ /** Payload-less commands (`status` / `update`): accept an absent payload or a
735
+ * bare `{}` so every union member carries the field (uniform access). */
736
+ const EmptyPayload = S.Struct({});
737
+
738
+ /**
739
+ * The CLOSED control-command vocabulary — one struct per kind, literal-
740
+ * discriminated, every payload field a constrained scalar (a provider-slug
741
+ * enum, a charset-pinned artifact slug, a boolean, an opaque base64 blob).
742
+ * NO field may carry a command string, script body, args array, URL, or
743
+ * free filesystem path — adding one is a deliberate, reviewable schema
744
+ * change, not something `S.Unknown` admits. A command outside this set
745
+ * fails decode at the parse boundary on BOTH ends (cloud/relay enqueue +
746
+ * the daemon's relay socket) before any handler runs. See
747
+ * `docs/proposals/daemon-os-sandbox-and-typed-control.md` §2.
748
+ *
749
+ * Built once and addressed three ways so the vocabularies can never drift:
750
+ * bare (enqueue validation), `id` (relay delivery wire), `key_id`
751
+ * (dashboard enqueue wire).
752
+ */
753
+ const commandVariants = <F extends S.Struct.Fields>(addressing: F) =>
754
+ [
755
+ S.Struct({
756
+ ...addressing,
757
+ kind: S.Literals(["auth"]),
758
+ payload: AuthPayload,
759
+ }),
760
+ S.Struct({
761
+ ...addressing,
762
+ kind: S.Literals(["connect"]),
763
+ payload: ProviderPayload,
764
+ }),
765
+ S.Struct({
766
+ ...addressing,
767
+ kind: S.Literals(["connect_device_code"]),
768
+ payload: ProviderPayload,
769
+ }),
770
+ S.Struct({
771
+ ...addressing,
772
+ kind: S.Literals(["cancel_connect"]),
773
+ payload: CancelConnectPayload,
774
+ }),
775
+ S.Struct({
776
+ ...addressing,
777
+ kind: S.Literals(["logout"]),
778
+ payload: ProviderPayload,
779
+ }),
780
+ S.Struct({
781
+ ...addressing,
782
+ kind: S.Literals(["submit_login_code"]),
783
+ payload: SubmitLoginCodePayload,
784
+ }),
785
+ S.Struct({
786
+ ...addressing,
787
+ kind: S.Literals(["add_account"]),
788
+ payload: AddAccountPayload,
789
+ }),
790
+ S.Struct({
791
+ ...addressing,
792
+ kind: S.Literals(["remove_account"]),
793
+ payload: RemoveAccountPayload,
794
+ }),
795
+ S.Struct({
796
+ ...addressing,
797
+ kind: S.Literals(["pin_account"]),
798
+ payload: PinAccountPayload,
799
+ }),
800
+ S.Struct({
801
+ ...addressing,
802
+ kind: S.Literals(["set_auto_update"]),
803
+ payload: SetAutoUpdatePayload,
804
+ }),
805
+ S.Struct({
806
+ ...addressing,
807
+ kind: S.Literals(["refresh"]),
808
+ payload: S.optional(RefreshPayload),
809
+ }),
810
+ S.Struct({
811
+ ...addressing,
812
+ kind: S.Literals(["status"]),
813
+ payload: S.optional(EmptyPayload),
814
+ }),
815
+ S.Struct({
816
+ ...addressing,
817
+ kind: S.Literals(["update"]),
818
+ payload: S.optional(EmptyPayload),
819
+ }),
820
+ // Drop every cached signed plan tuple NOW. The dashboard enqueues this
821
+ // after a successful chain/config save so the very next request bounces
822
+ // through the cloud and picks up the new chain instead of replaying the
823
+ // old one for up to the cache TTL (the "app feels unresponsive to chain
824
+ // reorders" friction). Payload-less and idempotent.
825
+ S.Struct({
826
+ ...addressing,
827
+ kind: S.Literals(["bust_plan_cache"]),
828
+ payload: S.optional(EmptyPayload),
829
+ }),
830
+ // Force a live model-list re-report NOW. The daemon's model-report
831
+ // throttle mirrors the cloud's 30m `MODEL_CACHE_TTL_MS` — without this
832
+ // command the only way to re-discover models mid-TTL is `openllmd
833
+ // restart`. The dashboard's "Available models" refresh button enqueues
834
+ // this; the executor clears the throttle, re-fetches every connected
835
+ // delegate's list, and POSTs to `/api/daemon/models` BEFORE acking so
836
+ // the subsequent `/v1/models` refetch the dashboard does after the
837
+ // lifecycle frame lands sees the fresh rows. Payload-less and
838
+ // idempotent.
839
+ S.Struct({
840
+ ...addressing,
841
+ kind: S.Literals(["refresh_models"]),
842
+ payload: S.optional(EmptyPayload),
843
+ }),
844
+ // Automatic, non-force model discovery. Distinct kind — never an
845
+ // optional flag on `refresh_models`, because an older daemon would
846
+ // strip unknown fields and run a throttle-resetting, auth-capable
847
+ // list. Empty payload. Quiet `done` even when every provider skips
848
+ // or fails; the dashboard only sends this when `control_caps`
849
+ // advertises the kind.
850
+ S.Struct({
851
+ ...addressing,
852
+ kind: S.Literals(["refresh_models_due"]),
853
+ payload: S.optional(EmptyPayload),
854
+ }),
855
+ // List vendor-local sessions on this machine for one device CLI
856
+ // (history stores + ~/.openllm/run live.json + in-memory PTYs). Result
857
+ // rides on the command ack / lifecycle.result for the picker.
858
+ S.Struct({
859
+ ...addressing,
860
+ kind: S.Literals(["list_local_sessions"]),
861
+ payload: ListLocalSessionsPayload,
862
+ }),
863
+ // Re-probe well-known (and user-added) local model-server ports NOW.
864
+ // Result is the current `TLocalServerState[]` on the command ack.
865
+ // Payload-less and idempotent; older daemons ignore the unknown kind.
866
+ S.Struct({
867
+ ...addressing,
868
+ kind: S.Literals(["local_rescan"]),
869
+ payload: S.optional(EmptyPayload),
870
+ }),
871
+ // Set or clear the API key for one local model-server port. The key is
872
+ // sealed to the daemon's X25519 pubkey in the browser; the relay never
873
+ // sees plaintext. Empty `sealed` clears. Older daemons ignore the kind.
874
+ S.Struct({
875
+ ...addressing,
876
+ kind: S.Literals(["set_local_key"]),
877
+ payload: SetLocalKeyPayload,
878
+ }),
879
+ // Add / replace / remove a `local_key` provider key slot (OpenCode Go,
880
+ // Z.AI, MiniMax). Sent only when `control_caps` advertises
881
+ // LOCAL_KEY_PROVIDERS_CONTROL_CAP; older daemons ignore the kind.
882
+ S.Struct({
883
+ ...addressing,
884
+ kind: S.Literals(["set_provider_key"]),
885
+ payload: SetProviderKeyPayload,
886
+ }),
887
+ S.Struct({
888
+ ...addressing,
889
+ kind: S.Literals(["set_team_key"]),
890
+ payload: SetTeamKeyPayload,
891
+ }),
892
+ S.Struct({
893
+ ...addressing,
894
+ kind: S.Literals(["delete_team_key"]),
895
+ payload: DeleteTeamKeyPayload,
896
+ }),
897
+ // Control-key-signed device-sessions DISABLE. Older daemons ignore the
898
+ // kind; the dashboard sends it only when `control_caps` advertises it.
899
+ // There is no remote enable — re-enable is install/update/login/desktop
900
+ // with the sessions toggle on (writes the anchor again).
901
+ S.Struct({
902
+ ...addressing,
903
+ kind: S.Literals(["set_device_sessions"]),
904
+ payload: SetDeviceSessionsPayload,
905
+ }),
906
+ ] as const;
907
+
908
+ /** The bare `{ kind, payload }` vocabulary — what an enqueue boundary (the
909
+ * relay's watcher `enqueue` frame, `enqueueCommand` in `packages/api`)
910
+ * validates before writing a `daemon_commands` row. */
911
+ export const DaemonCommandBody = S.Union([...commandVariants({})]);
912
+ export type TDaemonCommandBody = S.Schema.Type<typeof DaemonCommandBody>;
913
+
914
+ /** Every kind in the closed vocabulary (the union's discriminants). */
915
+ export type TDaemonCommandKind = TDaemonCommandBody["kind"];
916
+
917
+ /** Runtime literal of the closed command vocabulary — the discriminant only,
918
+ * no payload. Used by `control-channel.ts`'s `CommandLifecycle` to echo which
919
+ * command a lifecycle frame is reporting on. The `_kindDriftGuard` below makes
920
+ * this fail to compile if it ever drifts from the `commandVariants` union, so
921
+ * the two stay in lockstep without duplicating the payload mapping. */
922
+ export const DaemonCommandKind = S.Literals([
923
+ "auth",
924
+ "connect",
925
+ "connect_device_code",
926
+ "cancel_connect",
927
+ "logout",
928
+ "submit_login_code",
929
+ "add_account",
930
+ "remove_account",
931
+ "pin_account",
932
+ "set_auto_update",
933
+ "refresh",
934
+ "status",
935
+ "update",
936
+ "bust_plan_cache",
937
+ "refresh_models",
938
+ "refresh_models_due",
939
+ "list_local_sessions",
940
+ "local_rescan",
941
+ "set_local_key",
942
+ "set_provider_key",
943
+ "set_team_key",
944
+ "delete_team_key",
945
+ "set_device_sessions",
946
+ ]);
947
+ type TDaemonCommandKindLiteral = S.Schema.Type<typeof DaemonCommandKind>;
948
+ // Bidirectional assignability assertion: the literal and the union's
949
+ // discriminant must be the SAME set. Adding a kind to `commandVariants` without
950
+ // adding it here (or vice-versa) breaks this line at compile time.
951
+ type _AssertSameKinds = [TDaemonCommandKind] extends [TDaemonCommandKindLiteral]
952
+ ? [TDaemonCommandKindLiteral] extends [TDaemonCommandKind]
953
+ ? true
954
+ : never
955
+ : never;
956
+ const _kindDriftGuard: _AssertSameKinds = true;
957
+ void _kindDriftGuard;
958
+
959
+ /** One control command delivered to the daemon over its relay socket.
960
+ * `id` is `daemon_commands.id` (bigserial), stringified for the wire. */
961
+ export const DaemonCommand = S.Union([
962
+ ...commandVariants({
963
+ id: S.String,
964
+ replay_session_id: S.optional(ReplaySessionId),
965
+ }),
966
+ ]);
967
+ export type TDaemonCommand = S.Schema.Type<typeof DaemonCommand>;
968
+
969
+ /** POST /api/daemon/cmd (dashboard → cloud) — enqueue for a target key
970
+ * (`key_id` must belong to the session user). */
971
+ export const DaemonCmdRequest = S.Union([
972
+ ...commandVariants({ key_id: S.String }),
973
+ ]);
974
+ export type TDaemonCmdRequest = S.Schema.Type<typeof DaemonCmdRequest>;
975
+
976
+ /** A command result the daemon reports back over its relay socket (the
977
+ * `ack`/`status` frames in `relay.ts` carry these). */
978
+ export const DaemonCommandAck = S.Struct({
979
+ id: S.String,
980
+ /** `ack` confirms that the daemon dequeued the command. Terminal outcomes
981
+ * retain the previous ack shape for older relay binaries. */
982
+ status: S.Literals(["ack", "done", "not_done", "error"]),
983
+ result: S.optional(S.Unknown),
984
+ });
985
+ export type TDaemonCommandAck = S.Schema.Type<typeof DaemonCommandAck>;
986
+
987
+ // ─── Daemon control surface (browser → daemon, on localhost) ─────────
988
+
989
+ /** Per-provider auth-status on the daemon wire.
990
+ * `connected` = signed in; `disconnected` = unexpected loss; `signed_out` =
991
+ * user-initiated logout (sticky until the next successful login). */
992
+ export const DaemonProviderAuthStatus = S.Literals([
993
+ "connected",
994
+ "disconnected",
995
+ "signed_out",
996
+ ]);
997
+ export type TDaemonProviderAuthStatus = S.Schema.Type<
998
+ typeof DaemonProviderAuthStatus
999
+ >;
1000
+
1001
+ /** Latest model-list outcome for a connected oauth provider (UI live signal). */
1002
+ export const DaemonModelsStatus = S.Literals(["ok", "unavailable"]);
1003
+ export type TDaemonModelsStatus = S.Schema.Type<typeof DaemonModelsStatus>;
1004
+
1005
+ /**
1006
+ * Closed reasons for `models_status: "unavailable"`. Matches the daemon's
1007
+ * listModels null tokens; unknown `http_*` collapses to `http_error` on the
1008
+ * wire. Never paths, bodies, or headers.
1009
+ */
1010
+ export const DaemonModelsReason = S.Literals([
1011
+ "token_unavailable",
1012
+ "version_unresolved",
1013
+ "empty_after_filter",
1014
+ "error",
1015
+ "http_401",
1016
+ "http_403",
1017
+ "http_404",
1018
+ "http_429",
1019
+ "http_500",
1020
+ "http_502",
1021
+ "http_503",
1022
+ "http_error",
1023
+ ]);
1024
+ export type TDaemonModelsReason = S.Schema.Type<typeof DaemonModelsReason>;
1025
+
1026
+ export const DaemonProviderConnection = S.Struct({
1027
+ provider: S.String,
1028
+ /**
1029
+ * Auth-status literal — the single source of truth.
1030
+ * `connected` = signed in; `disconnected` = unexpected loss;
1031
+ * `signed_out` = user-initiated logout (sticky until the next login).
1032
+ */
1033
+ status: DaemonProviderAuthStatus,
1034
+ /**
1035
+ * Typed observation. Optional so old daemons and persisted blobs remain
1036
+ * valid. When present it wins over legacy `status` / `detail` classifiers.
1037
+ * `unknown` is never logout and never proven serviceability.
1038
+ */
1039
+ observation: S.optional(DaemonProviderObservation),
1040
+ /** Machine-readable cause for a non-connected observation. Display copy stays on `detail`. */
1041
+ reason_code: S.optional(DaemonProviderReasonCode),
1042
+ /** The vendor CLI the daemon runs is installed on the machine. The daemon
1043
+ * never installs it — installs are user-run (the daemon install script or by
1044
+ * hand); the daemon lazily auto-links its isolated run-view
1045
+ * (~/.openllm/cli/<provider>/) to the host binary. When false the dashboard
1046
+ * prompts the user to (re-)run the daemon installer. Absent means a status
1047
+ * probe failed before it could determine installation state; consumers must
1048
+ * not treat absence as not installed. */
1049
+ cli_installed: S.optional(S.Boolean),
1050
+ /** Progress of an OpenLLM-started background vendor installer. Independent
1051
+ * of authentication and CLI presence; absent on older daemons or externally
1052
+ * managed installations. Contains no logs, process identity or host paths. */
1053
+ cli_install: S.optional(VendorCliInstall),
1054
+ /** Version of the isolated CLI, when installed + readable. */
1055
+ cli_version: S.optional(S.String),
1056
+ /** The user appears signed in to this vendor's CLI in their OWN home on the
1057
+ * daemon's machine (e.g. `~/.codex/auth.json` holds a ChatGPT login). A
1058
+ * read-only, secret-free presence hint so onboarding can put that provider
1059
+ * first with a one-tap Connect. It is never a connection: the daemon does
1060
+ * not copy, import or use that credential, and Connect still runs the
1061
+ * vendor login inside the daemon's isolated home. Absent = unknown (an
1062
+ * older daemon, a provider whose host store sits in an OS keychain the
1063
+ * daemon will not touch, or an unreadable store); consumers must not read
1064
+ * absence as signed out. */
1065
+ host_signed_in: S.optional(S.Boolean),
1066
+ detail: S.optional(S.String),
1067
+ last_login_at_ms: S.optional(S.NullOr(S.Number)),
1068
+ /** A LIVE device-code flow awaiting the user (codex/kimi on a remote box):
1069
+ * the verification URL + one-time code to surface so the dashboard can
1070
+ * render a synced "open this link, enter this code" panel. Present only
1071
+ * while a flow is pending; cleared the moment the credential lands. The
1072
+ * card flips to Connected automatically on the next status push.
1073
+ *
1074
+ * The actionable `url`/`code` are OPTIONAL because the relay REDACTS them
1075
+ * from the broadcast + persisted status for every dashboard EXCEPT the one
1076
+ * that started the login (issue #3 — otherwise the OAuth secret fans out to
1077
+ * every same-user browser). A redacted / marker snapshot is the non-secret
1078
+ * owner shape `{ pending: true, flow_id?, started_at_ms?, cancel_requested?,
1079
+ * mode? }` with no url/code — not a new `mode` value. The initiating
1080
+ * dashboard receives `{ url, code, mode? }` on `auth.login.prompt` only.
1081
+ * UIs must treat a missing/empty `url` as non-actionable (never auto-open).
1082
+ * A cached HTTP/DB marker is unconfirmed until a current-session ordered
1083
+ * live `status_push` is applied; TTL does not evict that live owner. */
1084
+ pending_auth: S.optional(
1085
+ S.NullOr(
1086
+ S.Struct({
1087
+ url: S.optional(S.String),
1088
+ code: S.optional(S.String),
1089
+ /** True on a REDACTED snapshot (non-origin watcher / persisted row):
1090
+ * a login is in progress but the actionable url/code were stripped. */
1091
+ pending: S.optional(S.Boolean),
1092
+ /** `device_code` (codex/kimi: surface URL + one-time code to enter in
1093
+ * the browser, then poll) or `paste_code` (claude headless login:
1094
+ * surface URL, then a paste-back input for the code the hosted
1095
+ * callback page displays). Absent ⇒ `device_code`. */
1096
+ mode: S.optional(S.Literals(["device_code", "paste_code"])),
1097
+ /** Relay command id of the login that produced this snapshot (same
1098
+ * value as `auth.login.*` `flow_id`). The browser `req_id` lives on
1099
+ * `command_lifecycle`, not here. Absent on daemons predating auth
1100
+ * events. */
1101
+ flow_id: S.optional(S.String),
1102
+ /** Epoch ms when this pending flow was created. Carried on both the
1103
+ * actionable and the REDACTED snapshot so every consumer can expire a
1104
+ * STALE entry (older than {@link PENDING_AUTH_TTL_MS}) without needing
1105
+ * the daemon to re-push. The daemon persists its whole status snapshot
1106
+ * to `api_key_activity.daemon_status_json`; an abandoned/never-completed
1107
+ * login (or a daemon restart that drops the live child) would otherwise
1108
+ * leave a dead `pending_auth` in that row forever, and the dashboard
1109
+ * would re-surface + auto-open a sign-in flow that no longer exists on
1110
+ * every cold load. Absent on daemons predating this field. */
1111
+ started_at_ms: S.optional(S.Number),
1112
+ /** Slot-derived: cancel was accepted but the owner is still
1113
+ * contained. Additive; older decoders ignore it. Not a new mode. */
1114
+ cancel_requested: S.optional(S.Boolean),
1115
+ }),
1116
+ ),
1117
+ ),
1118
+ /** Metadata-only usage snapshot for a CONNECTED provider, read locally by
1119
+ * the daemon and pushed with its status. Absent when not connected or the
1120
+ * read failed. */
1121
+ usage: S.optional(S.NullOr(ProviderUsageSnapshot)),
1122
+ /**
1123
+ * Live local hop cooldown with reason `auth` (any model of this provider).
1124
+ * Visibility only — does not change `status` / `observation` / `reason_code`.
1125
+ * Transient; not remembered as last-known.
1126
+ */
1127
+ upstream_auth_cooldown: S.optional(DaemonProviderUpstreamAuthCooldown),
1128
+ /** Obscured vendor-account identity for a CONNECTED provider:
1129
+ * sha256("openllm-account-v1:<provider>:<stable-account-id>") over the
1130
+ * stable account id the vendor CLI stores locally (Anthropic's
1131
+ * accountUuid, ChatGPT's account_id, Kimi's user_id, Grok's user_id).
1132
+ * Lets the cloud key usage-meter series per ACCOUNT — two devices on the
1133
+ * same account share the hash; a second account on the same provider gets
1134
+ * its own — without ever shipping the raw vendor id off-box. Absent when
1135
+ * not connected or unreadable, and on daemons predating it. See
1136
+ * docs/proposals/inferred-subscription-usage-calibration.md §10. */
1137
+ account_hash: S.optional(S.String),
1138
+ /** Device-local account slot this row describes (multi-account). Several
1139
+ * rows may share one `provider` with distinct indexes. Absent ⇒ 0. */
1140
+ account_index: S.optional(AccountIndex),
1141
+ /** User label for the account slot, when set. */
1142
+ account_label: S.optional(S.String.check(S.isMaxLength(64))),
1143
+ /** True on the slot the user pinned first in routing for this provider. */
1144
+ account_pinned: S.optional(S.Boolean),
1145
+ /** `local_key` slots only: the last four characters of the stored key, so
1146
+ * the user can tell keys apart. Never more of the secret. */
1147
+ key_hint: S.optional(S.String.check(S.isMaxLength(4))),
1148
+ /**
1149
+ * Latest live model-list / discover outcome for this provider (UI signal for
1150
+ * "Connected, but this device hasn't reported models yet"). Optional +
1151
+ * omitted when never attempted so older daemons and older clients stay
1152
+ * compatible. Mirror of how {@link LocalServerState} carries models.
1153
+ */
1154
+ models_status: S.optional(DaemonModelsStatus),
1155
+ /** Closed null-reason when `models_status` is `unavailable`. Omitted on `ok`. */
1156
+ models_reason: S.optional(DaemonModelsReason),
1157
+ });
1158
+ export type TDaemonProviderConnection = S.Schema.Type<
1159
+ typeof DaemonProviderConnection
1160
+ >;
1161
+
1162
+ /** `control_caps` entry: the daemon understands `account_index` on auth
1163
+ * commands and the `add_account` / `remove_account` / `pin_account` kinds.
1164
+ * Senders must not address account n >= 1 without it (old daemons strip the
1165
+ * field and would act on account 0). */
1166
+ export const MULTI_ACCOUNT_CONTROL_CAP = "multi_account";
1167
+ /** Control cap: the daemon runs the unified `auth` command (kind `"auth"`).
1168
+ * Older daemons drop an unknown kind silently; the browser must refuse with
1169
+ * `daemon_outdated` when this cap is absent rather than waiting out a timeout. */
1170
+ export const AUTH_CONTROL_CAP = "auth";
1171
+ /** Control cap: the daemon stores `local_key` provider keys
1172
+ * (`set_provider_key`) and reports each slot as a `connections` row. */
1173
+ export const LOCAL_KEY_PROVIDERS_CONTROL_CAP = "local_key_providers_v1";
1174
+ /** Control cap: the daemon executes the signed `set_device_sessions` disable. */
1175
+ export const DEVICE_SESSIONS_CONTROL_CAP = "device_sessions_v1";
1176
+ /** Control cap: the daemon holds team keys (`set_team_key` /
1177
+ * `delete_team_key`) and reports them in `team_psk`. */
1178
+ export const TEAM_KEY_CUSTODY_CONTROL_CAP = "team_key_custody_v1";
1179
+
1180
+ /** One team key this device holds — the epoch only, never the key. */
1181
+ export const DaemonTeamKeyEpoch = S.Struct({
1182
+ team_id: S.String,
1183
+ epoch: S.Int.check(S.isGreaterThanOrEqualTo(0)),
1184
+ });
1185
+ export type TDaemonTeamKeyEpoch = S.Schema.Type<typeof DaemonTeamKeyEpoch>;
1186
+
1187
+ /**
1188
+ * A `pending_auth` self-expires after this **on cached / unconfirmed
1189
+ * snapshots**. The login ceiling (`DEFAULT_LOGIN_TIMEOUT_MS`, 5 min) reaps
1190
+ * the live child and matching-flow finalization clears the marker; this TTL
1191
+ * is the BACKSTOP for abandoned HTTP/DB rows. A current-session live marker
1192
+ * beats its age — replacement Connect stays forbidden while ownership is
1193
+ * confirmed. Shared by the daemon (in-memory expiry) and the browser. */
1194
+ export const PENDING_AUTH_TTL_MS = 10 * 60_000;
1195
+
1196
+ // Outcome of the daemon's last cloud bootstrap — drives the dashboard's
1197
+ // Providers UI: needs a key (`no_key`/`invalid_key`) → show the API-key
1198
+ // picker; `unreachable` → retry hint; `connecting` → first bootstrap still
1199
+ // in flight (key is configured, outcome unknown); `ok` → provider cards.
1200
+ export const DaemonCloudState = S.Literals([
1201
+ "ok",
1202
+ "no_key",
1203
+ "invalid_key",
1204
+ "unreachable",
1205
+ "connecting",
1206
+ ]);
1207
+ export type TDaemonCloudState = S.Schema.Type<typeof DaemonCloudState>;
1208
+
1209
+ /**
1210
+ * The openllm CLI's presence on this box, as the daemon already knows it from
1211
+ * its device-state probe (`device-state.ts`) — no probe scripts, no per-client
1212
+ * walk. This is the ONLY install state the dashboard needs now: clients are
1213
+ * configured at RUN time by `openllm <client>`, so there is nothing per-client
1214
+ * to install, stamp, or diverge.
1215
+ */
1216
+ export const DaemonCliState = S.Struct({
1217
+ installed: S.Boolean,
1218
+ /** Version the installed binary reports; absent when it can't be read. */
1219
+ version: S.optional(S.NullOr(S.String)),
1220
+ });
1221
+ export type TDaemonCliState = S.Schema.Type<typeof DaemonCliState>;
1222
+
1223
+ /**
1224
+ * An update replacing the `openllm` binary right now — the body of the
1225
+ * cross-process update lease (`packages/cli/src/update-lease.ts`, which a
1226
+ * parity test pins to this shape). `source` is who is updating (`app` = the
1227
+ * desktop app), `received`/`total` the download bytes when known.
1228
+ */
1229
+ export const DaemonUpdateState = S.Struct({
1230
+ pid: S.Number,
1231
+ source: S.Literals(["daemon", "cli", "installer", "app"]),
1232
+ version: S.NullOr(S.String),
1233
+ phase: S.Literals(["download", "verify", "install", "restart"]),
1234
+ received: S.NullOr(S.Number),
1235
+ total: S.NullOr(S.Number),
1236
+ started_at: S.Number,
1237
+ updated_at: S.Number,
1238
+ });
1239
+ export type TDaemonUpdateState = S.Schema.Type<typeof DaemonUpdateState>;
1240
+
1241
+ // GET /status
1242
+ export const DaemonStatus = S.Struct({
1243
+ /** The RUNNING daemon's version. The dashboard shows this. */
1244
+ daemon_version: S.String,
1245
+ /** The installed binary's version on disk. One binary is both CLI and
1246
+ * daemon, and a swap whose daemon code is unchanged does not restart the
1247
+ * daemon, so this can be ahead of `daemon_version` until the next restart.
1248
+ * Absent on daemons too old to report it. */
1249
+ installed_version: S.optional(S.NullOr(S.String)),
1250
+ /** Whether an sk-llm key is set (the daemon installs keyless). */
1251
+ key_configured: S.Boolean,
1252
+ /** Whether automatic self-update is enabled (OPT-OUT, default on). Drives the
1253
+ * dashboard's auto-update switch; toggled via the `set_auto_update` command.
1254
+ * Absent on daemons too old to report it — those always self-updated, so the
1255
+ * switch then reads as on. See `packages/cli/daemon/src/auto-update-pref.ts`. */
1256
+ auto_update: S.optional(S.Boolean),
1257
+ /** Result of the last bootstrap — see `DaemonCloudState`. */
1258
+ cloud_state: DaemonCloudState,
1259
+ /** This daemon's X25519 public key (SPKI DER, base64). Lets ANOTHER of the
1260
+ * user's daemons SEAL a Claude setup-token to it for cross-machine copy
1261
+ * (`/api/daemon/relay-credential`) — the cloud only ever relays ciphertext.
1262
+ * Absent on daemons too old to publish one. */
1263
+ pubkey: S.optional(S.String),
1264
+ /** True when the cloud's immutable daemon X25519 pin differs from this
1265
+ * daemon's local key. A browser session must reset the pin before RTC can
1266
+ * connect; absent on daemons that have not observed this conflict. */
1267
+ identity_conflict: S.optional(S.Boolean),
1268
+ /** The device-control pin this daemon verifies grants against: `fp` is the
1269
+ * key's fingerprint (`keyFingerprint` in `@openllmsh/sdk/tunnel`), `via` the
1270
+ * path that set it. Whether it is agent-eligible is reported once, in
1271
+ * `device_sessions.anchored`. Absent when unpinned or on older daemons. */
1272
+ device_access_pin: S.optional(DeviceAccessPinReport),
1273
+ /** Device sessions readiness + the dpk proof (`DeviceSessionsReport`).
1274
+ * `anchored` == sessions on (env-file trust anchor present). Absent on
1275
+ * daemons too old to anchor — treat as not anchored. */
1276
+ device_sessions: S.optional(DeviceSessionsReport),
1277
+ /** The loopback port this daemon's `/v1/*` + `/whoami` surface listens on
1278
+ * (`OPENLLM_DAEMON_PORT`, default 8787). Reported in `daemon_status_json`
1279
+ * for display; routing never uses it (origin reaches devices over the
1280
+ * relay, not loopback). Absent on daemons too old to publish it. */
1281
+ port: S.optional(S.Number),
1282
+ /** The OS-sandbox posture this daemon booted with (`sandbox/landlock.ts`):
1283
+ * `enforced` (Landlock active), `off` (kill switch / dev opt-out),
1284
+ * `unsupported` (non-Linux, or a kernel without Landlock — the systemd
1285
+ * unit hardening may still confine the service), `error` (setup failed —
1286
+ * fail-open, surfaced so an unconfined daemon is visible, not silent).
1287
+ * Absent on daemons too old to report it. */
1288
+ sandbox: S.optional(S.Literals(["enforced", "off", "unsupported", "error"])),
1289
+ connections: S.Array(DaemonProviderConnection),
1290
+ /** Team keys this device holds for team tunnels' PSK handshake, so the
1291
+ * browser can tell which teams still need T sealed here. Absent on daemons
1292
+ * without `TEAM_KEY_CUSTODY_CONTROL_CAP`. */
1293
+ team_psk: S.optional(S.Array(DaemonTeamKeyEpoch)),
1294
+ /** The openllm CLI on this box. Absent on daemons too old to report it. */
1295
+ cli: S.optional(DaemonCliState),
1296
+ /** The update replacing the binary right now, or null when none is.
1297
+ * Absent on daemons too old to report it. */
1298
+ update: S.optional(S.NullOr(DaemonUpdateState)),
1299
+ /** Advertised transport capabilities, retained in fleet status telemetry. */
1300
+ caps: S.optional(S.Array(S.String)),
1301
+ /** Current and maximum concurrently-served tunneled requests. Optional for
1302
+ * older daemons; origin uses it only as an additive target-ranking signal. */
1303
+ served_tunnels: S.optional(
1304
+ S.Struct({
1305
+ active: S.Number,
1306
+ capacity: S.Number,
1307
+ }),
1308
+ ),
1309
+ /**
1310
+ * Control-plane capabilities this daemon implements (distinct from
1311
+ * mux/RTC `caps`). Open strings so a future daemon can advertise an
1312
+ * extra cap without the cloud rejecting the whole status. Optional so
1313
+ * older daemons omit it; the dashboard sends `refresh_models_due` only
1314
+ * when this array includes that exact literal. Command vocabulary stays
1315
+ * closed independently of this list.
1316
+ */
1317
+ control_caps: S.optional(S.Array(S.String)),
1318
+ /** Whether this daemon can host device chat sessions (PTY — POSIX only;
1319
+ * false on win32). Absent on daemons too old to report it — the
1320
+ * dashboard then hides the device variant for this box. */
1321
+ pty_supported: S.optional(S.Boolean),
1322
+ /** Live/dormant device sessions hosted on this box (feature §2.2) —
1323
+ * lets the dashboard mark which sessions can `attach` vs `continue`. */
1324
+ sessions: S.optional(
1325
+ S.Array(
1326
+ S.Struct({
1327
+ /** Local daemon session id; independent of the mux SessionId validator. */
1328
+ id: S.String.check(S.isMinLength(1), S.isMaxLength(128)),
1329
+ // Same closed vocabulary as the local `LocalSessionOpenPayload.cli`.
1330
+ cli: DeviceSessionCli,
1331
+ started_at_ms: S.Number,
1332
+ /** A consumer channel is currently bound. */
1333
+ attached: S.Boolean,
1334
+ /** The PTY is still running (attach re-binds; false → continue). */
1335
+ live: S.Boolean,
1336
+ /** Best-effort process-tree activity signal for dormant sessions. */
1337
+ busy: S.optional(S.Boolean),
1338
+ /** User-visible session label, bounded for presence snapshots. */
1339
+ title: S.optional(SessionTitleField),
1340
+ /** Terminal reason retained for a dead resumable session. */
1341
+ last_exit_reason: S.optional(SessionExitReason),
1342
+ /** Vendor resume id when known (local history / resume spawn). */
1343
+ vendor_session_id: S.optional(
1344
+ S.NullOr(S.String.check(S.isMaxLength(128))),
1345
+ ),
1346
+ }),
1347
+ ).check(S.isMaxLength(32)),
1348
+ ),
1349
+ /**
1350
+ * Local model servers discovered on this device (no key material —
1351
+ * `has_key` only). Absent on daemons too old to probe. Bounded so a
1352
+ * noisy scan cannot bloat fleet status.
1353
+ */
1354
+ local_servers: S.optional(S.Array(LocalServerState).check(S.isMaxLength(64))),
1355
+ });
1356
+ export type TDaemonStatus = S.Schema.Type<typeof DaemonStatus>;
1357
+
1358
+ /**
1359
+ * Canonical payload the cloud HMAC-signs for a daemon plan
1360
+ * (`/api/daemon/plan`), and the daemon re-derives to verify it. Order +
1361
+ * separators are load-bearing — both sides MUST assemble it identically, so
1362
+ * it lives here, shared. Covers: the ordered `plan` (provider/model ids), the
1363
+ * parallel `pmids` (concrete upstream `provider_model_id`s, so the daemon
1364
+ * serves catalog-free), and the `origin` (the deployment that issued the
1365
+ * plan, so the daemon forwards +
1366
+ * records back to it). Signing the lot makes the upstream ids and the
1367
+ * forward/record target tamper-evident.
1368
+ */
1369
+ export const daemonPlanSigningPayload = (
1370
+ plan: string,
1371
+ providerModelIds: string,
1372
+ origin: string,
1373
+ contextOverflowStrategy?: TContextOverflowStrategy | null,
1374
+ holdNonce?: string | null,
1375
+ maxOutputTokens?: number | null,
1376
+ ): string => {
1377
+ if (holdNonce != null && !HOLD_NONCE_PATTERN.test(holdNonce)) {
1378
+ throw new Error("Invalid hold nonce");
1379
+ }
1380
+ if (
1381
+ maxOutputTokens != null &&
1382
+ (!Number.isInteger(maxOutputTokens) || maxOutputTokens <= 0)
1383
+ ) {
1384
+ throw new Error("Invalid max output tokens");
1385
+ }
1386
+ const base =
1387
+ contextOverflowStrategy === undefined || contextOverflowStrategy === null
1388
+ ? `${plan}\n${providerModelIds}\n${origin}`
1389
+ : `${plan}\n${providerModelIds}\n${origin}\n${contextOverflowStrategy}`;
1390
+ // A capped key's one-hop plan binds its cap hold. The `hold:` prefix can't
1391
+ // collide with a strategy line, which is always a fixed literal.
1392
+ const held =
1393
+ holdNonce === undefined || holdNonce === null
1394
+ ? base
1395
+ : `${base}\nhold:${holdNonce}`;
1396
+ // The output budget only rides a held plan; `out:` can't collide either.
1397
+ return maxOutputTokens === undefined || maxOutputTokens === null
1398
+ ? held
1399
+ : `${held}\nout:${maxOutputTokens}`;
1400
+ };
1401
+
1402
+ // ─── GET /api/daemon/plan (daemon → cloud) ───────────────────────────
1403
+ //
1404
+ // The local-first gateway's plan fetch: the signed plan tuple, returned as
1405
+ // JSON so a daemon serving a DIRECT client request can obtain a plan without
1406
+ // the request body transiting the cloud. The daemon verifies `sig` with the
1407
+ // bootstrap-delivered per-user key (`planSignatureOk`) before caching or
1408
+ // executing. See
1409
+ // `docs/proposals/local-first-gateway.md` §4.1. For capped keys, repeated
1410
+ // `exclude=<model>` query parameters skip already-failed hops; uncapped keys
1411
+ // ignore them.
1412
+ export const DaemonPlanResponse = S.Struct({
1413
+ /** Comma-joined ordered `provider/model` chain. */
1414
+ plan: S.String,
1415
+ /** Parallel concrete `provider_model_id`s. */
1416
+ pmids: S.String,
1417
+ /** The issuing deployment's origin. */
1418
+ origin: S.String,
1419
+ /** Context-overflow strategy for this plan. Absent means hop-to-larger-context. */
1420
+ context_overflow_strategy: S.optional(ContextOverflowStrategy),
1421
+ /** Reservation for a capped one-hop plan, included in the signed payload. */
1422
+ hold_nonce: S.optional(HoldNonce),
1423
+ /** Largest output the hold allows (held plans only; signed). The daemon
1424
+ * lowers the request's output limit to it before dispatch. */
1425
+ max_output_tokens: S.optional(S.Number.check(S.isInt(), S.isGreaterThan(0))),
1426
+ /** Revision of the key's access policy this plan was built under; a
1427
+ * change drops the daemon's plan cache (see bootstrap `key_policy_rev`).
1428
+ * Optional so a plan from a cloud that predates it still decodes; absent
1429
+ * keeps the revision the daemon already knows. */
1430
+ policy_rev: S.optional(S.String),
1431
+ /** HMAC over the canonical payload; null when the cloud has no signing
1432
+ * secret configured (dev) — the daemon then treats it as unsigned. */
1433
+ sig: S.NullOr(S.String),
1434
+ });
1435
+ export type TDaemonPlanResponse = S.Schema.Type<typeof DaemonPlanResponse>;
1436
+
1437
+ /** Header that carries the opaque held-tool continuation between client turns. */
1438
+ export const TOOL_SESSION_HEADER = "x-openllm-tool-session";
1439
+
1440
+ /** Headers the daemon stamps on EVERY cloud control call (poll/status/bootstrap
1441
+ * /requests/relay/search) so the cloud can record which device a key's daemon
1442
+ * runs on — `api_key_activity.device_id`/`device_label`. The id is the daemon's
1443
+ * stable opaque per-machine UUID (`OPENLLM_DEVICE_ID` in `~/.openllm/.env`); the label is the
1444
+ * host's `os.hostname()` for the dashboard to show. Both metadata-only (no
1445
+ * token, no content). Lets the dashboard tell two daemons behind one NAT apart
1446
+ * — device code + IP, not IP alone. See
1447
+ * `docs/proposals/daemon-device-aware-this-machine.md`. */
1448
+ export const DAEMON_DEVICE_ID_HEADER = "x-openllm-device-id";
1449
+ export const DAEMON_DEVICE_LABEL_HEADER = "x-openllm-device-label";
1450
+
1451
+ /**
1452
+ * Optional OS platform the daemon reports on control-plane calls
1453
+ * (`process.platform`: `darwin` / `linux` / `win32` / `freebsd` /
1454
+ * `openbsd` / `android` / `aix` / `sunos`). Metadata only —
1455
+ * used for `daemon_connected` analytics. Absent on older binaries.
1456
+ */
1457
+ export const DAEMON_PLATFORM_HEADER = "x-openllm-platform";
1458
+
1459
+ /**
1460
+ * Header a daemon sends on control-plane calls (chiefly
1461
+ * `GET /api/daemon/bootstrap`) listing the open-vocabulary decode
1462
+ * capabilities it supports — e.g. `MODEL_CAPABILITIES_OPEN_CAP` from
1463
+ * `./models`. Comma-joined; absent/empty on an old compiled daemon, which
1464
+ * the bootstrap encoder MUST treat as "closed literal decoder only" —
1465
+ * never inferred from a version string, which an unbumped daemon build
1466
+ * would leave stale.
1467
+ */
1468
+ export const DAEMON_BOOTSTRAP_CAPS_HEADER = "x-openllm-daemon-caps";
1469
+
1470
+ /**
1471
+ * Parse the comma-joined {@link DAEMON_BOOTSTRAP_CAPS_HEADER} value into a
1472
+ * capability list. A null/empty header (old daemon, or the header simply
1473
+ * absent) decodes to an empty list — no negotiated capability.
1474
+ */
1475
+ export const parseDaemonBootstrapCapsHeader = (
1476
+ value: string | null,
1477
+ ): string[] =>
1478
+ value === null || value.trim() === ""
1479
+ ? []
1480
+ : value
1481
+ .split(",")
1482
+ .map((c) => c.trim())
1483
+ .filter((c) => c.length > 0);
1484
+
1485
+ // POST /config/api-key — set/update the daemon's sk-llm key after install.
1486
+ export const DaemonSetApiKeyRequest = S.Struct({
1487
+ api_key: S.String,
1488
+ });
1489
+ export type TDaemonSetApiKeyRequest = S.Schema.Type<
1490
+ typeof DaemonSetApiKeyRequest
1491
+ >;
1492
+
1493
+ export const DaemonSetApiKeyResponse = S.Struct({
1494
+ key_configured: S.Boolean,
1495
+ cloud_state: DaemonCloudState,
1496
+ });
1497
+ export type TDaemonSetApiKeyResponse = S.Schema.Type<
1498
+ typeof DaemonSetApiKeyResponse
1499
+ >;
1500
+
1501
+ // POST /connect/:slug
1502
+ export const DaemonConnectResponse = S.Struct({
1503
+ provider: S.String,
1504
+ connected: S.Boolean,
1505
+ detail: S.optional(S.String),
1506
+ /**
1507
+ * True when `connect` kicked off an async flow that hasn't finished yet
1508
+ * (Kimi's device-code login: browser opened, daemon polling in the
1509
+ * background). `detail` is then INFORMATIONAL guidance, not an error —
1510
+ * the UI renders it neutrally and the status stream flips to connected
1511
+ * when the flow completes. Absent/false on terminal results.
1512
+ */
1513
+ pending: S.optional(S.Boolean),
1514
+ });
1515
+ export type TDaemonConnectResponse = S.Schema.Type<
1516
+ typeof DaemonConnectResponse
1517
+ >;
1518
+
1519
+ // GET /usage/:slug — reuses the existing snapshot shape verbatim.
1520
+ export const DaemonUsageResponse = S.Struct({
1521
+ provider: S.String,
1522
+ snapshot: ProviderUsageSnapshot,
1523
+ });
1524
+ export type TDaemonUsageResponse = S.Schema.Type<typeof DaemonUsageResponse>;