opencode-codebuddy-quota 0.1.2 → 0.1.3

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.
package/README.md CHANGED
@@ -76,6 +76,7 @@ bun run build:gui # 构建桌面端 GUI(dist/gui-experimental.cjs)
76
76
  - 每站本期至多一个账号;数据结构预留了多账号,但本期不提供切换 UI。
77
77
  - 本地代理是 "confused deputy":本机任意进程都能借它用 JWT 调上游,接受此风险。
78
78
  - 模型倍率名称来自上游 `credits` 字段;上游未声明时倍率标签会省略。
79
+ - 7688 网关在同进程的多个 workspace 间共享,且沿用**首个绑定实例**的凭证与配置(store / models / embeddingMode)。因此插件重载后在 GUI 里重新登录或改嵌入配置,代理仍用首实例的旧值;若上游返回 401/403,日志会提示「重启 OpenCode 或重新登录」以刷新凭证。这是单监听实例设计的已知取舍。
79
80
 
80
81
  ## License
81
82
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-codebuddy-quota",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "OpenCode plugin: dual-site (CN/INTL) CodeBuddy providers with dynamic JWT and a quota capsule that switches sites",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/server.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, writeFileSync } from "node:fs"
2
2
  import { Plugin } from "@opencode/plugin"
3
3
  import { CodebuddyQuota } from "./rpc"
4
- import type { Site } from "./src/shared"
4
+ import { PROXY_PORT, type Site } from "./src/shared"
5
5
  import { fetchCatalog } from "./src/server/catalog"
6
6
  import { loadConfig, opencodeConfigPath, type QuotaConfig } from "./src/server/config"
7
7
  import { writeProvider } from "./src/server/config-writer"
@@ -24,7 +24,6 @@ import { anySignal, timeoutSignal } from "./src/server/signal"
24
24
  import { createTokenStore } from "./src/server/token-store"
25
25
  import { fetchUpstream } from "./src/server/upstream"
26
26
 
27
- const PROXY_PORT = 7688
28
27
  const UPSTREAM_TIMEOUT_MS = 15_000
29
28
 
30
29
  /** Offline inputs the /v2/models list is built from; injected so the seam is testable. */
@@ -1,4 +1,5 @@
1
1
  import { readFileSync, writeFileSync } from "node:fs"
2
+ import { PROXY_PORT } from "../shared"
2
3
  import type { ImportedModel } from "./model-info"
3
4
  import { withVersion } from "./package-version"
4
5
  import { isVersion, packageSpec, PROVIDER_IDS } from "./package-spec"
@@ -543,7 +544,7 @@ export function writeProvider(deps: WriteProviderDeps): WriteModelsResult {
543
544
  return { status: "skipped", reason: "invalid package version" }
544
545
  }
545
546
 
546
- const port = deps.proxyPort ?? 7688
547
+ const port = deps.proxyPort ?? PROXY_PORT
547
548
  const site = deps.providerId === "codebuddy-intl" ? "intl" : "cn"
548
549
  const baseURL = `http://127.0.0.1:${port}/${site}/v2`
549
550
 
@@ -1,4 +1,4 @@
1
- import { HEALTH_BODY, type ProxyServer } from "./proxy"
1
+ import { HEALTH_BODY, processNonce, type ProxyServer } from "./proxy"
2
2
 
3
3
  /**
4
4
  * Process-wide owner of the single bound gateway. The state lives on globalThis
@@ -14,9 +14,12 @@ export interface GatewayOwnerState {
14
14
  probeTimer: ReturnType<typeof setInterval> | null
15
15
  /** In-flight cold bind; concurrent ensures await it instead of racing a second listen. */
16
16
  starting: Promise<ProxyServer | null> | null
17
+ /** In-flight close of the previous server; a new cold bind waits for it. */
18
+ closing: Promise<void> | null
17
19
  }
18
20
 
19
- const OWNER_KEY = Symbol.for("codebuddy-quota.gateway.owner")
21
+ /** Exposed for tests so they read the real key instead of a hardcoded copy. */
22
+ export const OWNER_KEY = Symbol.for("codebuddy-quota.gateway.owner")
20
23
  const DEFAULT_GRACE_MS = 8000
21
24
  const DEFAULT_PROBE_MS = 5000
