opencode-codebuddy-quota 0.0.0-stage → 0.1.2

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/config.default.json +41 -0
  4. package/dist/gui-experimental.cjs +1 -0
  5. package/package.json +47 -4
  6. package/rpc.ts +92 -0
  7. package/server.ts +251 -0
  8. package/src/gui/battery.tsx +81 -0
  9. package/src/gui/dialog-helpers.ts +30 -0
  10. package/src/gui/dialog.css +83 -0
  11. package/src/gui/dialog.tsx +262 -0
  12. package/src/gui/pace.ts +76 -0
  13. package/src/gui/quota.ts +198 -0
  14. package/src/gui/store.ts +181 -0
  15. package/src/gui.tsx +111 -0
  16. package/src/server/catalog.ts +264 -0
  17. package/src/server/config-writer.ts +621 -0
  18. package/src/server/config.ts +215 -0
  19. package/src/server/embedding-local.ts +166 -0
  20. package/src/server/embedding-mode.ts +14 -0
  21. package/src/server/gateway-owner.ts +243 -0
  22. package/src/server/gateway-setup.ts +51 -0
  23. package/src/server/headers.ts +72 -0
  24. package/src/server/logger.ts +26 -0
  25. package/src/server/login-gate.ts +21 -0
  26. package/src/server/login.ts +206 -0
  27. package/src/server/model-cache.ts +136 -0
  28. package/src/server/model-info.ts +109 -0
  29. package/src/server/model-prewarm.ts +123 -0
  30. package/src/server/models-dev.ts +77 -0
  31. package/src/server/models-endpoint.ts +74 -0
  32. package/src/server/package-spec.ts +42 -0
  33. package/src/server/package-version.ts +51 -0
  34. package/src/server/pricing.ts +169 -0
  35. package/src/server/proxy.ts +564 -0
  36. package/src/server/quota-source.ts +129 -0
  37. package/src/server/rpc-handlers.ts +87 -0
  38. package/src/server/signal.ts +36 -0
  39. package/src/server/site-select.ts +24 -0
  40. package/src/server/site-state.ts +58 -0
  41. package/src/server/stream-collect.ts +166 -0
  42. package/src/server/token-store.ts +263 -0
  43. package/src/server/upstream.ts +150 -0
  44. package/src/server/wire.ts +67 -0
  45. package/src/shared.ts +20 -0
