@redonvn/event-ws-cliproxyapi-sdk 1.0.3 → 1.0.5

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.
Files changed (50) hide show
  1. package/README.md +258 -428
  2. package/dist/claude/client.d.ts +1 -1
  3. package/dist/claude/index.d.ts +1 -1
  4. package/dist/client.d.ts +19 -0
  5. package/dist/client.js +96 -0
  6. package/dist/cliproxy/client.d.ts +1 -1
  7. package/dist/cliproxy/index.d.ts +1 -1
  8. package/dist/codec.d.ts +8 -0
  9. package/dist/codec.js +79 -0
  10. package/dist/errors/index.d.ts +13 -0
  11. package/dist/errors/index.js +26 -0
  12. package/dist/gemini/client.d.ts +1 -1
  13. package/dist/gemini/index.d.ts +1 -1
  14. package/dist/http/client.d.ts +260 -0
  15. package/dist/http/client.js +591 -0
  16. package/dist/http/index.d.ts +2 -0
  17. package/dist/http/index.js +2 -0
  18. package/dist/http/types.d.ts +783 -0
  19. package/dist/http/types.js +1 -0
  20. package/dist/http-client.d.ts +259 -0
  21. package/dist/http-client.js +557 -0
  22. package/dist/http-types.d.ts +677 -0
  23. package/dist/http-types.js +1 -0
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +3 -3
  26. package/dist/management/client.d.ts +1 -1
  27. package/dist/management/client.js +1 -1
  28. package/dist/management/index.d.ts +1 -1
  29. package/dist/openai/client.d.ts +1 -1
  30. package/dist/openai/index.d.ts +1 -1
  31. package/dist/shared/errors.d.ts +4 -4
  32. package/dist/shared/errors.js +15 -9
  33. package/dist/shared/http.d.ts +3 -1
  34. package/dist/shared/http.js +18 -12
  35. package/dist/shared/index.d.ts +1 -1
  36. package/dist/shared/index.js +1 -1
  37. package/dist/shared/types.d.ts +9 -8
  38. package/dist/types/index.d.ts +2 -0
  39. package/dist/types/index.js +2 -0
  40. package/dist/types.d.ts +101 -0
  41. package/dist/types.js +1 -0
  42. package/dist/utils/index.d.ts +0 -0
  43. package/dist/utils/index.js +2 -0
  44. package/dist/ws/client.d.ts +1 -0
  45. package/dist/ws/client.js +22 -14
  46. package/dist/ws/codec.js +1 -1
  47. package/dist/ws/index.d.ts +1 -1
  48. package/dist/ws/index.js +1 -1
  49. package/dist/ws/types.d.ts +7 -4
  50. package/package.json +23 -23