22
25
  const PROBE_TIMEOUT_MS = 2000
@@ -44,6 +47,7 @@ function owner(): GatewayOwnerState {
44
47
  generation: 0,
45
48
  probeTimer: null,
46
49
  starting: null,
50
+ closing: null,
47
51
  }
48
52
  ;(globalThis as unknown as GlobalWithOwner)[OWNER_KEY] = created
49
53
  return created
@@ -54,7 +58,6 @@ export interface EnsureGatewayDeps {
54
58
  createServer: () => ProxyServer
55
59
  start: (s: ProxyServer, port: number) => Promise<void>
56
60
  log: (s: string) => void
57
- graceMs?: number
58
61
  /** Injected health probe; defaults to an HTTP GET of `/health`. */
59
62
  probe?: () => Promise<boolean>
60
63
  /** Probe interval in milliseconds (default 5000). */
@@ -84,17 +87,40 @@ function isEaddrinuse(error: unknown): boolean {
84
87
  return /EADDRINUSE|address already in use/i.test(text)
85
88
  }
86
89
 
87
- /** Default probe: a bare `GET /health` answering only with the exact health body. */
90
+ /**
91
+ * Default probe: a bare `GET /health`. The body carries a process nonce so the
92
+ * probe distinguishes its own gateway (nonce matches) from another OpenCode
93
+ * instance serving the same port (nonce differs) — a foreign gateway is not
94
+ * "recovered"; we log an actionable hint and keep probing without taking over.
95
+ */
88
96
  function makeDefaultProbe(deps: EnsureGatewayDeps): () => Promise<boolean> {
89
97
  const fetchImpl = deps.fetchImpl ?? fetch
98
+ let foreignReported = false
90
99
  return async () => {
91
100
  try {
92
101
  const response = await fetchImpl(`http://127.0.0.1:${deps.port}/health`, {
93
102
  signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
94
103
  })
95
104
  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
105
+ const body = (await response.json()) as {
106
+ status?: string
107
+ service?: string
108
+ nonce?: string
109
+ } | null
110
+ if (body?.status !== HEALTH_FIELDS.status || body?.service !== HEALTH_FIELDS.service) {
111
+ return false
112
+ }
113
+ if (body.nonce !== processNonce()) {
114
+ if (!foreignReported) {
115
+ foreignReported = true
116
+ safeLog(
117
+ deps.log,
118
+ `another OpenCode instance is serving port ${deps.port}; close the duplicate instance (no takeover)`,
119
+ )
120
+ }
121
+ return false
122
+ }
123
+ return true
98
124
  } catch {
99
125
  return false
100
126
  }
@@ -102,9 +128,10 @@ function makeDefaultProbe(deps: EnsureGatewayDeps): () => Promise<boolean> {
102
128
  }
103
129
 
104
130
  /**
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.
131
+ * Diagnostic backstop for a port held by another process or a Windows orphan
132
+ * socket. In-process reloads reuse the shared server and never reach here. The
133
+ * loop only observes /health (own vs foreign via nonce); it never rebinds. The
134
+ * loop is owned by `state`, so a reset / rebind / newer probe can cancel it.
108
135
  */
109
136
  function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void {
110
137
  if (state.probeTimer !== null) {
@@ -125,9 +152,15 @@ function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void
125
152
  if (!healthy) return
126
153
  clearInterval(timer)
127
154
  if (state.probeTimer === timer) state.probeTimer = null
128
- safeLog(deps.log, "gateway probe recovered the port; stopping probe")
155
+ // A healthy /health responder stops the diagnostic probe; this process
156
+ // never (re)bound the port itself. The default probe already emitted an
157
+ // own-vs-foreign nonce hint, so keep this line neutral — never claim a
158
+ // takeover/recovery that did not happen.
159
+ safeLog(deps.log, "gateway /health responder present; diagnostic probe stopped (no rebind by this process)")
129
160
  })()
130
161
  }, deps.probeMs ?? DEFAULT_PROBE_MS)
162
+ // Do not keep the process alive solely for the backstop probe.
163
+ timer.unref?.()
131
164
  state.probeTimer = timer
132
165
  }
133
166
 
@@ -138,7 +171,9 @@ function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void
138
171
  *