@@ -0,0 +1,215 @@
1
+ import { existsSync, readFileSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { join } from "node:path"
4
+ import { DEFAULT_PACKAGE_VERSION, isVersion } from "./package-spec"
5
+
6
+ /** Where a CodeBuddy model lives in the models.dev catalog. */
7
+ export interface ModelMapping {
8
+ /** models.dev provider id, e.g. `deepseek`, `zhipuai`, `tencent-tokenhub`. */
9
+ provider: string
10
+ /** The id the provider files the model under, which is not always CodeBuddy's. */
11
+ model: string
12
+ }
13
+
14
+ /** Keys the user may override; everything else in the file is ignored. */
15
+ export interface QuotaConfig {
16
+ /** CodeBuddy model id → its models.dev entry. A model absent here is never offered. */
17
+ models: Record<string, ModelMapping>
18
+ /** Hard block, applied on top of `models`: listed ids are dropped even when mapped. */
19
+ excluded_models: string[]
20
+ /**
21
+ * The `@ai-sdk/openai-compatible` version to write when the npm lookup fails
22
+ * or is unavailable. Ships as "the version this plugin was tested against", so
23
+ * an offline start still produces a working config rather than a bare spec
24
+ * OpenCode would resolve unpredictably.
25
+ */
26
+ package_version: string
27
+ /** Cloud embedding model id; set to `""` to disable cloud embeddings. */
28
+ embedding_model: string
29
+ /** Local (transformers.js) embedding model id; `""` means no local model. */
30
+ local_embedding_model: string
31
+ }
32
+
33
+ /**
34
+ * Mirrors `config.default.json`. The JSON file is documentation plus the
35
+ * schema anchor; the constant is what runs, so nothing has to read a file at
36
+ * plugin load time. A test asserts the two never drift apart.
37
+ */
38
+ export const DEFAULT_CONFIG: QuotaConfig = {
39
+ models: {
40
+ "deepseek-v4-pro": { provider: "deepseek", model: "deepseek-v4-pro" },
41
+ // CodeBuddy's revision of v4.1-flash is the vendor's plain v4-flash.
42
+ "deepseek-v4.1-flash": { provider: "deepseek", model: "deepseek-v4-flash" },
43
+ "glm-5.3-flash": { provider: "zhipuai", model: "glm-5.3-flash" },
44
+ "glm-5.3-flashx": { provider: "zhipuai", model: "glm-5.3-flashx" },
45
+ "minimax-m3.1-flash": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
46
+ "step-5-preview": { provider: "stepfun", model: "step-5-preview" },
47
+ "mimo-v2.6-pro": { provider: "xiaomi", model: "mimo-v2.6-pro" },
48
+ hy4std: { provider: "tencent-tokenhub", model: "hy4" },
49
+ // `Hy4 flash` ships twice: a free id and a paid one. models.dev has no
50
+ // flash entry, so both map to Hy4; the free one is zero-priced by credits.
51
+ "hy4flash-free": { provider: "tencent-tokenhub", model: "hy4" },
52
+ hy4flash: { provider: "tencent-tokenhub", model: "hy4" },
53
+ hy4free: { provider: "tencent-tokenhub", model: "hy4" },
54
+ hy3: { provider: "tencent-tokenhub", model: "hy3" },
55
+ "hy3-x": { provider: "tencent-tokenhub", model: "hy3" },
56
+ // Same model as minimax-m3.1-flash; CodeBuddy just bills it under its own id.
57
+ "space-bunny": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
58
+ // International-site cli-whitelist (ids from /v3/config agents[cli]).
59
+ // Four virtual routing aliases (default/fast/balanced/primary-model) have no
60
+ // models.dev entity and are intentionally left unmapped so they are skipped.
61
+ "hy4-preview": { provider: "tencent-tokenhub", model: "hy4-preview" },
62
+ // SG variant shares the same underlying model; models.dev has no separate id.
63
+ "deepseek-v4.1-flash-sg": { provider: "deepseek", model: "deepseek-v4-flash" },
64
+ // models.dev v3 carries all GPT ids under openai; use the official vendor.
65
+ "gpt-6-astra": { provider: "openai", model: "gpt-6-astra" },
66
+ "gpt-6.1-sol": { provider: "openai", model: "gpt-6.1-sol" },
67
+ "gpt-6-sol": { provider: "openai", model: "gpt-6-sol" },
68
+ "gpt-6-luna": { provider: "openai", model: "gpt-6-luna" },
69
+ "gpt-5.6-sol": { provider: "openai", model: "gpt-5.6-sol" },
70
+ "gpt-5.6-terra": { provider: "openai", model: "gpt-5.6-terra" },
71
+ "gpt-5.5": { provider: "openai", model: "gpt-5.5" },
72
+ "gpt-5.4": { provider: "openai", model: "gpt-5.4" },
73
+ "gpt-5.6-luna": { provider: "openai", model: "gpt-5.6-luna" },
74
+ // Official vendor mappings: reseller entries carry distorted prices.
75
+ "grok-4.7": { provider: "xai", model: "grok-4.7" },
76
+ "gemini-3.8-flash": { provider: "google", model: "gemini-3.8-flash" },
77
+ "glm-5.3": { provider: "zhipuai", model: "glm-5.3" },
78
+ // models.dev's `zhipuai` provider has no glm-5.4 entry; only coding-plan
79
+ // resellers do. tencent-token-plan is the one carrying real per-token prices.
80
+ "glm-5.4": { provider: "tencent-token-plan", model: "glm-5.4" },
81
+ "glm-5.2": { provider: "zhipuai", model: "glm-5.2" },
82
+ // moonshotai is the official vendor; wafer.ai resells kimi at skewed prices.
83
+ "kimi-k3.1-pro": { provider: "moonshotai", model: "kimi-k3.1-pro" },
84
+ "kimi-k3": { provider: "moonshotai", model: "kimi-k3" },
85
+ "kimi-k3.1-pro-highspeed": { provider: "moonshotai", model: "kimi-k3.1-pro-highspeed" },
86
+ },
87
+ // auto/max-model are virtual routing tiers with no models.dev entity; exclude
88
+ // them explicitly rather than relying on the no-mapping skip.
89
+ excluded_models: ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
90
+ package_version: DEFAULT_PACKAGE_VERSION,
91
+ embedding_model: "bge-m3",
92
+ local_embedding_model: "",
93
+ }
94
+
95
+ export const CONFIG_FILE_NAME = "codebuddy-quota.json"
96
+
97
+ /** `$XDG_CONFIG_HOME/opencode`, or `~/.config/opencode` when it is unset. */
98
+ export function configDir(
99
+ env: Record<string, string | undefined> = process.env,
100
+ home: string = homedir(),
101
+ ): string {
102
+ const xdg = env.XDG_CONFIG_HOME
103
+ if (xdg) return join(xdg, "opencode")
104
+ return join(home, ".config", "opencode")
105
+ }
106
+
107
+ /** `~/.config/opencode/codebuddy-quota.json`, beside the user's `opencode.json(c)`. */
108
+ export function configPath(home: string = homedir()): string {
109
+ return join(configDir(undefined, home), CONFIG_FILE_NAME)
110
+ }
111
+
112
+ /**
113
+ * The names OpenCode accepts for a config file, in the order it prefers them.
114
+ * Both parse; JSONC is the one with comments.
115
+ */
116
+ export const OPENCODE_CONFIG_NAMES = ["opencode.jsonc", "opencode.json"] as const
117
+
118
+ /**
119
+ * The OpenCode config this plugin should edit.
120
+ *
121
+ * OpenCode reads `opencode.jsonc` or `opencode.json`, whichever exists — a user
122
+ * who picked `.json` must not be left with a plugin that silently imports
123
+ * nothing. The first name that exists wins; with neither present the returned
124
+ * path ends in `.jsonc`, matching what OpenCode writes for a fresh config.
125
+ */
126
+ export function opencodeConfigPath(
127
+ dir: string = configDir(),
128
+ exists: (path: string) => boolean = existsSync,
129
+ ): string {
130
+ for (const name of OPENCODE_CONFIG_NAMES) {
131
+ const candidate = join(dir, name)
132
+ if (exists(candidate)) return candidate
133
+ }
134
+ return join(dir, OPENCODE_CONFIG_NAMES[0])
135
+ }
136
+
137
+ function isRecord(value: unknown): value is Record<string, unknown> {
138
+ return typeof value === "object" && value !== null && !Array.isArray(value)
139
+ }
140
+
141
+ /**
142
+ * `{ codebuddyId: { provider, model } }`. A single malformed entry drops the
143
+ * whole field rather than half-applying it — a partially understood model list
144
+ * is worse than the shipped one.
145
+ */
146
+ function modelMap(value: unknown): Record<string, ModelMapping> | undefined {
147
+ if (!isRecord(value)) return undefined
148
+ const out: Record<string, ModelMapping> = {}
149
+ for (const [id, entry] of Object.entries(value)) {
150
+ if (id.length === 0 || !isRecord(entry)) return undefined
151
+ const { provider, model } = entry as Record<string, unknown>
152
+ if (typeof provider !== "string" || provider.length === 0) return undefined
153
+ if (typeof model !== "string" || model.length === 0) return undefined
154
+ out[id] = { provider, model }
155
+ }
156
+ return out
157
+ }
158
+
159
+ function stringList(value: unknown): string[] | undefined {
160
+ if (!Array.isArray(value)) return undefined
161
+ const out: string[] = []
162
+ for (const v of value) {
163
+ if (typeof v !== "string" || v.length === 0) return undefined
164
+ out.push(v)
165
+ }
166
+ return out
167
+ }
168
+
169
+ /**
170
+ * Unlike `stringList`, an empty string is a meaningful value here: it is how a
171
+ * user disables one embedding backend. Only the wrong type falls back.
172
+ */
173
+ function optionalString(value: unknown): string | undefined {
174
+ return typeof value === "string" ? value : undefined
175
+ }
176
+
177
+ export interface LoadConfigDeps {
178
+ configPath?: string
179
+ readFile?: (path: string) => string
180
+ }
181
+
182
+ /**
183
+ * The user file is layered over the defaults: `models` merges one level deep so
184
+ * a user who adds a model does not have to repeat the twelve shipped ones, while
185
+ * `excluded_models` replaces wholesale. A field that fails validation silently
186
+ * keeps its default so one typo cannot take the rest down. This function never
187
+ * throws — a broken config must not stop the quota panel.
188
+ */
189
+ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
190
+ const path = deps.configPath ?? configPath()
191
+ const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
192
+
193
+ let parsed: unknown
194
+ try {
195
+ parsed = JSON.parse(read(path))
196
+ } catch {
197
+ return DEFAULT_CONFIG
198
+ }
199
+ if (!isRecord(parsed)) return DEFAULT_CONFIG
200
+
201
+ const models = modelMap(parsed.models)
202
+ const excluded = stringList(parsed.excluded_models)
203
+ // Only a real version may reach the config writer: anything else would be
204
+ // written verbatim into the provider's `package` spec.
205
+ const packageVersion = isVersion(parsed.package_version) ? parsed.package_version : undefined
206
+
207
+ return {
208
+ models: models ? { ...DEFAULT_CONFIG.models, ...models } : DEFAULT_CONFIG.models,
209
+ excluded_models: excluded ?? DEFAULT_CONFIG.excluded_models,
210
+ package_version: packageVersion ?? DEFAULT_CONFIG.package_version,
211
+ embedding_model: optionalString(parsed.embedding_model) ?? DEFAULT_CONFIG.embedding_model,
212
+ local_embedding_model:
213
+ optionalString(parsed.local_embedding_model) ?? DEFAULT_CONFIG.local_embedding_model,
214
+ }
215
+ }
@@ -0,0 +1,166 @@
1
+ import { join } from "node:path"
2
+ import { configDir } from "./config"
3
+
4
+ /** An in-process embedder that mirrors the cloud `bge-m3` contract. */
5
+ export interface LocalEmbedding {
6
+ embed(inputs: string[]): Promise<number[][]>
7
+ readonly dimension: number
8
+ }
9
+
10
+ /** OpenAI's `/embeddings` wire shape. */
11
+ export interface EmbeddingResponse {
12
+ object: "list"
13
+ data: { object: "embedding"; index: number; embedding: number[] }[]
14
+ model: string
15
+ usage: { prompt_tokens: number; total_tokens: number }
16
+ }
17
+
18
+ /** The cloud model is 1024-dim; a local result must not change the caller's index shape. */
19
+ const DIMENSION = 1024
20
+
21
+ /**
22
+ * Guard the wire shape against a mis-shaped ONNX output. A vector of the wrong
23
+ * width would be accepted by clients with no error and silently corrupt their
24
+ * index, so it is converted into a failure here, at the one place every local
25
+ * result passes through.
26
+ */
27
+ function assertVectors(vectors: number[][], expected: number, count: number): number[][] {
28
+ if (vectors.length !== count) {
29
+ throw new Error(`local embedder returned ${vectors.length} vectors for ${count} inputs`)
30
+ }
31
+ for (const vector of vectors) {
32
+ if (!Array.isArray(vector) || vector.length !== expected) {
33
+ throw new Error(`local embedder returned a vector of width ${vector?.length} (expected ${expected})`)
34
+ }
35
+ }
36
+ return vectors
37
+ }
38
+
39
+ /**
40
+ * The full HuggingFace id is the only local selector. The bare `bge-m3` must keep
41
+ * going upstream so existing cloud callers are unaffected.
42
+ */
43
+ const LOCAL_PREFIX = "Xenova/"
44
+
45
+ /**
46
+ * Single source of truth for the local-vs-upstream split; `proxy.ts` uses this
47
+ * too, so the two call sites cannot drift apart.
48
+ */
49
+ export function isLocalModel(model: string): boolean {
50
+ return model.startsWith(LOCAL_PREFIX)
51
+ }
52
+
53
+ /** Keep the cache inside the plugin's own config tree so it never fights OpenCode or opencode-mem. */
54
+ export const MODEL_CACHE_DIR = join(configDir(), "codebuddy-quota-models")
55
+
56
+ export async function routeEmbedding(
57
+ model: string,
58
+ input: string | string[],
59
+ deps: { local: LocalEmbedding },
60
+ ): Promise<EmbeddingResponse | null> {
61
+ if (!isLocalModel(model)) return null
62
+ const inputs = Array.isArray(input) ? input : [input]
63
+ const vectors = assertVectors(await deps.local.embed(inputs), DIMENSION, inputs.length)
64
+ return {
65
+ object: "list",
66
+ data: vectors.map((embedding, index) => ({ object: "embedding" as const, index, embedding })),
67
+ model,
68
+ // Tokenisation would need the model's own tokenizer; a per-input count is
69
+ // enough to keep the field populated without pulling one in.
70
+ usage: { prompt_tokens: inputs.length, total_tokens: inputs.length },
71
+ }
72
+ }
73
+
74
+ /** The slice of transformers.js this module uses. */
75
+ type FeatureExtractor = (
76
+ inputs: string[],
77
+ options: { pooling: "cls"; normalize: boolean },
78
+ ) => Promise<{ tolist(): number[][] }>
79
+
80
+ /** The shipped default; a configured local model id overrides it. */
81
+ const DEFAULT_LOCAL_MODEL = "Xenova/bge-m3"
82
+
83
+ /**
84
+ * A build is expensive (~600 MB download + ONNX load), so failures must not be
85
+ * sticky. The builder receives the target id so tests can assert which model a
86
+ * factory was asked to load without downloading it.
87
+ */
88
+ export type LocalEmbedderBuilder = (modelId: string) => Promise<LocalEmbedding>
89
+
90
+ /**
91
+ * The successful pipeline is memoised at module scope on purpose: production
92
+ * constructs a new embedder per request (`deps.local ?? createLocalEmbedder()`),
93
+ * so a per-instance memo would reload the ONNX sessions on every local call.
94
+ */
95
+ let pending: Promise<LocalEmbedding> | null = null
96
+
97
+ /**
98
+ * Forget the memoised build. Production calls this after repairing a corrupt
99
+ * cache: the files that were deleted must be downloaded again, and the memo
100
+ * would otherwise hand every later request the old, broken pipeline. Only the
101
+ * repair path calls it; one pipeline per process is still the normal contract.
102
+ */
103
+ export function clearLocalEmbedderMemo(): void {
104
+ pending = null
105
+ }
106
+
107
+ /** Test alias: each case must start from a cold process. */
108
+ export function resetLocalEmbedderForTests(): void {
109
+ clearLocalEmbedderMemo()
110
+ }
111
+
112
+ /**
113
+ * Builds the pipeline on first use. `@huggingface/transformers` is imported
114
+ * dynamically on purpose: a static import would make every plugin cold start
115
+ * pay for ONNX runtime even though almost no request uses local embeddings.
116
+ * The promise is memoised process-wide so concurrent first requests share one
117
+ * pipeline. A failed build clears the memo before rethrowing, otherwise a single
118
+ * transient download error would pin every later request to 502 until the
119
+ * process restarts.
120
+ *
121
+ * Both call styles are supported: `createLocalEmbedder(modelId, builder)` and
122
+ * the legacy `createLocalEmbedder(builder)`, so existing callers keep the
123
+ * shipped default id. `builder` exists so tests can exercise the retry without
124
+ * downloading the model.
125
+ */
126
+ export function createLocalEmbedder(modelId?: string, builder?: LocalEmbedderBuilder): LocalEmbedding
127
+ export function createLocalEmbedder(builder: LocalEmbedderBuilder, modelId?: string): LocalEmbedding
128
+ export function createLocalEmbedder(
129
+ first?: string | LocalEmbedderBuilder,
130
+ second?: string | LocalEmbedderBuilder,
131
+ ): LocalEmbedding {
132
+ const modelId = typeof first === "string" ? first : typeof second === "string" ? second : DEFAULT_LOCAL_MODEL
133
+ const builder = typeof first === "function" ? first : typeof second === "function" ? second : undefined
134
+ const build = async (): Promise<LocalEmbedding> => {
135
+ const { pipeline, env } = await import("@huggingface/transformers")
136
+ // Must be set before the pipeline is created, otherwise the model lands in
137
+ // the shared default cache.
138
+ env.cacheDir = MODEL_CACHE_DIR
139
+ // The configured id drives both the download and the cache directory that
140
+ // prewarm verifies (model-cache.ts uses `join(cacheDir, model)`).
141
+ const extractor = (await pipeline("feature-extraction", modelId, { dtype: "q8" })) as FeatureExtractor
142
+ return {
143
+ dimension: DIMENSION,
144
+ embed: async (inputs) => {
145
+ const output = await extractor(inputs, { pooling: "cls", normalize: true })
146
+ // Validate the raw ONNX rows, not just the wire response: `tolist()` can
147
+ // hand back a ragged array that would otherwise only fail much later.
148
+ return assertVectors(output.tolist(), DIMENSION, inputs.length)
149
+ },
150
+ }
151
+ }
152
+ const ensure = (): Promise<LocalEmbedding> => {
153
+ if (!pending) {
154
+ pending = (builder ? builder(modelId) : build()).catch((error: unknown) => {
155
+ // Rejections are not nullish, so `??=` would reuse them forever.
156
+ pending = null
157
+ throw error
158
+ })
159
+ }
160
+ return pending
161
+ }
162
+ return {
163
+ dimension: DIMENSION,
164
+ embed: async (inputs) => (await ensure()).embed(inputs),
165
+ }
166
+ }
@@ -0,0 +1,14 @@
1
+ import type { QuotaConfig } from "./config"
2
+
3
+ /**
4
+ * Choose the embedding backend from configuration alone. Pure: no I/O and no
5
+ * request-body sniffing, so proxy routing and startup warmup agree on one rule.
6
+ * Local mode requires an explicit opt-in: the cloud model must be disabled
7
+ * *and* a local model must be named.
8
+ */
9
+ export function resolveEmbeddingMode(
10
+ config: Pick<QuotaConfig, "embedding_model" | "local_embedding_model">,
11
+ ): "cloud" | "local" {
12
+ if (config.local_embedding_model !== "" && config.embedding_model === "") return "local"
13
+ return "cloud"
14
+ }
@@ -0,0 +1,243 @@
1
+ import { HEALTH_BODY, type ProxyServer } from "./proxy"
2
+
3
+ /**
4
+ * Process-wide owner of the single bound gateway. The state lives on globalThis
5
+ * behind a Symbol.for key (not in module scope) because OpenCode reloads a
6
+ * plugin by re-evaluating its modules: module-level state is lost, while
7
+ * globalThis survives. Symbol.for gives every plugin instance the same key.
8
+ */
9
+ export interface GatewayOwnerState {
10
+ server: ProxyServer | null
11
+ refs: number
12
+ closeTimer: ReturnType<typeof setTimeout> | null
13
+ generation: number
14
+ probeTimer: ReturnType<typeof setInterval> | null
15
+ /** In-flight cold bind; concurrent ensures await it instead of racing a second listen. */
16
+ starting: Promise<ProxyServer | null> | null
17
+ }
18
+
19
+ const OWNER_KEY = Symbol.for("codebuddy-quota.gateway.owner")
20
+ const DEFAULT_GRACE_MS = 8000
21
+ const DEFAULT_PROBE_MS = 5000
22
+ const PROBE_TIMEOUT_MS = 2000
23
+
24
+ /**
25
+ * The exact health payload proxy.ts serves. Parse the exported wire body once
26
+ * so the probe compares against the shared contract instead of a copy of the
27
+ * literal.
28
+ */
29
+ const HEALTH_FIELDS = JSON.parse(HEALTH_BODY) as { status: string; service: string }
30
+
31
+ type GlobalWithOwner = Record<PropertyKey, GatewayOwnerState | undefined>
32
+
33
+ function readOwner(): GatewayOwnerState | undefined {
34
+ return (globalThis as unknown as GlobalWithOwner)[OWNER_KEY]
35
+ }
36
+
37
+ function owner(): GatewayOwnerState {
38
+ const existing = readOwner()
39
+ if (existing) return existing
40
+ const created: GatewayOwnerState = {
41
+ server: null,
42
+ refs: 0,
43
+ closeTimer: null,
44
+ generation: 0,
45
+ probeTimer: null,
46
+ starting: null,
47
+ }
48
+ ;(globalThis as unknown as GlobalWithOwner)[OWNER_KEY] = created
49
+ return created
50
+ }
51
+
52
+ export interface EnsureGatewayDeps {
53
+ port: number
54
+ createServer: () => ProxyServer
55
+ start: (s: ProxyServer, port: number) => Promise<void>
56
+ log: (s: string) => void
57
+ graceMs?: number
58
+ /** Injected health probe; defaults to an HTTP GET of `/health`. */
59
+ probe?: () => Promise<boolean>
60
+ /** Probe interval in milliseconds (default 5000). */
61
+ probeMs?: number
62
+ /** Injected fetch for the default probe, so tests never touch the network. */
63
+ fetchImpl?: typeof fetch
64
+ }
65
+
66
+ export interface ReleaseGatewayDeps {
67
+ log: (s: string) => void
68
+ graceMs?: number
69
+ }
70
+
71
+ /** A throwing injected logger must never break ownership bookkeeping. */
72
+ function safeLog(log: (s: string) => void, message: string): void {
73
+ try {
74
+ log(message)
75
+ } catch {
76
+ // ignore
77
+ }
78
+ }
79
+
80
+ /** Node-style EADDRINUSE, matched by code or by the usual message text. */
81
+ function isEaddrinuse(error: unknown): boolean {
82
+ if ((error as { code?: unknown } | null)?.code === "EADDRINUSE") return true
83
+ const text = String((error as { message?: unknown } | null)?.message ?? error ?? "")
84
+ return /EADDRINUSE|address already in use/i.test(text)
85
+ }
86
+
87
+ /** Default probe: a bare `GET /health` answering only with the exact health body. */
88
+ function makeDefaultProbe(deps: EnsureGatewayDeps): () => Promise<boolean> {
89
+ const fetchImpl = deps.fetchImpl ?? fetch
90
+ return async () => {
91
+ try {
92
+ const response = await fetchImpl(`http://127.0.0.1:${deps.port}/health`, {
93
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
94
+ })
95
+ if (response.status !== 200) return false
96
+ const body = (await response.json()) as { status?: string; service?: string } | null
97
+ return body?.status === HEALTH_FIELDS.status && body?.service === HEALTH_FIELDS.service
98
+ } catch {
99
+ return false
100
+ }
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Lightweight backstop for a port held by another process or a Windows orphan
106
+ * socket. In-process reloads reuse the shared server and never reach here.
107
+ * The loop is owned by `state`, so a reset (or a newer probe) can cancel it.
108
+ */
109
+ function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void {
110
+ if (state.probeTimer !== null) {
111
+ clearInterval(state.probeTimer)
112
+ state.probeTimer = null
113
+ }
114
+ const probe = deps.probe ?? makeDefaultProbe(deps)
115
+ const timer = setInterval(() => {
116
+ void (async () => {
117
+ let healthy = false
118
+ try {
119
+ healthy = await probe()
120
+ } catch (error) {
121
+ const reason = String((error as Error)?.message ?? error)
122
+ safeLog(deps.log, `gateway probe error: ${reason}`)
123
+ return
124
+ }
125
+ if (!healthy) return
126
+ clearInterval(timer)
127
+ if (state.probeTimer === timer) state.probeTimer = null
128
+ safeLog(deps.log, "gateway probe recovered the port; stopping probe")
129
+ })()
130
+ }, deps.probeMs ?? DEFAULT_PROBE_MS)
131
+ state.probeTimer = timer
132
+ }
133
+
134
+ /**
135
+ * Acquire the shared gateway. A live server is returned as-is — no re-bind and
136
+ * no second `start`, so a plugin reload never opens a listen gap on the port.
137
+ * A pending close is cancelled because a new holder has arrived.
138
+ *
139
+ * Create/start failures roll the ref count back. A non-EADDRINUSE failure is
140
+ * rethrown unchanged; EADDRINUSE does not claim ownership (returns null) and
141
+ * instead starts a probe loop that notices when the port is ours again.
142
+ */
143
+ export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServer | null> {
144
+ const state = owner()
145
+ state.refs++
146
+ if (state.closeTimer !== null) {
147
+ clearTimeout(state.closeTimer)
148
+ state.closeTimer = null
149
+ }
150
+ if (state.server !== null) return state.server
151
+ // A concurrent cold start must not race a second bind on the same port.
152
+ // Everyone arriving while `starting` is pending awaits the same promise, so
153
+ // start is invoked once and every caller observes the same outcome. The
154
+ // shared promise normalizes EADDRINUSE to `null` exactly once; each caller
155
+ // below rolls back its *own* ref when no server was actually acquired.
156
+ if (state.starting === null) {
157
+ state.starting = (async () => {
158
+ try {
159
+ const server = deps.createServer()
160
+ await deps.start(server, deps.port)
161
+ state.server = server
162
+ return server
163
+ } catch (error) {
164
+ if (isEaddrinuse(error)) {
165
+ safeLog(deps.log, "gateway port in use; probing for recovery")
166
+ startProbeLoop(state, deps)
167
+ return null
168
+ }
169
+ throw error
170
+ }
171
+ })()
172
+ }
173
+ const starting = state.starting
174
+ try {
175
+ const server = await starting
176
+ if (server === null) state.refs-- // EADDRINUSE: this caller never owned a server
177
+ return server
178
+ } catch (error) {
179
+ state.refs-- // failed bind: roll back this caller's own ref
180
+ throw error
181
+ } finally {
182
+ if (state.starting === starting) state.starting = null
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Release one holder. The server is closed only after the last holder is gone
188
+ * AND a grace window has passed, so a reload's release/ensure pair does not
189
+ * tear down a listener that is immediately re-acquired.
190
+ *
191
+ * The generation is captured when the timer is scheduled: if a later
192
+ * release/ensure cycle changes it, a stale timer that still runs must not
193
+ * close a server bound by that newer cycle.
194
+ */
195
+ export function releaseGateway(deps: ReleaseGatewayDeps): void {
196
+ const state = owner()
197
+ // An EADDRINUSE ensure returns null without holding a ref, but Task 4 still
198
+ // disposes that null proxy. Clamp so such a redundant release cannot underflow
199
+ // and permanently prevent a later last-holder release from reaching zero.
200
+ // A redundant release must also leave `generation` untouched: bumping it would
201
+ // invalidate an already-scheduled close timer and leak the port via a different
202
+ // path. Only a real holder drop advances the generation.
203
+ const hadHolder = state.refs > 0
204
+ if (!hadHolder) return
205
+ state.generation++
206
+ state.refs = Math.max(0, state.refs - 1)
207
+ if (state.refs !== 0) return
208
+
209
+ const generation = state.generation
210
+ if (state.closeTimer !== null) clearTimeout(state.closeTimer)
211
+ state.closeTimer = setTimeout(() => {
212
+ state.closeTimer = null
213
+ if (state.refs !== 0 || state.generation !== generation || state.server === null) return
214
+ const server = state.server
215
+ state.server = null
216
+ void server.close().catch((error: unknown) => {
217
+ const reason = String((error as Error)?.message ?? error)
218
+ try {
219
+ deps.log(`gateway close error: ${reason}`)
220
+ } catch {
221
+ // A throwing injected logger must not turn into an unhandled rejection.
222
+ }
223
+ })
224
+ }, deps.graceMs ?? DEFAULT_GRACE_MS)
225
+ }
226
+
227
+ /**
228
+ * Drop the process-wide state and clear any pending timers. Test isolation
229
+ * only: a fresh owner is lazily created by the next ensure/release/ref-count
230
+ * call.
231
+ */
232
+ export function resetGatewayOwnerForTests(): void {
233
+ const state = readOwner()
234
+ if (state === undefined) return
235
+ if (state.closeTimer !== null) clearTimeout(state.closeTimer)
236
+ if (state.probeTimer !== null) clearInterval(state.probeTimer)
237
+ delete (globalThis as unknown as GlobalWithOwner)[OWNER_KEY]
238
+ }
239
+
240
+ /** Diagnostic/test hook: number of live holders of the shared gateway. */
241
+ export function getGatewayRefCount(): number {
242
+ return owner().refs
243
+ }
@@ -0,0 +1,51 @@
1
+ import type { ensureGateway, releaseGateway } from "./gateway-owner"
2
+ import type { ProxyServer } from "./proxy"
3
+
4
+ const PROXY_PORT = 7688
5
+
6
+ /**
7
+ * Pure startup wiring: acquire the shared gateway, register the RPC handlers,
8
+ * and hand back a dispose that only drops one owner reference. All deps are
9
+ * injected so this can be tested without binding a port or touching `ctx`.
10
+ */
11
+ export interface SetupGatewayDeps {
12
+ ensureGateway: typeof ensureGateway
13
+ releaseGateway: typeof releaseGateway
14
+ createServer: () => ProxyServer
15
+ register: () => Promise<{ dispose(): void }>
16
+ log: (s: string) => void
17
+ }
18
+
19
+ export interface GatewaySetup {
20
+ proxy: ProxyServer | null
21
+ dispose: () => Promise<void>
22
+ }
23
+
24
+ /**
25
+ * The owner handles create/start failure bookkeeping (including its own ref
26
+ * rollback), so only a failure AFTER a successful ensure needs a matching
27
+ * release here. Closing the shared server is the owner's grace-period job;
28
+ * dispose must never close it directly.
29
+ */
30
+ export async function setupGateway(deps: SetupGatewayDeps): Promise<GatewaySetup> {
31
+ const proxy = await deps.ensureGateway({
32
+ port: PROXY_PORT,
33
+ createServer: deps.createServer,
34
+ start: (server, port) => server.start(port),
35
+ log: deps.log,
36
+ })
37
+
38
+ try {
39
+ await deps.register()
40
+ } catch (error) {
41
+ await deps.releaseGateway({ log: deps.log })
42
+ throw error
43
+ }
44
+
45
+ return {
46
+ proxy,
47
+ dispose: async () => {
48
+ await deps.releaseGateway({ log: deps.log })
49
+ },
50
+ }
51
+ }