codexmate 0.0.54 → 0.0.56

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 (42) hide show
  1. package/README.md +3 -0
  2. package/README.vi.md +172 -0
  3. package/README.zh.md +2 -0
  4. package/cli/local-bridge.js +221 -22
  5. package/cli.js +666 -6
  6. package/package.json +1 -1
  7. package/web-ui/app.js +40 -0
  8. package/web-ui/logic.claude.mjs +8 -0
  9. package/web-ui/modules/app.computed.session.mjs +210 -0
  10. package/web-ui/modules/app.methods.claude-config.mjs +196 -13
  11. package/web-ui/modules/app.methods.codex-config.mjs +294 -65
  12. package/web-ui/modules/app.methods.index.mjs +4 -0
  13. package/web-ui/modules/app.methods.navigation.mjs +7 -1
  14. package/web-ui/modules/app.methods.provider-cache.mjs +223 -0
  15. package/web-ui/modules/app.methods.providers.mjs +15 -1
  16. package/web-ui/modules/app.methods.runtime.mjs +7 -2
  17. package/web-ui/modules/app.methods.session-actions.mjs +36 -0
  18. package/web-ui/modules/app.methods.session-browser.mjs +3 -0
  19. package/web-ui/modules/app.methods.session-trash.mjs +3 -0
  20. package/web-ui/modules/app.methods.startup-claude.mjs +47 -4
  21. package/web-ui/modules/app.methods.web-ui-preferences.mjs +161 -0
  22. package/web-ui/modules/i18n/locales/en.mjs +106 -3
  23. package/web-ui/modules/i18n/locales/ja.mjs +103 -3
  24. package/web-ui/modules/i18n/locales/vi.mjs +950 -0
  25. package/web-ui/modules/i18n/locales/zh-tw.mjs +103 -3
  26. package/web-ui/modules/i18n/locales/zh.mjs +103 -3
  27. package/web-ui/modules/provider-default-names.mjs +25 -0
  28. package/web-ui/partials/index/layout-header.html +18 -5
  29. package/web-ui/partials/index/modal-health-check.html +69 -5
  30. package/web-ui/partials/index/modals-basic.html +182 -0
  31. package/web-ui/partials/index/panel-config-codex.html +2 -2
  32. package/web-ui/partials/index/panel-sessions.html +99 -19
  33. package/web-ui/partials/index/panel-settings.html +20 -0
  34. package/web-ui/res/web-ui-render.precompiled.js +742 -113
  35. package/web-ui/session-helpers.mjs +4 -1
  36. package/web-ui/styles/layout-shell.css +51 -1
  37. package/web-ui/styles/responsive.css +98 -0
  38. package/web-ui/styles/sessions-preview.css +212 -2
  39. package/web-ui/styles/sessions-toolbar-trash.css +61 -18
  40. package/web-ui/styles/settings-panel.css +398 -0
  41. package/web-ui/styles/skills-list.css +122 -0
  42. package/web-ui/styles/titles-cards.css +52 -0
package/README.md CHANGED
@@ -10,6 +10,7 @@
10
10
  <a href="https://sakurabytecore.github.io/codexmate/">[Documentation]</a>
11
11
  <a href="#quick-start">[Quick Start]</a>
12
12
  <a href="README.zh.md">[简体中文]</a>
13
+ <a href="README.vi.md">[Tiếng Việt]</a>
13
14
  </p>
14
15
 
