local-gateway 1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 (2026-06-25)
4
+
5
+ - Fix: GBK terminal compatibility for model mapping display
6
+ - ASCII-only output in CLI
7
+
8
+ ## 0.1.0 (2026-06-25)
9
+
10
+ - Initial release
11
+ - Multi-provider sequential failover (DeepSeek, KIMI, OpenAI, Anthropic, Groq, Together, Mistral, Google, OpenRouter)
12
+ - Cross-provider model name mapping (deepseek-chat → moonshot-v1-128k, etc.)
13
+ - SSE streaming passthrough (failover before headers sent)
14
+ - CLI with `local-gateway` command
15
+ - API keys via environment variables or `--api-key` flag
16
+ - Health check endpoint (`GET /health`)
17
+ - Model listing endpoint (`GET /v1/models`)
18
+ - Zero dependencies — pure Python stdlib
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, and merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ thereto, that is intentionally submitted to Licensor for inclusion
51
+ in the Work by the copyright owner or by an individual or Legal Entity
52
+ authorized to submit on behalf of the copyright owner. For the purposes
53
+ of this definition, "submitted" means any form of electronic, verbal,
54
+ or written communication sent to the Licensor or its representatives,
55
+ including but not limited to communication on electronic mailing lists,
56
+ source code control systems, and issue tracking systems that are
57
+ managed by, or on behalf of, the Licensor for the purpose of discussing
58
+ and improving the Work, but excluding communications that are
59
+ conspicuously marked or otherwise designated in writing by the
60
+ copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # LocalGateway
2
+
3
+ **Desktop LLM gateway with multi-provider failover and automatic model name mapping.**
4
+
5
+ ```
6
+ pip install local-gateway
7
+ ```
8
+
9
+ ```bash
10
+ # Set your API keys
11
+ export DEEPSEEK_API_KEY=sk-...
12
+ export KIMI_API_KEY=sk-...
13
+
14
+ # Start the gateway
15
+ local-gateway --providers deepseek,kimi
16
+ ```
17
+
18
+ ## Why?
19
+
20
+ Every desktop AI tool (Cursor, Claude Desktop, Windsurf, Continue.dev) lets you configure **one** API endpoint. If that provider goes down, your tool stops working.
21
+
22
+ LocalGateway is a lightweight proxy that sits between your desktop tools and LLM providers. It tries providers in sequence — if the first one fails, it **automatically falls back** to the next.
23
+
24
+ ## The Model Name Problem
25
+
26
+ Model names are not portable across providers:
27
+
28
+ | Your Request | DeepSeek | KIMI |
29
+ |-------------|----------|------|
30
+ | `deepseek-chat` | ✅ works | ❌ 404 — KIMI doesn't know this name |
31
+ | `gpt-4o` | ❌ doesn't exist | ❌ doesn't exist |
32
+
33
+ LocalGateway solves this with a **cross-provider model name mapping table**. When falling back from DeepSeek to KIMI, it automatically maps `deepseek-chat → moonshot-v1-128k`.
34
+
35
+ ## Usage
36
+
37
+ ```bash
38
+ # Two providers (DeepSeek → KIMI auto-failover)
39
+ local-gateway --providers deepseek,kimi
40
+
41
+ # Three providers
42
+ local-gateway --providers deepseek,kimi,openai
43
+
44
+ # Custom port
45
+ local-gateway --providers deepseek,kimi --port 8080
46
+
47
+ # Explicit API keys (instead of env vars)
48
+ local-gateway --providers deepseek,kimi \
49
+ --api-key deepseek=sk-xxx \
50
+ --api-key kimi=sk-yyy
51
+
52
+ # Listen on all interfaces (for Docker/LAN)
53
+ local-gateway --providers deepseek,kimi --host 0.0.0.0
54
+ ```
55
+
56
+ ## Configuration
57
+
58
+ ### Environment Variables
59
+
60
+ | Provider | Env Variable |
61
+ |----------|-------------|
62
+ | DeepSeek | `DEEPSEEK_API_KEY` |
63
+ | KIMI | `KIMI_API_KEY` |
64
+ | OpenAI | `OPENAI_API_KEY` |
65
+ | Anthropic | `ANTHROPIC_API_KEY` |
66
+ | Groq | `GROQ_API_KEY` |
67
+ | Together | `TOGETHER_API_KEY` |
68
+ | Mistral | `MISTRAL_API_KEY` |
69
+ | Google Gemini | `GOOGLE_API_KEY` |
70
+ | OpenRouter | `OPENROUTER_API_KEY` |
71
+
72
+ ### Using with any OpenAI-compatible client
73
+
74
+ ```python
75
+ import openai
76
+ client = openai.OpenAI(
77
+ base_url="http://127.0.0.1:18790/v1",
78
+ api_key="not-needed", # local-gateway doesn't validate the client key
79
+ )
80
+ ```
81
+
82
+ ## How It Works
83
+
84
+ ```
85
+ ┌─────────────────┐
86
+ Client ──POST──→ local-gateway │
87
+ │ │
88
+ ├→ try DeepSeek ──→ HTTP 200 → forward response
89
+ │ │
90
+ └→ DeepSeek fails │
91
+ → try KIMI ────→ HTTP 200 → forward response
92
+
93
+ all fail ────→ 502
94
+ ```
95
+
96
+ For SSE streaming, the proxy connects to the upstream **before** sending HTTP 200 to the client. This means failover is transparent — the client never sees a partial response.
97
+
98
+ ## Built-in Providers
99
+
100
+ See `local-gateway --list-providers` for the full list.
101
+
102
+ ## Cross-Provider Model Mappings
103
+
104
+ See `local-gateway --list-models` for the current mapping table.
105
+
106
+ ## License
107
+
108
+ Apache 2.0
109
+
110
+ ---
111
+
112
+ Built by [Correctover](https://correctover.com) — verified failover for LLM APIs.
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "local-gateway",
3
+ "version": "1.0.0",
4
+ "description": "Desktop LLM gateway with multi-provider failover and automatic model name mapping. Zero dependencies.",
5
+ "main": "src/local-gateway.js",
6
+ "bin": {
7
+ "local-gateway": "src/local-gateway.js"
8
+ },
9
+ "keywords": ["llm", "gateway", "proxy", "failover", "openai", "deepseek", "kimi", "desktop"],
10
+ "author": "Correctover <team@correctover.com>",
11
+ "license": "Apache-2.0",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/correctover/local-gateway.git"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/correctover/local-gateway/issues"
18
+ },
19
+ "homepage": "https://github.com/correctover/local-gateway",
20
+ "engines": {
21
+ "node": ">=16.0.0"
22
+ },
23
+ "files": [
24
+ "src/local-gateway.js",
25
+ "README.md",
26
+ "LICENSE",
27
+ "CHANGELOG.md"
28
+ ]
29
+ }
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * local-gateway — Desktop LLM gateway with multi-provider failover
4
+ *
5
+ * Node.js implementation. Pure built-in modules (http, https).
6
+ * Usage: node local-gateway.js --providers deepseek,kimi
7
+ */
8
+
9
+ const http = require('http');
10
+ const https = require('https');
11
+ const { URL } = require('url');
12
+
13
+ // ── Built-in provider registry ────────────────────────────────────────
14
+ const BUILTIN_PROVIDERS = {
15
+ deepseek: { base_url: 'https://api.deepseek.com/v1', env_key: 'DEEPSEEK_API_KEY', default_model: 'deepseek-chat' },
16
+ kimi: { base_url: 'https://api.moonshot.cn/v1', env_key: 'KIMI_API_KEY', default_model: 'moonshot-v1-128k' },
17
+ openai: { base_url: 'https://api.openai.com/v1', env_key: 'OPENAI_API_KEY', default_model: 'gpt-4o' },
18
+ openrouter: { base_url: 'https://openrouter.ai/api/v1', env_key: 'OPENROUTER_API_KEY',default_model: 'openai/gpt-4o' },
19
+ anthropic: { base_url: 'https://api.anthropic.com/v1', env_key: 'ANTHROPIC_API_KEY', default_model: 'claude-sonnet-4-20250514' },
20
+ groq: { base_url: 'https://api.groq.com/openai/v1', env_key: 'GROQ_API_KEY', default_model: 'llama-3.3-70b-versatile' },
21
+ together: { base_url: 'https://api.together.xyz/v1', env_key: 'TOGETHER_API_KEY', default_model: 'meta-llama/Llama-3.3-70B-Instruct-Turbo' },
22
+ mistral: { base_url: 'https://api.mistral.ai/v1', env_key: 'MISTRAL_API_KEY', default_model: 'mistral-large-latest' },
23
+ google: { base_url: 'https://generativelanguage.googleapis.com/v1beta/openai', env_key: 'GOOGLE_API_KEY', default_model: 'gemini-2.0-flash' },
24
+ };
25
+
26
+ // ── Cross-provider model name mapping ─────────────────────────────────
27
+ const MODEL_MAP = {
28
+ 'deepseek-chat|deepseek|kimi': 'moonshot-v1-128k',
29
+ 'deepseek-chat|deepseek|openai': 'gpt-4o',
30
+ 'deepseek-chat|deepseek|openrouter': 'deepseek/deepseek-chat',
31
+ 'deepseek-chat|deepseek|groq': 'llama-3.3-70b-versatile',
32
+ 'gpt-4o|openai|deepseek': 'deepseek-chat',
33
+ 'gpt-4o|openai|kimi': 'moonshot-v1-128k',
34
+ 'gpt-4o|openai|openrouter': 'openai/gpt-4o',
35
+ 'claude-sonnet-4-20250514|anthropic|openai': 'gpt-4o',
36
+ 'claude-sonnet-4-20250514|anthropic|deepseek': 'deepseek-chat',
37
+ };
38
+
39
+ function resolveModel(model, fromProvider, toProvider) {
40
+ const key = `${model}|${fromProvider}|${toProvider}`;
41
+ const mapped = MODEL_MAP[key];
42
+ if (mapped) return mapped;
43
+ console.warn(`[local-gateway] No model mapping for '${model}' ${fromProvider} -> ${toProvider}, passing through`);
44
+ return model;
45
+ }
46
+
47
+ // ── Provider loading ──────────────────────────────────────────────────
48
+ function loadProviders(names, apiKeys = {}) {
49
+ return names.map(name => {
50
+ let spec = BUILTIN_PROVIDERS[name];
51
+ if (!spec) {
52
+ console.warn(`[local-gateway] Unknown provider '${name}', using generic`);
53
+ spec = { base_url: `https://api.${name}.com/v1`, env_key: `${name.toUpperCase()}_API_KEY`, default_model: `${name}-default` };
54
+ }
55
+ let key = apiKeys[name] || process.env[spec.env_key] || process.env[`${name.toUpperCase()}_API_KEY`];
56
+ if (!key) throw new Error(`API key for '${name}' not found. Set ${spec.env_key} env var.`);
57
+ return { name, base_url: spec.base_url, api_key: key, default_model: spec.default_model };
58
+ });
59
+ }
60
+
61
+ // ── HTTP client helper (pure Node.js, no dependencies) ────────────────
62
+ function upstreamRequest(urlStr, data, apiKey, modelName, isStream) {
63
+ return new Promise((resolve, reject) => {
64
+ const url = new URL(urlStr);
65
+ const body = JSON.stringify({ ...JSON.parse(data), model: modelName, stream: isStream });
66
+ const opts = {
67
+ hostname: url.hostname,
68
+ port: url.port || 443,
69
+ path: url.pathname + url.search,
70
+ method: 'POST',
71
+ headers: {
72
+ 'Content-Type': 'application/json',
73
+ 'Authorization': `Bearer ${apiKey}`,
74
+ 'User-Agent': 'local-gateway/1.0.0',
75
+ 'Content-Length': Buffer.byteLength(body),
76
+ },
77
+ };
78
+
79
+ const req = https.request(opts, (res) => {
80
+ resolve(res);
81
+ });
82
+ req.on('error', reject);
83
+ req.setTimeout(120000, () => { req.destroy(new Error('timeout')); });
84
+ req.write(body);
85
+ req.end();
86
+ });
87
+ }
88
+
89
+ // ── SSE streaming helper ──────────────────────────────────────────────
90
+ function pipeStream(upstreamRes, clientRes) {
91
+ upstreamRes.on('data', chunk => {
92
+ clientRes.write(chunk);
93
+ });
94
+ upstreamRes.on('end', () => clientRes.end());
95
+ upstreamRes.on('error', () => clientRes.end());
96
+ }
97
+
98
+ // ── Parse CLI args ────────────────────────────────────────────────────
99
+ function parseArgs() {
100
+ const args = process.argv.slice(2);
101
+ const opts = { providers: [], port: 18790, host: '127.0.0.1', apiKeys: {} };
102
+ for (let i = 0; i < args.length; i++) {
103
+ switch (args[i]) {
104
+ case '--providers': case '-p':
105
+ opts.providers = (args[++i] || '').split(',').map(s => s.trim()).filter(Boolean);
106
+ break;
107
+ case '--port':
108
+ opts.port = parseInt(args[++i] || '18790', 10);
109
+ break;
110
+ case '--host':
111
+ opts.host = args[++i] || '127.0.0.1';
112
+ break;
113
+ case '--api-key':
114
+ const kv = args[++i] || '';
115
+ const eq = kv.indexOf('=');
116
+ if (eq > 0) opts.apiKeys[kv.slice(0, eq)] = kv.slice(eq + 1);
117
+ break;
118
+ case '--list-providers':
119
+ console.log('Built-in providers:\n');
120
+ Object.entries(BUILTIN_PROVIDERS).forEach(([k, v]) => {
121
+ console.log(` ${k.padEnd(15)} ${v.base_url}`);
122
+ console.log(` env: ${v.env_key}`);
123
+ console.log(` default model: ${v.default_model}\n`);
124
+ });
125
+ process.exit(0);
126
+ case '--list-models':
127
+ console.log('# Cross-Provider Model Name Mapping\n');
128
+ const seen = new Set();
129
+ Object.entries(MODEL_MAP).sort().forEach(([key, mapped]) => {
130
+ const [model, src, dst] = key.split('|');
131
+ const sk = `${model}|${src}`;
132
+ if (!seen.has(sk)) { seen.add(sk); console.log(`\n${model} (${src})`); }
133
+ console.log(` => ${String(mapped).padEnd(40)} (${dst})`);
134
+ });
135
+ process.exit(0);
136
+ case '--version':
137
+ console.log('local-gateway 1.0.0');
138
+ process.exit(0);
139
+ }
140
+ }
141
+ return opts;
142
+ }
143
+
144
+ // ── Main: HTTP Server ─────────────────────────────────────────────────
145
+ function main() {
146
+ const opts = parseArgs();
147
+
148
+ if (!opts.providers.length) {
149
+ console.error('Usage: local-gateway --providers deepseek,kimi [--port 18790] [--host 127.0.0.1]');
150
+ console.error(' local-gateway --list-providers');
151
+ console.error(' local-gateway --list-models');
152
+ process.exit(1);
153
+ }
154
+
155
+ const providers = loadProviders(opts.providers, opts.apiKeys);
156
+ const providerOrder = opts.providers;
157
+
158
+ const server = http.createServer((req, res) => {
159
+ // CORS
160
+ res.setHeader('Access-Control-Allow-Origin', '*');
161
+ res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS, GET');
162
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
163
+
164
+ if (req.method === 'OPTIONS') {
165
+ res.writeHead(204);
166
+ res.end();
167
+ return;
168
+ }
169
+
170
+ // GET /health
171
+ if (req.method === 'GET' && req.url === '/health') {
172
+ res.writeHead(200, { 'Content-Type': 'application/json' });
173
+ res.end(JSON.stringify({ status: 'ok', providers: providerOrder }));
174
+ return;
175
+ }
176
+
177
+ // POST /v1/chat/completions
178
+ if (req.method === 'POST' && req.url.includes('/chat/completions')) {
179
+ let body = '';
180
+ req.on('data', chunk => body += chunk);
181
+ req.on('end', async () => {
182
+ let parsed;
183
+ try { parsed = JSON.parse(body); } catch (e) {
184
+ res.writeHead(400, { 'Content-Type': 'application/json' });
185
+ res.end(JSON.stringify({ error: { message: `Invalid JSON: ${e.message}` } }));
186
+ return;
187
+ }
188
+
189
+ const isStream = parsed.stream === true;
190
+ const originalModel = parsed.model || '';
191
+ let lastError = null;
192
+
193
+ for (let idx = 0; idx < providerOrder.length; idx++) {
194
+ const pName = providerOrder[idx];
195
+ const p = providers.find(pr => pr.name === pName);
196
+ if (!p) continue;
197
+
198
+ const model = idx === 0
199
+ ? (originalModel || p.default_model)
200
+ : resolveModel(originalModel || p.default_model, providerOrder[0], pName);
201
+
202
+ const url = `${p.base_url.replace(/\/+$/, '')}/chat/completions`;
203
+
204
+ try {
205
+ const upstreamRes = await upstreamRequest(url, body, p.api_key, model, isStream);
206
+
207
+ if (upstreamRes.statusCode !== 200) {
208
+ let errData = '';
209
+ await new Promise(r => { upstreamRes.on('data', d => errData += d); upstreamRes.on('end', r); });
210
+ console.warn(`[local-gateway] FAIL ${pName} — HTTP ${upstreamRes.statusCode}: ${errData.slice(0, 200)}`);
211
+ lastError = { provider: pName, status: upstreamRes.statusCode };
212
+ continue;
213
+ }
214
+
215
+ // Connected — forward response
216
+ console.log(`[local-gateway] 200 ${pName} (${isStream ? 'stream' : 'sync'})`);
217
+
218
+ if (isStream) {
219
+ res.writeHead(200, {
220
+ 'Content-Type': 'text/event-stream',
221
+ 'Cache-Control': 'no-cache',
222
+ 'Connection': 'close',
223
+ });
224
+ pipeStream(upstreamRes, res);
225
+ } else {
226
+ let respData = '';
227
+ await new Promise(r => { upstreamRes.on('data', d => respData += d); upstreamRes.on('end', r); });
228
+ res.writeHead(200, {
229
+ 'Content-Type': 'application/json',
230
+ 'Content-Length': Buffer.byteLength(respData),
231
+ });
232
+ res.end(respData);
233
+ }
234
+ return;
235
+
236
+ } catch (e) {
237
+ console.warn(`[local-gateway] FAIL ${pName} — ${e.message}`);
238
+ lastError = { provider: pName, status: 0, detail: e.message };
239
+ }
240
+ }
241
+
242
+ // All failed
243
+ console.error(`[local-gateway] ALL PROVIDERS FAILED`);
244
+ res.writeHead(502, { 'Content-Type': 'application/json' });
245
+ res.end(JSON.stringify({
246
+ error: { message: `All providers failed. Last: ${lastError?.provider || 'none'}`, type: 'upstream_error' }
247
+ }));
248
+ });
249
+ return;
250
+ }
251
+
252
+ // 404
253
+ res.writeHead(404);
254
+ res.end('not found');
255
+ });
256
+
257
+ server.listen(opts.port, opts.host, () => {
258
+ console.log('='.repeat(55));
259
+ console.log(' LocalGateway (Node.js)');
260
+ console.log(` listening on http://${opts.host}:${opts.port}`);
261
+ console.log(` providers: ${providerOrder.join(', ')}`);
262
+ console.log(' streaming: supported (SSE passthrough)');
263
+ console.log('='.repeat(55));
264
+ });
265
+ }
266
+
267
+ // ── Entry ─────────────────────────────────────────────────────────────
268
+ if (require.main === module) main();
269
+ module.exports = { BUILTIN_PROVIDERS, MODEL_MAP, loadProviders, resolveModel };