opencode-codebuddy-quota 0.1.0 → 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.
@@ -0,0 +1,306 @@
1
+ import { HEALTH_BODY, processNonce, 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
+ /** In-flight close of the previous server; a new cold bind waits for it. */
18
+ closing: Promise<void> | null
19
+ }
20
+
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")
23
+ const DEFAULT_GRACE_MS = 8000
24
+ const DEFAULT_PROBE_MS = 5000
25
+ const PROBE_TIMEOUT_MS = 2000
26
+
27
+ /**
28
+ * The exact health payload proxy.ts serves. Parse the exported wire body once
29
+ * so the probe compares against the shared contract instead of a copy of the
30
+ * literal.
31
+ */
32
+ const HEALTH_FIELDS = JSON.parse(HEALTH_BODY) as { status: string; service: string }
33
+
34
+ type GlobalWithOwner = Record<PropertyKey, GatewayOwnerState | undefined>
35
+
36
+ function readOwner(): GatewayOwnerState | undefined {
37
+ return (globalThis as unknown as GlobalWithOwner)[OWNER_KEY]
38
+ }
39
+
40
+ function owner(): GatewayOwnerState {
41
+ const existing = readOwner()
42
+ if (existing) return existing
43
+ const created: GatewayOwnerState = {
44
+ server: null,
45
+ refs: 0,
46
+ closeTimer: null,
47
+ generation: 0,
48
+ probeTimer: null,
49
+ starting: null,
50
+ closing: null,
51
+ }
52
+ ;(globalThis as unknown as GlobalWithOwner)[OWNER_KEY] = created
53
+ return created
54
+ }
55
+
56
+ export interface EnsureGatewayDeps {
57
+ port: number
58
+ createServer: () => ProxyServer
59
+ start: (s: ProxyServer, port: number) => Promise<void>
60
+ log: (s: string) => void
61
+ /** Injected health probe; defaults to an HTTP GET of `/health`. */
62
+ probe?: () => Promise<boolean>
63
+ /** Probe interval in milliseconds (default 5000). */
64
+ probeMs?: number
65
+ /** Injected fetch for the default probe, so tests never touch the network. */
66
+ fetchImpl?: typeof fetch
67
+ }
68
+
69
+ export interface ReleaseGatewayDeps {
70
+ log: (s: string) => void
71
+ graceMs?: number
72
+ }
73
+
74
+ /** A throwing injected logger must never break ownership bookkeeping. */
75
+ function safeLog(log: (s: string) => void, message: string): void {
76
+ try {
77
+ log(message)
78
+ } catch {
79
+ // ignore
80
+ }
81
+ }
82
+
83
+ /** Node-style EADDRINUSE, matched by code or by the usual message text. */
84
+ function isEaddrinuse(error: unknown): boolean {
85
+ if ((error as { code?: unknown } | null)?.code === "EADDRINUSE") return true
86
+ const text = String((error as { message?: unknown } | null)?.message ?? error ?? "")
87
+ return /EADDRINUSE|address already in use/i.test(text)
88
+ }
89
+
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
+ */
96
+ function makeDefaultProbe(deps: EnsureGatewayDeps): () => Promise<boolean> {
97
+ const fetchImpl = deps.fetchImpl ?? fetch
98
+ let foreignReported = false
99
+ return async () => {
100
+ try {
101
+ const response = await fetchImpl(`http://127.0.0.1:${deps.port}/health`, {
102
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
103
+ })
104
+ if (response.status !== 200) return false
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
124
+ } catch {
125
+ return false
126
+ }
127
+ }
128
+ }
129
+
130
+ /**
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.
135
+ */
136
+ function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void {
137
+ if (state.probeTimer !== null) {
138
+ clearInterval(state.probeTimer)
139
+ state.probeTimer = null
140
+ }
141
+ const probe = deps.probe ?? makeDefaultProbe(deps)
142
+ const timer = setInterval(() => {
143
+ void (async () => {
144
+ let healthy = false
145
+ try {
146
+ healthy = await probe()
147
+ } catch (error) {
148
+ const reason = String((error as Error)?.message ?? error)
149
+ safeLog(deps.log, `gateway probe error: ${reason}`)
150
+ return
151
+ }
152
+ if (!healthy) return
153
+ clearInterval(timer)
154
+ if (state.probeTimer === timer) state.probeTimer = null
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)")
160
+ })()
161
+ }, deps.probeMs ?? DEFAULT_PROBE_MS)
162
+ // Do not keep the process alive solely for the backstop probe.
163
+ timer.unref?.()
164
+ state.probeTimer = timer
165
+ }
166
+
167
+ /**
168
+ * Acquire the shared gateway. A live server is returned as-is — no re-bind and
169
+ * no second `start`, so a plugin reload never opens a listen gap on the port.
170
+ * A pending close is cancelled because a new holder has arrived.
171
+ *
172
+ * Create/start failures roll the ref count back. A non-EADDRINUSE failure is
173
+ * rethrown unchanged; EADDRINUSE does not claim ownership (returns null) and
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).
177
+ */
178
+ export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServer | null> {
179
+ const state = owner()
180
+ state.refs++
181
+ if (state.closeTimer !== null) {
182
+ clearTimeout(state.closeTimer)
183
+ state.closeTimer = null
184
+ }
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
190
+ // A concurrent cold start must not race a second bind on the same port.
191
+ // Everyone arriving while `starting` is pending awaits the same promise, so
192
+ // start is invoked once and every caller observes the same outcome. The
193
+ // shared promise normalizes EADDRINUSE to `null` exactly once; each caller
194
+ // below rolls back its *own* ref when no server was actually acquired.
195
+ if (state.starting === null) {
196
+ state.starting = (async () => {
197
+ try {
198
+ const server = deps.createServer()
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
+ }
207
+ state.server = server
208
+ return server
209
+ } catch (error) {
210
+ if (isEaddrinuse(error)) {
211
+ safeLog(deps.log, "gateway port in use; probing for recovery")
212
+ startProbeLoop(state, deps)
213
+ return null
214
+ }
215
+ throw error
216
+ }
217
+ })()
218
+ }
219
+ const starting = state.starting
220
+ try {
221
+ const server = await starting
222
+ if (server === null) state.refs-- // EADDRINUSE: this caller never owned a server
223
+ return server
224
+ } catch (error) {
225
+ state.refs-- // failed bind: roll back this caller's own ref
226
+ throw error
227
+ } finally {
228
+ if (state.starting === starting) state.starting = null
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Release one holder. The server is closed only after the last holder is gone
234
+ * AND a grace window has passed, so a reload's release/ensure pair does not
235
+ * tear down a listener that is immediately re-acquired.
236
+ *
237
+ * The generation is captured when the timer is scheduled: if a later
238
+ * release/ensure cycle changes it, a stale timer that still runs must not
239
+ * close a server bound by that newer cycle.
240
+ */
241
+ export function releaseGateway(deps: ReleaseGatewayDeps): void {
242
+ const state = owner()
243
+ // An EADDRINUSE ensure returns null without holding a ref, but Task 4 still
244
+ // disposes that null proxy. Clamp so such a redundant release cannot underflow
245
+ // and permanently prevent a later last-holder release from reaching zero.
246
+ // A redundant release must also leave `generation` untouched: bumping it would
247
+ // invalidate an already-scheduled close timer and leak the port via a different
248
+ // path. Only a real holder drop advances the generation.
249
+ const hadHolder = state.refs > 0
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
+ }
261
+ state.generation++
262
+ state.refs = Math.max(0, state.refs - 1)
263
+ if (state.refs !== 0) return
264
+
265
+ const generation = state.generation
266
+ if (state.closeTimer !== null) clearTimeout(state.closeTimer)
267
+ state.closeTimer = setTimeout(() => {
268
+ state.closeTimer = null
269
+ if (state.refs !== 0 || state.generation !== generation || state.server === null) return
270
+ const server = state.server
271
+ state.server = null
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) => {
276
+ const reason = String((error as Error)?.message ?? error)
277
+ try {
278
+ deps.log(`gateway close error: ${reason}`)
279
+ } catch {
280
+ // A throwing injected logger must not turn into an unhandled rejection.
281
+ }
282
+ })
283
+ state.closing = closing
284
+ void closing.finally(() => {
285
+ if (state.closing === closing) state.closing = null
286
+ })
287
+ }, deps.graceMs ?? DEFAULT_GRACE_MS)
288
+ }
289
+
290
+ /**
291
+ * Drop the process-wide state and clear any pending timers. Test isolation
292
+ * only: a fresh owner is lazily created by the next ensure/release/ref-count
293
+ * call.
294
+ */
295
+ export function resetGatewayOwnerForTests(): void {
296
+ const state = readOwner()
297
+ if (state === undefined) return
298
+ if (state.closeTimer !== null) clearTimeout(state.closeTimer)
299
+ if (state.probeTimer !== null) clearInterval(state.probeTimer)
300
+ delete (globalThis as unknown as GlobalWithOwner)[OWNER_KEY]
301
+ }
302
+
303
+ /** Diagnostic/test hook: number of live holders of the shared gateway. */
304
+ export function getGatewayRefCount(): number {
305
+ return owner().refs
306
+ }
@@ -0,0 +1,74 @@
1
+ import type { ensureGateway, releaseGateway } from "./gateway-owner"
2
+ import type { ProxyServer } from "./proxy"
3
+ import { PROXY_PORT } from "../shared"
4
+
5
+ /**
6
+ * Pure startup wiring: acquire the shared gateway, register the RPC handlers,
7
+ * and hand back a dispose that only drops one owner reference. All deps are
8
+ * injected so this can be tested without binding a port or touching `ctx`.
9
+ */
10
+ export interface SetupGatewayDeps {
11
+ ensureGateway: typeof ensureGateway
12
+ releaseGateway: typeof releaseGateway
13
+ createServer: () => ProxyServer
14
+ register: () => Promise<{ dispose(): void }>
15
+ log: (s: string) => void
16
+ }
17
+
18
+ export interface GatewaySetup {
19
+ proxy: ProxyServer | null
20
+ dispose: () => Promise<void>
21
+ }
22
+
23
+ /**
24
+ * The owner handles create/start failure bookkeeping (including its own ref
25
+ * rollback), so only a failure AFTER a successful ensure needs a matching
26
+ * release here. Closing the shared server is the owner's grace-period job;
27
+ * dispose must never close it directly.
28
+ */
29
+ export async function setupGateway(deps: SetupGatewayDeps): Promise<GatewaySetup> {
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
+ }
53
+
54
+ try {
55
+ await deps.register()
56
+ } catch (error) {
57
+ if (holdsRef) await deps.releaseGateway({ log: deps.log })
58
+ throw error
59
+ }
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
66
+ return {
67
+ proxy,
68
+ dispose: async () => {
69
+ if (released) return
70
+ released = true
71
+ if (holdsRef) await deps.releaseGateway({ log: deps.log })
72
+ },
73
+ }
74
+ }
@@ -1,26 +1,26 @@
1
- /**
2
- * A warning sink that reports each distinct message once per process.
3
- *
4
- * Import runs at plugin load and can emit the same "provider X has no entry for
5
- * Y" for several models at once; deduping keeps the console readable. Logging
6
- * must also never be the thing that breaks a caller: a throwing writer is
7
- * swallowed.
8
- */
9
- export function createDedupedLogger(
10
- write: (line: string) => void,
11
- prefix?: string,
12
- ): (message: string) => void {
13
- const seen = new Set<string>()
14
-
15
- return (message: string) => {
16
- // Dedupe on the raw message, not the formatted line, so changing the
17
- // prefix later does not re-emit everything.
18
- if (seen.has(message)) return
19
- seen.add(message)
20
- try {
21
- write(prefix ? `${prefix} ${message}` : message)
22
- } catch {
23
- /* a broken writer must not become a broken transform */
24
- }
25
- }
26
- }
1
+ /**
2
+ * A warning sink that reports each distinct message once per process.
3
+ *
4
+ * Import runs at plugin load and can emit the same "provider X has no entry for
5
+ * Y" for several models at once; deduping keeps the console readable. Logging
6
+ * must also never be the thing that breaks a caller: a throwing writer is
7
+ * swallowed.
8
+ */
9
+ export function createDedupedLogger(
10
+ write: (line: string) => void,
11
+ prefix?: string,
12
+ ): (message: string) => void {
13
+ const seen = new Set<string>()
14
+
15
+ return (message: string) => {
16
+ // Dedupe on the raw message, not the formatted line, so changing the
17
+ // prefix later does not re-emit everything.
18
+ if (seen.has(message)) return
19
+ seen.add(message)
20
+ try {
21
+ write(prefix ? `${prefix} ${message}` : message)
22
+ } catch {
23
+ /* a broken writer must not become a broken transform */
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,136 @@
1
+ import { createHash } from "node:crypto"
2
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ /** A verified local model cache, persisted across process restarts. */
6
+ export interface ReadyFlag {
7
+ version: number
8
+ model: string
9
+ revision: string
10
+ /** filename -> official HuggingFace sha256 */
11
+ hashes: Record<string, string>
12
+ }
13
+
14
+ /** Bump this when `ReadyFlag` changes shape; old flags are then treated as absent. */
15
+ export const FLAGS_VERSION = 1
16
+
17
+ function readyFlagPath(cacheDir: string): string {
18
+ return join(cacheDir, "ready.json")
19
+ }
20
+
21
+ /**
22
+ * transformers.js FS cache stores a model's files directly under
23
+ * `path.join(env.cacheDir, pathJoin(modelId, filename))` — no `models--`
24
+ * prefix and no `blobs/` subdirectory.
25
+ */
26
+ function modelDir(cacheDir: string, model: string): string {
27
+ return join(cacheDir, model)
28
+ }
29
+
30
+ function isReadyFlag(value: unknown): value is ReadyFlag {
31
+ if (typeof value !== "object" || value === null) return false
32
+ const flag = value as Record<string, unknown>
33
+ if (flag.version !== FLAGS_VERSION) return false
34
+ if (typeof flag.model !== "string" || typeof flag.revision !== "string") return false
35
+ if (typeof flag.hashes !== "object" || flag.hashes === null || Array.isArray(flag.hashes)) return false
36
+ return Object.values(flag.hashes).every((hash) => typeof hash === "string")
37
+ }
38
+
39
+ /**
40
+ * A missing, corrupt or outdated flag is indistinguishable from "never warmed":
41
+ * the caller retries instead of trusting a half-written marker. Never throws.
42
+ */
43
+ export function readReadyFlag(deps: { cacheDir: string }): ReadyFlag | null {
44
+ try {
45
+ const raw = readFileSync(readyFlagPath(deps.cacheDir), "utf8")
46
+ const parsed: unknown = JSON.parse(raw)
47
+ return isReadyFlag(parsed) ? parsed : null
48
+ } catch {
49
+ return null
50
+ }
51
+ }
52
+
53
+ /** Commit via rename so a reader never observes a partially written flag. */
54
+ export function writeReadyFlag(flag: ReadyFlag, deps: { cacheDir: string }): void {
55
+ const path = readyFlagPath(deps.cacheDir)
56
+ const tmp = `${path}.tmp.${process.pid}`
57
+ mkdirSync(deps.cacheDir, { recursive: true })
58
+ try {
59
+ writeFileSync(tmp, JSON.stringify(flag, null, 2))
60
+ renameSync(tmp, path)
61
+ } catch (error) {
62
+ try { unlinkSync(tmp) } catch { /* nothing to clean up */ }
63
+ throw error
64
+ }
65
+ }
66
+
67
+ /** Ask the Hub for the authoritative sha256 of every LFS-backed model file. */
68
+ export async function fetchOfficialHashes(
69
+ model: string,
70
+ deps: { fetchImpl?: typeof fetch } = {},
71
+ ): Promise<{ revision: string; hashes: Record<string, string> }> {
72
+ const doFetch = deps.fetchImpl ?? fetch
73
+ const res = await doFetch(`https://huggingface.co/api/models/${model}?blobs=true`)
74
+ if (!res.ok) throw new Error(`HuggingFace hash lookup failed for ${model}: HTTP ${res.status}`)
75
+ const json = (await res.json()) as {
76
+ sha?: string
77
+ siblings?: { rfilename?: string; lfs?: { sha256?: string } }[]
78
+ }
79
+ const hashes: Record<string, string> = {}
80
+ for (const sibling of json.siblings ?? []) {
81
+ const sha256 = sibling.lfs?.sha256
82
+ if (typeof sibling.rfilename === "string" && typeof sha256 === "string" && sha256 !== "") {
83
+ hashes[sibling.rfilename] = sha256
84
+ }
85
+ }
86
+ return { revision: typeof json.sha === "string" ? json.sha : "main", hashes }
87
+ }
88
+
89
+ export interface VerifyCacheDeps {
90
+ cacheDir: string
91
+ model: string
92
+ official: Record<string, string>
93
+ listFiles: (dir: string) => string[]
94
+ hashFile: (path: string) => string
95
+ }
96
+
97
+ /**
98
+ * Only LFS-backed files (those with an official sha256 from the Hub) are verified:
99
+ * each must be present locally with the expected hash. Small non-LFS files have
100
+ * no official hash and are deliberately ignored, never treated as bad. Bad
101
+ * entries are returned as full paths so the caller can delete them and re-download.
102
+ */
103
+ export function verifyCache(deps: VerifyCacheDeps): { ok: boolean; badFiles: string[] } {
104
+ const dir = modelDir(deps.cacheDir, deps.model)
105
+ let files: string[]
106
+ try {
107
+ files = deps.listFiles(dir)
108
+ } catch {
109
+ return { ok: false, badFiles: [] }
110
+ }
111
+
112
+ const local = new Set(files)
113
+ const badFiles: string[] = []
114
+ for (const [filename, expectedHash] of Object.entries(deps.official)) {
115
+ const path = join(dir, filename)
116
+ if (!local.has(filename)) {
117
+ badFiles.push(path)
118
+ continue
119
+ }
120
+ let actualHash: string
121
+ try {
122
+ actualHash = deps.hashFile(path)
123
+ } catch {
124
+ badFiles.push(path)
125
+ continue
126
+ }
127
+ if (actualHash !== expectedHash) badFiles.push(path)
128
+ }
129
+
130
+ return { ok: badFiles.length === 0, badFiles }
131
+ }
132
+
133
+ /** Content hash used by the default `hashFile` seam in callers. */
134
+ export function sha256Of(contents: string | Buffer): string {
135
+ return createHash("sha256").update(contents).digest("hex")
136
+ }