15
16
  [![Version](https://img.shields.io/npm/v/codexmate?style=flat-square&color=A179FF)](https://www.npmjs.com/package/codexmate)
@@ -57,6 +58,7 @@ Unlike simple wrappers, Codex Mate acts as a **Local Agent Bridge**:
57
58
  - **OpenAI-Compatible Bridge**: Use Codex with any OpenAI-compatible UI by normalizing the Responses API; the built-in Codex conversion also fills and normalizes Codex fingerprint headers such as `User-Agent`, `Version`, `OpenAI-Beta`, and `Originator` so upstream providers see an official Codex CLI-shaped request.
58
59
  - **Claude Provider Bridge**: Connect Claude Code to OpenAI Chat Completions-compatible providers and Ollama through the built-in local Claude-compatible proxy.
59
60
  - **OpenCode Provider Control**: Manage OpenCode provider/model selection with a CodexMate-owned provider store under `~/.codexmate`, projecting only the active provider into native OpenCode config to avoid polluting or deleting user-owned settings.
61
+ - **Provider Health Cleanup**: Probe local Codex and Claude provider routes, surface failed configs in one modal, and bulk-clean selected broken providers without touching healthy or protected entries.
60
62
  - **Skills Marketplace**: A local-first market to share and import skills between different agent apps.
61
63
  - **Prompt File Editor**: Unified editor for global and project-level `CLAUDE.md` and `AGENTS.md` with auto-detection of project paths.
62
64
  - **Task Orchestrator**: Plan and execute complex tasks with dependency tracking.
@@ -76,6 +78,7 @@ Unlike simple wrappers, Codex Mate acts as a **Local Agent Bridge**:
76
78
  | **OpenAI Bridge** | ✅ | Convert Codex Responses API to standard OpenAI format and attach/normalize Codex fingerprints in the built-in conversion |
77
79
  | **Claude Provider Bridge** | ✅ | Connect Claude Code to OpenAI Chat Completions-compatible providers and Ollama via the built-in Claude-compatible proxy |
78
80
  | **OpenCode Provider Store** | ✅ | Keep multiple OpenCode providers in `~/.codexmate` while projecting only the selected provider to native OpenCode config |
81
+ | **Provider Health Check** | ✅ | Probe local Codex/Claude provider routes, highlight failed configs, and bulk-remove selected broken providers safely |
79
82
  | **Prompt Templates** | ✅ | Reusable prompt plugins with variables |
80
83
  | **Prompt File Editor** | ✅ | Edit global and project-level CLAUDE.md / AGENTS.md with auto-detect and path switching |
81
84
  | **MCP Integration** | ✅ | Expose local tools and resources via MCP stdio |
package/README.vi.md ADDED
@@ -0,0 +1,172 @@
1
+ <div align="center">
2
+
3
+ <img src="site/.vitepress/public/images/logo.png" alt="Codex Mate logo" width="160" />
4
+
5
+ # Codex Mate
6
+
7
+ **Một dashboard duy nhất cho tất cả AI coding agent cục bộ của bạn. Chuyển đổi provider, quản lý phiên làm việc và điều phối tác vụ giữa Codex, Claude Code và OpenClaw. Không cloud, trung tâm điều khiển agent hoàn toàn cục bộ.**
8
+
9
+ <p>
10
+ <a href="https://sakurabytecore.github.io/codexmate/">[Tài liệu]</a>
11
+ <a href="#bắt-đầu-nhanh">[Bắt đầu nhanh]</a>
12
+ <a href="README.md">[English]</a>
13
+ <a href="README.zh.md">[简体中文]</a>
14
+ </p>
15
+
16
+ [![Version](https://img.shields.io/npm/v/codexmate?style=flat-square&color=A179FF)](https://www.npmjs.com/package/codexmate)
17
+ [![Build](https://img.shields.io/github/actions/workflow/status/SakuraByteCore/codexmate/release.yml?style=flat-square&color=44cc11)](https://github.com/SakuraByteCore/codexmate/actions/workflows/release.yml)
18
+ [![Downloads](https://img.shields.io/npm/dt/codexmate?style=flat-square)](https://www.npmjs.com/package/codexmate)
19
+ [![Install](https://img.shields.io/badge/cài%20đặt-brew%20%7C%20curl%20%7C%20npm-0A0?style=flat-square)](#bắt-đầu-nhanh)
20
+ [![Platform](https://img.shields.io/badge/nền%20tảng-Termux%20%7C%20Linux%20%7C%20macOS%20%7C%20Windows-555?style=flat-square)](#bắt-đầu-nhanh)
21
+ [![Node](https://img.shields.io/node/v/codexmate?style=flat-square&logo=node.js&logoColor=white)](https://nodejs.org/)
22
+ [![License](https://img.shields.io/npm/l/codexmate?style=flat-square)](LICENSE)
23
+ [![Stars](https://img.shields.io/github/stars/SakuraByteCore/codexmate?style=flat-square&color=gold)](https://github.com/SakuraByteCore/codexmate/stargazers)
24
+ [![Issues](https://img.shields.io/github/issues/SakuraByteCore/codexmate?style=flat-square&color=ff69b4)](https://github.com/SakuraByteCore/codexmate/issues)
25
+
26
+ <br />
27
+
28
+ <img src="site/.vitepress/public/images/readme-hero.png" alt="Giao diện Codex Mate" width="100%" />
29
+
30
+ </div>
31
+
32
+ ---
33
+
34
+ > [!TIP]
35
+ > **Ưu tiên cục bộ**: Toàn bộ cấu hình và phiên làm việc được lưu trong thư mục home của bạn. Không có telemetry, không cần tài khoản cloud.
36
+
37
+ > [!IMPORTANT]
38
+ > Dự án đang ở giai đoạn đầu. Chúng tôi đang tìm kiếm các nhà phát triển để cùng xây dựng hệ sinh thái agent cục bộ!
39
+
40
+ ## Codex Mate là gì?
41
+
42
+ Bạn có bao giờ cảm thấy rối khi phải quản lý nhiều AI agent cục bộ? Mỗi tool lại có định dạng cấu hình, nơi lưu phiên và thư mục skill riêng.
43
+
44
+ **Codex Mate** cung cấp một trung tâm điều khiển thống nhất để giải quyết sự hỗn loạn đó. Đây là CLI + Web UI ưu tiên cục bộ, được thiết kế để quản lý [Codex](https://github.com/openai/codex), [Claude Code](https://github.com/anthropic-ai/claude-code) và [OpenClaw](https://github.com/moeru-ai/openclaw) một cách liền mạch.
45
+
46
+ ### Điểm nổi bật
47
+
48
+ Khác với các wrapper đơn giản, Codex Mate hoạt động như một **Agent Bridge cục bộ**:
49
+ - **Trình duyệt phiên thống nhất**: Tìm kiếm và xuất phiên làm việc từ tất cả tool trong một nơi duy nhất.
50
+ - **Bridge tương thích OpenAI**: Dùng Codex với bất kỳ UI nào hỗ trợ OpenAI bằng cách chuẩn hóa Responses API.
51
+ - **Dọn dẹp provider lỗi**: Kiểm tra route provider cục bộ của Codex/Claude, hiển thị cấu hình lỗi trong một modal và xóa hàng loạt các provider hỏng đã chọn mà không chạm vào mục khỏe mạnh hoặc được bảo vệ.
52
+ - **Chợ skill cục bộ**: Chia sẻ và nhập skill giữa các app agent khác nhau.
53
+ - **Điều phối tác vụ**: Lập kế hoạch và thực thi tác vụ phức tạp với theo dõi phụ thuộc.
54
+
55
+ ---
56
+
57
+ ## Tiến độ hiện tại
58
+
59
+ | Tính năng | Trạng thái | Mô tả |
60
+ | --- | --- | --- |
61
+ | **Quản lý Provider** | ✅ | Chuyển đổi provider/model cho Codex, Claude và OpenClaw |
62
+ | **Đồng bộ Agent trực tiếp** | ✅ | Giám sát cấu hình & trạng thái Codex/Claude theo thời gian thực |
63
+ | **Trình duyệt phiên** | ✅ | Liệt kê, lọc và xuất phiên (Codex/Claude/Gemini) |
64
+ | **Phân tích sử dụng** | ✅ | Trực quan hóa xu hướng tin nhắn và dự án nổi bật |
65
+ | **Chợ skill cục bộ** | ✅ | Import/export skill giữa các app agent |
66
+ | **Hàng đợi tác vụ** | ✅ | Thực thi tác vụ theo DAG và xem log |
67
+ | **Bridge OpenAI** | ✅ | Chuyển đổi Codex Responses API sang định dạng OpenAI chuẩn |
68
+ | **Kiểm tra sức khỏe Provider** | ✅ | Kiểm tra route provider Codex/Claude, đánh dấu cấu hình lỗi và xóa hàng loạt các provider hỏng đã chọn một cách an toàn |
69
+ | **Mẫu Prompt** | ✅ | Plugin prompt tái sử dụng được với hỗ trợ biến |
70
+ | **Tích hợp MCP** | ✅ | Expose tool và resource cục bộ qua MCP stdio |
71
+ | **Tự động cập nhật** | ✅ | Cập nhật nhanh qua `codexmate update` |
72
+
73
+ ---
74
+
75
+ ## Bắt đầu nhanh
76
+
77
+ ### Cài đặt qua Homebrew (macOS / Linux)
78
+
79
+ ```bash
80
+ brew tap SakuraByteCore/codexmate
81
+ brew install codexmate
82
+ ```
83
+
84
+ Yêu cầu [Node.js](https://nodejs.org/) (`brew install node` nếu chưa có).
85
+
86
+ ### Cài đặt qua npm
87
+
88
+ ```bash
89
+ npm install -g codexmate
90
+ codexmate run
91
+ ```
92
+
93
+ Nếu cổng mặc định `3737` bận, Codex Mate tự động thử cổng kế tiếp (`3738`, `3739`, ...). Để chỉ định cổng cố định:
94
+
95
+ ```bash
96
+ CODEXMATE_PORT=8080 codexmate run
97
+ ```
98
+
99
+ Windows PowerShell:
100
+
101
+ ```powershell
102
+ $env:CODEXMATE_PORT=8080; codexmate run
103
+ ```
104
+
105
+ ### Cài đặt qua curl (Standalone)
106
+
107
+ ```bash
108
+ curl -fsSL https://raw.githubusercontent.com/SakuraByteCore/codexmate/main/scripts/install.sh | bash
109
+ ```
110
+
111
+ ### Agent được hỗ trợ
112
+
113
+ - **Codex**: `npm install -g @openai/codex`
114
+ - **Claude Code**: `npm install -g @anthropic-ai/claude-code`
115
+ - **Gemini CLI**: `npm install -g @google/gemini-cli`
116
+ - **CodeBuddy**: `npm install -g @tencent-ai/codebuddy-code`
117
+ - **OpenCode**: xem [tài liệu chính thức OpenCode](https://opencode.ai/)
118
+
119
+ ---
120
+
121
+ ## Kiến trúc
122
+
123
+ ```mermaid
124
+ %%{ init: { 'flowchart': { 'curve': 'catmullRom' } } }%%
125
+ flowchart TD
126
+ User([Người dùng])
127
+ CLI[CLI]
128
+ WebUI[Web UI]
129
+ MCP[MCP Server]
130
+
131
+ subgraph Mate [Codex Mate Core]
132
+ API[HTTP API]
133
+ Config[Config Engine]
134
+ Session[Quản lý phiên]
135
+ Skills[Chợ Skill]
136
+ Tasks[Thực thi tác vụ]
137
+ end
138
+
139
+ subgraph Local [Hệ thống tệp cục bộ]
140
+ CodexDir[~/.codex]
141
+ ClaudeDir[~/.claude]
142
+ ClawDir[~/.openclaw]
143
+ State[Phiên/Sử dụng/Thùng rác]
144
+ end
145
+
146
+ User --> CLI & WebUI & MCP
147
+ CLI & WebUI & MCP --> API
148
+
149
+ API --> Config & Session & Skills & Tasks
150
+
151
+ Config --> CodexDir & ClaudeDir & ClawDir
152
+ Session --> State
153
+ Skills --> Local
154
+ ```
155
+
156
+ ---
157
+
158
+ ## Lời cảm ơn
159
+
160
+ Cảm ơn tất cả những người đóng góp cho Codex Mate ❤️
161
+
162
+ <a href="https://github.com/SakuraByteCore/codexmate/graphs/contributors">
163
+ <img src="https://contrib.rocks/image?repo=SakuraByteCore/codexmate" alt="Contributors" />
164
+ </a>
165
+
166
+ ## Lịch sử Star
167
+
168
+ [![Star History Chart](https://api.star-history.com/svg?repos=SakuraByteCore/codexmate&type=Date)](https://star-history.com/#SakuraByteCore/codexmate&Date)
169
+
170
+ ## Giấy phép
171
+
172
+ Apache-2.0
package/README.zh.md CHANGED
@@ -57,6 +57,7 @@
57
57
  - **OpenAI 兼容桥接**:通过归一化 Responses API,让 Codex 能够与任何支持 OpenAI 格式的 UI 配合使用;内建 Codex 转换会补齐并规范化 `User-Agent`、`Version`、`OpenAI-Beta`、`Originator` 等 Codex 指纹,对上游伪装为官方 Codex CLI 请求。
58
58
  - **Claude Provider 桥接**:通过内建本地 Claude 兼容代理,让 Claude Code 接入 OpenAI Chat Completions 兼容 provider 与 Ollama。
59
59
  - **OpenCode Provider 控制**:在 `~/.codexmate` 下维护 CodexMate 自有的 OpenCode 多 provider 存储,只将当前选中的 provider 投影到 OpenCode 原生配置,避免污染或误删用户已有配置。
60
+ - **Provider 健康清理**:探测本地 Codex 与 Claude provider 路由,在同一个弹窗里集中展示失败配置,并批量清理已选坏配置,不影响正常或受保护项。
60
61
  - **Skills 市场**:本地优先的市场,支持在不同的智能体应用之间共享和导入 Skills。
61
62
  - **提示词文件编辑器**:统一编辑全局和项目级 `CLAUDE.md` 与 `AGENTS.md`,支持项目路径自动检测。
62
63
  - **任务编排器**:支持带有依赖跟踪的复杂任务规划与执行。
@@ -76,6 +77,7 @@
76
77
  | **OpenAI 桥接** | ✅ | 将 Codex Responses API 转换为标准 OpenAI 格式,并在内建转换中附加/规范化 Codex 指纹 |
77
78
  | **Claude Provider 桥接** | ✅ | 通过内建 Claude 兼容代理,让 Claude Code 接入 OpenAI Chat Completions 兼容 provider 与 Ollama |
78
79
  | **OpenCode Provider 存储** | ✅ | 在 `~/.codexmate` 中保留多个 OpenCode provider,只将当前选中的 provider 投影到 OpenCode 原生配置 |
80
+ | **Provider 健康检查** | ✅ | 探测本地 Codex/Claude provider 路由,标记失败配置,并安全批量移除已选坏配置 |
79
81
  | **提示词模板** | ✅ | 支持变量的可复用提示词插件 |
80
82
  | **提示词文件编辑器** | ✅ | 编辑全局和项目级 CLAUDE.md / AGENTS.md,支持自动检测与路径切换 |
81
83
  | **MCP 集成** | ✅ | 通过 MCP stdio 暴露本地工具与资源 |
@@ -20,6 +20,14 @@ const {
20
20
  isLoopbackAddress
21
21
  } = require('./openai-bridge');
22
22
  const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
23
+ const {
24
+ buildBuiltinClaudeChatCompletionsRequest,
25
+ buildBuiltinClaudeOllamaChatRequest,
26
+ buildAnthropicMessageFromChatCompletion,
27
+ buildAnthropicMessageFromOllamaChat,
28
+ buildAnthropicModelsPayload,
29
+ buildAnthropicStreamEvents
30
+ } = require('./claude-proxy');
23
31
 
24
32
  const BUILTIN_PROXY_PROVIDER_NAME = 'codexmate-proxy';
25
33
  const BUILTIN_LOCAL_PROVIDER_NAME = 'local';
@@ -28,6 +36,52 @@ const CLAUDE_LOCAL_EXCLUDED_KEY = 'claudeLocalExcluded';
28
36
  const CIRCUIT_BREAKER_THRESHOLD = 3;
29
37
  const CIRCUIT_BREAKER_COOLDOWN_MS = 5 * 60 * 1000;
30
38
 
39
+ function normalizeClaudeLocalTargetApi(value) {
40
+ const raw = typeof value === 'string' ? value.trim().toLowerCase() : '';
41
+ if (raw === 'chat_completions' || raw === 'chat-completions' || raw === 'chat/completions') return 'chat_completions';
42
+ if (raw === 'ollama') return 'ollama';
43
+ return 'responses';
44
+ }
45
+
46
+ function normalizeClaudeLocalSuffix(pathname) {
47
+ const suffix = String(pathname || '').replace(/^\/bridge\/claude-local\/?/, '').replace(/^\/+/, '');
48
+ if (!suffix || suffix === 'v1') return '';
49
+ return suffix.replace(/^v1\/?/, '');
50
+ }
51
+
52
+ function joinClaudeLocalUpstreamUrl(baseUrl, pathSuffix) {
53
+ const suffix = typeof pathSuffix === 'string' ? pathSuffix.replace(/^\/+/, '') : '';
54
+ if (suffix === 'api/tags' || suffix === 'api/chat') {
55
+ const normalized = normalizeBaseUrl(baseUrl);
56
+ return normalized ? `${normalized}/${suffix}` : '';
57
+ }
58
+ return joinApiUrl(baseUrl, suffix);
59
+ }
60
+
61
+ function buildClaudeLocalAuthHeaders(entry, requestToken, targetApi, expectedToken = '') {
62
+ const headers = { 'Content-Type': 'application/json' };
63
+ const trimmedRequestToken = typeof requestToken === 'string' ? requestToken.trim() : '';
64
+ const bridgeToken = typeof expectedToken === 'string' ? expectedToken.trim() : '';
65
+ const upstreamRequestToken = trimmedRequestToken && (!bridgeToken || trimmedRequestToken !== bridgeToken)
66
+ ? trimmedRequestToken
67
+ : '';
68
+ const token = entry && typeof entry.apiKey === 'string' && entry.apiKey.trim()
69
+ ? entry.apiKey.trim()
70
+ : upstreamRequestToken;
71
+ if (!token) {
72
+ if (targetApi === 'responses') headers['anthropic-version'] = '2023-06-01';
73
+ return headers;
74
+ }
75
+ const bareToken = token.replace(/^Bearer\s+/i, '');
76
+ if (targetApi === 'responses') {
77
+ headers['x-api-key'] = bareToken;
78
+ headers['anthropic-version'] = '2023-06-01';
79
+ } else {
80
+ headers.Authorization = /^Bearer\s+/i.test(token) ? token : `Bearer ${token}`;
81
+ }
82
+ return headers;
83
+ }
84
+
31
85
  function buildUpstreamPool(readConfigFn, openaiBridgeFile, excludedProviders) {
32
86
  let config;
33
87
  try { config = readConfigFn(); } catch (e) { return { error: '读取配置失败' }; }
@@ -74,7 +128,13 @@ function buildClaudeUpstreamPool(claudeProvidersFile, excludedProviders) {
74
128
  if (excludedSet.has(name.toLowerCase())) continue;
75
129
  const baseUrl = typeof p.baseUrl === 'string' ? p.baseUrl.trim() : '';
76
130
  if (!baseUrl || !isValidHttpUrl(normalizeBaseUrl(baseUrl))) continue;
77
- pool.push({ name, baseUrl: normalizeBaseUrl(baseUrl), apiKey: typeof p.apiKey === 'string' ? p.apiKey : '', model: typeof p.model === 'string' ? p.model.trim() : '' });
131
+ pool.push({
132
+ name,
133
+ baseUrl: normalizeBaseUrl(baseUrl),
134
+ apiKey: typeof p.apiKey === 'string' ? p.apiKey : '',
135
+ model: typeof p.model === 'string' ? p.model.trim() : '',
136
+ targetApi: normalizeClaudeLocalTargetApi(p.targetApi)
137
+ });
78
138
  }
79
139
  if (pool.length === 0) return { error: '请先添加可用的 Claude 上游提供商' };
80
140
  return { pool };
@@ -263,7 +323,7 @@ function createLocalBridgeHttpHandler(options = {}) {
263
323
  const pool = poolResult.pool;
264
324
  const { entry } = pickUpstream(pool);
265
325
 
266
- const suffix = (parsedUrl.pathname || '').replace(/^\/bridge\/claude-local\/?/, '');
326
+ const suffix = normalizeClaudeLocalSuffix(parsedUrl.pathname || '');
267
327
  if (!suffix) {
268
328
  if ((req.method || 'GET').toUpperCase() !== 'GET') {
269
329
  res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
@@ -271,11 +331,151 @@ function createLocalBridgeHttpHandler(options = {}) {
271
331
  return;
272
332
  }
273
333
  res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
274
- res.end(JSON.stringify({ object: 'codexmate.claude_local_bridge', provider: entry.name, model: entry.model || '', status: 'ok', pool: pool.map(p => p.name) }));
334
+ res.end(JSON.stringify({
335
+ object: 'codexmate.claude_local_bridge',
336
+ provider: entry.name,
337
+ model: entry.model || '',
338
+ targetApi: entry.targetApi,
339
+ status: 'ok',
340
+ pool: pool.map(p => p.name),
341
+ targetApis: Object.fromEntries(pool.map(p => [p.name, p.targetApi]))
342
+ }));
343
+ return;
344
+ }
345
+
346
+ const targetApi = normalizeClaudeLocalTargetApi(entry.targetApi);
347
+ const method = (req.method || 'GET').toUpperCase();
348
+ const isMessagesRequest = suffix === 'messages';
349
+ const isModelsRequest = suffix === 'models';
350
+
351
+ if ((targetApi === 'chat_completions' || targetApi === 'ollama') && !isMessagesRequest && !isModelsRequest) {
352
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
353
+ res.end(JSON.stringify({ error: 'Claude local bridge transform providers only support /v1/messages and /v1/models' }));
354
+ return;
355
+ }
356
+
357
+ if (targetApi === 'chat_completions' || targetApi === 'ollama') {
358
+ if (isModelsRequest) {
359
+ if (method !== 'GET') {
360
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8', Allow: 'GET' });
361
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
362
+ return;
363
+ }
364
+ const modelsUrl = joinClaudeLocalUpstreamUrl(entry.baseUrl.replace(/\/+$/, ''), targetApi === 'ollama' ? 'api/tags' : 'models');
365
+ const upstreamResult = await retryTransientRequest(() => proxyRequestJson(modelsUrl, {
366
+ method: 'GET',
367
+ body: null,
368
+ headers: buildClaudeLocalAuthHeaders(entry, token, targetApi, expectedToken),
369
+ maxBytes: maxUpstreamBytes,
370
+ httpAgent,
371
+ httpsAgent
372
+ }));
373
+ if (!upstreamResult.ok) {
374
+ recordFailure(entry.name);
375
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
376
+ res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
377
+ return;
378
+ }
379
+ const parsedModels = parseJsonOrError(upstreamResult.bodyText || '{}');
380
+ if (upstreamResult.status >= 400) {
381
+ recordFailure(entry.name);
382
+ res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
383
+ res.end(upstreamResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
384
+ return;
385
+ }
386
+ if (parsedModels.error) {
387
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
388
+ res.end(JSON.stringify({ error: `Upstream parse failed: ${parsedModels.error}` }));
389
+ return;
390
+ }
391
+ recordSuccess(entry.name);
392
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
393
+ res.end(JSON.stringify(buildAnthropicModelsPayload(parsedModels.value)));
394
+ return;
395
+ }
396
+
397
+ if (method !== 'POST') {
398
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8', Allow: 'POST' });
399
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
400
+ return;
401
+ }
402
+ const bodyResult = await readRequestBody(req, maxBodySize);
403
+ if (bodyResult.error) {
404
+ res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
405
+ res.end(JSON.stringify({ error: bodyResult.error }));
406
+ return;
407
+ }
408
+ const parsed = parseJsonOrError(bodyResult.body);
409
+ if (parsed.error) {
410
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
411
+ res.end(JSON.stringify({ error: parsed.error }));
412
+ return;
413
+ }
414
+ const requestPayload = parsed.value && typeof parsed.value === 'object' ? parsed.value : {};
415
+ if (entry.model) requestPayload.model = entry.model;
416
+ let upstreamBody;
417
+ try {
418
+ upstreamBody = targetApi === 'ollama'
419
+ ? buildBuiltinClaudeOllamaChatRequest(requestPayload)
420
+ : buildBuiltinClaudeChatCompletionsRequest(requestPayload);
421
+ } catch (e) {
422
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
423
+ res.end(JSON.stringify({ error: e && e.message ? e.message : 'Invalid request payload' }));
424
+ return;
425
+ }
426
+ const upstreamUrl = joinClaudeLocalUpstreamUrl(entry.baseUrl.replace(/\/+$/, ''), targetApi === 'ollama' ? 'api/chat' : 'chat/completions');
427
+ const upstreamResult = await retryTransientRequest(() => proxyRequestJson(upstreamUrl, {
428
+ method: 'POST',
429
+ body: upstreamBody,
430
+ headers: buildClaudeLocalAuthHeaders(entry, token, targetApi, expectedToken),
431
+ maxBytes: maxUpstreamBytes,
432
+ httpAgent,
433
+ httpsAgent
434
+ }));
435
+
436
+ if (!upstreamResult.ok) {
437
+ recordFailure(entry.name);
438
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
439
+ res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
440
+ return;
441
+ }
442
+ if (upstreamResult.status >= 400) {
443
+ recordFailure(entry.name);
444
+ res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
445
+ res.end(upstreamResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
446
+ return;
447
+ }
448
+ const parsedUpstream = parseJsonOrError(upstreamResult.bodyText || '{}');
449
+ if (parsedUpstream.error) {
450
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
451
+ res.end(JSON.stringify({ error: `Upstream parse failed: ${parsedUpstream.error}` }));
452
+ return;
453
+ }
454
+ recordSuccess(entry.name);
455
+ const anthropicMessage = targetApi === 'ollama'
456
+ ? buildAnthropicMessageFromOllamaChat(parsedUpstream.value || {}, requestPayload)
457
+ : buildAnthropicMessageFromChatCompletion(parsedUpstream.value || {}, requestPayload);
458
+ if (requestPayload.stream === true) {
459
+ const events = buildAnthropicStreamEvents(anthropicMessage);
460
+ res.writeHead(200, {
461
+ 'Content-Type': 'text/event-stream; charset=utf-8',
462
+ 'Cache-Control': 'no-cache, no-transform',
463
+ Connection: 'keep-alive',
464
+ 'X-Accel-Buffering': 'no'
465
+ });
466
+ for (const event of events) {
467
+ if (event && event.event) res.write(`event: ${event.event}\n`);
468
+ res.write(`data: ${JSON.stringify(event && event.data ? event.data : {})}\n\n`);
469
+ }
470
+ res.end();
471
+ return;
472
+ }
473
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
474
+ res.end(JSON.stringify(anthropicMessage));
275
475
  return;
276
476
  }
277
477
 
278
- // Proxy Anthropic Messages API requests
478
+ // Native Anthropic-compatible provider: keep /v1/messages passthrough.
279
479
  const bodyResult = await readRequestBody(req, maxBodySize);
280
480
  if (bodyResult.error) {
281
481
  res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
@@ -283,26 +483,26 @@ function createLocalBridgeHttpHandler(options = {}) {
283
483
  return;
284
484
  }
285
485
 
286
- let parsedBody;
287
- try { parsedBody = bodyResult.body ? JSON.parse(bodyResult.body) : {}; } catch (_) { parsedBody = {}; }
288
- // Override model to match the selected upstream provider
486
+ const hasRequestBody = typeof bodyResult.body === 'string' && bodyResult.body.trim().length > 0;
487
+ let parsedBody = null;
488
+ if (hasRequestBody) {
489
+ const parsed = parseJsonOrError(bodyResult.body);
490
+ if (parsed.error) {
491
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
492
+ res.end(JSON.stringify({ error: parsed.error }));
493
+ return;
494
+ }
495
+ parsedBody = parsed.value;
496
+ }
289
497
  if (entry.model && parsedBody && typeof parsedBody === 'object') {
290
498
  parsedBody.model = entry.model;
291
499
  }
292
- const wantsStream = !!(parsedBody && parsedBody.stream);
293
- const bodyToForward = JSON.stringify(parsedBody);
500
+ const wantsStream = !!(parsedBody && typeof parsedBody === 'object' && parsedBody.stream);
501
+ const bodyToForward = hasRequestBody ? JSON.stringify(parsedBody) : null;
294
502
  const upstreamUrl = joinApiUrl(entry.baseUrl.replace(/\/+$/, ''), suffix);
295
- const headers = { 'Content-Type': 'application/json' };
296
- if (entry.apiKey) {
297
- headers['x-api-key'] = entry.apiKey.startsWith('Bearer ') ? entry.apiKey.slice(7) : entry.apiKey;
298
- }
299
- if (token && !entry.apiKey) {
300
- headers['x-api-key'] = token.startsWith('Bearer ') ? token.slice(7) : token;
301
- }
302
- headers['anthropic-version'] = '2023-06-01';
503
+ const headers = buildClaudeLocalAuthHeaders(entry, token, targetApi, expectedToken);
303
504
 
304
505
  if (wantsStream) {
305
- // Streaming proxy: pipe upstream SSE directly to client
306
506
  const upstreamResult = await streamClaudeUpstream(upstreamUrl, {
307
507
  method: req.method || 'POST',
308
508
  body: bodyToForward,
@@ -324,10 +524,9 @@ function createLocalBridgeHttpHandler(options = {}) {
324
524
  return;
325
525
  }
326
526
 
327
- // Non-streaming proxy
328
527
  const upstreamResult = await retryTransientRequest(() => proxyRequestJson(upstreamUrl, {
329
528
  method: req.method || 'POST',
330
- body: bodyToForward || null,
529
+ body: parsedBody || null,
331
530
  headers,
332
531
  maxBytes: maxUpstreamBytes,
333
532
  httpAgent,
@@ -432,7 +631,7 @@ function createLocalBridgeHttpHandler(options = {}) {
432
631
  const upstreamResponsesUrl = joinApiUrl(upstreamBase, 'responses');
433
632
  const upstreamResponsesResult = await retryTransientRequest(() => proxyRequestJson(upstreamResponsesUrl, {
434
633
  method: 'POST',
435
- body: bodyResult.body,
634
+ body: responsesRequest,
436
635
  headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
437
636
  maxBytes: maxUpstreamBytes,
438
637
  httpAgent,
@@ -484,7 +683,7 @@ function createLocalBridgeHttpHandler(options = {}) {
484
683
  const chatUrl = joinApiUrl(upstreamBase, 'chat/completions');
485
684
  const chatResult = await retryTransientRequest(() => proxyRequestJson(chatUrl, {
486
685
  method: 'POST',
487
- body: JSON.stringify(converted.chat),
686
+ body: converted.chat,
488
687
  headers: { ...(authHeader ? { Authorization: authHeader } : {}), 'Content-Type': 'application/json' },
489
688
  maxBytes: maxUpstreamBytes,
490
689
  httpAgent,