139
172
  * Create/start failures roll the ref count back. A non-EADDRINUSE failure is
140
173
  * rethrown unchanged; EADDRINUSE does not claim ownership (returns null) and
141
- * instead starts a probe loop that notices when the port is ours again.
174
+ * instead starts a diagnostic probe that watches for a healthy /health responder
175
+ * (distinguishing own vs foreign by nonce). The probe never rebinds — recovery
176
+ * still requires a later ensure (e.g. a plugin reload).
142
177
  */
143
178
  export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServer | null> {
144
179
  const state = owner()
@@ -148,6 +183,10 @@ export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServe
148
183
  state.closeTimer = null
149
184
  }
150
185
  if (state.server !== null) return state.server
186
+ // If a previous holder's server is still closing, wait for it to release the
187
+ // port before attempting a cold bind. Otherwise the bind races the close,
188
+ // hits EADDRINUSE, and leaves no owner once the old server finishes closing.
189
+ if (state.closing !== null) await state.closing
151
190
  // A concurrent cold start must not race a second bind on the same port.
152
191
  // Everyone arriving while `starting` is pending awaits the same promise, so
153
192
  // start is invoked once and every caller observes the same outcome. The
@@ -158,6 +197,13 @@ export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServe
158
197
  try {
159
198
  const server = deps.createServer()
160
199
  await deps.start(server, deps.port)
200
+ // A successful bind (cold or after a prior EADDRINUSE) means we now own
201
+ // the port. Any leftover probe from an earlier EADDRINUSE is stale —
202
+ // clear it so it cannot emit a false "foreign gateway" log or leak.
203
+ if (state.probeTimer !== null) {
204
+ clearInterval(state.probeTimer)
205
+ state.probeTimer = null
206
+ }
161
207
  state.server = server
162
208
  return server
163
209
  } catch (error) {
@@ -201,7 +247,17 @@ export function releaseGateway(deps: ReleaseGatewayDeps): void {
201
247
  // invalidate an already-scheduled close timer and leak the port via a different
202
248
  // path. Only a real holder drop advances the generation.
203
249
  const hadHolder = state.refs > 0
204
- if (!hadHolder) return
250
+ if (!hadHolder) {
251
+ // A null-proxy setup (EADDRINUSE) holds no ref but may have left a probe
252
+ // loop running. When the last instance disposes with no owned server, tear
253
+ // the probe down so it cannot outlive the plugin. Do not touch generation
254
+ // or any close timer — this release never represented a real holder.
255
+ if (state.refs === 0 && state.server === null && state.probeTimer !== null) {
256
+ clearInterval(state.probeTimer)
257
+ state.probeTimer = null
258
+ }
259
+ return
260
+ }
205
261
  state.generation++
206
262
  state.refs = Math.max(0, state.refs - 1)
207
263
  if (state.refs !== 0) return
@@ -213,7 +269,10 @@ export function releaseGateway(deps: ReleaseGatewayDeps): void {
213
269
  if (state.refs !== 0 || state.generation !== generation || state.server === null) return
214
270
  const server = state.server
215
271
  state.server = null
216
- void server.close().catch((error: unknown) => {
272
+ // Track the in-flight close so a new cold bind waits for the port to be
273
+ // released instead of racing it (which would EADDRINUSE and strand the
274
+ // owner). Swallow close failures into a log — setup must stay non-fatal.
275
+ const closing = server.close().catch((error: unknown) => {
217
276
  const reason = String((error as Error)?.message ?? error)
218
277
  try {
219
278
  deps.log(`gateway close error: ${reason}`)
@@ -221,6 +280,10 @@ export function releaseGateway(deps: ReleaseGatewayDeps): void {
221
280
  // A throwing injected logger must not turn into an unhandled rejection.
222
281
  }
223
282
  })
283
+ state.closing = closing
284
+ void closing.finally(() => {
285
+ if (state.closing === closing) state.closing = null
286
+ })
224
287
  }, deps.graceMs ?? DEFAULT_GRACE_MS)
225
288
  }
226
289
 
@@ -1,7 +1,6 @@
1
1
  import type { ensureGateway, releaseGateway } from "./gateway-owner"
2
2
  import type { ProxyServer } from "./proxy"
3
-
4
- const PROXY_PORT = 7688
3
+ import { PROXY_PORT } from "../shared"
5
4
 
6
5
  /**
7
6
  * Pure startup wiring: acquire the shared gateway, register the RPC handlers,
@@ -28,24 +27,48 @@ export interface GatewaySetup {
28
27
  * dispose must never close it directly.
29
28
  */
30
29
  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
- })
30
+ let proxy: ProxyServer | null = null
31
+ let holdsRef = false
32
+ try {
33
+ proxy = await deps.ensureGateway({
34
+ port: PROXY_PORT,
35
+ createServer: deps.createServer,
36
+ start: (server, port) => server.start(port),
37
+ log: deps.log,
38
+ })
39
+ // A non-null proxy is a real acquired ref. EADDRINUSE returns null *after*
40
+ // ensureGateway already rolled its own ref back, so null means "not held".
41
+ holdsRef = proxy !== null
42
+ } catch (error) {
43
+ // A bind failure other than EADDRINUSE must stay non-fatal, as it was before
44
+ // the shared-owner refactor: log it and let the rest of setup (RPC/providers)
45
+ // proceed. ensureGateway already rolled back its own ref — no release.
46
+ const reason = String((error as Error)?.message ?? error)
47
+ try {
48
+ deps.log(`gateway bind failed; proxy unavailable (non-fatal): ${reason}`)
49
+ } catch {
50
+ // a throwing logger must never turn a non-fatal bind failure fatal
51
+ }
52
+ }
37
53
 
38
54
  try {
39
55
  await deps.register()
40
56
  } catch (error) {
41
- await deps.releaseGateway({ log: deps.log })
57
+ if (holdsRef) await deps.releaseGateway({ log: deps.log })
42
58
  throw error
43
59
  }
44
60
 
61
+ // Only an instance that actually acquired a ref may release it. Releasing
62
+ // from a null-proxy instance would decrement a *different* live holder and,
63
+ // after grace, close a server this instance never owned. The released guard
64
+ // makes dispose idempotent so a repeated call cannot double-release.
65
+ let released = false
45
66
  return {
46
67
  proxy,
47
68
  dispose: async () => {
48
- await deps.releaseGateway({ log: deps.log })
69
+ if (released) return
70
+ released = true
71
+ if (holdsRef) await deps.releaseGateway({ log: deps.log })
49
72
  },
50
73
  }
51
74
  }