package/README.md CHANGED
@@ -1,428 +1,258 @@
1
- # event-ws-CLIProxyAPI-sdk
2
-
3
- TypeScript SDK for CLIProxyAPI covering:
4
- - WebSocket relay (provider-side) via `/v1/ws`
5
- - Full HTTP client for public and management APIs
6
-
7
- ## Endpoints (Full List + Function)
8
-
9
- WebSocket relay
10
- - `GET /v1/ws`: WebSocket relay endpoint for provider-side request/response and streaming.
11
-
12
- Public (no management key)
13
- - `GET /`: Health/info root. Returns server message + key endpoints list.
14
- - `GET /management.html`: Management UI HTML (if enabled on server).
15
- - `GET /keep-alive`: Keep-alive heartbeat (only if server enabled it). Requires local password when set.
16
- - OAuth callbacks (used by browser auth flows):
17
- - `GET /anthropic/callback`: Persist Anthropic OAuth callback.
18
- - `GET /codex/callback`: Persist Codex OAuth callback.
19
- - `GET /google/callback`: Persist Gemini OAuth callback.
20
- - `GET /iflow/callback`: Persist iFlow OAuth callback.
21
- - `GET /antigravity/callback`: Persist Antigravity OAuth callback.
22
- - `POST /v1internal:method`: Gemini CLI handler (localhost only). For `generateContent` / `streamGenerateContent`.
23
-
24
- OpenAI-compatible (`/v1`)
25
- - `GET /v1/models`: List models (OpenAI or Claude depending on User-Agent).
26
- - `POST /v1/chat/completions`: Chat Completions (OpenAI-compatible, supports stream).
27
- - `POST /v1/completions`: Completions (OpenAI-compatible, supports stream).
28
- - `POST /v1/messages`: Claude-style messages (supports stream).
29
- - `POST /v1/messages/count_tokens`: Claude token counting.
30
- - `POST /v1/responses`: OpenAI Responses API (supports stream).
31
- - `POST /v1/responses/compact`: OpenAI Responses Compact (non-stream).
32
-
33
- CLIProxy simplified (`/v1/cliproxy`)
34
- - `GET /v1/cliproxy/auths`: List authenticated accounts and supported models.
35
- - `GET /v1/cliproxy/models`: List available models (format: openai/claude/gemini/generic).
36
- - `POST /v1/cliproxy/chat`: Simplified chat proxy (maps to OpenAI chat).
37
-
38
- Gemini-compatible (`/v1beta`)
39
- - `GET /v1beta/models`: List Gemini models.
40
- - `POST /v1beta/models/*action`: Gemini generate/stream endpoints (e.g. `:generateContent`, `:streamGenerateContent`).
41
- - `GET /v1beta/models/*action`: Gemini GET actions.
42
-
43
- Management (`/v0/management`, requires management key)
44
- - `GET /v0/management/usage`: Usage snapshot (in-memory stats).
45
- - `GET /v0/management/usage/export`: Export usage snapshot.
46
- - `POST /v0/management/usage/import`: Import usage snapshot.
47
- - `GET /v0/management/config`: Full config JSON.
48
- - `GET /v0/management/config.yaml`: Config YAML.
49
- - `PUT /v0/management/config.yaml`: Replace config YAML (validates then saves).
50
- - `GET /v0/management/latest-version`: Latest release version (from GitHub).
51
- - `GET /v0/management/debug`: Debug flag.
52
- - `PUT /v0/management/debug`: Update debug flag.
53
- - `PATCH /v0/management/debug`: Update debug flag.
54
- - `GET /v0/management/logging-to-file`: Logging-to-file flag.
55
- - `PUT /v0/management/logging-to-file`: Update logging-to-file.
56
- - `PATCH /v0/management/logging-to-file`: Update logging-to-file.
57
- - `GET /v0/management/logs-max-total-size-mb`: Logs max size.
58
- - `PUT /v0/management/logs-max-total-size-mb`: Update logs max size.
59
- - `PATCH /v0/management/logs-max-total-size-mb`: Update logs max size.
60
- - `GET /v0/management/error-logs-max-files`: Error logs max files.
61
- - `PUT /v0/management/error-logs-max-files`: Update error logs max files.
62
- - `PATCH /v0/management/error-logs-max-files`: Update error logs max files.
63
- - `GET /v0/management/usage-statistics-enabled`: Usage stats enabled.
64
- - `PUT /v0/management/usage-statistics-enabled`: Update usage stats enabled.
65
- - `PATCH /v0/management/usage-statistics-enabled`: Update usage stats enabled.
66
- - `GET /v0/management/proxy-url`: Proxy URL.
67
- - `PUT /v0/management/proxy-url`: Update proxy URL.
68
- - `PATCH /v0/management/proxy-url`: Update proxy URL.
69
- - `DELETE /v0/management/proxy-url`: Clear proxy URL.
70
- - `POST /v0/management/api-call`: Test outbound API call using an auth entry.
71
- - `GET /v0/management/quota-exceeded/switch-project`: Switch project flag.
72
- - `PUT /v0/management/quota-exceeded/switch-project`: Update switch project flag.
73
- - `PATCH /v0/management/quota-exceeded/switch-project`: Update switch project flag.
74
- - `GET /v0/management/quota-exceeded/switch-preview-model`: Switch preview model flag.
75
- - `PUT /v0/management/quota-exceeded/switch-preview-model`: Update switch preview model flag.
76
- - `PATCH /v0/management/quota-exceeded/switch-preview-model`: Update switch preview model flag.
77
- - `GET /v0/management/api-keys`: List API keys.
78
- - `PUT /v0/management/api-keys`: Replace API keys.
79
- - `PATCH /v0/management/api-keys`: Patch API keys.
80
- - `DELETE /v0/management/api-keys`: Delete API keys.
81
- - `GET /v0/management/gemini-api-key`: List Gemini keys.
82
- - `PUT /v0/management/gemini-api-key`: Replace Gemini keys.
83
- - `PATCH /v0/management/gemini-api-key`: Patch Gemini keys.
84
- - `DELETE /v0/management/gemini-api-key`: Delete Gemini keys.
85
- - `GET /v0/management/logs`: Read log lines.
86
- - `DELETE /v0/management/logs`: Clear logs.
87
- - `GET /v0/management/request-error-logs`: List request error logs.
88
- - `GET /v0/management/request-error-logs/:name`: Download a request error log.
89
- - `GET /v0/management/request-log-by-id/:id`: Download request log by request ID.
90
- - `GET /v0/management/request-log`: Request log enabled flag.
91
- - `PUT /v0/management/request-log`: Update request log enabled flag.
92
- - `PATCH /v0/management/request-log`: Update request log enabled flag.
93
- - `GET /v0/management/ws-auth`: WebSocket auth enabled flag.
94
- - `PUT /v0/management/ws-auth`: Update WebSocket auth enabled flag.
95
- - `PATCH /v0/management/ws-auth`: Update WebSocket auth enabled flag.
96
- - `GET /v0/management/ampcode`: Amp CLI config.
97
- - `GET /v0/management/ampcode/upstream-url`: Amp upstream URL.
98
- - `PUT /v0/management/ampcode/upstream-url`: Update Amp upstream URL.
99
- - `PATCH /v0/management/ampcode/upstream-url`: Update Amp upstream URL.
100
- - `DELETE /v0/management/ampcode/upstream-url`: Clear Amp upstream URL.
101
- - `GET /v0/management/ampcode/upstream-api-key`: Amp upstream API key.
102
- - `PUT /v0/management/ampcode/upstream-api-key`: Update Amp upstream API key.
103
- - `PATCH /v0/management/ampcode/upstream-api-key`: Update Amp upstream API key.
104
- - `DELETE /v0/management/ampcode/upstream-api-key`: Clear Amp upstream API key.
105
- - `GET /v0/management/ampcode/restrict-management-to-localhost`: Restrict Amp management to localhost.
106
- - `PUT /v0/management/ampcode/restrict-management-to-localhost`: Update restriction.
107
- - `PATCH /v0/management/ampcode/restrict-management-to-localhost`: Update restriction.
108
- - `GET /v0/management/ampcode/model-mappings`: List Amp model mappings.
109
- - `PUT /v0/management/ampcode/model-mappings`: Replace Amp model mappings.
110
- - `PATCH /v0/management/ampcode/model-mappings`: Patch Amp model mappings.
111
- - `DELETE /v0/management/ampcode/model-mappings`: Delete Amp model mappings.
112
- - `GET /v0/management/ampcode/force-model-mappings`: Force model mappings flag.
113
- - `PUT /v0/management/ampcode/force-model-mappings`: Update force model mappings.
114
- - `PATCH /v0/management/ampcode/force-model-mappings`: Update force model mappings.
115
- - `GET /v0/management/ampcode/upstream-api-keys`: List Amp upstream API keys.
116
- - `PUT /v0/management/ampcode/upstream-api-keys`: Replace Amp upstream API keys.
117
- - `PATCH /v0/management/ampcode/upstream-api-keys`: Patch Amp upstream API keys.
118
- - `DELETE /v0/management/ampcode/upstream-api-keys`: Delete Amp upstream API keys.
119
- - `GET /v0/management/request-retry`: Request retry count.
120
- - `PUT /v0/management/request-retry`: Update request retry count.
121
- - `PATCH /v0/management/request-retry`: Update request retry count.
122
- - `GET /v0/management/max-retry-interval`: Max retry interval.
123
- - `PUT /v0/management/max-retry-interval`: Update max retry interval.
124
- - `PATCH /v0/management/max-retry-interval`: Update max retry interval.
125
- - `GET /v0/management/force-model-prefix`: Force model prefix flag.
126
- - `PUT /v0/management/force-model-prefix`: Update force model prefix.
127
- - `PATCH /v0/management/force-model-prefix`: Update force model prefix.
128
- - `GET /v0/management/routing/strategy`: Routing strategy.
129
- - `PUT /v0/management/routing/strategy`: Update routing strategy.
130
- - `PATCH /v0/management/routing/strategy`: Update routing strategy.
131
- - `GET /v0/management/claude-api-key`: List Claude keys.
132
- - `PUT /v0/management/claude-api-key`: Replace Claude keys.
133
- - `PATCH /v0/management/claude-api-key`: Patch Claude keys.
134
- - `DELETE /v0/management/claude-api-key`: Delete Claude keys.
135
- - `GET /v0/management/codex-api-key`: List Codex keys.
136
- - `PUT /v0/management/codex-api-key`: Replace Codex keys.
137
- - `PATCH /v0/management/codex-api-key`: Patch Codex keys.
138
- - `DELETE /v0/management/codex-api-key`: Delete Codex keys.
139
- - `GET /v0/management/openai-compatibility`: List OpenAI compatibility configs.
140
- - `PUT /v0/management/openai-compatibility`: Replace OpenAI compatibility configs.
141
- - `PATCH /v0/management/openai-compatibility`: Patch OpenAI compatibility configs.
142
- - `DELETE /v0/management/openai-compatibility`: Delete OpenAI compatibility configs.
143
- - `GET /v0/management/vertex-api-key`: List Vertex compatibility keys.
144
- - `PUT /v0/management/vertex-api-key`: Replace Vertex compatibility keys.
145
- - `PATCH /v0/management/vertex-api-key`: Patch Vertex compatibility keys.
146
- - `DELETE /v0/management/vertex-api-key`: Delete Vertex compatibility keys.
147
- - `GET /v0/management/oauth-excluded-models`: List OAuth excluded models.
148
- - `PUT /v0/management/oauth-excluded-models`: Replace OAuth excluded models.
149
- - `PATCH /v0/management/oauth-excluded-models`: Patch OAuth excluded models.
150
- - `DELETE /v0/management/oauth-excluded-models`: Delete OAuth excluded models.
151
- - `GET /v0/management/oauth-model-alias`: List OAuth model alias.
152
- - `PUT /v0/management/oauth-model-alias`: Replace OAuth model alias.
153
- - `PATCH /v0/management/oauth-model-alias`: Patch OAuth model alias.
154
- - `DELETE /v0/management/oauth-model-alias`: Delete OAuth model alias.
155
- - `GET /v0/management/auth-files`: List auth files.
156
- - `GET /v0/management/auth-files/models`: Get models for an auth file.
157
- - `GET /v0/management/model-definitions/:channel`: Get static model definitions.
158
- - `GET /v0/management/auth-files/download`: Download auth file.
159
- - `POST /v0/management/auth-files`: Upload auth file.
160
- - `DELETE /v0/management/auth-files`: Delete auth file.
161
- - `PATCH /v0/management/auth-files/status`: Enable/disable auth file.
162
- - `POST /v0/management/vertex/import`: Import Vertex credentials.
163
- - OAuth token helpers:
164
- - `GET /v0/management/anthropic-auth-url`: Start Anthropic OAuth.
165
- - `GET /v0/management/codex-auth-url`: Start Codex OAuth.
166
- - `GET /v0/management/gemini-cli-auth-url`: Start Gemini CLI OAuth.
167
- - `GET /v0/management/antigravity-auth-url`: Start Antigravity OAuth.
168
- - `GET /v0/management/qwen-auth-url`: Start Qwen OAuth.
169
- - `GET /v0/management/kimi-auth-url`: Start Kimi OAuth.
170
- - `GET /v0/management/iflow-auth-url`: Start iFlow OAuth.
171
- - `POST /v0/management/iflow-auth-url`: Submit iFlow cookie token.
172
- - `POST /v0/management/oauth-callback`: Post OAuth callback data.
173
- - `GET /v0/management/get-auth-status`: Poll OAuth status.
174
-
175
- ## Install
176
-
177
- ```bash
178
- npm i
179
- ```
180
-
181
- ## Build
182
-
183
- ```bash
184
- npm run build
185
- ```
186
-
187
- ## Exports
188
-
189
- ```ts
190
- import {
191
- // WS relay
192
- CliproxyWSProvider,
193
- CliproxyWSClient,
194
- decodeRequest,
195
- encodeResponse,
196
- encodeChunk,
197
- encodeError,
198
- type HTTPRequest,
199
- type HTTPResponse,
200
- type ProviderOptions,
201
- type ProviderEvent,
202
- type WSRequestContext,
203
-
204
- // HTTP clients by service
205
- CliproxyClient,
206
- OpenAIClient,
207
- ClaudeClient,
208
- GeminiClient,
209
- ManagementClient,
210
-
211
- // Primary request types
212
- type PrimaryOpenAIChatRequest,
213
- type PrimaryClaudeRequest,
214
- type PrimaryGeminiRequest,
215
- type PrimaryCliproxyRequest
216
- } from 'event-ws-cliproxyapi-sdk';
217
- ```
218
-
219
- ## Types (Events and Protocol)
220
-
221
- ### Events (SDK level)
222
-
223
- - `ProviderEvent`
224
- - `ws:open` – WebSocket connected
225
- - `ws:close` – WebSocket closed
226
- - `request` – server sent an `http_request`
227
- - `error` – handler error
228
-
229
- ### Protocol messages (WS level)
230
-
231
- - `WSMessageType`
232
- - `http_request` (server → client)
233
- - `http_response` (client → server)
234
- - `stream_start` / `stream_chunk` / `stream_end` (client → server)
235
- - `error` (client → server)
236
- - `ping` / `pong`
237
-
238
- ### Request/Response types
239
-
240
- - `HTTPRequest`
241
- - `method`, `url`, `headers`, `body`, `sent_at`
242
- - `HTTPResponse`
243
- - `status`, `headers`, `body`
244
-
245
- ### Helper context
246
-
247
- - `WSRequestContext`
248
- - `respond(resp)`
249
- - `streamStart(status?, headers?)`
250
- - `streamChunk(chunk)`
251
- - `streamEnd()`
252
- - `error(message, status?)`
253
-
254
- ## Usage (Provider Relay)
255
-
256
- ```ts
257
- import { CliproxyWSProvider } from 'event-ws-cliproxyapi-sdk';
258
-
259
- const provider = new CliproxyWSProvider({
260
- baseUrl: 'http://127.0.0.1:8317',
261
- accessKey: 'andev'
262
- });
263
-
264
- await provider.connect({
265
- onEvent: (ev) => {
266
- if (ev.type === 'ws:open') console.log('ws open');
267
- if (ev.type === 'ws:close') console.log('ws close', ev.code, ev.reason);
268
- },
269
- onRequest: async (req, ctx) => {
270
- if (req.url === '/v1/cliproxy/chat') {
271
- ctx.streamStart(200, { 'Content-Type': 'text/plain' });
272
- ctx.streamChunk('hello ');
273
- ctx.streamChunk('world');
274
- ctx.streamEnd();
275
- return;
276
- }
277
- ctx.respond({ status: 404, body: 'not found' });
278
- }
279
- });
280
-
281
- provider.close();
282
- ```
283
-
284
- ## Usage (HTTP Client)
285
-
286
- ```ts
287
- import { CliproxyClient, OpenAIClient, ClaudeClient, GeminiClient, ManagementClient } from 'event-ws-cliproxyapi-sdk';
288
-
289
- const cliproxy = new CliproxyClient({
290
- baseUrl: 'http://127.0.0.1:8317',
291
- accessKey: 'your-access-key',
292
- managementKey: 'your-management-key'
293
- });
294
-
295
- // Public: list auths
296
- const auths = await cliproxy.getCliproxyAuths();
297
-
298
- // OpenAI-compatible chat
299
- const openai = new OpenAIClient({ baseUrl: 'http://127.0.0.1:8317', accessKey: 'your-access-key' });
300
- await openai.postChatCompletions({
301
- model: 'gpt-4o-mini',
302
- messages: [
303
- { role: 'user', content: [{ type: 'text', text: 'hello' }] }
304
- ]
305
- });
306
- ```
307
-
308
- ## Response Types
309
-
310
- OpenAI-compatible
311
- - `OpenAIChatCompletionResponse` (non-stream)
312
- - `OpenAIChatCompletionChunk` (stream)
313
- - `OpenAICompletionResponse` (non-stream)
314
- - `OpenAICompletionChunk` (stream)
315
- - `OpenAIResponsesResponse` (non-stream)
316
- - `OpenAIResponsesChunk` (stream)
317
-
318
- Claude-compatible
319
- - `ClaudeMessagesResponse` (non-stream)
320
- - `ClaudeStreamEvent` (stream)
321
-
322
- Gemini-compatible
323
- - `GeminiGenerateContentResponse` (non-stream)
324
- - `GeminiStreamChunk` (stream)
325
-
326
- Errors
327
- - `OpenAIErrorResponse` (OpenAI-style `{ error: { message, type, code? } }`)
328
- - `ErrorResponse` (management `{ error: string, message?: string }`)
329
- - `StatusResponse` (status polling `{ status: "ok" | "error" | "wait", error?: string }`)
330
- - `APIError` (thrown by service clients on non-2xx)
331
-
332
- ## Response Examples (OK / Failed)
333
-
334
- OpenAI Chat Completions (OK, non-stream):
335
- ```json
336
- {
337
- "id": "chatcmpl_123",
338
- "object": "chat.completion",
339
- "created": 1730000000,
340
- "model": "gpt-4o-mini",
341
- "choices": [
342
- {
343
- "index": 0,
344
- "message": { "role": "assistant", "content": "hello" },
345
- "finish_reason": "stop"
346
- }
347
- ],
348
- "usage": { "total_tokens": 10 }
349
- }
350
- ```
351
-
352
- OpenAI Chat Completions (Failed):
353
- ```json
354
- {
355
- "error": {
356
- "message": "Invalid request: Missing model",
357
- "type": "invalid_request_error",
358
- "code": "invalid_request_error"
359
- }
360
- }
361
- ```
362
-
363
- Claude Messages (OK, non-stream):
364
- ```json
365
- {
366
- "id": "msg_123",
367
- "type": "message",
368
- "role": "assistant",
369
- "model": "claude-3-5-sonnet",
370
- "content": [{ "type": "text", "text": "hello" }],
371
- "stop_reason": "end_turn",
372
- "usage": { "input_tokens": 5, "output_tokens": 5 }
373
- }
374
- ```
375
-
376
- Claude Messages (Failed):
377
- ```json
378
- { "error": "invalid request" }
379
- ```
380
-
381
- Gemini GenerateContent (OK, non-stream):
382
- ```json
383
- {
384
- "candidates": [
385
- {
386
- "content": {
387
- "role": "model",
388
- "parts": [{ "text": "hello" }]
389
- },
390
- "finishReason": "STOP",
391
- "index": 0
392
- }
393
- ]
394
- }
395
- ```
396
-
397
- Gemini GenerateContent (Failed):
398
- ```json
399
- { "error": "invalid request" }
400
- ```
401
-
402
- Management (Failed):
403
- ```json
404
- { "error": "invalid management key" }
405
- ```
406
-
407
- ## Image + Text in One Message
408
-
409
- ```ts
410
- await openai.postChatCompletions({
411
- model: 'gpt-4o-mini',
412
- messages: [
413
- {
414
- role: 'user',
415
- content: [
416
- { type: 'text', text: 'describe this image' },
417
- { type: 'image_url', image_url: { url: 'https://example.com/cat.jpg' } }
418
- ]
419
- }
420
- ]
421
- });
422
- ```
423
-
424
- ## Notes
425
-
426
- - For WS relay, if `ws-auth: true`, pass `accessKey` as `Authorization: Bearer ...`.
427
- - Management APIs require `managementKey` (or local password for `/keep-alive` if enabled).
428
- - HTTP client returns `Response` for streaming endpoints; parse SSE or chunks based on your client.
1
+ # @redonvn/event-ws-cliproxyapi-sdk
2
+
3
+ TypeScript SDK for CLIProxyAPI with two main capabilities:
4
+ - HTTP clients for OpenAI/Claude/Gemini-compatible and management endpoints
5
+ - Provider-side WebSocket relay for `/v1/ws`
6
+
7
+ ## Why This SDK
8
+
9
+ - Strong TypeScript types for request/response payloads
10
+ - Unified auth model (`accessKey`, `managementKey`, `localPassword`)
11
+ - Shared error model (`APIError`) across all HTTP clients
12
+ - Explicit client modules by domain: `OpenAIClient`, `ClaudeClient`, `GeminiClient`, `CliproxyClient`, `ManagementClient`, `CliproxyWSProvider`
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm i @redonvn/event-ws-cliproxyapi-sdk
18
+ ```
19
+
20
+ ## Requirements
21
+
22
+ - Node.js with `fetch` support (Node 18+ recommended)
23
+ - TypeScript 5+ (if consuming types in TS)
24
+
25
+ If your runtime does not provide `fetch`, pass `options.fetch` when creating clients.
26
+
27
+ ## Quick Start
28
+
29
+ ```ts
30
+ import {
31
+ CliproxyClient,
32
+ OpenAIClient,
33
+ ClaudeClient,
34
+ GeminiClient,
35
+ ManagementClient,
36
+ APIError
37
+ } from '@redonvn/event-ws-cliproxyapi-sdk';
38
+
39
+ const baseUrl = 'http://127.0.0.1:8317';
40
+
41
+ const cliproxy = new CliproxyClient({
42
+ baseUrl,
43
+ accessKey: process.env.ACCESS_KEY,
44
+ managementKey: process.env.MANAGEMENT_KEY,
45
+ localPassword: process.env.LOCAL_PASSWORD
46
+ });
47
+
48
+ const openai = new OpenAIClient({ baseUrl, accessKey: process.env.ACCESS_KEY });
49
+ const claude = new ClaudeClient({ baseUrl, accessKey: process.env.ACCESS_KEY });
50
+ const gemini = new GeminiClient({ baseUrl, accessKey: process.env.ACCESS_KEY });
51
+ const management = new ManagementClient({ baseUrl, managementKey: process.env.MANAGEMENT_KEY });
52
+
53
+ try {
54
+ const models = await openai.getModels();
55
+ console.log(models.data.length);
56
+ } catch (err) {
57
+ if (err instanceof APIError) {
58
+ console.error(err.status, err.message, err.payload);
59
+ }
60
+ }
61
+ ```
62
+
63
+ ## Auth Model
64
+
65
+ - `accessKey`: used for access-protected public inference endpoints
66
+ - `managementKey`: used for `/v0/management/*`
67
+ - `localPassword`: used for local-protected endpoints such as `/keep-alive`
68
+
69
+ You can update keys at runtime:
70
+ - `setAccessKey(key?)`
71
+ - `setManagementKey(key?)`
72
+ - `setLocalPassword(value?)`
73
+
74
+ ## Exported Modules
75
+
76
+ From package root (`src/index.ts`):
77
+ - `openai/*`
78
+ - `claude/*`
79
+ - `gemini/*`
80
+ - `cliproxy/*`
81
+ - `management/*`
82
+ - `ws/*`
83
+ - `shared/*`
84
+
85
+ Core exports:
86
+ - Clients: `OpenAIClient`, `ClaudeClient`, `GeminiClient`, `CliproxyClient`, `ManagementClient`
87
+ - WS relay: `CliproxyWSProvider`, `CliproxyWSClient`
88
+ - WS codec helpers: `decodeRequest`, `encodeResponse`, `decodeResponse`, `encodeChunk`, `decodeChunk`, `encodeError`, `decodeError`
89
+ - Errors: `APIError`, `isOpenAIError`, `isStatusError`, `isManagementError`
90
+ - Full payload types from `shared/types`
91
+
92
+ ## HTTP Clients
93
+
94
+ ### `OpenAIClient`
95
+
96
+ Methods:
97
+ - `getModels()` -> `GET /v1/models`
98
+ - `postChatCompletions(body)` -> `POST /v1/chat/completions`
99
+ - `postCompletions(body)` -> `POST /v1/completions`
100
+ - `postResponses(body)` -> `POST /v1/responses`
101
+ - `postResponsesCompact(body)` -> `POST /v1/responses/compact`
102
+
103
+ Example:
104
+
105
+ ```ts
106
+ const res = await openai.postChatCompletions({
107
+ model: 'gpt-4o-mini',
108
+ messages: [{ role: 'user', content: 'hello' }],
109
+ stream: false
110
+ });
111
+
112
+ const json = await res.json();
113
+ console.log(json);
114
+ ```
115
+
116
+ ### `ClaudeClient`
117
+
118
+ Methods:
119
+ - `getModels()` -> `GET /v1/models` (adds `User-Agent: claude-cli`)
120
+ - `postMessages(body)` -> `POST /v1/messages`
121
+ - `postMessagesCountTokens(body)` -> `POST /v1/messages/count_tokens`
122
+
123
+ ### `GeminiClient`
124
+
125
+ Methods:
126
+ - `getModels()` -> `GET /v1beta/models`
127
+ - `postModelsAction(action, body)` -> `POST /v1beta/models/{action}`
128
+ - `getModelsAction(action, query?)` -> `GET /v1beta/models/{action}`
129
+ - `postV1Internal(method, body)` -> `POST /v1internal:{method}`
130
+
131
+ ### `CliproxyClient`
132
+
133
+ Methods:
134
+ - `getRoot()` -> `GET /`
135
+ - `getManagementHtml()` -> `GET /management.html`
136
+ - `keepAlive()` -> `GET /keep-alive`
137
+ - OAuth callbacks:
138
+ - `anthropicCallback(query)` -> `GET /anthropic/callback`
139
+ - `codexCallback(query)` -> `GET /codex/callback`
140
+ - `googleCallback(query)` -> `GET /google/callback`
141
+ - `iflowCallback(query)` -> `GET /iflow/callback`
142
+ - `antigravityCallback(query)` -> `GET /antigravity/callback`
143
+ - CLIProxy endpoints:
144
+ - `getCliproxyAuths(query?)` -> `GET /v1/cliproxy/auths`
145
+ - `getCliproxyModels(query?)` -> `GET /v1/cliproxy/models`
146
+ - `postCliproxyChat(body)` -> `POST /v1/cliproxy/chat`
147
+
148
+ ### `ManagementClient`
149
+
150
+ Covers management APIs under `/v0/management/*`, including:
151
+ - usage import/export
152
+ - runtime config and YAML config
153
+ - logging and debug flags
154
+ - key/config CRUD (`api-keys`, `claude-api-key`, `gemini-api-key`, `codex-api-key`, `vertex-api-key`, `openai-compatibility`)
155
+ - routing/retry/quota flags
156
+ - auth files and model definitions
157
+ - OAuth helper flows
158
+
159
+ Also includes:
160
+ - `getDesktopKeys()` -> `GET /desktop/keys`
161
+ - `getManagementApiKeys()` convenience fallback helper
162
+
163
+ ## Streaming Responses
164
+
165
+ Many inference methods return raw `Response` for stream compatibility.
166
+ - For SSE/event-stream, read `response.body`
167
+ - For non-stream mode, parse with `await response.json()` or `await response.text()`
168
+
169
+ ## WebSocket Relay (Provider Side)
170
+
171
+ Use `CliproxyWSProvider` to handle server forwarded requests over `/v1/ws`.
172
+
173
+ ```ts
174
+ import { CliproxyWSProvider } from '@redonvn/event-ws-cliproxyapi-sdk';
175
+
176
+ const provider = new CliproxyWSProvider({
177
+ baseUrl: 'http://127.0.0.1:8317',
178
+ accessKey: process.env.ACCESS_KEY
179
+ });
180
+
181
+ await provider.connect({
182
+ onEvent: (ev) => {
183
+ if (ev.type === 'ws:open') console.log('connected');
184
+ if (ev.type === 'ws:close') console.log('closed', ev.code, ev.reason);
185
+ if (ev.type === 'error') console.error(ev.error);
186
+ },
187
+ onRequest: async (req, ctx) => {
188
+ if (req.url === '/health') {
189
+ ctx.respond({ status: 200, body: 'ok' });
190
+ return;
191
+ }
192
+
193
+ ctx.streamStart(200, { 'Content-Type': 'text/plain' });
194
+ ctx.streamChunk('hello ');
195
+ ctx.streamChunk('world');
196
+ ctx.streamEnd();
197
+ }
198
+ });
199
+
200
+ provider.close();
201
+ ```
202
+
203
+ WS message/event types are exported from `ws/types`.
204
+
205
+ ## Error Handling
206
+
207
+ All non-2xx HTTP responses throw `APIError`.
208
+
209
+ ```ts
210
+ import { APIError, isOpenAIError, isManagementError } from '@redonvn/event-ws-cliproxyapi-sdk';
211
+
212
+ try {
213
+ await management.getConfig();
214
+ } catch (err) {
215
+ if (err instanceof APIError) {
216
+ if (isOpenAIError(err.payload)) {
217
+ console.error('openai error:', err.payload.error.message);
218
+ } else if (isManagementError(err.payload)) {
219
+ console.error('management error:', err.payload.error);
220
+ } else {
221
+ console.error(err.status, err.message);
222
+ }
223
+ }
224
+ }
225
+ ```
226
+
227
+ ## Common Types
228
+
229
+ Selected primary request aliases:
230
+ - `PrimaryOpenAIChatRequest`
231
+ - `PrimaryOpenAICompletionRequest`
232
+ - `PrimaryOpenAIResponsesRequest`
233
+ - `PrimaryClaudeRequest`
234
+ - `PrimaryGeminiRequest`
235
+ - `PrimaryCliproxyRequest`
236
+
237
+ Protocol and shared types:
238
+ - JSON primitives/objects (`JsonValue`, `JsonObject`)
239
+ - model/config/auth entities
240
+ - OpenAI/Claude/Gemini compatible request/response types
241
+
242
+ ## Development
243
+
244
+ ```bash
245
+ npm i
246
+ npm run build
247
+ ```
248
+
249
+ Build output:
250
+ - JS: `dist/*.js`
251
+ - Declarations: `dist/*.d.ts`
252
+
253
+ ## Notes
254
+
255
+ - WebSocket auth: if server has `ws-auth: true`, provide `accessKey`.
256
+ - Management endpoints require `managementKey`.
257
+ - `keepAlive()` uses local auth (`localPassword`) if server enforces it.
258
+ - This SDK is transport-oriented; retries/backoff are intentionally left to the consumer.