@gemus/mcp-proxy 0.1.8 → 0.1.10

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/src/proxy.mjs CHANGED
@@ -1,417 +1,42 @@
1
1
  #!/usr/bin/env node
2
- // @gemus/mcp-proxy local stdio<->HTTP MCP proxy for Codex desktop (Issue #1751, P1).
3
- //
4
- // Codex (stdio) <-> this proxy <-> remote gemus /api/mcp (streamable HTTP, Bearer mak_ key).
5
- // The proxy is a TRANSPARENT JSON-RPC passthrough (tools + resources + notifications all relay
6
- // untouched) that additionally TAPS execute/batch_execute to observe client-delivered image
7
- // backfill anchors, then at turn end backfills codex imagegen output into the planned gen-* nodes.
8
- // Codex does no auth for stdio MCP servers, so THIS process owns upstream auth (the user's mak_ key).
9
- //
10
- // Turn-end backfill has two triggers:
11
- // • Stop hook (trusted) → loopback HTTP POST /backfill { transcript_path, thread_id } → claim path.
12
- // • idle-timer fallback (untrusted hook) → salvageOnly (orphan-only). Both idempotent via seen-set.
13
- //
14
- // Validated end-to-end on 2026-07-06 (codex-cli 0.142.2, real dev /api/mcp): transparent passthrough
15
- // of all 12 gemus tools; codex spawns one proxy per session; real tool-calls tapped with workflowId
16
- // (from arguments) + turn/thread identity (from _meta.x-codex-turn-metadata). Step-0.4: plugin-bundled
17
- // Stop hook fires after /hooks trust. The plugin-scoped Companion forwards GEMUS_KEY from the user
18
- // environment, so neither the plugin config nor generated commands contain a literal key.
19
- // See docs/plans/1751-codex-desktop-companion.md.
20
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
21
- import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
22
- import http from 'node:http'
23
- import os from 'node:os'
24
- import path from 'node:path'
25
- import fs from 'node:fs'
26
- import { randomBytes } from 'node:crypto'
27
- import { createBackfiller, injectSteering } from './backfill.mjs'
28
- import { unwrapMcpContent } from '@gemus/codex-backfill-core'
29
- import { buildProxyUpstreamHeaders } from './mcpHeaders.mjs'
30
- import { createFailFast, isJsonRpcResponse } from './failFast.mjs'
31
- import {
32
- assertGemusKey,
33
- createFatalReporter,
34
- createShutdownCoordinator,
35
- safeEndpointLabel,
36
- startProxy,
37
- } from './startup.mjs'
2
+ import { pathToFileURL } from 'node:url'
38
3
 
