anthropic-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/LICENSE +25 -0
- package/README.md +75 -0
- package/cli.js +261 -0
- package/config.example.json +20 -0
- package/lib/server.js +132 -0
- package/package.json +39 -0
- package/vendor/LICENSE.claude-adapter +21 -0
- package/vendor/dist/cli.js +288 -0
- package/vendor/dist/converters/index.js +22 -0
- package/vendor/dist/converters/request.js +349 -0
- package/vendor/dist/converters/response.js +125 -0
- package/vendor/dist/converters/streaming.js +308 -0
- package/vendor/dist/converters/tools.js +51 -0
- package/vendor/dist/converters/xmlPrompt.js +87 -0
- package/vendor/dist/converters/xmlStreaming.js +258 -0
- package/vendor/dist/index.js +32 -0
- package/vendor/dist/server/handlers.js +184 -0
- package/vendor/dist/server/index.js +116 -0
- package/vendor/dist/types/anthropic.js +4 -0
- package/vendor/dist/types/config.js +4 -0
- package/vendor/dist/types/index.js +21 -0
- package/vendor/dist/types/openai.js +4 -0
- package/vendor/dist/utils/config.js +169 -0
- package/vendor/dist/utils/errorLog.js +61 -0
- package/vendor/dist/utils/fileStorage.js +114 -0
- package/vendor/dist/utils/index.js +19 -0
- package/vendor/dist/utils/logger.js +138 -0
- package/vendor/dist/utils/metadata.js +128 -0
- package/vendor/dist/utils/provider.js +14 -0
- package/vendor/dist/utils/tokenUsage.js +32 -0
- package/vendor/dist/utils/ui.js +107 -0
- package/vendor/dist/utils/update.js +112 -0
- package/vendor/dist/utils/validation.js +130 -0
- package/vendor/package.json +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 anthropic-gateway contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
The Software includes a vendored conversion core originally written for
|
|
16
|
+
claude-adapter (https://github.com/shanthropic/claude-adapter), which is also
|
|
17
|
+
MIT-licensed — see vendor/LICENSE.claude-adapter.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# anthropic-gateway
|
|
2
|
+
|
|
3
|
+
A local gateway that speaks the **Anthropic Messages API** and forwards every
|
|
4
|
+
request to **any OpenAI-compatible provider** (kilo, OpenAI, DeepSeek, Groq,
|
|
5
|
+
local servers, ...). It forces every request to a single configured upstream
|
|
6
|
+
model, which makes it work with clients that can only talk to Anthropic —
|
|
7
|
+
including the **Claude Code GUI (desktop app)** via its custom gateway
|
|
8
|
+
(3P / enterprise) mode, Claude Code CLI, or any Anthropic-SDK tool.
|
|
9
|
+
|
|
10
|
+
```
|
|
11
|
+
Claude Code GUI/CLI ──(Anthropic format)──▶ anthropic-gateway (127.0.0.1:3080)
|
|
12
|
+
│ translate + force model
|
|
13
|
+
▼
|
|
14
|
+
OpenAI-compatible provider (/v1/chat/completions)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install # inside this folder, once
|
|
21
|
+
npm i -g . # optional: real global install (needs an admin shell
|
|
22
|
+
# if node lives under C:\Program Files)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Without admin rights a `C:\Users\<you>\bin\anthropic-gateway.cmd` wrapper is
|
|
26
|
+
used instead — both give you the `anthropic-gateway` command (alias: `ag`).
|
|
27
|
+
Open a **new** terminal after installing so PATH picks it up.
|
|
28
|
+
|
|
29
|
+
## Quick start
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
anthropic-gateway setup # interactive wizard (or flags, see below)
|
|
33
|
+
anthropic-gateway start # run the gateway (keep this console open)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Config, pid and log live in `~/.anthropic-gateway/` (`config.json`,
|
|
37
|
+
`gateway.pid`, `gateway.log`).
|
|
38
|
+
|
|
39
|
+
Then point your client at:
|
|
40
|
+
|
|
41
|
+
- Base URL: `http://127.0.0.1:3080`
|
|
42
|
+
- API key / `x-api-key` / `Authorization: Bearer`: the **proxy token** printed by `setup`
|
|
43
|
+
|
|
44
|
+
### Non-interactive setup
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
anthropic-gateway setup --provider kilo --api-key YOUR_KILO_KEY --model kilo-auto/free --yes
|
|
48
|
+
anthropic-gateway setup --base-url https://api.openai.com/v1 --api-key sk-... --model gpt-5 --port 3090 --token mytoken --yes
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Commands
|
|
52
|
+
|
|
53
|
+
| Command | Description |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| `anthropic-gateway setup` | Create/overwrite `~/.anthropic-gateway/config.json`; tests connectivity |
|
|
56
|
+
| `anthropic-gateway start` | Start the gateway |
|
|
57
|
+
| `anthropic-gateway stop` | Stop the gateway |
|
|
58
|
+
| `anthropic-gateway status` | Is the gateway up? |
|
|
59
|
+
| `anthropic-gateway autostart on\|off` | Launch at Windows logon (Startup folder) |
|
|
60
|
+
|
|
61
|
+
## config.json
|
|
62
|
+
|
|
63
|
+
See `config.example.json`. Key fields: `upstreamBaseUrl`, `upstreamApiKey`,
|
|
64
|
+
`upstreamModel`, `port`, `proxyTokens` (accepts several), `advertisedModels`
|
|
65
|
+
(models shown to Claude Code model discovery — must look Anthropic-ish, e.g.
|
|
66
|
+
`claude-sonnet-4-5` or `sonnet`), `toolFormat`.
|
|
67
|
+
|
|
68
|
+
## Using it with Claude Code GUI (desktop app)
|
|
69
|
+
|
|
70
|
+
1. Keep the gateway running (`anthropic-gateway start`, or `autostart on`).
|
|
71
|
+
2. In Claude desktop: Settings → custom provider / Claude Code Setup →
|
|
72
|
+
base URL `http://127.0.0.1:<port>`, API key = your proxy token.
|
|
73
|
+
3. Run its connection test, restart Claude, open Claude Code — the model
|
|
74
|
+
selector lists the `advertisedModels`, and every chat is served by your
|
|
75
|
+
upstream model.
|
package/cli.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
/*
|
|
4
|
+
* anthropic-gateway CLI
|
|
5
|
+
*
|
|
6
|
+
* node cli.js setup [--provider kilo|openai|custom] [--base-url ..] [--api-key ..]
|
|
7
|
+
* [--model ..] [--port ..] [--token ..] [--config path] [--yes]
|
|
8
|
+
* node cli.js start [--config path]
|
|
9
|
+
* node cli.js stop [--config path]
|
|
10
|
+
* node cli.js status [--config path]
|
|
11
|
+
* node cli.js autostart on|off [--config path]
|
|
12
|
+
*/
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const os = require('os');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const readline = require('readline');
|
|
17
|
+
const { spawn } = require('child_process');
|
|
18
|
+
|
|
19
|
+
const APP_DIR = __dirname;
|
|
20
|
+
const HOME_DIR =
|
|
21
|
+
process.env.ANTHROPIC_GATEWAY_HOME || path.join(os.homedir(), '.anthropic-gateway');
|
|
22
|
+
const DEFAULT_CONFIG = path.join(HOME_DIR, 'config.json');
|
|
23
|
+
const PID_FILE = path.join(HOME_DIR, 'gateway.pid');
|
|
24
|
+
const LOG_FILE = path.join(HOME_DIR, 'gateway.log');
|
|
25
|
+
const STARTUP_CMD = path.join(
|
|
26
|
+
os.homedir(),
|
|
27
|
+
'AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/anthropic-gateway.cmd'
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
function ensureHomeDir() {
|
|
31
|
+
fs.mkdirSync(HOME_DIR, { recursive: true });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const PRESETS = {
|
|
35
|
+
kilo: { name: 'kilo.imedata.ir', baseUrl: 'https://kilo.imedata.ir/v1', model: 'kilo-auto/free', needsKey: true },
|
|
36
|
+
openai: { name: 'OpenAI', baseUrl: 'https://api.openai.com/v1', model: '', needsKey: true },
|
|
37
|
+
custom: { name: 'custom', baseUrl: '', model: '', needsKey: true },
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function fail(msg) {
|
|
41
|
+
console.error('error: ' + msg);
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function ask(rl, q, def) {
|
|
46
|
+
return new Promise((resolve) => {
|
|
47
|
+
rl.question(q + (def ? ' [' + def + '] ' : ' '), (a) => resolve(a.trim() === '' ? (def || '') : a.trim()));
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function randomToken() {
|
|
52
|
+
return 'ag-' + require('crypto').randomBytes(24).toString('base64url');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function loadConfig(cfgPath) {
|
|
56
|
+
if (!fs.existsSync(cfgPath)) fail('no config at ' + cfgPath + ' — run "node cli.js setup" first');
|
|
57
|
+
return JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function testUpstream(baseUrl, apiKey, model) {
|
|
61
|
+
const OpenAI = require('openai');
|
|
62
|
+
const client = new OpenAI({ baseURL: baseUrl, apiKey });
|
|
63
|
+
const started = Date.now();
|
|
64
|
+
try {
|
|
65
|
+
await client.chat.completions.create({
|
|
66
|
+
model,
|
|
67
|
+
messages: [{ role: 'user', content: 'Reply with exactly: OK' }],
|
|
68
|
+
max_tokens: 16,
|
|
69
|
+
});
|
|
70
|
+
console.log(' connectivity: OK (' + (Date.now() - started) + ' ms) via ' + model);
|
|
71
|
+
return true;
|
|
72
|
+
} catch (e) {
|
|
73
|
+
console.log(' connectivity FAILED: ' + (e && e.message ? String(e.message).slice(0, 300) : e));
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function cmdSetup(args) {
|
|
79
|
+
ensureHomeDir();
|
|
80
|
+
let cfgPath = DEFAULT_CONFIG;
|
|
81
|
+
let provider = args.provider || '';
|
|
82
|
+
let baseUrl = args['base-url'] || '';
|
|
83
|
+
let apiKey = args['api-key'] || '';
|
|
84
|
+
let model = args.model || '';
|
|
85
|
+
let port = args.port ? Number(args.port) : NaN;
|
|
86
|
+
let token = args.token || '';
|
|
87
|
+
const yes = !!args.yes;
|
|
88
|
+
|
|
89
|
+
if (args.config) cfgPath = path.resolve(args.config);
|
|
90
|
+
|
|
91
|
+
const interactive = !yes;
|
|
92
|
+
const rl = interactive ? readline.createInterface({ input: process.stdin, output: process.stdout }) : null;
|
|
93
|
+
const q = async (prompt, def) => (interactive ? ask(rl, prompt, def) : def || '');
|
|
94
|
+
|
|
95
|
+
if (!provider) provider = await q('Provider preset (kilo | openai | custom):', 'kilo');
|
|
96
|
+
provider = provider.toLowerCase();
|
|
97
|
+
const preset = PRESETS[provider] || PRESETS.custom;
|
|
98
|
+
if (provider !== 'custom') console.log('Using preset: ' + preset.name);
|
|
99
|
+
|
|
100
|
+
if (!baseUrl) baseUrl = await q('Upstream base URL (OpenAI-compatible, e.g. https://host/v1):', preset.baseUrl);
|
|
101
|
+
if (!apiKey) apiKey = await q('API key:', '');
|
|
102
|
+
if (!model) model = await q('Upstream model id (all requests are sent to this model):', preset.model);
|
|
103
|
+
if (!Number.isFinite(port)) {
|
|
104
|
+
const p = await q('Local port:', '3080');
|
|
105
|
+
port = Number(p);
|
|
106
|
+
}
|
|
107
|
+
if (!token) {
|
|
108
|
+
const want = await q('Proxy token (client auth; enter to auto-generate):', '');
|
|
109
|
+
token = want || randomToken();
|
|
110
|
+
}
|
|
111
|
+
const adv = await q('Advertised model ids (comma separated, shown to Claude Code):', 'claude-sonnet-4-5,claude-haiku-4-5,claude-opus-4-5,sonnet,haiku,opus');
|
|
112
|
+
if (interactive) rl.close();
|
|
113
|
+
|
|
114
|
+
if (!baseUrl || !apiKey || !model) fail('base URL, API key and model are required');
|
|
115
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) fail('invalid port');
|
|
116
|
+
|
|
117
|
+
const advertisedModels = adv.split(',').map((s) => s.trim()).filter(Boolean);
|
|
118
|
+
const config = {
|
|
119
|
+
providerName: preset.name || 'custom',
|
|
120
|
+
upstreamBaseUrl: baseUrl.replace(/\/+$/, ''),
|
|
121
|
+
upstreamApiKey: apiKey,
|
|
122
|
+
upstreamModel: model,
|
|
123
|
+
port,
|
|
124
|
+
proxyTokens: [token],
|
|
125
|
+
toolFormat: 'native',
|
|
126
|
+
advertisedModels,
|
|
127
|
+
logFile: LOG_FILE,
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
console.log('Testing upstream connectivity...');
|
|
131
|
+
const ok = await testUpstream(config.upstreamBaseUrl, config.upstreamApiKey, config.upstreamModel);
|
|
132
|
+
if (!ok && !yes) {
|
|
133
|
+
const c = await ask(readline.createInterface({ input: process.stdin, output: process.stdout }), 'Connectivity test failed. Save anyway? (y/N):', 'N');
|
|
134
|
+
if (c.toLowerCase() !== 'y') fail('aborted — nothing written');
|
|
135
|
+
}
|
|
136
|
+
fs.writeFileSync(cfgPath, JSON.stringify(config, null, 2));
|
|
137
|
+
console.log('Config written to ' + cfgPath);
|
|
138
|
+
console.log('Proxy token (use as API key / x-api-key / Bearer in the client): ' + token);
|
|
139
|
+
console.log('Next: anthropic-gateway start (or: anthropic-gateway autostart on)');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function cmdStart(args) {
|
|
143
|
+
ensureHomeDir();
|
|
144
|
+
const cfgPath = args.config ? path.resolve(args.config) : DEFAULT_CONFIG;
|
|
145
|
+
const cfg = loadConfig(cfgPath);
|
|
146
|
+
if (cfg.logFile && !path.isAbsolute(cfg.logFile)) cfg.logFile = path.join(HOME_DIR, cfg.logFile);
|
|
147
|
+
const { makeServer } = require('./lib/server');
|
|
148
|
+
const server = makeServer(cfg);
|
|
149
|
+
const started = await server.start();
|
|
150
|
+
fs.writeFileSync(PID_FILE, String(process.pid));
|
|
151
|
+
console.log('pid ' + process.pid + ' written to ' + PID_FILE);
|
|
152
|
+
console.log('Health: http://127.0.0.1:' + started + '/health');
|
|
153
|
+
const shutdown = async () => {
|
|
154
|
+
await server.stop();
|
|
155
|
+
try { fs.unlinkSync(PID_FILE); } catch {}
|
|
156
|
+
process.exit(0);
|
|
157
|
+
};
|
|
158
|
+
process.on('SIGINT', shutdown);
|
|
159
|
+
process.on('SIGTERM', shutdown);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function cmdStop() {
|
|
163
|
+
ensureHomeDir();
|
|
164
|
+
if (!fs.existsSync(PID_FILE)) fail('no pid file (was it started with "anthropic-gateway start"? or already stopped)');
|
|
165
|
+
const pid = Number(fs.readFileSync(PID_FILE, 'utf8'));
|
|
166
|
+
try {
|
|
167
|
+
process.kill(pid);
|
|
168
|
+
console.log('stopped pid ' + pid);
|
|
169
|
+
} catch (e) {
|
|
170
|
+
console.log('pid ' + pid + ' not running (' + e.message + ')');
|
|
171
|
+
}
|
|
172
|
+
try { fs.unlinkSync(PID_FILE); } catch {}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function cmdStatus(args) {
|
|
176
|
+
ensureHomeDir();
|
|
177
|
+
const cfgPath = args.config ? path.resolve(args.config) : DEFAULT_CONFIG;
|
|
178
|
+
let cfg;
|
|
179
|
+
try { cfg = loadConfig(cfgPath); } catch (e) { console.log('down (no config)'); return; }
|
|
180
|
+
try {
|
|
181
|
+
const res = await fetch('http://127.0.0.1:' + cfg.port + '/health');
|
|
182
|
+
console.log('UP on ' + cfg.port + ' — ' + (await res.text()));
|
|
183
|
+
} catch {
|
|
184
|
+
console.log('DOWN — nothing listening on 127.0.0.1:' + cfg.port);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function startupCmdContents() {
|
|
189
|
+
const node = process.execPath;
|
|
190
|
+
return [
|
|
191
|
+
'@echo off',
|
|
192
|
+
'start "" /min "' + node + '" "' + path.join(APP_DIR, 'cli.js') + '" start',
|
|
193
|
+
'',
|
|
194
|
+
].join('\r\n');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function cmdAutostart(mode) {
|
|
198
|
+
ensureHomeDir();
|
|
199
|
+
if (mode === 'on') {
|
|
200
|
+
if (!fs.existsSync(DEFAULT_CONFIG)) fail('config.json missing — run setup first');
|
|
201
|
+
fs.writeFileSync(STARTUP_CMD, startupCmdContents());
|
|
202
|
+
console.log('Autostart enabled: ' + STARTUP_CMD);
|
|
203
|
+
} else if (mode === 'off') {
|
|
204
|
+
if (fs.existsSync(STARTUP_CMD)) {
|
|
205
|
+
fs.unlinkSync(STARTUP_CMD);
|
|
206
|
+
console.log('Autostart disabled');
|
|
207
|
+
} else {
|
|
208
|
+
console.log('Autostart was not enabled');
|
|
209
|
+
}
|
|
210
|
+
} else {
|
|
211
|
+
fail('usage: node cli.js autostart on|off');
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function parseFlags(argv) {
|
|
216
|
+
const out = {};
|
|
217
|
+
for (let i = 0; i < argv.length; i++) {
|
|
218
|
+
const a = argv[i];
|
|
219
|
+
if (a.startsWith('--')) {
|
|
220
|
+
const k = a.slice(2);
|
|
221
|
+
const v = argv[i + 1];
|
|
222
|
+
if (v !== undefined && !v.startsWith('--')) {
|
|
223
|
+
out[k] = v;
|
|
224
|
+
i++;
|
|
225
|
+
} else {
|
|
226
|
+
out[k] = true;
|
|
227
|
+
}
|
|
228
|
+
} else {
|
|
229
|
+
out._ = out._ || [];
|
|
230
|
+
out._.push(a);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
(async () => {
|
|
237
|
+
const argv = process.argv.slice(2);
|
|
238
|
+
const flags = parseFlags(argv);
|
|
239
|
+
const cmd = flags._ && flags._[0];
|
|
240
|
+
if (!cmd) {
|
|
241
|
+
console.log(
|
|
242
|
+
[
|
|
243
|
+
'anthropic-gateway — Anthropic-compatible gateway for OpenAI-compatible providers',
|
|
244
|
+
'',
|
|
245
|
+
'usage:',
|
|
246
|
+
' anthropic-gateway setup [--provider kilo|openai|custom] [--base-url URL] [--api-key KEY] [--model ID] [--port N] [--token TOK] [--yes]',
|
|
247
|
+
' anthropic-gateway start',
|
|
248
|
+
' anthropic-gateway stop',
|
|
249
|
+
' anthropic-gateway status',
|
|
250
|
+
' anthropic-gateway autostart on|off',
|
|
251
|
+
].join('\n')
|
|
252
|
+
);
|
|
253
|
+
process.exit(0);
|
|
254
|
+
}
|
|
255
|
+
if (cmd === 'setup') await cmdSetup(flags);
|
|
256
|
+
else if (cmd === 'start') await cmdStart(flags);
|
|
257
|
+
else if (cmd === 'stop') await cmdStop();
|
|
258
|
+
else if (cmd === 'status') await cmdStatus(flags);
|
|
259
|
+
else if (cmd === 'autostart') await cmdAutostart(flags._[1]);
|
|
260
|
+
else fail('unknown command: ' + cmd);
|
|
261
|
+
})();
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"providerName": "example-provider",
|
|
3
|
+
"upstreamBaseUrl": "https://PROVIDER-HOST/v1",
|
|
4
|
+
"upstreamApiKey": "<YOUR-PROVIDER-API-KEY>",
|
|
5
|
+
"upstreamModel": "your-model-id",
|
|
6
|
+
"port": 3080,
|
|
7
|
+
"proxyTokens": [
|
|
8
|
+
"<YOUR-PROXY-TOKEN>"
|
|
9
|
+
],
|
|
10
|
+
"toolFormat": "native",
|
|
11
|
+
"advertisedModels": [
|
|
12
|
+
"claude-sonnet-4-5",
|
|
13
|
+
"claude-haiku-4-5",
|
|
14
|
+
"claude-opus-4-5",
|
|
15
|
+
"sonnet",
|
|
16
|
+
"haiku",
|
|
17
|
+
"opus"
|
|
18
|
+
],
|
|
19
|
+
"logFile": "gateway.log"
|
|
20
|
+
}
|
package/lib/server.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* anthropic-gateway server core.
|
|
4
|
+
* Speaks the Anthropic Messages API locally (/v1/messages, /v1/models, /health)
|
|
5
|
+
* and forwards every request to any OpenAI-compatible upstream, always using
|
|
6
|
+
* the configured upstreamModel.
|
|
7
|
+
*
|
|
8
|
+
* config fields:
|
|
9
|
+
* upstreamBaseUrl e.g. https://kilo.imedata.ir/v1
|
|
10
|
+
* upstreamApiKey provider key
|
|
11
|
+
* upstreamModel model id sent upstream (all requests use it)
|
|
12
|
+
* port local listen port (default 3080)
|
|
13
|
+
* proxyTokens string[] — accepted client auth tokens (Bearer or x-api-key)
|
|
14
|
+
* toolFormat 'native' (default) or 'xml'
|
|
15
|
+
* advertisedModels model ids returned by GET /v1/models (for GUI discovery)
|
|
16
|
+
* logFile optional path to append logs to (default: none, console only)
|
|
17
|
+
*/
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const crypto = require('crypto');
|
|
21
|
+
const fastify = require('fastify');
|
|
22
|
+
const OpenAI = require('openai');
|
|
23
|
+
const { convertRequestToOpenAI } = require('../vendor/dist/converters/request');
|
|
24
|
+
const { convertResponseToAnthropic, createErrorResponse } = require('../vendor/dist/converters/response');
|
|
25
|
+
const { streamOpenAIToAnthropic } = require('../vendor/dist/converters/streaming');
|
|
26
|
+
const { validateAnthropicRequest, formatValidationErrors } = require('../vendor/dist/utils/validation');
|
|
27
|
+
|
|
28
|
+
const DEFAULTS = {
|
|
29
|
+
port: 3080,
|
|
30
|
+
toolFormat: 'native',
|
|
31
|
+
advertisedModels: ['claude-sonnet-4-5', 'claude-haiku-4-5', 'claude-opus-4-5'],
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function matchesToken(value, expected) {
|
|
35
|
+
if (typeof value !== 'string') return false;
|
|
36
|
+
const a = Buffer.from(value);
|
|
37
|
+
const b = Buffer.from(expected);
|
|
38
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function makeServer(rawCfg) {
|
|
42
|
+
const cfg = { ...DEFAULTS, ...rawCfg };
|
|
43
|
+
if (!Array.isArray(cfg.proxyTokens) || cfg.proxyTokens.length === 0) {
|
|
44
|
+
throw new Error('config needs at least one proxyTokens entry');
|
|
45
|
+
}
|
|
46
|
+
if (!cfg.upstreamBaseUrl || !cfg.upstreamApiKey || !cfg.upstreamModel) {
|
|
47
|
+
throw new Error('config needs upstreamBaseUrl, upstreamApiKey and upstreamModel');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
let logStream = null;
|
|
51
|
+
if (cfg.logFile) {
|
|
52
|
+
logStream = fs.createWriteStream(cfg.logFile, { flags: 'a' });
|
|
53
|
+
}
|
|
54
|
+
function log(line) {
|
|
55
|
+
const s = '[' + new Date().toISOString() + '] ' + line;
|
|
56
|
+
console.log(s);
|
|
57
|
+
if (logStream) logStream.write(s + '\n');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const app = fastify({ logger: false });
|
|
61
|
+
const isAzure = cfg.upstreamBaseUrl.includes('.openai.azure.com');
|
|
62
|
+
const openai = new OpenAI({ baseURL: cfg.upstreamBaseUrl, apiKey: cfg.upstreamApiKey });
|
|
63
|
+
|
|
64
|
+
const modelsPayload = { data: (cfg.advertisedModels || []).map((id) => ({ id, display_name: id + ' (via ' + cfg.upstreamModel + ')' })) };
|
|
65
|
+
|
|
66
|
+
app.get('/health', async () => ({ status: 'ok', gateway: 'anthropic-gateway', upstream: cfg.upstreamModel }));
|
|
67
|
+
app.get('/v1/models', async () => modelsPayload);
|
|
68
|
+
|
|
69
|
+
app.post('/v1/messages', async (request, reply) => {
|
|
70
|
+
const isAuthed = (() => {
|
|
71
|
+
const h = request.headers;
|
|
72
|
+
let candidate = null;
|
|
73
|
+
if (typeof h.authorization === 'string' && h.authorization.startsWith('Bearer ')) {
|
|
74
|
+
candidate = h.authorization.slice('Bearer '.length);
|
|
75
|
+
} else if (typeof h['x-api-key'] === 'string') {
|
|
76
|
+
candidate = h['x-api-key'];
|
|
77
|
+
}
|
|
78
|
+
return candidate !== null && cfg.proxyTokens.some((t) => matchesToken(candidate, t));
|
|
79
|
+
})();
|
|
80
|
+
if (!isAuthed) {
|
|
81
|
+
const h = request.headers;
|
|
82
|
+
log('AUTH-FAIL (auth header present: ' + (!!h.authorization) + ', x-api-key present: ' + (!!h['x-api-key']) + ')');
|
|
83
|
+
const err = createErrorResponse(new Error('Invalid proxy authentication token'), 401);
|
|
84
|
+
reply.code(401).send({ error: err.error });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const validation = validateAnthropicRequest(request.body);
|
|
88
|
+
if (!validation.valid) {
|
|
89
|
+
const err = createErrorResponse(new Error(formatValidationErrors(validation.errors)), 400);
|
|
90
|
+
reply.code(400).send({ error: err.error });
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const anthropicRequest = request.body;
|
|
94
|
+
const clientModel = anthropicRequest.model || 'sonnet';
|
|
95
|
+
const isStreaming = anthropicRequest.stream ?? false;
|
|
96
|
+
log('-> ' + clientModel + ' (upstream ' + cfg.upstreamModel + ') stream=' + isStreaming);
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const openaiRequest = convertRequestToOpenAI(anthropicRequest, cfg.upstreamModel, cfg.toolFormat, isAzure);
|
|
100
|
+
if (isStreaming) {
|
|
101
|
+
const stream = await openai.chat.completions.create({ ...openaiRequest, stream: true });
|
|
102
|
+
reply.hijack();
|
|
103
|
+
await streamOpenAIToAnthropic(stream, reply, clientModel, cfg.upstreamBaseUrl);
|
|
104
|
+
} else {
|
|
105
|
+
const response = await openai.chat.completions.create({ ...openaiRequest, stream: false });
|
|
106
|
+
reply.send(convertResponseToAnthropic(response, clientModel));
|
|
107
|
+
}
|
|
108
|
+
log('<- ' + clientModel + ' ok');
|
|
109
|
+
} catch (caught) {
|
|
110
|
+
const error = caught instanceof Error ? caught : new Error(String(caught));
|
|
111
|
+
const rawStatus = caught && typeof caught === 'object' && 'status' in caught ? caught.status : undefined;
|
|
112
|
+
const statusCode = typeof rawStatus === 'number' && rawStatus >= 400 && rawStatus <= 599 ? rawStatus : 500;
|
|
113
|
+
log('<- upstream error ' + statusCode + ' ' + String(error.message).slice(0, 400));
|
|
114
|
+
const err = createErrorResponse(error, statusCode);
|
|
115
|
+
reply.code(err.status).send({ error: err.error });
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
start: async () => {
|
|
121
|
+
await app.listen({ port: cfg.port, host: '127.0.0.1' });
|
|
122
|
+
log('anthropic-gateway listening on http://127.0.0.1:' + cfg.port + ' (upstream ' + cfg.upstreamModel + ')');
|
|
123
|
+
return cfg.port;
|
|
124
|
+
},
|
|
125
|
+
stop: async () => {
|
|
126
|
+
try { await app.close(); } catch {}
|
|
127
|
+
if (logStream) logStream.end();
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
module.exports = { makeServer, DEFAULTS };
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "anthropic-gateway",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Anthropic-compatible local gateway for any OpenAI-compatible model provider — make Claude Code (GUI/CLI) work with kilo, OpenAI, DeepSeek, local models, etc.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=18.0.0"
|
|
8
|
+
},
|
|
9
|
+
"keywords": [
|
|
10
|
+
"claude",
|
|
11
|
+
"claude-code",
|
|
12
|
+
"anthropic",
|
|
13
|
+
"openai",
|
|
14
|
+
"gateway",
|
|
15
|
+
"proxy",
|
|
16
|
+
"kilo",
|
|
17
|
+
"llm",
|
|
18
|
+
"api"
|
|
19
|
+
],
|
|
20
|
+
"bin": {
|
|
21
|
+
"anthropic-gateway": "cli.js",
|
|
22
|
+
"ag": "cli.js"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"cli.js",
|
|
26
|
+
"lib/",
|
|
27
|
+
"vendor/",
|
|
28
|
+
"config.example.json",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"start": "node cli.js start"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"fastify": "^4.28.1",
|
|
37
|
+
"openai": "^4.76.0"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Shanto Islam (shantoislamdev@gmail.com)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|