@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,66 @@
1
+ import type {
2
+ TDefaultChainClass,
3
+ TExtendedModel,
4
+ TModelCapability,
5
+ } from "./models";
6
+ import { MEDIA_DEFAULT_CLASS } from "./models";
7
+
8
+ /**
9
+ * Shared catalog default-chain ranking. Browser-safe (no DB/HTTP).
10
+ * Trail: host-paid included models (`included_usage`) come LAST in every
11
+ * chain they belong to — a user's own providers are tried first, and a
12
+ * fresh user with none still lands on what OpenLLM gives them.
13
+ * Primary: `tier_rank` ascending — the provider bands (subscriptions
14
+ * 10–79, free-tier APIs 100–199, metered APIs 200+).
15
+ * Tie-break: index of `chainClass` in `default_tiers`, then catalog order.
16
+ */
17
+ export type TDefaultChainRankable = Pick<
18
+ TExtendedModel,
19
+ | "default_tiers"
20
+ | "tier_rank"
21
+ | "capabilities"
22
+ | "deprecated"
23
+ | "provider"
24
+ | "included_usage"
25
+ >;
26
+
27
+ export const compareDefaultChainMembers = (
28
+ a: TDefaultChainRankable,
29
+ b: TDefaultChainRankable,
30
+ chainClass: TDefaultChainClass,
31
+ ): number => {
32
+ const trailA = a.included_usage === undefined ? 0 : 1;
33
+ const trailB = b.included_usage === undefined ? 0 : 1;
34
+ if (trailA !== trailB) return trailA - trailB;
35
+ const rankA = a.tier_rank ?? Number.MAX_SAFE_INTEGER;
36
+ const rankB = b.tier_rank ?? Number.MAX_SAFE_INTEGER;
37
+ if (rankA !== rankB) return rankA - rankB;
38
+ return (
39
+ (a.default_tiers?.indexOf(chainClass) ?? Number.MAX_SAFE_INTEGER) -
40
+ (b.default_tiers?.indexOf(chainClass) ?? Number.MAX_SAFE_INTEGER)
41
+ );
42
+ };
43
+
44
+ export const orderDefaultChainMembers = <T extends TDefaultChainRankable>(
45
+ catalog: ReadonlyArray<T>,
46
+ available: ReadonlySet<string> | undefined,
47
+ chainClass: TDefaultChainClass,
48
+ capability: TModelCapability,
49
+ ): ReadonlyArray<T> =>
50
+ catalog
51
+ .filter(
52
+ (m) =>
53
+ (m.default_tiers?.includes(chainClass) ?? false) &&
54
+ m.capabilities.includes(capability) &&
55
+ m.deprecated !== true &&
56
+ (available === undefined || available.has(m.provider)),
57
+ )
58
+ .sort((a, b) => compareDefaultChainMembers(a, b, chainClass));
59
+
60
+ /** Ordered catalog media defaults for one capability. Empty if none qualify. */
61
+ export const deriveMediaDefaultModels = (
62
+ catalog: ReadonlyArray<TExtendedModel>,
63
+ available: ReadonlySet<string>,
64
+ capability: TModelCapability,
65
+ ): ReadonlyArray<TExtendedModel> =>
66
+ orderDefaultChainMembers(catalog, available, MEDIA_DEFAULT_CLASS, capability);
@@ -0,0 +1,85 @@
1
+ import { Schema as S } from "effect";
2
+ import {
3
+ DaemonCliState,
4
+ DaemonCloudState,
5
+ DaemonProviderConnection,
6
+ } from "./daemon";
7
+
8
+ // ─── Device state — the daemon's live, manifest-derived snapshot ─────
9
+ //
10
+ // The daemon is the source of truth for what's on the box. This snapshot is
11
+ // read LIVE through the relay and never persisted cloud-side: a dashboard with
12
+ // no live daemon socket shows offline, which is the truth.
13
+ //
14
+ // It no longer carries a per-integration `items` array: clients are configured
15
+ // at RUN time by `openllm <client>`, so there is nothing installed per client to
16
+ // probe. The only install state left is `cli` — which the daemon already knows
17
+ // from its auto-update loop, with no probe scripts to run. See
18
+ // `docs/proposals/remove-registry-runtime-config-merge.md`.
19
+
20
+ export type {
21
+ TDaemonCliState,
22
+ TDaemonCloudState,
23
+ TDaemonProviderConnection,
24
+ } from "./daemon";
25
+ // Re-export the pieces device-state composes so the contract imports from one
26
+ // module.
27
+ export {
28
+ DaemonCliState,
29
+ DaemonCloudState,
30
+ DaemonProviderConnection,
31
+ } from "./daemon";
32
+
33
+ /**
34
+ * The full device snapshot — daemon self + subscription providers + the openllm
35
+ * CLI's presence. Supersedes `DaemonStatus`: `connections` keeps the
36
+ * per-provider shape.
37
+ */
38
+ export const DeviceState = S.Struct({
39
+ daemon_version: S.String,
40
+ /** Whether an sk-llm key is set (the daemon installs keyless). */
41
+ key_configured: S.Boolean,
42
+ /** Auto-update opt-in (default on). Absent on daemons too old to report it. */
43
+ auto_update: S.optional(S.Boolean),
44
+ /** Result of the last cloud bootstrap — drives the 3-state Providers UI. */
45
+ cloud_state: DaemonCloudState,
46
+ /** The OS-sandbox posture this daemon booted with. */
47
+ sandbox: S.optional(S.Literals(["enforced", "off", "unsupported", "error"])),
48
+ /** Loopback port for this daemon's `/v1/*` + `/whoami` surface. */
49
+ port: S.optional(S.Number),
50
+ /** This daemon's X25519 public key (SPKI DER, base64) for cross-machine seal. */
51
+ pubkey: S.optional(S.String),
52
+ /** Subscription-provider connections (claude_code/chatgpt/kimi_code). */
53
+ connections: S.Array(DaemonProviderConnection),
54
+ /** The openllm CLI on this box (from the daemon's auto-update loop). */
55
+ cli: S.optional(DaemonCliState),
56
+ });
57
+ export type TDeviceState = S.Schema.Type<typeof DeviceState>;
58
+
59
+ // ─── New relay → watcher frame (stateless-relay transport) ───────────
60
+ //
61
+ // Supersedes the old `status_push` + `presence` frames: presence is encoded by
62
+ // `online`, the snapshot by `device_state` (present iff online). Defined
63
+ // additively; the full `RelayFrame` union swap happens with the Phase 3 relay
64
+ // rewrite.
65
+
66
+ /** relay → watcher. A key's daemon presence and/or device-state changed. The
67
+ * `online`/`device_state` invariant is encoded structurally: `online:true`
68
+ * ALWAYS carries a `device_state`; `online:false` is the offline flip (the
69
+ * relay holds no socket for the key) and never carries one. */
70
+ export const RelayDeviceStateFrame = S.Union([
71
+ S.Struct({
72
+ type: S.Literal("device_state"),
73
+ key_id: S.String,
74
+ online: S.Literal(true),
75
+ device_state: DeviceState,
76
+ }),
77
+ S.Struct({
78
+ type: S.Literal("device_state"),
79
+ key_id: S.String,
80
+ online: S.Literal(false),
81
+ }),
82
+ ]);
83
+ export type TRelayDeviceStateFrame = S.Schema.Type<
84
+ typeof RelayDeviceStateFrame
85
+ >;
@@ -0,0 +1,443 @@
1
+ import { Schema as S } from "effect";
2
+ import {
3
+ DOCTOR_EPOCH_MS_MAX,
4
+ DOCTOR_OPAQUE_ID_PATTERN,
5
+ DOCTOR_REPORT_MAX_EVENTS,
6
+ DOCTOR_REPORT_SCHEMA_VERSION,
7
+ DOCTOR_SCOPE_HASH_PREFIX,
8
+ DOCTOR_VERSION_STAMP_PATTERN,
9
+ EpochMs,
10
+ OpaqueId,
11
+ STRICT_DOCTOR_PARSE,
12
+ VersionStamp,
13
+ } from "./doctor-report";
14
+ import {
15
+ DAEMON_DIAGNOSTICS_OPT_IN_EXTRA_KEY,
16
+ DAEMON_DIAGNOSTICS_POLICY_GENERATION_EXTRA_KEY,
17
+ DAEMON_DIAGNOSTICS_PREFERENCE_PATH,
18
+ DAEMON_DOCTOR_REPORTS_PATH,
19
+ DOCTOR_REPORT_DEBOUNCE_MS,
20
+ DOCTOR_REPORT_LEASE_MS,
21
+ DOCTOR_REPORT_MAX_BACKOFF_MS,
22
+ DOCTOR_REPORT_MAX_BODY_BYTES,
23
+ DOCTOR_REPORT_MAX_IN_FLIGHT,
24
+ DOCTOR_REPORT_MAX_SPOOL_BYTES,
25
+ DOCTOR_REPORT_PENDING_TTL_MS,
26
+ DOCTOR_REPORTING_POLICY_TTL_MS,
27
+ } from "./doctor-report-policy";
28
+
29
+ /**
30
+ * CLI-only localhost control surface for doctor reporting. Not a browser
31
+ * loopback API. Paths, capability filename and local opt-out filename are
32
+ * constants so the CLI generator can emit them without duplicating schemas.
33
+ */
34
+
35
+ export const DOCTOR_LOCAL_REPORT_PATH = "/doctor/report" as const;
36
+ export const DOCTOR_LOCAL_STATUS_PATH = "/doctor/reporting-status" as const;
37
+ export const DOCTOR_LOCAL_PREFERENCE_PATH = "/doctor/local-preference" as const;
38
+
39
+ /** Owner-only capability file basename under the install data dir. */
40
+ export const DOCTOR_LOCAL_CAPABILITY_FILENAME =
41
+ "doctor-report.capability" as const;
42
+
43
+ /** HTTP header the CLI presents from the capability file (not a cookie). */
44
+ export const DOCTOR_LOCAL_CAPABILITY_HEADER =
45
+ "x-openllm-doctor-capability" as const;
46
+
47
+ /** Shared local opt-out / pending-sync record basename. */
48
+ export const DOCTOR_LOCAL_OPT_OUT_FILENAME =
49
+ "doctor-report.local.json" as const;
50
+
51
+ export const DoctorLocalReportRequest = S.Struct({
52
+ dry_run: S.optional(S.Boolean),
53
+ reporter_cli_version: S.optional(VersionStamp),
54
+ });
55
+ export type TDoctorLocalReportRequest = S.Schema.Type<
56
+ typeof DoctorLocalReportRequest
57
+ >;
58
+
59
+ export const DOCTOR_LOCAL_UNAVAILABLE_REASONS = [
60
+ "daemon_stopped",
61
+ "upgrade_required",
62
+ "capability_missing",
63
+ ] as const;
64
+
65
+ export const DoctorLocalUnavailableReason = S.Literals([
66
+ ...DOCTOR_LOCAL_UNAVAILABLE_REASONS,
67
+ ]);
68
+ export type TDoctorLocalUnavailableReason = S.Schema.Type<
69
+ typeof DoctorLocalUnavailableReason
70
+ >;
71
+
72
+ export const DoctorLocalReportResult = S.Struct({
73
+ nothing_new: S.Boolean,
74
+ dry_run: S.Boolean,
75
+ report_id: S.optional(OpaqueId),
76
+ accepted_count: S.Number.check(
77
+ S.isFinite(),
78
+ S.isInt(),
79
+ S.isGreaterThanOrEqualTo(0),
80
+ ),
81
+ skipped_count: S.Number.check(
82
+ S.isFinite(),
83
+ S.isInt(),
84
+ S.isGreaterThanOrEqualTo(0),
85
+ ),
86
+ gap_count: S.Number.check(
87
+ S.isFinite(),
88
+ S.isInt(),
89
+ S.isGreaterThanOrEqualTo(0),
90
+ ),
91
+ legacy_records_skipped: S.Number.check(
92
+ S.isFinite(),
93
+ S.isInt(),
94
+ S.isGreaterThanOrEqualTo(0),
95
+ ),
96
+ daemon_versions: S.Array(VersionStamp).check(S.isMaxLength(16)),
97
+ pending: S.Boolean,
98
+ unavailable_reason: S.optional(DoctorLocalUnavailableReason),
99
+ });
100
+ export type TDoctorLocalReportResult = S.Schema.Type<
101
+ typeof DoctorLocalReportResult
102
+ >;
103
+
104
+ export const DoctorLocalPreference = S.Struct({
105
+ enabled: S.Boolean,
106
+ pending_account_sync: S.Boolean,
107
+ /** Hash/UUID of the configured origin — never a URL. */
108
+ origin_scope: S.optional(OpaqueId),
109
+ /** Hash/UUID of the account/key — never a credential. */
110
+ account_scope: S.optional(OpaqueId),
111
+ /** Consent generation fence (UUID/hex). */
112
+ generation: S.optional(OpaqueId),
113
+ });
114
+ export type TDoctorLocalPreference = S.Schema.Type<
115
+ typeof DoctorLocalPreference
116
+ >;
117
+
118
+ export const DOCTOR_UPLOAD_BLOCKERS = [
119
+ "development_environment",
120
+ "missing_key",
121
+ "inactive_policy",
122
+ "expired_policy",
123
+ "local_opt_out",
124
+ "cloud_suspended",
125
+ "cloud_revoked",
126
+ ] as const;
127
+
128
+ export const DoctorUploadBlocker = S.Literals(DOCTOR_UPLOAD_BLOCKERS);
129
+ export type TDoctorUploadBlocker = S.Schema.Type<typeof DoctorUploadBlocker>;
130
+
131
+ export const DOCTOR_UPLOAD_ATTEMPT_OUTCOMES = [
132
+ "uploaded",
133
+ "retry",
134
+ "rejected",
135
+ "stopped",
136
+ "error",
137
+ ] as const;
138
+
139
+ export const DoctorUploadAttemptOutcome = S.Literals([
140
+ ...DOCTOR_UPLOAD_ATTEMPT_OUTCOMES,
141
+ ]);
142
+ export type TDoctorUploadAttemptOutcome = S.Schema.Type<
143
+ typeof DoctorUploadAttemptOutcome
144
+ >;
145
+
146
+ export const DoctorReportingStatus = S.Struct({
147
+ local_enabled: S.Boolean,
148
+ account_enabled: S.Boolean,
149
+ pending_account_sync: S.Boolean,
150
+ last_acknowledged_report_id: S.optional(OpaqueId),
151
+ daemon_version: S.optional(VersionStamp),
152
+ unavailable_reason: S.optional(DoctorLocalUnavailableReason),
153
+ /** Absent on older daemons — treat as unknown, not false. */
154
+ upload_eligible: S.optional(S.Boolean),
155
+ upload_blocker: S.optional(DoctorUploadBlocker),
156
+ pending_report_upload: S.optional(S.Boolean),
157
+ last_attempt_at_ms: S.optional(EpochMs),
158
+ last_attempt_outcome: S.optional(DoctorUploadAttemptOutcome),
159
+ });
160
+ export type TDoctorReportingStatus = S.Schema.Type<
161
+ typeof DoctorReportingStatus
162
+ >;
163
+
164
+ export const parseDoctorLocalReportRequest = (
165
+ input: unknown,
166
+ ): TDoctorLocalReportRequest => {
167
+ const decoded = S.decodeUnknownSync(DoctorLocalReportRequest)(
168
+ input,
169
+ STRICT_DOCTOR_PARSE,
170
+ );
171
+ return { ...decoded, dry_run: decoded.dry_run ?? false };
172
+ };
173
+
174
+ export const parseDoctorLocalReportResult = (
175
+ input: unknown,
176
+ ): TDoctorLocalReportResult =>
177
+ S.decodeUnknownSync(DoctorLocalReportResult)(input, STRICT_DOCTOR_PARSE);
178
+
179
+ export const parseDoctorLocalPreference = (
180
+ input: unknown,
181
+ ): TDoctorLocalPreference =>
182
+ S.decodeUnknownSync(DoctorLocalPreference)(input, STRICT_DOCTOR_PARSE);
183
+
184
+ export const parseDoctorReportingStatus = (
185
+ input: unknown,
186
+ ): TDoctorReportingStatus =>
187
+ S.decodeUnknownSync(DoctorReportingStatus)(input, STRICT_DOCTOR_PARSE);
188
+
189
+ /**
190
+ * Flat constants the CLI generator copies into a committed artifact.
191
+ * Do not hand-duplicate these in CLI source.
192
+ */
193
+ export const DOCTOR_REPORT_CLI_CONSTANTS = {
194
+ schemaVersion: DOCTOR_REPORT_SCHEMA_VERSION,
195
+ extraKey: DAEMON_DIAGNOSTICS_OPT_IN_EXTRA_KEY,
196
+ policyGenerationExtraKey: DAEMON_DIAGNOSTICS_POLICY_GENERATION_EXTRA_KEY,
197
+ cloudReportsPath: DAEMON_DOCTOR_REPORTS_PATH,
198
+ cloudPreferencePath: DAEMON_DIAGNOSTICS_PREFERENCE_PATH,
199
+ localReportPath: DOCTOR_LOCAL_REPORT_PATH,
200
+ localStatusPath: DOCTOR_LOCAL_STATUS_PATH,
201
+ localPreferencePath: DOCTOR_LOCAL_PREFERENCE_PATH,
202
+ capabilityFilename: DOCTOR_LOCAL_CAPABILITY_FILENAME,
203
+ capabilityHeader: DOCTOR_LOCAL_CAPABILITY_HEADER,
204
+ localOptOutFilename: DOCTOR_LOCAL_OPT_OUT_FILENAME,
205
+ maxEvents: DOCTOR_REPORT_MAX_EVENTS,
206
+ maxBodyBytes: DOCTOR_REPORT_MAX_BODY_BYTES,
207
+ maxSpoolBytes: DOCTOR_REPORT_MAX_SPOOL_BYTES,
208
+ pendingTtlMs: DOCTOR_REPORT_PENDING_TTL_MS,
209
+ debounceMs: DOCTOR_REPORT_DEBOUNCE_MS,
210
+ maxBackoffMs: DOCTOR_REPORT_MAX_BACKOFF_MS,
211
+ maxInFlight: DOCTOR_REPORT_MAX_IN_FLIGHT,
212
+ leaseMs: DOCTOR_REPORT_LEASE_MS,
213
+ reportingPolicyTtlMs: DOCTOR_REPORTING_POLICY_TTL_MS,
214
+ scopeHashPrefix: DOCTOR_SCOPE_HASH_PREFIX,
215
+ uploadBlockers: DOCTOR_UPLOAD_BLOCKERS,
216
+ uploadAttemptOutcomes: DOCTOR_UPLOAD_ATTEMPT_OUTCOMES,
217
+ } as const;
218
+
219
+ export type TDoctorReportCliConstants = typeof DOCTOR_REPORT_CLI_CONSTANTS;
220
+
221
+ /** Render the committed CLI artifact. Generator-only; CLI runtime stays
222
+ * workspace-free by checking in the output later. */
223
+ export const renderDoctorReportCliArtifact = (): string =>
224
+ `// AUTOGENERATED from protocol doctor-report contracts — DO NOT EDIT BY HAND.
225
+ // Regenerate via packages/sdk/protocol/doctor-report-local.ts#renderDoctorReportCliArtifact
226
+ // (scripts/generate-sdk-openapi.ts calls this when regenerating CLI artifacts).
227
+
228
+ import { createHash } from ${JSON.stringify("node:crypto")};
229
+
230
+ export const DOCTOR_REPORT_CLI_CONSTANTS = ${JSON.stringify(
231
+ DOCTOR_REPORT_CLI_CONSTANTS,
232
+ null,
233
+ 2,
234
+ )} as const;
235
+
236
+ export type TDoctorReportCliConstants = typeof DOCTOR_REPORT_CLI_CONSTANTS;
237
+
238
+ export const opaqueDoctorScope = (
239
+ label: "origin" | "account",
240
+ value: string,
241
+ ): string =>
242
+ createHash("sha256")
243
+ .update(\`\${DOCTOR_REPORT_CLI_CONSTANTS.scopeHashPrefix}:\${label}:\${value}\`)
244
+ .digest("hex")
245
+ .slice(0, 32);
246
+
247
+ export const DOCTOR_OPAQUE_ID_PATTERN = /${DOCTOR_OPAQUE_ID_PATTERN.source}/;
248
+ const OPAQUE_ID = DOCTOR_OPAQUE_ID_PATTERN;
249
+ const VERSION_STAMP = /${DOCTOR_VERSION_STAMP_PATTERN.source}/;
250
+ const UNAVAILABLE = ${JSON.stringify(DOCTOR_LOCAL_UNAVAILABLE_REASONS)} as const;
251
+
252
+ export type TDoctorLocalUnavailableReason = (typeof UNAVAILABLE)[number];
253
+
254
+ export type TDoctorLocalReportResult = {
255
+ readonly nothing_new: boolean;
256
+ readonly dry_run: boolean;
257
+ readonly report_id?: string;
258
+ readonly accepted_count: number;
259
+ readonly skipped_count: number;
260
+ readonly gap_count: number;
261
+ readonly legacy_records_skipped: number;
262
+ readonly daemon_versions: readonly string[];
263
+ readonly pending: boolean;
264
+ readonly unavailable_reason?: TDoctorLocalUnavailableReason;
265
+ };
266
+
267
+ const UPLOAD_BLOCKERS = DOCTOR_REPORT_CLI_CONSTANTS.uploadBlockers;
268
+ const ATTEMPT_OUTCOMES = DOCTOR_REPORT_CLI_CONSTANTS.uploadAttemptOutcomes;
269
+ const EPOCH_MS_MAX = ${DOCTOR_EPOCH_MS_MAX};
270
+
271
+ export type TDoctorUploadBlocker = (typeof UPLOAD_BLOCKERS)[number];
272
+ export type TDoctorUploadAttemptOutcome = (typeof ATTEMPT_OUTCOMES)[number];
273
+
274
+ export type TDoctorReportingStatus = {
275
+ readonly local_enabled: boolean;
276
+ readonly account_enabled: boolean;
277
+ readonly pending_account_sync: boolean;
278
+ readonly last_acknowledged_report_id?: string;
279
+ readonly daemon_version?: string;
280
+ readonly unavailable_reason?: TDoctorLocalUnavailableReason;
281
+ readonly upload_eligible?: boolean;
282
+ readonly upload_blocker?: TDoctorUploadBlocker;
283
+ readonly pending_report_upload?: boolean;
284
+ readonly last_attempt_at_ms?: number;
285
+ readonly last_attempt_outcome?: TDoctorUploadAttemptOutcome;
286
+ };
287
+
288
+ const fail = (message: string): never => {
289
+ throw new Error(message);
290
+ };
291
+
292
+ const isRecord = (input: unknown): input is Record<string, unknown> =>
293
+ typeof input === "object" && input !== null && !Array.isArray(input);
294
+
295
+ const bool = (input: Record<string, unknown>, key: string): boolean => {
296
+ const value = input[key];
297
+ return typeof value === "boolean" ? value : fail(\`invalid \${key}\`);
298
+ };
299
+
300
+ const nonNegInt = (input: Record<string, unknown>, key: string): number => {
301
+ const value = input[key];
302
+ return typeof value === "number" && Number.isInteger(value) && value >= 0
303
+ ? value
304
+ : fail(\`invalid \${key}\`);
305
+ };
306
+
307
+ const optionalOpaque = (
308
+ input: Record<string, unknown>,
309
+ key: string,
310
+ ): string | undefined => {
311
+ const value = input[key];
312
+ if (value === undefined) return undefined;
313
+ return typeof value === "string" && OPAQUE_ID.test(value)
314
+ ? value
315
+ : fail(\`invalid \${key}\`);
316
+ };
317
+
318
+ const optionalVersion = (
319
+ input: Record<string, unknown>,
320
+ key: string,
321
+ ): string | undefined => {
322
+ const value = input[key];
323
+ if (value === undefined) return undefined;
324
+ return typeof value === "string" && VERSION_STAMP.test(value)
325
+ ? value
326
+ : fail(\`invalid \${key}\`);
327
+ };
328
+
329
+ const optionalUnavailable = (
330
+ input: Record<string, unknown>,
331
+ ): TDoctorLocalUnavailableReason | undefined => {
332
+ const value = input.unavailable_reason;
333
+ if (value === undefined) return undefined;
334
+ return typeof value === "string" &&
335
+ (UNAVAILABLE as readonly string[]).includes(value)
336
+ ? (value as TDoctorLocalUnavailableReason)
337
+ : fail("invalid unavailable_reason");
338
+ };
339
+
340
+ const optionalBool = (
341
+ input: Record<string, unknown>,
342
+ key: string,
343
+ ): boolean | undefined => {
344
+ const value = input[key];
345
+ if (value === undefined) return undefined;
346
+ return typeof value === "boolean" ? value : fail(\`invalid \${key}\`);
347
+ };
348
+
349
+ const optionalEpoch = (
350
+ input: Record<string, unknown>,
351
+ key: string,
352
+ ): number | undefined => {
353
+ const value = input[key];
354
+ if (value === undefined) return undefined;
355
+ return typeof value === "number" &&
356
+ Number.isInteger(value) &&
357
+ value >= 0 &&
358
+ value <= EPOCH_MS_MAX
359
+ ? value
360
+ : fail(\`invalid \${key}\`);
361
+ };
362
+
363
+ const optionalLiteral = <T extends string>(
364
+ input: Record<string, unknown>,
365
+ key: string,
366
+ allowed: readonly T[],
367
+ ): T | undefined => {
368
+ const value = input[key];
369
+ if (value === undefined) return undefined;
370
+ return typeof value === "string" && (allowed as readonly string[]).includes(value)
371
+ ? (value as T)
372
+ : fail(\`invalid \${key}\`);
373
+ };
374
+
375
+ export const parseDoctorLocalReportResult = (
376
+ input: unknown,
377
+ ): TDoctorLocalReportResult => {
378
+ if (!isRecord(input)) {
379
+ return fail("invalid doctor local report result");
380
+ }
381
+ const record: Record<string, unknown> = input;
382
+ const versions: unknown = record.daemon_versions;
383
+ if (!Array.isArray(versions) || versions.length > 16) {
384
+ return fail("invalid daemon_versions");
385
+ }
386
+ const daemonVersions: string[] = [];
387
+ for (const item of versions) {
388
+ const version: unknown = item;
389
+ if (typeof version !== "string" || !VERSION_STAMP.test(version)) {
390
+ return fail("invalid daemon_versions");
391
+ }
392
+ daemonVersions.push(version);
393
+ }
394
+ return {
395
+ nothing_new: bool(record, "nothing_new"),
396
+ dry_run: bool(record, "dry_run"),
397
+ report_id: optionalOpaque(record, "report_id"),
398
+ accepted_count: nonNegInt(record, "accepted_count"),
399
+ skipped_count: nonNegInt(record, "skipped_count"),
400
+ gap_count: nonNegInt(record, "gap_count"),
401
+ legacy_records_skipped: nonNegInt(record, "legacy_records_skipped"),
402
+ daemon_versions: daemonVersions,
403
+ pending: bool(record, "pending"),
404
+ unavailable_reason: optionalUnavailable(record),
405
+ };
406
+ };
407
+
408
+ export const parseDoctorReportingStatus = (
409
+ input: unknown,
410
+ ): TDoctorReportingStatus => {
411
+ if (!isRecord(input)) {
412
+ return fail("invalid doctor reporting status");
413
+ }
414
+ const record: Record<string, unknown> = input;
415
+ return {
416
+ local_enabled: bool(record, "local_enabled"),
417
+ account_enabled: bool(record, "account_enabled"),
418
+ pending_account_sync: bool(record, "pending_account_sync"),
419
+ last_acknowledged_report_id: optionalOpaque(
420
+ record,
421
+ "last_acknowledged_report_id",
422
+ ),
423
+ daemon_version: optionalVersion(record, "daemon_version"),
424
+ unavailable_reason: optionalUnavailable(record),
425
+ upload_eligible: optionalBool(record, "upload_eligible"),
426
+ upload_blocker: optionalLiteral(
427
+ record,
428
+ "upload_blocker",
429
+ UPLOAD_BLOCKERS,
430
+ ),
431
+ pending_report_upload: optionalBool(record, "pending_report_upload"),
432
+ last_attempt_at_ms: optionalEpoch(record, "last_attempt_at_ms"),
433
+ last_attempt_outcome: optionalLiteral(
434
+ record,
435
+ "last_attempt_outcome",
436
+ ATTEMPT_OUTCOMES,
437
+ ),
438
+ };
439
+ };
440
+
441
+ export const parseDoctorLocalReportResultCli = parseDoctorLocalReportResult;
442
+ export const parseDoctorReportingStatusCli = parseDoctorReportingStatus;
443
+ `.replace(/\s+$/u, "\n");