39
- const KEY = process.env.GEMUS_KEY || ''
40
- const GEMUS_URL = process.env.GEMUS_URL || 'https://gemus.ai/api/mcp'
41
- const LOG = process.env.PROXY_LOG // optional debug log path
42
- const log = (dir, m) => {
43
- if (!LOG) return
44
- try {
45
- fs.appendFileSync(LOG, `[${new Date().toISOString()}] ${dir} ${typeof m === 'string' ? m : JSON.stringify(m).slice(0, 1000)}\n`)
46
- } catch {
47
- // Debug logging is optional and must never affect proxy lifecycle.
4
+ class ProxyUsageError extends Error {
5
+ constructor() {
6
+ super('Usage: gemus-mcp-proxy [setup]')
7
+ this.code = 'PROXY_USAGE'
48
8
  }
49
9
  }
50
10
 
51
- const reportFatal = createFatalReporter({
52
- secret: KEY,
53
- writeStderr: (message) => fs.writeSync(2, message),
54
- writeLog: (message) => log('FATAL', message),
55
- })
56
- let shutdown
57
- let shutdownRequested = false
58
- function terminateFatally(error) {
59
- reportFatal(error)
60
- shutdownRequested = true
61
- if (shutdown) return shutdown(1)
62
- process.exit(1)
63
- }
64
- process.on('uncaughtException', (error) => { void terminateFatally(error) })
65
- process.on('unhandledRejection', (reason) => { void terminateFatally(reason) })
66
-
67
- try {
68
- assertGemusKey(KEY)
69
- } catch (error) {
70
- terminateFatally(error)
71
- }
72
-
73
- const SERVER_ORIGIN = GEMUS_URL.replace(/\/api\/mcp\/?$/, '') // core delivery appends /api/mcp itself
74
- const CODEX_HOME = process.env.CODEX_HOME || path.join(os.homedir(), '.codex')
75
- // turn-idle fallback (untrusted-hook path). Default 3min: imagegen alone runs 30-60s with NO MCP tool
76
- // calls, so a short idle looks like "turn ended" mid-generation and fires prematurely. A trusted Stop
77
- // hook fires at turn end and clears this timer, so trusted users never hit it (#1751 real-machine fix).
78
- const IDLE_MS = Number(process.env.PROXY_BACKFILL_IDLE_MS) || 180_000
79
- // footprint-0 注入交付超时(#1756 Layer 1a)。必须 ≥ 平台对 codex-imagen 回填节点的同步等待上限
80
- // (deriveWaitTimeoutMs('gen-image-generation')=180s,见 src/server/generation/waitTimeout.ts),否则
81
- // proxy 先超时 → 假失败 → orphan 回退 → 同图重复交付。240s = 180s + 余量。别调到 180s 以下。
82
- const INJECT_TIMEOUT_MS = Number(process.env.PROXY_INJECT_TIMEOUT_MS) || 240_000
83
-
84
- // ── footprint-0 交付注入(#1756 Layer 1a)─────────────────────────────────────────────────────────
85
- // 交付/orphan 不再每图新开 key-only session(connect-per-call,抢 KEY_ONLY_SESSION_CAP 槽),而是把
86
- // execute/canvas_edit 的 tools/call **注入到 proxy 已建好、已计入 cap 的那条 upstream 连接**上(footprint
87
- // 0)——即便 cap 被泄漏填满也能交付。注入用字符串 id 命名空间 `gemus-bf-*`(绝不撞 Codex 的数字 id),
88
- // 响应在 upstream.onmessage 里按 id 自消费、不转发给 Codex。`upstream` 在下方声明,注入在 turn 末才调,
89
- // 故闭包内按调用时解析、无 TDZ 问题。
90
- /** in-flight 注入:id(string) → { settle }。settle 幂等收敛(响应/超时/取消/关停任一先到即结算)。 */
91
- const pendingInjections = new Map()
92
- let injectSeq = 0
93
-
94
- /** 把 JSON-RPC 响应转成与 core `callGemusTool` 逐字一致的 CallGemusToolResult 形状。 */
95
- function interpretInjection(m) {
96
- if (m?.error) return { ok: false, error: m.error.message || `MCP error ${m.error.code}` }
97
- const result = m?.result
98
- if (result && result.isError === true) {
99
- const first = Array.isArray(result.content) ? result.content[0] : undefined
100
- return { ok: false, error: (first && first.text) || 'MCP tool error' }
101
- }
102
- return { ok: true, result: unwrapMcpContent(result && result.content) }
103
- }
104
-
105
- /** @type {import('@gemus/codex-backfill-core').GemusToolCall} */
106
- function injectedCall(toolName, args, opts = {}) {
107
- const { progressToken, signal } = opts
108
- const id = `gemus-bf-${++injectSeq}`
109
- const req = {
110
- jsonrpc: '2.0',
111
- id,
112
- method: 'tools/call',
113
- params: { name: toolName, arguments: args, ...(progressToken ? { _meta: { progressToken } } : {}) },
11
+ export function validateProxyArgs(args = []) {
12
+ if (!Array.isArray(args) || args.length > 1 || (args.length === 1 && args[0] !== 'setup')) {
13
+ throw new ProxyUsageError()
114
14
  }
115
- return new Promise((resolve) => {
116
- const settle = (v) => {
117
- clearTimeout(timer)
118
- if (signal) signal.removeEventListener('abort', onAbort)
119
- pendingInjections.delete(id)
120
- resolve(v)
121
- }
122
- const onAbort = () => settle({ ok: false, error: 'aborted' })
123
- const timer = setTimeout(() => settle({ ok: false, timedOut: true, error: 'inject timeout' }), INJECT_TIMEOUT_MS)
124
- pendingInjections.set(id, { settle })
125
- if (signal) signal.addEventListener('abort', onAbort)
126
- upstream.send(req).catch((e) => settle({ ok: false, error: String(e) }))
127
- log('INJECT', { id, toolName, progressToken })
128
- })
129
15
  }
130
16
 
131
- const backfiller = createBackfiller({
132
- server: SERVER_ORIGIN,
133
- apiKey: KEY,
134
- codexHome: CODEX_HOME,
135
- call: injectedCall,
136
- log: (msg, obj) => log('BACKFILL', obj ? `${msg} ${JSON.stringify(obj)}` : msg),
137
- })
138
-
139
- // ── turn identity + request↔response correlation ───────────────────────────────────────────────
140
- // Step-0.4 capture: tool-call `_meta` + Stop-hook payload both carry `turn_id` + `session_id` (no
141
- // thread_id). Turn state keys on turn_id; session_id locates the rollout in the idle fallback.
142
- /** in-flight tools/call: jsonrpc id (string) → { turnKey, name } — so the server→client response
143
- * (which carries no _meta) can be attributed to its turn + tool. */
144
- const inflight = new Map()
145
- /** per-turn idle timer — turn-END fallback when no Stop hook fires (untrusted). Reset on activity. */
146
- const idleTimers = new Map()
147
- let sessionId // learned from first tool-call _meta.session_id; used for the hook discovery file
148
- let discoveryFile // <tmpdir>/gemus-proxy-<sessionId>.json — written once sessionId is known
149
-
150
- function metaOf(msg) {
151
- const meta = msg?.params?._meta?.['x-codex-turn-metadata']
152
- return {
153
- turnId: meta?.turn_id || meta?.turnId,
154
- sessionId: meta?.session_id || meta?.sessionId,
155
- }
156
- }
157
-
158
- function armIdleTimer(turnKey) {
159
- if (!turnKey) return
160
- const existing = idleTimers.get(turnKey)
161
- if (existing) clearTimeout(existing)
162
- const timer = setTimeout(() => {
163
- idleTimers.delete(turnKey)
164
- // salvageOnly fallback: turn went quiet with no Stop hook. Orphan any fresh images (never claim).
165
- // seen-set makes this a no-op if a hook already backfilled this turn.
166
- backfiller
167
- .backfillTurn({ turnKey, rolloutPath: null, salvageOnly: true })
168
- .catch((e) => log('IDLE-BACKFILL-ERR', String(e)))
169
- }, IDLE_MS)
170
- if (typeof timer.unref === 'function') timer.unref() // don't keep the process alive on this timer alone
171
- idleTimers.set(turnKey, timer)
172
- }
173
-
174
- function writeDiscoveryOnce() {
175
- if (discoveryFile || !sessionId || !hookPort || !hookToken) return
176
- discoveryFile = path.join(os.tmpdir(), `gemus-proxy-${sessionId}.json`)
177
- try {
178
- fs.writeFileSync(discoveryFile, JSON.stringify({ port: hookPort, token: hookToken }))
179
- log('DISCOVERY-WRITE', { discoveryFile, port: hookPort })
180
- } catch (e) {
181
- log('DISCOVERY-ERR', String(e))
182
- }
183
- }
184
-
185
- // injectSteering (imported) mutates the initialize response's `instructions` to tell codex not to
186
- // self-forward imagegen output — the one always-on steering channel in Mode B. See backfill.mjs.
187
- function steerOnInit(msg) {
188
- try {
189
- if (injectSteering(msg)) log('STEERING-INJECTED', { instructionsLen: msg.result.instructions.length })
190
- } catch (e) {
191
- log('STEERING-ERR', String(e))
192
- }
193
- }
194
-
195
- // ── taps (do not mutate the relayed messages) ──────────────────────────────────────────────────
196
- function tapClientToServer(msg) {
197
- try {
198
- if (msg?.method !== 'tools/call') return
199
- const { turnId, sessionId: sid } = metaOf(msg)
200
- if (sid && !sessionId) {
201
- sessionId = sid
202
- writeDiscoveryOnce()
203
- }
204
- if (turnId) armIdleTimer(turnId)
205
- const id = msg.id
206
- if (id === undefined || id === null) return // notifications: no response to correlate
207
- const name = msg.params?.name || ''
208
- inflight.set(String(id), { turnKey: turnId, name })
209
- backfiller.observeCall({ jsonrpcId: id, turnKey: turnId, sessionId: sid, name, args: msg.params?.arguments || {} })
210
- } catch (e) {
211
- log('TAP-C2S-ERR', String(e))
212
- }
213
- }
214
-
215
- function tapServerToClient(msg) {
216
- try {
217
- const id = msg?.id
218
- if (id === undefined || id === null) return
219
- const pending = inflight.get(String(id))
220
- if (!pending) return
221
- inflight.delete(String(id))
222
- if (!msg.result) return // errors: nothing to observe for claim tracking
223
- backfiller.observeResult({
224
- jsonrpcId: id,
225
- turnKey: pending.turnKey,
226
- name: pending.name,
227
- resultContent: msg.result?.content,
228
- })
229
- } catch (e) {
230
- log('TAP-S2C-ERR', String(e))
231
- }
232
- }
233
-
234
- // ── loopback Stop-hook endpoint (127.0.0.1:<random port> + per-run token) ──────────────────────
235
- let hookPort
236
- const hookToken = randomBytes(16).toString('hex')
237
- const hookServer = http.createServer((req, res) => {
238
- if (req.method !== 'POST' || !req.url?.startsWith('/backfill')) {
239
- res.writeHead(404).end()
240
- return
241
- }
242
- let body = ''
243
- req.on('data', (c) => {
244
- body += c
245
- if (body.length > 64 * 1024) req.destroy() // trivial DoS guard; payload is tiny JSON
246
- })
247
- req.on('end', () => {
248
- let payload
249
- try {
250
- payload = JSON.parse(body)
251
- } catch {
252
- res.writeHead(400).end()
253
- return
254
- }
255
- if (payload?.token !== hookToken) {
256
- res.writeHead(403).end()
257
- return
258
- }
259
- // Stop-hook payload (Step-0.4 capture): { session_id, turn_id, transcript_path, ... } — no thread_id.
260
- const turnKey = payload.turn_id || payload.turnId
261
- const sid = payload.session_id || payload.sessionId
262
- const rolloutPath = payload.transcript_path || payload.transcriptPath || null
263
- log('HOOK-BACKFILL', { turnKey, sid, rolloutPath })
264
- res.writeHead(200).end('ok')
265
- // A Stop hook backfilled this turn → cancel its idle-timer fallback (avoid a redundant salvage pass).
266
- const timer = idleTimers.get(turnKey)
267
- if (timer) { clearTimeout(timer); idleTimers.delete(turnKey) }
268
- // Stop hook fires post-flush → claim path (not salvage). Fire-and-forget; never throw.
269
- backfiller
270
- .backfillTurn({ turnKey, sessionId: sid, rolloutPath, salvageOnly: false })
271
- .catch((e) => log('HOOK-BACKFILL-ERR', String(e)))
272
- })
273
- })
274
- hookServer.on('error', (error) => {
275
- if (shutdownRequested) return
276
- void terminateFatally(error)
277
- })
278
- hookServer.listen(0, '127.0.0.1', () => {
279
- hookPort = hookServer.address().port
280
- log('HOOK-SERVER', { port: hookPort })
281
- writeDiscoveryOnce() // in case sessionId was already learned before listen resolved
282
- })
283
- if (typeof hookServer.unref === 'function') hookServer.unref()
284
-
285
- // ── transparent JSON-RPC passthrough (raw send/onmessage) ──────────────────────────────────────
286
- const stdio = new StdioServerTransport()
287
-
288
- // #2068 fail-fast: StreamableHTTPClientTransport.send() resolves before the upstream SSE result
289
- // arrives and only surfaces a stream death via a global, id-less `onerror` (no reconnect for POST).
290
- // The custom `fetch` wrapper parses each request's JSON-RPC id and, if the response stream dies
291
- // before that id's result crosses the wire, injects a JSON-RPC error so Codex fails in <2s instead
292
- // of hanging to its 300s timeout. onLost only injects to stdio — it does NOT tap: tapping here would
293
- // delete the proxy's `inflight` entry, so the DROP-AFTER-FAILFAST branch below could no longer let
294
- // backfill observe a late real result (env delivery on the still-open, idle-timed-out case).
295
- const failFast = createFailFast({
296
- idleTimeoutMs: Number(process.env.PROXY_FAILFAST_TIMEOUT_MS) || 120_000,
297
- log,
298
- onLost: (id, reason) => {
299
- const errObj = {
300
- jsonrpc: '2.0',
301
- id,
302
- error: { code: -32000, message: 'Gemus upstream stream disconnected before the tool result was delivered' },
303
- }
304
- log('FAILFAST-INJECT', { id, reason })
305
- stdio.send(errObj).catch((e) => log('ERR-stdio-send', String(e)))
306
- },
307
- })
308
-
309
- const upstream = new StreamableHTTPClientTransport(new URL(GEMUS_URL), {
310
- requestInit: { headers: buildProxyUpstreamHeaders(KEY) },
311
- fetch: failFast.fetch,
312
- })
313
-
314
- stdio.onmessage = (m) => {
315
- tapClientToServer(m)
316
- log('C->G', m)
317
- upstream.send(m).catch((error) => {
318
- if (m?.method === 'initialize') {
319
- void terminateFatally(error)
320
- return
321
- }
322
- log('ERR-http-send', String(error))
323
- })
324
- }
325
- upstream.onmessage = (m) => {
326
- // footprint-0 (#1756): our injected execute/canvas_edit responses carry a `gemus-bf-*` string id.
327
- // Self-consume them here (settle the pending injection) and DO NOT forward to Codex — Codex never
328
- // issued these calls, so it must never see the responses.
329
- if (typeof m?.id === 'string' && m.id.startsWith('gemus-bf-')) {
330
- const p = pendingInjections.get(m.id)
331
- if (p) p.settle(interpretInjection(m))
17
+ export async function main(args = process.argv.slice(2)) {
18
+ validateProxyArgs(args)
19
+ if (args[0] === 'setup') {
20
+ const { runSetup } = await import('./setup/cli.mjs')
21
+ await runSetup()
332
22
  return
333
23
  }
334
- // #1756 liveness heartbeat: our own `ping` pongs (gemus-ping-*) are self-consumed — Codex never
335
- // issued them, so it must never see the responses.
336
- if (typeof m?.id === 'string' && m.id.startsWith('gemus-ping-')) return
337
- // #2068 fail-fast bookkeeping. Gate on RESPONSE only (isJsonRpcResponse) — a server→client request
338
- // (elicitation/sampling) also carries an id that can collide with an in-flight tools/call id, and
339
- // must be forwarded to Codex untouched, never settled/dropped.
340
- if (isJsonRpcResponse(m)) {
341
- if (failFast.failedIds.has(String(m.id))) {
342
- // Already fail-fasted (idle timeout on a still-open stream) → Codex got the error. Still tap so
343
- // backfill (#1751) observes the late real result (inflight survives — onLost didn't tap), but
344
- // do NOT re-forward it to Codex (no double-send). forget() bounds failedIds.
345
- tapServerToClient(m); failFast.forget(m.id); log('DROP-AFTER-FAILFAST', m.id); return
24
+ await import('./relay.mjs')
25
+ }
26
+
27
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
28
+ const args = process.argv.slice(2)
29
+ main(args).catch(async (error) => {
30
+ if (args.length === 0) {
31
+ const { createFatalReporter } = await import('./startup.mjs')
32
+ createFatalReporter({
33
+ secret: process.env.GEMUS_KEY || '',
34
+ writeStderr: (message) => process.stderr.write(message),
35
+ writeLog: () => {},
36
+ })(error)
37
+ } else {
38
+ process.stderr.write(`${error.message}\n`)
346
39
  }
347
- failFast.settle(m.id)
348
- }
349
- tapServerToClient(m); steerOnInit(m); log('G->C', m); stdio.send(m).catch((e) => log('ERR-stdio-send', String(e)))
350
- }
351
-
352
- // ── session hygiene (spike: KEY_ONLY_SESSION_CAP=3) ────────────────────────────────────────────
353
- // We must DELETE the upstream session or we leak a key-only slot when codex ends the conversation.
354
- // NOTE: transport.close() does NOT issue DELETE (it only aborts + fires onclose, streamableHttp.js:280);
355
- // terminateSession() sends the DELETE (:431). Call it first, then close(). Also clean up local artifacts.
356
- // #1756 proxy-death detection: send an MCP `ping` every 30s so the platform can tell a live proxy
357
- // (keeps pinging) from a dead one (hard-killed → no graceful DELETE → leaked session). This is
358
- // **independent of Codex tool activity**, so a proxy mid-imagegen (silent to Codex for minutes) still
359
- // proves liveness → the platform reclaims only genuinely-dead sessions (short floor), never a live one.
360
- const HEARTBEAT_MS = Number(process.env.PROXY_HEARTBEAT_MS) || 30_000
361
- let pingSeq = 0
362
- let heartbeatTimer
363
- function startHeartbeat() {
364
- heartbeatTimer = setInterval(() => {
365
- upstream.send({ jsonrpc: '2.0', id: `gemus-ping-${++pingSeq}`, method: 'ping' }).catch((e) => log('PING-ERR', String(e)))
366
- }, HEARTBEAT_MS)
367
- if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref() // don't keep the process alive on this alone
368
- }
369
-
370
- async function cleanup() {
371
- if (heartbeatTimer) clearInterval(heartbeatTimer)
372
- for (const t of idleTimers.values()) clearTimeout(t)
373
- idleTimers.clear()
374
- // Settle any in-flight footprint-0 injections so a mid-delivery shutdown doesn't hang their awaits.
375
- for (const p of pendingInjections.values()) p.settle({ ok: false, error: 'proxy shutting down' })
376
- pendingInjections.clear()
377
- failFast.dispose() // #2068: clear fail-fast final-safety timers
378
- try { hookServer.close() } catch { /* ignore */ }
379
- if (discoveryFile) { try { fs.unlinkSync(discoveryFile) } catch { /* ignore */ } }
380
- try { await upstream.terminateSession() } catch { /* ignore */ }
381
- try { await upstream.close() } catch { /* ignore */ }
382
- }
383
- shutdown = createShutdownCoordinator({
384
- cleanup,
385
- exit: (code) => process.exit(code),
386
- })
387
- function shutdownGracefully() {
388
- shutdownRequested = true
389
- return shutdown(0)
390
- }
391
- stdio.onclose = () => { log('stdio-close', ''); void shutdownGracefully() }
392
- upstream.onclose = () => { log('http-close', '') }
393
- stdio.onerror = (e) => log('stdio-err', String(e))
394
- upstream.onerror = (e) => log('http-err', String(e))
395
- process.on('SIGTERM', () => { void shutdownGracefully() })
396
- process.on('SIGINT', () => { void shutdownGracefully() })
397
-
398
- try {
399
- await startProxy({
400
- key: KEY,
401
- upstream,
402
- stdio,
403
- onStarted: () => {
404
- if (shutdownRequested) return
405
- startHeartbeat()
406
- log('STARTED', {
407
- endpoint: safeEndpointLabel(GEMUS_URL),
408
- hasKey: Boolean(KEY),
409
- pid: process.pid,
410
- idleMs: IDLE_MS,
411
- heartbeatMs: HEARTBEAT_MS,
412
- })
413
- },
40
+ process.exitCode = error?.code === 'PROXY_USAGE' ? 2 : 1
414
41
  })
415
- } catch (error) {
416
- await terminateFatally(error)
417
42
  }
@@ -0,0 +1,38 @@
1
+ const PUBLIC_MESSAGES = {
2
+ connection: 'Gemus upstream connection failed before a response was received',
3
+ http: 'Gemus upstream returned an HTTP error before the tool result was delivered',
4
+ stream: 'Gemus upstream stream disconnected before the tool result was delivered',
5
+ idle: 'Gemus upstream stream became unresponsive before the tool result was delivered',
6
+ }
7
+
8
+ const FALLBACK_MESSAGE = 'Gemus upstream failed before the tool result was delivered'
9
+ const SAFE_CODE = /^[A-Z0-9_]{1,64}$/
10
+
11
+ export function publicMessageForFailure(failure) {
12
+ return Object.hasOwn(PUBLIC_MESSAGES, failure?.kind)
13
+ ? PUBLIC_MESSAGES[failure.kind]
14
+ : FALLBACK_MESSAGE
15
+ }
16
+
17
+ export function createProxyFailure(id, failure) {
18
+ const knownKind = Object.hasOwn(PUBLIC_MESSAGES, failure?.kind)
19
+ const kind = knownKind ? failure.kind : 'unknown'
20
+ const diagnostic = { id, kind }
21
+
22
+ if (kind === 'connection') {
23
+ diagnostic.code = typeof failure.code === 'string' && SAFE_CODE.test(failure.code)
24
+ ? failure.code
25
+ : 'UNKNOWN'
26
+ } else if (kind === 'http' && Number.isInteger(failure.status)) {
27
+ diagnostic.status = failure.status
28
+ }
29
+
30
+ return {
31
+ response: {
32
+ jsonrpc: '2.0',
33
+ id,
34
+ error: { code: -32000, message: publicMessageForFailure(failure) },
35
+ },
36
+ diagnostic,
37
+ }
38
+ }