@geohar/pi-svg-mcp 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ // Resolve the `sharedserver` binary, fetching it when none is usable.
2
+ //
3
+ // VENDORED FILE. This is copied byte-identical into the consuming OpenCode plugins
4
+ // (cribsheet, svg-mcp) by their scripts/sync-vendored.sh, so the drift check is a plain
5
+ // diff. There is no way to share it as a dependency without coupling their versions to
6
+ // sharedserver's — see plugins/claude/bin/sharedserver for the same reasoning on the
7
+ // shell side. Edit it HERE; consumers re-sync.
8
+ //
9
+ // Everything repo-specific arrives through ResolveConfig rather than being hardcoded,
10
+ // mirroring bin/sharedserver.conf.
11
+
12
+ import { spawnSync } from "node:child_process"
13
+ import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs"
14
+ import { homedir } from "node:os"
15
+ import { join } from "node:path"
16
+
17
+ export type LogFn = (level: "info" | "warn" | "error", message: string) => void
18
+ export type ToastFn = (variant: "success" | "warning" | "error", message: string) => void
19
+
20
+ export type ResolveConfig = {
21
+ /** Prefix for user-facing messages. Default "sharedserver". */
22
+ label?: string
23
+ /** Minimum acceptable version. Defaults to pkgVersion (lockstep). */
24
+ minVersion?: string
25
+ /** Installer to fetch. Defaults to the release pinned to pkgVersion. */
26
+ installerUrl?: string
27
+ /** The host package's own version — only meaningful in lockstep mode. */
28
+ pkgVersion?: string
29
+ }
30
+
31
+ /** Oldest release these plugins are correct against: 0.5.0 added the PID-reuse guard,
32
+ * without which a recycled client PID can hold a server open indefinitely. */
33
+ const HARDCODED_FLOOR = "0.5.0"
34
+
35
+ const CANDIDATE_BINARIES = [
36
+ "sharedserver",
37
+ join(homedir(), ".cargo", "bin", "sharedserver"),
38
+ join(homedir(), ".local", "bin", "sharedserver"),
39
+ "/usr/local/bin/sharedserver",
40
+ "/opt/homebrew/bin/sharedserver",
41
+ ]
42
+
43
+ function parseVersion(text: string): [number, number, number] | undefined {
44
+ const m = text.match(/(\d+)\.(\d+)\.(\d+)/)
45
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : undefined
46
+ }
47
+
48
+ function gte(a: [number, number, number], b: [number, number, number]): boolean {
49
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]
50
+ return true
51
+ }
52
+
53
+ function versionOf(candidate: string, env: NodeJS.ProcessEnv): [number, number, number] | undefined {
54
+ const r = spawnSync(candidate, ["--version"], { env })
55
+ if (r.error) return undefined
56
+ return parseVersion(`${r.stdout?.toString() ?? ""}${r.stderr?.toString() ?? ""}`)
57
+ }
58
+
59
+ /** Synchronous sleep — this path runs before anything can be awaited, so the lock wait
60
+ * cannot use timers. Atomics.wait blocks without spinning. */
61
+ function sleepSync(ms: number): void {
62
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
63
+ }
64
+
65
+ /** First sharedserver found at ANY version, or undefined. */
66
+ function probeAny(override: string | undefined, env: NodeJS.ProcessEnv): string | undefined {
67
+ const candidates = [override, env.SHAREDSERVER_BIN, ...CANDIDATE_BINARIES].filter(
68
+ (v): v is string => typeof v === "string" && v.length > 0,
69
+ )
70
+ for (const candidate of candidates) {
71
+ if (candidate.includes("/")) {
72
+ if (existsSync(candidate)) return candidate
73
+ continue
74
+ }
75
+ // Presence is "spawn did not fail", NOT "exited 0" — a build that rejects some
76
+ // flag is still present.
77
+ if (!spawnSync(candidate, ["--version"], { stdio: "ignore", env }).error) return candidate
78
+ }
79
+ return undefined
80
+ }
81
+
82
+ /** Download and run the cargo-dist installer, then re-probe. */
83
+ function installPinned(
84
+ cfg: Required<Pick<ResolveConfig, "label">> & ResolveConfig,
85
+ url: string,
86
+ what: string,
87
+ env: NodeJS.ProcessEnv,
88
+ log?: LogFn,
89
+ toast?: ToastFn,
90
+ ): string | undefined {
91
+ // The SAME lock directory as the shell shim — cross-client coordination, so a
92
+ // Claude session and an OpenCode session starting together do not race.
93
+ const lockdir = join(env.TMPDIR || "/tmp", ".sharedserver-install.lock")
94
+ let haveLock = false
95
+ try {
96
+ mkdirSync(lockdir)
97
+ haveLock = true
98
+ } catch {
99
+ const deadline = Date.now() + 20_000
100
+ while (existsSync(lockdir) && Date.now() < deadline) sleepSync(250)
101
+ const after = probeAny(undefined, env)
102
+ if (after) return after
103
+ try {
104
+ mkdirSync(lockdir)
105
+ haveLock = true
106
+ } catch {
107
+ log?.("warn", `${cfg.label}: another process is installing sharedserver and did not finish; remove the stale lock if this persists: ${lockdir}`)
108
+ return undefined
109
+ }
110
+ }
111
+
112
+ try {
113
+ // Re-probe under the lock: the winner may have finished while we waited.
114
+ const already = probeAny(undefined, env)
115
+ const floor = parseVersion(cfg.minVersion ?? HARDCODED_FLOOR)
116
+ if (already) {
117
+ const v = versionOf(already, env)
118
+ if (v && floor && gte(v, floor)) return already
119
+ }
120
+
121
+ // Download to a file, then run it. `curl … | sh` would report success on a 404,
122
+ // since a pipeline's status is sh's; spawnSync uses no shell, so this is exact.
123
+ const script = join(lockdir, "installer.sh")
124
+ const dl = spawnSync("curl", ["--proto", "=https", "--tlsv1.2", "-LsSf", url, "-o", script], { env })
125
+ if (dl.error || dl.status !== 0) {
126
+ const msg = `${cfg.label}: could not download the sharedserver installer (${what})`
127
+ log?.("warn", msg)
128
+ toast?.("warning", msg)
129
+ return undefined
130
+ }
131
+ if (!existsSync(script) || statSync(script).size === 0) {
132
+ log?.("warn", `${cfg.label}: the downloaded sharedserver installer was empty`)
133
+ return undefined
134
+ }
135
+
136
+ // cargo-dist embeds the expected sha256 but looks up only `sha256sum` and SKIPS
137
+ // verification when missing — i.e. always, on macOS. Give it one (identical
138
+ // output) rather than execute an unverified binary.
139
+ let runEnv = env
140
+ if (spawnSync("sh", ["-c", "command -v sha256sum"], { stdio: "ignore" }).status !== 0) {
141
+ if (spawnSync("sh", ["-c", "command -v shasum"], { stdio: "ignore" }).status !== 0) {
142
+ log?.("warn", `${cfg.label}: refusing to install sharedserver — no sha256sum or shasum to verify the download`)
143
+ return undefined
144
+ }
145
+ writeFileSync(join(lockdir, "sha256sum"), '#!/bin/sh\nexec shasum -a 256 "$@"\n', { mode: 0o755 })
146
+ runEnv = { ...env, PATH: `${lockdir}:${env.PATH ?? ""}` }
147
+ }
148
+
149
+ const run = spawnSync("sh", [script], { env: runEnv, stdio: "ignore" })
150
+ if (run.error || run.status !== 0) {
151
+ log?.("warn", `${cfg.label}: the sharedserver installer ran but failed`)
152
+ return undefined
153
+ }
154
+ return probeAny(undefined, env)
155
+ } finally {
156
+ if (haveLock) {
157
+ try {
158
+ rmSync(lockdir, { recursive: true, force: true })
159
+ } catch {
160
+ /* best effort — a leaked lock costs the next run its bounded wait */
161
+ }
162
+ }
163
+ }
164
+ }
165
+
166
+ /** Resolve the sharedserver binary, fetching a release when nothing usable is present.
167
+ *
168
+ * Behaviourally identical to plugins/claude/bin/sharedserver — same ladder, floor,
169
+ * lock and degrade-rather-than-die fallback, so a user running both clients gets the
170
+ * same answer to "which sharedserver am I on, and why". */
171
+ export function resolveSharedserver(
172
+ cfg: ResolveConfig,
173
+ override: string | undefined,
174
+ env: NodeJS.ProcessEnv,
175
+ log?: LogFn,
176
+ toast?: ToastFn,
177
+ ): string | undefined {
178
+ const label = cfg.label ?? "sharedserver"
179
+ const minVersion = cfg.minVersion ?? cfg.pkgVersion ?? HARDCODED_FLOOR
180
+ const url =
181
+ cfg.installerUrl ??
182
+ (cfg.pkgVersion
183
+ ? `https://github.com/georgeharker/sharedserver/releases/download/v${cfg.pkgVersion}/sharedserver-installer.sh`
184
+ : "https://github.com/georgeharker/sharedserver/releases/latest/download/sharedserver-installer.sh")
185
+ const what = cfg.installerUrl || !cfg.pkgVersion ? "the latest release" : `v${cfg.pkgVersion}`
186
+ const resolved = { ...cfg, label, minVersion }
187
+ const floor = parseVersion(minVersion)
188
+
189
+ // An explicit binary / SHAREDSERVER_BIN is never second-guessed: the user named a
190
+ // specific one, so quietly downloading a different one is the wrong answer.
191
+ const explicit = override ?? env.SHAREDSERVER_BIN
192
+ if (explicit) {
193
+ const present = explicit.includes("/")
194
+ ? existsSync(explicit)
195
+ : !spawnSync(explicit, ["--version"], { stdio: "ignore", env }).error
196
+ if (present) {
197
+ const v = versionOf(explicit, env)
198
+ if (v && floor && !gte(v, floor)) {
199
+ const msg = `${label}: sharedserver at ${explicit} is ${v.join(".")}; this plugin expects >= ${minVersion}. Using it anyway because you set it explicitly.`
200
+ log?.("warn", msg)
201
+ toast?.("warning", msg)
202
+ }
203
+ return explicit
204
+ }
205
+ }
206
+
207
+ const found = probeAny(override, env)
208
+ if (found) {
209
+ const v = versionOf(found, env)
210
+ if (v && floor && gte(v, floor)) return found
211
+ // Too old: fetch, but remember this one — if the download fails we would rather
212
+ // run the old binary than nothing.
213
+ const msg = `${label}: sharedserver at ${found} is ${v?.join(".") ?? "an unknown version"}; this plugin expects >= ${minVersion}. Fetching ${what}. To keep your own build, set SHAREDSERVER_BIN=${found}`
214
+ log?.("warn", msg)
215
+ toast?.("warning", msg)
216
+ return installPinned(resolved, url, what, env, log, toast) ?? found
217
+ }
218
+
219
+ log?.("info", `${label}: no usable sharedserver found; fetching ${what} (one time). This needs no Rust toolchain.`)
220
+ return installPinned(resolved, url, what, env, log, toast)
221
+ }