opencode-codebuddy-quota 0.1.0 → 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.
@@ -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
+ }
@@ -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
+ }