@@ -8,12 +8,31 @@ import { collectSse, collectSseFromStream, toChatCompletion } from "./stream-col
8
8
  import type { TokenStore } from "./token-store"
9
9
 
10
10
  /**
11
- * Exact wire body of `GET /health`. Cross-task contract: a later probe parses
11
+ * Base fields of `GET /health`. Cross-task contract: a probe parses
12
12
  * `status === "ok" && service === "codebuddy-quota"`, so both the keys and the
13
- * spelling are part of the API. Export it instead of duplicating the literal.
13
+ * spelling are part of the API. The live body adds a process nonce (below) so a
14
+ * probe can tell its own gateway from another OpenCode instance on the port.
14
15
  */
15
16
  export const HEALTH_BODY = '{"status":"ok","service":"codebuddy-quota"}'
16
17
 
18
+ const NONCE_KEY = Symbol.for("codebuddy-quota.gateway.nonce")
19
+
20
+ /** Process-wide nonce, stable across plugin module reloads via globalThis. */
21
+ export function processNonce(): string {
22
+ const g = globalThis as unknown as Record<PropertyKey, string | undefined>
23
+ if (!g[NONCE_KEY]) g[NONCE_KEY] = crypto.randomUUID()
24
+ return g[NONCE_KEY] as string
25
+ }
26
+
27
+ /** Live health body: base fields plus the process nonce. */
28
+ export function healthBody(): string {
29
+ return JSON.stringify({
30
+ status: "ok",
31
+ service: "codebuddy-quota",
32
+ nonce: processNonce(),
33
+ })
34
+ }
35
+
17
36
  export function routeSite(url: string): Site | null {
18
37
  if (url.startsWith("/cn/v2/")) return "cn"
19
38
  if (url.startsWith("/intl/v2/")) return "intl"
@@ -258,7 +277,7 @@ export async function handleRequest(
258
277
  if ((req.method === "GET" || req.method === undefined) && req.url === "/health") {
259
278
  res.setHeader("Content-Type", "application/json")
260
279
  res.status(200)
261
- res.end(HEALTH_BODY)
280
+ res.end(healthBody())
262
281
  return
263
282
  }
264
283
 
@@ -443,6 +462,17 @@ export async function handleRequest(
443
462
  return
444
463
  }
445
464
 
465
+ // An upstream 401/403 on a request we authenticated is actionable: the shared
466
+ // gateway uses the first plugin instance's credential store (by design), so a
467
+ // re-login in a later instance can leave this store holding a stale token.
468
+ // Keep the response untouched; only emit a hint that maps the symptom to the
469
+ // known trade-off so it is diagnosable instead of a silent failure.
470
+ if ((upstream.status === 401 || upstream.status === 403) && !isAggregate) {
471
+ deps.log?.(
472
+ `upstream ${upstream.status}: the shared gateway may hold a stale credential from the first plugin instance; restart OpenCode or re-login to refresh it`,
473
+ )
474
+ }
475
+
446
476
  copyHeaders(upstream.headers, res)
447
477
  res.status(upstream.status)
448
478
 
@@ -466,16 +496,23 @@ export interface ProxyServer {
466
496
  }
467
497
 
468
498
  /**
469
- * Bind options for the listener. `reuseAddr` + `exclusive: false` let a bind
470
- * succeed on Windows when an orphaned socket still holds the fixed port; an
471
- * injected object overrides these defaults field by field.
499
+ * Bind options for the listener. An injected object overrides the defaults
500
+ * field by field. Only options Node/Bun actually recognize belong here.
472
501
  */
473
502
  export interface ListenOptions {
474
- reuseAddr?: boolean
475
503
  exclusive?: boolean
476
504
  }
477
505
 
478
- const DEFAULT_LISTEN_OPTIONS: Required<ListenOptions> = { reuseAddr: true, exclusive: false }
506
+ /**
507
+ * Bind options for the fixed local port. `exclusive:false` is an explicit
508
+ * `server.listen` option (disables SO_EXCLUSIVEADDRUSE on Windows). A genuinely
509
+ * occupied/orphaned port is NOT recovered here — that is the EADDRINUSE probe's
510
+ * job in gateway-owner.ts. There is no `reuseAddr` server.listen option (it is
511
+ * silently ignored), so none is carried; `reusePort` must never be set because
512
+ * under Bun it lets two processes share the port and split requests across
513
+ * per-process token stores, causing intermittent 401s. A guard test pins this.
514
+ */
515
+ export const DEFAULT_LISTEN_OPTIONS: Required<ListenOptions> = { exclusive: false }
479
516
 
480
517
  export function createProxy(deps: {
481
518
  store: TokenStore
@@ -552,9 +589,15 @@ export function createProxy(deps: {
552
589
  return {
553
590
  start: (port) =>
554
591
  new Promise<void>((resolve, reject) => {
555
- server.once("error", reject)
592
+ const onError = (error: Error) => reject(error)
593
+ server.once("error", onError)
556
594
  const options = { ...DEFAULT_LISTEN_OPTIONS, ...deps.listenOptions }
557
- server.listen({ port, host: "127.0.0.1", ...options }, () => resolve())
595
+ server.listen({ port, host: "127.0.0.1", ...options }, () => {
596
+ // The temporary bind-error listener must not linger after a successful
597
+ // listen; otherwise it accumulates on repeated start attempts.
598
+ server.removeListener("error", onError)
599
+ resolve()
600
+ })
558
601
  }),
559
602
  close: () =>
560
603
  new Promise<void>((resolve, reject) => {
package/src/shared.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  /** The two CodeBuddy sites. Pure type shared by server and GUI bundles. */
2
2
  export type Site = "cn" | "intl"
3
3
 
4
+ /** Fixed local proxy port. Provider baseURLs in opencode.jsonc are pinned to it. */
5
+ export const PROXY_PORT = 7688
6
+
4
7
  /** A brief account identity sent to the GUI. Never carries a token. */
5
8
  export interface AccountBrief {
6
9
  id: string