mirror of
https://github.com/musistudio/claude-code-router.git
synced 2026-07-11 18:18:25 +00:00
Compare commits
66 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9cd0aab309 | ||
|
|
9d1ff83708 | ||
|
|
2bb2611447 | ||
|
|
222ccfa208 | ||
|
|
ef90d57ee1 | ||
|
|
be9a50e585 | ||
|
|
f1b8fd1fa0 | ||
|
|
ca2609c727 | ||
|
|
ee243fbfe5 | ||
|
|
8cfd4bbd8b | ||
|
|
3c27b7f912 | ||
|
|
0663c0463e | ||
|
|
78f4859a9b | ||
|
|
9c98e353e6 | ||
|
|
81fbae63a6 | ||
|
|
c0da81d6f3 | ||
|
|
5a3e1cb71f | ||
|
|
4c5af02aae | ||
|
|
4cf0c2468c | ||
|
|
15f67ab8d8 | ||
|
|
9163e306c0 | ||
|
|
088ec97e7b | ||
|
|
768baa8575 | ||
|
|
2cc208d857 | ||
|
|
ab6a2c1c50 | ||
|
|
113c9059b4 | ||
|
|
990bc0d958 | ||
|
|
fcd386c80c | ||
|
|
1aaee2ef60 | ||
|
|
92a16b0d4b | ||
|
|
2020e8f53c | ||
|
|
70f85864a6 | ||
|
|
8361805bdf | ||
|
|
f568968673 | ||
|
|
421cbd05b2 | ||
|
|
a65b8bb6f9 | ||
|
|
d8154e5357 | ||
|
|
cce7292877 | ||
|
|
980a9bae63 | ||
|
|
a8ccdf0403 | ||
|
|
499d25d200 | ||
|
|
04185dba99 | ||
|
|
d29f2176e8 | ||
|
|
bc872a29b3 | ||
|
|
c8cbc09b96 | ||
|
|
52a6371600 | ||
|
|
027826fd13 | ||
|
|
7216b9dcfa | ||
|
|
300096e39e | ||
|
|
07fd47ad65 | ||
|
|
4d7c1990ba | ||
|
|
8cf350e041 | ||
|
|
7faf59276a | ||
|
|
a4f5cc9172 | ||
|
|
ad0d9db795 | ||
|
|
1da1723530 | ||
|
|
d4ff6706f4 | ||
|
|
fce80a0c3a | ||
|
|
9af987d224 | ||
|
|
61108ed6e3 | ||
|
|
c409797bc5 | ||
|
|
964d1dbf23 | ||
|
|
5f92120114 | ||
|
|
528a8e0efa | ||
|
|
daf745ac3f | ||
|
|
ee44357a34 |
322 changed files with 22552 additions and 2153 deletions
17
.dockerignore
Normal file
17
.dockerignore
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
.git
|
||||
.DS_Store
|
||||
.env
|
||||
.env.*
|
||||
node_modules
|
||||
dist
|
||||
packages/*/dist
|
||||
release
|
||||
release-local
|
||||
logs
|
||||
tmp
|
||||
test-results
|
||||
playwright-report
|
||||
blob-report
|
||||
docs/node_modules
|
||||
docs/dist
|
||||
docs/.astro
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
|
|
@ -13,4 +13,8 @@ release
|
|||
tmp
|
||||
release-local
|
||||
logs
|
||||
.opencat
|
||||
.opencat
|
||||
test-results
|
||||
playwright-report
|
||||
blob-report
|
||||
.tmp
|
||||
75
Dockerfile
Normal file
75
Dockerfile
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
ARG NODE_IMAGE=node:22-bookworm
|
||||
ARG RUNTIME_NODE_IMAGE=node:22-bookworm-slim
|
||||
|
||||
FROM ${NODE_IMAGE} AS build
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY packages/cli/package.json packages/cli/package.json
|
||||
COPY packages/core/package.json packages/core/package.json
|
||||
COPY packages/electron/package.json packages/electron/package.json
|
||||
COPY packages/ui/package.json packages/ui/package.json
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build:docker
|
||||
|
||||
FROM ${NODE_IMAGE} AS production-deps
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY packages/core/package.json packages/core/package.json
|
||||
RUN npm ci --omit=dev --workspace=@claude-code-router/core --include-workspace-root=false \
|
||||
&& npm cache clean --force
|
||||
|
||||
FROM ${RUNTIME_NODE_IMAGE} AS runtime
|
||||
ENV NODE_ENV=production \
|
||||
CCR_DATA_DIR=/data \
|
||||
CCR_WEB_HOST=127.0.0.1 \
|
||||
CCR_WEB_PORT=3459 \
|
||||
CCR_NGINX_PORT=8080 \
|
||||
CCR_GATEWAY_HOST=127.0.0.1 \
|
||||
CCR_GATEWAY_PORT=3456 \
|
||||
CCR_GATEWAY_CORE_PORT=3457 \
|
||||
CCR_PUBLIC_HOST=127.0.0.1 \
|
||||
CCR_PUBLIC_PORT=3458
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 nginx \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& rm -f /etc/nginx/sites-enabled/default /etc/nginx/conf.d/default.conf \
|
||||
&& rm -rf \
|
||||
/opt/yarn-* \
|
||||
/usr/local/bin/corepack \
|
||||
/usr/local/bin/npm \
|
||||
/usr/local/bin/npx \
|
||||
/usr/local/bin/yarn \
|
||||
/usr/local/bin/yarnpkg \
|
||||
/usr/local/include/node \
|
||||
/usr/local/lib/node_modules/corepack \
|
||||
/usr/local/lib/node_modules/npm \
|
||||
/usr/local/share/doc \
|
||||
/usr/local/share/man
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY packages/core/package.json packages/core/package.json
|
||||
COPY --from=production-deps /app/node_modules node_modules
|
||||
|
||||
COPY --from=build /app/packages/core/dist packages/core/dist
|
||||
COPY --from=build /app/packages/ui/dist/renderer /usr/share/nginx/html
|
||||
COPY docker/entrypoint.sh /usr/local/bin/ccr-docker-entrypoint
|
||||
COPY docker/pm2.config.cjs docker/pm2.config.cjs
|
||||
|
||||
RUN chmod +x /usr/local/bin/ccr-docker-entrypoint \
|
||||
&& mkdir -p /data /run/nginx /var/lib/nginx /var/log/nginx
|
||||
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:' + (process.env.CCR_NGINX_PORT || '8080') + '/').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||
|
||||
ENTRYPOINT ["ccr-docker-entrypoint"]
|
||||
69
README.md
69
README.md
|
|
@ -1,19 +1,52 @@
|
|||
<h1 align="center">Claude Code Router Desktop</h1>
|
||||
<h1 align="center">Claude Code Router</h1>
|
||||
|
||||
<p align="center">
|
||||
<a href="README_zh.md"><img alt="Chinese README" src="https://img.shields.io/badge/%F0%9F%87%A8%F0%9F%87%B3-%E4%B8%AD%E6%96%87%E7%89%88-ff0000?style=flat" /></a>
|
||||
<a href="https://discord.gg/rdftVMaUcS"><img alt="Discord" src="https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white" /></a>
|
||||
<a href="https://x.com/musistudio2026"><img alt="X" src="https://img.shields.io/badge/X-@musistudio2026-000000?logo=x&logoColor=white" /></a>
|
||||
<a href="https://github.com/musistudio/claude-code-router/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/musistudio/claude-code-router" /></a>
|
||||
<a href="https://github.com/musistudio/claude-code-router/releases"><img alt="Desktop downloads" src="https://img.shields.io/github/downloads/musistudio/claude-code-router/total?label=Desktop%20downloads&logo=github" /></a>
|
||||
<a href="https://ccrdesk.top/"><img alt="Documentation" src="https://img.shields.io/badge/Docs-ccrdesk.top-0ea5e9?style=flat" /></a>
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<a href="https://www.kimi.com/code?aff=ccr">
|
||||
<img src="https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-en.png" width="960" alt="Kimi K2.7 Code sponsor banner" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>
|
||||
<a href="https://www.kimi.com/code?aff=ccr"><strong>Kimi Code Subscription</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.ai?aff=ccr"><strong>API Global</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.com?aff=ccr">API China</a>
|
||||
</sub>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left">
|
||||
<p>
|
||||
<strong>Thanks to Kimi for sponsoring this project!</strong> Kimi K2.7 Code is an open-source, coding-focused agentic model developed by Moonshot AI, with substantial gains on real-world long-horizon coding tasks and higher end-to-end success across complex software engineering workflows. It also cuts thinking-token usage by approximately 30% compared with K2.6. Inside CCR, Kimi ships as built-in provider presets: import the pay-as-you-go API or the Kimi Code subscription in one click and route your coding agent's requests to Kimi, the subscription endpoint passes straight through natively with no protocol conversion, API endpoints are adapted automatically, and your balance and subscription usage show up right in the CCR dashboard.
|
||||
</p>
|
||||
<p align="center">
|
||||
CCR already supports Kimi. Visit the Kimi Open Platform (<a href="https://platform.kimi.com?aff=ccr">中文站</a> | <a href="https://platform.kimi.ai?aff=ccr">Global</a>) to try the API, or explore the <a href="https://www.kimi.com/code?aff=ccr">cost-effective Coding Plan</a>.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
Claude Code Router Desktop is a local gateway and desktop control panel for routing agent requests from Claude Code, Codex, ZCode, and compatible clients to the model provider you actually want to use.
|
||||
|
||||
<p align="center">
|
||||
<img src="blog/images/claude-code-router.png" width="720" alt="Claude Code Router Desktop screenshot" />
|
||||
</p>
|
||||
|
||||
Claude Code Router Desktop is a local gateway and desktop control panel for routing agent requests from Claude Code, Codex, ZCode, and compatible clients to the model provider you actually want to use.
|
||||
|
||||
## Why Use CCR
|
||||
|
||||
- Use one local endpoint for multiple agent tools instead of configuring every client separately.
|
||||
|
|
@ -176,6 +209,36 @@ Codex support is powered by [musistudio/codexl](https://github.com/musistudio/co
|
|||
<strong>TeamoRouter</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://code0.ai/agent/register/9n9jOsSnYQoemIVL?utm_source=claudecoderouter&utm_medium=partner&utm_campaign=claudecoderouter_2026&utm_content=default">
|
||||
<img src="/docs/public/provider-icons/code0.png" width="42" height="42" alt="code0.ai icon" />
|
||||
<br />
|
||||
<strong>code0.ai</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://console.claudeapi.com/agent/register/LbmB7Y9kPloyzhwF?utm_source=claudecoderouter&utm_medium=partner&utm_campaign=claudecoderouter_2026&utm_content=default">
|
||||
<img src="/docs/public/provider-icons/claudeapi.png" width="42" height="42" alt="claudeapi icon" />
|
||||
<br />
|
||||
<strong>claudeapi</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="330">
|
||||
<a href="https://s.qiniu.com/AVjMVf">
|
||||
<img src="/docs/public/provider-icons/qiniu-ai.png" width="42" height="42" alt="Qiniu Cloud AI icon" />
|
||||
<br />
|
||||
<strong>Qiniu Cloud AI</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=9HHHAB5QLAES">
|
||||
<img src="/docs/public/provider-icons/fenno.jpg" width="42" height="42" alt="Fenno.ai icon" />
|
||||
<br />
|
||||
<strong>Fenno.ai</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
|
|
|||
69
README_zh.md
69
README_zh.md
|
|
@ -1,19 +1,52 @@
|
|||
<h1 align="center">Claude Code Router Desktop</h1>
|
||||
<h1 align="center">Claude Code Router</h1>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md"><img alt="English README" src="https://img.shields.io/badge/%F0%9F%87%AC%F0%9F%87%A7-English-000aff?style=flat" /></a>
|
||||
<a href="https://discord.gg/rdftVMaUcS"><img alt="Discord" src="https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white" /></a>
|
||||
<a href="https://x.com/musistudio2026"><img alt="X" src="https://img.shields.io/badge/X-@musistudio2026-000000?logo=x&logoColor=white" /></a>
|
||||
<a href="https://github.com/musistudio/claude-code-router/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/musistudio/claude-code-router" /></a>
|
||||
<a href="https://github.com/musistudio/claude-code-router/releases"><img alt="桌面端下载次数" src="https://img.shields.io/github/downloads/musistudio/claude-code-router/total?label=%E6%A1%8C%E9%9D%A2%E7%AB%AF%E4%B8%8B%E8%BD%BD&logo=github" /></a>
|
||||
<a href="https://ccrdesk.top/"><img alt="文档" src="https://img.shields.io/badge/%E6%96%87%E6%A1%A3-ccrdesk.top-0ea5e9?style=flat" /></a>
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<a href="https://www.kimi.com/code?aff=ccr">
|
||||
<img src="https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-zh.png" width="960" alt="Kimi K2.7 Code 赞助横幅" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>
|
||||
<a href="https://www.kimi.com/code?aff=ccr"><strong>Kimi Code 订阅</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.com?aff=ccr"><strong>API 中文站</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.ai?aff=ccr">API Global</a>
|
||||
</sub>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left">
|
||||
<p>
|
||||
<strong>感谢 Kimi 赞助本项目!</strong>Kimi K2.7 Code 是 Moonshot AI 推出的编程专用开源智能体模型,在真实长程编程与复杂软件工程工作流中显著提升端到端任务成功率,同时优化推理效率,相比 K2.6 平均减少约 30% 的推理 token 消耗。在 CCR 中,Kimi 已作为内置供应商预设开箱即用:无论按量付费 API 还是 Kimi Code 订阅,一键导入即可把你的编程 Agent 请求路由到 Kimi,订阅端点原生直通、无需协议转换,API 端点自动适配,账户余额与订阅用量也能直接在 CCR 面板中查看。
|
||||
</p>
|
||||
<p align="center">
|
||||
CCR 已内置 Kimi 供应商预设。前往 Kimi 开放平台(<a href="https://platform.kimi.com?aff=ccr">中文站</a>|<a href="https://platform.kimi.ai?aff=ccr">Global</a>)体验 API,或了解高性价比 <a href="https://www.kimi.com/code?aff=ccr">Coding Plan</a> 套餐。
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
Claude Code Router Desktop 是一个本地网关和桌面控制台,用来把 Claude Code、Codex、ZCode 以及兼容客户端的 Agent 请求路由到你真正想使用的模型服务。
|
||||
|
||||
<p align="center">
|
||||
<img src="blog/images/claude-code-router.png" width="720" alt="Claude Code Router Desktop 项目截图" />
|
||||
</p>
|
||||
|
||||
Claude Code Router Desktop 是一个本地网关和桌面控制台,用来把 Claude Code、Codex、ZCode 以及兼容客户端的 Agent 请求路由到你真正想使用的模型服务。
|
||||
|
||||
## 为什么使用 CCR
|
||||
|
||||
- 用一个本地入口连接多个 Agent 工具,不需要在每个客户端里重复配置 Provider。
|
||||
|
|
@ -175,6 +208,36 @@ CCR 可以完全通过桌面 UI 完成配置。首次使用建议按下面顺序
|
|||
<strong>TeamoRouter</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://code0.ai/agent/register/9n9jOsSnYQoemIVL?utm_source=claudecoderouter&utm_medium=partner&utm_campaign=claudecoderouter_2026&utm_content=default">
|
||||
<img src="/docs/public/provider-icons/code0.png" width="42" height="42" alt="code0.ai 图标" />
|
||||
<br />
|
||||
<strong>code0.ai</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://console.claudeapi.com/agent/register/LbmB7Y9kPloyzhwF?utm_source=claudecoderouter&utm_medium=partner&utm_campaign=claudecoderouter_2026&utm_content=default">
|
||||
<img src="/docs/public/provider-icons/claudeapi.png" width="42" height="42" alt="claudeapi 图标" />
|
||||
<br />
|
||||
<strong>claudeapi</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="330">
|
||||
<a href="https://s.qiniu.com/AVjMVf">
|
||||
<img src="/docs/public/provider-icons/qiniu-ai.png" width="42" height="42" alt="七牛云 AI 图标" />
|
||||
<br />
|
||||
<strong>七牛云 AI</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=9HHHAB5QLAES">
|
||||
<img src="/docs/public/provider-icons/fenno.jpg" width="42" height="42" alt="Fenno.ai 图标" />
|
||||
<br />
|
||||
<strong>Fenno.ai</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { buildBrowserRenderer, buildMain, buildRenderer, buildStyles, buildTrayRenderer, buildWebClientBridge, cleanDist, copyAppAssets, copyBrowserRendererHtml, copyMarketplacePlugins, copyModelCatalog, copyRendererHtml, copyTrayRendererHtml } from "./esbuild.config.mjs";
|
||||
import { buildBrowserRenderer, buildMain, buildRenderer, buildStyles, buildTrayRenderer, buildWebClientBridge, cleanDist, copyAppAssets, copyBrowserRendererHtml, copyMarketplacePlugins, copyModelCatalog, copyRendererHtml, copyTrayRendererHtml, syncUiRendererToRuntimeDists } from "./esbuild.config.mjs";
|
||||
|
||||
const mode = process.argv.includes("--dev") ? "development" : "production";
|
||||
|
||||
|
|
@ -19,4 +19,6 @@ await Promise.all([
|
|||
buildStyles({ minify: mode === "production" })
|
||||
]);
|
||||
|
||||
console.log(`Built Electron app assets in ${mode} mode.`);
|
||||
syncUiRendererToRuntimeDists();
|
||||
|
||||
console.log(`Built monorepo package assets in ${mode} mode.`);
|
||||
|
|
|
|||
294
build/dev.mjs
294
build/dev.mjs
|
|
@ -5,12 +5,14 @@ import { spawn } from "node:child_process";
|
|||
import { existsSync, readdirSync, readFileSync, statSync, watch } from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
binPath,
|
||||
buildStyles,
|
||||
cleanDist,
|
||||
browserRendererHtmlInput,
|
||||
cliSourceRoot,
|
||||
coreSourceRoot,
|
||||
copyAppAssets,
|
||||
copyBrowserRendererHtml,
|
||||
copyCliRuntimeToElectronDist,
|
||||
copyMarketplacePlugins,
|
||||
copyModelCatalog,
|
||||
copyRendererHtml,
|
||||
|
|
@ -21,12 +23,12 @@ import {
|
|||
createRendererBuildOptions,
|
||||
createTrayRendererBuildOptions,
|
||||
createWebClientBridgeBuildOptions,
|
||||
cssInput,
|
||||
cssOutput,
|
||||
appAssetsInput,
|
||||
modelCatalogInput,
|
||||
projectRoot,
|
||||
rendererRoot,
|
||||
rendererHtmlInput,
|
||||
syncUiRendererToRuntimeDists,
|
||||
trayRendererHtmlInput,
|
||||
watchPlugin
|
||||
} from "./esbuild.config.mjs";
|
||||
|
|
@ -37,7 +39,12 @@ let pendingRestartReasons = [];
|
|||
const watchSignatures = new Map();
|
||||
let shuttingDown = false;
|
||||
const restartDelayMs = 160;
|
||||
const styleBuildDelayMs = 160;
|
||||
const stylePollIntervalMs = 1000;
|
||||
const ignoredSignatureEntries = new Set([".DS_Store"]);
|
||||
let styleBuildTimer = null;
|
||||
let styleBuildInFlight = false;
|
||||
let queuedStyleBuildReason = null;
|
||||
const ready = {
|
||||
browser: false,
|
||||
cli: false,
|
||||
|
|
@ -46,6 +53,32 @@ const ready = {
|
|||
tray: false,
|
||||
webBridge: false
|
||||
};
|
||||
const devTarget = parseDevTarget(process.argv.slice(2));
|
||||
const enabled = {
|
||||
cli: devTarget === "cli" || devTarget === "electron",
|
||||
electron: devTarget === "electron",
|
||||
ui: true
|
||||
};
|
||||
const coreSharedSourceRoot = path.join(coreSourceRoot, "shared");
|
||||
const styleWatchRoots = [rendererRoot, coreSharedSourceRoot].filter((watchRoot) => existsSync(watchRoot));
|
||||
const activeReadyNames = new Set([
|
||||
...(enabled.ui ? ["browser", "renderer", "tray", "webBridge"] : []),
|
||||
...(enabled.cli ? ["cli"] : []),
|
||||
...(enabled.electron ? ["main"] : [])
|
||||
]);
|
||||
|
||||
function parseDevTarget(args) {
|
||||
const target = args[0] ?? "electron";
|
||||
if (target === "--help" || target === "-h") {
|
||||
console.log("Usage: node build/dev.mjs [ui|cli|electron]");
|
||||
process.exit(0);
|
||||
}
|
||||
if (target === "ui" || target === "cli" || target === "electron") {
|
||||
return target;
|
||||
}
|
||||
console.error(`Unknown dev target "${target}". Expected ui, cli, or electron.`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
function logDev(message) {
|
||||
console.log(`[dev] ${new Date().toISOString()} ${message}`);
|
||||
|
|
@ -57,6 +90,7 @@ function relativePath(file) {
|
|||
|
||||
function readyState() {
|
||||
return Object.entries(ready)
|
||||
.filter(([name]) => activeReadyNames.has(name))
|
||||
.map(([name, value]) => `${name}:${value ? "ready" : "pending"}`)
|
||||
.join(" ");
|
||||
}
|
||||
|
|
@ -163,7 +197,63 @@ function handleWatchedInput(label, watchedPath, eventType, filename, options, on
|
|||
}
|
||||
|
||||
onChange();
|
||||
scheduleRestart(reason);
|
||||
if (enabled.electron && options?.restart !== false) {
|
||||
scheduleRestart(reason);
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleStyleBuild(reason) {
|
||||
queuedStyleBuildReason = reason;
|
||||
if (styleBuildTimer) {
|
||||
clearTimeout(styleBuildTimer);
|
||||
}
|
||||
styleBuildTimer = setTimeout(() => {
|
||||
styleBuildTimer = null;
|
||||
void rebuildStyles(queuedStyleBuildReason ?? reason);
|
||||
}, styleBuildDelayMs);
|
||||
}
|
||||
|
||||
async function rebuildStyles(reason) {
|
||||
if (styleBuildInFlight) {
|
||||
queuedStyleBuildReason = reason;
|
||||
return;
|
||||
}
|
||||
|
||||
styleBuildInFlight = true;
|
||||
queuedStyleBuildReason = null;
|
||||
try {
|
||||
logDev(`rebuilding styles: ${reason}`);
|
||||
await buildStyles({ minify: false });
|
||||
syncUiRendererToRuntimeDists();
|
||||
if (enabled.electron) {
|
||||
scheduleRestart(`styles rebuilt: ${reason}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logDev(`style rebuild failed: ${message}`);
|
||||
} finally {
|
||||
styleBuildInFlight = false;
|
||||
if (queuedStyleBuildReason) {
|
||||
const queuedReason = queuedStyleBuildReason;
|
||||
queuedStyleBuildReason = null;
|
||||
scheduleStyleBuild(queuedReason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pollStyleWatchRoots() {
|
||||
for (const styleWatchRoot of styleWatchRoots) {
|
||||
const label = `styles ${relativePath(styleWatchRoot)}`;
|
||||
const signature = contentSignature(styleWatchRoot);
|
||||
const previousSignature = watchSignatures.get(label);
|
||||
if (previousSignature === signature.key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
watchSignatures.set(label, signature.key);
|
||||
logDev(`watch event: ${label}; ${signature.summary}; content=changed`);
|
||||
scheduleStyleBuild(label);
|
||||
}
|
||||
}
|
||||
|
||||
function markReady(name, reason = `${name} esbuild completed`) {
|
||||
|
|
@ -171,7 +261,7 @@ function markReady(name, reason = `${name} esbuild completed`) {
|
|||
ready[name] = true;
|
||||
}
|
||||
logDev(`build ready: ${reason}; ${readyState()}`);
|
||||
if (ready.browser && ready.cli && ready.main && ready.renderer && ready.tray && ready.webBridge) {
|
||||
if (enabled.electron && Array.from(activeReadyNames).every((readyName) => ready[readyName])) {
|
||||
scheduleRestart(reason);
|
||||
}
|
||||
}
|
||||
|
|
@ -221,114 +311,153 @@ function restartElectron() {
|
|||
});
|
||||
}
|
||||
|
||||
logDev("starting dev build");
|
||||
logDev(`starting dev build target=${devTarget} ui=${enabled.ui ? "on" : "off"} cli=${enabled.cli ? "on" : "off"} electron=${enabled.electron ? "on" : "off"}`);
|
||||
cleanDist();
|
||||
copyAppAssets();
|
||||
copyMarketplacePlugins();
|
||||
copyModelCatalog();
|
||||
if (enabled.electron) {
|
||||
copyAppAssets();
|
||||
}
|
||||
if (enabled.cli || enabled.electron) {
|
||||
copyMarketplacePlugins();
|
||||
copyModelCatalog();
|
||||
}
|
||||
copyBrowserRendererHtml();
|
||||
copyRendererHtml();
|
||||
copyTrayRendererHtml();
|
||||
await buildStyles({ minify: false });
|
||||
|
||||
const tailwindProcess = spawn(binPath("tailwindcss"), ["-i", cssInput, "-o", cssOutput, "--watch"], {
|
||||
cwd: projectRoot,
|
||||
stdio: "inherit",
|
||||
shell: process.platform === "win32"
|
||||
});
|
||||
logDev(`Tailwind watcher started pid=${tailwindProcess.pid ?? "unknown"} input=${relativePath(cssInput)} output=${relativePath(cssOutput)}`);
|
||||
tailwindProcess.on("exit", (code, signal) => {
|
||||
logDev(`Tailwind watcher exited code=${code ?? "null"} signal=${signal ?? "null"}`);
|
||||
});
|
||||
syncUiRendererToRuntimeDists();
|
||||
|
||||
rememberWatchSignature("home html", rendererHtmlInput);
|
||||
rememberWatchSignature("browser html", browserRendererHtmlInput);
|
||||
rememberWatchSignature("tray html", trayRendererHtmlInput);
|
||||
rememberWatchSignature("app assets", appAssetsInput);
|
||||
if (existsSync(modelCatalogInput)) {
|
||||
for (const styleWatchRoot of styleWatchRoots) {
|
||||
rememberWatchSignature(`styles ${relativePath(styleWatchRoot)}`, styleWatchRoot);
|
||||
}
|
||||
if (enabled.electron) {
|
||||
rememberWatchSignature("app assets", appAssetsInput);
|
||||
}
|
||||
if ((enabled.cli || enabled.electron) && existsSync(modelCatalogInput)) {
|
||||
rememberWatchSignature("model catalog", modelCatalogInput);
|
||||
}
|
||||
|
||||
const htmlWatcher = watch(rendererHtmlInput, { persistent: true }, (eventType, filename) => {
|
||||
handleWatchedInput("home html", rendererHtmlInput, eventType, filename, undefined, copyRendererHtml);
|
||||
handleWatchedInput("home html", rendererHtmlInput, eventType, filename, undefined, () => {
|
||||
copyRendererHtml();
|
||||
syncUiRendererToRuntimeDists();
|
||||
});
|
||||
});
|
||||
|
||||
const browserHtmlWatcher = watch(browserRendererHtmlInput, { persistent: true }, (eventType, filename) => {
|
||||
handleWatchedInput("browser html", browserRendererHtmlInput, eventType, filename, undefined, copyBrowserRendererHtml);
|
||||
handleWatchedInput("browser html", browserRendererHtmlInput, eventType, filename, undefined, () => {
|
||||
copyBrowserRendererHtml();
|
||||
syncUiRendererToRuntimeDists();
|
||||
});
|
||||
});
|
||||
|
||||
const trayHtmlWatcher = watch(trayRendererHtmlInput, { persistent: true }, (eventType, filename) => {
|
||||
handleWatchedInput("tray html", trayRendererHtmlInput, eventType, filename, undefined, copyTrayRendererHtml);
|
||||
handleWatchedInput("tray html", trayRendererHtmlInput, eventType, filename, undefined, () => {
|
||||
copyTrayRendererHtml();
|
||||
syncUiRendererToRuntimeDists();
|
||||
});
|
||||
});
|
||||
|
||||
const appAssetsWatcher = watch(appAssetsInput, { persistent: true }, (eventType, filename) => {
|
||||
handleWatchedInput("app assets", appAssetsInput, eventType, filename, { isDirectory: true }, copyAppAssets);
|
||||
});
|
||||
const stylePoller = setInterval(pollStyleWatchRoots, stylePollIntervalMs);
|
||||
|
||||
const modelCatalogWatcher = existsSync(modelCatalogInput)
|
||||
const appAssetsWatcher = enabled.electron
|
||||
? watch(appAssetsInput, { persistent: true }, (eventType, filename) => {
|
||||
handleWatchedInput("app assets", appAssetsInput, eventType, filename, { isDirectory: true }, copyAppAssets);
|
||||
})
|
||||
: { close: () => undefined };
|
||||
|
||||
const modelCatalogWatcher = (enabled.cli || enabled.electron) && existsSync(modelCatalogInput)
|
||||
? watch(modelCatalogInput, { persistent: true }, (eventType, filename) => {
|
||||
handleWatchedInput("model catalog", modelCatalogInput, eventType, filename, undefined, copyModelCatalog);
|
||||
})
|
||||
: { close: () => undefined };
|
||||
|
||||
const mainContext = await esbuild.context(
|
||||
createMainBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [watchPlugin("main", (name) => markReady(name))]
|
||||
})
|
||||
);
|
||||
const contexts = [];
|
||||
|
||||
const cliContext = await esbuild.context(
|
||||
createCliBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [watchPlugin("cli", (name) => markReady(name))]
|
||||
})
|
||||
);
|
||||
|
||||
const rendererContext = await esbuild.context(
|
||||
createRendererBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("renderer", (name) => {
|
||||
copyRendererHtml();
|
||||
markReady(name);
|
||||
if (enabled.electron) {
|
||||
contexts.push(
|
||||
await esbuild.context(
|
||||
createMainBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [watchPlugin("main", (name) => markReady(name))]
|
||||
})
|
||||
]
|
||||
})
|
||||
);
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const trayRendererContext = await esbuild.context(
|
||||
createTrayRendererBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("tray", (name) => {
|
||||
copyTrayRendererHtml();
|
||||
markReady(name);
|
||||
if (enabled.cli) {
|
||||
contexts.push(
|
||||
await esbuild.context(
|
||||
createCliBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("cli", (name) => {
|
||||
if (enabled.electron) {
|
||||
copyCliRuntimeToElectronDist();
|
||||
}
|
||||
markReady(name);
|
||||
})
|
||||
]
|
||||
})
|
||||
]
|
||||
})
|
||||
);
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const browserRendererContext = await esbuild.context(
|
||||
createBrowserRendererBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("browser", (name) => {
|
||||
copyBrowserRendererHtml();
|
||||
markReady(name);
|
||||
if (enabled.ui) {
|
||||
contexts.push(
|
||||
await esbuild.context(
|
||||
createRendererBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("renderer", (name) => {
|
||||
copyRendererHtml();
|
||||
syncUiRendererToRuntimeDists();
|
||||
markReady(name);
|
||||
})
|
||||
]
|
||||
})
|
||||
]
|
||||
})
|
||||
);
|
||||
),
|
||||
await esbuild.context(
|
||||
createTrayRendererBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("tray", (name) => {
|
||||
copyTrayRendererHtml();
|
||||
syncUiRendererToRuntimeDists();
|
||||
markReady(name);
|
||||
})
|
||||
]
|
||||
})
|
||||
),
|
||||
await esbuild.context(
|
||||
createBrowserRendererBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("browser", (name) => {
|
||||
copyBrowserRendererHtml();
|
||||
syncUiRendererToRuntimeDists();
|
||||
markReady(name);
|
||||
})
|
||||
]
|
||||
})
|
||||
),
|
||||
await esbuild.context(
|
||||
createWebClientBridgeBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [
|
||||
watchPlugin("webBridge", (name) => {
|
||||
syncUiRendererToRuntimeDists();
|
||||
markReady(name);
|
||||
})
|
||||
]
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const webClientBridgeContext = await esbuild.context(
|
||||
createWebClientBridgeBuildOptions({
|
||||
mode: "development",
|
||||
plugins: [watchPlugin("webBridge", (name) => markReady(name))]
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all([mainContext.watch(), cliContext.watch(), rendererContext.watch(), trayRendererContext.watch(), browserRendererContext.watch(), webClientBridgeContext.watch()]);
|
||||
await Promise.all(contexts.map((context) => context.watch()));
|
||||
logDev("watchers are active");
|
||||
|
||||
async function shutdown() {
|
||||
|
|
@ -340,13 +469,16 @@ async function shutdown() {
|
|||
if (electronProcess) {
|
||||
electronProcess.kill();
|
||||
}
|
||||
tailwindProcess.kill();
|
||||
if (styleBuildTimer) {
|
||||
clearTimeout(styleBuildTimer);
|
||||
}
|
||||
htmlWatcher.close();
|
||||
browserHtmlWatcher.close();
|
||||
trayHtmlWatcher.close();
|
||||
clearInterval(stylePoller);
|
||||
appAssetsWatcher.close();
|
||||
modelCatalogWatcher.close();
|
||||
await Promise.all([mainContext.dispose(), cliContext.dispose(), rendererContext.dispose(), trayRendererContext.dispose(), browserRendererContext.dispose(), webClientBridgeContext.dispose()]);
|
||||
await Promise.all(contexts.map((context) => context.dispose()));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
|
|
|
|||
37
build/docker-build.mjs
Normal file
37
build/docker-build.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {
|
||||
buildBrowserRenderer,
|
||||
buildCoreServer,
|
||||
buildRenderer,
|
||||
buildStyles,
|
||||
buildTrayRenderer,
|
||||
buildWebClientBridge,
|
||||
cleanDist,
|
||||
copyBrowserRendererHtml,
|
||||
copyMarketplacePlugins,
|
||||
copyModelCatalog,
|
||||
copyRendererHtml,
|
||||
copyTrayRendererHtml,
|
||||
syncUiRendererToRuntimeDists
|
||||
} from "./esbuild.config.mjs";
|
||||
|
||||
const mode = process.argv.includes("--dev") ? "development" : "production";
|
||||
|
||||
cleanDist();
|
||||
copyMarketplacePlugins();
|
||||
copyModelCatalog();
|
||||
copyBrowserRendererHtml();
|
||||
copyRendererHtml();
|
||||
copyTrayRendererHtml();
|
||||
|
||||
await Promise.all([
|
||||
buildCoreServer({ mode }),
|
||||
buildBrowserRenderer({ mode }),
|
||||
buildRenderer({ mode }),
|
||||
buildTrayRenderer({ mode }),
|
||||
buildWebClientBridge({ mode }),
|
||||
buildStyles({ minify: mode === "production" })
|
||||
]);
|
||||
|
||||
syncUiRendererToRuntimeDists();
|
||||
|
||||
console.log(`Built Docker core server and UI assets in ${mode} mode.`);
|
||||
|
|
@ -1,23 +1,63 @@
|
|||
import esbuild from "esbuild";
|
||||
import { spawn } from "node:child_process";
|
||||
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { builtinModules } from "node:module";
|
||||
import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { builtinModules, createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const requireFromHere = createRequire(import.meta.url);
|
||||
|
||||
export const projectRoot = path.resolve(__dirname, "..");
|
||||
export const distDir = path.join(projectRoot, "dist");
|
||||
export const mainOutDir = path.join(distDir, "main");
|
||||
export const rendererOutDir = path.join(distDir, "renderer");
|
||||
export const appAssetsDir = path.join(distDir, "assets");
|
||||
export const packagesRoot = path.join(projectRoot, "packages");
|
||||
export const cliRoot = path.join(packagesRoot, "cli");
|
||||
export const coreRoot = path.join(packagesRoot, "core");
|
||||
export const electronRoot = path.join(packagesRoot, "electron");
|
||||
export const uiRoot = path.join(packagesRoot, "ui");
|
||||
export const cliSourceRoot = path.join(cliRoot, "src");
|
||||
export const coreSourceRoot = path.join(coreRoot, "src");
|
||||
export const electronSourceRoot = path.join(electronRoot, "src");
|
||||
export const uiSourceRoot = path.join(uiRoot, "src");
|
||||
export const legacyDistDir = path.join(projectRoot, "dist");
|
||||
export const cliDistDir = path.join(cliRoot, "dist");
|
||||
export const coreDistDir = path.join(coreRoot, "dist");
|
||||
export const electronDistDir = path.join(electronRoot, "dist");
|
||||
export const uiDistDir = path.join(uiRoot, "dist");
|
||||
export const distDir = electronDistDir;
|
||||
export const cliMainOutDir = path.join(cliDistDir, "main");
|
||||
export const coreMainOutDir = path.join(coreDistDir, "main");
|
||||
export const electronMainOutDir = path.join(electronDistDir, "main");
|
||||
export const mainOutDir = electronMainOutDir;
|
||||
export const gatewayPackageRoot = path.dirname(requireFromHere.resolve("@the-next-ai/ai-gateway/package.json"));
|
||||
export const gatewayRuntimeInput = path.join(gatewayPackageRoot, "bin", "next-ai-gateway.js");
|
||||
export const electronGatewayRuntimeOutput = path.join(electronMainOutDir, "next-ai-gateway.js");
|
||||
export const botGatewaySdkPackageRoot = path.dirname(requireFromHere.resolve("@the-next-ai/bot-gateway-sdk/package.json"));
|
||||
export const botGatewaySdkEntryInput = path.join(botGatewaySdkPackageRoot, "dist", "index.js");
|
||||
export const botGatewaySdkRunnerInput = path.join(botGatewaySdkPackageRoot, "bin", "bot-gateway-stdio.mjs");
|
||||
export const electronBotGatewaySdkRootDir = path.join(electronMainOutDir, "bot-gateway-sdk");
|
||||
export const electronBotGatewaySdkDistDir = path.join(electronBotGatewaySdkRootDir, "dist");
|
||||
export const electronBotGatewaySdkBinDir = path.join(electronBotGatewaySdkRootDir, "bin");
|
||||
export const electronBotGatewaySdkPackageOutput = path.join(electronBotGatewaySdkRootDir, "package.json");
|
||||
export const electronBotGatewaySdkEntryOutput = path.join(electronBotGatewaySdkDistDir, "index.js");
|
||||
export const electronBotGatewaySdkRunnerOutput = path.join(electronBotGatewaySdkBinDir, "bot-gateway-stdio.mjs");
|
||||
export const rendererOutDir = path.join(uiDistDir, "renderer");
|
||||
export const cliRendererOutDir = path.join(cliDistDir, "renderer");
|
||||
export const coreRendererOutDir = path.join(coreDistDir, "renderer");
|
||||
export const electronRendererOutDir = path.join(electronDistDir, "renderer");
|
||||
export const runtimeRendererOutDirs = [cliRendererOutDir, coreRendererOutDir, electronRendererOutDir];
|
||||
export const appAssetsDir = path.join(electronDistDir, "assets");
|
||||
export const rendererAssetsDir = path.join(rendererOutDir, "assets");
|
||||
export const marketplacePluginsDir = path.join(distDir, "marketplace", "plugins");
|
||||
export const appAssetsInput = path.join(projectRoot, "assets");
|
||||
export const modelCatalogInput = path.join(projectRoot, "models.json");
|
||||
export const modelCatalogOutput = path.join(distDir, "models.json");
|
||||
export const rendererRoot = path.join(projectRoot, "src", "renderer");
|
||||
export const cliMarketplacePluginsDir = path.join(cliDistDir, "marketplace", "plugins");
|
||||
export const coreMarketplacePluginsDir = path.join(coreDistDir, "marketplace", "plugins");
|
||||
export const electronMarketplacePluginsDir = path.join(electronDistDir, "marketplace", "plugins");
|
||||
export const marketplacePluginsDir = electronMarketplacePluginsDir;
|
||||
export const appAssetsInput = path.join(electronRoot, "assets");
|
||||
export const modelCatalogInput = path.join(coreRoot, "models.json");
|
||||
export const cliModelCatalogOutput = path.join(cliDistDir, "models.json");
|
||||
export const coreModelCatalogOutput = path.join(coreDistDir, "models.json");
|
||||
export const electronModelCatalogOutput = path.join(electronDistDir, "models.json");
|
||||
export const modelCatalogOutput = electronModelCatalogOutput;
|
||||
export const rendererRoot = uiSourceRoot;
|
||||
export const rendererHtmlInput = path.join(rendererRoot, "pages", "home", "index.html");
|
||||
export const rendererHtmlOutput = path.join(rendererOutDir, "pages", "home", "index.html");
|
||||
export const browserRendererHtmlInput = path.join(rendererRoot, "pages", "browser", "index.html");
|
||||
|
|
@ -27,11 +67,14 @@ export const trayRendererHtmlOutput = path.join(rendererOutDir, "pages", "tray",
|
|||
export const cssInput = path.join(rendererRoot, "styles", "globals.css");
|
||||
export const cssOutput = path.join(rendererAssetsDir, "main.css");
|
||||
export const webClientBridgeOutput = path.join(rendererAssetsDir, "web-client-bridge.js");
|
||||
export const electronUndiciProxyAgentInput = path.join(coreSourceRoot, "proxy", "undici-proxy-agent.ts");
|
||||
const lightweightMcpBundleNames = ["browser-web-search-proxy-mcp.js", "fusion-vision-mcp.js", "fusion-tool-fallback-mcp.js"];
|
||||
const lightweightMcpBundleMaxBytes = 128 * 1024;
|
||||
const forbiddenLightweightMcpInputs = [
|
||||
{ prefix: "src/main/", reason: "main-process modules can pull in config, Electron, or native storage side effects" },
|
||||
{ prefix: "src/renderer/", reason: "renderer modules do not belong in stdio MCP subprocesses" },
|
||||
{ prefix: "packages/core/src/config/", reason: "config modules can pull in native storage side effects" },
|
||||
{ prefix: "packages/core/src/storage/", reason: "native SQLite storage is not allowed in lightweight MCP subprocesses" },
|
||||
{ prefix: "packages/electron/src/", reason: "Electron runtime modules are not allowed in lightweight MCP subprocesses" },
|
||||
{ prefix: "packages/ui/src/", reason: "UI modules do not belong in stdio MCP subprocesses" },
|
||||
{ prefix: "node_modules/better-sqlite3/", reason: "native SQLite is not allowed in lightweight MCP subprocesses" },
|
||||
{ prefix: "node_modules/electron/", reason: "Electron runtime modules are not allowed in lightweight MCP subprocesses" }
|
||||
];
|
||||
|
|
@ -45,15 +88,28 @@ const nodeExternals = [
|
|||
];
|
||||
|
||||
export function cleanDist() {
|
||||
rmSync(distDir, { force: true, recursive: true });
|
||||
rmSync(legacyDistDir, { force: true, recursive: true });
|
||||
rmSync(cliDistDir, { force: true, recursive: true });
|
||||
rmSync(coreDistDir, { force: true, recursive: true });
|
||||
rmSync(electronDistDir, { force: true, recursive: true });
|
||||
rmSync(uiDistDir, { force: true, recursive: true });
|
||||
ensureDist();
|
||||
}
|
||||
|
||||
export function ensureDist() {
|
||||
mkdirSync(mainOutDir, { recursive: true });
|
||||
mkdirSync(cliMainOutDir, { recursive: true });
|
||||
mkdirSync(coreMainOutDir, { recursive: true });
|
||||
mkdirSync(electronMainOutDir, { recursive: true });
|
||||
mkdirSync(electronBotGatewaySdkDistDir, { recursive: true });
|
||||
mkdirSync(electronBotGatewaySdkBinDir, { recursive: true });
|
||||
mkdirSync(appAssetsDir, { recursive: true });
|
||||
mkdirSync(marketplacePluginsDir, { recursive: true });
|
||||
mkdirSync(cliMarketplacePluginsDir, { recursive: true });
|
||||
mkdirSync(coreMarketplacePluginsDir, { recursive: true });
|
||||
mkdirSync(electronMarketplacePluginsDir, { recursive: true });
|
||||
mkdirSync(rendererAssetsDir, { recursive: true });
|
||||
for (const outputDir of runtimeRendererOutDirs) {
|
||||
mkdirSync(path.join(outputDir, "assets"), { recursive: true });
|
||||
}
|
||||
mkdirSync(path.dirname(rendererHtmlOutput), { recursive: true });
|
||||
mkdirSync(path.dirname(browserRendererHtmlOutput), { recursive: true });
|
||||
mkdirSync(path.dirname(trayRendererHtmlOutput), { recursive: true });
|
||||
|
|
@ -69,12 +125,16 @@ export function copyAppAssets() {
|
|||
export function copyModelCatalog() {
|
||||
ensureDist();
|
||||
if (existsSync(modelCatalogInput)) {
|
||||
cpSync(modelCatalogInput, modelCatalogOutput);
|
||||
cpSync(modelCatalogInput, cliModelCatalogOutput);
|
||||
cpSync(modelCatalogInput, coreModelCatalogOutput);
|
||||
cpSync(modelCatalogInput, electronModelCatalogOutput);
|
||||
}
|
||||
}
|
||||
|
||||
export function copyRendererHtml() {
|
||||
copyRendererPageHtml(rendererHtmlInput, rendererHtmlOutput, "main.js");
|
||||
copyRendererPageHtml(rendererHtmlInput, rendererHtmlOutput, "main.js", {
|
||||
beforeModuleScriptTags: [' <script src="../../assets/web-client-bridge.js"></script>']
|
||||
});
|
||||
}
|
||||
|
||||
export function copyTrayRendererHtml() {
|
||||
|
|
@ -89,14 +149,25 @@ export function copyMarketplacePlugins() {
|
|||
ensureDist();
|
||||
for (const filename of ["claude-design-plugin.cjs", "cursor-proxy-plugin.cjs"]) {
|
||||
const source = path.join(projectRoot, "examples", "plugins", filename);
|
||||
const target = path.join(marketplacePluginsDir, filename);
|
||||
if (existsSync(source)) {
|
||||
cpSync(source, target);
|
||||
cpSync(source, path.join(cliMarketplacePluginsDir, filename));
|
||||
cpSync(source, path.join(coreMarketplacePluginsDir, filename));
|
||||
cpSync(source, path.join(electronMarketplacePluginsDir, filename));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function copyRendererPageHtml(input, output, scriptName) {
|
||||
export function syncUiRendererToRuntimeDists() {
|
||||
ensureDist();
|
||||
for (const outputDir of runtimeRendererOutDirs) {
|
||||
rmSync(outputDir, { force: true, recursive: true });
|
||||
if (existsSync(rendererOutDir)) {
|
||||
cpSync(rendererOutDir, outputDir, { recursive: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function copyRendererPageHtml(input, output, scriptName, options = {}) {
|
||||
ensureDist();
|
||||
const source = readFileSync(input, "utf8");
|
||||
const styleTag = ' <link rel="stylesheet" href="../../assets/main.css" />';
|
||||
|
|
@ -105,6 +176,12 @@ function copyRendererPageHtml(input, output, scriptName) {
|
|||
? source.replace(' <script type="module" src="./main.tsx"></script>', scriptTag)
|
||||
: source.replace("</body>", `${scriptTag}\n </body>`);
|
||||
|
||||
for (const extraScriptTag of options.beforeModuleScriptTags ?? []) {
|
||||
if (!hasScriptTag(html, extraScriptTag)) {
|
||||
html = html.replace(scriptTag, `${extraScriptTag}\n${scriptTag}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!html.includes('href="../../assets/main.css"')) {
|
||||
html = html.replace("</head>", `${styleTag}\n </head>`);
|
||||
}
|
||||
|
|
@ -112,18 +189,38 @@ function copyRendererPageHtml(input, output, scriptName) {
|
|||
writeFileSync(output, html, "utf8");
|
||||
}
|
||||
|
||||
function hasScriptTag(html, scriptTag) {
|
||||
const sourceMatch = scriptTag.match(/\bsrc="([^"]+)"/);
|
||||
return sourceMatch ? html.includes(sourceMatch[1]) : html.includes(scriptTag);
|
||||
}
|
||||
|
||||
function normalizeDuplicateShebangs(source) {
|
||||
const lines = source.split("\n");
|
||||
if (!lines[0]?.startsWith("#!")) {
|
||||
return source;
|
||||
}
|
||||
let index = 1;
|
||||
while (lines[index]?.startsWith("#!")) {
|
||||
index += 1;
|
||||
}
|
||||
return [lines[0], ...lines.slice(index)].join("\n");
|
||||
}
|
||||
|
||||
export function createMainBuildOptions({ mode = "production", plugins = [] } = {}) {
|
||||
return {
|
||||
absWorkingDir: projectRoot,
|
||||
bundle: true,
|
||||
entryNames: "[name]",
|
||||
entryPoints: [
|
||||
path.join(projectRoot, "src", "main", "main.ts"),
|
||||
path.join(projectRoot, "src", "main", "browser-preload.ts"),
|
||||
path.join(projectRoot, "src", "server", "mcp", "browser-web-search-proxy-mcp.ts"),
|
||||
path.join(projectRoot, "src", "server", "mcp", "fusion-vision-mcp.ts"),
|
||||
path.join(projectRoot, "src", "server", "mcp", "fusion-tool-fallback-mcp.ts"),
|
||||
path.join(projectRoot, "src", "main", "preload.ts")
|
||||
path.join(electronSourceRoot, "main", "main.ts"),
|
||||
path.join(electronSourceRoot, "main", "browser-preload.ts"),
|
||||
gatewayRuntimeInput,
|
||||
path.join(coreSourceRoot, "mcp", "browser-web-search-proxy-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "fusion-vision-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "fusion-tool-fallback-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "toolhub-mcp.ts"),
|
||||
electronUndiciProxyAgentInput,
|
||||
path.join(electronSourceRoot, "main", "preload.ts")
|
||||
],
|
||||
external: nodeExternals,
|
||||
format: "cjs",
|
||||
|
|
@ -131,9 +228,9 @@ export function createMainBuildOptions({ mode = "production", plugins = [] } = {
|
|||
logLevel: "info",
|
||||
metafile: true,
|
||||
minify: mode === "production",
|
||||
outdir: mainOutDir,
|
||||
outdir: electronMainOutDir,
|
||||
platform: "node",
|
||||
plugins,
|
||||
plugins: [packageAliasPlugin(), ...plugins],
|
||||
sourcemap: mode !== "production",
|
||||
target: "node22"
|
||||
};
|
||||
|
|
@ -144,15 +241,44 @@ export function createCliBuildOptions({ mode = "production", plugins = [] } = {}
|
|||
absWorkingDir: projectRoot,
|
||||
bundle: true,
|
||||
entryNames: "[name]",
|
||||
entryPoints: [path.join(projectRoot, "src", "main", "cli.ts")],
|
||||
entryPoints: [
|
||||
path.join(cliSourceRoot, "cli.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "fusion-vision-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "fusion-tool-fallback-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "toolhub-mcp.ts")
|
||||
],
|
||||
external: nodeExternals.filter((moduleName) => moduleName !== "electron"),
|
||||
format: "cjs",
|
||||
legalComments: "none",
|
||||
logLevel: "info",
|
||||
minify: mode === "production",
|
||||
outdir: mainOutDir,
|
||||
outdir: cliMainOutDir,
|
||||
platform: "node",
|
||||
plugins: [forbidCliElectronPlugin(), ...plugins],
|
||||
plugins: [forbidCliElectronPlugin(), packageAliasPlugin(), ...plugins],
|
||||
sourcemap: mode !== "production",
|
||||
target: "node22"
|
||||
};
|
||||
}
|
||||
|
||||
export function createCoreServerBuildOptions({ mode = "production", plugins = [] } = {}) {
|
||||
return {
|
||||
absWorkingDir: projectRoot,
|
||||
bundle: true,
|
||||
entryNames: "[name]",
|
||||
entryPoints: [
|
||||
path.join(coreSourceRoot, "entrypoints", "server.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "fusion-vision-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "fusion-tool-fallback-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "toolhub-mcp.ts")
|
||||
],
|
||||
external: nodeExternals.filter((moduleName) => moduleName !== "electron"),
|
||||
format: "cjs",
|
||||
legalComments: "none",
|
||||
logLevel: "info",
|
||||
minify: mode === "production",
|
||||
outdir: coreMainOutDir,
|
||||
platform: "node",
|
||||
plugins: [forbidCliElectronPlugin(), packageAliasPlugin(), ...plugins],
|
||||
sourcemap: mode !== "production",
|
||||
target: "node22"
|
||||
};
|
||||
|
|
@ -183,7 +309,7 @@ export function createRendererBuildOptions({ mode = "production", plugins = [] }
|
|||
minify: mode === "production",
|
||||
outfile: path.join(rendererAssetsDir, "main.js"),
|
||||
platform: "browser",
|
||||
plugins: [rendererAliasPlugin(), ...plugins],
|
||||
plugins: [rendererAliasPlugin(), packageAliasPlugin(), ...plugins],
|
||||
publicPath: "../../assets",
|
||||
sourcemap: mode !== "production",
|
||||
target: "chrome120"
|
||||
|
|
@ -210,19 +336,40 @@ export function createWebClientBridgeBuildOptions({ mode = "production", plugins
|
|||
return {
|
||||
absWorkingDir: projectRoot,
|
||||
bundle: true,
|
||||
entryPoints: [path.join(projectRoot, "src", "main", "web-client-bridge.ts")],
|
||||
entryPoints: [path.join(uiSourceRoot, "web-client-bridge.ts")],
|
||||
format: "iife",
|
||||
legalComments: "none",
|
||||
logLevel: "info",
|
||||
minify: mode === "production",
|
||||
outfile: webClientBridgeOutput,
|
||||
platform: "browser",
|
||||
plugins,
|
||||
plugins: [packageAliasPlugin(), ...plugins],
|
||||
sourcemap: mode !== "production",
|
||||
target: "chrome120"
|
||||
};
|
||||
}
|
||||
|
||||
export function createBotGatewaySdkBuildOptions({ mode = "production", plugins = [] } = {}) {
|
||||
return {
|
||||
absWorkingDir: projectRoot,
|
||||
bundle: true,
|
||||
entryPoints: [botGatewaySdkEntryInput],
|
||||
external: [
|
||||
...builtinModules,
|
||||
...builtinModules.map((moduleName) => `node:${moduleName}`)
|
||||
],
|
||||
format: "esm",
|
||||
legalComments: "none",
|
||||
logLevel: "info",
|
||||
minify: mode === "production",
|
||||
outfile: electronBotGatewaySdkEntryOutput,
|
||||
platform: "node",
|
||||
plugins,
|
||||
sourcemap: mode !== "production",
|
||||
target: "node22"
|
||||
};
|
||||
}
|
||||
|
||||
export function watchPlugin(name, onEnd) {
|
||||
return {
|
||||
name: `${name}-watch`,
|
||||
|
|
@ -239,11 +386,38 @@ export function watchPlugin(name, onEnd) {
|
|||
export async function buildMain(options = {}) {
|
||||
const [mainBuildResult] = await Promise.all([
|
||||
esbuild.build(createMainBuildOptions(options)),
|
||||
esbuild.build(createCliBuildOptions(options))
|
||||
buildBotGatewaySdkRuntime(options),
|
||||
buildCoreServer(options),
|
||||
buildCli(options)
|
||||
]);
|
||||
copyCliRuntimeToElectronDist();
|
||||
validateLightweightMcpBundles(mainBuildResult.metafile);
|
||||
}
|
||||
|
||||
export async function buildBotGatewaySdkRuntime(options = {}) {
|
||||
ensureDist();
|
||||
await esbuild.build(createBotGatewaySdkBuildOptions(options));
|
||||
writeFileSync(
|
||||
electronBotGatewaySdkPackageOutput,
|
||||
`${JSON.stringify({ private: true, type: "module" }, null, 2)}\n`,
|
||||
"utf8"
|
||||
);
|
||||
writeFileSync(
|
||||
electronBotGatewaySdkRunnerOutput,
|
||||
normalizeDuplicateShebangs(readFileSync(botGatewaySdkRunnerInput, "utf8")),
|
||||
"utf8"
|
||||
);
|
||||
chmodSync(electronBotGatewaySdkRunnerOutput, 0o755);
|
||||
}
|
||||
|
||||
export async function buildCli(options = {}) {
|
||||
await esbuild.build(createCliBuildOptions(options));
|
||||
}
|
||||
|
||||
export async function buildCoreServer(options = {}) {
|
||||
await esbuild.build(createCoreServerBuildOptions(options));
|
||||
}
|
||||
|
||||
export async function buildRenderer(options = {}) {
|
||||
await esbuild.build(createRendererBuildOptions(options));
|
||||
}
|
||||
|
|
@ -260,6 +434,14 @@ export async function buildWebClientBridge(options = {}) {
|
|||
await esbuild.build(createWebClientBridgeBuildOptions(options));
|
||||
}
|
||||
|
||||
export function copyCliRuntimeToElectronDist() {
|
||||
ensureDist();
|
||||
const cliRuntime = path.join(cliMainOutDir, "cli.js");
|
||||
if (existsSync(cliRuntime)) {
|
||||
cpSync(cliRuntime, path.join(electronMainOutDir, "cli.js"));
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildStyles({ minify = false } = {}) {
|
||||
ensureDist();
|
||||
const args = ["-i", cssInput, "-o", cssOutput];
|
||||
|
|
@ -305,6 +487,26 @@ function rendererAliasPlugin() {
|
|||
};
|
||||
}
|
||||
|
||||
function packageAliasPlugin() {
|
||||
return {
|
||||
name: "ccr-package-alias",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^@ccr\/cli\// }, (args) => {
|
||||
return { path: resolvePackageImport(cliSourceRoot, args.path.slice("@ccr/cli/".length)) };
|
||||
});
|
||||
build.onResolve({ filter: /^@ccr\/core\// }, (args) => {
|
||||
return { path: resolvePackageImport(coreSourceRoot, args.path.slice("@ccr/core/".length)) };
|
||||
});
|
||||
build.onResolve({ filter: /^@ccr\/electron\// }, (args) => {
|
||||
return { path: resolvePackageImport(electronSourceRoot, args.path.slice("@ccr/electron/".length)) };
|
||||
});
|
||||
build.onResolve({ filter: /^@ccr\/ui\// }, (args) => {
|
||||
return { path: resolvePackageImport(uiSourceRoot, args.path.slice("@ccr/ui/".length)) };
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function forbidCliElectronPlugin() {
|
||||
return {
|
||||
name: "forbid-cli-electron",
|
||||
|
|
@ -371,19 +573,23 @@ function normalizeBuildPath(value) {
|
|||
}
|
||||
|
||||
function resolveRendererImport(importPath) {
|
||||
const basePath = path.resolve(rendererRoot, importPath);
|
||||
return resolvePackageImport(rendererRoot, importPath);
|
||||
}
|
||||
|
||||
function resolvePackageImport(rootDir, importPath) {
|
||||
const packageBasePath = path.resolve(rootDir, importPath);
|
||||
const candidates = [
|
||||
basePath,
|
||||
`${basePath}.tsx`,
|
||||
`${basePath}.ts`,
|
||||
`${basePath}.jsx`,
|
||||
`${basePath}.js`,
|
||||
`${basePath}.json`,
|
||||
`${basePath}.css`,
|
||||
path.join(basePath, "index.tsx"),
|
||||
path.join(basePath, "index.ts"),
|
||||
path.join(basePath, "index.jsx"),
|
||||
path.join(basePath, "index.js")
|
||||
packageBasePath,
|
||||
`${packageBasePath}.tsx`,
|
||||
`${packageBasePath}.ts`,
|
||||
`${packageBasePath}.jsx`,
|
||||
`${packageBasePath}.js`,
|
||||
`${packageBasePath}.json`,
|
||||
`${packageBasePath}.css`,
|
||||
path.join(packageBasePath, "index.tsx"),
|
||||
path.join(packageBasePath, "index.ts"),
|
||||
path.join(packageBasePath, "index.jsx"),
|
||||
path.join(packageBasePath, "index.js")
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
|
|
@ -392,5 +598,5 @@ function resolveRendererImport(importPath) {
|
|||
}
|
||||
}
|
||||
|
||||
return basePath;
|
||||
return packageBasePath;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ function runSuite(suite) {
|
|||
console.log(`\nRunning ${suite} tests...`);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(electron, ["--test", `dist/tests/${suite}/*.js`], {
|
||||
const child = spawn(electron, ["--test", `dist/tests/${suite}/*.test.js`], {
|
||||
cwd: projectRoot,
|
||||
env: {
|
||||
...process.env,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,9 @@ import { fileURLToPath } from "node:url";
|
|||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const projectRoot = path.resolve(__dirname, "..");
|
||||
const testsOutDir = path.join(projectRoot, "dist", "tests");
|
||||
const rendererRoot = path.join(projectRoot, "src", "renderer");
|
||||
const rendererRoot = path.join(projectRoot, "packages", "ui", "src");
|
||||
const cliSourceRoot = path.join(projectRoot, "packages", "cli", "src");
|
||||
const coreSourceRoot = path.join(projectRoot, "packages", "core", "src");
|
||||
const testSuites = [
|
||||
{ name: "main", testDir: path.join(projectRoot, "tests", "main") },
|
||||
{ name: "renderer", testDir: path.join(projectRoot, "tests", "renderer") }
|
||||
|
|
@ -25,7 +27,10 @@ if (unknownSuites.length > 0) {
|
|||
rmSync(testsOutDir, { force: true, recursive: true });
|
||||
|
||||
for (const suite of selectedSuites) {
|
||||
const entryPoints = findTestFiles(suite.testDir);
|
||||
const entryPoints = [
|
||||
...findTestFiles(suite.testDir),
|
||||
...runtimeEntryPointsForSuite(suite.name)
|
||||
];
|
||||
if (entryPoints.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
|
@ -53,11 +58,21 @@ for (const suite of selectedSuites) {
|
|||
logLevel: "info",
|
||||
outdir: path.join(testsOutDir, suite.name),
|
||||
platform: "node",
|
||||
plugins: [rendererAliasPlugin()],
|
||||
plugins: [rendererAliasPlugin(), packageAliasPlugin()],
|
||||
target: "node22"
|
||||
});
|
||||
}
|
||||
|
||||
function runtimeEntryPointsForSuite(suiteName) {
|
||||
if (suiteName !== "main") {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
path.join(coreSourceRoot, "mcp", "fusion-vision-mcp.ts"),
|
||||
path.join(coreSourceRoot, "mcp", "toolhub-mcp.ts")
|
||||
];
|
||||
}
|
||||
|
||||
function findTestFiles(dir) {
|
||||
if (!existsSync(dir)) {
|
||||
return [];
|
||||
|
|
@ -87,8 +102,26 @@ function rendererAliasPlugin() {
|
|||
};
|
||||
}
|
||||
|
||||
function packageAliasPlugin() {
|
||||
return {
|
||||
name: "test-package-alias",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^@ccr\/cli\// }, (args) => {
|
||||
return { path: resolvePackageImport(cliSourceRoot, args.path.slice("@ccr/cli/".length)) };
|
||||
});
|
||||
build.onResolve({ filter: /^@ccr\/core\// }, (args) => {
|
||||
return { path: resolvePackageImport(coreSourceRoot, args.path.slice("@ccr/core/".length)) };
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function resolveRendererImport(importPath) {
|
||||
const basePath = path.resolve(rendererRoot, importPath);
|
||||
return resolvePackageImport(rendererRoot, importPath);
|
||||
}
|
||||
|
||||
function resolvePackageImport(rootDir, importPath) {
|
||||
const basePath = path.resolve(rootDir, importPath);
|
||||
const candidates = [
|
||||
basePath,
|
||||
`${basePath}.tsx`,
|
||||
|
|
|
|||
|
|
@ -9,6 +9,19 @@ const betterSqliteNativeRelativePath = path.join(
|
|||
"Release",
|
||||
"better_sqlite3.node"
|
||||
);
|
||||
const betterSqlitePackageRelativePath = path.join("app.asar.unpacked", "node_modules", "better-sqlite3");
|
||||
const betterSqlitePrunablePaths = [
|
||||
"deps",
|
||||
"src",
|
||||
"binding.gyp",
|
||||
"README.md",
|
||||
"docs",
|
||||
"benchmark",
|
||||
"benchmarks",
|
||||
"test",
|
||||
path.join("build", "Release", "obj"),
|
||||
path.join("build", "Release", "obj.target")
|
||||
];
|
||||
|
||||
module.exports = async function verifyPackagedApp(context) {
|
||||
const platform = context?.electronPlatformName;
|
||||
|
|
@ -21,6 +34,7 @@ module.exports = async function verifyPackagedApp(context) {
|
|||
|
||||
const resourcesDir = findResourcesDir(appOutDir, platform);
|
||||
assertFile(path.join(resourcesDir, "app.asar"), "Packaged app archive");
|
||||
cleanupBetterSqlitePackage(resourcesDir);
|
||||
|
||||
const nativeModule = path.join(resourcesDir, betterSqliteNativeRelativePath);
|
||||
assertFile(nativeModule, "better-sqlite3 native module");
|
||||
|
|
@ -41,6 +55,13 @@ module.exports = async function verifyPackagedApp(context) {
|
|||
}
|
||||
};
|
||||
|
||||
function cleanupBetterSqlitePackage(resourcesDir) {
|
||||
const packageDir = path.join(resourcesDir, betterSqlitePackageRelativePath);
|
||||
for (const relativePath of betterSqlitePrunablePaths) {
|
||||
fs.rmSync(path.join(packageDir, relativePath), { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function findResourcesDir(appOutDir, platform) {
|
||||
if (platform !== "darwin") {
|
||||
return path.join(appOutDir, "resources");
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/renderer/styles/globals.css",
|
||||
"css": "packages/ui/src/styles/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
|
|
|
|||
15
docker-compose.yml
Normal file
15
docker-compose.yml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
services:
|
||||
ccr:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: claude-code-router:local
|
||||
ports:
|
||||
# Publish only Nginx. Internal web/gateway listeners stay inside the container.
|
||||
- "3458:8080"
|
||||
volumes:
|
||||
- ccr-data:/data
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
ccr-data:
|
||||
91
docker/README.md
Normal file
91
docker/README.md
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
# Docker deployment
|
||||
|
||||
This image runs the core server package with PM2 and serves the built UI package
|
||||
through Nginx. Nginx is the only published entrypoint: it serves the UI, proxies
|
||||
management API calls to the internal core server, and proxies gateway API calls
|
||||
to the internal gateway listener.
|
||||
|
||||
## Build and run
|
||||
|
||||
```sh
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
Then open:
|
||||
|
||||
- Web UI: <http://localhost:3458>
|
||||
- Gateway endpoint: <http://localhost:3458>
|
||||
|
||||
`docker-compose.yml` publishes only Nginx (`3458:8080`). Behind Nginx, the image
|
||||
runs separate container-private listeners for management RPC, API gateway
|
||||
routing, and the core gateway runtime. They are implementation details and are
|
||||
not published or configured by the default Compose file.
|
||||
|
||||
To use a different host port, change the Compose port mapping and keep the
|
||||
public router endpoint in sync:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
ccr:
|
||||
ports:
|
||||
- "8088:8080"
|
||||
environment:
|
||||
CCR_PUBLIC_BASE_URL: http://127.0.0.1:8088
|
||||
```
|
||||
|
||||
The container stores config and SQLite databases under `/data`, backed by the
|
||||
`ccr-data` volume in `docker-compose.yml`.
|
||||
|
||||
On a fresh data volume, the Web UI starts immediately. The gateway endpoint is
|
||||
available through the same Nginx entrypoint, but the gateway only starts after at
|
||||
least one provider and model are configured.
|
||||
|
||||
## Image scripts
|
||||
|
||||
```sh
|
||||
npm run docker:build
|
||||
npm run docker:run
|
||||
```
|
||||
|
||||
## Smoke test
|
||||
|
||||
```sh
|
||||
npm run test:docker
|
||||
```
|
||||
|
||||
The smoke test builds the image, starts an isolated temporary container with a
|
||||
special-character `CCR_WEB_AUTH_TOKEN`, verifies that only the Nginx port is
|
||||
published, checks UI and RPC authentication, confirms legacy Docker config is
|
||||
migrated to the public Nginx router endpoint, and removes its temporary
|
||||
container and volume. Set `CCR_DOCKER_TEST_SKIP_BUILD=1` to reuse an already
|
||||
built image.
|
||||
|
||||
The Dockerfile uses `node:22-bookworm` for build and native SQLite dependency
|
||||
installation, then copies the production dependencies into a smaller
|
||||
`node:22-bookworm-slim` runtime image. To use different base images:
|
||||
|
||||
```sh
|
||||
docker build \
|
||||
--build-arg NODE_IMAGE=node:22-bookworm \
|
||||
--build-arg RUNTIME_NODE_IMAGE=node:22-bookworm-slim \
|
||||
-t claude-code-router:local .
|
||||
```
|
||||
|
||||
## Environment
|
||||
|
||||
Most deployments only need the published Nginx port mapping, `CCR_WEB_AUTH_TOKEN`,
|
||||
and optionally `CCR_PUBLIC_BASE_URL` when the host-facing URL is not
|
||||
`http://127.0.0.1:3458`.
|
||||
|
||||
| Variable | Default | Description |
|
||||
| --- | --- | --- |
|
||||
| `CCR_WEB_AUTH_TOKEN` | generated | Shared management UI token used by Nginx redirects and the core server. |
|
||||
| `CCR_PUBLIC_BASE_URL` | `http://127.0.0.1:3458` | Full public router endpoint override. Set this when changing the host-facing Compose port. |
|
||||
| `CCR_DATA_DIR` | `/data` | Container data root. |
|
||||
| `CCR_NO_GATEWAY` | `0` | Set to `1` to run only the Web UI management service. |
|
||||
| `CCR_DOCKER_INIT_CONFIG` | `1` | Set to `0` to disable first-run `config.json` bootstrap. |
|
||||
| `CCR_DOCKER_SYNC_PUBLIC_ENDPOINT` | `1` | Sync existing Docker config to the Nginx public router endpoint on startup. |
|
||||
|
||||
The first-run bootstrap writes a minimal legacy `config.json` only when neither
|
||||
`config.json` nor `config.sqlite` exists in the mounted data directory. Once the
|
||||
UI saves settings into SQLite, existing persisted configuration takes priority.
|
||||
207
docker/entrypoint.sh
Normal file
207
docker/entrypoint.sh
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
CCR_DATA_DIR="${CCR_DATA_DIR:-/data}"
|
||||
CCR_WEB_HOST="${CCR_WEB_HOST:-127.0.0.1}"
|
||||
CCR_WEB_PORT="${CCR_WEB_PORT:-3459}"
|
||||
CCR_NGINX_PORT="${CCR_NGINX_PORT:-8080}"
|
||||
CCR_GATEWAY_HOST="${CCR_GATEWAY_HOST:-127.0.0.1}"
|
||||
CCR_GATEWAY_PORT="${CCR_GATEWAY_PORT:-3456}"
|
||||
CCR_GATEWAY_CORE_PORT="${CCR_GATEWAY_CORE_PORT:-3457}"
|
||||
CCR_PUBLIC_HOST="${CCR_PUBLIC_HOST:-127.0.0.1}"
|
||||
CCR_PUBLIC_PORT="${CCR_PUBLIC_PORT:-3458}"
|
||||
CCR_PUBLIC_BASE_URL="${CCR_PUBLIC_BASE_URL:-http://${CCR_PUBLIC_HOST}:${CCR_PUBLIC_PORT}}"
|
||||
CCR_NO_GATEWAY="${CCR_NO_GATEWAY:-0}"
|
||||
|
||||
if [ -z "${CCR_WEB_AUTH_TOKEN:-}" ]; then
|
||||
CCR_WEB_AUTH_TOKEN="$(node -e "process.stdout.write(require('node:crypto').randomBytes(32).toString('base64url'))")"
|
||||
fi
|
||||
CCR_WEB_AUTH_TOKEN_QUERY="$(node -e "process.stdout.write(encodeURIComponent(process.argv[1] || ''))" "${CCR_WEB_AUTH_TOKEN}")"
|
||||
|
||||
export HOME="${CCR_DATA_DIR}"
|
||||
export CCR_DATA_DIR
|
||||
export CCR_GATEWAY_CORE_PORT
|
||||
export CCR_GATEWAY_HOST
|
||||
export CCR_GATEWAY_PORT
|
||||
export CCR_NGINX_PORT
|
||||
export CCR_NO_GATEWAY
|
||||
export CCR_PUBLIC_BASE_URL
|
||||
export CCR_PUBLIC_HOST
|
||||
export CCR_PUBLIC_PORT
|
||||
export CCR_WEB_AUTH_TOKEN
|
||||
export CCR_WEB_AUTH_TOKEN_QUERY
|
||||
export CCR_WEB_HOST
|
||||
export CCR_WEB_PORT
|
||||
|
||||
CONFIG_DIR="${HOME}/.claude-code-router"
|
||||
CONFIG_FILE="${CONFIG_DIR}/config.json"
|
||||
APP_CONFIG_DB_FILE="${CONFIG_DIR}/config.sqlite"
|
||||
|
||||
mkdir -p "${CONFIG_DIR}" "${CONFIG_DIR}/app-data" /run/nginx /var/lib/nginx /var/log/nginx
|
||||
|
||||
if [ "${CCR_DOCKER_INIT_CONFIG:-1}" != "0" ] && [ ! -f "${CONFIG_FILE}" ] && [ ! -f "${APP_CONFIG_DB_FILE}" ]; then
|
||||
node - <<'NODE'
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const configDir = path.join(process.env.HOME, ".claude-code-router");
|
||||
const configFile = path.join(configDir, "config.json");
|
||||
const gatewayHost = process.env.CCR_GATEWAY_HOST || "0.0.0.0";
|
||||
const gatewayPort = Number(process.env.CCR_GATEWAY_PORT || "3456");
|
||||
const gatewayCorePort = Number(process.env.CCR_GATEWAY_CORE_PORT || "3457");
|
||||
const publicBaseUrl = (process.env.CCR_PUBLIC_BASE_URL || `http://127.0.0.1:${process.env.CCR_PUBLIC_PORT || "3458"}`).replace(/\/+$/, "");
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(configFile, `${JSON.stringify({
|
||||
HOST: gatewayHost,
|
||||
PORT: gatewayPort,
|
||||
gateway: {
|
||||
coreHost: "127.0.0.1",
|
||||
corePort: gatewayCorePort,
|
||||
enabled: true,
|
||||
host: gatewayHost,
|
||||
port: gatewayPort
|
||||
},
|
||||
routerEndpoint: publicBaseUrl
|
||||
}, null, 2)}\n`, { mode: 0o600 });
|
||||
NODE
|
||||
fi
|
||||
|
||||
if [ "${CCR_DOCKER_SYNC_PUBLIC_ENDPOINT:-1}" != "0" ]; then
|
||||
node - <<'NODE'
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const configDir = path.join(process.env.HOME, ".claude-code-router");
|
||||
const configFile = path.join(configDir, "config.json");
|
||||
const appConfigDbFile = path.join(configDir, "config.sqlite");
|
||||
const gatewayHost = process.env.CCR_GATEWAY_HOST || "127.0.0.1";
|
||||
const gatewayPort = Number(process.env.CCR_GATEWAY_PORT || "3456");
|
||||
const gatewayCorePort = Number(process.env.CCR_GATEWAY_CORE_PORT || "3457");
|
||||
const publicBaseUrl = (process.env.CCR_PUBLIC_BASE_URL || `http://127.0.0.1:${process.env.CCR_PUBLIC_PORT || "3458"}`).replace(/\/+$/, "");
|
||||
|
||||
function syncConfig(value) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return value;
|
||||
}
|
||||
value.HOST = gatewayHost;
|
||||
value.PORT = gatewayPort;
|
||||
value.gateway = {
|
||||
...(value.gateway && typeof value.gateway === "object" && !Array.isArray(value.gateway) ? value.gateway : {}),
|
||||
coreHost: "127.0.0.1",
|
||||
corePort: gatewayCorePort,
|
||||
enabled: true,
|
||||
host: gatewayHost,
|
||||
port: gatewayPort
|
||||
};
|
||||
value.routerEndpoint = publicBaseUrl;
|
||||
return value;
|
||||
}
|
||||
|
||||
function syncJsonFile() {
|
||||
if (!fs.existsSync(configFile)) {
|
||||
return;
|
||||
}
|
||||
const parsed = JSON.parse(fs.readFileSync(configFile, "utf8"));
|
||||
fs.writeFileSync(configFile, `${JSON.stringify(syncConfig(parsed), null, 2)}\n`, { mode: 0o600 });
|
||||
}
|
||||
|
||||
function syncSqliteConfig() {
|
||||
if (!fs.existsSync(appConfigDbFile)) {
|
||||
return;
|
||||
}
|
||||
let Database;
|
||||
try {
|
||||
Database = require("better-sqlite3");
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const db = new Database(appConfigDbFile);
|
||||
try {
|
||||
const row = db.prepare("select value_json from app_config where key = ?").get("default");
|
||||
if (!row?.value_json) {
|
||||
return;
|
||||
}
|
||||
const parsed = JSON.parse(row.value_json);
|
||||
db.prepare("update app_config set value_json = ?, updated_at = ? where key = ?")
|
||||
.run(JSON.stringify(syncConfig(parsed)), new Date().toISOString(), "default");
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
syncJsonFile();
|
||||
syncSqliteConfig();
|
||||
NODE
|
||||
fi
|
||||
|
||||
cat > /etc/nginx/conf.d/default.conf <<EOF
|
||||
server {
|
||||
listen ${CCR_NGINX_PORT};
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index pages/home/index.html;
|
||||
absolute_redirect off;
|
||||
|
||||
client_max_body_size 8m;
|
||||
|
||||
location = / {
|
||||
return 302 /pages/home/index.html?ccr_web_token=${CCR_WEB_AUTH_TOKEN_QUERY};
|
||||
}
|
||||
|
||||
location = /pages/home/index.html {
|
||||
if (\$arg_ccr_web_token = "") {
|
||||
return 302 /pages/home/index.html?ccr_web_token=${CCR_WEB_AUTH_TOKEN_QUERY};
|
||||
}
|
||||
try_files /pages/home/index.html =404;
|
||||
}
|
||||
|
||||
location = /api/ccr/rpc {
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host ${CCR_WEB_HOST}:${CCR_WEB_PORT};
|
||||
proxy_set_header Origin http://${CCR_WEB_HOST}:${CCR_WEB_PORT};
|
||||
proxy_set_header Referer http://${CCR_WEB_HOST}:${CCR_WEB_PORT}/;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Host \$host;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
proxy_pass http://${CCR_WEB_HOST}:${CCR_WEB_PORT};
|
||||
}
|
||||
|
||||
location = /health {
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host ${CCR_GATEWAY_HOST}:${CCR_GATEWAY_PORT};
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Host \$host;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
proxy_pass http://${CCR_GATEWAY_HOST}:${CCR_GATEWAY_PORT};
|
||||
}
|
||||
|
||||
location ~ ^/(v1|v1beta|mcp|messages|chat/completions|responses|interactions)(/|$) {
|
||||
proxy_http_version 1.1;
|
||||
proxy_buffering off;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host ${CCR_GATEWAY_HOST}:${CCR_GATEWAY_PORT};
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Host \$host;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
proxy_pass http://${CCR_GATEWAY_HOST}:${CCR_GATEWAY_PORT};
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files \$uri \$uri/ /pages/home/index.html;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
if [ "$#" -gt 0 ]; then
|
||||
exec "$@"
|
||||
fi
|
||||
|
||||
if [ -x /app/node_modules/.bin/pm2-runtime ]; then
|
||||
exec /app/node_modules/.bin/pm2-runtime docker/pm2.config.cjs
|
||||
fi
|
||||
|
||||
exec /app/packages/core/node_modules/.bin/pm2-runtime docker/pm2.config.cjs
|
||||
35
docker/pm2.config.cjs
Normal file
35
docker/pm2.config.cjs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
const noGateway = /^(1|true|yes)$/i.test(process.env.CCR_NO_GATEWAY || "");
|
||||
const serverArgs = [
|
||||
"--host",
|
||||
process.env.CCR_WEB_HOST || "127.0.0.1",
|
||||
"--port",
|
||||
process.env.CCR_WEB_PORT || "3459",
|
||||
"--no-open"
|
||||
];
|
||||
|
||||
if (noGateway) {
|
||||
serverArgs.push("--no-gateway");
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: "ccr-core-server",
|
||||
script: "/app/packages/core/dist/main/server.js",
|
||||
args: serverArgs,
|
||||
cwd: "/app",
|
||||
interpreter: "node",
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_ENV: "production"
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "ccr-nginx",
|
||||
script: "/usr/sbin/nginx",
|
||||
args: ["-g", "daemon off;"],
|
||||
cwd: "/app",
|
||||
interpreter: "none"
|
||||
}
|
||||
]
|
||||
};
|
||||
BIN
docs/public/provider-icons/claudeapi.png
Normal file
BIN
docs/public/provider-icons/claudeapi.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
BIN
docs/public/provider-icons/code0.png
Normal file
BIN
docs/public/provider-icons/code0.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
BIN
docs/public/provider-icons/fenno.jpg
Normal file
BIN
docs/public/provider-icons/fenno.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 97 KiB |
BIN
docs/public/provider-icons/qiniu-ai.png
Normal file
BIN
docs/public/provider-icons/qiniu-ai.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 5.6 KiB |
|
|
@ -2,29 +2,37 @@
|
|||
title: Claude Code Router Detailed Configuration
|
||||
pageTitle: Detailed Configuration
|
||||
eyebrow: Detailed Configuration
|
||||
lead: Configure the overview dashboard, API keys, server, providers, routing, Agent Config, Fusion, Bots, tray, and the config database location in detail.
|
||||
lead: "Separate main app pages from settings pages while following the app's actual order: main pages cover overview, providers, Agent Config, routing, Fusion, API keys, logs and observability, server, and extensions; settings pages cover ToolHub, Bots, data, and tray."
|
||||
---
|
||||
|
||||
## Page Structure
|
||||
|
||||
Detailed configuration docs are split into standalone pages. Every left-sidebar item opens a page; the right outline is reserved for headings inside the current page.
|
||||
Detailed configuration docs are split into standalone pages. Every left-sidebar item opens a page; the right outline is reserved for headings inside the current page. Main pages follow the app's left navigation order. Settings pages are grouped separately and follow the settings dialog order.
|
||||
|
||||
## Main Pages
|
||||
|
||||
| Page | Covers |
|
||||
| --- | --- |
|
||||
| Overview Dashboard | System status, account balance, usage widgets, layout editing, and share cards |
|
||||
| API Keys | Client access keys, expiration, and local limits |
|
||||
| Server | Host, port, proxy mode, system proxy, network capture, and CA certificate |
|
||||
| Provider Config | Upstream services, protocol, Base URL, model list, and credentials |
|
||||
| One click import | Provider deeplink protocol, manifest import, one-click import buttons, and security boundaries |
|
||||
| Routing Config | Default routing, conditional rules, fallback, and request rewrites |
|
||||
| Logs & Observability | Request logs, Agent execution traces, tool calls, and tool results |
|
||||
| Fusion Models | Combine a base model with vision, search, or MCP tools into a new selectable model |
|
||||
| Agent Config | Agent launch method, model, scope, multi-instance launching, and Bot binding |
|
||||
| Routing Config | Default routing, conditional rules, fallback, and request rewrites |
|
||||
| Fusion Models | Combine a base model with vision, search, or MCP tools into a new selectable model |
|
||||
| API Keys | Client access keys, expiration, and local limits |
|
||||
| Logs & Observability | Request logs, Agent execution traces, tool calls, and tool results |
|
||||
| Server | Host, port, proxy mode, system proxy, network capture, and CA certificate |
|
||||
| Extension Mechanism | Wrapper plugins, core gateway plugins, custom extension creation, and debugging |
|
||||
|
||||
## Settings Pages
|
||||
|
||||
| Page | Covers |
|
||||
| --- | --- |
|
||||
| ToolHub | Collapse many MCP servers into one dynamic tool resolution entry point for agents |
|
||||
| Bots And IM Agent Relay | Bot forwarding, handoff mode, and platform pages |
|
||||
| Tray Configuration | Tray icon, balance progress, and tray window widgets |
|
||||
| Config Database Location | SQLite config database location maintained by the desktop app |
|
||||
| Tray Configuration | Tray icon, balance progress, and tray window widgets |
|
||||
|
||||
## Content Relationships
|
||||
|
||||
Overview Dashboard shows system status and usage. API Keys control client access to CCR. Server controls the local gateway listener and proxy features. Provider Config and One click import cover how upstream model services enter CCR. Routing determines where model requests go. Agent Config covers Claude Code, Codex, and ZCode launch, multi-instance usage, and model selection. Fusion covers vision, web search, and MCP tools. Extension Mechanism covers local plugin creation, installation, and debugging. Bots cover IM platform relay. Tray Configuration covers the menu bar icon and tray window.
|
||||
Overview Dashboard shows system status and usage. Provider Config and One click import cover how upstream model services enter CCR. Agent Config covers Claude Code, Codex, and ZCode launch, multi-instance usage, and model selection. Routing determines where model requests go. Fusion covers vision, web search, and MCP tools. API Keys control client access to CCR. Logs & Observability cover request logs and agent execution traces. Server controls the local gateway listener and proxy features. Extension Mechanism covers local plugin creation, installation, and debugging. ToolHub, Bots, Config Database Location, and Tray Configuration match the corresponding settings pages in the settings dialog.
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ Every Agent Config has its own `id` and name. When CCR opens an agent, it finds
|
|||
| --- | --- |
|
||||
| Separate config files | With **Only opened from CCR**, Claude Code and Codex write CCR-managed config files in directories separated by config `id` |
|
||||
| Separate launchers | Claude Code uses a separate launch wrapper; Codex and ZCode use separate middleware launchers; filenames are also separated by config `id` or name |
|
||||
| Separate app data directories | When opening App mode, Claude App, Codex App, and ZCode App use user-data directories separated by config `id` |
|
||||
| Separate app data directories | When opening App mode, Claude App, ChatGPT (the renamed Codex desktop app), and ZCode App use user-data directories separated by config `id` |
|
||||
| Runtime state | CCR tracks running app instances by entry mode and config `id`; reopening the same config activates the existing window, while a different config can open a separate instance |
|
||||
|
||||
This lets you create multiple configs for the same agent, such as "Claude Code - Work Project", "Claude Code - Test Model", or "Codex - Fusion Vision". They can use different models, scopes, and Bots, then open as separate agent instances.
|
||||
|
|
@ -74,10 +74,12 @@ Claude App and Claude Code CLI use different model-list adapters:
|
|||
| Codex model | Default Codex model. It can be a provider model or Fusion model; if left empty, CCR uses the first available default model. |
|
||||
| Show all sessions | Lets Codex show all sessions. ZCode does not expose this option. |
|
||||
| Config file | Defaults to `~/.codex/config.toml`. Only opened from CCR writes into CCR-managed isolated config directories. |
|
||||
| Environment variables | Injected into Codex CLI or Codex App. Claude Code-specific model discovery variables are not passed to Codex. |
|
||||
| Bot | Applies only to the Codex App entry. |
|
||||
| Environment variables | Injected into Codex CLI or ChatGPT. Claude Code-specific model discovery variables are not passed to Codex. |
|
||||
| Bot | Applies only to the ChatGPT app entry. |
|
||||
|
||||
After saving, use the terminal button on the config card to copy the Codex CLI command, for example `ccr "Codex - Work"`. Use the play button to open Codex App. CCR generates `config.toml`, a model catalog file, and a middleware launcher so Codex CLI and Codex App use the same CCR model and provider information.
|
||||
After saving, use the terminal button on the config card to copy the Codex CLI command, for example `ccr "Codex - Work"`. Use the play button to open ChatGPT. Following the CodexL launch model, CCR starts the Electron executable inside the ChatGPT app bundle directly, gives it an isolated user-data directory, and points `CODEX_CLI_PATH` at the CCR middleware. The middleware forwards app-server traffic to ChatGPT's bundled Codex CLI and only adapts the account display: an existing valid ChatGPT token is shown as the real ChatGPT account, while a profile without credentials uses a tokenless ChatGPT-shaped workspace identity so the desktop renderer keeps model selection available without storing a real user login. To make the native app-server select its official API marketplace, CCR creates the exact `ccr-local-profile` bootstrap only during process startup and removes it after the first native response; it is also cleaned after startup or abnormal exit and is never retained as login state. Every other authentication file is preserved. Older `Codex.app` installations remain supported.
|
||||
|
||||
Model and public plugin listings are not synthesized by the middleware. The native Codex app-server reads the generated `model_catalog_json` and handles `model/list` plus public `plugin/list` requests unchanged. This lets Codex refresh the official public [`openai/plugins`](https://github.com/openai/plugins) Git marketplace over the network. In a virtual workspace, only account-private marketplace requests are answered with an explicit empty result because the native service requires real ChatGPT authentication for those sections; they are never replaced with local plugins. Any downloaded Git checkout is owned only by Codex as its normal last-known-good data, not used by CCR as a replacement catalog.
|
||||
|
||||
### ZCode
|
||||
|
||||
|
|
@ -112,7 +114,7 @@ When opening Claude App from the desktop app, CCR also prepares a separate user-
|
|||
|
||||
Codex config writes `config.toml` and a model catalog file. With **Only opened from CCR**, CCR stores those files in a directory separated by config `id`.
|
||||
|
||||
Codex supports CLI and App. CLI opens through the launcher for the selected config; App uses a separate user-data directory and passes the selected model and provider into Codex App.
|
||||
Codex supports CLI and App. CLI opens through the launcher for the selected config; App launches ChatGPT, uses a separate user-data directory, and passes the selected model and provider into the app.
|
||||
|
||||
### ZCode
|
||||
|
||||
|
|
|
|||
|
|
@ -78,6 +78,22 @@ Choose a provider below to get started. CCR shows what will be added before savi
|
|||
<span class="provider-import-icon-shell"><img src="../../../provider-icons/teamorouter.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">TeamoRouter</span><span class="provider-import-meta">Anthropic / Chat / Responses</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-code0" href="ccr://provider?name=code0.ai&base_url=https%3A%2F%2Fconsole.code0.ai&protocol=anthropic_messages&source=https%3A%2F%2Fcode0.ai%2Fagent%2Fregister%2F9n9jOsSnYQoemIVL%3Futm_source%3Dclaudecoderouter%26utm_medium%3Dpartner%26utm_campaign%3Dclaudecoderouter_2026%26utm_content%3Ddefault" aria-label="Import code0.ai provider">
|
||||
<span class="provider-import-icon-shell"><img src="../../../provider-icons/code0.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">code0.ai</span><span class="provider-import-meta">Anthropic / Chat / Responses</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-claudeapi" href="ccr://provider?name=claudeapi&base_url=https%3A%2F%2Fgw.claudeapi.com&protocol=anthropic_messages&source=https%3A%2F%2Fconsole.claudeapi.com%2Fagent%2Fregister%2FLbmB7Y9kPloyzhwF%3Futm_source%3Dclaudecoderouter%26utm_medium%3Dpartner%26utm_campaign%3Dclaudecoderouter_2026%26utm_content%3Ddefault" aria-label="Import claudeapi provider">
|
||||
<span class="provider-import-icon-shell"><img src="../../../provider-icons/claudeapi.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">claudeapi</span><span class="provider-import-meta">Anthropic Messages</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-qiniu-ai" href="ccr://provider?name=%E4%B8%83%E7%89%9B%E4%BA%91+AI&base_url=https%3A%2F%2Fapi.qnaigc.com&protocol=openai_chat_completions&source=https%3A%2F%2Fs.qiniu.com%2FAVjMVf" aria-label="Import Qiniu Cloud AI provider">
|
||||
<span class="provider-import-icon-shell"><img src="../../../provider-icons/qiniu-ai.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">Qiniu Cloud AI</span><span class="provider-import-meta">Chat / Responses / Anthropic / Gemini Generate</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-fenno" href="ccr://provider?name=Fenno.ai&base_url=https%3A%2F%2Fapi.fenno.ai&protocol=openai_chat_completions&source=https%3A%2F%2Fapi.fenno.ai%2Fregister%3Fredirect%3D%2Fpurchase%3Ftab%3Dsubscription%2526group%3D16%26aff%3D9HHHAB5QLAES" aria-label="Import Fenno.ai provider">
|
||||
<span class="provider-import-icon-shell"><img src="../../../provider-icons/fenno.jpg" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">Fenno.ai</span><span class="provider-import-meta">Chat / Responses / Anthropic</span></span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Embeddable Button Component
|
||||
|
|
|
|||
|
|
@ -162,7 +162,7 @@ Network errors move to the next attempt. Status-code fallback depends on the mod
|
|||
| Retry | `408`, `409`, `429`, `5xx` |
|
||||
| Fallback targets | Any `4xx` or `5xx` |
|
||||
|
||||
For `429` rate-limit responses, CCR waits before the next attempt. It honors `Retry-After` when the upstream provides it; otherwise it uses exponential backoff starting at 1 second and capped at 30 seconds per attempt.
|
||||
Before moving to the next attempt, CCR waits for every fallback-triggering failure, including network errors. It honors a positive `Retry-After` header when the upstream provides one; otherwise it uses exponential backoff starting at 1 second and capped at 30 seconds per attempt.
|
||||
|
||||
**Fallback targets** also switches on `4xx` because model-not-found, auth, or provider-side rejection errors may only affect the current target. If the fallback model works, the request can still succeed.
|
||||
|
||||
|
|
|
|||
167
docs/src/content/docs/en/configuration/toolhub.md
Normal file
167
docs/src/content/docs/en/configuration/toolhub.md
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
---
|
||||
title: ToolHub
|
||||
pageTitle: ToolHub
|
||||
eyebrow: Detailed Configuration
|
||||
lead: Collapse many MCP servers into one compact entry point so agents lazy-load task-specific tools and save context.
|
||||
---
|
||||
|
||||
## When To Use It
|
||||
|
||||
As your MCP setup grows, exposing every tool directly to an agent makes the eager tool list large and easier to misuse. ToolHub exposes one `ccr-toolhub` MCP server with two meta tools:
|
||||
|
||||
- `tool_hub.resolve`: searches the available MCP tool catalog for the current task.
|
||||
- `tool_hub.invoke`: calls a real MCP tool that was selected for this task.
|
||||
|
||||
Use ToolHub for tools that are not needed often but are still useful occasionally. It lazy-loads them only when a task actually needs them. The main value is saving context: large low-frequency tool catalogs do not have to stay in the agent's eager tool list, which reduces context use and the chance of selecting the wrong tool. Simple local code, file, or conversation tasks usually do not need ToolHub.
|
||||
|
||||
## How It Works
|
||||
|
||||
1. Enable ToolHub in **Settings → ToolHub**.
|
||||
2. Select a configured model as the **Resolver model**. It reads the MCP tool catalog and chooses the tools needed for the task. Prefer `deepseek-v4-flash`, or another stable lightweight model in a similar flash-price tier.
|
||||
3. Add or import backend MCP servers. ToolHub supports `stdio`, `streamable-http`, and `sse`.
|
||||
4. Open Claude Code or Codex from CCR. CCR writes the `ccr-toolhub` MCP server into that agent config.
|
||||
5. When the agent receives a request about external services, installed MCP capabilities, or business APIs, it calls `tool_hub.resolve` first, then uses `tool_hub.invoke` to run the selected tools.
|
||||
|
||||
ToolHub combines MCP servers configured on the ToolHub page with compatible global Agent MCP servers from older configs, and excludes `ccr-toolhub` itself to avoid recursive calls.
|
||||
|
||||
## Built-In Browser Automation
|
||||
|
||||
When ToolHub is enabled in CCR Desktop and **Built-in browser automation** is turned on, agents can use the desktop built-in browser for web tasks. You do not need to add a browser backend on the ToolHub page, and you do not need a separate API key; CCR connects to it through the local gateway authentication path.
|
||||
|
||||
To enable it:
|
||||
|
||||
1. Open **Settings → ToolHub** and turn on **Enable ToolHub**.
|
||||
2. Turn on **Built-in browser automation** on the same page. This switch is shown only after ToolHub is enabled.
|
||||
3. After saving settings, reopen Claude Code or Codex from CCR so the new agent instance loads the latest configuration.
|
||||
|
||||
> Already-running agent instances usually do not pick up this switch immediately. Restart the agent instance, or use the agent's own controls to restart ToolHub.
|
||||
|
||||
Built-in browser automation is useful for tasks that need real browser state, such as opening sites, reading pages, filling forms, clicking buttons, scrolling, or completing web flows like ordering, booking, lookup, and checkout when no domain-specific capability exists. After it is enabled, the agent can:
|
||||
|
||||
- Open or attach built-in browser tabs, then navigate to URLs or search queries.
|
||||
- Read page content and find buttons, links, form fields, and other page elements.
|
||||
- Click, type, select, press keys, and scroll page elements.
|
||||
- Wait for page loads, navigation, dialogs, or human handoff results before continuing.
|
||||
- Request human help for login, verification codes, CAPTCHA, human checks, or manual confirmation.
|
||||
|
||||
When a web flow needs login, verification codes, CAPTCHA, a human check, or manual confirmation, CCR shows the built-in browser window and displays the requested action in the top toolbar. After the user clicks **Done** or **Hide**, the agent receives the result and continues. Handoff waits support up to 10 minutes.
|
||||
|
||||
### Chrome Login Import Extension
|
||||
|
||||
Built-in browser automation can also import login state for selected domains from system Chrome into CCR's in-app browser. This lets the agent reuse sites where you are already signed in to Chrome. It requires the unpacked Chrome extension in this repository: `extension/chrome`.
|
||||
|
||||
Install it:
|
||||
|
||||
1. Open `chrome://extensions` in Chrome.
|
||||
2. Enable **Developer mode**.
|
||||
3. Click **Load unpacked**.
|
||||
4. Select the repository's `extension/chrome` directory.
|
||||
|
||||
Import flow:
|
||||
|
||||
1. When a task needs existing Chrome login state, the agent can request an import; the user can also click the key button in CCR's in-app browser toolbar.
|
||||
2. CCR creates a one-time import job and opens a confirmation page. If your default browser is not Chrome, copy the confirmation URL into Chrome with the extension installed.
|
||||
3. Review the requested domains on the confirmation page, then click **Confirm and Import**.
|
||||
4. The Chrome extension reads cookies and localStorage for those domains and submits them to CCR. After it completes, the agent can continue the task in the built-in browser.
|
||||
|
||||
The extension reads only the domains listed in the CCR import job. It does not enumerate every Chrome cookie. For localStorage, the extension temporarily opens non-active tabs for the selected origins, reads `localStorage`, and closes those tabs. If the confirmation page says the extension does not have site access, allow the extension to access the target domains in Chrome extension settings, reload the unpacked extension, and try again.
|
||||
|
||||
> Note: Built-in browser automation depends on CCR Desktop's built-in browser and is only available in the desktop app. CLI, server deployments, and pure web environments do not include this built-in capability; use an external browser automation MCP server instead.
|
||||
|
||||
## Options
|
||||
|
||||
| Option | Description |
|
||||
| --- | --- |
|
||||
| Enable ToolHub | Exposes `ccr-toolhub` to agents. If no backend MCP server is available, CCR does not generate a ToolHub MCP config. |
|
||||
| Built-in browser automation | Shown only after ToolHub is enabled. Lets agents use CCR Desktop's built-in browser for web tasks. |
|
||||
| Resolver model | Choose from configured provider models. Prefer `deepseek-v4-flash`, or another stable lightweight model in a similar flash-price tier with enough tool-description understanding. |
|
||||
| Max tools | Maximum tools returned by one resolve call. Range `1` to `20`, default `10`. |
|
||||
| Timeout ms | Base timeout for ToolHub resolving and invocation. Range `8000` to `300000`, default `60000`. If a backend MCP server needs a longer request timeout, CCR raises the effective invocation timeout to match the backend. |
|
||||
| MCP servers | Backend tool sources. Each server needs a unique name plus transport, command or URL, environment variables, headers, and timeouts. |
|
||||
| Import JSON | Imports common MCP JSON shapes. Supports a root object, array, `mcpServers`, or `mcp_servers`. |
|
||||
|
||||
## Add MCP Servers
|
||||
|
||||
### stdio
|
||||
|
||||
Use `stdio` for local command-line MCP servers. Configure:
|
||||
|
||||
- **Command**: launch command, such as `npx`, `node`, or `python`.
|
||||
- **Arguments**: command arguments.
|
||||
- **Working directory**: optional working directory.
|
||||
- **Stdio message mode**: keep `content-length` by default; use `newline-json` for line-delimited JSON servers.
|
||||
- **Environment variables**: variables needed only by this MCP server.
|
||||
|
||||
### streamable-http / sse
|
||||
|
||||
Remote MCP servers need a URL. Authentication can use:
|
||||
|
||||
- **API key**: stored directly in the config.
|
||||
- **API key env**: read from an environment variable.
|
||||
- **Headers**: custom request headers.
|
||||
|
||||
If a remote server starts slowly or has long-running calls, adjust that server's **Startup timeout** or **Request timeout**.
|
||||
|
||||
## JSON Example
|
||||
|
||||
The desktop app's SQLite config is the effective source, so prefer editing through the UI. The fields below are useful for backups, migration, or troubleshooting:
|
||||
|
||||
```json
|
||||
{
|
||||
"toolHub": {
|
||||
"enabled": true,
|
||||
"browserAutomation": true,
|
||||
"llm": {
|
||||
"apiKey": "sk-...",
|
||||
"baseUrl": "https://api.openai.com/v1",
|
||||
"model": "gpt-5-mini"
|
||||
},
|
||||
"maxTools": 10,
|
||||
"requestTimeoutMs": 60000,
|
||||
"mcpServers": [
|
||||
{
|
||||
"name": "filesystem",
|
||||
"transport": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
||||
"env": {},
|
||||
"stdioMessageMode": "content-length",
|
||||
"requestTimeoutMs": 30000,
|
||||
"startupTimeoutMs": 600000
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The import dialog also accepts common MCP JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ToolHub vs Fusion MCP
|
||||
|
||||
| Capability | ToolHub | Fusion Custom MCP Tool |
|
||||
| --- | --- | --- |
|
||||
| Entry point | Agent-side `ccr-toolhub` MCP server | Capability inside one Fusion model |
|
||||
| Tool selection | Dynamically resolves a tool bundle for each task | Fixed tools selected in the model config |
|
||||
| Best for | Many MCP servers, changing tool catalogs, agent-led capability discovery | Adding a known tool set to one model |
|
||||
| Visibility | Claude Code or Codex configs opened through CCR | Routes or agents that select that Fusion model |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Agent cannot see ToolHub: make sure ToolHub is enabled and at least one backend MCP server is configured or **Built-in browser automation** is turned on, then reopen Claude Code or Codex from CCR.
|
||||
- Missing resolver model or API key: select a configured resolver model and confirm the provider credential works.
|
||||
- The agent cannot use built-in browser automation: make sure you are using CCR Desktop, turned on **Built-in browser automation** in **Settings → ToolHub**, and reopened Claude Code or Codex from CCR. CLI, server deployments, and pure web environments do not include this built-in capability.
|
||||
- Chrome login import confirmation keeps waiting for the extension: make sure the unpacked `extension/chrome` extension is loaded in Chrome and has site access for the target domains. If your default browser is not Chrome, copy the confirmation URL into Chrome manually.
|
||||
- No tools are resolved: confirm the MCP server can list tools, improve tool names and descriptions, or increase **Max tools**.
|
||||
- Calls time out: check ToolHub **Timeout ms** and the backend server request/startup timeouts.
|
||||
- Import fails: validate JSON, avoid duplicate server names, make sure `stdio` entries have a command and remote entries have a URL.
|
||||
|
|
@ -2,29 +2,37 @@
|
|||
title: Claude Code Router 详细配置
|
||||
pageTitle: 详细配置
|
||||
eyebrow: 详细配置
|
||||
lead: 深入配置概览仪表盘、API 密钥、服务、供应商、路由、Agent配置、Fusion、Bot、托盘和配置数据库位置。这里是按功能查字段和扩展能力的地方。
|
||||
lead: 按应用中的实际顺序,将主页页面和设置页分开说明:主页覆盖概览、供应商、Agent配置、路由、Fusion、API 密钥、日志&观测、服务和扩展;设置页覆盖 ToolHub、Bot、数据和托盘。
|
||||
---
|
||||
|
||||
## 页面结构
|
||||
|
||||
详细配置文档已经拆成独立页面。左侧目录中的每一项都会进入一个页面;当前页面内的标题由右侧大纲负责。
|
||||
详细配置文档已经拆成独立页面。左侧目录中的每一项都会进入一个页面;当前页面内的标题由右侧大纲负责。主页页面跟随应用左侧主导航顺序;设置页单独分组,并按设置弹窗顺序排列。
|
||||
|
||||
## 主页页面
|
||||
|
||||
| 页面 | 内容 |
|
||||
| --- | --- |
|
||||
| 概览仪表盘 | 系统状态、账户余额、用量组件、布局编辑和分享卡片 |
|
||||
| API 密钥 | 客户端访问 Key、过期时间和本地限额 |
|
||||
| 服务配置 | Host、Port、代理模式、系统代理、网络捕获和 CA 证书 |
|
||||
| 供应商配置 | 上游服务、协议、基础 URL、模型列表和凭据 |
|
||||
| 一键导入供应商 | Provider deeplink 协议、Manifest 导入、一键导入按钮和安全边界 |
|
||||
| 路由配置 | 条件规则、fallback 和请求改写 |
|
||||
| 日志&观测 | 请求日志、Agent 执行追踪、工具调用和工具结果 |
|
||||
| Fusion 组合模型 | 把基础模型与视觉、搜索、MCP 工具组合成新的可选模型 |
|
||||
| Agent配置 | Agent 启动方式、模型、作用范围、多开和 Bot 绑定 |
|
||||
| 路由配置 | 条件规则、fallback 和请求改写 |
|
||||
| Fusion 组合模型 | 把基础模型与视觉、搜索、MCP 工具组合成新的可选模型 |
|
||||
| API 密钥 | 客户端访问 Key、过期时间和本地限额 |
|
||||
| 日志&观测 | 请求日志、Agent 执行追踪、工具调用和工具结果 |
|
||||
| 服务配置 | Host、Port、代理模式、系统代理、网络捕获和 CA 证书 |
|
||||
| 扩展机制 | Wrapper plugin、Core gateway plugin、自定义扩展创建和调试 |
|
||||
|
||||
## 设置页
|
||||
|
||||
| 页面 | 内容 |
|
||||
| --- | --- |
|
||||
| ToolHub | 将多个 MCP server 收束成一个 Agent 可用的动态工具检索入口 |
|
||||
| Bot 与 IM 接力 Agent | Bot 转发、接力模式和平台页面 |
|
||||
| 托盘配置 | 托盘图标、余额进度条和托盘窗口组件 |
|
||||
| 配置数据库位置 | 桌面 App 维护的 SQLite 配置数据库位置 |
|
||||
| 托盘配置 | 托盘图标、余额进度条和托盘窗口组件 |
|
||||
|
||||
## 内容关系
|
||||
|
||||
概览仪表盘用于查看系统状态和用量;API 密钥控制客户端访问 CCR;服务配置控制本地网关监听和代理能力;供应商配置和一键导入供应商页面覆盖上游模型服务如何进入 CCR;路由决定模型请求的上游去向;Agent配置页面覆盖 Claude Code、Codex 和 ZCode 的启动、多开与模型选择;Fusion 页面覆盖图像、搜索和 MCP 工具;扩展机制页面覆盖本地插件的创建、安装和调试;Bot 页面覆盖 IM 平台接力;托盘配置覆盖菜单栏图标和托盘窗口。
|
||||
概览仪表盘用于查看系统状态和用量;供应商配置和一键导入供应商页面覆盖上游模型服务如何进入 CCR;Agent配置页面覆盖 Claude Code、Codex 和 ZCode 的启动、多开与模型选择;路由决定模型请求的上游去向;Fusion 页面覆盖图像、搜索和 MCP 工具;API 密钥控制客户端访问 CCR;日志&观测覆盖请求日志和 Agent 执行链路;服务配置控制本地网关监听和代理能力;扩展机制覆盖本地插件的创建、安装和调试。ToolHub、Bot、配置数据库位置和托盘配置对应设置弹窗中的同名配置页。
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ lead: 为 Claude Code、Codex、ZCode 创建可复用的启动配置,并通过
|
|||
| --- | --- |
|
||||
| 独立配置文件 | 选择“仅从 CCR 打开时生效”时,Claude Code 和 Codex 会写入 CCR 管理的独立配置目录,路径按配置 `id` 区分 |
|
||||
| 独立启动器 | Claude Code 使用独立启动包装器,Codex 和 ZCode 使用独立中间层启动器,文件名同样按配置 `id` 或名称区分 |
|
||||
| 独立 App 数据目录 | 从 App 打开时,Claude App、Codex App、ZCode App 都会使用按配置 `id` 区分的用户数据目录 |
|
||||
| 独立 App 数据目录 | 从 App 打开时,Claude App、ChatGPT(Codex 桌面端的新名称)、ZCode App 都会使用按配置 `id` 区分的用户数据目录 |
|
||||
| 运行状态 | CCR 按打开入口和配置 `id` 记录运行中的 App 实例;同一个配置再次打开会激活已有窗口,不同配置可以打开不同实例 |
|
||||
|
||||
这意味着你可以为同一个 Agent 建多个配置,例如“Claude Code - 工作项目”“Claude Code - 测试模型”“Codex - Fusion 图像能力”。它们可以选择不同模型、不同作用范围和不同 Bot,打开后就是不同的 Agent 实例。
|
||||
|
|
@ -74,10 +74,12 @@ Claude App 和 Claude Code CLI 的模型列表适配方式不同:
|
|||
| Codex model | 写入 Codex 默认模型。可以选择普通供应商模型或 Fusion 模型;留空时 CCR 使用可用模型中的默认值。 |
|
||||
| Show all sessions | 让 Codex 显示所有会话。ZCode 不提供该项。 |
|
||||
| 配置文件 | 默认是 `~/.codex/config.toml`。仅从 CCR 打开时生效会写入 CCR 管理的独立配置目录。 |
|
||||
| 环境变量 | 注入 Codex CLI 或 Codex App。Claude Code 专用的模型发现变量不会传给 Codex。 |
|
||||
| Bot | 只在 Codex App 入口生效。 |
|
||||
| 环境变量 | 注入 Codex CLI 或 ChatGPT。Claude Code 专用的模型发现变量不会传给 Codex。 |
|
||||
| Bot | 只在 ChatGPT App 入口生效。 |
|
||||
|
||||
保存后,Codex CLI 使用配置卡片里的终端图标复制命令,例如 `ccr "Codex - Work"`。Codex App 使用播放图标打开。CCR 会生成 `config.toml`、模型目录文件和中间层启动器,让 Codex CLI 与 Codex App 都使用同一套 CCR 模型和供应商信息。
|
||||
保存后,Codex CLI 使用配置卡片里的终端图标复制命令,例如 `ccr "Codex - Work"`。ChatGPT 使用播放图标打开。CCR 按照 CodexL 的启动方式,直接运行 ChatGPT App bundle 内的 Electron 可执行文件,为它设置隔离的用户数据目录,并把 `CODEX_CLI_PATH` 指向 CCR 中间层。中间层把 app-server 流量转发给 ChatGPT 内置的 Codex CLI,只适配账号展示:隔离目录已有有效 ChatGPT token 时显示真实账号;没有凭据时使用无 token、ChatGPT 形态的虚拟工作区身份,让桌面端在不保存真实用户登录的情况下仍可使用模型选择。为让原生 app-server 选择官方 API marketplace,CCR 只在进程启动阶段创建精确的 `ccr-local-profile` 引导标记,收到第一条原生响应后立即删除;正常启动后或异常退出时也会清理,不会把它保留成登录状态。其他认证文件全部保留。旧版 `Codex.app` 仍然兼容。
|
||||
|
||||
模型和公共插件列表不再由中间层合成。原生 Codex app-server 读取生成的 `model_catalog_json`,并原样处理 `model/list` 与公共 `plugin/list` 请求,因此 Codex 可以自行联网刷新官方公开 [`openai/plugins`](https://github.com/openai/plugins) Git marketplace。虚拟 workspace 中,只有必须使用真实 ChatGPT 鉴权的账号私有 marketplace 请求会得到明确空结果,绝不会用本地插件替代。下载后的 Git checkout 只作为 Codex 自己的常规 last-known-good 数据,CCR 不会拿它替代远端目录。
|
||||
|
||||
### ZCode
|
||||
|
||||
|
|
@ -112,7 +114,7 @@ Claude Code CLI 配置会写入设置文件。选择“仅从 CCR 打开时生
|
|||
|
||||
Codex 配置会写入 `config.toml`,并生成模型目录文件。选择“仅从 CCR 打开时生效”时,CCR 会把这些文件放在按配置 `id` 区分的目录中。
|
||||
|
||||
Codex 支持 CLI 和 App。CLI 会通过对应配置的启动器打开;App 会使用独立用户数据目录,并把当前配置中的模型和供应商信息带入 Codex App。
|
||||
Codex 支持 CLI 和 App。CLI 会通过对应配置的启动器打开;App 会启动 ChatGPT、使用独立用户数据目录,并把当前配置中的模型和供应商信息带入 App。
|
||||
|
||||
### ZCode
|
||||
|
||||
|
|
|
|||
|
|
@ -78,6 +78,22 @@ lead: 快速添加常见模型供应商,确认无误后即可保存,减少
|
|||
<span class="provider-import-icon-shell"><img src="../../provider-icons/teamorouter.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">TeamoRouter</span><span class="provider-import-meta">Anthropic / Chat / Responses</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-code0" href="ccr://provider?name=code0.ai&base_url=https%3A%2F%2Fconsole.code0.ai&protocol=anthropic_messages&source=https%3A%2F%2Fcode0.ai%2Fagent%2Fregister%2F9n9jOsSnYQoemIVL%3Futm_source%3Dclaudecoderouter%26utm_medium%3Dpartner%26utm_campaign%3Dclaudecoderouter_2026%26utm_content%3Ddefault" aria-label="导入 code0.ai 供应商">
|
||||
<span class="provider-import-icon-shell"><img src="../../provider-icons/code0.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">code0.ai</span><span class="provider-import-meta">Anthropic / Chat / Responses</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-claudeapi" href="ccr://provider?name=claudeapi&base_url=https%3A%2F%2Fgw.claudeapi.com&protocol=anthropic_messages&source=https%3A%2F%2Fconsole.claudeapi.com%2Fagent%2Fregister%2FLbmB7Y9kPloyzhwF%3Futm_source%3Dclaudecoderouter%26utm_medium%3Dpartner%26utm_campaign%3Dclaudecoderouter_2026%26utm_content%3Ddefault" aria-label="导入 claudeapi 供应商">
|
||||
<span class="provider-import-icon-shell"><img src="../../provider-icons/claudeapi.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">claudeapi</span><span class="provider-import-meta">Anthropic Messages</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-qiniu-ai" href="ccr://provider?name=%E4%B8%83%E7%89%9B%E4%BA%91+AI&base_url=https%3A%2F%2Fapi.qnaigc.com&protocol=openai_chat_completions&source=https%3A%2F%2Fs.qiniu.com%2FAVjMVf" aria-label="导入七牛云 AI 供应商">
|
||||
<span class="provider-import-icon-shell"><img src="../../provider-icons/qiniu-ai.png" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">七牛云 AI</span><span class="provider-import-meta">Chat / Responses / Anthropic / Gemini Generate</span></span>
|
||||
</a>
|
||||
<a class="provider-import-button provider-fenno" href="ccr://provider?name=Fenno.ai&base_url=https%3A%2F%2Fapi.fenno.ai&protocol=openai_chat_completions&source=https%3A%2F%2Fapi.fenno.ai%2Fregister%3Fredirect%3D%2Fpurchase%3Ftab%3Dsubscription%2526group%3D16%26aff%3D9HHHAB5QLAES" aria-label="导入 Fenno.ai 供应商">
|
||||
<span class="provider-import-icon-shell"><img src="../../provider-icons/fenno.jpg" alt="" loading="lazy" /></span>
|
||||
<span class="provider-import-copy"><span class="provider-import-name">Fenno.ai</span><span class="provider-import-meta">Chat / Responses / Anthropic</span></span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## 嵌入式按钮组件
|
||||
|
|
|
|||
|
|
@ -162,7 +162,7 @@ Fallback 处理请求失败后的降级。第一次选模型由路由完成;
|
|||
| 继续重试 | `408`、`409`、`429`、`5xx` |
|
||||
| 失败降级目标 | 任意 `4xx` 或 `5xx` |
|
||||
|
||||
对于 `429` 限流响应,CCR 会在下一次尝试前等待。上游提供 `Retry-After` 时会优先遵守;否则使用从 1 秒开始、单次最多 30 秒的指数退避。
|
||||
进入下一次尝试前,CCR 会对每个触发 Fallback 的失败进行等待,包括网络错误。上游提供正数 `Retry-After` 时会优先遵守;否则使用从 1 秒开始、单次最多 30 秒的指数退避。
|
||||
|
||||
**失败降级目标** 对 `4xx` 也会切换,是因为模型不存在、鉴权或供应商侧拒绝等错误可能只影响当前目标。切换后如果备用模型可用,请求仍然可以成功。
|
||||
|
||||
|
|
|
|||
167
docs/src/content/docs/zh/configuration/toolhub.md
Normal file
167
docs/src/content/docs/zh/configuration/toolhub.md
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
---
|
||||
title: ToolHub
|
||||
pageTitle: ToolHub
|
||||
eyebrow: 详细配置
|
||||
lead: 将多个 MCP server 收束成一个紧凑入口,让 Agent 按任务懒加载需要的工具,减少工具列表占用的上下文。
|
||||
---
|
||||
|
||||
## 适用场景
|
||||
|
||||
当你接入的 MCP server 越来越多时,直接把所有工具暴露给 Agent 会让工具列表变长,也更容易选错工具。ToolHub 会向 Agent 暴露一个 `ccr-toolhub` MCP server,里面只有两个元工具:
|
||||
|
||||
- `tool_hub.resolve`:根据用户任务和上下文检索可用 MCP 工具。
|
||||
- `tool_hub.invoke`:调用已经被本轮任务选中的真实 MCP 工具。
|
||||
|
||||
它适合把不常用但偶尔会用到的工具统一懒加载,在任务真正需要时才交给 Agent 使用。核心价值是节省上下文:避免把大量低频工具常驻在 Agent 的工具列表里,减少上下文占用和选错工具的概率。简单本地代码、文件或普通聊天任务通常不需要经过 ToolHub。
|
||||
|
||||
## 工作方式
|
||||
|
||||
1. 在 **设置 → ToolHub** 中启用 ToolHub。
|
||||
2. 选择一个已配置模型作为 **检索模型**。它负责阅读 MCP 工具目录并挑选本轮任务需要的工具;建议使用 `deepseek-v4-flash`,或同等 Flash 价位、响应稳定的轻量模型。
|
||||
3. 添加或导入后端 MCP server。ToolHub 支持 `stdio`、`streamable-http` 和 `sse`。
|
||||
4. 从 CCR 打开 Claude Code 或 Codex。CCR 会在对应 Agent 配置中写入 `ccr-toolhub`。
|
||||
5. Agent 遇到外部服务、已安装 MCP 能力或业务 API 相关请求时,先调用 `tool_hub.resolve`,再用 `tool_hub.invoke` 执行选中的工具。
|
||||
|
||||
ToolHub 会合并 **ToolHub 页面配置的 MCP servers** 和兼容旧配置中的全局 Agent MCP servers,并自动排除 `ccr-toolhub` 自身,避免递归调用。
|
||||
|
||||
## 内置浏览器自动化
|
||||
|
||||
在 CCR Desktop 中启用 ToolHub,并打开 **内置浏览器自动化** 开关后,Agent 可以使用桌面端内置浏览器完成网页操作。不需要在 ToolHub 页面手动添加浏览器后端,也不需要额外 API Key;CCR 会使用本地网关鉴权连接它。
|
||||
|
||||
启用步骤:
|
||||
|
||||
1. 打开 **设置 → ToolHub**,先开启 **启用 ToolHub**。
|
||||
2. 在同一页打开 **内置浏览器自动化** 开关。该开关只会在 ToolHub 已启用时显示。
|
||||
3. 保存设置后,从 CCR 重新打开 Claude Code 或 Codex,让新的 Agent 实例加载最新配置。
|
||||
|
||||
> 已经运行中的 Agent 实例通常不会立即拿到这个开关变化。要让现有会话生效,请重启该 Agent 实例,或使用 Agent 自身能力重启 ToolHub。
|
||||
|
||||
内置浏览器自动化适合让 Agent 处理需要真实浏览器状态的任务,例如打开网站、读取页面、填写表单、点击按钮、在页面中滚动,或在没有专用业务能力时完成下单、预约、查询、结账等网页流程。开启后 Agent 可以:
|
||||
|
||||
- 打开或附加内置浏览器标签页、导航 URL 或搜索词。
|
||||
- 读取页面内容,并找到按钮、链接、输入框等页面元素。
|
||||
- 点击、输入、选择、按键和滚动页面元素。
|
||||
- 等待页面加载、跳转、弹窗或人类接管结果,再继续后续步骤。
|
||||
- 在登录、验证码、CAPTCHA、人机验证或人工确认时请求用户接管。
|
||||
|
||||
当网页流程需要登录、验证码、CAPTCHA、人机验证或人工确认时,CCR 会显示内置浏览器窗口,并在顶部工具栏提示用户需要完成的步骤。用户点击 **Done** 或 **Hide** 后,Agent 会收到结果并继续执行。接管等待最长支持 10 分钟。
|
||||
|
||||
### Chrome 登录态导入扩展
|
||||
|
||||
内置浏览器自动化还支持把系统 Chrome 中指定域名的登录状态导入 CCR 内置浏览器。这样 Agent 处理网页任务时,可以复用你已经在 Chrome 中登录过的网站状态。该能力需要安装仓库里的 Chrome 解包扩展:`extension/chrome`。
|
||||
|
||||
安装方式:
|
||||
|
||||
1. 在 Chrome 打开 `chrome://extensions`。
|
||||
2. 开启 **Developer mode**。
|
||||
3. 点击 **Load unpacked**。
|
||||
4. 选择仓库中的 `extension/chrome` 目录。
|
||||
|
||||
导入流程:
|
||||
|
||||
1. 当任务需要复用 Chrome 登录状态时,Agent 会请求导入;用户也可以在 CCR 内置浏览器工具栏点击钥匙按钮主动发起。
|
||||
2. CCR 创建一次性导入任务,并打开确认页。如果默认浏览器不是 Chrome,请把确认页 URL 复制到已安装扩展的 Chrome 中打开。
|
||||
3. 用户在确认页检查要导入的域名,点击 **Confirm and Import**。
|
||||
4. Chrome 扩展读取这些域名的 cookies 和 localStorage,提交给 CCR;完成后 Agent 可以继续使用内置浏览器执行任务。
|
||||
|
||||
扩展只读取 CCR 导入任务列出的域名,不会枚举 Chrome 中的全部 cookies。读取 localStorage 时,扩展会临时打开对应 origin 的非激活标签页,读取后自动关闭。若确认页提示扩展没有站点访问权限,请在 Chrome 扩展设置中允许该扩展访问目标域名,然后重新加载解包扩展再重试。
|
||||
|
||||
> 注意:内置浏览器自动化依赖 CCR Desktop 的内置浏览器,只在桌面端可用。CLI、服务器部署或纯 Web 环境没有这项内置能力,请改用外部浏览器自动化 MCP server。
|
||||
|
||||
## 配置项
|
||||
|
||||
| 配置项 | 说明 |
|
||||
| --- | --- |
|
||||
| 启用 ToolHub | 开启后才会向 Agent 暴露 `ccr-toolhub`。如果没有可用后端 MCP server,CCR 不会生成 ToolHub MCP 配置。 |
|
||||
| 内置浏览器自动化 | 仅在启用 ToolHub 后显示。开启后让 Agent 可以使用 CCR Desktop 的内置浏览器完成网页操作。 |
|
||||
| 检索模型 | 从已配置供应商模型中选择。建议使用 `deepseek-v4-flash`,或同等 Flash 价位、响应稳定、工具理解能力足够的轻量模型。 |
|
||||
| 最大工具数 | 单次解析最多返回的工具数量,范围 `1` 到 `20`,默认 `10`。 |
|
||||
| 超时毫秒 | ToolHub 解析和调用的基础超时时间,范围 `8000` 到 `300000`,默认 `60000`。如果后端 MCP server 需要更长 request timeout,CCR 会按后端超时自动抬高实际调用超时。 |
|
||||
| MCP servers | 后端工具来源。每个 server 需要唯一名称,并配置 transport、命令或 URL、环境变量、headers 和超时。 |
|
||||
| Import JSON | 导入常见 MCP JSON。支持根对象、数组、`mcpServers` 或 `mcp_servers`。 |
|
||||
|
||||
## 添加 MCP Server
|
||||
|
||||
### stdio
|
||||
|
||||
`stdio` 适合本地命令行 MCP server。需要填写:
|
||||
|
||||
- **Command**:启动命令,例如 `npx`、`node`、`python`。
|
||||
- **Arguments**:命令参数。
|
||||
- **Working directory**:可选工作目录。
|
||||
- **Stdio message mode**:默认 `content-length`,如果 server 使用逐行 JSON,选择 `newline-json`。
|
||||
- **Environment variables**:只放这个 MCP server 需要的变量。
|
||||
|
||||
### streamable-http / sse
|
||||
|
||||
远程 MCP server 需要填写 URL。鉴权可以使用:
|
||||
|
||||
- **API key**:直接保存在配置中。
|
||||
- **API key env**:从环境变量读取。
|
||||
- **Headers**:添加自定义请求头。
|
||||
|
||||
如果远程服务启动慢或请求耗时长,可以单独调高该 server 的 **Startup timeout** 或 **Request timeout**。
|
||||
|
||||
## JSON 示例
|
||||
|
||||
桌面 App 的 SQLite 配置是当前生效来源,建议优先通过 UI 修改。下面字段适用于备份、迁移或排查时理解 ToolHub 配置结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"toolHub": {
|
||||
"enabled": true,
|
||||
"browserAutomation": true,
|
||||
"llm": {
|
||||
"apiKey": "sk-...",
|
||||
"baseUrl": "https://api.openai.com/v1",
|
||||
"model": "gpt-5-mini"
|
||||
},
|
||||
"maxTools": 10,
|
||||
"requestTimeoutMs": 60000,
|
||||
"mcpServers": [
|
||||
{
|
||||
"name": "filesystem",
|
||||
"transport": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
||||
"env": {},
|
||||
"stdioMessageMode": "content-length",
|
||||
"requestTimeoutMs": 30000,
|
||||
"startupTimeoutMs": 600000
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
导入 MCP JSON 时也可以使用常见格式:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 与 Fusion MCP 的区别
|
||||
|
||||
| 能力 | ToolHub | Fusion 自定义 MCP 工具 |
|
||||
| --- | --- | --- |
|
||||
| 使用入口 | Agent 侧的 `ccr-toolhub` MCP server | 某个 Fusion 模型内部能力 |
|
||||
| 工具选择 | 每个任务动态检索并返回工具包 | 模型配置中固定选择工具 |
|
||||
| 适合场景 | MCP server 很多、工具目录经常变化、希望 Agent 自主发现能力 | 给某个模型补一组明确工具 |
|
||||
| 可见范围 | 通过 CCR 打开的 Claude Code 或 Codex 配置 | 选择该 Fusion 模型的路由或 Agent |
|
||||
|
||||
## 排查
|
||||
|
||||
- Agent 看不到 ToolHub:确认已启用 ToolHub,并且至少配置了一个后端 MCP server 或开启了 **内置浏览器自动化**,然后从 CCR 重新打开 Claude Code 或 Codex。
|
||||
- 提示缺少检索模型或 API Key:在 **检索模型** 中选择已配置模型,并确认供应商凭据可用。
|
||||
- Agent 无法使用内置浏览器自动化:确认正在使用 CCR Desktop,并且已在 **设置 → ToolHub** 中开启 **内置浏览器自动化**,然后从 CCR 重新打开 Claude Code 或 Codex。CLI、服务器部署或纯 Web 环境没有这项内置能力。
|
||||
- Chrome 登录态导入确认页一直等待扩展:确认已在 Chrome 中加载 `extension/chrome` 解包扩展,并允许扩展访问要导入的目标域名。如果默认浏览器不是 Chrome,请手动把确认页 URL 复制到 Chrome。
|
||||
- 解析不到工具:检查 MCP server 是否能正常列出工具,工具名称和描述是否足够清楚,必要时提高 **最大工具数**。
|
||||
- 调用超时:分别检查 ToolHub 的 **超时毫秒** 和单个 MCP server 的 request/startup timeout。
|
||||
- 导入失败:检查 JSON 是否有效、server 名称是否重复、`stdio` 是否有 command,远程 transport 是否有 URL。
|
||||
|
|
@ -60,25 +60,33 @@ export const docsContent = {
|
|||
configuration: {
|
||||
sidebarGroups: [
|
||||
{
|
||||
label: "详细配置",
|
||||
label: "主页页面",
|
||||
icon: "wand",
|
||||
items: [
|
||||
"概览仪表盘",
|
||||
"供应商配置",
|
||||
"一键导入供应商",
|
||||
"路由配置",
|
||||
"日志&观测",
|
||||
"Fusion 组合模型",
|
||||
"Agent配置",
|
||||
"路由配置",
|
||||
"Fusion 组合模型",
|
||||
"API 密钥",
|
||||
"日志&观测",
|
||||
"服务配置",
|
||||
"托盘配置",
|
||||
"扩展机制",
|
||||
"Bot 与 IM 接力 Agent",
|
||||
"配置数据库位置",
|
||||
],
|
||||
active: "概览仪表盘",
|
||||
},
|
||||
{
|
||||
label: "设置页",
|
||||
icon: "book",
|
||||
items: [
|
||||
"ToolHub",
|
||||
"Bot 与 IM 接力 Agent",
|
||||
"配置数据库位置",
|
||||
"托盘配置",
|
||||
],
|
||||
active: "",
|
||||
},
|
||||
],
|
||||
expandableSidebarItems: ["Fusion 组合模型", "Bot 与 IM 接力 Agent"],
|
||||
sidebarChildren: {
|
||||
|
|
@ -105,6 +113,7 @@ export const docsContent = {
|
|||
内置图像能力: "/configuration/fusion-vision/",
|
||||
内置联网搜索: "/configuration/fusion-web-search/",
|
||||
"自定义 MCP 工具": "/configuration/fusion-mcp-tool/",
|
||||
ToolHub: "/configuration/toolhub/",
|
||||
Agent配置: "/configuration/profile/",
|
||||
"API 密钥": "/configuration/api-keys/",
|
||||
服务配置: "/configuration/server/",
|
||||
|
|
@ -208,25 +217,33 @@ export const docsContent = {
|
|||
configuration: {
|
||||
sidebarGroups: [
|
||||
{
|
||||
label: "Detailed Configuration",
|
||||
label: "Main Pages",
|
||||
icon: "wand",
|
||||
items: [
|
||||
"Overview Dashboard",
|
||||
"Provider Config",
|
||||
"One click import",
|
||||
"Routing Config",
|
||||
"Logs & Observability",
|
||||
"Fusion Models",
|
||||
"Agent Config",
|
||||
"Routing Config",
|
||||
"Fusion Models",
|
||||
"API Keys",
|
||||
"Logs & Observability",
|
||||
"Server",
|
||||
"Tray Configuration",
|
||||
"Extension Mechanism",
|
||||
"Bots And IM Agent Relay",
|
||||
"Config Database Location",
|
||||
],
|
||||
active: "Overview Dashboard",
|
||||
},
|
||||
{
|
||||
label: "Settings Pages",
|
||||
icon: "book",
|
||||
items: [
|
||||
"ToolHub",
|
||||
"Bots And IM Agent Relay",
|
||||
"Config Database Location",
|
||||
"Tray Configuration",
|
||||
],
|
||||
active: "",
|
||||
},
|
||||
],
|
||||
expandableSidebarItems: ["Fusion Models", "Bots And IM Agent Relay"],
|
||||
sidebarChildren: {
|
||||
|
|
@ -243,6 +260,7 @@ export const docsContent = {
|
|||
"Built-In Vision": "/en/configuration/fusion-vision/",
|
||||
"Built-In Web Search": "/en/configuration/fusion-web-search/",
|
||||
"Custom MCP Tool": "/en/configuration/fusion-mcp-tool/",
|
||||
ToolHub: "/en/configuration/toolhub/",
|
||||
"Agent Config": "/en/configuration/profiles/",
|
||||
"API Keys": "/en/configuration/api-keys/",
|
||||
Server: "/en/configuration/server/",
|
||||
|
|
|
|||
|
|
@ -291,6 +291,11 @@ const sidebarCloseLabel = locale === "zh" ? "关闭目录" : "Close navigation";
|
|||
<ul class="sidebar-children directory-children">
|
||||
{section.groups.map((group) => (
|
||||
<li class="directory-group">
|
||||
{(section.groups.length > 1 || group.label !== section.label) && (
|
||||
<div class="directory-group-label">
|
||||
<span>{group.label}</span>
|
||||
</div>
|
||||
)}
|
||||
<ul>
|
||||
{group.items.map((item) => {
|
||||
const isExpandable = item.children.length > 0;
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export function getStaticPaths() {
|
|||
"fusion-vision": "内置图像能力",
|
||||
"fusion-web-search": "内置联网搜索",
|
||||
"fusion-mcp-tool": "自定义 MCP 工具",
|
||||
toolhub: "ToolHub",
|
||||
extensions: "扩展机制",
|
||||
server: "服务配置",
|
||||
tray: "托盘配置",
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export function getStaticPaths() {
|
|||
"fusion-vision": "Built-In Vision",
|
||||
"fusion-web-search": "Built-In Web Search",
|
||||
"fusion-mcp-tool": "Custom MCP Tool",
|
||||
toolhub: "ToolHub",
|
||||
extensions: "Extension Mechanism",
|
||||
server: "Server",
|
||||
tray: "Tray Configuration",
|
||||
|
|
|
|||
|
|
@ -642,28 +642,26 @@ pre {
|
|||
}
|
||||
|
||||
.directory-group {
|
||||
margin: 2px 0 9px;
|
||||
margin: 8px 0 14px;
|
||||
}
|
||||
|
||||
.directory-group:last-child {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.directory-group-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 28px;
|
||||
padding: 7px 8px 3px 0;
|
||||
color: var(--sidebar-heading);
|
||||
font-size: 12px;
|
||||
font-weight: 720;
|
||||
line-height: 1.35;
|
||||
.directory-group + .directory-group {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.directory-group-label .group-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
.directory-group-label {
|
||||
display: block;
|
||||
min-height: 20px;
|
||||
padding: 2px 8px 5px 0;
|
||||
color: var(--sidebar-subtle);
|
||||
font-size: 11px;
|
||||
font-weight: 760;
|
||||
letter-spacing: 0.04em;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.sidebar-group h2 {
|
||||
|
|
@ -768,7 +766,7 @@ pre {
|
|||
}
|
||||
|
||||
.sidebar-directory .sidebar-children {
|
||||
padding-left: 24px;
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
.sidebar-children::before {
|
||||
|
|
@ -786,6 +784,14 @@ pre {
|
|||
left: 8px;
|
||||
}
|
||||
|
||||
.sidebar-directory .directory-children {
|
||||
padding-left: 13px;
|
||||
}
|
||||
|
||||
.sidebar-directory .directory-children::before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sidebar-details[open] > .sidebar-children {
|
||||
margin-bottom: 7px;
|
||||
}
|
||||
|
|
@ -1312,6 +1318,18 @@ h1 {
|
|||
--provider-brand-3: #f4f4f5;
|
||||
}
|
||||
|
||||
.doc-markdown a.provider-import-button.provider-code0 {
|
||||
--provider-brand: #101214;
|
||||
--provider-brand-2: #267dff;
|
||||
--provider-brand-3: #d8e8ff;
|
||||
}
|
||||
|
||||
.doc-markdown a.provider-import-button.provider-claudeapi {
|
||||
--provider-brand: #0d1b2a;
|
||||
--provider-brand-2: #2f8f83;
|
||||
--provider-brand-3: #d7fff8;
|
||||
}
|
||||
|
||||
.doc-markdown a.provider-import-button.provider-deepseek {
|
||||
--provider-brand: #173aa8;
|
||||
--provider-brand-2: #4e69ff;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
"asarUnpack": [
|
||||
"**/*.node"
|
||||
],
|
||||
"electronLanguages": ["en-US", "zh-CN", "zh-TW", "zh_CN", "zh_TW"],
|
||||
"npmRebuild": true,
|
||||
"publish": [
|
||||
{
|
||||
|
|
@ -15,6 +16,7 @@
|
|||
}
|
||||
],
|
||||
"directories": {
|
||||
"app": "packages/electron",
|
||||
"output": "release/${version}"
|
||||
},
|
||||
"afterPack": "build/verify-packaged-app.cjs",
|
||||
|
|
@ -27,7 +29,14 @@
|
|||
],
|
||||
"files": [
|
||||
"dist",
|
||||
"package.json"
|
||||
"package.json",
|
||||
"!node_modules/better-sqlite3/deps/**",
|
||||
"!node_modules/better-sqlite3/src/**",
|
||||
"!node_modules/better-sqlite3/binding.gyp",
|
||||
"!node_modules/better-sqlite3/README.md",
|
||||
"!node_modules/better-sqlite3/docs/**",
|
||||
"!node_modules/better-sqlite3/benchmark/**",
|
||||
"!node_modules/better-sqlite3/test/**"
|
||||
],
|
||||
"mac": {
|
||||
"icon": "build/icon.icns",
|
||||
|
|
@ -52,6 +61,7 @@
|
|||
"artifactName": "Claude-Code-Router_${version}.${ext}"
|
||||
},
|
||||
"linux": {
|
||||
"executableName": "claude-code-router",
|
||||
"target": ["AppImage"],
|
||||
"artifactName": "Claude-Code-Router_${version}.${ext}"
|
||||
},
|
||||
|
|
|
|||
23
extension/chrome/README.md
Normal file
23
extension/chrome/README.md
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# CCR Login Import Chrome Extension
|
||||
|
||||
This unpacked Chrome extension imports cookies and localStorage for explicitly selected domains into CCR's in-app browser.
|
||||
|
||||
## Development install
|
||||
|
||||
1. Open `chrome://extensions`.
|
||||
2. Enable **Developer mode**.
|
||||
3. Click **Load unpacked**.
|
||||
4. Select this `extension/chrome` directory.
|
||||
|
||||
After changing extension files, click **Reload** for this unpacked extension in `chrome://extensions`.
|
||||
The confirmation-page flow uses the site access declared in `manifest.json`; it does not request new host permissions from the page click.
|
||||
|
||||
## Flow
|
||||
|
||||
1. An agent calls CCR's Chrome login import browser tool, or the user clicks the key button in CCR's in-app browser.
|
||||
2. CCR opens a one-time confirmation page in the system browser.
|
||||
3. Review the requested domains and click **Confirm and Import**.
|
||||
|
||||
The extension reads only the domains listed in the CCR job. It does not enumerate all Chrome cookies.
|
||||
|
||||
For localStorage, the extension temporarily opens non-active tabs for the selected origins, reads `localStorage`, then closes those tabs.
|
||||
262
extension/chrome/background.js
Normal file
262
extension/chrome/background.js
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
|
||||
if (!message || message.type !== "ccr-login-import-confirm") {
|
||||
return false;
|
||||
}
|
||||
|
||||
runImport(message.importUrl)
|
||||
.then((result) => sendResponse({ ok: true, result }))
|
||||
.catch((error) => sendResponse({ error: formatError(error), ok: false }));
|
||||
return true;
|
||||
});
|
||||
|
||||
async function runImport(importUrl) {
|
||||
const normalizedImportUrl = normalizeImportUrl(importUrl);
|
||||
if (!normalizedImportUrl) {
|
||||
throw new Error("Invalid CCR import URL.");
|
||||
}
|
||||
|
||||
const job = await fetchImportJob(normalizedImportUrl);
|
||||
const domains = Array.isArray(job.domains) ? job.domains.map(normalizeDomain).filter(Boolean) : [];
|
||||
if (domains.length === 0) {
|
||||
throw new Error("CCR import job does not include any domains.");
|
||||
}
|
||||
|
||||
await ensureHostPermissions(domains);
|
||||
|
||||
const cookies = await readCookiesForDomains(domains);
|
||||
const localStorageEntries = await readLocalStorageForDomains(domains, cookies);
|
||||
if (cookies.length === 0 && localStorageEntries.length === 0) {
|
||||
throw new Error("No cookies or localStorage entries were found for the selected domains.");
|
||||
}
|
||||
|
||||
return await submitLoginState(normalizedImportUrl, cookies, localStorageEntries, domains);
|
||||
}
|
||||
|
||||
async function fetchImportJob(importUrl) {
|
||||
const response = await fetch(importUrl, {
|
||||
headers: {
|
||||
"x-ccr-login-import": "chrome-extension"
|
||||
}
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(body?.error?.message || `CCR import job request failed (${response.status}).`);
|
||||
}
|
||||
if (!body.job || body.job.status !== "pending") {
|
||||
throw new Error(`CCR import job is ${body.job?.status || "unavailable"}.`);
|
||||
}
|
||||
return body.job;
|
||||
}
|
||||
|
||||
async function submitLoginState(importUrl, cookies, localStorage, domains) {
|
||||
const response = await fetch(`${importUrl.replace(/\/+$/, "")}/cookies`, {
|
||||
body: JSON.stringify({
|
||||
cookies,
|
||||
domains,
|
||||
localStorage,
|
||||
source: {
|
||||
browser: "chrome",
|
||||
extension: chrome.runtime.getManifest().version
|
||||
}
|
||||
}),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-ccr-login-import": "chrome-extension"
|
||||
},
|
||||
method: "POST"
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(body?.error?.message || `CCR login import failed (${response.status}).`);
|
||||
}
|
||||
return body.result || {};
|
||||
}
|
||||
|
||||
async function readCookiesForDomains(domains) {
|
||||
const cookies = [];
|
||||
for (const domain of domains) {
|
||||
cookies.push(...await chrome.cookies.getAll({ domain }));
|
||||
}
|
||||
return dedupeCookies(cookies);
|
||||
}
|
||||
|
||||
async function readLocalStorageForDomains(domains, cookies) {
|
||||
const origins = localStorageOriginsForDomains(domains, cookies);
|
||||
const entries = [];
|
||||
for (const origin of origins) {
|
||||
const entry = await readLocalStorageForOrigin(origin).catch(() => undefined);
|
||||
if (entry && Object.keys(entry.items).length > 0) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
async function readLocalStorageForOrigin(origin) {
|
||||
const tab = await chrome.tabs.create({
|
||||
active: false,
|
||||
url: `${origin}/`
|
||||
});
|
||||
try {
|
||||
await waitForTabLoad(tab.id, 15000);
|
||||
const [frameResult] = await chrome.scripting.executeScript({
|
||||
func: () => {
|
||||
const items = {};
|
||||
for (let index = 0; index < window.localStorage.length; index += 1) {
|
||||
const key = window.localStorage.key(index);
|
||||
if (key !== null) {
|
||||
items[key] = window.localStorage.getItem(key) || "";
|
||||
}
|
||||
}
|
||||
return {
|
||||
items,
|
||||
origin: window.location.origin
|
||||
};
|
||||
},
|
||||
target: { tabId: tab.id },
|
||||
world: "MAIN"
|
||||
});
|
||||
const result = frameResult?.result;
|
||||
if (!result || !allowedLocalStorageOrigin(result.origin, origin)) {
|
||||
return undefined;
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
if (tab.id !== undefined) {
|
||||
await chrome.tabs.remove(tab.id).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function waitForTabLoad(tabId, timeoutMs) {
|
||||
return new Promise((resolve) => {
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
done = true;
|
||||
chrome.tabs.onUpdated.removeListener(listener);
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
};
|
||||
const listener = (updatedTabId, changeInfo) => {
|
||||
if (updatedTabId === tabId && changeInfo.status === "complete") {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const timeout = setTimeout(finish, timeoutMs);
|
||||
chrome.tabs.onUpdated.addListener(listener);
|
||||
});
|
||||
}
|
||||
|
||||
function dedupeCookies(cookies) {
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
for (const cookie of cookies) {
|
||||
const partitionKey = cookie.partitionKey ? JSON.stringify(cookie.partitionKey) : "";
|
||||
const key = `${cookie.storeId || ""}\n${cookie.domain}\n${cookie.path}\n${cookie.name}\n${partitionKey}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
result.push(cookie);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function localStorageOriginsForDomains(domains, cookies) {
|
||||
const origins = new Set();
|
||||
for (const domain of domains) {
|
||||
if (domain === "localhost" || isIpAddress(domain)) {
|
||||
origins.add(`http://${domain}`);
|
||||
origins.add(`https://${domain}`);
|
||||
} else {
|
||||
origins.add(`https://${domain}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const cookie of cookies) {
|
||||
const host = normalizeDomain(cookie.domain);
|
||||
if (!host || !cookie.hostOnly || !domains.some((domain) => host === domain || host.endsWith(`.${domain}`))) {
|
||||
continue;
|
||||
}
|
||||
origins.add(`${cookie.secure === false ? "http" : "https"}://${host}`);
|
||||
}
|
||||
|
||||
return [...origins];
|
||||
}
|
||||
|
||||
function originsForDomains(domains) {
|
||||
return [...new Set(domains.flatMap((domain) => {
|
||||
if (domain === "localhost" || isIpAddress(domain)) {
|
||||
return [
|
||||
`http://${domain}/*`,
|
||||
`https://${domain}/*`
|
||||
];
|
||||
}
|
||||
return [
|
||||
`http://${domain}/*`,
|
||||
`https://${domain}/*`,
|
||||
`http://*.${domain}/*`,
|
||||
`https://*.${domain}/*`
|
||||
];
|
||||
}))];
|
||||
}
|
||||
|
||||
async function ensureHostPermissions(domains) {
|
||||
const origins = originsForDomains(domains);
|
||||
const granted = await chrome.permissions.contains({ origins });
|
||||
if (granted) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
[
|
||||
`CCR Login Import does not have Chrome site access for ${domains.join(", ")}.`,
|
||||
"Reload the unpacked extension after updating it, then grant the extension site access for the requested domains in Chrome extensions settings."
|
||||
].join(" ")
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeImportUrl(value) {
|
||||
const raw = typeof value === "string" ? value.trim() : "";
|
||||
if (!raw) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (!["127.0.0.1", "localhost"].includes(url.hostname)) {
|
||||
return "";
|
||||
}
|
||||
if (!/^\/chrome-import\/jobs\/[^/]+\/?$/.test(url.pathname)) {
|
||||
return "";
|
||||
}
|
||||
url.pathname = url.pathname.replace(/\/+$/, "");
|
||||
return url.toString();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDomain(value) {
|
||||
return typeof value === "string"
|
||||
? value.trim().replace(/^\*\./, "").replace(/^\./, "").toLowerCase()
|
||||
: "";
|
||||
}
|
||||
|
||||
function allowedLocalStorageOrigin(actualOrigin, requestedOrigin) {
|
||||
try {
|
||||
const actual = new URL(actualOrigin);
|
||||
const requested = new URL(requestedOrigin);
|
||||
return actual.protocol === requested.protocol && actual.hostname === requested.hostname && actual.port === requested.port;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isIpAddress(value) {
|
||||
return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(value) || value.includes(":");
|
||||
}
|
||||
|
||||
function formatError(error) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
46
extension/chrome/confirm.js
Normal file
46
extension/chrome/confirm.js
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
const root = document.getElementById("ccr-chrome-login-import");
|
||||
const button = document.getElementById("ccr-confirm-import");
|
||||
const statusElement = document.getElementById("ccr-import-status");
|
||||
|
||||
if (root && button && statusElement) {
|
||||
const importUrl = root.getAttribute("data-import-url") || "";
|
||||
button.disabled = false;
|
||||
button.textContent = "Confirm and Import";
|
||||
setStatus("CCR Login Import extension is connected. Review the domains, then confirm.");
|
||||
|
||||
button.addEventListener("click", () => {
|
||||
void confirmImport(importUrl);
|
||||
});
|
||||
}
|
||||
|
||||
async function confirmImport(importUrl) {
|
||||
button.disabled = true;
|
||||
setStatus("Importing Chrome cookies and localStorage into CCR...");
|
||||
try {
|
||||
const response = await chrome.runtime.sendMessage({
|
||||
importUrl,
|
||||
type: "ccr-login-import-confirm"
|
||||
});
|
||||
if (!response?.ok) {
|
||||
throw new Error(response?.error || "Chrome login import failed.");
|
||||
}
|
||||
const result = response.result || {};
|
||||
setStatus(
|
||||
`Imported ${result.cookieImported || 0} cookies and ${result.localStorageImported || 0} localStorage items. Skipped ${result.skipped || 0}.`,
|
||||
"ok"
|
||||
);
|
||||
button.textContent = "Imported";
|
||||
} catch (error) {
|
||||
button.disabled = false;
|
||||
setStatus(formatError(error), "error");
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(message, kind = "") {
|
||||
statusElement.textContent = message;
|
||||
statusElement.className = `status ${kind}`.trim();
|
||||
}
|
||||
|
||||
function formatError(error) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
35
extension/chrome/manifest.json
Normal file
35
extension/chrome/manifest.json
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
{
|
||||
"manifest_version": 3,
|
||||
"name": "CCR Login Import",
|
||||
"description": "Import selected Chrome site login cookies into CCR's in-app browser.",
|
||||
"version": "0.1.0",
|
||||
"action": {
|
||||
"default_popup": "popup.html",
|
||||
"default_title": "CCR Login Import"
|
||||
},
|
||||
"background": {
|
||||
"service_worker": "background.js"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"js": [
|
||||
"confirm.js"
|
||||
],
|
||||
"matches": [
|
||||
"http://127.0.0.1/*",
|
||||
"http://localhost/*"
|
||||
]
|
||||
}
|
||||
],
|
||||
"permissions": [
|
||||
"cookies",
|
||||
"scripting",
|
||||
"storage"
|
||||
],
|
||||
"host_permissions": [
|
||||
"http://127.0.0.1/*",
|
||||
"http://localhost/*",
|
||||
"http://*/*",
|
||||
"https://*/*"
|
||||
]
|
||||
}
|
||||
110
extension/chrome/popup.html
Normal file
110
extension/chrome/popup.html
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>CCR Login Import</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-width: 360px;
|
||||
background: Canvas;
|
||||
color: CanvasText;
|
||||
}
|
||||
|
||||
main {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 15px;
|
||||
line-height: 1.25;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
label {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
textarea {
|
||||
background: color-mix(in srgb, CanvasText 4%, Canvas);
|
||||
border: 1px solid color-mix(in srgb, CanvasText 14%, transparent);
|
||||
border-radius: 8px;
|
||||
color: CanvasText;
|
||||
font: inherit;
|
||||
min-height: 76px;
|
||||
outline: none;
|
||||
padding: 8px;
|
||||
resize: vertical;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
textarea:focus {
|
||||
border-color: #2563eb;
|
||||
}
|
||||
|
||||
button {
|
||||
align-items: center;
|
||||
background: #0f766e;
|
||||
border: 1px solid #0f766e;
|
||||
border-radius: 8px;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
height: 34px;
|
||||
justify-content: center;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.58;
|
||||
}
|
||||
|
||||
.status {
|
||||
border-radius: 8px;
|
||||
color: color-mix(in srgb, CanvasText 74%, transparent);
|
||||
font-size: 12px;
|
||||
line-height: 1.35;
|
||||
min-height: 18px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.status.error {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.status.ok {
|
||||
color: #15803d;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>CCR Login Import</h1>
|
||||
<label>
|
||||
Import URL
|
||||
<textarea id="import-url" spellcheck="false" placeholder="Paste the URL copied from CCR"></textarea>
|
||||
</label>
|
||||
<button id="import-button" type="button">Import Selected Domains</button>
|
||||
<div id="status" class="status" role="status"></div>
|
||||
</main>
|
||||
<script src="popup.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
297
extension/chrome/popup.js
Normal file
297
extension/chrome/popup.js
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
const importUrlInput = document.getElementById("import-url");
|
||||
const importButton = document.getElementById("import-button");
|
||||
const statusElement = document.getElementById("status");
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
void restoreLastImportUrl();
|
||||
});
|
||||
|
||||
importButton.addEventListener("click", () => {
|
||||
void runImport();
|
||||
});
|
||||
|
||||
async function restoreLastImportUrl() {
|
||||
const stored = await chrome.storage.local.get(["lastImportUrl"]);
|
||||
if (typeof stored.lastImportUrl === "string") {
|
||||
importUrlInput.value = stored.lastImportUrl;
|
||||
}
|
||||
}
|
||||
|
||||
async function runImport() {
|
||||
const importUrl = normalizeImportUrl(importUrlInput.value);
|
||||
if (!importUrl) {
|
||||
setStatus("Paste the import URL copied from CCR.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
importButton.disabled = true;
|
||||
try {
|
||||
await chrome.storage.local.set({ lastImportUrl: importUrl });
|
||||
setStatus("Reading CCR import job...");
|
||||
const job = await fetchImportJob(importUrl);
|
||||
const domains = Array.isArray(job.domains) ? job.domains.map(normalizeDomain).filter(Boolean) : [];
|
||||
if (domains.length === 0) {
|
||||
throw new Error("CCR import job does not include any domains.");
|
||||
}
|
||||
|
||||
await ensureHostPermissions(domains);
|
||||
|
||||
setStatus(`Reading cookies for ${domains.join(", ")}...`);
|
||||
const cookies = await readCookiesForDomains(domains);
|
||||
setStatus(`Reading localStorage for ${domains.join(", ")}...`);
|
||||
const localStorageEntries = await readLocalStorageForDomains(domains, cookies);
|
||||
|
||||
if (cookies.length === 0 && localStorageEntries.length === 0) {
|
||||
throw new Error("No cookies or localStorage entries were found for the selected domains.");
|
||||
}
|
||||
|
||||
setStatus(`Sending ${cookies.length} cookies and ${localStorageItemCount(localStorageEntries)} localStorage items to CCR...`);
|
||||
const result = await submitCookies(importUrl, cookies, localStorageEntries, domains);
|
||||
setStatus(
|
||||
`Imported ${result.cookieImported ?? 0} cookies and ${result.localStorageImported ?? 0} localStorage items. Skipped ${result.skipped ?? 0}.`,
|
||||
"ok"
|
||||
);
|
||||
} catch (error) {
|
||||
setStatus(formatError(error), "error");
|
||||
} finally {
|
||||
importButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchImportJob(importUrl) {
|
||||
const response = await fetch(importUrl, {
|
||||
headers: {
|
||||
"x-ccr-login-import": "chrome-extension"
|
||||
}
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(body?.error?.message || `CCR import job request failed (${response.status}).`);
|
||||
}
|
||||
if (!body.job || body.job.status !== "pending") {
|
||||
throw new Error(`CCR import job is ${body.job?.status || "unavailable"}.`);
|
||||
}
|
||||
return body.job;
|
||||
}
|
||||
|
||||
async function submitCookies(importUrl, cookies, localStorage, domains) {
|
||||
const response = await fetch(`${importUrl.replace(/\/+$/, "")}/cookies`, {
|
||||
body: JSON.stringify({
|
||||
cookies,
|
||||
domains,
|
||||
localStorage,
|
||||
source: {
|
||||
browser: "chrome",
|
||||
extension: chrome.runtime.getManifest().version
|
||||
}
|
||||
}),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-ccr-login-import": "chrome-extension"
|
||||
},
|
||||
method: "POST"
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(body?.error?.message || `CCR cookie import failed (${response.status}).`);
|
||||
}
|
||||
return body.result || {};
|
||||
}
|
||||
|
||||
async function readCookiesForDomains(domains) {
|
||||
const cookies = [];
|
||||
for (const domain of domains) {
|
||||
cookies.push(...await chrome.cookies.getAll({ domain }));
|
||||
}
|
||||
return dedupeCookies(cookies);
|
||||
}
|
||||
|
||||
async function readLocalStorageForDomains(domains, cookies) {
|
||||
const origins = localStorageOriginsForDomains(domains, cookies);
|
||||
const entries = [];
|
||||
for (const origin of origins) {
|
||||
const entry = await readLocalStorageForOrigin(origin).catch(() => undefined);
|
||||
if (entry && Object.keys(entry.items).length > 0) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
async function readLocalStorageForOrigin(origin) {
|
||||
const tab = await chrome.tabs.create({
|
||||
active: false,
|
||||
url: `${origin}/`
|
||||
});
|
||||
try {
|
||||
await waitForTabLoad(tab.id, 15000);
|
||||
const [frameResult] = await chrome.scripting.executeScript({
|
||||
func: () => {
|
||||
const items = {};
|
||||
for (let index = 0; index < window.localStorage.length; index += 1) {
|
||||
const key = window.localStorage.key(index);
|
||||
if (key !== null) {
|
||||
items[key] = window.localStorage.getItem(key) || "";
|
||||
}
|
||||
}
|
||||
return {
|
||||
items,
|
||||
origin: window.location.origin
|
||||
};
|
||||
},
|
||||
target: { tabId: tab.id },
|
||||
world: "MAIN"
|
||||
});
|
||||
const result = frameResult?.result;
|
||||
if (!result || !allowedLocalStorageOrigin(result.origin, origin)) {
|
||||
return undefined;
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
if (tab.id !== undefined) {
|
||||
await chrome.tabs.remove(tab.id).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function waitForTabLoad(tabId, timeoutMs) {
|
||||
return new Promise((resolve) => {
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
done = true;
|
||||
chrome.tabs.onUpdated.removeListener(listener);
|
||||
window.clearTimeout(timeout);
|
||||
resolve();
|
||||
};
|
||||
const listener = (updatedTabId, changeInfo) => {
|
||||
if (updatedTabId === tabId && changeInfo.status === "complete") {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const timeout = window.setTimeout(finish, timeoutMs);
|
||||
chrome.tabs.onUpdated.addListener(listener);
|
||||
});
|
||||
}
|
||||
|
||||
function dedupeCookies(cookies) {
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
for (const cookie of cookies) {
|
||||
const partitionKey = cookie.partitionKey ? JSON.stringify(cookie.partitionKey) : "";
|
||||
const key = `${cookie.storeId || ""}\n${cookie.domain}\n${cookie.path}\n${cookie.name}\n${partitionKey}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
result.push(cookie);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function localStorageOriginsForDomains(domains, cookies) {
|
||||
const origins = new Set();
|
||||
for (const domain of domains) {
|
||||
if (domain === "localhost" || isIpAddress(domain)) {
|
||||
origins.add(`http://${domain}`);
|
||||
origins.add(`https://${domain}`);
|
||||
} else {
|
||||
origins.add(`https://${domain}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const cookie of cookies) {
|
||||
const host = normalizeDomain(cookie.domain);
|
||||
if (!host || !cookie.hostOnly || !domains.some((domain) => host === domain || host.endsWith(`.${domain}`))) {
|
||||
continue;
|
||||
}
|
||||
origins.add(`${cookie.secure === false ? "http" : "https"}://${host}`);
|
||||
}
|
||||
|
||||
return [...origins];
|
||||
}
|
||||
|
||||
function allowedLocalStorageOrigin(actualOrigin, requestedOrigin) {
|
||||
try {
|
||||
const actual = new URL(actualOrigin);
|
||||
const requested = new URL(requestedOrigin);
|
||||
return actual.protocol === requested.protocol && actual.hostname === requested.hostname && actual.port === requested.port;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function localStorageItemCount(entries) {
|
||||
return entries.reduce((count, entry) => count + Object.keys(entry.items || {}).length, 0);
|
||||
}
|
||||
|
||||
function originsForDomains(domains) {
|
||||
return [...new Set(domains.flatMap((domain) => {
|
||||
if (domain === "localhost" || isIpAddress(domain)) {
|
||||
return [
|
||||
`http://${domain}/*`,
|
||||
`https://${domain}/*`
|
||||
];
|
||||
}
|
||||
return [
|
||||
`http://${domain}/*`,
|
||||
`https://${domain}/*`,
|
||||
`http://*.${domain}/*`,
|
||||
`https://*.${domain}/*`
|
||||
];
|
||||
}))];
|
||||
}
|
||||
|
||||
async function ensureHostPermissions(domains) {
|
||||
const origins = originsForDomains(domains);
|
||||
const granted = await chrome.permissions.contains({ origins });
|
||||
if (granted) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
[
|
||||
`CCR Login Import does not have Chrome site access for ${domains.join(", ")}.`,
|
||||
"Reload the unpacked extension after updating it, then grant the extension site access for the requested domains in Chrome extensions settings."
|
||||
].join(" ")
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeImportUrl(value) {
|
||||
const raw = value.trim();
|
||||
if (!raw) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (!["127.0.0.1", "localhost"].includes(url.hostname)) {
|
||||
return "";
|
||||
}
|
||||
if (!/^\/chrome-import\/jobs\/[^/]+\/?$/.test(url.pathname)) {
|
||||
return "";
|
||||
}
|
||||
url.pathname = url.pathname.replace(/\/+$/, "");
|
||||
return url.toString();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeDomain(value) {
|
||||
return typeof value === "string"
|
||||
? value.trim().replace(/^\*\./, "").replace(/^\./, "").toLowerCase()
|
||||
: "";
|
||||
}
|
||||
|
||||
function isIpAddress(value) {
|
||||
return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(value) || value.includes(":");
|
||||
}
|
||||
|
||||
function setStatus(message, kind = "") {
|
||||
statusElement.textContent = message;
|
||||
statusElement.className = `status ${kind}`.trim();
|
||||
}
|
||||
|
||||
function formatError(error) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
1584
package-lock.json
generated
1584
package-lock.json
generated
File diff suppressed because it is too large
Load diff
34
package.json
34
package.json
|
|
@ -1,6 +1,7 @@
|
|||
{
|
||||
"name": "claude-code-router",
|
||||
"version": "3.0.7",
|
||||
"name": "claude-code-router-monorepo",
|
||||
"version": "3.0.11",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"description": "Local Claude Code Router gateway with CLI and web management UI.",
|
||||
"repository": {
|
||||
|
|
@ -18,15 +19,9 @@
|
|||
"gateway",
|
||||
"router"
|
||||
],
|
||||
"main": "dist/main/main.js",
|
||||
"bin": {
|
||||
"ccr": "dist/main/cli.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"README_zh.md"
|
||||
"main": "packages/electron/dist/main/main.js",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
|
|
@ -35,9 +30,13 @@
|
|||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "node build/dev.mjs",
|
||||
"build": "npm run build:assets && electron-builder",
|
||||
"dev": "npm run dev:cli",
|
||||
"dev:ui": "node build/dev.mjs ui",
|
||||
"dev:cli": "node build/dev.mjs cli",
|
||||
"dev:electron": "node build/dev.mjs electron",
|
||||
"build": "node build/build.mjs && electron-builder",
|
||||
"build:assets": "node build/build.mjs",
|
||||
"build:docker": "node build/docker-build.mjs",
|
||||
"build:app:mac": "npm run build:app:mac:local",
|
||||
"build:app:mac:local": "npm run build:assets && electron-builder --config build/electron-builder.local.cjs --mac --publish never",
|
||||
"build:app:mac:release": "node build/macos-release-preflight.mjs && npm run build:assets && electron-builder --mac --publish never",
|
||||
|
|
@ -45,24 +44,31 @@
|
|||
"prepack": "npm run build:assets",
|
||||
"prepublishOnly": "npm run typecheck",
|
||||
"preview": "npm run build:assets && electron .",
|
||||
"docker:build": "docker build -t claude-code-router:local .",
|
||||
"docker:run": "docker run --rm -p 3458:8080 -v ccr-data:/data claude-code-router:local",
|
||||
"test": "node build/test.mjs && node build/run-tests.mjs",
|
||||
"test:docker": "node tests/docker/docker-smoke.mjs",
|
||||
"test:e2e": "npm run build:assets && playwright test",
|
||||
"test:e2e:install": "playwright install chromium",
|
||||
"test:main": "node build/test.mjs main && node build/run-tests.mjs main",
|
||||
"test:renderer": "node build/test.mjs renderer && node build/run-tests.mjs renderer",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"rebuild:sqlite3": "electron-rebuild -f -w better-sqlite3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@the-next-ai/ai-gateway": "^1.0.4",
|
||||
"@the-next-ai/ai-gateway": "^1.0.7",
|
||||
"@the-next-ai/bot-gateway-sdk": "^0.1.0",
|
||||
"better-sqlite3": "^12.11.1",
|
||||
"electron-updater": "^6.8.9",
|
||||
"node-forge": "^1.4.0",
|
||||
"openai": "^6.27.0",
|
||||
"undici": "^7.27.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@tailwindcss/cli": "^4.3.0",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/node": "^22.10.2",
|
||||
|
|
|
|||
21
packages/cli/LICENSE
Normal file
21
packages/cli/LICENSE
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2025 musistudio
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
375
packages/cli/README.md
Normal file
375
packages/cli/README.md
Normal file
|
|
@ -0,0 +1,375 @@
|
|||
<h1 align="center">Claude Code Router Desktop</h1>
|
||||
|
||||
<p align="center">
|
||||
<a href="README_zh.md"><img alt="Chinese README" src="https://img.shields.io/badge/%F0%9F%87%A8%F0%9F%87%B3-%E4%B8%AD%E6%96%87%E7%89%88-ff0000?style=flat" /></a>
|
||||
<a href="https://discord.gg/rdftVMaUcS"><img alt="Discord" src="https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white" /></a>
|
||||
<a href="https://x.com/musistudio2026"><img alt="X" src="https://img.shields.io/badge/X-@musistudio2026-000000?logo=x&logoColor=white" /></a>
|
||||
<a href="https://github.com/musistudio/claude-code-router/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/musistudio/claude-code-router" /></a>
|
||||
<a href="https://ccrdesk.top/"><img alt="Documentation" src="https://img.shields.io/badge/Docs-ccrdesk.top-0ea5e9?style=flat" /></a>
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<a href="https://www.kimi.com/code?aff=ccr">
|
||||
<img src="https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-en.png" width="960" alt="Kimi K2.7 Code sponsor banner" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>
|
||||
<a href="https://www.kimi.com/code?aff=ccr"><strong>Kimi Code Subscription</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.ai?aff=ccr"><strong>API Global</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.com?aff=ccr">API China</a>
|
||||
</sub>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left">
|
||||
<p>
|
||||
<strong>Thanks to Kimi for sponsoring this project!</strong> Kimi K2.7 Code is an open-source, coding-focused agentic model developed by Moonshot AI, with substantial gains on real-world long-horizon coding tasks and higher end-to-end success across complex software engineering workflows. It also cuts thinking-token usage by approximately 30% compared with K2.6. Inside CCR, Kimi ships as built-in provider presets: import the pay-as-you-go API or the Kimi Code subscription in one click and route your coding agent's requests to Kimi, the subscription endpoint passes straight through natively with no protocol conversion, API endpoints are adapted automatically, and your balance and subscription usage show up right in the CCR dashboard.
|
||||
</p>
|
||||
<p align="center">
|
||||
CCR already supports Kimi. Visit the Kimi Open Platform (<a href="https://platform.kimi.com?aff=ccr">中文站</a> | <a href="https://platform.kimi.ai?aff=ccr">Global</a>) to try the API, or explore the <a href="https://www.kimi.com/code?aff=ccr">cost-effective Coding Plan</a>.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
Claude Code Router Desktop is a local gateway and desktop control panel for routing agent requests from Claude Code, Codex, ZCode, and compatible clients to the model provider you actually want to use.
|
||||
|
||||
<p align="center">
|
||||
<img src="blog/images/claude-code-router.png" width="720" alt="Claude Code Router Desktop screenshot" />
|
||||
</p>
|
||||
|
||||
## Why Use CCR
|
||||
|
||||
- Use one local endpoint for multiple agent tools instead of configuring every client separately.
|
||||
- Route requests with default routing, conditional rules, fallback targets, and request rewrites instead of editing client configuration by hand.
|
||||
- Mix providers without changing your workflow. CCR supports OpenAI-compatible APIs, Anthropic Messages, Gemini Generate Content, OpenRouter, DeepSeek, SiliconFlow, Moonshot, Kimi Code, Mistral, Z.AI, Bailian, and custom providers.
|
||||
- Control cost and reliability with fallback routing, API key rotation, usage statistics, and request logs.
|
||||
|
||||
## Features
|
||||
|
||||
- **Overview dashboard**: inspect system status, usage widgets, account balances, model distribution, and share cards.
|
||||
- **Provider management**: add provider presets or custom endpoints, probe protocol support, test model connectivity, manage credentials, and monitor supported account balances where available.
|
||||
- **Routing rules**: configure default routing, conditional and model-prefix rules, fallback handling, and request rewrites.
|
||||
- **Agent Config**: configure Claude Code, Codex, and ZCode launch entries, models, scopes, and multi-instance app profiles.
|
||||
- **Gateway compatibility**: translate supported client requests through the local CCR model gateway.
|
||||
- **Proxy mode**: capture supported API traffic through a local proxy with optional system proxy integration and network capture.
|
||||
- **Fusion models**: combine a base model with vision, web search, or MCP tools into a reusable selectable model.
|
||||
|
||||
## Documentation
|
||||
|
||||
Read the full documentation at [ccrdesk.top](https://ccrdesk.top/).
|
||||
|
||||
## Download And Install
|
||||
|
||||
1. Open the [GitHub Releases page](https://github.com/musistudio/claude-code-router/releases).
|
||||
2. Download the package for your platform:
|
||||
- macOS Apple Silicon: `Claude-Code-Router_<version>-mac-Apple-Silicon-arm64.dmg` or `.zip`
|
||||
- macOS Intel: `Claude-Code-Router_<version>-mac-Intel-x64.dmg` or `.zip`
|
||||
- Windows: `Claude Code Router_<version>.exe`
|
||||
- Linux: `Claude Code Router_<version>.AppImage`
|
||||
3. Install and launch **Claude Code Router**.
|
||||
4. On first launch, CCR creates its local configuration database:
|
||||
- macOS/Linux: `~/.claude-code-router/config.sqlite`
|
||||
- Windows: `%APPDATA%\Claude Code Router\config.sqlite`
|
||||
|
||||
CCR stores runtime configuration in SQLite. A legacy `config.json` is read only once for migration when no SQLite config exists.
|
||||
|
||||
After the service is started from the **Server** page, CCR listens on `http://localhost:8080` by default. The **Server** page controls the gateway `Host`, `Port`, proxy mode, system proxy, network capture, and CA certificate status.
|
||||
|
||||
## Quick Start
|
||||
|
||||
CCR can be configured entirely from the desktop UI. Use this setup order for a clean first run.
|
||||
|
||||
### 1. Add a provider
|
||||
|
||||
Open **Providers**, click **Add Provider**, then choose a built-in preset or **Other / custom API endpoint**. Fill in the provider name, base URL, protocol, API key, and model list. Run protocol probing and model connectivity checks when available, then save the provider.
|
||||
|
||||
### 2. Configure routing
|
||||
|
||||
Open **Routing** to add conditional rules, configure request rewrites, and set fallback behavior.
|
||||
|
||||
Use **Add Routing Rule** for request conditions, model-prefix routing, or rule-level fallback targets.
|
||||
|
||||
### 3. Start the gateway
|
||||
|
||||
Open **Server** and click **Start**. After the page shows Running, CCR listens on `http://localhost:8080`. Enable **Auto start** if you want CCR to start the local gateway whenever the desktop app opens.
|
||||
|
||||
### 4. Connect your agent tool
|
||||
|
||||
Open **Agent Config** and choose the client you want to use. Configure Claude Code, Codex, or ZCode, select the target model and effect scope, then apply the config. For app entries, use the **Open Agent** action to open the target app through CCR.
|
||||
|
||||
### 5. Monitor and adjust
|
||||
|
||||
Use **Settings → Logs & Observability** to enable request logs and agent observability. Use **Logs** to confirm `request model`, `resolved provider`, `resolved model`, status, tokens, latency, and errors; use the tray window for quick token and account status.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
Codex support is powered by [musistudio/codexl](https://github.com/musistudio/codexl).
|
||||
|
||||
## Support & Sponsoring
|
||||
|
||||
<div align="center">
|
||||
|
||||
<p>If you find this project helpful, please consider sponsoring its development. Your support is greatly appreciated.</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="220">
|
||||
<a href="https://ko-fi.com/F1F31GN2GM">
|
||||
<img src="https://ko-fi.com/img/githubbutton_sm.svg" alt="Support on Ko-fi" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>One-time support via Ko-fi</sub>
|
||||
</td>
|
||||
<td align="center" width="220">
|
||||
<a href="https://paypal.me/musistudio1999">
|
||||
<img src="https://img.shields.io/badge/PayPal-Sponsor-003087?logo=paypal&logoColor=white" alt="Sponsor with PayPal" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>International sponsorship</sub>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="220">
|
||||
<strong>Alipay</strong>
|
||||
<br />
|
||||
<img src="/blog/images/alipay.jpg" width="160" alt="Alipay QR code" />
|
||||
</td>
|
||||
<td align="center" width="220">
|
||||
<strong>WeChat Pay</strong>
|
||||
<br />
|
||||
<img src="/blog/images/wechat.jpg" width="160" alt="WeChat Pay QR code" />
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
### Our Sponsors
|
||||
|
||||
<div align="center">
|
||||
|
||||
<p>A huge thank you to all our sponsors for their generous support.</p>
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center" width="330">
|
||||
<a href="https://www.bigmodel.cn/claude-code?ic=FPF9IVAGFJ">
|
||||
<img src="/docs/public/provider-icons/zhipu-cn-general.png" width="42" height="42" alt="Zhipu icon" />
|
||||
<br />
|
||||
<strong>Z智谱</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://aihubmix.com/">
|
||||
<img src="https://www.google.com/s2/favicons?domain=aihubmix.com&sz=128" width="42" height="42" alt="AIHubmix icon" />
|
||||
<br />
|
||||
<strong>AIHubmix</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://ai.burncloud.com">
|
||||
<img src="https://www.burncloud.com/favicon.png" width="42" height="42" alt="BurnCloud icon" />
|
||||
<br />
|
||||
<strong>BurnCloud</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://share.302.ai/ZGVF9w">
|
||||
<img src="https://www.google.com/s2/favicons?domain=302.ai&sz=128" width="42" height="42" alt="302.AI icon" />
|
||||
<br />
|
||||
<strong>302.AI</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="330">
|
||||
<a href="https://runapi.co/register?aff=IX1t">
|
||||
<img src="/docs/public/provider-icons/runapi.jpg" width="42" height="42" alt="RunAPI icon" />
|
||||
<br />
|
||||
<strong>RunAPI</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://teamorouter.com/">
|
||||
<img src="/docs/public/provider-icons/teamorouter.png" width="42" height="42" alt="TeamoRouter icon" />
|
||||
<br />
|
||||
<strong>TeamoRouter</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://s.qiniu.com/AVjMVf">
|
||||
<img src="/docs/public/provider-icons/qiniu-ai.png" width="42" height="42" alt="Qiniu Cloud AI icon" />
|
||||
<br />
|
||||
<strong>Qiniu Cloud AI</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=9HHHAB5QLAES">
|
||||
<img src="/docs/public/provider-icons/fenno.jpg" width="42" height="42" alt="Fenno.ai icon" />
|
||||
<br />
|
||||
<strong>Fenno.ai</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h4>Community Sponsors</h4>
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center" width="220">@Simon Leischnig</td>
|
||||
<td align="center" width="220"><a href="https://github.com/duanshuaimin">@duanshuaimin</a></td>
|
||||
<td align="center" width="220"><a href="https://github.com/vrgitadmin">@vrgitadmin</a></td>
|
||||
<td align="center" width="220">@*o</td>
|
||||
<td align="center" width="220"><a href="https://github.com/ceilwoo">@ceilwoo</a></td>
|
||||
<td align="center" width="220">@*说</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*更</td>
|
||||
<td align="center" width="220">@K*g</td>
|
||||
<td align="center" width="220">@R*R</td>
|
||||
<td align="center" width="220"><a href="https://github.com/bobleer">@bobleer</a></td>
|
||||
<td align="center" width="220">@*苗</td>
|
||||
<td align="center" width="220">@*划</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220"><a href="https://github.com/Clarence-pan">@Clarence-pan</a></td>
|
||||
<td align="center" width="220"><a href="https://github.com/carter003">@carter003</a></td>
|
||||
<td align="center" width="220">@S*r</td>
|
||||
<td align="center" width="220">@*晖</td>
|
||||
<td align="center" width="220">@*敏</td>
|
||||
<td align="center" width="220">@Z*z</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*然</td>
|
||||
<td align="center" width="220"><a href="https://github.com/cluic">@cluic</a></td>
|
||||
<td align="center" width="220">@*苗</td>
|
||||
<td align="center" width="220"><a href="https://github.com/PromptExpert">@PromptExpert</a></td>
|
||||
<td align="center" width="220">@*应</td>
|
||||
<td align="center" width="220"><a href="https://github.com/yusnake">@yusnake</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*飞</td>
|
||||
<td align="center" width="220">@董*</td>
|
||||
<td align="center" width="220">@*汀</td>
|
||||
<td align="center" width="220">@*涯</td>
|
||||
<td align="center" width="220">@*:-)</td>
|
||||
<td align="center" width="220">@**磊</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*琢</td>
|
||||
<td align="center" width="220">@*成</td>
|
||||
<td align="center" width="220">@Z*o</td>
|
||||
<td align="center" width="220">@*琨</td>
|
||||
<td align="center" width="220"><a href="https://github.com/congzhangzh">@congzhangzh</a></td>
|
||||
<td align="center" width="220">@*_</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@Z*m</td>
|
||||
<td align="center" width="220">@*鑫</td>
|
||||
<td align="center" width="220">@c*y</td>
|
||||
<td align="center" width="220">@*昕</td>
|
||||
<td align="center" width="220"><a href="https://github.com/witsice">@witsice</a></td>
|
||||
<td align="center" width="220">@b*g</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*亿</td>
|
||||
<td align="center" width="220">@*辉</td>
|
||||
<td align="center" width="220">@JACK</td>
|
||||
<td align="center" width="220">@*光</td>
|
||||
<td align="center" width="220">@W*l</td>
|
||||
<td align="center" width="220"><a href="https://github.com/kesku">@kesku</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220"><a href="https://github.com/biguncle">@biguncle</a></td>
|
||||
<td align="center" width="220">@二吉吉</td>
|
||||
<td align="center" width="220">@a*g</td>
|
||||
<td align="center" width="220">@*林</td>
|
||||
<td align="center" width="220">@*咸</td>
|
||||
<td align="center" width="220">@*明</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@S*y</td>
|
||||
<td align="center" width="220">@f*o</td>
|
||||
<td align="center" width="220">@*智</td>
|
||||
<td align="center" width="220">@F*t</td>
|
||||
<td align="center" width="220">@r*c</td>
|
||||
<td align="center" width="220"><a href="https://github.com/qierkang">@qierkang</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*军</td>
|
||||
<td align="center" width="220"><a href="https://github.com/snrise-z">@snrise-z</a></td>
|
||||
<td align="center" width="220">@*王</td>
|
||||
<td align="center" width="220"><a href="https://github.com/greatheart1000">@greatheart1000</a></td>
|
||||
<td align="center" width="220">@*王</td>
|
||||
<td align="center" width="220">@zcutlip</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220"><a href="https://github.com/Peng-YM">@Peng-YM</a></td>
|
||||
<td align="center" width="220">@*更</td>
|
||||
<td align="center" width="220">@*.</td>
|
||||
<td align="center" width="220">@F*t</td>
|
||||
<td align="center" width="220">@*政</td>
|
||||
<td align="center" width="220">@*铭</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*叶</td>
|
||||
<td align="center" width="220">@七*o</td>
|
||||
<td align="center" width="220">@*青</td>
|
||||
<td align="center" width="220">@**晨</td>
|
||||
<td align="center" width="220">@*远</td>
|
||||
<td align="center" width="220">@*霄</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@**吉</td>
|
||||
<td align="center" width="220">@**飞</td>
|
||||
<td align="center" width="220">@**驰</td>
|
||||
<td align="center" width="220">@x*g</td>
|
||||
<td align="center" width="220">@**东</td>
|
||||
<td align="center" width="220">@*落</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@哆*k</td>
|
||||
<td align="center" width="220">@*涛</td>
|
||||
<td align="center" width="220"><a href="https://github.com/WitMiao">@苗大</a></td>
|
||||
<td align="center" width="220">@*呢</td>
|
||||
<td align="center" width="220">@d*u</td>
|
||||
<td align="center" width="220">@crizcraig</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">s*s</td>
|
||||
<td align="center" width="220">*火</td>
|
||||
<td align="center" width="220">*勤</td>
|
||||
<td align="center" width="220">**锟</td>
|
||||
<td align="center" width="220">*涛</td>
|
||||
<td align="center" width="220">**明</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">*知</td>
|
||||
<td align="center" width="220">*语</td>
|
||||
<td align="center" width="220">*瓜</td>
|
||||
<td align="center" width="220"></td>
|
||||
<td align="center" width="220"></td>
|
||||
<td align="center" width="220"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<sub>If your name is masked, please contact me via my homepage email to update it with your GitHub username.</sub>
|
||||
|
||||
</div>
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT License](LICENSE).
|
||||
374
packages/cli/README_zh.md
Normal file
374
packages/cli/README_zh.md
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
<h1 align="center">Claude Code Router Desktop</h1>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md"><img alt="English README" src="https://img.shields.io/badge/%F0%9F%87%AC%F0%9F%87%A7-English-000aff?style=flat" /></a>
|
||||
<a href="https://discord.gg/rdftVMaUcS"><img alt="Discord" src="https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white" /></a>
|
||||
<a href="https://x.com/musistudio2026"><img alt="X" src="https://img.shields.io/badge/X-@musistudio2026-000000?logo=x&logoColor=white" /></a>
|
||||
<a href="https://github.com/musistudio/claude-code-router/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/musistudio/claude-code-router" /></a>
|
||||
<a href="https://ccrdesk.top/"><img alt="文档" src="https://img.shields.io/badge/%E6%96%87%E6%A1%A3-ccrdesk.top-0ea5e9?style=flat" /></a>
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<a href="https://www.kimi.com/code?aff=ccr">
|
||||
<img src="https://gcdn.moonshot.cn/growth-cdn/sponsor/kimi-zh.png" width="960" alt="Kimi K2.7 Code 赞助横幅" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>
|
||||
<a href="https://www.kimi.com/code?aff=ccr"><strong>Kimi Code 订阅</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.com?aff=ccr"><strong>API 中文站</strong></a>
|
||||
·
|
||||
<a href="https://platform.kimi.ai?aff=ccr">API Global</a>
|
||||
</sub>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="left">
|
||||
<p>
|
||||
<strong>感谢 Kimi 赞助本项目!</strong>Kimi K2.7 Code 是 Moonshot AI 推出的编程专用开源智能体模型,在真实长程编程与复杂软件工程工作流中显著提升端到端任务成功率,同时优化推理效率,相比 K2.6 平均减少约 30% 的推理 token 消耗。在 CCR 中,Kimi 已作为内置供应商预设开箱即用:无论按量付费 API 还是 Kimi Code 订阅,一键导入即可把你的编程 Agent 请求路由到 Kimi,订阅端点原生直通、无需协议转换,API 端点自动适配,账户余额与订阅用量也能直接在 CCR 面板中查看。
|
||||
</p>
|
||||
<p align="center">
|
||||
CCR 已内置 Kimi 供应商预设。前往 Kimi 开放平台(<a href="https://platform.kimi.com?aff=ccr">中文站</a>|<a href="https://platform.kimi.ai?aff=ccr">Global</a>)体验 API,或了解高性价比 <a href="https://www.kimi.com/code?aff=ccr">Coding Plan</a> 套餐。
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
Claude Code Router Desktop 是一个本地网关和桌面控制台,用来把 Claude Code、Codex、ZCode 以及兼容客户端的 Agent 请求路由到你真正想使用的模型服务。
|
||||
|
||||
<p align="center">
|
||||
<img src="blog/images/claude-code-router.png" width="720" alt="Claude Code Router Desktop 项目截图" />
|
||||
</p>
|
||||
|
||||
## 为什么使用 CCR
|
||||
|
||||
- 用一个本地入口连接多个 Agent 工具,不需要在每个客户端里重复配置 Provider。
|
||||
- 在不改变工作流的情况下混用不同 Provider。CCR 支持 OpenAI 兼容 API、Anthropic Messages、Gemini Generate Content、OpenRouter、DeepSeek、SiliconFlow、Moonshot、Kimi Code、Mistral、Z.AI、百炼以及自定义 Provider。
|
||||
- 通过 fallback 路由、API Key 轮换、用量统计和请求日志来控制成本和可靠性。
|
||||
|
||||
## 功能和特性
|
||||
|
||||
- **概览仪表盘**:查看系统状态、用量组件、账号余额、模型分布和分享卡片。
|
||||
- **Provider 管理**:添加预设或自定义端点,探测协议支持,检测模型连通性,管理凭据,并在可用时查看账号余额。
|
||||
- **路由规则**:配置条件路由、模型前缀规则、失败降级和请求改写。
|
||||
- **Agent配置**:为 Claude Code、Codex 和 ZCode 配置启动入口、模型、作用范围和多开 App 配置。
|
||||
- **网关兼容层**:通过本地 CCR 模型网关转换支持的客户端请求。
|
||||
- **代理模式**:通过本地代理捕获支持的 API 流量,可选系统代理和网络捕获。
|
||||
- **Fusion 组合模型**:把基础模型与视觉、联网搜索或 MCP 工具组合成新的可选模型。
|
||||
|
||||
## 文档
|
||||
|
||||
完整文档见 [ccrdesk.top](https://ccrdesk.top/)。
|
||||
|
||||
## 下载和安装
|
||||
|
||||
1. 打开 [GitHub Releases 页面](https://github.com/musistudio/claude-code-router/releases)。
|
||||
2. 按系统下载对应安装包:
|
||||
- macOS Apple 芯片:`Claude-Code-Router_<version>-mac-Apple-Silicon-arm64.dmg` 或 `.zip`
|
||||
- macOS Intel 芯片:`Claude-Code-Router_<version>-mac-Intel-x64.dmg` 或 `.zip`
|
||||
- Windows:`Claude Code Router_<version>.exe`
|
||||
- Linux:`Claude Code Router_<version>.AppImage`
|
||||
3. 安装并启动 **Claude Code Router**。
|
||||
4. 首次启动后,CCR 会创建本地配置数据库:
|
||||
- macOS/Linux:`~/.claude-code-router/config.sqlite`
|
||||
- Windows:`%APPDATA%\Claude Code Router\config.sqlite`
|
||||
|
||||
CCR 的运行配置存储在 SQLite 中。旧版 `config.json` 只会在没有 SQLite 配置时作为迁移来源读取一次。
|
||||
|
||||
从 **服务** 页面启动后,CCR 默认监听 `http://localhost:8080`。**服务** 页面负责配置网关 `Host`、`Port`、代理模式、系统代理、网络捕获和 CA 证书状态。
|
||||
|
||||
## 快速开始
|
||||
|
||||
CCR 可以完全通过桌面 UI 完成配置。首次使用建议按下面顺序操作。
|
||||
|
||||
### 1. 添加 Provider
|
||||
|
||||
打开 **供应商**,点击 **添加供应商**,选择内置预设或 **其他 / 自定义 API 端点**。按表单填写 Provider 名称、基础 URL、协议、API Key 和模型列表。可用时先运行协议探测和模型连通性检查,然后保存 Provider。
|
||||
|
||||
### 2. 设置路由
|
||||
|
||||
打开 **路由**,添加条件规则,配置请求改写和失败降级。
|
||||
|
||||
如果需要更细粒度控制,使用 **添加路由规则** 添加模型前缀、请求条件或规则级失败降级目标。
|
||||
|
||||
### 3. 启动网关
|
||||
|
||||
打开 **服务**,点击 **启动**。页面显示运行中后,CCR 会在本机监听 `http://localhost:8080`。如果希望每次打开桌面应用时自动启动网关,可以启用自动启动。
|
||||
|
||||
### 4. 连接 Agent 工具
|
||||
|
||||
打开 **Agent配置**,选择要使用的客户端。配置 Claude Code、Codex 或 ZCode,选择目标模型和作用范围,然后应用配置。对于 App 入口,可以使用 **打开 Agent** 操作通过 CCR 打开目标应用。
|
||||
|
||||
### 5. 日常查看和调整
|
||||
|
||||
到 **设置 → 日志与观测** 打开请求日志和 Agent 观测。使用 **日志** 确认 `request model`、`resolved provider`、`resolved model`、状态码、tokens、耗时和错误;使用托盘窗口快速查看 Token 和账号状态。
|
||||
|
||||
## 致谢
|
||||
|
||||
对 Codex 的支持来自于 [musistudio/codexl](https://github.com/musistudio/codexl) 这个项目。
|
||||
|
||||
## 支持与赞助
|
||||
|
||||
<div align="center">
|
||||
|
||||
<p>如果你觉得这个项目有帮助,欢迎赞助项目开发。非常感谢你的支持。</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="220">
|
||||
<a href="https://ko-fi.com/F1F31GN2GM">
|
||||
<img src="https://ko-fi.com/img/githubbutton_sm.svg" alt="通过 Ko-fi 赞助" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>通过 Ko-fi 单次赞助</sub>
|
||||
</td>
|
||||
<td align="center" width="220">
|
||||
<a href="https://paypal.me/musistudio1999">
|
||||
<img src="https://img.shields.io/badge/PayPal-Sponsor-003087?logo=paypal&logoColor=white" alt="通过 PayPal 赞助" />
|
||||
</a>
|
||||
<br />
|
||||
<sub>国际赞助通道</sub>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="220">
|
||||
<strong>支付宝</strong>
|
||||
<br />
|
||||
<img src="/blog/images/alipay.jpg" width="160" alt="支付宝收款码" />
|
||||
</td>
|
||||
<td align="center" width="220">
|
||||
<strong>微信支付</strong>
|
||||
<br />
|
||||
<img src="/blog/images/wechat.jpg" width="160" alt="微信支付收款码" />
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
|
||||
### 我们的赞助商
|
||||
|
||||
<div align="center">
|
||||
|
||||
<p>非常感谢所有赞助商的慷慨支持。</p>
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center" width="330">
|
||||
<a href="https://www.bigmodel.cn/claude-code?ic=FPF9IVAGFJ">
|
||||
<img src="/docs/public/provider-icons/zhipu-cn-general.png" width="42" height="42" alt="智谱图标" />
|
||||
<br />
|
||||
<strong>Z智谱</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://aihubmix.com/">
|
||||
<img src="https://www.google.com/s2/favicons?domain=aihubmix.com&sz=128" width="42" height="42" alt="AIHubmix 图标" />
|
||||
<br />
|
||||
<strong>AIHubmix</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://ai.burncloud.com">
|
||||
<img src="https://www.burncloud.com/favicon.png" width="42" height="42" alt="BurnCloud 图标" />
|
||||
<br />
|
||||
<strong>BurnCloud</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://share.302.ai/ZGVF9w">
|
||||
<img src="https://www.google.com/s2/favicons?domain=302.ai&sz=128" width="42" height="42" alt="302.AI 图标" />
|
||||
<br />
|
||||
<strong>302.AI</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="330">
|
||||
<a href="https://runapi.co/register?aff=IX1t">
|
||||
<img src="/docs/public/provider-icons/runapi.jpg" width="42" height="42" alt="RunAPI 图标" />
|
||||
<br />
|
||||
<strong>RunAPI</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://teamorouter.com/">
|
||||
<img src="/docs/public/provider-icons/teamorouter.png" width="42" height="42" alt="TeamoRouter 图标" />
|
||||
<br />
|
||||
<strong>TeamoRouter</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://s.qiniu.com/AVjMVf">
|
||||
<img src="/docs/public/provider-icons/qiniu-ai.png" width="42" height="42" alt="七牛云 AI 图标" />
|
||||
<br />
|
||||
<strong>七牛云 AI</strong>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" width="330">
|
||||
<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=9HHHAB5QLAES">
|
||||
<img src="/docs/public/provider-icons/fenno.jpg" width="42" height="42" alt="Fenno.ai 图标" />
|
||||
<br />
|
||||
<strong>Fenno.ai</strong>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h4>社区赞助者</h4>
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td align="center" width="220">@Simon Leischnig</td>
|
||||
<td align="center" width="220"><a href="https://github.com/duanshuaimin">@duanshuaimin</a></td>
|
||||
<td align="center" width="220"><a href="https://github.com/vrgitadmin">@vrgitadmin</a></td>
|
||||
<td align="center" width="220">@*o</td>
|
||||
<td align="center" width="220"><a href="https://github.com/ceilwoo">@ceilwoo</a></td>
|
||||
<td align="center" width="220">@*说</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*更</td>
|
||||
<td align="center" width="220">@K*g</td>
|
||||
<td align="center" width="220">@R*R</td>
|
||||
<td align="center" width="220"><a href="https://github.com/bobleer">@bobleer</a></td>
|
||||
<td align="center" width="220">@*苗</td>
|
||||
<td align="center" width="220">@*划</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220"><a href="https://github.com/Clarence-pan">@Clarence-pan</a></td>
|
||||
<td align="center" width="220"><a href="https://github.com/carter003">@carter003</a></td>
|
||||
<td align="center" width="220">@S*r</td>
|
||||
<td align="center" width="220">@*晖</td>
|
||||
<td align="center" width="220">@*敏</td>
|
||||
<td align="center" width="220">@Z*z</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*然</td>
|
||||
<td align="center" width="220"><a href="https://github.com/cluic">@cluic</a></td>
|
||||
<td align="center" width="220">@*苗</td>
|
||||
<td align="center" width="220"><a href="https://github.com/PromptExpert">@PromptExpert</a></td>
|
||||
<td align="center" width="220">@*应</td>
|
||||
<td align="center" width="220"><a href="https://github.com/yusnake">@yusnake</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*飞</td>
|
||||
<td align="center" width="220">@董*</td>
|
||||
<td align="center" width="220">@*汀</td>
|
||||
<td align="center" width="220">@*涯</td>
|
||||
<td align="center" width="220">@*:-)</td>
|
||||
<td align="center" width="220">@**磊</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*琢</td>
|
||||
<td align="center" width="220">@*成</td>
|
||||
<td align="center" width="220">@Z*o</td>
|
||||
<td align="center" width="220">@*琨</td>
|
||||
<td align="center" width="220"><a href="https://github.com/congzhangzh">@congzhangzh</a></td>
|
||||
<td align="center" width="220">@*_</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@Z*m</td>
|
||||
<td align="center" width="220">@*鑫</td>
|
||||
<td align="center" width="220">@c*y</td>
|
||||
<td align="center" width="220">@*昕</td>
|
||||
<td align="center" width="220"><a href="https://github.com/witsice">@witsice</a></td>
|
||||
<td align="center" width="220">@b*g</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*亿</td>
|
||||
<td align="center" width="220">@*辉</td>
|
||||
<td align="center" width="220">@JACK</td>
|
||||
<td align="center" width="220">@*光</td>
|
||||
<td align="center" width="220">@W*l</td>
|
||||
<td align="center" width="220"><a href="https://github.com/kesku">@kesku</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220"><a href="https://github.com/biguncle">@biguncle</a></td>
|
||||
<td align="center" width="220">@二吉吉</td>
|
||||
<td align="center" width="220">@a*g</td>
|
||||
<td align="center" width="220">@*林</td>
|
||||
<td align="center" width="220">@*咸</td>
|
||||
<td align="center" width="220">@*明</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@S*y</td>
|
||||
<td align="center" width="220">@f*o</td>
|
||||
<td align="center" width="220">@*智</td>
|
||||
<td align="center" width="220">@F*t</td>
|
||||
<td align="center" width="220">@r*c</td>
|
||||
<td align="center" width="220"><a href="https://github.com/qierkang">@qierkang</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*军</td>
|
||||
<td align="center" width="220"><a href="https://github.com/snrise-z">@snrise-z</a></td>
|
||||
<td align="center" width="220">@*王</td>
|
||||
<td align="center" width="220"><a href="https://github.com/greatheart1000">@greatheart1000</a></td>
|
||||
<td align="center" width="220">@*王</td>
|
||||
<td align="center" width="220">@zcutlip</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220"><a href="https://github.com/Peng-YM">@Peng-YM</a></td>
|
||||
<td align="center" width="220">@*更</td>
|
||||
<td align="center" width="220">@*.</td>
|
||||
<td align="center" width="220">@F*t</td>
|
||||
<td align="center" width="220">@*政</td>
|
||||
<td align="center" width="220">@*铭</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@*叶</td>
|
||||
<td align="center" width="220">@七*o</td>
|
||||
<td align="center" width="220">@*青</td>
|
||||
<td align="center" width="220">@**晨</td>
|
||||
<td align="center" width="220">@*远</td>
|
||||
<td align="center" width="220">@*霄</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@**吉</td>
|
||||
<td align="center" width="220">@**飞</td>
|
||||
<td align="center" width="220">@**驰</td>
|
||||
<td align="center" width="220">@x*g</td>
|
||||
<td align="center" width="220">@**东</td>
|
||||
<td align="center" width="220">@*落</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">@哆*k</td>
|
||||
<td align="center" width="220">@*涛</td>
|
||||
<td align="center" width="220"><a href="https://github.com/WitMiao">@苗大</a></td>
|
||||
<td align="center" width="220">@*呢</td>
|
||||
<td align="center" width="220">@d*u</td>
|
||||
<td align="center" width="220">@crizcraig</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">s*s</td>
|
||||
<td align="center" width="220">*火</td>
|
||||
<td align="center" width="220">*勤</td>
|
||||
<td align="center" width="220">**锟</td>
|
||||
<td align="center" width="220">*涛</td>
|
||||
<td align="center" width="220">**明</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="220">*知</td>
|
||||
<td align="center" width="220">*语</td>
|
||||
<td align="center" width="220">*瓜</td>
|
||||
<td align="center" width="220"></td>
|
||||
<td align="center" width="220"></td>
|
||||
<td align="center" width="220"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<sub>如果你的名字被打码,请通过我的主页邮箱联系我更新为 GitHub 用户名。</sub>
|
||||
|
||||
</div>
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目基于 [MIT License](LICENSE) 发布。
|
||||
48
packages/cli/package.json
Normal file
48
packages/cli/package.json
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
{
|
||||
"name": "@musistudio/claude-code-router",
|
||||
"version": "3.0.3",
|
||||
"license": "MIT",
|
||||
"description": "Local Claude Code Router gateway with CLI and web management UI.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@github.com/musistudio/claude-code-router.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/musistudio/claude-code-router/issues"
|
||||
},
|
||||
"homepage": "https://github.com/musistudio/claude-code-router#readme",
|
||||
"keywords": [
|
||||
"claude-code",
|
||||
"codex",
|
||||
"llm",
|
||||
"gateway",
|
||||
"router"
|
||||
],
|
||||
"main": "dist/main/cli.js",
|
||||
"bin": {
|
||||
"ccr": "dist/main/cli.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"README_zh.md"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"prepack": "npm --prefix ../.. run build:assets",
|
||||
"prepublishOnly": "npm --prefix ../.. run typecheck"
|
||||
},
|
||||
"dependencies": {
|
||||
"@the-next-ai/ai-gateway": "^1.0.4",
|
||||
"@the-next-ai/bot-gateway-sdk": "^0.1.0",
|
||||
"better-sqlite3": "^12.11.1",
|
||||
"node-forge": "^1.4.0",
|
||||
"undici": "^7.27.2"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +1,19 @@
|
|||
#!/usr/bin/env node
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { accessSync, constants as fsConstants, existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { assertAvailableGatewayModels, type ProfileConfig, type ProfileOpenSurface } from "../shared/app";
|
||||
import { botGatewayProfileEnv } from "./bot-gateway-env";
|
||||
import { applyClaudeAppGatewayConfig } from "./claude-app-gateway-service";
|
||||
import { launchClaudeAppProfile, resolveClaudeAppProfileUserDataDir } from "./claude-app-launch";
|
||||
import { launchCodexAppProfile, launchZcodeAppProfile } from "./codex-app-launch";
|
||||
import { loadAppConfig } from "./config";
|
||||
import { CONFIGDIR } from "./constants";
|
||||
import { applyProfileConfig, applyProfileRuntimeConfig } from "./profile-service";
|
||||
import { ensureProfileGateway } from "./profile-launch-service";
|
||||
import { buildProfileLaunchPlan, defaultProfileOpenSurface, findProfileForOpen, profileLaunchSpawnCommand, resolveProfileOpenSurface } from "./profile-launch-core";
|
||||
import { startWebManagementServer } from "./web-management-server";
|
||||
import { botGatewayProfileEnv } from "@ccr/core/agents/bot-gateway/env";
|
||||
import { applyClaudeAppGatewayConfig } from "@ccr/core/agents/claude-app/gateway-service";
|
||||
import { launchClaudeAppProfile, resolveClaudeAppProfileUserDataDir } from "@ccr/core/agents/claude-app/launch";
|
||||
import { codexDesktopAppName, launchCodexAppProfile, launchZcodeAppProfile } from "@ccr/core/agents/codex/app-launch";
|
||||
import { loadAppConfig } from "@ccr/core/config/config";
|
||||
import { CONFIGDIR } from "@ccr/core/config/constants";
|
||||
import { applyProfileConfig, applyProfileRuntimeConfig } from "@ccr/core/profiles/service";
|
||||
import { ensureProfileGateway } from "@ccr/core/profiles/launch-service";
|
||||
import { buildProfileLaunchPlan, defaultProfileOpenSurface, findProfileForOpen, profileLaunchSpawnCommand, resolveProfileOpenSurface } from "@ccr/core/profiles/launch-core";
|
||||
import { openSystemExternal, startWebManagementServer } from "@ccr/core/web/management-server";
|
||||
import { assertAvailableGatewayModels, type ProfileConfig, type ProfileOpenSurface } from "@ccr/core/contracts/app";
|
||||
|
||||
type ProfileCliOptions = {
|
||||
agentArgs: string[];
|
||||
|
|
@ -23,7 +24,7 @@ type ProfileCliOptions = {
|
|||
};
|
||||
|
||||
type WebCliOptions = {
|
||||
command: "start" | "web";
|
||||
command: "start" | "ui" | "web";
|
||||
daemonChild: boolean;
|
||||
help: boolean;
|
||||
host?: string;
|
||||
|
|
@ -42,22 +43,22 @@ type CliOptions = ProfileCliOptions | StopCliOptions | WebCliOptions;
|
|||
type ServiceState = {
|
||||
host?: string;
|
||||
pid: number;
|
||||
serviceToken?: string;
|
||||
startedAt: string;
|
||||
startGateway: boolean;
|
||||
url: string;
|
||||
};
|
||||
|
||||
const serviceStateFileName = "service.json";
|
||||
const serviceInstanceTokenEnv = "CCR_SERVICE_INSTANCE_TOKEN";
|
||||
const serviceRpcTimeoutMs = 2_000;
|
||||
const serviceStartTimeoutMs = 30_000;
|
||||
const serviceStopTimeoutMs = 10_000;
|
||||
const webAuthHeader = "x-ccr-web-auth";
|
||||
const webAuthQueryParam = "ccr_web_token";
|
||||
const defaultCliCommandName = "ccr";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const delegatedExitCode = delegateManagedDesktopCliToExternalCli();
|
||||
if (delegatedExitCode !== undefined) {
|
||||
process.exitCode = delegatedExitCode;
|
||||
return;
|
||||
}
|
||||
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.command === "start") {
|
||||
if (options.help) {
|
||||
|
|
@ -67,6 +68,14 @@ async function main(): Promise<void> {
|
|||
await startService(options);
|
||||
return;
|
||||
}
|
||||
if (options.command === "ui") {
|
||||
if (options.help) {
|
||||
printUiHelp(0);
|
||||
return;
|
||||
}
|
||||
await openManagementUi(options);
|
||||
return;
|
||||
}
|
||||
if (options.command === "stop") {
|
||||
if (options.help) {
|
||||
printStopHelp(0);
|
||||
|
|
@ -141,9 +150,9 @@ async function main(): Promise<void> {
|
|||
const launch = launchCodexAppProfile(configDir, profile, launchConfig);
|
||||
const spawnError = await waitForImmediateSpawnError(launch.child, 500);
|
||||
if (spawnError) {
|
||||
throw new Error(`Failed to open Codex App: ${spawnError}`);
|
||||
throw new Error(`Failed to open ${codexDesktopAppName}: ${spawnError}`);
|
||||
}
|
||||
process.stdout.write(`Opened Codex App with ${profile.name || profile.id}.\n`);
|
||||
process.stdout.write(`Opened ${codexDesktopAppName} with ${profile.name || profile.id}.\n`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
|
@ -175,6 +184,9 @@ function parseArgs(args: string[]): CliOptions {
|
|||
if (args[0] === "start") {
|
||||
return parseWebArgs(args.slice(1), "start");
|
||||
}
|
||||
if (args[0] === "ui") {
|
||||
return parseWebArgs(args.slice(1), "ui", true);
|
||||
}
|
||||
if (args[0] === "stop") {
|
||||
return parseStopArgs(args.slice(1));
|
||||
}
|
||||
|
|
@ -226,7 +238,7 @@ function profileAppName(profile: Pick<ProfileConfig, "agent">): string {
|
|||
if (profile.agent === "zcode") {
|
||||
return "ZCode App";
|
||||
}
|
||||
return "Codex App";
|
||||
return codexDesktopAppName;
|
||||
}
|
||||
|
||||
function parseStopArgs(args: string[]): StopCliOptions {
|
||||
|
|
@ -244,12 +256,12 @@ function parseStopArgs(args: string[]): StopCliOptions {
|
|||
return options;
|
||||
}
|
||||
|
||||
function parseWebArgs(args: string[], command: WebCliOptions["command"]): WebCliOptions {
|
||||
function parseWebArgs(args: string[], command: WebCliOptions["command"], defaultOpen = false): WebCliOptions {
|
||||
const options: WebCliOptions = {
|
||||
command,
|
||||
daemonChild: false,
|
||||
help: false,
|
||||
open: false,
|
||||
open: defaultOpen,
|
||||
startGateway: true
|
||||
};
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
|
|
@ -303,24 +315,31 @@ function parseWebArgs(args: string[], command: WebCliOptions["command"]): WebCli
|
|||
|
||||
async function startService(options: WebCliOptions): Promise<void> {
|
||||
const current = readServiceState();
|
||||
if (current && isProcessRunning(current.pid)) {
|
||||
const currentVerification = current ? await verifyServiceState(current) : undefined;
|
||||
if (current && currentVerification?.ok) {
|
||||
process.stdout.write(`CCR service is already running at ${current.url} (pid ${current.pid}).\n`);
|
||||
if (options.open) {
|
||||
await openManagementUrl(current.url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
clearServiceState();
|
||||
if (current) {
|
||||
clearServiceState(current.pid);
|
||||
}
|
||||
|
||||
const serviceToken = generateServiceToken();
|
||||
const childArgs = [
|
||||
currentCliScript(),
|
||||
"serve",
|
||||
"--daemon-child",
|
||||
...(options.host ? ["--host", options.host] : []),
|
||||
...(options.port ? ["--port", String(options.port)] : []),
|
||||
...(options.open ? ["--open"] : ["--no-open"]),
|
||||
"--no-open",
|
||||
...(options.startGateway ? [] : ["--no-gateway"])
|
||||
];
|
||||
const child = spawn(process.execPath, childArgs, {
|
||||
detached: true,
|
||||
env: serviceChildEnv(),
|
||||
env: serviceChildEnv(serviceToken),
|
||||
stdio: "ignore",
|
||||
windowsHide: true
|
||||
});
|
||||
|
|
@ -335,10 +354,31 @@ async function startService(options: WebCliOptions): Promise<void> {
|
|||
throw new Error(`CCR service did not report ready within ${serviceStartTimeoutMs}ms.`);
|
||||
}
|
||||
process.stdout.write(`CCR service started at ${state.url} (pid ${state.pid}).\n`);
|
||||
if (options.open) {
|
||||
await openManagementUrl(state.url);
|
||||
}
|
||||
}
|
||||
|
||||
function serviceChildEnv(): NodeJS.ProcessEnv {
|
||||
async function openManagementUi(options: WebCliOptions): Promise<void> {
|
||||
await startService({
|
||||
...options,
|
||||
command: "start"
|
||||
});
|
||||
}
|
||||
|
||||
async function openManagementUrl(url: string): Promise<void> {
|
||||
try {
|
||||
await openSystemExternal(url);
|
||||
process.stdout.write(`Opened CCR management UI at ${url}\n`);
|
||||
} catch (error) {
|
||||
process.stderr.write(`Failed to open browser: ${formatError(error)}\n`);
|
||||
process.stdout.write(`CCR management UI is available at ${url}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
function serviceChildEnv(serviceToken: string): NodeJS.ProcessEnv {
|
||||
const env = { ...process.env };
|
||||
env[serviceInstanceTokenEnv] = serviceToken;
|
||||
if (process.versions.electron) {
|
||||
env.ELECTRON_RUN_AS_NODE = "1";
|
||||
} else {
|
||||
|
|
@ -355,9 +395,11 @@ async function runWebServer(options: WebCliOptions): Promise<void> {
|
|||
startGateway: options.startGateway
|
||||
});
|
||||
if (options.daemonChild) {
|
||||
const serviceToken = process.env[serviceInstanceTokenEnv]?.trim() || undefined;
|
||||
writeServiceState({
|
||||
host: options.host,
|
||||
pid: process.pid,
|
||||
...(serviceToken ? { serviceToken } : {}),
|
||||
startedAt: new Date().toISOString(),
|
||||
startGateway: options.startGateway,
|
||||
url: runtime.url
|
||||
|
|
@ -389,33 +431,40 @@ async function stopService(): Promise<void> {
|
|||
process.stdout.write("CCR service is not running.\n");
|
||||
return;
|
||||
}
|
||||
if (!isProcessRunning(state.pid)) {
|
||||
const verification = await verifyServiceState(state);
|
||||
if (!verification.ok) {
|
||||
clearServiceState(state.pid);
|
||||
process.stdout.write("CCR service is not running.\n");
|
||||
return;
|
||||
}
|
||||
process.kill(state.pid, "SIGTERM");
|
||||
const stopped = await waitForProcessExit(state.pid, serviceStopTimeoutMs);
|
||||
if (!stopped && isProcessRunning(state.pid)) {
|
||||
throw new Error(`CCR service pid ${state.pid} did not stop within ${serviceStopTimeoutMs}ms.`);
|
||||
|
||||
await callServiceRpc(state, "quitApp");
|
||||
const stopped = verification.trustedPid
|
||||
? await waitForProcessExit(state.pid, serviceStopTimeoutMs)
|
||||
: await waitForServiceUnavailable(state, serviceStopTimeoutMs);
|
||||
if (!stopped) {
|
||||
throw new Error(`CCR service did not stop within ${serviceStopTimeoutMs}ms.`);
|
||||
}
|
||||
clearServiceState(state.pid);
|
||||
process.stdout.write("CCR service stopped.\n");
|
||||
}
|
||||
|
||||
function printHelp(exitCode: number): void {
|
||||
const command = cliCommandName();
|
||||
const output = [
|
||||
"Usage:",
|
||||
" ccr start [--host <host>] [--port <port>] [--open] [--no-gateway]",
|
||||
" ccr stop",
|
||||
" ccr <profile-name-or-id> [cli|app] [-- <agent args>]",
|
||||
` ${command} start [--host <host>] [--port <port>] [--open] [--no-gateway]`,
|
||||
` ${command} ui [--host <host>] [--port <port>] [--no-gateway]`,
|
||||
` ${command} stop`,
|
||||
` ${command} <profile-name-or-id> [cli|app] [-- <agent args>]`,
|
||||
"",
|
||||
"Examples:",
|
||||
" ccr start",
|
||||
" ccr stop",
|
||||
" ccr Codex",
|
||||
" ccr default-codex -- --model gpt-5-codex",
|
||||
" ccr default-codex app"
|
||||
` ${command} start`,
|
||||
` ${command} ui`,
|
||||
` ${command} stop`,
|
||||
` ${command} Codex`,
|
||||
` ${command} default-codex -- --model gpt-5-codex`,
|
||||
` ${command} default-codex app`
|
||||
].join("\n");
|
||||
const stream = exitCode === 0 ? process.stdout : process.stderr;
|
||||
stream.write(`${output}\n`);
|
||||
|
|
@ -423,16 +472,42 @@ function printHelp(exitCode: number): void {
|
|||
}
|
||||
|
||||
function printStartHelp(exitCode: number): void {
|
||||
const command = cliCommandName();
|
||||
const output = [
|
||||
"Usage:",
|
||||
" ccr start [--host <host>] [--port <port>] [--open] [--no-gateway]",
|
||||
` ${command} start [--host <host>] [--port <port>] [--open] [--no-gateway]`,
|
||||
"",
|
||||
"Options:",
|
||||
" --host <host> Management server host. Defaults to 127.0.0.1.",
|
||||
" --port <port> Management server port. Defaults to 3458.",
|
||||
" --open Open the management page in the default browser.",
|
||||
" --no-open Do not open the management page.",
|
||||
" --no-gateway Start only the web management server."
|
||||
" --no-gateway Start only the web management server.",
|
||||
"",
|
||||
"Environment:",
|
||||
" CCR_WEB_AUTH_TOKEN Use this token for management UI and RPC authentication."
|
||||
].join("\n");
|
||||
const stream = exitCode === 0 ? process.stdout : process.stderr;
|
||||
stream.write(`${output}\n`);
|
||||
process.exitCode = exitCode;
|
||||
}
|
||||
|
||||
function printUiHelp(exitCode: number): void {
|
||||
const command = cliCommandName();
|
||||
const output = [
|
||||
"Usage:",
|
||||
` ${command} ui [--host <host>] [--port <port>] [--no-gateway]`,
|
||||
"",
|
||||
"Starts the background CCR service if needed and opens the management UI in the default browser.",
|
||||
"",
|
||||
"Options:",
|
||||
" --host <host> Management server host. Defaults to 127.0.0.1.",
|
||||
" --port <port> Management server port. Defaults to 3458.",
|
||||
" --no-open Start or find the service and print the management URL without opening a browser.",
|
||||
" --no-gateway Start only the web management server when the service is not already running.",
|
||||
"",
|
||||
"Environment:",
|
||||
" CCR_WEB_AUTH_TOKEN Use this token for management UI and RPC authentication."
|
||||
].join("\n");
|
||||
const stream = exitCode === 0 ? process.stdout : process.stderr;
|
||||
stream.write(`${output}\n`);
|
||||
|
|
@ -440,11 +515,12 @@ function printStartHelp(exitCode: number): void {
|
|||
}
|
||||
|
||||
function printStopHelp(exitCode: number): void {
|
||||
const command = cliCommandName();
|
||||
const output = [
|
||||
"Usage:",
|
||||
" ccr stop",
|
||||
` ${command} stop`,
|
||||
"",
|
||||
"Stops the background CCR service started by `ccr start`."
|
||||
`Stops the background CCR service started by \`${command} start\`.`
|
||||
].join("\n");
|
||||
const stream = exitCode === 0 ? process.stdout : process.stderr;
|
||||
stream.write(`${output}\n`);
|
||||
|
|
@ -452,21 +528,32 @@ function printStopHelp(exitCode: number): void {
|
|||
}
|
||||
|
||||
function printWebHelp(exitCode: number): void {
|
||||
const command = cliCommandName();
|
||||
const output = [
|
||||
"Usage:",
|
||||
" ccr serve [--host <host>] [--port <port>] [--open] [--no-gateway]",
|
||||
` ${command} serve [--host <host>] [--port <port>] [--open] [--no-gateway]`,
|
||||
"",
|
||||
"Options:",
|
||||
" --host <host> Management server host. Defaults to 127.0.0.1.",
|
||||
" --port <port> Management server port. Defaults to 3458.",
|
||||
" --open Open the management page in the default browser.",
|
||||
" --no-gateway Start only the web management server."
|
||||
" --no-gateway Start only the web management server.",
|
||||
"",
|
||||
"Environment:",
|
||||
" CCR_WEB_AUTH_TOKEN Use this token for management UI and RPC authentication."
|
||||
].join("\n");
|
||||
const stream = exitCode === 0 ? process.stdout : process.stderr;
|
||||
stream.write(`${output}\n`);
|
||||
process.exitCode = exitCode;
|
||||
}
|
||||
|
||||
function cliCommandName(): string {
|
||||
const configured = process.env.CCR_CLI_COMMAND_NAME?.trim();
|
||||
return configured && /^[A-Za-z0-9._-]+$/.test(configured)
|
||||
? configured
|
||||
: defaultCliCommandName;
|
||||
}
|
||||
|
||||
function readServiceState(): ServiceState | undefined {
|
||||
const file = serviceStateFile();
|
||||
if (!existsSync(file)) {
|
||||
|
|
@ -481,6 +568,7 @@ function readServiceState(): ServiceState | undefined {
|
|||
return {
|
||||
host: parsed.host,
|
||||
pid,
|
||||
serviceToken: typeof parsed.serviceToken === "string" && parsed.serviceToken.trim() ? parsed.serviceToken.trim() : undefined,
|
||||
startedAt: parsed.startedAt || "",
|
||||
startGateway: parsed.startGateway !== false,
|
||||
url: parsed.url
|
||||
|
|
@ -516,99 +604,11 @@ function currentCliScript(): string {
|
|||
return __filename;
|
||||
}
|
||||
|
||||
function delegateManagedDesktopCliToExternalCli(): number | undefined {
|
||||
if (!isManagedDesktopCliRuntime()) {
|
||||
return undefined;
|
||||
}
|
||||
if (process.env.CCR_MANAGED_CLI_NO_DELEGATE === "1" || process.env.CCR_MANAGED_CLI_DELEGATED === "1") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const externalCcr = findExternalCcrCommand();
|
||||
if (!externalCcr) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const launch = profileLaunchSpawnCommand({
|
||||
args: process.argv.slice(2),
|
||||
command: externalCcr
|
||||
});
|
||||
const result = spawnSync(launch.command, launch.args, {
|
||||
env: {
|
||||
...process.env,
|
||||
CCR_MANAGED_CLI_DELEGATED: "1"
|
||||
},
|
||||
stdio: "inherit",
|
||||
windowsVerbatimArguments: !!launch.windowsVerbatimArguments
|
||||
});
|
||||
if (result.error) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof result.status === "number") {
|
||||
return result.status;
|
||||
}
|
||||
return result.signal === "SIGINT" ? 130 : 1;
|
||||
}
|
||||
|
||||
function isManagedDesktopCliRuntime(): boolean {
|
||||
const script = process.argv[1] || __filename;
|
||||
return samePath(path.resolve(script), path.join(CONFIGDIR, "bin", "ccr-cli.js"));
|
||||
}
|
||||
|
||||
function findExternalCcrCommand(): string | undefined {
|
||||
const pathKey = process.platform === "win32"
|
||||
? Object.keys(process.env).find((key) => key.toLowerCase() === "path") || "Path"
|
||||
: "PATH";
|
||||
const pathValue = process.env[pathKey] || "";
|
||||
const managedBinDir = path.resolve(CONFIGDIR, "bin");
|
||||
const names = process.platform === "win32"
|
||||
? ["ccr.cmd", "ccr.exe", "ccr.bat", "ccr"]
|
||||
: ["ccr"];
|
||||
|
||||
for (const rawSegment of pathValue.split(path.delimiter)) {
|
||||
const dir = path.resolve(rawSegment || ".");
|
||||
if (samePath(dir, managedBinDir)) {
|
||||
continue;
|
||||
}
|
||||
for (const name of names) {
|
||||
const candidate = path.join(dir, name);
|
||||
if (isExecutableFile(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isExecutableFile(file: string): boolean {
|
||||
try {
|
||||
const stats = statSync(file);
|
||||
if (!stats.isFile() && !stats.isSymbolicLink()) {
|
||||
return false;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return true;
|
||||
}
|
||||
accessSync(file, fsConstants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.normalize(left);
|
||||
const normalizedRight = path.normalize(right);
|
||||
return process.platform === "win32"
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
async function waitForServiceState(pid: number | undefined, timeoutMs: number): Promise<ServiceState | undefined> {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
const state = readServiceState();
|
||||
if (state && (!pid || state.pid === pid) && isProcessRunning(state.pid)) {
|
||||
if (state && (!pid || state.pid === pid) && (await verifyServiceState(state)).ok) {
|
||||
return state;
|
||||
}
|
||||
await delay(150);
|
||||
|
|
@ -640,6 +640,98 @@ function isProcessRunning(pid: number | undefined): boolean {
|
|||
}
|
||||
}
|
||||
|
||||
type ServiceStateVerification =
|
||||
| { ok: true; trustedPid: boolean }
|
||||
| { ok: false };
|
||||
|
||||
type ServiceIdentity = {
|
||||
pid?: unknown;
|
||||
serviceTokenConfigured?: unknown;
|
||||
serviceTokenMatches?: unknown;
|
||||
};
|
||||
|
||||
async function verifyServiceState(state: ServiceState): Promise<ServiceStateVerification> {
|
||||
if (!isProcessRunning(state.pid)) {
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
if (state.serviceToken) {
|
||||
const identity = await callServiceRpc<ServiceIdentity>(state, "getServiceIdentity", [state.serviceToken]).catch(() => undefined);
|
||||
if (identity?.serviceTokenMatches === true && Number(identity.pid) === state.pid) {
|
||||
return { ok: true, trustedPid: true };
|
||||
}
|
||||
return { ok: false };
|
||||
}
|
||||
|
||||
const appInfo = await callServiceRpc<{ name?: unknown }>(state, "getAppInfo").catch(() => undefined);
|
||||
return appInfo?.name === "Claude Code Router"
|
||||
? { ok: true, trustedPid: false }
|
||||
: { ok: false };
|
||||
}
|
||||
|
||||
async function waitForServiceUnavailable(state: ServiceState, timeoutMs: number): Promise<boolean> {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
const appInfo = await callServiceRpc<{ name?: unknown }>(state, "getAppInfo").catch(() => undefined);
|
||||
if (appInfo?.name !== "Claude Code Router") {
|
||||
return true;
|
||||
}
|
||||
await delay(150);
|
||||
}
|
||||
const appInfo = await callServiceRpc<{ name?: unknown }>(state, "getAppInfo").catch(() => undefined);
|
||||
return appInfo?.name !== "Claude Code Router";
|
||||
}
|
||||
|
||||
async function callServiceRpc<T>(state: ServiceState, method: string, args: unknown[] = []): Promise<T> {
|
||||
const endpoint = serviceRpcEndpoint(state.url);
|
||||
const authToken = serviceAuthToken(state.url);
|
||||
if (!endpoint || !authToken) {
|
||||
throw new Error("CCR service state does not include a usable management URL.");
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), serviceRpcTimeoutMs);
|
||||
try {
|
||||
const response = await fetch(endpoint, {
|
||||
body: JSON.stringify({ args, method }),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
[webAuthHeader]: authToken
|
||||
},
|
||||
method: "POST",
|
||||
signal: controller.signal
|
||||
});
|
||||
const payload = await response.json().catch(() => undefined) as { ok?: boolean; value?: T } | undefined;
|
||||
if (!response.ok || !payload?.ok) {
|
||||
throw new Error(`CCR service RPC ${method} failed with HTTP ${response.status}`);
|
||||
}
|
||||
return payload.value as T;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function serviceRpcEndpoint(url: string): string | undefined {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return `${parsed.origin}/api/ccr/rpc`;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function serviceAuthToken(url: string): string {
|
||||
try {
|
||||
return new URL(url).searchParams.get(webAuthQueryParam)?.trim() ?? "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function generateServiceToken(): string {
|
||||
return randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
7
packages/cli/tsconfig.json
Normal file
7
packages/cli/tsconfig.json
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.d.ts"]
|
||||
}
|
||||
21
packages/core/package.json
Normal file
21
packages/core/package.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"name": "@claude-code-router/core",
|
||||
"version": "3.0.3",
|
||||
"private": true,
|
||||
"description": "Claude Code Router core gateway, routing, provider, and storage services.",
|
||||
"main": "dist/main/server.js",
|
||||
"bin": {
|
||||
"ccr-core-server": "dist/main/server.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"dependencies": {
|
||||
"@the-next-ai/ai-gateway": "^1.0.4",
|
||||
"@the-next-ai/bot-gateway-sdk": "^0.1.0",
|
||||
"better-sqlite3": "^12.11.1",
|
||||
"node-forge": "^1.4.0",
|
||||
"pm2": "^6.0.13",
|
||||
"undici": "^7.27.2"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import os from "node:os";
|
||||
import { createRequire } from "node:module";
|
||||
import { existsSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { AppConfig, BotGatewayRuntimeConfig, ProfileConfig, ProfileOpenSurface } from "../shared/app";
|
||||
import { CONFIGDIR } from "./constants";
|
||||
import type { AppConfig, BotGatewayRuntimeConfig, ProfileConfig, ProfileOpenSurface } from "@ccr/core/contracts/app";
|
||||
import { CONFIGDIR } from "@ccr/core/config/constants";
|
||||
|
||||
const requireFromHere = createRequire(__filename);
|
||||
|
||||
|
|
@ -126,6 +127,11 @@ function botGatewaySdkEnv(): Record<string, string> {
|
|||
}
|
||||
|
||||
function resolveBotGatewaySdkModule(): string {
|
||||
const bundled = resolveBundledBotGatewaySdkModule();
|
||||
if (bundled) {
|
||||
return bundled;
|
||||
}
|
||||
|
||||
try {
|
||||
return path.join(path.dirname(requireFromHere.resolve("@the-next-ai/bot-gateway-sdk/package.json")), "dist", "index.js");
|
||||
} catch {
|
||||
|
|
@ -133,6 +139,20 @@ function resolveBotGatewaySdkModule(): string {
|
|||
}
|
||||
}
|
||||
|
||||
function resolveBundledBotGatewaySdkModule(): string {
|
||||
const resourcesPath = (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath;
|
||||
const candidates = [
|
||||
path.join(__dirname, "bot-gateway-sdk", "dist", "index.js"),
|
||||
...(resourcesPath
|
||||
? [
|
||||
path.join(resourcesPath, "app.asar", "dist", "main", "bot-gateway-sdk", "dist", "index.js"),
|
||||
path.join(resourcesPath, "app", "dist", "main", "bot-gateway-sdk", "dist", "index.js")
|
||||
]
|
||||
: [])
|
||||
];
|
||||
return candidates.find((candidate) => existsSync(candidate)) ?? "";
|
||||
}
|
||||
|
||||
function normalizeBotGatewayForWebSocket(bot: BotGatewayRuntimeConfig): BotGatewayRuntimeConfig {
|
||||
const platform = normalizeBotGatewayPlatform(bot.platform);
|
||||
return {
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import type { BotHandoffScanTarget } from "../shared/app";
|
||||
import { windowsSystemCommand } from "./windows-system";
|
||||
import type { BotHandoffScanTarget } from "@ccr/core/contracts/app";
|
||||
import { windowsSystemCommand } from "@ccr/core/platform/windows-system";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
|
|
@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { CONFIGDIR } from "./constants";
|
||||
import { CONFIGDIR } from "@ccr/core/config/constants";
|
||||
import type {
|
||||
BotGatewayQrLoginCancelRequest,
|
||||
BotGatewayQrLoginCancelResult,
|
||||
|
|
@ -11,7 +11,7 @@ import type {
|
|||
BotGatewayQrLoginWaitRequest,
|
||||
BotGatewayQrLoginWaitResult,
|
||||
BotGatewayRuntimeConfig
|
||||
} from "../shared/app";
|
||||
} from "@ccr/core/contracts/app";
|
||||
|
||||
type BotGatewayClientWithRequest = {
|
||||
close?: () => Promise<void> | void;
|
||||
|
|
@ -244,6 +244,7 @@ async function loadBotGatewaySdk(): Promise<BotGatewaySdkModule> {
|
|||
async function importBotGatewaySdk(): Promise<BotGatewaySdkModule> {
|
||||
const candidates = [
|
||||
process.env.CCR_BOT_GATEWAY_SDK_MODULE,
|
||||
resolveBundledBotGatewaySdkModule(),
|
||||
"@the-next-ai/bot-gateway-sdk"
|
||||
].filter((value): value is string => Boolean(value?.trim()));
|
||||
const errors: string[] = [];
|
||||
|
|
@ -261,6 +262,20 @@ async function importBotGatewaySdk(): Promise<BotGatewaySdkModule> {
|
|||
throw new Error(`Unable to load @the-next-ai/bot-gateway-sdk. ${errors.join("; ")}`);
|
||||
}
|
||||
|
||||
function resolveBundledBotGatewaySdkModule(): string {
|
||||
const resourcesPath = (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath;
|
||||
const candidates = [
|
||||
path.join(__dirname, "bot-gateway-sdk", "dist", "index.js"),
|
||||
...(resourcesPath
|
||||
? [
|
||||
path.join(resourcesPath, "app.asar", "dist", "main", "bot-gateway-sdk", "dist", "index.js"),
|
||||
path.join(resourcesPath, "app", "dist", "main", "bot-gateway-sdk", "dist", "index.js")
|
||||
]
|
||||
: [])
|
||||
];
|
||||
return candidates.find((candidate) => existsSync(candidate)) ?? "";
|
||||
}
|
||||
|
||||
function botGatewaySdkImportSpecifier(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import type { AppConfig } from "./app";
|
||||
import { normalizeProfileScopeValue } from "./app";
|
||||
import type { AppConfig } from "@ccr/core/contracts/app";
|
||||
import { normalizeProfileScopeValue } from "@ccr/core/contracts/app";
|
||||
|
||||
export const CLAUDE_APP_FALLBACK_MODEL = "claude-sonnet-4-5";
|
||||
export const CLAUDE_APP_ONE_MILLION_CONTEXT_SUFFIX = "[1m]";
|
||||
|
|
@ -2,16 +2,16 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync }
|
|||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import { resolveRuntimeAppPath } from "./app-paths";
|
||||
import { saveAppConfig } from "./config";
|
||||
import { CONFIGDIR } from "./constants";
|
||||
import { resolveRuntimeAppPath } from "@ccr/core/runtime/app-paths";
|
||||
import { saveAppConfig } from "@ccr/core/config/config";
|
||||
import { CONFIGDIR } from "@ccr/core/config/constants";
|
||||
import {
|
||||
buildClaudeAppGatewayInferenceModels,
|
||||
type ClaudeAppGatewayInferenceModel,
|
||||
type ClaudeAppGatewayModelRouteOptions
|
||||
} from "../shared/claude-app-gateway";
|
||||
import { NO_AVAILABLE_GATEWAY_MODELS_MESSAGE, hasAvailableGatewayModels, type ApiKeyConfig, type AppConfig, type ClaudeAppGatewayApplyResult } from "../shared/app";
|
||||
import { findModelCatalogEntry } from "../server/gateway/model-catalog";
|
||||
} from "@ccr/core/agents/claude-app/gateway-routes";
|
||||
import { NO_AVAILABLE_GATEWAY_MODELS_MESSAGE, hasAvailableGatewayModels, type ApiKeyConfig, type AppConfig, type ClaudeAppGatewayApplyResult } from "@ccr/core/contracts/app";
|
||||
import { findModelCatalogEntry } from "@ccr/core/gateway/model-catalog";
|
||||
|
||||
const CLAUDE_APP_CONFIG_ID = "8f69f2f1-3275-4ad8-9317-4aa7e972f311";
|
||||
const CLAUDE_APP_CONFIG_NAME = "Claude Code Router";
|
||||
|
|
@ -2,12 +2,12 @@ import { spawn, type ChildProcess } from "node:child_process";
|
|||
import { mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { AppConfig, ProfileConfig } from "../shared/app";
|
||||
import { botGatewayProfileEnv } from "./bot-gateway-env";
|
||||
import { prepareClaudeAppCdpUserDataDir, reserveClaudeAppCdpPort, scheduleClaudeAppDesignCdp } from "./claude-app-cdp";
|
||||
import { claudeCodeUtcTimezoneEnvOverride } from "./claude-environment";
|
||||
import { resolveClaudeCodeSettingsFile } from "./profile-launch-core";
|
||||
import { normalizeWindowsDesktopAppCandidate, windowsDesktopAppCandidates } from "./windows-app-discovery";
|
||||
import type { AppConfig, ProfileConfig } from "@ccr/core/contracts/app";
|
||||
import { botGatewayProfileEnv } from "@ccr/core/agents/bot-gateway/env";
|
||||
import { prepareClaudeAppCdpUserDataDir, reserveClaudeAppCdpPort, scheduleClaudeAppDesignCdp } from "@ccr/core/agents/claude-app/cdp";
|
||||
import { claudeCodeUtcTimezoneEnvOverride } from "@ccr/core/agents/claude-code/environment";
|
||||
import { resolveClaudeCodeSettingsFile } from "@ccr/core/profiles/launch-core";
|
||||
import { normalizeWindowsDesktopAppCandidate, windowsDesktopAppCandidates } from "@ccr/core/platform/windows-app-discovery";
|
||||
|
||||
type ClaudeAppLookupResult = {
|
||||
checked: string[];
|
||||
|
|
@ -36,8 +36,12 @@ const windowsClaudeExeNames = [
|
|||
];
|
||||
const windowsClaudePackageKeywords = ["claude", "anthropic"];
|
||||
|
||||
type ClaudeAppCandidateOptions = {
|
||||
allowGenericExecutable?: boolean;
|
||||
};
|
||||
|
||||
export async function launchClaudeAppProfile(configDir: string, profile: ProfileConfig, config?: AppConfig): Promise<ClaudeAppLaunchResult> {
|
||||
const lookup = findInstalledClaudeAppExecutable();
|
||||
const lookup = findInstalledClaudeAppExecutable(profile.appPath);
|
||||
if (!lookup.executable) {
|
||||
throw new Error([
|
||||
"Claude App was not found. Install Claude App or set CLAUDE_APP_PATH to its executable, then try again.",
|
||||
|
|
@ -224,9 +228,14 @@ function claudeElectronUserDataDir(settingsDir: string, profile: ProfileConfig):
|
|||
);
|
||||
}
|
||||
|
||||
function findInstalledClaudeAppExecutable(): ClaudeAppLookupResult {
|
||||
export function findInstalledClaudeAppExecutable(profileAppPath?: string): ClaudeAppLookupResult {
|
||||
const checked: string[] = [];
|
||||
const envCandidate = findFirstExecutable(envClaudeAppPathCandidates(), checked);
|
||||
const profileCandidate = findFirstExecutable(profileClaudeAppPathCandidates(profileAppPath), checked, { allowGenericExecutable: true });
|
||||
if (profileCandidate) {
|
||||
return { checked, executable: profileCandidate };
|
||||
}
|
||||
|
||||
const envCandidate = findFirstExecutable(envClaudeAppPathCandidates(), checked, { allowGenericExecutable: true });
|
||||
if (envCandidate) {
|
||||
return { checked, executable: envCandidate };
|
||||
}
|
||||
|
|
@ -240,13 +249,13 @@ function findInstalledClaudeAppExecutable(): ClaudeAppLookupResult {
|
|||
return { checked, executable: findFirstExecutable(linuxClaudeAppCandidates(), checked) };
|
||||
}
|
||||
|
||||
function findFirstExecutable(candidates: string[], checked: string[]): string | undefined {
|
||||
function findFirstExecutable(candidates: string[], checked: string[], options: ClaudeAppCandidateOptions = {}): string | undefined {
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate || checked.includes(candidate)) {
|
||||
continue;
|
||||
}
|
||||
checked.push(candidate);
|
||||
const executable = normalizeClaudeAppCandidate(candidate);
|
||||
const executable = normalizeClaudeAppCandidate(candidate, options);
|
||||
if (executable) {
|
||||
return executable;
|
||||
}
|
||||
|
|
@ -261,6 +270,11 @@ function envClaudeAppPathCandidates(): string[] {
|
|||
.map(resolveUserPath);
|
||||
}
|
||||
|
||||
function profileClaudeAppPathCandidates(value: string | undefined): string[] {
|
||||
const trimmed = value?.trim() || "";
|
||||
return trimmed ? [resolveUserPath(trimmed)] : [];
|
||||
}
|
||||
|
||||
function macClaudeAppCandidates(): string[] {
|
||||
const roots = [
|
||||
"/Applications",
|
||||
|
|
@ -289,13 +303,20 @@ function windowsClaudeAppCandidates(): string[] {
|
|||
function linuxClaudeAppCandidates(): string[] {
|
||||
return [
|
||||
"/usr/bin/claude",
|
||||
"/usr/bin/claude-desktop",
|
||||
"/usr/local/bin/claude",
|
||||
"/usr/local/bin/claude-desktop",
|
||||
"/opt/Claude/claude",
|
||||
"/opt/Claude/Claude"
|
||||
"/opt/Claude/Claude",
|
||||
"/opt/Claude Desktop/claude",
|
||||
"/opt/Claude Desktop/Claude",
|
||||
"/opt/Claude Desktop/claude-desktop",
|
||||
"/opt/ClaudeDesktop/ClaudeDesktop",
|
||||
"/opt/AnthropicClaude/AnthropicClaude"
|
||||
];
|
||||
}
|
||||
|
||||
function normalizeClaudeAppCandidate(candidate: string): string | undefined {
|
||||
export function normalizeClaudeAppCandidate(candidate: string, options: ClaudeAppCandidateOptions = {}): string | undefined {
|
||||
if (process.platform === "darwin") {
|
||||
if (candidate.endsWith(".app")) {
|
||||
return executableFromMacAppBundle(candidate);
|
||||
|
|
@ -303,9 +324,10 @@ function normalizeClaudeAppCandidate(candidate: string): string | undefined {
|
|||
return isFile(candidate) ? candidate : undefined;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return normalizeWindowsClaudeAppCandidate(candidate);
|
||||
const executable = normalizeWindowsClaudeAppCandidate(candidate);
|
||||
return executable && isAllowedClaudeAppExecutable(executable, options) ? executable : undefined;
|
||||
}
|
||||
return isFile(candidate) ? candidate : undefined;
|
||||
return isFile(candidate) && isAllowedClaudeAppExecutable(candidate, options) ? candidate : undefined;
|
||||
}
|
||||
|
||||
function executableFromMacAppBundle(appPath: string): string | undefined {
|
||||
|
|
@ -358,6 +380,25 @@ function normalizeWindowsClaudeAppCandidate(candidate: string): string | undefin
|
|||
});
|
||||
}
|
||||
|
||||
function isAllowedClaudeAppExecutable(executable: string, options: ClaudeAppCandidateOptions): boolean {
|
||||
if (options.allowGenericExecutable || !isGenericClaudeExecutableName(executable)) {
|
||||
return true;
|
||||
}
|
||||
return hasElectronDesktopAppResources(executable);
|
||||
}
|
||||
|
||||
function isGenericClaudeExecutableName(executable: string): boolean {
|
||||
const name = path.basename(executable).toLowerCase();
|
||||
return name === "claude" || name === "claude.exe";
|
||||
}
|
||||
|
||||
function hasElectronDesktopAppResources(executable: string): boolean {
|
||||
const resourcesDir = path.join(path.dirname(executable), "resources");
|
||||
return isFile(path.join(resourcesDir, "app.asar")) ||
|
||||
isDirectory(path.join(resourcesDir, "app")) ||
|
||||
isDirectory(path.join(resourcesDir, "app.asar.unpacked"));
|
||||
}
|
||||
|
||||
function profileEnv(profile: ProfileConfig): Record<string, string> {
|
||||
return Object.entries(profile.env ?? {}).reduce<Record<string, string>>((result, [key, value]) => {
|
||||
if (isEnvName(key) && typeof value === "string") {
|
||||
|
|
@ -1,3 +1,6 @@
|
|||
export const CLAUDE_CODE_MCP_CONFIG_ENV = "CCR_CLAUDE_CODE_MCP_CONFIG";
|
||||
export const CODEXL_CLAUDE_CODE_MCP_CONFIG_ENV = "CODEXL_CLAUDE_CODE_MCP_CONFIG";
|
||||
|
||||
const chinaTimeZones = new Set([
|
||||
"asia/chongqing",
|
||||
"asia/chungking",
|
||||
|
|
@ -9,6 +12,15 @@ const chinaTimeZones = new Set([
|
|||
"prc"
|
||||
]);
|
||||
|
||||
export function claudeCodeMcpConfigEnv(configFile: string | undefined): Record<string, string> {
|
||||
return configFile
|
||||
? {
|
||||
[CLAUDE_CODE_MCP_CONFIG_ENV]: configFile,
|
||||
[CODEXL_CLAUDE_CODE_MCP_CONFIG_ENV]: configFile
|
||||
}
|
||||
: {};
|
||||
}
|
||||
|
||||
export function claudeCodeUtcTimezoneEnvOverride(timeZone = currentTimeZone()): Record<string, string> {
|
||||
return isChinaTimeZone(timeZone) ? { TZ: "UTC" } : {};
|
||||
}
|
||||
|
|
@ -1,15 +1,15 @@
|
|||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { AppConfig, ProfileConfig } from "../shared/app";
|
||||
import { botGatewayProfileEnv } from "./bot-gateway-env";
|
||||
import { codexModelCatalogJson } from "./codex-model-catalog";
|
||||
import { buildProfileLaunchPlan, resolveCodexConfigFile } from "./profile-launch-core";
|
||||
import { normalizeWindowsDesktopAppCandidate, windowsDesktopAppCandidates } from "./windows-app-discovery";
|
||||
import { writeZcodeGatewayConfig, zcodeHomeFromConfigFile } from "./zcode-profile-config";
|
||||
import type { AppConfig, ProfileConfig } from "@ccr/core/contracts/app";
|
||||
import { botGatewayProfileEnv } from "@ccr/core/agents/bot-gateway/env";
|
||||
import { codexModelCatalogJson } from "@ccr/core/agents/codex/model-catalog";
|
||||
import { buildProfileLaunchPlan, resolveCodexConfigFile } from "@ccr/core/profiles/launch-core";
|
||||
import { normalizeWindowsDesktopAppCandidate, windowsDesktopAppCandidates } from "@ccr/core/platform/windows-app-discovery";
|
||||
import { writeZcodeGatewayConfig, zcodeHomeFromConfigFile } from "@ccr/core/agents/zcode/profile-config";
|
||||
|
||||
type CodexAppLookupResult = {
|
||||
export type CodexAppLookupResult = {
|
||||
checked: string[];
|
||||
executable?: string;
|
||||
};
|
||||
|
|
@ -47,13 +47,21 @@ export type CodexCompatibleAppModelCatalogWriteResult = {
|
|||
userDataDir: string;
|
||||
};
|
||||
|
||||
export const codexDesktopAppName = "ChatGPT";
|
||||
|
||||
const codexAppSpec: CodexCompatibleAppSpec = {
|
||||
bundledCliNames: ["codex", "Codex", "OpenAI Codex"],
|
||||
defaultCliCommand: "codex",
|
||||
displayName: "Codex App",
|
||||
envPathKeys: ["CCR_CODEX_APP_PATH", "CODEX_APP_PATH", "CODEXL_CODEX_PATH"],
|
||||
displayName: codexDesktopAppName,
|
||||
envPathKeys: ["CCR_CHATGPT_APP_PATH", "CHATGPT_APP_PATH", "CODEXL_CHATGPT_PATH", "CCR_CODEX_APP_PATH", "CODEX_APP_PATH", "CODEXL_CODEX_PATH"],
|
||||
kind: "codex",
|
||||
linuxCandidates: [
|
||||
"/opt/ChatGPT/chatgpt",
|
||||
"/opt/ChatGPT/ChatGPT",
|
||||
"/opt/OpenAI ChatGPT/chatgpt",
|
||||
"/opt/OpenAI ChatGPT/ChatGPT",
|
||||
"/usr/local/bin/chatgpt-app",
|
||||
"/usr/bin/chatgpt-app",
|
||||
"/opt/Codex/codex",
|
||||
"/opt/Codex/Codex",
|
||||
"/opt/OpenAI Codex/codex",
|
||||
|
|
@ -61,11 +69,18 @@ const codexAppSpec: CodexCompatibleAppSpec = {
|
|||
"/usr/local/bin/codex-app",
|
||||
"/usr/bin/codex-app"
|
||||
],
|
||||
macAppNames: ["Codex.app", "OpenAI Codex.app"],
|
||||
macAppNames: ["ChatGPT.app", "OpenAI ChatGPT.app", "Codex.app", "OpenAI Codex.app"],
|
||||
modelCatalogFilename: "ccr-codex-model-catalog.json",
|
||||
userDataDirName: "codex-app-user-data",
|
||||
windowsAppDirs: ["Codex", "OpenAI Codex", "OpenAICodex"],
|
||||
windowsAppDirs: ["ChatGPT", "OpenAI ChatGPT", "OpenAIChatGPT", "Codex", "OpenAI Codex", "OpenAICodex"],
|
||||
windowsExeNames: [
|
||||
"ChatGPT.exe",
|
||||
"chatgpt.exe",
|
||||
"OpenAI ChatGPT.exe",
|
||||
"OpenAIChatGPT.exe",
|
||||
"OpenAIChatGPTApp.exe",
|
||||
"chatgpt-app.exe",
|
||||
"openai-chatgpt.exe",
|
||||
"Codex.exe",
|
||||
"codex.exe",
|
||||
"OpenAI Codex.exe",
|
||||
|
|
@ -74,9 +89,16 @@ const codexAppSpec: CodexCompatibleAppSpec = {
|
|||
"codex-app.exe",
|
||||
"openai-codex.exe"
|
||||
],
|
||||
windowsPackageKeywords: ["codex", "openaicodex"],
|
||||
windowsPackageKeywords: ["chatgpt", "openaichatgpt", "codex", "openaicodex"],
|
||||
windowsVendorDirs: ["OpenAI"],
|
||||
windowsWhereNames: [
|
||||
"ChatGPT",
|
||||
"chatgpt",
|
||||
"OpenAI ChatGPT",
|
||||
"OpenAIChatGPT",
|
||||
"OpenAIChatGPTApp",
|
||||
"chatgpt-app",
|
||||
"openai-chatgpt",
|
||||
"Codex",
|
||||
"codex",
|
||||
"OpenAI Codex",
|
||||
|
|
@ -135,6 +157,10 @@ export function launchCodexAppProfile(configDir: string, profile: ProfileConfig,
|
|||
return launchCodexCompatibleAppProfile(configDir, profile, codexAppSpec, config);
|
||||
}
|
||||
|
||||
export function findInstalledCodexAppExecutable(profileAppPath?: string): CodexAppLookupResult {
|
||||
return findInstalledCodexCompatibleAppExecutable(codexAppSpec, profileAppPath);
|
||||
}
|
||||
|
||||
export function launchZcodeAppProfile(configDir: string, profile: ProfileConfig, config?: AppConfig): CodexAppLaunchResult {
|
||||
return launchCodexCompatibleAppProfile(configDir, profile, zcodeAppSpec, config);
|
||||
}
|
||||
|
|
@ -164,6 +190,9 @@ export function writeCodexCompatibleAppModelCatalog(
|
|||
const spec = profile.agent === "zcode" ? zcodeAppSpec : codexAppSpec;
|
||||
const configFile = resolveCodexConfigFile(configDir, profile);
|
||||
const codexHome = codexCompatibleHomeFromConfigFile(spec, configFile);
|
||||
if (spec.kind === "codex") {
|
||||
removeLegacyCodexVirtualAuthMarker(codexHome);
|
||||
}
|
||||
const userDataDir = codexElectronUserDataDir(codexHome, profile, spec);
|
||||
mkdirSync(userDataDir, { recursive: true });
|
||||
const file = codexAppModelCatalogFile(userDataDir, spec);
|
||||
|
|
@ -175,13 +204,37 @@ export function writeCodexCompatibleAppModelCatalog(
|
|||
return { changed: previous !== content, file, userDataDir };
|
||||
}
|
||||
|
||||
export function removeLegacyCodexVirtualAuthMarker(codexHome: string): boolean {
|
||||
const authFile = path.join(codexHome, "auth.json");
|
||||
if (!isFile(authFile)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const value = JSON.parse(readFileSync(authFile, "utf8")) as Record<string, unknown>;
|
||||
const keys = Object.keys(value).sort();
|
||||
if (
|
||||
keys.length !== 2 ||
|
||||
keys[0] !== "OPENAI_API_KEY" ||
|
||||
keys[1] !== "auth_mode" ||
|
||||
value.auth_mode !== "apikey" ||
|
||||
value.OPENAI_API_KEY !== "ccr-local-profile"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
unlinkSync(authFile);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function launchCodexCompatibleAppProfile(
|
||||
configDir: string,
|
||||
profile: ProfileConfig,
|
||||
spec: CodexCompatibleAppSpec,
|
||||
config?: AppConfig
|
||||
): CodexAppLaunchResult {
|
||||
const lookup = findInstalledCodexAppExecutable(spec);
|
||||
const lookup = findInstalledCodexCompatibleAppExecutable(spec, profile.appPath);
|
||||
if (!lookup.executable) {
|
||||
throw new Error([
|
||||
`${spec.displayName} was not found. Install ${spec.displayName} or set ${spec.envPathKeys[1]} to its executable, then try again.`,
|
||||
|
|
@ -218,7 +271,7 @@ function launchCodexCompatibleAppProfile(
|
|||
delete env.CODEXL_ZCODE_MODEL_CATALOG_B64;
|
||||
sanitizeCodexCompatibleAppEnv(env, spec.kind);
|
||||
|
||||
const launch = codexAppLaunchCommand(lookup.executable, userDataDir, appEnv);
|
||||
const launch = codexAppLaunchCommand(lookup.executable, userDataDir);
|
||||
const child = spawn(launch.command, launch.args, {
|
||||
detached: true,
|
||||
env,
|
||||
|
|
@ -255,6 +308,9 @@ function codexProfileEnv(profile: ProfileConfig, appExecutable: string, spec: Co
|
|||
}
|
||||
return {
|
||||
...(profile.model.trim() ? { CCR_CODEX_MODEL: profile.model.trim() } : {}),
|
||||
...(process.env.CCR_CODEX_CLI_MIDDLEWARE_LOG?.trim()
|
||||
? { CCR_CODEX_CLI_MIDDLEWARE_LOG: process.env.CCR_CODEX_CLI_MIDDLEWARE_LOG.trim() }
|
||||
: {}),
|
||||
CCR_CODEX_MODEL_PROVIDER: providerId,
|
||||
CCR_CODEX_PROFILE: providerId,
|
||||
CCR_CODEX_REMOTE_FRONTEND_MODE: remoteFrontendMode,
|
||||
|
|
@ -351,34 +407,13 @@ function codexElectronArgs(userDataDir: string): string[] {
|
|||
];
|
||||
}
|
||||
|
||||
function codexAppLaunchCommand(executable: string, userDataDir: string, env: Record<string, string>): { args: string[]; command: string; pidIsLauncher?: boolean } {
|
||||
const appBundle = process.platform === "darwin" ? macAppBundleFromExecutable(executable) : undefined;
|
||||
if (appBundle) {
|
||||
return {
|
||||
command: "/usr/bin/open",
|
||||
pidIsLauncher: true,
|
||||
args: [
|
||||
"-W",
|
||||
"-n",
|
||||
...macOpenEnvArgs(env),
|
||||
appBundle,
|
||||
"--args",
|
||||
...codexElectronArgs(userDataDir)
|
||||
]
|
||||
};
|
||||
}
|
||||
function codexAppLaunchCommand(executable: string, userDataDir: string): { args: string[]; command: string; pidIsLauncher?: boolean } {
|
||||
return {
|
||||
command: executable,
|
||||
args: codexElectronArgs(userDataDir)
|
||||
};
|
||||
}
|
||||
|
||||
function macOpenEnvArgs(env: Record<string, string>): string[] {
|
||||
return Object.entries(env)
|
||||
.filter(([key, value]) => isEnvName(key) && typeof value === "string")
|
||||
.flatMap(([key, value]) => ["--env", `${key}=${value}`]);
|
||||
}
|
||||
|
||||
function macAppBundleFromExecutable(executable: string): string | undefined {
|
||||
const marker = ".app/Contents/MacOS/";
|
||||
const index = executable.indexOf(marker);
|
||||
|
|
@ -389,10 +424,6 @@ function macAppBundleFromExecutable(executable: string): string | undefined {
|
|||
return isDirectory(appBundle) ? appBundle : undefined;
|
||||
}
|
||||
|
||||
function isEnvName(value: string): boolean {
|
||||
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
|
||||
}
|
||||
|
||||
function codexElectronUserDataDir(codexHome: string, profile: ProfileConfig, spec: CodexCompatibleAppSpec): string {
|
||||
return path.join(
|
||||
codexHome,
|
||||
|
|
@ -410,8 +441,13 @@ function codexCompatibleHomeFromConfigFile(spec: CodexCompatibleAppSpec, configF
|
|||
return spec.kind === "zcode" ? zcodeHomeFromConfigFile(configFile) : path.dirname(configFile);
|
||||
}
|
||||
|
||||
function findInstalledCodexAppExecutable(spec: CodexCompatibleAppSpec): CodexAppLookupResult {
|
||||
function findInstalledCodexCompatibleAppExecutable(spec: CodexCompatibleAppSpec, profileAppPath?: string): CodexAppLookupResult {
|
||||
const checked: string[] = [];
|
||||
const profileCandidate = findFirstExecutable(profileCodexAppPathCandidates(profileAppPath), checked, spec);
|
||||
if (profileCandidate) {
|
||||
return { checked, executable: profileCandidate };
|
||||
}
|
||||
|
||||
const envCandidate = findFirstExecutable(envCodexAppPathCandidates(spec), checked, spec);
|
||||
if (envCandidate) {
|
||||
return { checked, executable: envCandidate };
|
||||
|
|
@ -447,6 +483,11 @@ function envCodexAppPathCandidates(spec: CodexCompatibleAppSpec): string[] {
|
|||
.map(resolveUserPath);
|
||||
}
|
||||
|
||||
function profileCodexAppPathCandidates(value: string | undefined): string[] {
|
||||
const trimmed = value?.trim() || "";
|
||||
return trimmed ? [resolveUserPath(trimmed)] : [];
|
||||
}
|
||||
|
||||
function macCodexAppCandidates(spec: CodexCompatibleAppSpec): string[] {
|
||||
const roots = [
|
||||
"/Applications",
|
||||
|
|
@ -18,6 +18,8 @@ const REQUEST_TIMEOUT_MS = numberEnv("CCR_CODEX_APP_REQUEST_TIMEOUT_MS", 10 * 60
|
|||
const TURN_IDLE_TIMEOUT_MS = numberEnv("CCR_CODEX_CLAUDE_TURN_IDLE_TIMEOUT_MS", 10 * 60 * 1000);
|
||||
const CONFIG_DIR = resolveConfigDir();
|
||||
const LOG_PATH = process.env.CCR_CODEX_CLI_MIDDLEWARE_LOG || "";
|
||||
const CLAUDE_CODE_MCP_CONFIG_ENV = "CCR_CLAUDE_CODE_MCP_CONFIG";
|
||||
const CODEXL_CLAUDE_CODE_MCP_CONFIG_ENV = "CODEXL_CLAUDE_CODE_MCP_CONFIG";
|
||||
const CLAUDE_CODE_CHINA_TIME_ZONES = new Set([
|
||||
"asia/chongqing",
|
||||
"asia/chungking",
|
||||
|
|
@ -28,6 +30,11 @@ const CLAUDE_CODE_CHINA_TIME_ZONES = new Set([
|
|||
"china standard time",
|
||||
"prc"
|
||||
]);
|
||||
const ACCOUNT_REMOTE_PLUGIN_MARKETPLACE_KINDS = new Set([
|
||||
"created-by-me-remote",
|
||||
"shared-with-me",
|
||||
"workspace-directory"
|
||||
]);
|
||||
let BOT_BRIDGE_INSTANCE = null;
|
||||
|
||||
function claudeCodeUtcTimezoneEnvOverride() {
|
||||
|
|
@ -147,6 +154,11 @@ async function runClaudeCodeCliWrapper(args) {
|
|||
}
|
||||
|
||||
function claudeCodeCliWrapperArgs(args) {
|
||||
const modelArgs = claudeCodeArgsWithModel(args);
|
||||
return claudeCodeArgsWithMcpConfig(modelArgs, process.env);
|
||||
}
|
||||
|
||||
function claudeCodeArgsWithModel(args) {
|
||||
const model = nonEmptyEnv("CCR_CLAUDE_CODE_MODEL") || nonEmptyEnv("CODEXL_CLAUDE_CODE_MODEL") || nonEmptyEnv("ANTHROPIC_MODEL");
|
||||
if (!model || claudeCodeArgsHaveModel(args) || claudeCodeArgsShouldSkipModelInjection(args)) {
|
||||
return args;
|
||||
|
|
@ -154,6 +166,14 @@ function claudeCodeCliWrapperArgs(args) {
|
|||
return ["--model", model, ...args];
|
||||
}
|
||||
|
||||
function claudeCodeArgsWithMcpConfig(args, env) {
|
||||
const mcpConfig = nonEmptyEnvFrom(env, CLAUDE_CODE_MCP_CONFIG_ENV) || nonEmptyEnvFrom(env, CODEXL_CLAUDE_CODE_MCP_CONFIG_ENV);
|
||||
if (!mcpConfig || claudeCodeArgsHaveMcpConfig(args) || claudeCodeArgsShouldSkipModelInjection(args)) {
|
||||
return args;
|
||||
}
|
||||
return ["--mcp-config", mcpConfig, ...args];
|
||||
}
|
||||
|
||||
function claudeCodeArgsHaveModel(args) {
|
||||
for (const arg of args) {
|
||||
if (arg === "--model" || arg === "-m" || arg.startsWith("--model=")) {
|
||||
|
|
@ -163,6 +183,15 @@ function claudeCodeArgsHaveModel(args) {
|
|||
return false;
|
||||
}
|
||||
|
||||
function claudeCodeArgsHaveMcpConfig(args) {
|
||||
for (const arg of args) {
|
||||
if (arg === "--mcp-config" || arg.startsWith("--mcp-config=")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function claudeCodeArgsShouldSkipModelInjection(args) {
|
||||
if (args.some((arg) => arg === "--help" || arg === "-h" || arg === "--version" || arg === "-v")) {
|
||||
return true;
|
||||
|
|
@ -207,6 +236,7 @@ function claudeCodeOptionTakesValue(arg) {
|
|||
"--debug-to",
|
||||
"--fallback-model",
|
||||
"--model",
|
||||
"--mcp-config",
|
||||
"--output-format",
|
||||
"--permission-mode",
|
||||
"--resume",
|
||||
|
|
@ -259,16 +289,19 @@ async function runCodexCliMiddleware(args) {
|
|||
return;
|
||||
}
|
||||
|
||||
const cleanupAuthBootstrap = createEphemeralCodexApiKeyBootstrap(runtimeAgent);
|
||||
const child = childProcess.spawn(realCli, realArgs, {
|
||||
env: childEnvForAgent(runtimeAgent),
|
||||
stdio: ["pipe", "pipe", "inherit"]
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
cleanupAuthBootstrap();
|
||||
log("codex_cli_spawn_error", { error: formatError(error) });
|
||||
});
|
||||
|
||||
const requestMap = new Map();
|
||||
const current = { cwd: "" };
|
||||
const chatGptAuth = loadChatGptAuth();
|
||||
const stdinRl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity, terminal: false });
|
||||
stdinRl.on("line", (line) => {
|
||||
const custom = customAppServerLineResponse(line);
|
||||
|
|
@ -278,13 +311,16 @@ async function runCodexCliMiddleware(args) {
|
|||
}
|
||||
const rewritten = rewriteCodexStdinLine(line);
|
||||
trackRequestLine(rewritten, requestMap, current);
|
||||
child.stdin.write(rewritten + "\n");
|
||||
if (!child.stdin.destroyed) child.stdin.write(rewritten + "\n");
|
||||
});
|
||||
stdinRl.on("close", () => {
|
||||
if (!child.stdin.destroyed) child.stdin.end();
|
||||
});
|
||||
stdinRl.on("close", () => child.stdin.end());
|
||||
|
||||
const stdoutRl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity, terminal: false });
|
||||
stdoutRl.on("line", (line) => {
|
||||
const rewritten = rewriteCodexStdoutLine(line, requestMap);
|
||||
cleanupAuthBootstrap();
|
||||
const rewritten = rewriteCodexStdoutLine(line, requestMap, chatGptAuth);
|
||||
botBridge().handleJsonRpcLine(rewritten);
|
||||
if (!shouldSuppressBotBridgeLine(rewritten)) {
|
||||
process.stdout.write(rewritten + "\n");
|
||||
|
|
@ -292,10 +328,65 @@ async function runCodexCliMiddleware(args) {
|
|||
});
|
||||
|
||||
const exit = await waitForChildResult(child);
|
||||
cleanupAuthBootstrap();
|
||||
log("codex_cli_exit", { code: exit.code, signal: exit.signal, exitCode: exit.exitCode });
|
||||
process.exitCode = exit.exitCode;
|
||||
}
|
||||
|
||||
function createEphemeralCodexApiKeyBootstrap(runtimeAgent) {
|
||||
if (runtimeAgent !== "codex") return () => {};
|
||||
const scope = nonEmptyEnv("CCR_PROFILE_SCOPE");
|
||||
if (scope !== "ccr" && scope !== "custom") return () => {};
|
||||
const authFile = path.join(codexRuntimeHome(), "auth.json");
|
||||
if (fs.existsSync(authFile)) return () => {};
|
||||
const temporary = authFile + ".tmp-" + process.pid;
|
||||
let active = false;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(authFile), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(temporary, JSON.stringify({
|
||||
auth_mode: "apikey",
|
||||
OPENAI_API_KEY: "ccr-local-profile"
|
||||
}, null, 2) + "\n", { mode: 0o600 });
|
||||
fs.renameSync(temporary, authFile);
|
||||
active = true;
|
||||
log("codex_auth_bootstrap_created", { authFile });
|
||||
} catch (error) {
|
||||
try {
|
||||
fs.unlinkSync(temporary);
|
||||
} catch {
|
||||
}
|
||||
log("codex_auth_bootstrap_create_error", { authFile, error: formatError(error) });
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (!active) return;
|
||||
try {
|
||||
if (!fs.existsSync(authFile)) {
|
||||
active = false;
|
||||
return;
|
||||
}
|
||||
const value = readJsonFile(authFile);
|
||||
const keys = value && typeof value === "object" ? Object.keys(value).sort() : [];
|
||||
if (
|
||||
keys.length === 2 &&
|
||||
keys[0] === "OPENAI_API_KEY" &&
|
||||
keys[1] === "auth_mode" &&
|
||||
value.auth_mode === "apikey" &&
|
||||
value.OPENAI_API_KEY === "ccr-local-profile"
|
||||
) {
|
||||
fs.unlinkSync(authFile);
|
||||
active = false;
|
||||
log("codex_auth_bootstrap_removed", { authFile });
|
||||
return;
|
||||
}
|
||||
active = false;
|
||||
log("codex_auth_bootstrap_preserved_changed_file", { authFile });
|
||||
} catch (error) {
|
||||
log("codex_auth_bootstrap_remove_error", { authFile, error: formatError(error) });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function runDirectCodexCli(realCli, realArgs) {
|
||||
const runtimeAgent = codexRuntimeAgent();
|
||||
const child = childProcess.spawn(realCli, realArgs, {
|
||||
|
|
@ -371,7 +462,7 @@ function cliConfigString(key, value) {
|
|||
return key + "=\"" + tomlEscape(value) + "\"";
|
||||
}
|
||||
|
||||
function rewriteCodexStdoutLine(line, requestMap) {
|
||||
function rewriteCodexStdoutLine(line, requestMap, chatGptAuth) {
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(line);
|
||||
|
|
@ -382,15 +473,37 @@ function rewriteCodexStdoutLine(line, requestMap) {
|
|||
if (!id || !requestMap.has(id)) return line;
|
||||
const request = requestMap.get(id);
|
||||
requestMap.delete(id);
|
||||
if (value.error) return line;
|
||||
if (value.error) {
|
||||
if (request.method === "model/list" || request.method === "plugin/list") {
|
||||
log("app_server_list_error", { method: request.method, error: value.error });
|
||||
}
|
||||
return line;
|
||||
}
|
||||
if (request.method === "account/read") {
|
||||
value.result = mockAccountRead();
|
||||
value.result = codexAppAccountRead(chatGptAuth);
|
||||
} else if (request.method === "getAuthStatus") {
|
||||
value.result = mockAuthStatus(request.includeToken);
|
||||
value.result = codexAppAuthStatus(chatGptAuth, request.includeToken);
|
||||
} else if (request.method === "thread/list") {
|
||||
value = mergeForeignThreadList(value, request.params);
|
||||
} else if (request.method === "model/list") {
|
||||
value.result = modelList(request.params, value.result);
|
||||
log("app_server_model_list_response", {
|
||||
count: extractModelListItems(value.result).length,
|
||||
nextCursor: value.result && value.result.nextCursor
|
||||
});
|
||||
return line;
|
||||
} else if (request.method === "plugin/list") {
|
||||
const marketplaces = value.result && Array.isArray(value.result.marketplaces) ? value.result.marketplaces : [];
|
||||
log("app_server_plugin_list_response", {
|
||||
marketplaceCount: marketplaces.length,
|
||||
marketplaces: marketplaces.map((marketplace) => ({
|
||||
name: marketplace && marketplace.name,
|
||||
path: marketplace && marketplace.path,
|
||||
pluginCount: marketplace && Array.isArray(marketplace.plugins) ? marketplace.plugins.length : 0
|
||||
}))
|
||||
});
|
||||
return line;
|
||||
} else {
|
||||
return line;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
|
@ -408,6 +521,9 @@ function rewriteCodexStdinLine(line) {
|
|||
if (!value || typeof value !== "object" || typeof value.method !== "string") {
|
||||
return line;
|
||||
}
|
||||
if (value.method === "model/list" || value.method === "plugin/list") {
|
||||
log("app_server_list_request", { method: value.method, params: value.params || {} });
|
||||
}
|
||||
let changed = false;
|
||||
if (normalizeCliAppServerRequest(value)) {
|
||||
changed = true;
|
||||
|
|
@ -752,7 +868,7 @@ function trackRequestLine(line, requestMap, current) {
|
|||
if (!id || !method) return;
|
||||
const cwd = requestWorkspaceCwd(value, method);
|
||||
if (cwd) current.cwd = cwd;
|
||||
if (!["account/read", "getAuthStatus", "thread/list", "config/read", "model/list"].includes(method)) return;
|
||||
if (!["account/read", "getAuthStatus", "thread/list", "config/read", "model/list", "plugin/list"].includes(method)) return;
|
||||
const params = clone(value.params || {});
|
||||
if (method === "thread/list" && current.cwd && !params.codexlWorkspaceCwd) {
|
||||
params.codexlWorkspaceCwd = current.cwd;
|
||||
|
|
@ -771,6 +887,13 @@ function customAppServerLineResponse(line) {
|
|||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (value && typeof value.method === "string") {
|
||||
log("app_server_request", {
|
||||
id: jsonRpcIdKey(value.id),
|
||||
method: value.method,
|
||||
params: value.params || {}
|
||||
});
|
||||
}
|
||||
if (value && value.type === "fetch" && String(value.method || "").toUpperCase() === "POST" && fetchUrlIsTranscribe(value.url)) {
|
||||
return {
|
||||
requestId: value.requestId || value.id || uuid(),
|
||||
|
|
@ -780,9 +903,25 @@ function customAppServerLineResponse(line) {
|
|||
headers: { "content-type": "application/json" }
|
||||
};
|
||||
}
|
||||
if (value && value.method === "plugin/list" && jsonRpcIdKey(value.id) && accountRemoteOnlyPluginList(value.params)) {
|
||||
log("app_server_account_remote_plugin_list_empty", {
|
||||
marketplaceKinds: value.params.marketplaceKinds
|
||||
});
|
||||
return {
|
||||
id: value.id,
|
||||
result: { marketplaces: [], marketplaceLoadErrors: [], featuredPluginIds: [] }
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function accountRemoteOnlyPluginList(params) {
|
||||
const kinds = params && Array.isArray(params.marketplaceKinds)
|
||||
? params.marketplaceKinds.map((kind) => String(kind || "")).filter(Boolean)
|
||||
: [];
|
||||
return kinds.length > 0 && kinds.every((kind) => ACCOUNT_REMOTE_PLUGIN_MARKETPLACE_KINDS.has(kind));
|
||||
}
|
||||
|
||||
function fetchUrlIsTranscribe(url) {
|
||||
const text = String(url || "").trim();
|
||||
if (text === "/transcribe") return true;
|
||||
|
|
@ -1954,7 +2093,7 @@ function claudeCommand(work) {
|
|||
}
|
||||
return {
|
||||
command,
|
||||
args,
|
||||
args: claudeCodeArgsWithMcpConfig(args, env),
|
||||
env
|
||||
};
|
||||
}
|
||||
|
|
@ -2355,8 +2494,12 @@ function configRead(params, values) {
|
|||
model: agentEnv(runtimeAgent, "MODEL") || DEFAULT_MODEL,
|
||||
model_catalog_json: JSON.stringify(modelCatalogConfigValue()),
|
||||
model_provider: agentEnv(runtimeAgent, "MODEL_PROVIDER") || "claude-code",
|
||||
approval_policy: "default",
|
||||
sandbox_mode: "workspace-write"
|
||||
approval_policy: "default"
|
||||
// sandbox_mode intentionally omitted: let Codex read it from its own
|
||||
// config.toml (e.g. [windows] sandbox) instead of forcing workspace-write.
|
||||
// Forcing workspace-write triggers codex-windows-sandbox-setup.exe on every
|
||||
// command, which fails on systems where the COM+ catalog is unavailable
|
||||
// (see openai/codex#29332), surfacing as repeated error dialogs.
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -2434,15 +2577,83 @@ function configWriteResponse(params) {
|
|||
return { config: params.config || null, ok: true };
|
||||
}
|
||||
|
||||
function loadChatGptAuth() {
|
||||
const workspaceName = nonEmptyEnv("CCR_CODEX_WORKSPACE_NAME") ||
|
||||
nonEmptyEnv("CODEXL_CODEX_WORKSPACE_NAME") ||
|
||||
nonEmptyEnv("CODEXL_CODEX_INSTANCE_NAME") ||
|
||||
agentEnv("codex", "PROFILE");
|
||||
const fallback = {
|
||||
authToken: "",
|
||||
email: "",
|
||||
planType: "",
|
||||
workspaceName
|
||||
};
|
||||
const value = readJsonFile(path.join(codexRuntimeHome(), "auth.json"));
|
||||
if (!value || !isPlainObject(value)) return fallback;
|
||||
if (typeof value.auth_mode === "string" && value.auth_mode !== "chatgpt") return fallback;
|
||||
if (!isPlainObject(value.tokens)) return fallback;
|
||||
|
||||
const authToken = stringValue(value.tokens.access_token);
|
||||
const idToken = stringValue(value.tokens.id_token);
|
||||
const claims = jwtPayloadClaims(authToken) || jwtPayloadClaims(idToken) || {};
|
||||
const profileClaims = isPlainObject(claims["https://api.openai.com/profile"])
|
||||
? claims["https://api.openai.com/profile"]
|
||||
: {};
|
||||
const authClaims = isPlainObject(claims["https://api.openai.com/auth"])
|
||||
? claims["https://api.openai.com/auth"]
|
||||
: {};
|
||||
return {
|
||||
authToken,
|
||||
email: stringValue(profileClaims.email) || stringValue(claims.email) || stringValue(value.email),
|
||||
planType: stringValue(authClaims.chatgpt_plan_type) || stringValue(claims.chatgpt_plan_type),
|
||||
workspaceName
|
||||
};
|
||||
}
|
||||
|
||||
function jwtPayloadClaims(token) {
|
||||
if (!token) return undefined;
|
||||
const payload = String(token).split(".")[1];
|
||||
if (!payload) return undefined;
|
||||
try {
|
||||
const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
|
||||
const value = JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
|
||||
return isPlainObject(value) ? value : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function codexAppAccountRead(auth) {
|
||||
return {
|
||||
account: {
|
||||
type: "chatgpt",
|
||||
email: auth.email || auth.workspaceName || "codex",
|
||||
planType: auth.planType || "unknown"
|
||||
},
|
||||
requiresOpenaiAuth: true
|
||||
};
|
||||
}
|
||||
|
||||
function codexAppAuthStatus(auth, includeToken) {
|
||||
const result = {
|
||||
authMethod: "chatgpt",
|
||||
requiresOpenaiAuth: true
|
||||
};
|
||||
if (includeToken) result.authToken = auth.authToken || null;
|
||||
return result;
|
||||
}
|
||||
|
||||
function mockAccountRead() {
|
||||
const runtimeAgent = codexRuntimeAgent();
|
||||
const email = agentEnv(runtimeAgent, "WORKSPACE_NAME") || (runtimeAgent === "zcode" ? "ZCode" : "Claude Code");
|
||||
return { account: { type: "chatgpt", email, planType: "unknown" }, requiresOpenaiAuth: false };
|
||||
return {
|
||||
account: { type: "amazonBedrock", credentialSource: "codexManaged" },
|
||||
requiresOpenaiAuth: false
|
||||
};
|
||||
}
|
||||
|
||||
function mockAuthStatus(includeToken) {
|
||||
const result = { authMethod: "chatgpt", account: mockAccountRead().account, requiresOpenaiAuth: false };
|
||||
if (includeToken) result.authToken = null;
|
||||
const result = { authMethod: "amazonBedrock", authToken: null, requiresOpenaiAuth: false };
|
||||
if (includeToken) result.authToken = "ccr-local-profile";
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
@ -2490,7 +2701,7 @@ function claudeControlPermissionResponse(message, requestId, approval) {
|
|||
const allows = permissionResponseAllows(approval);
|
||||
const response = allows
|
||||
? { behavior: "allow", updatedInput: pointer(message, "/request/input") || pointer(message, "/params/input") || {} }
|
||||
: { behavior: "deny", message: "Denied in Codex App" };
|
||||
: { behavior: "deny", message: "Denied in ChatGPT" };
|
||||
const toolUseId = firstString(message, ["/request/tool_use_id", "/request/toolUseId", "/params/tool_use_id"]);
|
||||
if (toolUseId) response.toolUseID = toolUseId;
|
||||
return { type: "control_response", response: { subtype: "success", request_id: requestId, response } };
|
||||
|
|
@ -2510,7 +2721,7 @@ async function waitForAppResponse(map, requestId, timeoutMs) {
|
|||
}
|
||||
await sleep(100);
|
||||
}
|
||||
throw new Error("Timed out waiting for Codex App response: " + requestId);
|
||||
throw new Error("Timed out waiting for ChatGPT response: " + requestId);
|
||||
}
|
||||
|
||||
function permissionResponseAllows(value) {
|
||||
|
|
@ -3246,6 +3457,10 @@ async function importBotGatewaySdk() {
|
|||
if (configured) {
|
||||
candidates.push(configured);
|
||||
}
|
||||
const bundled = bundledBotGatewaySdkModule();
|
||||
if (bundled) {
|
||||
candidates.push(bundled);
|
||||
}
|
||||
candidates.push("@the-next-ai/bot-gateway-sdk");
|
||||
const errors = [];
|
||||
for (const candidate of candidates) {
|
||||
|
|
@ -3262,6 +3477,20 @@ async function importBotGatewaySdk() {
|
|||
throw new Error("Unable to load @the-next-ai/bot-gateway-sdk. " + errors.join("; "));
|
||||
}
|
||||
|
||||
function bundledBotGatewaySdkModule() {
|
||||
const resourcesPath = process["resourcesPath"];
|
||||
const candidates = [
|
||||
path.join(__dirname, "bot-gateway-sdk", "dist", "index.js"),
|
||||
...(resourcesPath
|
||||
? [
|
||||
path.join(resourcesPath, "app.asar", "dist", "main", "bot-gateway-sdk", "dist", "index.js"),
|
||||
path.join(resourcesPath, "app", "dist", "main", "bot-gateway-sdk", "dist", "index.js")
|
||||
]
|
||||
: [])
|
||||
];
|
||||
return candidates.find((candidate) => fs.existsSync(candidate)) || "";
|
||||
}
|
||||
|
||||
function botGatewaySdkImportSpecifier(value) {
|
||||
const trimmed = String(value || "").trim();
|
||||
if (!trimmed) return "@the-next-ai/bot-gateway-sdk";
|
||||
|
|
@ -4228,6 +4457,11 @@ function nonEmptyEnv(name) {
|
|||
return typeof value === "string" && value.trim() ? value.trim() : "";
|
||||
}
|
||||
|
||||
function nonEmptyEnvFrom(env, name) {
|
||||
const value = env?.[name];
|
||||
return typeof value === "string" && value.trim() ? value.trim() : "";
|
||||
}
|
||||
|
||||
function codexRuntimeAgent() {
|
||||
return nonEmptyEnv("CCR_ZCODE_PROFILE") ||
|
||||
nonEmptyEnv("CODEXL_ZCODE_PROFILE") ||
|
||||
|
|
@ -1,11 +1,14 @@
|
|||
import { BUILTIN_FUSION_WEB_SEARCH_TOOL_NAME } from "../shared/app";
|
||||
import type { AppConfig, GatewayProviderConfig, GatewayProviderProtocol, VirtualModelProfileConfig } from "../shared/app";
|
||||
import { BUILTIN_FUSION_WEB_SEARCH_TOOL_NAME } from "@ccr/core/contracts/app";
|
||||
import type { AppConfig, GatewayProviderConfig, GatewayProviderProtocol, ProviderModelMetadata, ProviderReasoningLevel, VirtualModelProfileConfig } from "@ccr/core/contracts/app";
|
||||
import {
|
||||
findModelCatalogEntry,
|
||||
modelCatalogMaxInputTokens,
|
||||
readCatalogCapability,
|
||||
type ModelCatalogEntry
|
||||
} from "../server/gateway/model-catalog";
|
||||
} from "@ccr/core/gateway/model-catalog";
|
||||
import { codexDefaultBaseUrl, readCodexLocalModelCatalog } from "@ccr/core/agents/local-providers/codex";
|
||||
import { localAgentProviderApiKey } from "@ccr/core/agents/local-providers/shared";
|
||||
import { normalizeProviderBaseUrl } from "@ccr/core/providers/url";
|
||||
|
||||
const fusionModelProviderName = "Fusion";
|
||||
const codexDefaultContextWindow = 128_000;
|
||||
|
|
@ -115,13 +118,13 @@ function codexModelCatalogItem(
|
|||
const profile = codexModelCapabilityProfile(model, config);
|
||||
const contextWindow = codexModelContextWindow(model, profile.catalogEntry);
|
||||
return {
|
||||
additional_speed_tiers: [],
|
||||
additional_speed_tiers: profile.additionalSpeedTiers,
|
||||
apply_patch_tool_type: profile.applyPatchToolType,
|
||||
availability_nux: null,
|
||||
base_instructions: "You are Codex, a coding agent.",
|
||||
context_window: contextWindow,
|
||||
default_reasoning_level: profile.supportsReasoning ? "medium" : null,
|
||||
default_reasoning_summary: "none",
|
||||
default_reasoning_level: profile.defaultReasoningLevel,
|
||||
default_reasoning_summary: profile.defaultReasoningSummary,
|
||||
description: `CCR gateway model ${model}`,
|
||||
display_name: model,
|
||||
effective_context_window_percent: codexEffectiveContextWindowPercent,
|
||||
|
|
@ -129,7 +132,7 @@ function codexModelCatalogItem(
|
|||
input_modalities: profile.inputModalities,
|
||||
max_context_window: contextWindow,
|
||||
priority,
|
||||
service_tiers: [],
|
||||
service_tiers: profile.serviceTiers,
|
||||
shell_type: "shell_command",
|
||||
slug: model,
|
||||
support_verbosity: true,
|
||||
|
|
@ -147,10 +150,14 @@ function codexModelCatalogItem(
|
|||
}
|
||||
|
||||
type CodexCapabilityProfile = {
|
||||
additionalSpeedTiers: unknown[];
|
||||
applyPatchToolType: string | null;
|
||||
catalogEntry?: ModelCatalogEntry;
|
||||
defaultReasoningLevel: string | null;
|
||||
defaultReasoningSummary: string;
|
||||
inputModalities: string[];
|
||||
supportedReasoningLevels: Array<{ description: string; effort: string }>;
|
||||
serviceTiers: unknown[];
|
||||
supportsImageInput: boolean;
|
||||
supportsParallelToolCalls: boolean;
|
||||
supportsReasoning: boolean;
|
||||
|
|
@ -162,13 +169,18 @@ function codexModelCapabilityProfile(
|
|||
config?: Partial<Pick<AppConfig, "Providers" | "Router" | "virtualModelProfiles">>
|
||||
): CodexCapabilityProfile {
|
||||
const selector = parseModelSelector(model);
|
||||
const provider = selector?.provider ? findConfiguredProvider(config, selector.provider) : undefined;
|
||||
const provider = selector?.provider ? findConfiguredProvider(config, selector.provider) : findConfiguredProviderForModel(config, model);
|
||||
const providerModel = selector?.model ?? model;
|
||||
const providerModelMetadata = provider
|
||||
? providerModelMetadataFor(provider, providerModel) ?? localCodexModelMetadataFor(provider, providerModel)
|
||||
: undefined;
|
||||
const catalogEntry = findModelCatalogEntry(model);
|
||||
const capabilities = catalogEntry?.capabilities ?? {};
|
||||
const providerProtocol = provider ? codexProviderProtocol(provider) : undefined;
|
||||
const providerSupportsResponses = provider ? codexProviderSupportsResponses(provider) : false;
|
||||
const supportsFusionWebSearch = codexVirtualModelSupportsFusionWebSearch(model, config);
|
||||
const supportsReasoning = readCatalogCapability(capabilities, "reasoning");
|
||||
const metadataReasoningLevels = normalizeProviderReasoningLevels(providerModelMetadata?.supportedReasoningLevels);
|
||||
const supportsReasoning = providerModelMetadata?.supportsReasoningSummaries ?? (metadataReasoningLevels ? true : readCatalogCapability(capabilities, "reasoning"));
|
||||
const supportsImageInput = catalogEntrySupportsImageInput(catalogEntry);
|
||||
const supportsParallelToolCalls = readCatalogCapability(capabilities, "parallelFunctionCalling");
|
||||
const applyPatchToolType = providerSupportsResponses || catalogModelLooksLikeGpt(model, catalogEntry) || codexPatchBridgeApplies(model, catalogEntry, config)
|
||||
|
|
@ -186,10 +198,18 @@ function codexModelCapabilityProfile(
|
|||
);
|
||||
|
||||
return {
|
||||
additionalSpeedTiers: providerModelMetadata?.additionalSpeedTiers ?? [],
|
||||
applyPatchToolType,
|
||||
catalogEntry,
|
||||
defaultReasoningLevel: providerModelMetadata && providerModelMetadata.defaultReasoningLevel !== undefined
|
||||
? providerModelMetadata.defaultReasoningLevel
|
||||
: supportsReasoning
|
||||
? "medium"
|
||||
: null,
|
||||
defaultReasoningSummary: providerModelMetadata?.defaultReasoningSummary ?? "none",
|
||||
inputModalities: supportsImageInput ? ["text", "image"] : ["text"],
|
||||
supportedReasoningLevels: supportsReasoning ? supportedReasoningLevels(capabilities) : [],
|
||||
serviceTiers: providerModelMetadata?.serviceTiers ?? [],
|
||||
supportedReasoningLevels: metadataReasoningLevels ?? (supportsReasoning ? supportedReasoningLevels(capabilities) : []),
|
||||
supportsImageInput,
|
||||
supportsParallelToolCalls,
|
||||
supportsReasoning,
|
||||
|
|
@ -197,6 +217,64 @@ function codexModelCapabilityProfile(
|
|||
};
|
||||
}
|
||||
|
||||
function providerModelMetadataFor(provider: GatewayProviderConfig, model: string): ProviderModelMetadata | undefined {
|
||||
const metadata = provider.modelMetadata ?? {};
|
||||
const direct = metadata[model];
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
const normalized = model.trim().toLowerCase();
|
||||
const match = Object.entries(metadata).find(([candidate]) => candidate.trim().toLowerCase() === normalized);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
function localCodexModelMetadataFor(provider: GatewayProviderConfig, model: string): ProviderModelMetadata | undefined {
|
||||
if (!isLocalCodexProvider(provider)) {
|
||||
return undefined;
|
||||
}
|
||||
return readCodexLocalModelCatalog().modelMetadata?.[model];
|
||||
}
|
||||
|
||||
function isLocalCodexProvider(provider: GatewayProviderConfig): boolean {
|
||||
const baseUrl = providerBaseUrl(provider).trim().replace(/\/+$/g, "");
|
||||
const normalizedBaseUrl = normalizeProviderBaseUrl(baseUrl);
|
||||
const normalizedCodexBaseUrl = normalizeProviderBaseUrl(codexDefaultBaseUrl);
|
||||
return (
|
||||
providerApiKey(provider) === localAgentProviderApiKey &&
|
||||
(
|
||||
baseUrl.toLowerCase() === codexDefaultBaseUrl.toLowerCase() ||
|
||||
baseUrl.toLowerCase().includes("chatgpt.com/backend-api/codex") ||
|
||||
normalizedBaseUrl === normalizedCodexBaseUrl
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function providerBaseUrl(provider: GatewayProviderConfig): string {
|
||||
return provider.api_base_url || provider.baseUrl || provider.baseurl || "";
|
||||
}
|
||||
|
||||
function providerApiKey(provider: GatewayProviderConfig): string {
|
||||
return provider.api_key || provider.apiKey || provider.apikey || "";
|
||||
}
|
||||
|
||||
function normalizeProviderReasoningLevels(levels: ProviderReasoningLevel[] | undefined): Array<{ description: string; effort: string }> | undefined {
|
||||
const normalized = (levels ?? [])
|
||||
.map((level) => ({
|
||||
description: level.description.trim() || effortDescription(level.effort),
|
||||
effort: level.effort.trim()
|
||||
}))
|
||||
.filter((level) => level.effort);
|
||||
return normalized.length > 0 ? normalized : undefined;
|
||||
}
|
||||
|
||||
function effortDescription(effort: string): string {
|
||||
const normalized = effort.trim().toLowerCase();
|
||||
if (normalized === "xhigh") {
|
||||
return "Extra high reasoning";
|
||||
}
|
||||
return `${effort.slice(0, 1).toUpperCase()}${effort.slice(1)} reasoning`;
|
||||
}
|
||||
|
||||
function codexModelContextWindow(model: string, entry = findModelCatalogEntry(model)): number {
|
||||
return modelCatalogMaxInputTokens(entry) || codexDefaultContextWindow;
|
||||
}
|
||||
|
|
@ -233,6 +311,19 @@ function findConfiguredProvider(
|
|||
return (config?.Providers ?? []).find((provider) => provider.name.trim().toLowerCase() === normalized);
|
||||
}
|
||||
|
||||
function findConfiguredProviderForModel(
|
||||
config: Partial<Pick<AppConfig, "Providers" | "virtualModelProfiles">> | undefined,
|
||||
model: string
|
||||
): GatewayProviderConfig | undefined {
|
||||
const normalized = model.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return undefined;
|
||||
}
|
||||
return (config?.Providers ?? []).find((provider) =>
|
||||
provider.models.some((candidate) => candidate.trim().toLowerCase() === normalized)
|
||||
);
|
||||
}
|
||||
|
||||
function codexProviderProtocol(provider: GatewayProviderConfig): GatewayProviderProtocol | undefined {
|
||||
const capabilityProtocols = uniqueProviderProtocols((provider.capabilities ?? []).map((capability) => normalizeProviderProtocol(capability.type)));
|
||||
for (const protocol of ["openai_responses", "openai_chat_completions", "anthropic_messages", "gemini_generate_content", "gemini_interactions"] as GatewayProviderProtocol[]) {
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { execFileSync } from "node:child_process";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type {
|
||||
|
|
@ -5,10 +6,11 @@ import type {
|
|||
LocalAgentProviderImportResult,
|
||||
ProviderAccountConfig,
|
||||
ProviderAccountMappingConfig
|
||||
} from "../../shared/app";
|
||||
} from "@ccr/core/contracts/app";
|
||||
import {
|
||||
bearerAuthPlugin,
|
||||
findOauthTokenSet,
|
||||
isRecord,
|
||||
missingCandidate,
|
||||
providerInternalNamePlaceholder,
|
||||
providerPayload,
|
||||
|
|
@ -16,9 +18,10 @@ import {
|
|||
uniqueProviderName,
|
||||
uniqueStrings,
|
||||
type OAuthTokenSet
|
||||
} from "./shared";
|
||||
} from "@ccr/core/agents/local-providers/shared";
|
||||
|
||||
const claudeDefaultModels = ["claude-sonnet-4-20250514"];
|
||||
const claudeDefaultModels = ["claude-sonnet-5"];
|
||||
const claudeCodeKeychainService = "Claude Code-credentials";
|
||||
|
||||
const percentLimitMapping = (id: string, label: string, path: string, window: string) => ({
|
||||
id,
|
||||
|
|
@ -148,6 +151,19 @@ function readClaudeCodeOauth(): OAuthTokenSet | undefined {
|
|||
sourceFile
|
||||
};
|
||||
}
|
||||
|
||||
const keychainRecord = readClaudeCodeKeychainRecord();
|
||||
if (keychainRecord) {
|
||||
const credential = findOauthTokenSet(keychainRecord);
|
||||
if (credential) {
|
||||
return {
|
||||
accessToken: credential.accessToken,
|
||||
refreshToken: credential.refreshToken,
|
||||
sourceFile: `keychain:${claudeCodeKeychainService}`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
|
@ -158,3 +174,24 @@ function claudeCredentialFiles(): string[] {
|
|||
path.join(os.homedir(), ".config", "claude", "credentials.json")
|
||||
]);
|
||||
}
|
||||
|
||||
// Newer macOS builds of the Claude Code CLI store credentials in the
|
||||
// Keychain instead of ~/.claude/.credentials.json. Reading it triggers the
|
||||
// standard macOS keychain access prompt (Allow / Always Allow); the user
|
||||
// declining or the item not existing both surface as a non-zero exit here.
|
||||
function readClaudeCodeKeychainRecord(): Record<string, unknown> | undefined {
|
||||
if (process.platform !== "darwin") {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const output = execFileSync(
|
||||
"security",
|
||||
["find-generic-password", "-s", claudeCodeKeychainService, "-w"],
|
||||
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
|
||||
);
|
||||
const parsed = JSON.parse(output.trim()) as unknown;
|
||||
return isRecord(parsed) ? parsed : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,18 +3,23 @@ import path from "node:path";
|
|||
import type {
|
||||
LocalAgentProviderCandidate,
|
||||
LocalAgentProviderImportResult,
|
||||
LocalAgentProviderProbeResult,
|
||||
GatewayProviderConfig,
|
||||
ProviderAccountConfig,
|
||||
ProviderAccountConnectorConfig,
|
||||
ProviderAccountMappingConfig,
|
||||
ProviderAccountMeter,
|
||||
ProviderAccountMeterDetail
|
||||
} from "../../shared/app";
|
||||
import { normalizeProviderBaseUrl } from "../../shared/provider-url";
|
||||
ProviderAccountMeterDetail,
|
||||
ProviderModelMetadata,
|
||||
ProviderReasoningLevel
|
||||
} from "@ccr/core/contracts/app";
|
||||
import { normalizeProviderBaseUrl } from "@ccr/core/providers/url";
|
||||
import { fetchWithSystemProxy } from "@ccr/core/proxy/system-proxy-fetch";
|
||||
import {
|
||||
isRecord,
|
||||
localAgentProviderApiKey,
|
||||
missingCandidate,
|
||||
modelMetadataForModels,
|
||||
modelDisplayNamesForModels,
|
||||
providerInternalNamePlaceholder,
|
||||
providerNamePlaceholder,
|
||||
|
|
@ -26,15 +31,17 @@ import {
|
|||
uniqueProviderName,
|
||||
uniqueStrings,
|
||||
type OAuthTokenSet
|
||||
} from "./shared";
|
||||
} from "@ccr/core/agents/local-providers/shared";
|
||||
|
||||
export const codexDefaultBaseUrl = "https://chatgpt.com/backend-api/codex";
|
||||
|
||||
const codexAccountBaseUrl = "https://chatgpt.com/backend-api";
|
||||
const codexDefaultModels = ["gpt-5-codex"];
|
||||
const codexProbeTimeoutMs = 8_000;
|
||||
|
||||
type LocalAgentModelCatalog = {
|
||||
export type LocalAgentModelCatalog = {
|
||||
modelDisplayNames?: Record<string, string>;
|
||||
modelMetadata?: Record<string, ProviderModelMetadata>;
|
||||
models: string[];
|
||||
};
|
||||
|
||||
|
|
@ -233,7 +240,7 @@ const codexAccountTokenUsageMapping: ProviderAccountMappingConfig = {
|
|||
|
||||
export function codexCandidate(): LocalAgentProviderCandidate {
|
||||
const auth = readCodexAuth();
|
||||
const catalog = readCodexModelCatalog();
|
||||
const catalog = readCodexLocalModelCatalog();
|
||||
if (auth?.refreshToken || auth?.accessToken) {
|
||||
return {
|
||||
detail: "ChatGPT login detected. Click Import to add it as a gateway provider.",
|
||||
|
|
@ -241,6 +248,7 @@ export function codexCandidate(): LocalAgentProviderCandidate {
|
|||
importable: true,
|
||||
kind: "codex",
|
||||
modelDisplayNames: catalog.modelDisplayNames,
|
||||
modelMetadata: catalog.modelMetadata,
|
||||
models: catalog.models,
|
||||
name: "Codex API",
|
||||
protocol: "openai_responses",
|
||||
|
|
@ -251,14 +259,15 @@ export function codexCandidate(): LocalAgentProviderCandidate {
|
|||
return missingCandidate("codex", "codex-api", "Codex API", "openai_responses", catalog.models, catalog.modelDisplayNames);
|
||||
}
|
||||
|
||||
export function importCodexProvider(candidate: LocalAgentProviderCandidate, providerNames: string[]): LocalAgentProviderImportResult {
|
||||
export async function importCodexProvider(candidate: LocalAgentProviderCandidate, providerNames: string[]): Promise<LocalAgentProviderImportResult> {
|
||||
const auth = readCodexAuth();
|
||||
if (!auth?.refreshToken && !auth?.accessToken) {
|
||||
throw new Error("Codex login token was not found.");
|
||||
}
|
||||
const provider = providerPayload(candidate, uniqueProviderName(providerNames, "Codex API"), codexDefaultBaseUrl, codexProviderAccountConfig());
|
||||
const probedCandidate = await codexCandidateWithProbedModels(candidate).catch(() => candidate);
|
||||
const provider = providerPayload(probedCandidate, uniqueProviderName(providerNames, "Codex API"), codexDefaultBaseUrl, codexProviderAccountConfig());
|
||||
return {
|
||||
candidate,
|
||||
candidate: probedCandidate,
|
||||
provider,
|
||||
providerPlugins: [
|
||||
codexOauthPlugin("codex-oauth"),
|
||||
|
|
@ -277,8 +286,16 @@ export function importCodexProvider(candidate: LocalAgentProviderCandidate, prov
|
|||
};
|
||||
}
|
||||
|
||||
export async function probeCodexProvider(candidate: LocalAgentProviderCandidate): Promise<LocalAgentProviderProbeResult> {
|
||||
const probedCandidate = await codexCandidateWithProbedModels(candidate).catch(() => candidate);
|
||||
return {
|
||||
candidate: probedCandidate,
|
||||
probe: codexProviderProbe(probedCandidate)
|
||||
};
|
||||
}
|
||||
|
||||
export function readCodexAuth(): OAuthTokenSet | undefined {
|
||||
const sourceFile = path.join(os.homedir(), ".codex", "auth.json");
|
||||
const sourceFile = path.join(codexHomeDir(), ".codex", "auth.json");
|
||||
const record = readJsonRecord(sourceFile);
|
||||
if (!record) {
|
||||
return undefined;
|
||||
|
|
@ -588,33 +605,234 @@ function codexBackendRequestTransform(): Record<string, unknown> {
|
|||
};
|
||||
}
|
||||
|
||||
function readCodexModelCatalog(): LocalAgentModelCatalog {
|
||||
const modelsFile = path.join(os.homedir(), ".codex", "models_cache.json");
|
||||
export function readCodexLocalModelCatalog(): LocalAgentModelCatalog {
|
||||
const modelsFile = path.join(codexHomeDir(), ".codex", "models_cache.json");
|
||||
const record = readJsonRecord(modelsFile);
|
||||
const catalog = codexModelCatalogFromPayload(record);
|
||||
const uniqueModels = uniqueStrings([...catalog.models, ...codexDefaultModels]);
|
||||
return {
|
||||
modelDisplayNames: modelDisplayNamesForModels(catalog.modelDisplayNames, uniqueModels),
|
||||
modelMetadata: modelMetadataForModels(catalog.modelMetadata, uniqueModels),
|
||||
models: uniqueModels
|
||||
};
|
||||
}
|
||||
|
||||
async function codexCandidateWithProbedModels(candidate: LocalAgentProviderCandidate): Promise<LocalAgentProviderCandidate> {
|
||||
const catalog = await fetchCodexModelCatalog();
|
||||
if (catalog.models.length === 0) {
|
||||
return candidate;
|
||||
}
|
||||
return {
|
||||
...candidate,
|
||||
modelDisplayNames: catalog.modelDisplayNames,
|
||||
modelMetadata: catalog.modelMetadata,
|
||||
models: catalog.models
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchCodexModelCatalog(): Promise<LocalAgentModelCatalog> {
|
||||
const auth = readCodexAuth();
|
||||
if (!auth?.accessToken) {
|
||||
throw new Error("Codex access token was not found.");
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), codexProbeTimeoutMs);
|
||||
try {
|
||||
const response = await fetchWithSystemProxy(`${codexDefaultBaseUrl}/models`, {
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
authorization: `Bearer ${auth.accessToken}`,
|
||||
"User-Agent": "codex-cli",
|
||||
...(auth.accountId ? { "ChatGPT-Account-Id": auth.accountId } : {}),
|
||||
...(auth.isFedrampAccount ? { "X-OpenAI-Fedramp": "true" } : {})
|
||||
},
|
||||
method: "GET",
|
||||
signal: controller.signal
|
||||
});
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(`Codex model probe returned HTTP ${response.status}.`);
|
||||
}
|
||||
const payload = parseJson(text);
|
||||
const catalog = codexModelCatalogFromPayload(payload);
|
||||
if (catalog.models.length === 0) {
|
||||
throw new Error("Codex model probe returned no models.");
|
||||
}
|
||||
return catalog;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function codexProviderProbe(candidate: LocalAgentProviderCandidate) {
|
||||
return {
|
||||
capabilities: [
|
||||
{
|
||||
baseUrl: codexDefaultBaseUrl,
|
||||
source: "detected" as const,
|
||||
type: "openai_responses" as const
|
||||
}
|
||||
],
|
||||
detectedProtocol: "openai_responses" as const,
|
||||
modelDisplayNames: candidate.modelDisplayNames,
|
||||
modelMetadata: candidate.modelMetadata,
|
||||
modelSource: "openai" as const,
|
||||
models: candidate.models,
|
||||
normalizedBaseUrl: codexDefaultBaseUrl,
|
||||
protocols: [
|
||||
{
|
||||
baseUrl: codexDefaultBaseUrl,
|
||||
endpoint: `${codexDefaultBaseUrl}/responses`,
|
||||
message: "",
|
||||
protocol: "openai_responses" as const,
|
||||
supported: true
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
function codexModelCatalogFromPayload(payload: unknown): LocalAgentModelCatalog {
|
||||
const models: string[] = [];
|
||||
const modelDisplayNames: Record<string, string> = {};
|
||||
for (const item of Array.isArray(record?.models) ? record.models : []) {
|
||||
const modelMetadata: Record<string, ProviderModelMetadata> = {};
|
||||
for (const item of codexModelCatalogItems(payload)) {
|
||||
const model = isRecord(item)
|
||||
? readString(item.slug) || readString(item.id) || readString(item.name)
|
||||
? readString(item.slug) || readString(item.id) || readString(item.model) || readString(item.name)
|
||||
: readString(item);
|
||||
if (!model) {
|
||||
continue;
|
||||
}
|
||||
models.push(model);
|
||||
if (isRecord(item)) {
|
||||
const displayName = readString(item.display_name) || readString(item.displayName) || readString(item.label) || readString(item.name);
|
||||
const displayName = readString(item.display_name) || readString(item.displayName) || readString(item.label) || readString(item.title) || readString(item.name);
|
||||
if (displayName && displayName !== model) {
|
||||
modelDisplayNames[model] = displayName;
|
||||
}
|
||||
const metadata = codexModelMetadataFromItem(item);
|
||||
if (metadata) {
|
||||
modelMetadata[model] = metadata;
|
||||
}
|
||||
}
|
||||
}
|
||||
const uniqueModels = uniqueStrings([...models, ...codexDefaultModels]);
|
||||
const uniqueModels = uniqueStrings(models);
|
||||
return {
|
||||
modelDisplayNames: modelDisplayNamesForModels(modelDisplayNames, uniqueModels),
|
||||
modelMetadata: modelMetadataForModels(modelMetadata, uniqueModels),
|
||||
models: uniqueModels
|
||||
};
|
||||
}
|
||||
|
||||
function codexModelMetadataFromItem(item: Record<string, unknown>): ProviderModelMetadata | undefined {
|
||||
const additionalSpeedTiers = readArray(item.additional_speed_tiers) ?? readArray(item.additionalSpeedTiers) ?? readArray(item.speed_tiers) ?? readArray(item.speedTiers);
|
||||
const serviceTiers = readArray(item.service_tiers) ?? readArray(item.serviceTiers);
|
||||
const supportedReasoningLevels =
|
||||
readReasoningLevels(item.supported_reasoning_levels) ??
|
||||
readReasoningLevels(item.supportedReasoningLevels) ??
|
||||
readReasoningEfforts(item.supported_reasoning_efforts) ??
|
||||
readReasoningEfforts(item.supportedReasoningEfforts) ??
|
||||
readReasoningEfforts(item.reasoning_efforts) ??
|
||||
readReasoningEfforts(item.reasoningEfforts);
|
||||
const defaultReasoningLevel = readNullableString(item.default_reasoning_level) ?? readNullableString(item.defaultReasoningLevel);
|
||||
const defaultReasoningSummary = readString(item.default_reasoning_summary) || readString(item.defaultReasoningSummary);
|
||||
const supportsReasoningSummaries = readBoolean(item.supports_reasoning_summaries) ?? readBoolean(item.supportsReasoningSummaries);
|
||||
const metadata: ProviderModelMetadata = {
|
||||
...(additionalSpeedTiers ? { additionalSpeedTiers } : {}),
|
||||
...(defaultReasoningLevel !== undefined ? { defaultReasoningLevel } : {}),
|
||||
...(defaultReasoningSummary ? { defaultReasoningSummary } : {}),
|
||||
...(serviceTiers ? { serviceTiers } : {}),
|
||||
...(supportedReasoningLevels ? { supportedReasoningLevels } : {}),
|
||||
...(supportsReasoningSummaries !== undefined ? { supportsReasoningSummaries } : {})
|
||||
};
|
||||
return Object.keys(metadata).length > 0 ? metadata : undefined;
|
||||
}
|
||||
|
||||
function readArray(value: unknown): unknown[] | undefined {
|
||||
return Array.isArray(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function readNullableString(value: unknown): string | null | undefined {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
const text = readString(value);
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
function readReasoningLevels(value: unknown): ProviderReasoningLevel[] | undefined {
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const levels = value
|
||||
.map((item): ProviderReasoningLevel | undefined => {
|
||||
if (!isRecord(item)) {
|
||||
const effort = readString(item);
|
||||
return effort ? { description: effortDescription(effort), effort } : undefined;
|
||||
}
|
||||
const effort = readString(item.effort) || readString(item.name) || readString(item.id) || readString(item.value);
|
||||
if (!effort) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
description: readString(item.description) || readString(item.label) || effortDescription(effort),
|
||||
effort
|
||||
};
|
||||
})
|
||||
.filter((item): item is ProviderReasoningLevel => Boolean(item));
|
||||
return levels.length > 0 ? levels : undefined;
|
||||
}
|
||||
|
||||
function readReasoningEfforts(value: unknown): ProviderReasoningLevel[] | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
return readReasoningLevels(value);
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return readReasoningLevels(Object.values(value));
|
||||
}
|
||||
|
||||
function effortDescription(effort: string): string {
|
||||
const normalized = effort.trim().toLowerCase();
|
||||
if (normalized === "xhigh") {
|
||||
return "Extra high reasoning";
|
||||
}
|
||||
return `${effort.slice(0, 1).toUpperCase()}${effort.slice(1)} reasoning`;
|
||||
}
|
||||
|
||||
function codexModelCatalogItems(payload: unknown): unknown[] {
|
||||
if (Array.isArray(payload)) {
|
||||
return payload;
|
||||
}
|
||||
if (!isRecord(payload)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const items: unknown[] = [];
|
||||
for (const candidate of [payload.data, payload.models]) {
|
||||
if (Array.isArray(candidate)) {
|
||||
items.push(...candidate);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function parseJson(text: string): unknown {
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function codexModelCatalogFromPayloadForTest(payload: unknown): LocalAgentModelCatalog {
|
||||
return codexModelCatalogFromPayload(payload);
|
||||
}
|
||||
|
||||
function codexHomeDir(): string {
|
||||
return process.env.CCR_INTERNAL_HOME_DIR?.trim() || process.env.HOME?.trim() || process.env.USERPROFILE?.trim() || os.homedir();
|
||||
}
|
||||
|
||||
function readCodexIdTokenClaims(idToken: string | undefined): { accountId?: string; isFedrampAccount?: boolean } {
|
||||
const payload = readJwtPayload(idToken);
|
||||
const auth = isRecord(payload?.["https://api.openai.com/auth"])
|
||||
50
packages/core/src/agents/local-providers/service.ts
Normal file
50
packages/core/src/agents/local-providers/service.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import type {
|
||||
LocalAgentProviderCandidate,
|
||||
LocalAgentProviderImportRequest,
|
||||
LocalAgentProviderImportResult,
|
||||
LocalAgentProviderProbeRequest,
|
||||
LocalAgentProviderProbeResult
|
||||
} from "@ccr/core/contracts/app";
|
||||
import { claudeCodeCandidate, importClaudeCodeProvider } from "@ccr/core/agents/local-providers/claude-code";
|
||||
import { codexCandidate, importCodexProvider, probeCodexProvider } from "@ccr/core/agents/local-providers/codex";
|
||||
import { importZcodeProvider, zcodeCandidate } from "@ccr/core/agents/local-providers/zcode";
|
||||
|
||||
export { codexDefaultBaseUrl, readCodexAuth } from "@ccr/core/agents/local-providers/codex";
|
||||
export { localAgentProviderApiKey, type OAuthTokenSet } from "@ccr/core/agents/local-providers/shared";
|
||||
|
||||
export function getLocalAgentProviderCandidates(): LocalAgentProviderCandidate[] {
|
||||
return [
|
||||
codexCandidate(),
|
||||
claudeCodeCandidate(),
|
||||
zcodeCandidate()
|
||||
].filter((candidate) => candidate.status !== "missing");
|
||||
}
|
||||
|
||||
export async function importLocalAgentProvider(request: LocalAgentProviderImportRequest): Promise<LocalAgentProviderImportResult> {
|
||||
const candidate = getLocalAgentProviderCandidates().find((item) => item.id === request.id);
|
||||
if (!candidate) {
|
||||
throw new Error("Local agent provider was not found.");
|
||||
}
|
||||
if (!candidate.importable) {
|
||||
throw new Error(candidate.detail || "Local agent login is not importable.");
|
||||
}
|
||||
|
||||
if (candidate.kind === "codex") {
|
||||
return importCodexProvider(candidate, request.providerNames ?? []);
|
||||
}
|
||||
if (candidate.kind === "claude-code") {
|
||||
return importClaudeCodeProvider(candidate, request.providerNames ?? []);
|
||||
}
|
||||
return importZcodeProvider(candidate, request.providerNames ?? []);
|
||||
}
|
||||
|
||||
export async function probeLocalAgentProvider(request: LocalAgentProviderProbeRequest): Promise<LocalAgentProviderProbeResult> {
|
||||
const candidate = getLocalAgentProviderCandidates().find((item) => item.id === request.id);
|
||||
if (!candidate) {
|
||||
throw new Error("Local agent provider was not found.");
|
||||
}
|
||||
if (candidate.kind === "codex") {
|
||||
return probeCodexProvider(candidate);
|
||||
}
|
||||
throw new Error("Local agent provider model probing is not supported.");
|
||||
}
|
||||
|
|
@ -4,8 +4,9 @@ import type {
|
|||
LocalAgentProviderCandidate,
|
||||
LocalAgentProviderKind,
|
||||
ProviderAccountConfig,
|
||||
ProviderDeepLinkPayload
|
||||
} from "../../shared/app";
|
||||
ProviderDeepLinkPayload,
|
||||
ProviderModelMetadata
|
||||
} from "@ccr/core/contracts/app";
|
||||
|
||||
export type OAuthTokenSet = {
|
||||
accountId?: string;
|
||||
|
|
@ -39,8 +40,8 @@ export function missingCandidate(
|
|||
importable: false,
|
||||
kind,
|
||||
modelDisplayNames: modelDisplayNamesForModels(modelDisplayNames, models),
|
||||
models,
|
||||
name,
|
||||
models,
|
||||
name,
|
||||
protocol,
|
||||
status: "missing"
|
||||
};
|
||||
|
|
@ -58,12 +59,24 @@ export function providerPayload(
|
|||
apiKey: localAgentProviderApiKey,
|
||||
baseUrl,
|
||||
modelDisplayNames: modelDisplayNamesForModels(candidate.modelDisplayNames, models),
|
||||
modelMetadata: modelMetadataForModels(candidate.modelMetadata, models),
|
||||
models,
|
||||
name,
|
||||
protocol: candidate.protocol
|
||||
};
|
||||
}
|
||||
|
||||
export function modelMetadataForModels(
|
||||
value: Record<string, ProviderModelMetadata> | undefined,
|
||||
models: string[]
|
||||
): Record<string, ProviderModelMetadata> | undefined {
|
||||
const modelIds = new Set(models);
|
||||
const entries = Object.entries(value ?? {})
|
||||
.map(([rawModel, metadata]) => [rawModel.trim(), metadata] as const)
|
||||
.filter(([model, metadata]) => model && modelIds.has(model) && metadata && typeof metadata === "object");
|
||||
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
|
||||
}
|
||||
|
||||
export function modelDisplayNamesForModels(
|
||||
value: Record<string, string> | undefined,
|
||||
models: string[]
|
||||
|
|
@ -4,8 +4,8 @@ import type {
|
|||
LocalAgentProviderCandidate,
|
||||
LocalAgentProviderImportResult,
|
||||
ProviderAccountConfig
|
||||
} from "../../shared/app";
|
||||
import { findProviderPresetByBaseUrl } from "../presets";
|
||||
} from "@ccr/core/contracts/app";
|
||||
import { findProviderPresetByBaseUrl } from "@ccr/core/providers/presets/index";
|
||||
import {
|
||||
apiKeyAuthPlugin,
|
||||
cloneProviderAccountConfig,
|
||||
|
|
@ -21,7 +21,7 @@ import {
|
|||
uniqueProviderName,
|
||||
uniqueStrings,
|
||||
type ApiTokenSet
|
||||
} from "./shared";
|
||||
} from "@ccr/core/agents/local-providers/shared";
|
||||
|
||||
type ZcodeConfiguredProvider = {
|
||||
apiKey: string;
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { AppConfig, ProfileConfig } from "../shared/app";
|
||||
import { normalizeRouteSelector } from "../server/gateway/claude-code-router-plugin";
|
||||
import { buildCodexModelCatalogIds } from "./codex-model-catalog";
|
||||
import type { AppConfig, ProfileConfig } from "@ccr/core/contracts/app";
|
||||
import { normalizeRouteSelector } from "@ccr/core/gateway/claude-code-router-plugin";
|
||||
import { buildCodexModelCatalogIds } from "@ccr/core/agents/codex/model-catalog";
|
||||
|
||||
export type ZcodeProfileConfigWriteResult = {
|
||||
backupFile?: string;
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { API_KEYS_DB_FILE, LEGACY_API_KEYS_DB_FILES } from "./constants";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase } from "./sqlite-native";
|
||||
import type { ApiKeyConfig, ApiKeyLimitConfig } from "../shared/app";
|
||||
import { API_KEYS_DB_FILE, LEGACY_API_KEYS_DB_FILES } from "@ccr/core/config/constants";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase } from "@ccr/core/storage/sqlite-native";
|
||||
import type { ApiKeyConfig, ApiKeyLimitConfig } from "@ccr/core/contracts/app";
|
||||
|
||||
type SqlDatabase = BetterSqliteDatabase;
|
||||
type SqlValue = bigint | Buffer | number | string | null;
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { chmodSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { APP_CONFIG_DB_FILE, LEGACY_APP_CONFIG_DB_FILES } from "./constants";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase } from "./sqlite-native";
|
||||
import { APP_CONFIG_DB_FILE, LEGACY_APP_CONFIG_DB_FILES } from "@ccr/core/config/constants";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase } from "@ccr/core/storage/sqlite-native";
|
||||
|
||||
type SqlDatabase = BetterSqliteDatabase;
|
||||
type SqlValue = bigint | Buffer | number | string | null;
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { loadPersistedAppConfig, replacePersistedAppConfig } from "./app-config-store";
|
||||
import { loadPersistedApiKeys, replacePersistedApiKeys } from "./api-key-store";
|
||||
import { CONFIG_FILE, GATEWAY_CONFIG_FILE, LEGACY_CONFIG_FILE, LEGACY_WINDOWS_CONFIG_FILE } from "./constants";
|
||||
import { normalizeCodexProviderAccountConfig } from "./local-agent-providers/codex";
|
||||
import { CLAUDE_CODE_DEFAULT_ENV, CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY_ENV, DEFAULT_OVERVIEW_WIDGETS, DEFAULT_TRAY_COMPONENT_VARIANTS, DEFAULT_TRAY_WIDGETS, DEFAULT_TRAY_WINDOW_MODULES, OVERVIEW_WIDGET_SIZE_VALUES, ROUTER_FALLBACK_MAX_RETRY_COUNT, TRAY_SINGLETON_WIDGET_TYPES, TRAY_TOP_WIDGET_TYPES, TRAY_WINDOW_MODULE_IDS, enforceSingleEnabledGlobalProfilePerAgent } from "../shared/app";
|
||||
import { createDefaultAppConfig } from "../shared/default-config";
|
||||
import { findProviderPresetByBaseUrl, providerApiKeySafetyIssue, providerEndpointCanReceiveProviderApiKey } from "./presets";
|
||||
import { loadPersistedAppConfig, replacePersistedAppConfig } from "@ccr/core/config/app-config-store";
|
||||
import { loadPersistedApiKeys, replacePersistedApiKeys } from "@ccr/core/config/api-key-store";
|
||||
import { CONFIG_FILE, GATEWAY_CONFIG_FILE, LEGACY_CONFIG_FILE, LEGACY_WINDOWS_CONFIG_FILE } from "@ccr/core/config/constants";
|
||||
import { normalizeCodexProviderAccountConfig } from "@ccr/core/agents/local-providers/codex";
|
||||
import { CLAUDE_CODE_DEFAULT_ENV, CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY_ENV, DEFAULT_OVERVIEW_WIDGETS, DEFAULT_TRAY_COMPONENT_VARIANTS, DEFAULT_TRAY_WIDGETS, DEFAULT_TRAY_WINDOW_MODULES, OVERVIEW_WIDGET_SIZE_VALUES, ROUTER_FALLBACK_MAX_RETRY_COUNT, TRAY_SINGLETON_WIDGET_TYPES, TRAY_TOP_WIDGET_TYPES, TRAY_WINDOW_MODULE_IDS, enforceSingleEnabledGlobalProfilePerAgent } from "@ccr/core/contracts/app";
|
||||
import { createDefaultAppConfig } from "@ccr/core/config/default-config";
|
||||
import { findProviderPresetByBaseUrl, providerApiKeySafetyIssue, providerEndpointCanReceiveProviderApiKey } from "@ccr/core/providers/presets/index";
|
||||
import type {
|
||||
AppConfig,
|
||||
ApiKeyConfig,
|
||||
|
|
@ -33,6 +33,8 @@ import type {
|
|||
ProviderAccountConfig,
|
||||
ProviderAccountConnectorConfig,
|
||||
ProviderCredentialConfig,
|
||||
ProviderModelMetadata,
|
||||
ProviderReasoningLevel,
|
||||
ProfileConfig,
|
||||
ProfileRuntimeConfig,
|
||||
ProxyRouteTarget,
|
||||
|
|
@ -50,11 +52,12 @@ import type {
|
|||
TrayBalanceProgressConfig,
|
||||
TrayComponentVariants,
|
||||
TrayIconPreference,
|
||||
ToolHubConfig,
|
||||
TrayWidgetConfig,
|
||||
TrayWidgetType,
|
||||
TrayWidgetVariant,
|
||||
TrayWindowModuleId
|
||||
} from "../shared/app";
|
||||
} from "@ccr/core/contracts/app";
|
||||
|
||||
type LoadedProfileConfig = Partial<Omit<ProfileRuntimeConfig, "claudeCode" | "codex" | "profiles">> & {
|
||||
claudeCode?: Partial<ClaudeCodeProfileConfig>;
|
||||
|
|
@ -66,7 +69,7 @@ type LoadedBotGatewayConfig = Partial<Omit<BotGatewayRuntimeConfig, "handoff">>
|
|||
handoff?: Partial<BotGatewayRuntimeConfig["handoff"]>;
|
||||
};
|
||||
|
||||
type LoadedAppConfig = Partial<Omit<AppConfig, "Router" | "agent" | "botGateway" | "gateway" | "observability" | "profile" | "proxy">> & {
|
||||
type LoadedAppConfig = Partial<Omit<AppConfig, "Router" | "agent" | "botGateway" | "gateway" | "observability" | "profile" | "proxy" | "toolHub">> & {
|
||||
Router?: Partial<RouterConfig>;
|
||||
agent?: Partial<GatewayAgentConfig>;
|
||||
botConfigs?: BotGatewaySavedConfig[];
|
||||
|
|
@ -75,9 +78,10 @@ type LoadedAppConfig = Partial<Omit<AppConfig, "Router" | "agent" | "botGateway"
|
|||
observability?: Partial<ObservabilityConfig>;
|
||||
profile?: LoadedProfileConfig;
|
||||
proxy?: Partial<ProxyRuntimeConfig>;
|
||||
toolHub?: Partial<ToolHubConfig>;
|
||||
};
|
||||
|
||||
type RawAppConfigSource = "default" | "legacy-json" | "sqlite";
|
||||
export type RawAppConfigSource = "default" | "legacy-json" | "sqlite";
|
||||
|
||||
type RawAppConfigLoadResult = {
|
||||
source: RawAppConfigSource;
|
||||
|
|
@ -209,7 +213,7 @@ export async function loadAppConfig(): Promise<AppConfig> {
|
|||
try {
|
||||
const loadedRawConfig = await loadRawAppConfig();
|
||||
const rawValue = loadedRawConfig.value;
|
||||
const value = interpolateEnvVars(rawValue) as Partial<AppConfig>;
|
||||
const value = interpolateRawAppConfigEnvVars(rawValue, loadedRawConfig.source) as Partial<AppConfig>;
|
||||
const picked = pickConfig(value);
|
||||
const providers = picked.Providers ?? DEFAULT_CONFIG.Providers;
|
||||
const port = picked.PORT ?? endpointPort(picked.routerEndpoint) ?? DEFAULT_CONFIG.PORT;
|
||||
|
|
@ -274,7 +278,16 @@ export async function loadAppConfig(): Promise<AppConfig> {
|
|||
...(picked.proxy ?? {}),
|
||||
targets: picked.proxy?.targets?.length ? picked.proxy.targets : DEFAULT_CONFIG.proxy.targets
|
||||
},
|
||||
routerEndpoint: endpoint
|
||||
routerEndpoint: endpoint,
|
||||
toolHub: {
|
||||
...DEFAULT_CONFIG.toolHub,
|
||||
...(picked.toolHub ?? {}),
|
||||
llm: {
|
||||
...DEFAULT_CONFIG.toolHub.llm,
|
||||
...(picked.toolHub?.llm ?? {})
|
||||
},
|
||||
mcpServers: picked.toolHub?.mcpServers ?? DEFAULT_CONFIG.toolHub.mcpServers
|
||||
}
|
||||
});
|
||||
const shouldPersistApiKeys = loadedApiKeys.length === 0 || hasConfigFileApiKeys(rawValue) || configFileApiKeys.length > 0;
|
||||
if (shouldPersistApiKeys) {
|
||||
|
|
@ -615,6 +628,10 @@ function pickConfig(value: Partial<AppConfig>): LoadedAppConfig {
|
|||
if (observability) {
|
||||
config.observability = observability;
|
||||
}
|
||||
const toolHub = parseToolHub((value as Record<string, unknown>).toolHub ?? (value as Record<string, unknown>).tool_hub);
|
||||
if (toolHub) {
|
||||
config.toolHub = toolHub;
|
||||
}
|
||||
if (typeof value.preferredProvider === "string" && value.preferredProvider.trim()) {
|
||||
config.preferredProvider = value.preferredProvider.trim();
|
||||
}
|
||||
|
|
@ -676,6 +693,53 @@ function parseObservability(value: unknown): Partial<ObservabilityConfig> | unde
|
|||
return Object.keys(observability).length ? observability : undefined;
|
||||
}
|
||||
|
||||
function parseToolHub(value: unknown): Partial<ToolHubConfig> | undefined {
|
||||
if (!isObject(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const toolHub: Partial<ToolHubConfig> = {};
|
||||
if (typeof value.enabled === "boolean") {
|
||||
toolHub.enabled = value.enabled;
|
||||
}
|
||||
const browserAutomation = value.browserAutomation ?? value.browser_automation;
|
||||
if (typeof browserAutomation === "boolean") {
|
||||
toolHub.browserAutomation = browserAutomation;
|
||||
}
|
||||
const maxTools = readNumber(value.maxTools ?? value.max_tools);
|
||||
if (maxTools !== undefined) {
|
||||
toolHub.maxTools = clampNumber(maxTools, 1, 20);
|
||||
}
|
||||
const requestTimeoutMs = readNumber(value.requestTimeoutMs ?? value.request_timeout_ms);
|
||||
if (requestTimeoutMs !== undefined) {
|
||||
toolHub.requestTimeoutMs = clampNumber(requestTimeoutMs, 8000, 300000);
|
||||
}
|
||||
const mcpServers = parseMcpServers(value.mcpServers ?? value.mcp_servers);
|
||||
if (mcpServers) {
|
||||
toolHub.mcpServers = mcpServers;
|
||||
}
|
||||
|
||||
const rawLlm = isObject(value.llm) ? value.llm : value;
|
||||
const llm: Partial<ToolHubConfig["llm"]> = {};
|
||||
const apiKey = readString(rawLlm.apiKey) || readString(rawLlm.api_key);
|
||||
if (apiKey !== undefined) {
|
||||
llm.apiKey = apiKey;
|
||||
}
|
||||
const baseUrl = readString(rawLlm.baseUrl) || readString(rawLlm.base_url);
|
||||
if (baseUrl !== undefined) {
|
||||
llm.baseUrl = baseUrl;
|
||||
}
|
||||
const model = readString(rawLlm.model);
|
||||
if (model !== undefined) {
|
||||
llm.model = model;
|
||||
}
|
||||
if (Object.keys(llm).length > 0) {
|
||||
toolHub.llm = llm as ToolHubConfig["llm"];
|
||||
}
|
||||
|
||||
return Object.keys(toolHub).length ? toolHub : undefined;
|
||||
}
|
||||
|
||||
function parseOverviewWidgets(value: unknown): OverviewWidgetConfig[] | undefined {
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
|
|
@ -973,6 +1037,7 @@ function parseProviders(value: unknown): GatewayProviderConfig[] | undefined {
|
|||
: [];
|
||||
const modelDescriptions = parseModelDescriptions(item.modelDescriptions ?? item.model_descriptions, models);
|
||||
const modelDisplayNames = parseModelDisplayNames(item.modelDisplayNames ?? item.model_display_names, models);
|
||||
const modelMetadata = parseModelMetadata(item.modelMetadata ?? item.model_metadata, models);
|
||||
|
||||
if (!name) {
|
||||
return undefined;
|
||||
|
|
@ -995,6 +1060,7 @@ function parseProviders(value: unknown): GatewayProviderConfig[] | undefined {
|
|||
id: readString(item.id),
|
||||
modelDescriptions,
|
||||
modelDisplayNames,
|
||||
modelMetadata,
|
||||
models,
|
||||
name,
|
||||
provider: readString(item.provider),
|
||||
|
|
@ -1040,6 +1106,68 @@ function parseModelDisplayNames(value: unknown, models: string[]): Record<string
|
|||
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
|
||||
}
|
||||
|
||||
function parseModelMetadata(value: unknown, models: string[]): Record<string, ProviderModelMetadata> | undefined {
|
||||
if (!isObject(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const modelIds = new Set(models);
|
||||
const entries = Object.entries(value)
|
||||
.map(([rawModel, rawMetadata]) => [rawModel.trim(), parseProviderModelMetadata(rawMetadata)] as const)
|
||||
.filter((entry): entry is [string, ProviderModelMetadata] => {
|
||||
const [model, metadata] = entry;
|
||||
return Boolean(model && metadata && modelIds.has(model));
|
||||
});
|
||||
|
||||
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
|
||||
}
|
||||
|
||||
function parseProviderModelMetadata(value: unknown): ProviderModelMetadata | undefined {
|
||||
if (!isObject(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const supportedReasoningLevels = parseProviderReasoningLevels(value.supportedReasoningLevels ?? value.supported_reasoning_levels);
|
||||
const metadata: ProviderModelMetadata = {
|
||||
...(Array.isArray(value.additionalSpeedTiers) ? { additionalSpeedTiers: value.additionalSpeedTiers } : {}),
|
||||
...(Array.isArray(value.additional_speed_tiers) ? { additionalSpeedTiers: value.additional_speed_tiers } : {}),
|
||||
...(value.defaultReasoningLevel === null ? { defaultReasoningLevel: null } : {}),
|
||||
...(readString(value.defaultReasoningLevel) ? { defaultReasoningLevel: readString(value.defaultReasoningLevel) } : {}),
|
||||
...(value.default_reasoning_level === null ? { defaultReasoningLevel: null } : {}),
|
||||
...(readString(value.default_reasoning_level) ? { defaultReasoningLevel: readString(value.default_reasoning_level) } : {}),
|
||||
...(readString(value.defaultReasoningSummary) ? { defaultReasoningSummary: readString(value.defaultReasoningSummary) } : {}),
|
||||
...(readString(value.default_reasoning_summary) ? { defaultReasoningSummary: readString(value.default_reasoning_summary) } : {}),
|
||||
...(Array.isArray(value.serviceTiers) ? { serviceTiers: value.serviceTiers } : {}),
|
||||
...(Array.isArray(value.service_tiers) ? { serviceTiers: value.service_tiers } : {}),
|
||||
...(supportedReasoningLevels ? { supportedReasoningLevels } : {}),
|
||||
...(typeof value.supportsReasoningSummaries === "boolean" ? { supportsReasoningSummaries: value.supportsReasoningSummaries } : {}),
|
||||
...(typeof value.supports_reasoning_summaries === "boolean" ? { supportsReasoningSummaries: value.supports_reasoning_summaries } : {})
|
||||
};
|
||||
return Object.keys(metadata).length > 0 ? metadata : undefined;
|
||||
}
|
||||
|
||||
function parseProviderReasoningLevels(value: unknown): ProviderReasoningLevel[] | undefined {
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const levels = value
|
||||
.map((item): ProviderReasoningLevel | undefined => {
|
||||
if (!isObject(item)) {
|
||||
const effort = readString(item);
|
||||
return effort ? { description: effort, effort } : undefined;
|
||||
}
|
||||
const effort = readString(item.effort);
|
||||
if (!effort) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
description: readString(item.description) || effort,
|
||||
effort
|
||||
};
|
||||
})
|
||||
.filter((item): item is ProviderReasoningLevel => Boolean(item));
|
||||
return levels.length > 0 ? levels : undefined;
|
||||
}
|
||||
|
||||
function withProviderIds(providers: GatewayProviderConfig[]): GatewayProviderConfig[] {
|
||||
const counts = new Map<string, number>();
|
||||
return providers.map((provider) => {
|
||||
|
|
@ -1737,7 +1865,7 @@ function parseMcpServers(value: unknown): GatewayMcpServerConfig[] | undefined {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
const transport = parseMcpServerTransport(item.transport);
|
||||
const transport = parseMcpServerTransport(item.transport ?? item.type);
|
||||
const name = readString(item.name) || (transport !== "stdio" ? readString(item.url) : readString(item.command)) || `mcp-${index + 1}`;
|
||||
const protocolVersion = readString(item.protocolVersion) || "2024-11-05";
|
||||
const startupTimeoutMs = clampNumber(readNumber(item.startupTimeoutMs) ?? 600000, 100, 600000);
|
||||
|
|
@ -1792,7 +1920,7 @@ function parseMcpServerTransport(value: unknown): GatewayMcpServerTransport {
|
|||
if (normalized === "sse") {
|
||||
return "sse";
|
||||
}
|
||||
if (normalized === "streamable-http" || normalized === "streamble-http" || normalized === "websocket") {
|
||||
if (normalized === "http" || normalized === "streamable-http" || normalized === "streamablehttp" || normalized === "streamble-http" || normalized === "websocket") {
|
||||
return "streamable-http";
|
||||
}
|
||||
return "stdio";
|
||||
|
|
@ -2135,8 +2263,10 @@ function parseProfiles(value: unknown): ProfileConfig[] | undefined {
|
|||
const botGateway = surface !== "cli" && parsedBotGateway ? completeBotGatewayConfig(parsedBotGateway) : undefined;
|
||||
|
||||
if (agent === "claude-code") {
|
||||
const appPath = readProfileAppPath(item, agent);
|
||||
return {
|
||||
agent,
|
||||
...(appPath ? { appPath } : {}),
|
||||
...(botConfigId ? { botConfigId } : {}),
|
||||
...(botGateway ? { botGateway } : {}),
|
||||
enabled,
|
||||
|
|
@ -2151,8 +2281,10 @@ function parseProfiles(value: unknown): ProfileConfig[] | undefined {
|
|||
};
|
||||
}
|
||||
|
||||
const appPath = readProfileAppPath(item, agent);
|
||||
return {
|
||||
agent,
|
||||
...(appPath ? { appPath } : {}),
|
||||
...(botConfigId ? { botConfigId } : {}),
|
||||
...(botGateway ? { botGateway } : {}),
|
||||
cliMiddleware: true,
|
||||
|
|
@ -2182,6 +2314,18 @@ function parseProfiles(value: unknown): ProfileConfig[] | undefined {
|
|||
.filter((item): item is ProfileConfig => Boolean(item));
|
||||
}
|
||||
|
||||
function readProfileAppPath(item: Record<string, unknown>, agent: ProfileConfig["agent"]): string | undefined {
|
||||
return readString(item.appPath) ||
|
||||
readString(item.app_path) ||
|
||||
readString(item.appExecutablePath) ||
|
||||
readString(item.app_executable_path) ||
|
||||
(agent === "claude-code"
|
||||
? readString(item.claudeAppPath) || readString(item.claude_app_path)
|
||||
: agent === "codex"
|
||||
? readString(item.chatgptAppPath) || readString(item.chatgpt_app_path) || readString(item.codexAppPath) || readString(item.codex_app_path)
|
||||
: readString(item.zcodeAppPath) || readString(item.zcode_app_path));
|
||||
}
|
||||
|
||||
function parseProfileAgent(value: unknown): ProfileConfig["agent"] | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
|
|
@ -2489,6 +2633,10 @@ function isDefaultSeedApiKey(apiKey: ApiKeyConfig): boolean {
|
|||
);
|
||||
}
|
||||
|
||||
export function interpolateRawAppConfigEnvVars(value: unknown, source: RawAppConfigSource): unknown {
|
||||
return source === "legacy-json" ? interpolateEnvVars(value) : value;
|
||||
}
|
||||
|
||||
function interpolateEnvVars(value: unknown): unknown {
|
||||
if (typeof value === "string") {
|
||||
return value.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g, (match, braced, unbraced) => {
|
||||
|
|
@ -1,20 +1,18 @@
|
|||
import path from "node:path";
|
||||
import { APP_NAME, APP_STORAGE_NAME, LEGACY_CONFIGDIR, resolveRuntimeAppPath } from "./app-paths";
|
||||
import { copyMissingDirectoryContents } from "./storage-migration";
|
||||
import { APP_NAME, APP_STORAGE_NAME, LEGACY_CONFIGDIR, resolveRuntimeAppPath, resolveRuntimeConfigDir, resolveRuntimeDataDir } from "@ccr/core/runtime/app-paths";
|
||||
import { copyMissingDirectoryContents } from "@ccr/core/storage/migration";
|
||||
|
||||
export { IPC_CHANNELS } from "../shared/ipc-channels";
|
||||
export { IPC_CHANNELS } from "@ccr/core/contracts/ipc-channels";
|
||||
export const LEGACY_CONFIG_FILE = path.join(LEGACY_CONFIGDIR, "config.json");
|
||||
|
||||
export { APP_NAME, APP_STORAGE_NAME, LEGACY_CONFIGDIR };
|
||||
|
||||
export const CONFIGDIR = process.platform === "win32"
|
||||
? path.join(resolveRuntimeAppPath("appData"), APP_STORAGE_NAME)
|
||||
: LEGACY_CONFIGDIR;
|
||||
export const CONFIGDIR = resolveRuntimeConfigDir();
|
||||
export const LEGACY_WINDOWS_CONFIGDIR = path.join(resolveRuntimeAppPath("appData"), APP_NAME);
|
||||
export const LEGACY_WINDOWS_CONFIG_FILE = path.join(LEGACY_WINDOWS_CONFIGDIR, "config.json");
|
||||
export const CONFIG_FILE = path.join(CONFIGDIR, "config.json");
|
||||
export const ONBOARDING_FINISHED_FILE = path.join(CONFIGDIR, ".onboard_finished");
|
||||
export const DATADIR = resolveRuntimeAppPath("userData");
|
||||
export const DATADIR = resolveRuntimeDataDir();
|
||||
export const APP_CONFIG_DB_FILE = path.join(CONFIGDIR, "config.sqlite");
|
||||
export const API_KEYS_DB_FILE = path.join(DATADIR, "api-keys.sqlite");
|
||||
export const LEGACY_APP_CONFIG_DB_FILES = process.platform === "win32" ? [path.join(LEGACY_WINDOWS_CONFIGDIR, "config.sqlite")] : [];
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
DEFAULT_TRAY_WINDOW_MODULES,
|
||||
type AppConfig,
|
||||
type ProxyRouteTarget
|
||||
} from "./app";
|
||||
} from "@ccr/core/contracts/app";
|
||||
|
||||
export const DEFAULT_PROXY_TARGETS: ProxyRouteTarget[] = [
|
||||
{ host: "api.anthropic.com", paths: ["/v1/messages", "/v1/messages/count_tokens"] },
|
||||
|
|
@ -169,6 +169,18 @@ export function createDefaultAppConfig(options: DefaultAppConfigOptions): AppCon
|
|||
trayProgressTargetTokens: 100000,
|
||||
trayWidgets: DEFAULT_TRAY_WIDGETS,
|
||||
trayWindowModules: DEFAULT_TRAY_WINDOW_MODULES,
|
||||
toolHub: {
|
||||
browserAutomation: false,
|
||||
enabled: false,
|
||||
llm: {
|
||||
apiKey: "",
|
||||
baseUrl: "https://api.openai.com/v1",
|
||||
model: ""
|
||||
},
|
||||
mcpServers: [],
|
||||
maxTools: 10,
|
||||
requestTimeoutMs: 60000
|
||||
},
|
||||
virtualModelProfiles: []
|
||||
};
|
||||
}
|
||||
|
|
@ -133,6 +133,7 @@ export type GatewayProviderConfig = {
|
|||
id?: string;
|
||||
modelDescriptions?: Record<string, string>;
|
||||
modelDisplayNames?: Record<string, string>;
|
||||
modelMetadata?: Record<string, ProviderModelMetadata>;
|
||||
models: string[];
|
||||
name: string;
|
||||
provider?: string;
|
||||
|
|
@ -140,6 +141,20 @@ export type GatewayProviderConfig = {
|
|||
type?: GatewayProviderProtocol | string;
|
||||
};
|
||||
|
||||
export type ProviderReasoningLevel = {
|
||||
description: string;
|
||||
effort: string;
|
||||
};
|
||||
|
||||
export type ProviderModelMetadata = {
|
||||
additionalSpeedTiers?: unknown[];
|
||||
defaultReasoningLevel?: string | null;
|
||||
defaultReasoningSummary?: string;
|
||||
serviceTiers?: unknown[];
|
||||
supportedReasoningLevels?: ProviderReasoningLevel[];
|
||||
supportsReasoningSummaries?: boolean;
|
||||
};
|
||||
|
||||
export type ProviderCredentialConfig = {
|
||||
account?: ProviderAccountConfig;
|
||||
api_key?: string;
|
||||
|
|
@ -160,6 +175,7 @@ export type ProviderAccountStatus = "ok" | "warning" | "critical" | "error" | "u
|
|||
export type ProviderAccountMeterKind = "balance" | "subscription" | "quota" | "time_window" | "tokens" | "requests";
|
||||
export type ProviderAccountMeterUnit = "USD" | "CNY" | "hours" | "minutes" | "tokens" | "requests" | string;
|
||||
export type ProviderAccountMeterWindow = "5h" | "daily" | "weekly" | "monthly" | string;
|
||||
export type ProviderAccountHttpJsonParser = "kimi-code-usages" | "new-api-key-usage" | "new-api-user-self";
|
||||
|
||||
export type ProviderAccountConfig = {
|
||||
connectors?: ProviderAccountConnectorConfig[];
|
||||
|
|
@ -193,7 +209,7 @@ export type ProviderAccountHttpJsonConnectorConfig = ProviderAccountConnectorBas
|
|||
headers?: Record<string, string>;
|
||||
mapping: ProviderAccountMappingConfig;
|
||||
method?: "GET" | "POST";
|
||||
parser?: "kimi-code-usages";
|
||||
parser?: ProviderAccountHttpJsonParser;
|
||||
type: "http-json";
|
||||
};
|
||||
|
||||
|
|
@ -292,6 +308,7 @@ export type ProviderDeepLinkPayload = {
|
|||
icon?: string;
|
||||
modelDescriptions?: Record<string, string>;
|
||||
modelDisplayNames?: Record<string, string>;
|
||||
modelMetadata?: Record<string, ProviderModelMetadata>;
|
||||
models: string[];
|
||||
name?: string;
|
||||
protocol?: GatewayProviderProtocol;
|
||||
|
|
@ -322,6 +339,7 @@ export type LocalAgentProviderCandidate = {
|
|||
importable: boolean;
|
||||
kind: LocalAgentProviderKind;
|
||||
modelDisplayNames?: Record<string, string>;
|
||||
modelMetadata?: Record<string, ProviderModelMetadata>;
|
||||
models: string[];
|
||||
name: string;
|
||||
protocol: GatewayProviderProtocol;
|
||||
|
|
@ -340,6 +358,16 @@ export type LocalAgentProviderImportResult = {
|
|||
providerPlugins: unknown[];
|
||||
};
|
||||
|
||||
export type LocalAgentProviderProbeRequest = {
|
||||
forceRefresh?: boolean;
|
||||
id: string;
|
||||
};
|
||||
|
||||
export type LocalAgentProviderProbeResult = {
|
||||
candidate: LocalAgentProviderCandidate;
|
||||
probe: GatewayProviderProbeResult;
|
||||
};
|
||||
|
||||
export type ProviderCatalogModelsRequest = {
|
||||
baseUrl?: string;
|
||||
name?: string;
|
||||
|
|
@ -351,6 +379,7 @@ export type ProviderCatalogModelsResult = {
|
|||
loadedFrom?: string;
|
||||
matchedBy?: "base-url" | "provider-id" | "provider-name";
|
||||
modelDisplayNames?: Record<string, string>;
|
||||
modelMetadata?: Record<string, ProviderModelMetadata>;
|
||||
models: string[];
|
||||
provider?: string;
|
||||
providerName?: string;
|
||||
|
|
@ -405,6 +434,8 @@ export type GatewayProviderCapability = {
|
|||
type: GatewayProviderProtocol;
|
||||
};
|
||||
|
||||
export type GatewayProviderDetectedProvider = "new-api";
|
||||
|
||||
export type GatewayProviderProbeRequest = {
|
||||
apiKey?: string;
|
||||
baseUrl: string;
|
||||
|
|
@ -417,6 +448,7 @@ export type GatewayProviderProbeRequest = {
|
|||
|
||||
export type GatewayProviderProbeCandidate = {
|
||||
baseUrl: string;
|
||||
declaredProtocols?: GatewayProviderProtocol[];
|
||||
label?: string;
|
||||
protocols: GatewayProviderProtocol[];
|
||||
source: "custom" | "preset";
|
||||
|
|
@ -445,6 +477,7 @@ export type ProviderIconDetectionResult = {
|
|||
|
||||
export type GatewayProviderProbeProtocolResult = {
|
||||
baseUrl?: string;
|
||||
detectedProvider?: GatewayProviderDetectedProvider;
|
||||
endpoint: string;
|
||||
message: string;
|
||||
protocol: GatewayProviderProtocol;
|
||||
|
|
@ -453,9 +486,12 @@ export type GatewayProviderProbeProtocolResult = {
|
|||
};
|
||||
|
||||
export type GatewayProviderProbeResult = {
|
||||
account?: ProviderAccountConfig;
|
||||
capabilities?: GatewayProviderCapability[];
|
||||
detectedProvider?: GatewayProviderDetectedProvider;
|
||||
detectedProtocol?: GatewayProviderProtocol;
|
||||
modelDisplayNames?: Record<string, string>;
|
||||
modelMetadata?: Record<string, ProviderModelMetadata>;
|
||||
modelSource?: "anthropic" | "gemini" | "openai";
|
||||
models: string[];
|
||||
normalizedBaseUrl: string;
|
||||
|
|
@ -635,6 +671,21 @@ export type GatewayAgentConfig = {
|
|||
mcpServers: GatewayMcpServerConfig[];
|
||||
};
|
||||
|
||||
export type ToolHubLlmConfig = {
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
};
|
||||
|
||||
export type ToolHubConfig = {
|
||||
browserAutomation: boolean;
|
||||
enabled: boolean;
|
||||
llm: ToolHubLlmConfig;
|
||||
mcpServers: GatewayMcpServerConfig[];
|
||||
maxTools: number;
|
||||
requestTimeoutMs: number;
|
||||
};
|
||||
|
||||
export const CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY_ENV = "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY";
|
||||
export const CLAUDE_CODE_DEFAULT_ENV: Record<string, string> = {
|
||||
[CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY_ENV]: "1"
|
||||
|
|
@ -1086,6 +1137,7 @@ export type CodexProfileConfig = {
|
|||
|
||||
export type ProfileConfig = {
|
||||
agent: ProfileClientKind;
|
||||
appPath?: string;
|
||||
botConfigId?: string;
|
||||
botGateway?: BotGatewayRuntimeConfig;
|
||||
configFile?: string;
|
||||
|
|
@ -1396,6 +1448,7 @@ export type AppConfig = {
|
|||
trayIcon: TrayIconPreference;
|
||||
trayWidgets: TrayWidgetConfig[];
|
||||
trayWindowModules: TrayWindowModuleId[];
|
||||
toolHub: ToolHubConfig;
|
||||
virtualModelProfiles?: VirtualModelProfileConfig[];
|
||||
};
|
||||
|
||||
|
|
@ -1453,12 +1506,91 @@ export type BuiltInBrowserTabState = {
|
|||
url: string;
|
||||
};
|
||||
|
||||
export type BuiltInBrowserAutomationHandoffKind =
|
||||
| "blocked"
|
||||
| "human_verification"
|
||||
| "login_required"
|
||||
| "other"
|
||||
| "verification_code";
|
||||
|
||||
export type BuiltInBrowserAutomationHandoff = {
|
||||
id: string;
|
||||
kind: BuiltInBrowserAutomationHandoffKind;
|
||||
message: string;
|
||||
reason?: string;
|
||||
requestedAt: number;
|
||||
sessionId?: string;
|
||||
status: "pending";
|
||||
tabId?: string;
|
||||
};
|
||||
|
||||
export type BuiltInBrowserState = {
|
||||
activeTabId?: string;
|
||||
apps: InstalledBrowserApp[];
|
||||
automationHandoff?: BuiltInBrowserAutomationHandoff;
|
||||
tabs: BuiltInBrowserTabState[];
|
||||
};
|
||||
|
||||
export type ChromeLoginImportTarget = "browser" | "browser-and-web-search";
|
||||
|
||||
export type ChromeLoginImportStatus =
|
||||
| "completed"
|
||||
| "expired"
|
||||
| "failed"
|
||||
| "pending";
|
||||
|
||||
export type ChromeLoginImportRequest = {
|
||||
domains: string[];
|
||||
openConfirmationPage?: boolean;
|
||||
target?: ChromeLoginImportTarget;
|
||||
};
|
||||
|
||||
export type ChromeLoginImportResult = {
|
||||
completedAt: number;
|
||||
cookieImported: number;
|
||||
cookieSkipped: number;
|
||||
domains: string[];
|
||||
errors?: string[];
|
||||
imported: number;
|
||||
localStorageImported: number;
|
||||
localStorageSkipped: number;
|
||||
partitions: string[];
|
||||
skipped: number;
|
||||
};
|
||||
|
||||
export type ChromeLoginImportJob = {
|
||||
confirmUrl: string;
|
||||
createdAt: number;
|
||||
domains: string[];
|
||||
endpointUrl: string;
|
||||
expiresAt: number;
|
||||
id: string;
|
||||
importUrl: string;
|
||||
result?: ChromeLoginImportResult;
|
||||
status: ChromeLoginImportStatus;
|
||||
target: ChromeLoginImportTarget;
|
||||
};
|
||||
|
||||
export type ChromeLoginImportCookie = {
|
||||
domain: string;
|
||||
expirationDate?: number;
|
||||
hostOnly?: boolean;
|
||||
httpOnly?: boolean;
|
||||
name: string;
|
||||
partitionKey?: unknown;
|
||||
path?: string;
|
||||
sameSite?: "lax" | "no_restriction" | "strict" | "unspecified";
|
||||
secure?: boolean;
|
||||
session?: boolean;
|
||||
storeId?: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type ChromeLoginImportLocalStorage = {
|
||||
items: Record<string, string>;
|
||||
origin: string;
|
||||
};
|
||||
|
||||
export type ProxyCertificateInstallResult = {
|
||||
caCertFile: string;
|
||||
manualCommand?: string;
|
||||
|
|
@ -6,8 +6,8 @@ import type {
|
|||
ProviderDeepLinkPayload,
|
||||
ProviderDeepLinkRequest,
|
||||
ProviderManifestDeepLinkPayload
|
||||
} from "./app";
|
||||
import { providerUrlWithDefaultScheme } from "./provider-url";
|
||||
} from "@ccr/core/contracts/app";
|
||||
import { providerUrlWithDefaultScheme } from "@ccr/core/providers/url";
|
||||
|
||||
export const appDeepLinkProtocol = "ccr";
|
||||
export const providerDeepLinkHost = "provider";
|
||||
|
|
@ -273,8 +273,8 @@ const zhPatternErrorMessages: PatternTranslator[] = [
|
|||
translate: (endpoint, status) => `CDP ${endpoint} 返回 HTTP ${status}`
|
||||
},
|
||||
{
|
||||
pattern: /^Timed out waiting for Codex App response: (.+)$/,
|
||||
translate: (requestId) => `等待 Codex App 响应超时:${requestId}`
|
||||
pattern: /^Timed out waiting for (?:ChatGPT|Codex App) response: (.+)$/,
|
||||
translate: (requestId) => `等待 ChatGPT 响应超时:${requestId}`
|
||||
},
|
||||
{
|
||||
pattern: /^No active turn for thread (.+)$/,
|
||||
|
|
@ -43,6 +43,7 @@ export const IPC_CHANNELS = {
|
|||
appBotHandoffBluetoothTargetsScan: "ccr:app:bot-handoff-bluetooth-targets-scan",
|
||||
appBotHandoffWifiTargetsScan: "ccr:app:bot-handoff-wifi-targets-scan",
|
||||
appCheckProviderConnectivity: "ccr:app:check-provider-connectivity",
|
||||
appProbeLocalAgentProvider: "ccr:app:probe-local-agent-provider",
|
||||
appProbeProvider: "ccr:app:probe-provider",
|
||||
appProbeProviderCandidates: "ccr:app:probe-provider-candidates",
|
||||
appProviderDeepLink: "ccr:app:provider-deep-link",
|
||||
|
|
@ -73,10 +74,13 @@ export const IPC_CHANNELS = {
|
|||
browserBack: "ccr:browser:back",
|
||||
browserCloseTab: "ccr:browser:close-tab",
|
||||
browserForward: "ccr:browser:forward",
|
||||
browserGetChromeLoginImport: "ccr:browser:get-chrome-login-import",
|
||||
browserGetState: "ccr:browser:get-state",
|
||||
browserNavigate: "ccr:browser:navigate",
|
||||
browserNewTab: "ccr:browser:new-tab",
|
||||
browserReload: "ccr:browser:reload",
|
||||
browserResolveAutomationHandoff: "ccr:browser:resolve-automation-handoff",
|
||||
browserSelectTab: "ccr:browser:select-tab",
|
||||
browserStartChromeLoginImport: "ccr:browser:start-chrome-login-import",
|
||||
browserStateChanged: "ccr:browser:state-changed"
|
||||
} as const;
|
||||
129
packages/core/src/entrypoints/server.ts
Normal file
129
packages/core/src/entrypoints/server.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
#!/usr/bin/env node
|
||||
import { startWebManagementServer } from "@ccr/core/web/management-server";
|
||||
|
||||
type CoreServerOptions = {
|
||||
help: boolean;
|
||||
host?: string;
|
||||
open: boolean;
|
||||
port?: number;
|
||||
startGateway: boolean;
|
||||
};
|
||||
|
||||
export async function runCoreServer(args = process.argv.slice(2)): Promise<void> {
|
||||
const options = parseCoreServerArgs(args);
|
||||
if (options.help) {
|
||||
printHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
const runtime = await startWebManagementServer({
|
||||
host: options.host,
|
||||
open: options.open,
|
||||
port: options.port,
|
||||
startGateway: options.startGateway
|
||||
});
|
||||
process.stdout.write(`CCR core server is running at ${runtime.url}\n`);
|
||||
|
||||
let closing = false;
|
||||
const shutdown = (signal: NodeJS.Signals) => {
|
||||
if (closing) {
|
||||
return;
|
||||
}
|
||||
closing = true;
|
||||
void runtime.close().finally(() => {
|
||||
process.exit(signal === "SIGINT" ? 130 : 143);
|
||||
});
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
await new Promise(() => undefined);
|
||||
}
|
||||
|
||||
function parseCoreServerArgs(args: string[]): CoreServerOptions {
|
||||
const options: CoreServerOptions = {
|
||||
help: false,
|
||||
open: false,
|
||||
startGateway: true
|
||||
};
|
||||
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const arg = args[index];
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
options.help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--open") {
|
||||
options.open = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--no-open") {
|
||||
options.open = false;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--gateway") {
|
||||
options.startGateway = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--no-gateway") {
|
||||
options.startGateway = false;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--host") {
|
||||
index += 1;
|
||||
options.host = requiredArg(args[index], "--host");
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith("--host=")) {
|
||||
options.host = requiredArg(arg.slice("--host=".length), "--host");
|
||||
continue;
|
||||
}
|
||||
if (arg === "--port") {
|
||||
index += 1;
|
||||
options.port = parsePort(requiredArg(args[index], "--port"));
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith("--port=")) {
|
||||
options.port = parsePort(requiredArg(arg.slice("--port=".length), "--port"));
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Unknown core server option: ${arg}`);
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function printHelp(): void {
|
||||
process.stdout.write([
|
||||
"Usage:",
|
||||
" ccr-core-server [--host <host>] [--port <port>] [--no-gateway]",
|
||||
"",
|
||||
"Options:",
|
||||
" --host <host> Management server host. Defaults to CCR_WEB_HOST or 127.0.0.1.",
|
||||
" --port <port> Management server port. Defaults to CCR_WEB_PORT or 3458.",
|
||||
" --no-gateway Start only the web management server.",
|
||||
"",
|
||||
"Environment:",
|
||||
" CCR_WEB_AUTH_TOKEN Use this token for management UI and RPC authentication."
|
||||
].join("\n") + "\n");
|
||||
}
|
||||
|
||||
function requiredArg(value: string | undefined, flag: string): string {
|
||||
if (!value) {
|
||||
throw new Error(`Missing value for ${flag}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePort(value: string): number {
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
throw new Error(`Invalid port: ${value}`);
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
runCoreServer().catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
process.stderr.write(`${message}\n`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
|
|
@ -2,8 +2,8 @@ import { createRequire } from "node:module";
|
|||
import { EventEmitter } from "node:events";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { availableGatewayModelIds, type AppConfig, type RouterBuiltInAgentRuleId, type RouterConfig, type RouterFallbackConfig, type RouterRule, type RouterRuleCondition, type RouterRuleRewrite } from "../../shared/app";
|
||||
import { CONFIGDIR } from "../../main/constants";
|
||||
import { availableGatewayModelIds, type AppConfig, type RouterBuiltInAgentRuleId, type RouterConfig, type RouterFallbackConfig, type RouterRule, type RouterRuleCondition, type RouterRuleRewrite } from "@ccr/core/contracts/app";
|
||||
import { CONFIGDIR } from "@ccr/core/config/constants";
|
||||
|
||||
type HeaderValue = string | string[] | undefined;
|
||||
|
||||
|
|
@ -57,6 +57,7 @@ export class ClaudeCodeRouterPlugin {
|
|||
};
|
||||
if (builtInAgentRouteMatches(request, this.config, "claude-code")) {
|
||||
injectClaudeCodeAgentToolDescription(body, this.config);
|
||||
injectClaudeCodeToolHubInstructions(body, this.config);
|
||||
removeClaudeCodeBillingSystemHeader(body);
|
||||
request.builtInSubagentModel = extractAndRemoveClaudeCodeSubagentModelTag(body);
|
||||
}
|
||||
|
|
@ -245,7 +246,7 @@ function resolveBuiltInClaudeCodeSubagentRouteDecision(
|
|||
return undefined;
|
||||
}
|
||||
const target = normalizeRouteSelector(request.builtInSubagentModel);
|
||||
if (!target) {
|
||||
if (!target || isSubagentModelPlaceholder(target) || !isKnownInlineRoute(target, config)) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
|
|
@ -321,6 +322,7 @@ function builtInAgentUserAgentNeedle(agent: RouterBuiltInAgentRuleId): string {
|
|||
const ccrSubagentModelOpenTag = "<CCR-SUBAGENT-MODEL>";
|
||||
const ccrSubagentModelCloseTag = "</CCR-SUBAGENT-MODEL>";
|
||||
const ccrSubagentModelTagExample = `${ccrSubagentModelOpenTag}Provider/model${ccrSubagentModelCloseTag}`;
|
||||
const ccrSubagentModelPlaceholder = "provider/model";
|
||||
const claudeCodeBillingSystemHeaderPrefix = "x-anthropic-billing-header";
|
||||
const ccrSubagentToolModelInstruction =
|
||||
`CCR subagent routing is enabled. When calling this tool, the prompt parameter MUST start with ` +
|
||||
|
|
@ -342,6 +344,107 @@ const ccrSubagentPromptFieldInstruction =
|
|||
type ClaudeCodeSubagentToolKind = "subagent" | "workflow";
|
||||
const claudeCodeAgentToolNames = new Set(["agent", "task"]);
|
||||
const claudeCodeWorkflowToolNames = new Set(["workflow"]);
|
||||
const ccrToolHubSystemInstructionMarker = "CCR ToolHub tool resolution is enabled.";
|
||||
|
||||
function claudeCodeToolName(tool: Record<string, unknown>): string | undefined {
|
||||
const functionSpec = isRecord(tool.function) ? tool.function : undefined;
|
||||
return readString(tool.name) ?? readString(functionSpec?.name);
|
||||
}
|
||||
|
||||
function normalizeClaudeCodeToolName(toolName: string | undefined): string {
|
||||
return toolName?.toLowerCase().replace(/[-._]/g, "") ?? "";
|
||||
}
|
||||
|
||||
function injectClaudeCodeToolHubInstructions(body: Record<string, unknown>, config: AppConfig): void {
|
||||
if (!config.toolHub?.enabled || !Array.isArray(body.tools)) {
|
||||
return;
|
||||
}
|
||||
const toolNames = claudeCodeToolHubToolNames(body.tools);
|
||||
if (!toolNames.resolve) {
|
||||
return;
|
||||
}
|
||||
const invokeName = toolNames.invoke ?? "tool_hub.invoke";
|
||||
appendSystemInstruction(body, [
|
||||
ccrToolHubSystemInstructionMarker,
|
||||
`The ToolHub search/resolution tool is ${toolNames.resolve}; call this actual tool, do not merely mention its name in text.`,
|
||||
`You MUST call the ToolHub search/resolution tool ${toolNames.resolve} before answering any request that asks about external services, installed MCP capabilities, business APIs, orders, coupons, stores, accounts, available tools, or capabilities that are not already obvious from the eager tools.`,
|
||||
`Do this even if the user did not mention ToolHub or ${toolNames.resolve}. Only skip the ToolHub search/resolution tool when the request is clearly local code/file/shell work or simple conversation that does not need an external or MCP capability.`,
|
||||
`If ${toolNames.resolve} returns selected tools, call the ToolHub invocation tool ${invokeName} to run the selected tool instead of telling the user that no such capability is available.`,
|
||||
"When the ToolHub resolve result includes executionPlanJs or workflowSketch, treat that JavaScript as the invocation dependency plan: await means serial order, and only callTool calls grouped inside the same Promise.all may be issued in parallel.",
|
||||
"Use the user's request as the task and include concise context when resolving. Do not ask the user to name the MCP tool unless the task is genuinely ambiguous after resolution."
|
||||
].join("\n"));
|
||||
}
|
||||
|
||||
function claudeCodeToolHubToolNames(tools: unknown[]): { invoke?: string; resolve?: string } {
|
||||
const names: { invoke?: string; resolve?: string } = {};
|
||||
for (const tool of tools) {
|
||||
if (!isRecord(tool)) {
|
||||
continue;
|
||||
}
|
||||
const name = claudeCodeToolName(tool);
|
||||
const normalized = normalizeClaudeCodeToolName(name);
|
||||
if (normalized.endsWith("toolhubresolve") && shouldUseClaudeCodeToolHubName(names.resolve, name)) {
|
||||
names.resolve = name;
|
||||
}
|
||||
if (normalized.endsWith("toolhubinvoke") && shouldUseClaudeCodeToolHubName(names.invoke, name)) {
|
||||
names.invoke = name;
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function shouldUseClaudeCodeToolHubName(current: string | undefined, candidate: string | undefined): boolean {
|
||||
if (!candidate) {
|
||||
return false;
|
||||
}
|
||||
if (!current) {
|
||||
return true;
|
||||
}
|
||||
return claudeCodeToolHubNameScore(candidate) > claudeCodeToolHubNameScore(current);
|
||||
}
|
||||
|
||||
function claudeCodeToolHubNameScore(name: string): number {
|
||||
const normalized = name.toLowerCase();
|
||||
if (normalized.startsWith("mcp__ccr-toolhub__") || normalized.startsWith("mcp__ccr_toolhub__")) {
|
||||
return 3;
|
||||
}
|
||||
if (normalized.startsWith("mcp__") && normalized.includes("toolhub")) {
|
||||
return 2;
|
||||
}
|
||||
if (normalized.startsWith("mcp__")) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function appendSystemInstruction(body: Record<string, unknown>, instruction: string): void {
|
||||
if (systemContainsInstruction(body.system, ccrToolHubSystemInstructionMarker)) {
|
||||
return;
|
||||
}
|
||||
if (typeof body.system === "string") {
|
||||
body.system = body.system.trim() ? `${body.system}\n\n${instruction}` : instruction;
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(body.system)) {
|
||||
body.system.push({ text: instruction, type: "text" });
|
||||
return;
|
||||
}
|
||||
if (body.system === undefined) {
|
||||
body.system = [{ text: instruction, type: "text" }];
|
||||
}
|
||||
}
|
||||
|
||||
function systemContainsInstruction(system: unknown, marker: string): boolean {
|
||||
if (typeof system === "string") {
|
||||
return system.includes(marker);
|
||||
}
|
||||
if (!Array.isArray(system)) {
|
||||
return false;
|
||||
}
|
||||
return system.some((block) => typeof block === "string"
|
||||
? block.includes(marker)
|
||||
: isRecord(block) && typeof block.text === "string" && block.text.includes(marker));
|
||||
}
|
||||
|
||||
function injectClaudeCodeAgentToolDescription(body: Record<string, unknown>, config: AppConfig): void {
|
||||
if (!Array.isArray(body.tools)) {
|
||||
|
|
@ -1098,6 +1201,10 @@ function isKnownInlineRoute(model: string | undefined, config: AppConfig): boole
|
|||
return config.Providers.some((provider) => provider.name.trim().toLowerCase() === providerName);
|
||||
}
|
||||
|
||||
function isSubagentModelPlaceholder(model: string): boolean {
|
||||
return model.trim().toLowerCase() === ccrSubagentModelPlaceholder;
|
||||
}
|
||||
|
||||
function calculateTokenCount(messages: unknown, system: unknown, tools: unknown): number {
|
||||
return countMessageTokens(messages) + countSystemTokens(system) + countToolTokens(tools);
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { loadModelCatalogPayload } from "../../main/model-catalog-file";
|
||||
import { loadModelCatalogPayload } from "@ccr/core/models/catalog-file";
|
||||
|
||||
const claudeCodeDefaultContextTokens = 200_000;
|
||||
let modelCatalogIndex: ModelCatalogIndex | undefined;
|
||||
23
packages/core/src/gateway/runtime-change.ts
Normal file
23
packages/core/src/gateway/runtime-change.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import type { AppConfig } from "@ccr/core/contracts/app";
|
||||
|
||||
export function shouldRestartGatewayForRuntimeConfigChange(previousConfig: AppConfig, nextConfig: AppConfig): boolean {
|
||||
return (
|
||||
previousConfig.gateway.enabled !== nextConfig.gateway.enabled ||
|
||||
previousConfig.gateway.host !== nextConfig.gateway.host ||
|
||||
previousConfig.gateway.port !== nextConfig.gateway.port ||
|
||||
previousConfig.gateway.coreHost !== nextConfig.gateway.coreHost ||
|
||||
previousConfig.gateway.corePort !== nextConfig.gateway.corePort ||
|
||||
previousConfig.proxy.enabled !== nextConfig.proxy.enabled ||
|
||||
previousConfig.proxy.host !== nextConfig.proxy.host ||
|
||||
previousConfig.proxy.mode !== nextConfig.proxy.mode ||
|
||||
previousConfig.proxy.port !== nextConfig.proxy.port ||
|
||||
previousConfig.proxy.systemProxy !== nextConfig.proxy.systemProxy ||
|
||||
JSON.stringify(previousConfig.proxy.targets) !== JSON.stringify(nextConfig.proxy.targets) ||
|
||||
JSON.stringify(previousConfig.agent) !== JSON.stringify(nextConfig.agent) ||
|
||||
JSON.stringify(previousConfig.Providers) !== JSON.stringify(nextConfig.Providers) ||
|
||||
JSON.stringify(previousConfig.plugins) !== JSON.stringify(nextConfig.plugins) ||
|
||||
JSON.stringify(previousConfig.providerPlugins) !== JSON.stringify(nextConfig.providerPlugins) ||
|
||||
JSON.stringify(previousConfig.toolHub) !== JSON.stringify(nextConfig.toolHub) ||
|
||||
JSON.stringify(previousConfig.virtualModelProfiles) !== JSON.stringify(nextConfig.virtualModelProfiles)
|
||||
);
|
||||
}
|
||||
|
|
@ -22,35 +22,36 @@ import type {
|
|||
VirtualModelFusionVisionConfig,
|
||||
VirtualModelFusionWebSearchConfig,
|
||||
VirtualModelFusionWebSearchProvider
|
||||
} from "../../shared/app";
|
||||
} from "@ccr/core/contracts/app";
|
||||
import {
|
||||
CLAUDE_APP_FALLBACK_MODEL,
|
||||
buildClaudeAppGatewayModelRoutes,
|
||||
inferClaudeAppGatewayTargetModel,
|
||||
resolveClaudeAppGatewayRouteModel,
|
||||
type ClaudeAppGatewayModelRouteOptions
|
||||
} from "../../shared/claude-app-gateway";
|
||||
} from "@ccr/core/agents/claude-app/gateway-routes";
|
||||
import {
|
||||
BUILTIN_FUSION_VISION_TOOL_NAME,
|
||||
BUILTIN_FUSION_WEB_SEARCH_TOOL_NAME,
|
||||
NO_AVAILABLE_GATEWAY_MODELS_MESSAGE,
|
||||
ROUTER_FALLBACK_MAX_RETRY_COUNT,
|
||||
hasAvailableGatewayModels
|
||||
} from "../../shared/app";
|
||||
import { findProviderPresetByBaseUrl, providerApiKeySafetyIssue } from "../../main/presets";
|
||||
import { normalizeProviderBaseUrl as normalizeProviderBaseUrlInput } from "../../shared/provider-url";
|
||||
import { backendService } from "../backend-service";
|
||||
import { RAW_TRACE_SPOOL_DIR } from "../../main/constants";
|
||||
import { loadPersistedApiKeys } from "../../main/api-key-store";
|
||||
import { codexDefaultBaseUrl, readCodexAuth } from "../../main/local-agent-provider-service";
|
||||
import { fetchWithSystemProxy, getSystemProxyUrlForProtocol } from "../../main/system-proxy-fetch";
|
||||
import { handleNetworkCaptureMcpRequest, isNetworkCaptureMcpPath } from "../mcp/network-capture-mcp";
|
||||
import { pluginService } from "../../main/plugins/service";
|
||||
import { proxyService } from "../proxy/service";
|
||||
import { createSseErrorDetector, recordGatewayRequestLog, updateGatewayRequestLogFromRawTrace, type RequestLogRawTraceUpdateInput } from "../../main/request-log-store";
|
||||
import { recordGatewayUsageCapture } from "../../main/usage-store";
|
||||
import { ClaudeCodeRouterPlugin, normalizeRouteSelector } from "./claude-code-router-plugin";
|
||||
import { ccrRemoteControlPathPrefix, ccrRemoteControlService } from "./remote-control-service";
|
||||
} from "@ccr/core/contracts/app";
|
||||
import { findProviderPresetByBaseUrl, providerApiKeySafetyIssue } from "@ccr/core/providers/presets/index";
|
||||
import { normalizeProviderBaseUrl as normalizeProviderBaseUrlInput } from "@ccr/core/providers/url";
|
||||
import { backendService } from "@ccr/core/plugins/backend-service";
|
||||
import { RAW_TRACE_SPOOL_DIR } from "@ccr/core/config/constants";
|
||||
import { loadPersistedApiKeys } from "@ccr/core/config/api-key-store";
|
||||
import { codexDefaultBaseUrl, readCodexAuth } from "@ccr/core/agents/local-providers/service";
|
||||
import { fetchWithSystemProxy, getSystemProxyUrlForProtocol } from "@ccr/core/proxy/system-proxy-fetch";
|
||||
import { handleNetworkCaptureMcpRequest, isNetworkCaptureMcpPath } from "@ccr/core/mcp/network-capture-mcp";
|
||||
import { BROWSER_AUTOMATION_MCP_PATH, TOOL_HUB_MCP_SERVER_NAME, browserAutomationMcpEnabled, toolHubBuiltInBackendServers, toolHubMcpRuntimeConfig, toolHubRequestTimeoutMs } from "@ccr/core/mcp/toolhub-config";
|
||||
import { pluginService } from "@ccr/core/plugins/service";
|
||||
import { proxyService } from "@ccr/core/proxy/service";
|
||||
import { createSseErrorDetector, recordGatewayRequestLog, updateGatewayRequestLogFromRawTrace, type RequestLogRawTraceUpdateInput } from "@ccr/core/observability/request-log-store";
|
||||
import { recordGatewayUsageCapture } from "@ccr/core/usage/store";
|
||||
import { ClaudeCodeRouterPlugin, normalizeRouteSelector } from "@ccr/core/gateway/claude-code-router-plugin";
|
||||
import { ccrRemoteControlPathPrefix, ccrRemoteControlService } from "@ccr/core/gateway/remote-control-service";
|
||||
import {
|
||||
claudeCodeEffectiveMaxInputTokens,
|
||||
findModelCatalogEntry,
|
||||
|
|
@ -59,7 +60,7 @@ import {
|
|||
readCatalogCapability,
|
||||
type ModelCatalogCapabilities,
|
||||
type ModelCatalogEntry
|
||||
} from "./model-catalog";
|
||||
} from "@ccr/core/gateway/model-catalog";
|
||||
|
||||
type CoreGatewayProvider = {
|
||||
apikey?: string;
|
||||
|
|
@ -129,6 +130,7 @@ export type BrowserWebSearchMcpRegistration = {
|
|||
|
||||
export type BrowserWebSearchProtocolResult = {
|
||||
content?: string;
|
||||
diagnostics?: string[];
|
||||
snippet?: string;
|
||||
title: string;
|
||||
url: string;
|
||||
|
|
@ -150,6 +152,11 @@ export type BrowserWebSearchMcpIntegration = {
|
|||
stopBrowserWebSearchMcpServers: () => Promise<void>;
|
||||
};
|
||||
|
||||
export type BrowserAutomationMcpIntegration = {
|
||||
handleBrowserAutomationMcpRequest: (request: IncomingMessage, response: ServerResponse) => Promise<void>;
|
||||
stopBrowserAutomationMcpServer: () => Promise<void>;
|
||||
};
|
||||
|
||||
type CoreGatewayHealth = {
|
||||
runtimeId?: string;
|
||||
status?: string;
|
||||
|
|
@ -311,6 +318,7 @@ const persistedApiKeyCacheTtlMs = 1000;
|
|||
let persistedApiKeyCache: { loadedAt: number; values: ApiKeyConfig[] } | undefined;
|
||||
|
||||
class GatewayService {
|
||||
private browserAutomationMcpIntegration?: BrowserAutomationMcpIntegration;
|
||||
private browserWebSearchMcpIntegration?: BrowserWebSearchMcpIntegration;
|
||||
private child?: ChildProcess;
|
||||
private config?: AppConfig;
|
||||
|
|
@ -331,14 +339,19 @@ class GatewayService {
|
|||
this.browserWebSearchMcpIntegration = integration;
|
||||
}
|
||||
|
||||
setBrowserAutomationMcpIntegration(integration: BrowserAutomationMcpIntegration): void {
|
||||
this.browserAutomationMcpIntegration = integration;
|
||||
}
|
||||
|
||||
async start(config: AppConfig): Promise<GatewayStatus> {
|
||||
const coreHostError = loopbackCoreHostError(config.gateway.coreHost);
|
||||
if (coreHostError) {
|
||||
return {
|
||||
this.status = {
|
||||
...this.getStatus(),
|
||||
lastError: coreHostError,
|
||||
state: "error"
|
||||
};
|
||||
return this.status;
|
||||
}
|
||||
await this.stop();
|
||||
this.config = config;
|
||||
|
|
@ -379,7 +392,7 @@ class GatewayService {
|
|||
}
|
||||
|
||||
if (shouldRunGateway) {
|
||||
await writeCoreGatewayConfig(config, this.rawTraceSyncToken, this.browserWebSearchMcpIntegration);
|
||||
await writeCoreGatewayConfig(config, this.rawTraceSyncToken, this.coreAuthToken, this.browserWebSearchMcpIntegration);
|
||||
await stopPreviousManagedCoreGateway(config, this.status.coreEndpoint);
|
||||
if (await isCoreGatewayHealthy(this.status.coreEndpoint)) {
|
||||
throw new Error(`Core gateway endpoint is already in use: ${this.status.coreEndpoint}`);
|
||||
|
|
@ -388,11 +401,12 @@ class GatewayService {
|
|||
const runtimeId = randomUUID();
|
||||
const upstreamProxyUrl = proxyService.getUpstreamProxyUrl("https") ?? await getSystemProxyUrlForProtocol("https");
|
||||
this.child = spawnGatewayProcess(config, upstreamProxyUrl, runtimeId, this.coreAuthToken);
|
||||
const managedChild = this.child;
|
||||
writeManagedCoreGatewayMarker(config, this.child, runtimeId);
|
||||
this.child.stdout?.on("data", (chunk) => console.info(`[gateway] ${chunk.toString().trimEnd()}`));
|
||||
this.child.stderr?.on("data", (chunk) => console.warn(`[gateway] ${chunk.toString().trimEnd()}`));
|
||||
this.child.on("exit", (code, signal) => {
|
||||
void this.handleCoreGatewayExit(code, signal);
|
||||
void this.handleCoreGatewayExit(managedChild, code, signal);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -437,6 +451,9 @@ class GatewayService {
|
|||
await this.browserWebSearchMcpIntegration?.stopBrowserWebSearchMcpServers().catch((error) => {
|
||||
console.warn(`[gateway] Failed to stop browser web search MCP: ${formatError(error)}`);
|
||||
});
|
||||
await this.browserAutomationMcpIntegration?.stopBrowserAutomationMcpServer().catch((error) => {
|
||||
console.warn(`[gateway] Failed to stop browser automation MCP: ${formatError(error)}`);
|
||||
});
|
||||
|
||||
this.status = {
|
||||
...this.status,
|
||||
|
|
@ -495,8 +512,8 @@ class GatewayService {
|
|||
});
|
||||
}
|
||||
|
||||
private async handleCoreGatewayExit(code: number | null, signal: NodeJS.Signals | null): Promise<void> {
|
||||
if (this.status.state === "stopped") {
|
||||
private async handleCoreGatewayExit(child: ChildProcess, code: number | null, signal: NodeJS.Signals | null): Promise<void> {
|
||||
if (this.child !== child || this.status.state === "stopped") {
|
||||
return;
|
||||
}
|
||||
removeManagedCoreGatewayMarker(this.config);
|
||||
|
|
@ -549,6 +566,31 @@ class GatewayService {
|
|||
return;
|
||||
}
|
||||
|
||||
if (path === BROWSER_AUTOMATION_MCP_PATH || path === `${BROWSER_AUTOMATION_MCP_PATH}/`) {
|
||||
if (!browserAutomationMcpEnabled(this.config)) {
|
||||
sendJson(response, 404, {
|
||||
error: {
|
||||
message: "CCR browser automation MCP is disabled."
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
const authorization = await authorize(request, response, this.config);
|
||||
if (!authorization.ok) {
|
||||
return;
|
||||
}
|
||||
if (!this.browserAutomationMcpIntegration) {
|
||||
sendJson(response, 503, {
|
||||
error: {
|
||||
message: "CCR browser automation MCP is only available in the Electron desktop app."
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
await this.browserAutomationMcpIntegration.handleBrowserAutomationMcpRequest(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isNetworkCaptureMcpPath(path)) {
|
||||
if (!this.config.proxy.captureNetwork) {
|
||||
sendJson(response, 404, { error: { message: "Network capture MCP is disabled." } });
|
||||
|
|
@ -635,7 +677,7 @@ class GatewayService {
|
|||
const client = inferGatewayClient(apiKey, request.headers);
|
||||
const cursorCompatPreparation = prepareCursorOpenAICompatChatBody(this.config, client, method, path, requestBody);
|
||||
if (cursorCompatPreparation) {
|
||||
headers["x-ccr-cursor-openai-compat"] = cursorCompatPreparation.diagnostic;
|
||||
headers["x-ccr-cursor-openai-compat"] = sanitizeHeaderValue(cursorCompatPreparation.diagnostic);
|
||||
}
|
||||
let bodyToForward: Buffer | undefined = cursorCompatPreparation?.body ?? requestBody;
|
||||
let routeFallback = this.config.Router.fallback;
|
||||
|
|
@ -643,12 +685,12 @@ class GatewayService {
|
|||
let codexApplyPatchBridgeActive = false;
|
||||
const claudeModelRewrite = prepareClaudeCodeDiscoveredModelRequest(this.config, request.headers, method, path, bodyToForward);
|
||||
if (claudeModelRewrite) {
|
||||
headers["x-ccr-claude-model-discovery"] = claudeModelRewrite.diagnostic;
|
||||
headers["x-ccr-claude-model-discovery"] = sanitizeHeaderValue(claudeModelRewrite.diagnostic);
|
||||
bodyToForward = claudeModelRewrite.body;
|
||||
}
|
||||
const claudeAppModelRewrite = prepareClaudeAppFallbackModelRequest(this.config, method, path, bodyToForward);
|
||||
if (claudeAppModelRewrite) {
|
||||
headers["x-ccr-claude-app-model-rewrite"] = claudeAppModelRewrite.diagnostic;
|
||||
headers["x-ccr-claude-app-model-rewrite"] = sanitizeHeaderValue(claudeAppModelRewrite.diagnostic);
|
||||
bodyToForward = claudeAppModelRewrite.body;
|
||||
routedModel = claudeAppModelRewrite.routedModel;
|
||||
}
|
||||
|
|
@ -665,18 +707,28 @@ class GatewayService {
|
|||
let responseCompleted = false;
|
||||
let onClientDisconnect: (() => void) | undefined;
|
||||
let onResponseFinish: (() => void) | undefined;
|
||||
const handleClientDisconnect = () => {
|
||||
if (responseCompleted || response.writableEnded) {
|
||||
return;
|
||||
}
|
||||
if (!clientDisconnected) {
|
||||
clientDisconnected = true;
|
||||
upstreamAbortController.abort(new Error(clientDisconnectMessage));
|
||||
}
|
||||
onClientDisconnect?.();
|
||||
};
|
||||
|
||||
response.once("finish", () => {
|
||||
responseCompleted = true;
|
||||
onResponseFinish?.();
|
||||
});
|
||||
response.once("close", () => {
|
||||
if (responseCompleted || response.writableEnded) {
|
||||
return;
|
||||
}
|
||||
clientDisconnected = true;
|
||||
upstreamAbortController.abort(new Error(clientDisconnectMessage));
|
||||
onClientDisconnect?.();
|
||||
response.once("close", handleClientDisconnect);
|
||||
response.on("error", () => {
|
||||
// Client-side write failures (EPIPE / ECONNRESET when the client closes
|
||||
// mid-stream, common during tool execution) must not crash the main
|
||||
// process as an Uncaught Exception. Swallow them here; the close handler
|
||||
// above already records the disconnect via writeStreamLog.
|
||||
handleClientDisconnect();
|
||||
});
|
||||
|
||||
const writeRequestLog = (
|
||||
|
|
@ -743,10 +795,10 @@ class GatewayService {
|
|||
});
|
||||
const serialized = Buffer.from(`${JSON.stringify(routed.body)}\n`, "utf8");
|
||||
headers["content-type"] = "application/json";
|
||||
headers["x-ccr-route-reason"] = routed.decision.reason;
|
||||
headers["x-ccr-route-reason"] = sanitizeHeaderValue(routed.decision.reason);
|
||||
routeFallback = routed.decision.fallback ?? routeFallback;
|
||||
if (routed.decision.model) {
|
||||
headers["x-ccr-routed-model"] = routed.decision.model;
|
||||
headers["x-ccr-routed-model"] = sanitizeHeaderValue(routed.decision.model);
|
||||
routedModel = routed.decision.model;
|
||||
}
|
||||
bodyToForward = serialized;
|
||||
|
|
@ -761,10 +813,10 @@ class GatewayService {
|
|||
});
|
||||
const serialized = Buffer.from(`${JSON.stringify(routed.body)}\n`, "utf8");
|
||||
headers["content-type"] = "application/json";
|
||||
headers["x-ccr-route-reason"] = routed.decision.reason;
|
||||
headers["x-ccr-route-reason"] = sanitizeHeaderValue(routed.decision.reason);
|
||||
routeFallback = routed.decision.fallback ?? routeFallback;
|
||||
if (routed.decision.model) {
|
||||
headers["x-ccr-routed-model"] = routed.decision.model;
|
||||
headers["x-ccr-routed-model"] = sanitizeHeaderValue(routed.decision.model);
|
||||
routedModel = routed.decision.model;
|
||||
}
|
||||
bodyToForward = serialized;
|
||||
|
|
@ -781,7 +833,7 @@ class GatewayService {
|
|||
if (codexApplyPatchBridgeRequest) {
|
||||
bodyToForward = codexApplyPatchBridgeRequest.body;
|
||||
codexApplyPatchBridgeActive = true;
|
||||
headers["x-ccr-codex-patch-bridge"] = codexApplyPatchBridgeRequest.diagnostic;
|
||||
headers["x-ccr-codex-patch-bridge"] = sanitizeHeaderValue(codexApplyPatchBridgeRequest.diagnostic);
|
||||
headers["content-type"] = "application/json";
|
||||
}
|
||||
|
||||
|
|
@ -807,6 +859,15 @@ class GatewayService {
|
|||
sinceMs: startedAt - 1_000
|
||||
});
|
||||
|
||||
if (hostedWebSearchProtocolContext && !this.browserWebSearchMcpIntegration) {
|
||||
const message = browserWebSearchUnavailableMessage(hostedWebSearchProtocolContext.toolName);
|
||||
const responseHeaders = new Headers({ "content-type": "application/json; charset=utf-8" });
|
||||
const responseBody = JSON.stringify({ error: { message } });
|
||||
writeRequestLog(503, responseHeaders, responseBody, false, message);
|
||||
sendJson(response, 503, { error: { message } });
|
||||
return;
|
||||
}
|
||||
|
||||
if (hostedWebSearchProtocolContext && this.browserWebSearchMcpIntegration) {
|
||||
const records = await selectHostedWebSearchProtocolRecords(
|
||||
hostedWebSearchProtocolContext,
|
||||
|
|
@ -906,10 +967,21 @@ class GatewayService {
|
|||
bodyToForward = upstreamResult.attempt.body ?? bodyToForward;
|
||||
routedModel = upstreamResult.attempt.model ?? routedModel;
|
||||
const responseHeaders = rewriteCapabilityResponseHeaders(
|
||||
mergeFallbackResponseHeaders(upstreamResponseHeaders(upstreamResult), upstreamResult),
|
||||
// Copy into a mutable Headers instance: upstream fetch Response.headers
|
||||
// can be immutable (TypeError: immutable on .delete/.set), and
|
||||
// mergeFallbackResponseHeaders returns the original object as-is when
|
||||
// no fallback occurred. Codex apply_patch / web-search paths call
|
||||
// .delete("content-length") below, which would otherwise throw and
|
||||
// surface as a 502.
|
||||
new Headers(mergeFallbackResponseHeaders(upstreamResponseHeaders(upstreamResult), upstreamResult)),
|
||||
this.config
|
||||
);
|
||||
const upstreamResponse = upstreamResult.response;
|
||||
if (clientDisconnected || upstreamAbortController.signal.aborted) {
|
||||
await cancelResponseBody(upstreamResponse);
|
||||
writeRequestLog(clientClosedRequestStatusCode, responseHeaders, "", false, clientDisconnectMessage);
|
||||
return;
|
||||
}
|
||||
if (codexApplyPatchBridgeActive) {
|
||||
responseHeaders.delete("content-length");
|
||||
}
|
||||
|
|
@ -923,6 +995,11 @@ class GatewayService {
|
|||
responseHeaders.delete("content-length");
|
||||
}
|
||||
recordProviderCredentialOutcome(this.config, method, upstreamResult.attempt, upstreamResponse.status, responseHeaders);
|
||||
if (clientDisconnected || response.destroyed) {
|
||||
await cancelResponseBody(upstreamResponse);
|
||||
writeRequestLog(clientClosedRequestStatusCode, responseHeaders, "", false, clientDisconnectMessage);
|
||||
return;
|
||||
}
|
||||
response.writeHead(upstreamResponse.status, Object.fromEntries(filteredResponseHeaders(responseHeaders)));
|
||||
if (!upstreamResponse.body) {
|
||||
if (shouldCaptureUsage) {
|
||||
|
|
@ -957,6 +1034,7 @@ class GatewayService {
|
|||
this.browserWebSearchMcpIntegration
|
||||
)
|
||||
: patchedResponseBody;
|
||||
const responseStreams = uniqueStreams([upstreamBody, patchedResponseBody, responseBody]);
|
||||
const sampler = createBodySampler();
|
||||
const sseErrorDetector = createSseErrorDetector(responseHeaders.get("content-type") ?? undefined);
|
||||
let streamDetectedError: string | undefined;
|
||||
|
|
@ -968,7 +1046,7 @@ class GatewayService {
|
|||
}
|
||||
logRecorded = true;
|
||||
writeRequestLog(
|
||||
upstreamResponse.status,
|
||||
clientDisconnected ? clientClosedRequestStatusCode : upstreamResponse.status,
|
||||
responseHeaders,
|
||||
sampler.read(),
|
||||
sampler.isTruncated(),
|
||||
|
|
@ -977,13 +1055,21 @@ class GatewayService {
|
|||
};
|
||||
onClientDisconnect = () => {
|
||||
writeStreamLog(clientDisconnectMessage);
|
||||
responseBody.destroy(new Error(clientDisconnectMessage));
|
||||
responseBody.unpipe(response);
|
||||
destroyResponseStreams(responseStreams);
|
||||
};
|
||||
onResponseFinish = () => {
|
||||
if (upstreamStreamEnded) {
|
||||
writeStreamLog();
|
||||
}
|
||||
};
|
||||
const onResponseStreamError = (error: Error) => {
|
||||
streamDetectedError ??= sseErrorDetector.finish();
|
||||
writeStreamLog(clientDisconnected ? clientDisconnectMessage : formatError(error));
|
||||
};
|
||||
for (const stream of responseStreams) {
|
||||
stream.on("error", onResponseStreamError);
|
||||
}
|
||||
responseBody.on("data", (chunk) => {
|
||||
sampler.append(chunk);
|
||||
streamDetectedError ??= sseErrorDetector.append(chunk);
|
||||
|
|
@ -995,10 +1081,6 @@ class GatewayService {
|
|||
writeStreamLog();
|
||||
}
|
||||
});
|
||||
responseBody.once("error", (error) => {
|
||||
streamDetectedError ??= sseErrorDetector.finish();
|
||||
writeStreamLog(clientDisconnected ? clientDisconnectMessage : formatError(error));
|
||||
});
|
||||
if (shouldCaptureUsage) {
|
||||
responseBody.once("end", () => {
|
||||
void recordGatewayUsageCapture({
|
||||
|
|
@ -1016,6 +1098,10 @@ class GatewayService {
|
|||
});
|
||||
});
|
||||
}
|
||||
if (clientDisconnected || response.destroyed) {
|
||||
onClientDisconnect();
|
||||
return;
|
||||
}
|
||||
responseBody.pipe(response);
|
||||
}
|
||||
|
||||
|
|
@ -1084,14 +1170,15 @@ export const gatewayService = new GatewayService();
|
|||
async function writeCoreGatewayConfig(
|
||||
config: AppConfig,
|
||||
rawTraceSyncToken: string,
|
||||
coreAuthToken: string,
|
||||
browserWebSearchMcpIntegration?: BrowserWebSearchMcpIntegration
|
||||
): Promise<void> {
|
||||
assertLoopbackCoreHost(config.gateway.coreHost);
|
||||
mkdirSync(dirname(config.gateway.generatedConfigFile), { mode: privateDirMode, recursive: true });
|
||||
const pluginCoreGatewayConfig = pluginService.getCoreGatewayConfig();
|
||||
const providerPlugins = withCodexOauthRuntimeDefaults([
|
||||
...(config.providerPlugins ?? []),
|
||||
...pluginService.getCoreProviderPlugins()
|
||||
...(config.providerPlugins ?? []).filter(providerPluginEnabled),
|
||||
...pluginService.getCoreProviderPlugins().filter(providerPluginEnabled)
|
||||
]);
|
||||
const codexOauthProviderNames = codexOauthLocalProviderNames(providerPlugins);
|
||||
const virtualModelProfiles = normalizeCoreGatewayVirtualModelProfiles(withCodexCompatibleVirtualModelProfiles(withFusionVirtualModelAliases([
|
||||
|
|
@ -1099,7 +1186,7 @@ async function writeCoreGatewayConfig(
|
|||
...pluginService.getVirtualModelProfiles()
|
||||
])), config);
|
||||
const coreEndpoint = endpoint(config.gateway.coreHost, config.gateway.corePort);
|
||||
const builtinToolArtifacts = await fusionBuiltinToolArtifacts(virtualModelProfiles, coreEndpoint, browserWebSearchMcpIntegration);
|
||||
const builtinToolArtifacts = await fusionBuiltinToolArtifacts(virtualModelProfiles, coreEndpoint, coreAuthToken, browserWebSearchMcpIntegration);
|
||||
const providers = [
|
||||
...config.Providers
|
||||
.flatMap((provider) => toCoreGatewayProviders(withCodexOauthProviderBaseUrl(provider, codexOauthProviderNames)))
|
||||
|
|
@ -1108,12 +1195,20 @@ async function writeCoreGatewayConfig(
|
|||
];
|
||||
const pluginAgentConfig = isRecord(pluginCoreGatewayConfig.agent) ? pluginCoreGatewayConfig.agent : {};
|
||||
const pluginMcpServers = Array.isArray(pluginAgentConfig.mcpServers) ? pluginAgentConfig.mcpServers : [];
|
||||
const externalMcpServers = [
|
||||
...pluginMcpServers,
|
||||
...(config.agent?.mcpServers ?? []),
|
||||
...(config.toolHub?.mcpServers ?? [])
|
||||
];
|
||||
const toolHubServer = toolHubMcpServer(config, externalMcpServers);
|
||||
const mcpServers = [
|
||||
...builtinToolArtifacts.mcpServers,
|
||||
...pluginMcpServers,
|
||||
...(config.agent?.mcpServers ?? [])
|
||||
...(toolHubServer ? [toolHubServer] : externalMcpServers)
|
||||
];
|
||||
const fallbackMcpServer = fusionToolFallbackMcpServer(virtualModelProfiles, mcpServers);
|
||||
const fallbackMcpServer = fusionToolFallbackMcpServer(virtualModelProfiles, [
|
||||
...builtinToolArtifacts.mcpServers,
|
||||
...externalMcpServers
|
||||
]);
|
||||
if (fallbackMcpServer) {
|
||||
mcpServers.push(fallbackMcpServer);
|
||||
}
|
||||
|
|
@ -1169,6 +1264,10 @@ function writePrivateTextFile(file: string, content: string): void {
|
|||
}
|
||||
}
|
||||
|
||||
function providerPluginEnabled(plugin: unknown): boolean {
|
||||
return !isRecord(plugin) || plugin.enabled !== false;
|
||||
}
|
||||
|
||||
export function normalizeCoreGatewayVirtualModelProfiles(profiles: unknown[], config: AppConfig): unknown[] {
|
||||
return profiles.map((profile) => normalizeCoreGatewayVirtualModelProfile(profile, config));
|
||||
}
|
||||
|
|
@ -1385,6 +1484,7 @@ function hasOwn(value: Record<string, unknown>, key: string): boolean {
|
|||
async function fusionBuiltinToolArtifacts(
|
||||
profiles: unknown[],
|
||||
coreEndpoint: string,
|
||||
coreAuthToken: string,
|
||||
browserWebSearchMcpIntegration?: BrowserWebSearchMcpIntegration
|
||||
): Promise<{ mcpServers: GatewayMcpServerConfig[]; providers: CoreGatewayProvider[] }> {
|
||||
const providers: CoreGatewayProvider[] = [];
|
||||
|
|
@ -1407,12 +1507,14 @@ async function fusionBuiltinToolArtifacts(
|
|||
const toolServerKey = `vision:${visionConfig.toolName}`;
|
||||
if (!toolServerKeys.has(toolServerKey)) {
|
||||
toolServerKeys.add(toolServerKey);
|
||||
const useGatewayVisionRuntime = !visionConfig.baseUrl;
|
||||
mcpServers.push(fusionBuiltinMcpServer({
|
||||
entry,
|
||||
env: {
|
||||
FUSION_BUILTIN_TOOL_KIND: "vision",
|
||||
FUSION_TOOL_NAME: visionConfig.toolName,
|
||||
...(visionConfig.baseUrl ? { VISION_BASE_URL: visionConfig.baseUrl } : { VISION_GATEWAY_BASE_URL: `${coreEndpoint}/v1` }),
|
||||
...(useGatewayVisionRuntime ? { VISION_GATEWAY_BASE_URL: `${coreEndpoint}/v1` } : { VISION_BASE_URL: visionConfig.baseUrl || "" }),
|
||||
...(useGatewayVisionRuntime && coreAuthToken ? { VISION_GATEWAY_API_KEY: coreAuthToken } : {}),
|
||||
...(resolvedVision.model ? { VISION_MODEL: resolvedVision.model } : {}),
|
||||
...(visionConfig.baseUrl && visionConfig.apiKey ? { VISION_API_KEY: visionConfig.apiKey } : {}),
|
||||
...(visionConfig.timeoutMs ? { VISION_TIMEOUT_MS: String(visionConfig.timeoutMs) } : {})
|
||||
|
|
@ -1460,6 +1562,15 @@ async function fusionBuiltinToolArtifacts(
|
|||
return { mcpServers, providers };
|
||||
}
|
||||
|
||||
export async function fusionBuiltinToolArtifactsForTest(
|
||||
profiles: unknown[],
|
||||
coreEndpoint: string,
|
||||
coreAuthToken: string,
|
||||
browserWebSearchMcpIntegration?: BrowserWebSearchMcpIntegration
|
||||
): Promise<{ mcpServers: GatewayMcpServerConfig[]; providers: unknown[] }> {
|
||||
return fusionBuiltinToolArtifacts(profiles, coreEndpoint, coreAuthToken, browserWebSearchMcpIntegration);
|
||||
}
|
||||
|
||||
function fusionBuiltinMcpServer({
|
||||
entry,
|
||||
env,
|
||||
|
|
@ -1518,56 +1629,146 @@ function bundledFusionToolFallbackMcpEntryPath(): string {
|
|||
return pathJoin(__dirname, "fusion-tool-fallback-mcp.js");
|
||||
}
|
||||
|
||||
function toolHubMcpServer(config: AppConfig, backendServers: unknown[]): GatewayMcpServerConfig | undefined {
|
||||
const toolHub = config.toolHub;
|
||||
const runtimeBackendServers = [
|
||||
...toolHubBuiltInBackendServers(config),
|
||||
...backendServers
|
||||
];
|
||||
const runtimeConfig = toolHubMcpRuntimeConfig(config, runtimeBackendServers);
|
||||
if (!toolHub?.enabled || !runtimeConfig) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
...runtimeConfig,
|
||||
name: uniqueMcpServerName(TOOL_HUB_MCP_SERVER_NAME, runtimeBackendServers),
|
||||
protocolVersion: "2024-11-05",
|
||||
requestTimeoutMs: toolHubRequestTimeoutMs(config, runtimeBackendServers),
|
||||
startupTimeoutMs: 600000,
|
||||
stdioMessageMode: "content-length",
|
||||
transport: "stdio"
|
||||
};
|
||||
}
|
||||
|
||||
export function fusionFallbackToolDefinitions(
|
||||
profiles: unknown[],
|
||||
backedToolNames: Set<string> = new Set()
|
||||
): Array<{ description?: string; inputSchema?: Record<string, unknown>; name: string }> {
|
||||
const byName = new Map<string, { description?: string; inputSchema?: Record<string, unknown>; name: string }>();
|
||||
): FusionFallbackToolDefinition[] {
|
||||
const byName = new Map<string, FusionFallbackToolDefinition>();
|
||||
|
||||
for (const profile of profiles) {
|
||||
if (!isRecord(profile) || profile.enabled === false || !Array.isArray(profile.tools)) {
|
||||
if (!isRecord(profile) || profile.enabled === false) {
|
||||
continue;
|
||||
}
|
||||
for (const tool of profile.tools) {
|
||||
if (!isRecord(tool)) {
|
||||
continue;
|
||||
}
|
||||
const name = stringValue(tool.name);
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
if (backedToolNames.has(name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = byName.get(name);
|
||||
const description = stringValue(tool.description);
|
||||
const inputSchema = isRecord(tool.inputSchema)
|
||||
? tool.inputSchema
|
||||
: isRecord(tool.input_schema)
|
||||
? tool.input_schema
|
||||
: undefined;
|
||||
if (existing) {
|
||||
if (!existing.description && description) {
|
||||
existing.description = description;
|
||||
if (Array.isArray(profile.tools)) {
|
||||
for (const tool of profile.tools) {
|
||||
if (!isRecord(tool)) {
|
||||
continue;
|
||||
}
|
||||
if (!existing.inputSchema && inputSchema) {
|
||||
existing.inputSchema = inputSchema;
|
||||
const name = stringValue(tool.name);
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
if (backedToolNames.has(name)) {
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
byName.set(name, {
|
||||
...(description ? { description } : {}),
|
||||
...(inputSchema ? { inputSchema } : {}),
|
||||
name
|
||||
});
|
||||
const existing = byName.get(name);
|
||||
const description = stringValue(tool.description);
|
||||
const inputSchema = isRecord(tool.inputSchema)
|
||||
? tool.inputSchema
|
||||
: isRecord(tool.input_schema)
|
||||
? tool.input_schema
|
||||
: undefined;
|
||||
const unavailableMessage = fusionFallbackToolUnavailableMessage(profile, name);
|
||||
if (existing) {
|
||||
if (!existing.description && description) {
|
||||
existing.description = description;
|
||||
}
|
||||
if (!existing.inputSchema && inputSchema) {
|
||||
existing.inputSchema = inputSchema;
|
||||
}
|
||||
if (!existing.unavailableMessage && unavailableMessage) {
|
||||
existing.unavailableMessage = unavailableMessage;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
byName.set(name, {
|
||||
...(description ? { description } : {}),
|
||||
...(inputSchema ? { inputSchema } : {}),
|
||||
...(unavailableMessage ? { unavailableMessage } : {}),
|
||||
name
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const browserFallback = browserWebSearchFallbackToolDefinition(profile, backedToolNames);
|
||||
if (browserFallback && !byName.has(browserFallback.name)) {
|
||||
byName.set(browserFallback.name, browserFallback);
|
||||
}
|
||||
}
|
||||
|
||||
return [...byName.values()];
|
||||
}
|
||||
|
||||
type FusionFallbackToolDefinition = {
|
||||
description?: string;
|
||||
inputSchema?: Record<string, unknown>;
|
||||
name: string;
|
||||
unavailableMessage?: string;
|
||||
};
|
||||
|
||||
function fusionFallbackToolUnavailableMessage(profile: unknown, toolName: string): string | undefined {
|
||||
if (!isRecord(profile)) {
|
||||
return undefined;
|
||||
}
|
||||
const metadata = isRecord(profile.metadata) ? profile.metadata : undefined;
|
||||
const fusionWebSearch = isRecord(metadata?.fusionWebSearch) ? metadata.fusionWebSearch : undefined;
|
||||
const webSearchConfig = readFusionWebSearchConfig(fusionWebSearch);
|
||||
if (webSearchConfig?.provider !== "browser" || webSearchConfig.toolName !== toolName) {
|
||||
return undefined;
|
||||
}
|
||||
return browserWebSearchUnavailableMessage(toolName);
|
||||
}
|
||||
|
||||
function browserWebSearchUnavailableMessage(toolName: string): string {
|
||||
return [
|
||||
`Fusion MCP tool "${toolName}" is unavailable because In-app Browser web search requires CCR Desktop.`,
|
||||
"This runtime did not register the Electron browser web search integration, so the hidden browser search tool cannot run here.",
|
||||
"Run the profile in CCR Desktop or switch the Fusion web search provider to Brave, Bing, Google CSE, Serper, SerpAPI, Tavily, or Exa."
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
function browserWebSearchFallbackToolDefinition(
|
||||
profile: Record<string, unknown>,
|
||||
backedToolNames: Set<string>
|
||||
): FusionFallbackToolDefinition | undefined {
|
||||
const metadata = isRecord(profile.metadata) ? profile.metadata : undefined;
|
||||
const fusionWebSearch = isRecord(metadata?.fusionWebSearch) ? metadata.fusionWebSearch : undefined;
|
||||
const webSearchConfig = readFusionWebSearchConfig(fusionWebSearch);
|
||||
if (webSearchConfig?.provider !== "browser" || !webSearchConfig.toolName || backedToolNames.has(webSearchConfig.toolName)) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
description: "Fallback registration for CCR In-app Browser web search when the Electron browser integration is unavailable.",
|
||||
inputSchema: {
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
count: { maximum: 20, minimum: 1, type: "number" },
|
||||
prompt: { type: "string" },
|
||||
query: { type: "string" }
|
||||
},
|
||||
required: ["prompt"],
|
||||
type: "object"
|
||||
},
|
||||
name: webSearchConfig.toolName,
|
||||
unavailableMessage: fusionFallbackToolUnavailableMessage(profile, webSearchConfig.toolName)
|
||||
};
|
||||
}
|
||||
|
||||
export function fusionToolNamesBackedByMcpServers(servers: unknown[]): Set<string> {
|
||||
const names = new Set<string>();
|
||||
for (const server of servers) {
|
||||
|
|
@ -2993,7 +3194,8 @@ function hostedWebSearchEvidenceText(records: BrowserWebSearchProtocolRecord[],
|
|||
const content = focusedWebSearchContent(result.content, queryHint);
|
||||
const details = [
|
||||
result.snippet ? `Search snippet: ${result.snippet}` : "",
|
||||
content ? `Extracted page content: ${content}` : ""
|
||||
content ? `Extracted page content: ${content}` : "",
|
||||
result.diagnostics?.length ? `Diagnostics: ${result.diagnostics.join("; ")}` : ""
|
||||
].filter(Boolean).join("\n");
|
||||
return [
|
||||
`${resultIndex + 1}. ${result.title}`,
|
||||
|
|
@ -5157,7 +5359,8 @@ function anthropicWebSearchResultBlock(result: BrowserWebSearchProtocolResult):
|
|||
function anthropicWebSearchResultSnippet(result: BrowserWebSearchProtocolResult): string | undefined {
|
||||
const parts = [
|
||||
result.snippet ? `Search snippet: ${sanitizeWebSearchEvidenceText(result.snippet)}` : "",
|
||||
result.content ? `Extracted page content: ${sanitizeWebSearchEvidenceText(result.content)}` : ""
|
||||
result.content ? `Extracted page content: ${sanitizeWebSearchEvidenceText(result.content)}` : "",
|
||||
result.diagnostics?.length ? `Diagnostics: ${result.diagnostics.join("; ")}` : ""
|
||||
].filter(Boolean);
|
||||
return parts.length > 0 ? parts.join("\n") : undefined;
|
||||
}
|
||||
|
|
@ -5498,7 +5701,7 @@ async function fetchUpstreamWithFallback(input: {
|
|||
});
|
||||
|
||||
if (hasNextAttempt && shouldFallbackAfterStatus(response.status, fallbackMode)) {
|
||||
const delayMs = retryDelayAfterStatus(response.status, response, failedAttempts.length);
|
||||
const delayMs = retryDelayAfterStatus(response.status, response.headers, failedAttempts.length);
|
||||
failedAttempts.push({
|
||||
credentialChain: attempt.credentialChain,
|
||||
credentialIds: attempt.credentialIds,
|
||||
|
|
@ -5521,10 +5724,13 @@ async function fetchUpstreamWithFallback(input: {
|
|||
};
|
||||
} catch (error) {
|
||||
const message = formatError(error);
|
||||
const delayMs = hasNextAttempt && !input.signal?.aborted
|
||||
? retryDelayAfterNetworkError(failedAttempts.length)
|
||||
: 0;
|
||||
failedAttempts.push({
|
||||
credentialChain: attempt.credentialChain,
|
||||
credentialIds: attempt.credentialIds,
|
||||
delayMs: 0,
|
||||
delayMs,
|
||||
error: message,
|
||||
model: attempt.model
|
||||
});
|
||||
|
|
@ -5536,6 +5742,9 @@ async function fetchUpstreamWithFallback(input: {
|
|||
});
|
||||
}
|
||||
if (hasNextAttempt) {
|
||||
if (delayMs > 0) {
|
||||
await delay(delayMs);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
throw new UpstreamRequestError(message, {
|
||||
|
|
@ -5560,12 +5769,19 @@ function prepareUpstreamCredentialAttempt(input: {
|
|||
}): UpstreamAttempt {
|
||||
const normalizedBody = normalizeConfiguredProviderModelBody(input.attempt.body, input.config);
|
||||
const target = resolveProviderCredentialRoutingTarget(input.config, input.headers, input.path, input.attempt.body);
|
||||
const attemptBody = (body: Buffer | undefined) => usageAwareOpenAiChatAttemptBody({
|
||||
body,
|
||||
config: input.config,
|
||||
path: input.path,
|
||||
target
|
||||
});
|
||||
if (!target) {
|
||||
const body = bodyHasConfiguredProviderModelSelector(input.attempt.body, input.config)
|
||||
? input.attempt.body
|
||||
: normalizedBody?.body ?? input.attempt.body;
|
||||
return {
|
||||
...input.attempt,
|
||||
body: bodyHasConfiguredProviderModelSelector(input.attempt.body, input.config)
|
||||
? input.attempt.body
|
||||
: normalizedBody?.body ?? input.attempt.body,
|
||||
body: attemptBody(body),
|
||||
headers: input.headers
|
||||
};
|
||||
}
|
||||
|
|
@ -5574,7 +5790,7 @@ function prepareUpstreamCredentialAttempt(input: {
|
|||
if (credentials.length === 0) {
|
||||
return {
|
||||
...input.attempt,
|
||||
body: target.body ?? normalizedBody?.body ?? input.attempt.body,
|
||||
body: attemptBody(target.body ?? normalizedBody?.body ?? input.attempt.body),
|
||||
headers: input.headers
|
||||
};
|
||||
}
|
||||
|
|
@ -5584,7 +5800,7 @@ function prepareUpstreamCredentialAttempt(input: {
|
|||
if (selection.credentials.length === 0) {
|
||||
return {
|
||||
...input.attempt,
|
||||
body: target.body ?? normalizedBody?.body ?? input.attempt.body,
|
||||
body: attemptBody(target.body ?? normalizedBody?.body ?? input.attempt.body),
|
||||
headers: input.headers
|
||||
};
|
||||
}
|
||||
|
|
@ -5592,7 +5808,7 @@ function prepareUpstreamCredentialAttempt(input: {
|
|||
const headers: Record<string, string> = {
|
||||
...input.headers,
|
||||
"x-target-providers": selection.credentials.map((candidate) => candidate.internalName).join(","),
|
||||
"x-ccr-logical-provider": target.provider.name,
|
||||
"x-ccr-logical-provider": providerRuntimeId(target.provider),
|
||||
"x-ccr-provider-credential-chain": selection.credentials.map((candidate) => candidate.credentialId).join(",")
|
||||
};
|
||||
delete headers["x-target-provider"];
|
||||
|
|
@ -5602,7 +5818,7 @@ function prepareUpstreamCredentialAttempt(input: {
|
|||
|
||||
return {
|
||||
...input.attempt,
|
||||
body: target.body ?? normalizedBody?.body ?? input.attempt.body,
|
||||
body: attemptBody(target.body ?? normalizedBody?.body ?? input.attempt.body),
|
||||
credentialChain: selection.credentials.map((candidate) => candidate.internalName),
|
||||
credentialIds: selection.credentials.map((candidate) => candidate.credentialId),
|
||||
credentialProtocol: target.protocol,
|
||||
|
|
@ -5611,6 +5827,53 @@ function prepareUpstreamCredentialAttempt(input: {
|
|||
};
|
||||
}
|
||||
|
||||
function usageAwareOpenAiChatAttemptBody(input: {
|
||||
body: Buffer | undefined;
|
||||
config: AppConfig;
|
||||
path: string;
|
||||
target?: { protocol: GatewayProviderProtocol };
|
||||
}): Buffer | undefined {
|
||||
if (input.target?.protocol === "openai_chat_completions") {
|
||||
return usageAwareOpenAiChatBody(input.body);
|
||||
}
|
||||
|
||||
const protocol = requestProtocolForPath(input.path);
|
||||
if (!protocol) {
|
||||
return input.body;
|
||||
}
|
||||
|
||||
const parsedBody = parseJsonObjectSafe(input.body);
|
||||
const modelSelector = resolveConfiguredProviderModelSelector(stringValue(parsedBody?.model), input.config);
|
||||
const providerProtocol = modelSelector
|
||||
? providerProtocolForClientProtocol(modelSelector.provider, protocol)
|
||||
: undefined;
|
||||
return providerProtocol === "openai_chat_completions"
|
||||
? usageAwareOpenAiChatBody(input.body)
|
||||
: input.body;
|
||||
}
|
||||
|
||||
function usageAwareOpenAiChatBody(body: Buffer | undefined): Buffer | undefined {
|
||||
const parsedBody = parseJsonObjectSafe(body);
|
||||
if (!parsedBody || parsedBody.stream !== true) {
|
||||
return body;
|
||||
}
|
||||
const streamOptions = isRecord(parsedBody.stream_options)
|
||||
? parsedBody.stream_options
|
||||
: isRecord(parsedBody.streamOptions)
|
||||
? parsedBody.streamOptions
|
||||
: {};
|
||||
if (streamOptions.include_usage === true || streamOptions.includeUsage === true) {
|
||||
return body;
|
||||
}
|
||||
return Buffer.from(`${JSON.stringify({
|
||||
...parsedBody,
|
||||
stream_options: {
|
||||
...streamOptions,
|
||||
include_usage: true
|
||||
}
|
||||
})}\n`, "utf8");
|
||||
}
|
||||
|
||||
function normalizeConfiguredProviderModelBody(
|
||||
body: Buffer | undefined,
|
||||
config: AppConfig
|
||||
|
|
@ -5933,17 +6196,30 @@ function shouldFallbackAfterStatus(statusCode: number, mode: RouterFallbackMode)
|
|||
return false;
|
||||
}
|
||||
|
||||
function retryDelayAfterStatus(statusCode: number, response: Response, failedAttemptIndex: number): number {
|
||||
if (statusCode !== 429) {
|
||||
return 0;
|
||||
}
|
||||
const retryAfterMs = parseRetryAfterHeaderMs(response.headers.get("retry-after"));
|
||||
if (retryAfterMs !== undefined) {
|
||||
return clampNumber(retryAfterMs, 0, upstreamRetryAfterMaxMs);
|
||||
function retryDelayAfterStatus(_statusCode: number, headers: Headers, failedAttemptIndex: number): number {
|
||||
const retryAfterMs = parseRetryAfterHeaderMs(headers.get("retry-after"));
|
||||
if (retryAfterMs !== undefined && retryAfterMs > 0) {
|
||||
return clampNumber(retryAfterMs, 1, upstreamRetryAfterMaxMs);
|
||||
}
|
||||
return exponentialRetryBackoffMs(failedAttemptIndex);
|
||||
}
|
||||
|
||||
function retryDelayAfterNetworkError(failedAttemptIndex: number): number {
|
||||
return exponentialRetryBackoffMs(failedAttemptIndex);
|
||||
}
|
||||
|
||||
export function fallbackRetryDelayAfterStatusForTest(input: { failedAttemptIndex?: number; retryAfter?: string | null; statusCode: number }): number {
|
||||
const headers = new Headers();
|
||||
if (input.retryAfter !== undefined && input.retryAfter !== null) {
|
||||
headers.set("retry-after", input.retryAfter);
|
||||
}
|
||||
return retryDelayAfterStatus(input.statusCode, headers, input.failedAttemptIndex ?? 0);
|
||||
}
|
||||
|
||||
export function fallbackRetryDelayAfterNetworkErrorForTest(failedAttemptIndex = 0): number {
|
||||
return retryDelayAfterNetworkError(failedAttemptIndex);
|
||||
}
|
||||
|
||||
function parseRetryAfterHeaderMs(value: string | null): number | undefined {
|
||||
const trimmed = value?.trim();
|
||||
if (!trimmed) {
|
||||
|
|
@ -5972,6 +6248,29 @@ async function drainResponseBody(response: Response): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
async function cancelResponseBody(response: Response): Promise<void> {
|
||||
try {
|
||||
await response.body?.cancel();
|
||||
} catch {
|
||||
// The client already disconnected; best-effort upstream cleanup must not mask that expected path.
|
||||
}
|
||||
}
|
||||
|
||||
function uniqueStreams(streams: Readable[]): Readable[] {
|
||||
return [...new Set(streams)];
|
||||
}
|
||||
|
||||
function destroyResponseStreams(streams: Readable[]): void {
|
||||
for (const stream of streams) {
|
||||
if (!stream.destroyed) {
|
||||
// A downstream client close is an expected abort path. Destroying with
|
||||
// an Error would emit another error event on Readable/Transform stages,
|
||||
// and intermediate stages may not be the final responseBody listener.
|
||||
stream.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseJsonObjectSafe(buffer: Buffer | undefined): Record<string, unknown> | undefined {
|
||||
if (!buffer || buffer.byteLength === 0) {
|
||||
return undefined;
|
||||
|
|
@ -6002,7 +6301,7 @@ function mergeFallbackResponseHeaders(headers: Headers, result: UpstreamFetchRes
|
|||
merged.set("x-ccr-fallback-delays-ms", formatFallbackDelays(result.failedAttempts));
|
||||
}
|
||||
if (result.attempt.model) {
|
||||
merged.set("x-ccr-fallback-model", result.attempt.model);
|
||||
merged.set("x-ccr-fallback-model", sanitizeHeaderValue(result.attempt.model));
|
||||
}
|
||||
}
|
||||
if (credentialIds.length) {
|
||||
|
|
@ -6070,6 +6369,11 @@ function resolveGatewayEntry(): string {
|
|||
return entry;
|
||||
}
|
||||
|
||||
const bundledEntry = resolveBundledGatewayEntry();
|
||||
if (bundledEntry) {
|
||||
return bundledEntry;
|
||||
}
|
||||
|
||||
for (const packageName of gatewayPackageCandidates) {
|
||||
try {
|
||||
return requireFromHere.resolve(packageName);
|
||||
|
|
@ -6080,6 +6384,45 @@ function resolveGatewayEntry(): string {
|
|||
return requireFromHere.resolve(gatewayPackageCandidates[0]);
|
||||
}
|
||||
|
||||
function resolveBundledGatewayEntry(): string | undefined {
|
||||
const resourcesPath = (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath;
|
||||
return [
|
||||
pathJoin(__dirname, "next-ai-gateway.js"),
|
||||
...(resourcesPath
|
||||
? [
|
||||
pathJoin(resourcesPath, "app.asar", "dist", "main", "next-ai-gateway.js"),
|
||||
pathJoin(resourcesPath, "app", "dist", "main", "next-ai-gateway.js")
|
||||
]
|
||||
: [])
|
||||
].find((candidate) => existsSync(candidate));
|
||||
}
|
||||
|
||||
function resolveUndiciProxyAgentModule(): string {
|
||||
const bundled = resolveBundledUndiciProxyAgentModule();
|
||||
if (bundled) {
|
||||
return bundled;
|
||||
}
|
||||
|
||||
try {
|
||||
return requireFromHere.resolve("undici");
|
||||
} catch (error) {
|
||||
throw new Error(`Unable to resolve undici ProxyAgent module for gateway proxy preload: ${formatError(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveBundledUndiciProxyAgentModule(): string | undefined {
|
||||
const resourcesPath = (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath;
|
||||
return [
|
||||
pathJoin(__dirname, "undici-proxy-agent.js"),
|
||||
...(resourcesPath
|
||||
? [
|
||||
pathJoin(resourcesPath, "app.asar", "dist", "main", "undici-proxy-agent.js"),
|
||||
pathJoin(resourcesPath, "app", "dist", "main", "undici-proxy-agent.js")
|
||||
]
|
||||
: [])
|
||||
].find((candidate) => existsSync(candidate));
|
||||
}
|
||||
|
||||
function createGatewayProcessEnv(config: AppConfig, upstreamProxyUrl: string | undefined, runtimeId: string, coreAuthToken: string): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
|
|
@ -6118,7 +6461,7 @@ function createGatewayProcessEnv(config: AppConfig, upstreamProxyUrl: string | u
|
|||
env.https_proxy = upstreamProxyUrl;
|
||||
env.all_proxy = upstreamProxyUrl;
|
||||
env.CCR_UPSTREAM_PROXY_URL = upstreamProxyUrl;
|
||||
env.CCR_UNDICI_MODULE = requireFromHere.resolve("undici");
|
||||
env.CCR_UNDICI_MODULE = resolveUndiciProxyAgentModule();
|
||||
return env;
|
||||
}
|
||||
|
||||
|
|
@ -6379,6 +6722,20 @@ function sanitizeProviderHeaderId(value: string | undefined): string | undefined
|
|||
return normalized || undefined;
|
||||
}
|
||||
|
||||
function sanitizeHeaderValue(value: unknown): string {
|
||||
// HTTP header values must be ByteString (code point <= 255). Values derived
|
||||
// from user-facing names — model selectors like "小米mimo/...", provider
|
||||
// names, route reasons — can contain non-ASCII characters that crash Node's
|
||||
// fetch/undici with "Cannot convert argument to a ByteString" (surfaced as
|
||||
// 502). Normalize to ASCII while preserving case and printable punctuation.
|
||||
const text = typeof value === "string" && value.trim() ? value : "unknown";
|
||||
const sanitized = text
|
||||
.replace(/[^\x20-\x7E]+/g, "-")
|
||||
.replace(/-{2,}/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
return sanitized || "unknown";
|
||||
}
|
||||
|
||||
function providerCredentialInternalName(
|
||||
provider: GatewayProviderConfig,
|
||||
protocol: GatewayProviderProtocol,
|
||||
|
|
@ -28,6 +28,7 @@ type McpTool = {
|
|||
description: string;
|
||||
inputSchema: JsonValue;
|
||||
name: string;
|
||||
unavailableMessage?: string;
|
||||
};
|
||||
|
||||
type ToolCallResult = {
|
||||
|
|
@ -134,10 +135,11 @@ async function handleJsonRpcRequest(payload: unknown): Promise<JsonRpcResponse |
|
|||
function callTool(params: unknown): ToolCallResult {
|
||||
const name = isRecord(params) && typeof params.name === "string" ? params.name.trim() : "";
|
||||
const toolLabel = name || "unknown";
|
||||
const tool = tools.find((item) => item.name === toolLabel);
|
||||
const knownSuffix = toolNames.has(toolLabel) ? "" : " The requested tool was not in the fallback catalog.";
|
||||
return {
|
||||
content: [{
|
||||
text:
|
||||
text: tool?.unavailableMessage ||
|
||||
`Fusion MCP tool "${toolLabel}" is temporarily unavailable. ` +
|
||||
"CCR registered a fallback definition because the real MCP server did not provide the tool during discovery. " +
|
||||
`Check the Fusion MCP server logs and retry.${knownSuffix}`,
|
||||
|
|
@ -179,7 +181,8 @@ function readFallbackTools(): McpTool[] {
|
|||
readString(item.description) ||
|
||||
`Fallback registration for Fusion MCP tool "${name}". The real MCP server should handle successful calls.`,
|
||||
inputSchema: isRecord(item.inputSchema) ? item.inputSchema as JsonValue : objectSchema({}),
|
||||
name
|
||||
name,
|
||||
unavailableMessage: readString(item.unavailableMessage)
|
||||
});
|
||||
}
|
||||
return result;
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import packageJson from "../../../package.json";
|
||||
import packageJson from "../../package.json";
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import type { ProxyNetworkExchange } from "../../shared/app";
|
||||
import { proxyService } from "../proxy/service";
|
||||
import type { ProxyNetworkExchange } from "@ccr/core/contracts/app";
|
||||
import { proxyService } from "@ccr/core/proxy/service";
|
||||
|
||||
type JsonPrimitive = boolean | null | number | string;
|
||||
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { fetchWithSystemProxy } from "../../main/system-proxy-fetch";
|
||||
import { fetchWithSystemProxy } from "@ccr/core/proxy/system-proxy-fetch";
|
||||
import type {
|
||||
GatewayMcpRemoteServerConfig,
|
||||
GatewayMcpServerConfig,
|
||||
GatewayMcpStdioServerConfig,
|
||||
GatewayMcpToolInfo
|
||||
} from "../../shared/app";
|
||||
} from "@ccr/core/contracts/app";
|
||||
|
||||
type JsonRpcMessage = {
|
||||
error?: unknown;
|
||||
226
packages/core/src/mcp/toolhub-config.ts
Normal file
226
packages/core/src/mcp/toolhub-config.ts
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
import { join as pathJoin } from "node:path";
|
||||
import { CONFIGDIR } from "@ccr/core/config/constants";
|
||||
import type { AppConfig, GatewayMcpServerConfig } from "@ccr/core/contracts/app";
|
||||
|
||||
export const TOOL_HUB_MCP_SERVER_NAME = "ccr-toolhub";
|
||||
export const TOOL_HUB_MCP_RUNTIME_FILE_NAME = "toolhub-mcp.js";
|
||||
export const BROWSER_AUTOMATION_MCP_SERVER_NAME = "ccr-browser-automation";
|
||||
export const BROWSER_AUTOMATION_MCP_PATH = "/__ccr/browser-automation/mcp";
|
||||
export const BROWSER_AUTOMATION_HANDOFF_TIMEOUT_MS = 600000;
|
||||
export const TOOL_HUB_DEFAULT_REQUEST_TIMEOUT_MS = 60000;
|
||||
|
||||
export type ToolHubMcpRuntimeConfig = {
|
||||
args: string[];
|
||||
command: string;
|
||||
env: Record<string, string>;
|
||||
};
|
||||
|
||||
export type ClaudeCodeMcpServerConfig = ToolHubMcpRuntimeConfig | {
|
||||
args?: string[];
|
||||
command: string;
|
||||
cwd?: string;
|
||||
env?: Record<string, string>;
|
||||
} | {
|
||||
headers?: Record<string, string>;
|
||||
type: "http" | "sse";
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type ToolHubClaudeCodeMcpConfig = {
|
||||
mcpServers: Record<string, ClaudeCodeMcpServerConfig>;
|
||||
};
|
||||
|
||||
export function toolHubBackendServers(
|
||||
config: AppConfig | undefined,
|
||||
extraServers: unknown[] = [],
|
||||
options: {
|
||||
apiKey?: string;
|
||||
includeBuiltIns?: boolean;
|
||||
} = {}
|
||||
): unknown[] {
|
||||
return [
|
||||
...(options.includeBuiltIns === false ? [] : toolHubBuiltInBackendServers(config, options)),
|
||||
...(Array.isArray(config?.agent?.mcpServers) ? config.agent.mcpServers : []),
|
||||
...(Array.isArray(config?.toolHub?.mcpServers) ? config.toolHub.mcpServers : []),
|
||||
...extraServers
|
||||
].filter(isToolHubBackendServer);
|
||||
}
|
||||
|
||||
export function toolHubBuiltInBackendServers(
|
||||
config: AppConfig | undefined,
|
||||
options: {
|
||||
apiKey?: string;
|
||||
} = {}
|
||||
): GatewayMcpServerConfig[] {
|
||||
if (!config || !browserAutomationMcpEnabled(config) || !hasGatewayEndpoint(config)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
apiKey: options.apiKey || firstConfiguredApiKey(config),
|
||||
headers: {},
|
||||
name: BROWSER_AUTOMATION_MCP_SERVER_NAME,
|
||||
protocolVersion: "2024-11-05",
|
||||
requestTimeoutMs: BROWSER_AUTOMATION_HANDOFF_TIMEOUT_MS,
|
||||
startupTimeoutMs: 60000,
|
||||
transport: "streamable-http",
|
||||
url: `${gatewayEndpoint(config)}${BROWSER_AUTOMATION_MCP_PATH}`
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
export function browserAutomationMcpEnabled(config: AppConfig | undefined): boolean {
|
||||
return Boolean(config?.toolHub?.enabled && config.toolHub.browserAutomation);
|
||||
}
|
||||
|
||||
export function toolHubMcpRuntimeConfig(
|
||||
config: AppConfig | undefined,
|
||||
backendServers?: unknown[],
|
||||
options: {
|
||||
command?: string;
|
||||
entryPath?: string;
|
||||
resolver?: {
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
model?: string;
|
||||
};
|
||||
} = {}
|
||||
): ToolHubMcpRuntimeConfig | undefined {
|
||||
const toolHub = config?.toolHub;
|
||||
if (!toolHub?.enabled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const resolvedBackendServers = backendServers ?? toolHubBackendServers(config, [], {
|
||||
apiKey: options.resolver?.apiKey
|
||||
});
|
||||
const normalizedBackendServers = resolvedBackendServers.filter(isToolHubBackendServer);
|
||||
if (normalizedBackendServers.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const requestTimeoutMs = toolHubRequestTimeoutMs(config, normalizedBackendServers);
|
||||
|
||||
return {
|
||||
args: [options.entryPath ?? bundledToolHubMcpEntryPath()],
|
||||
command: options.command ?? process.execPath,
|
||||
env: {
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
TOOLHUB_CACHE_FILE: pathJoin(CONFIGDIR, "toolhub-cache.json"),
|
||||
TOOLHUB_MAX_TOOLS: String(toolHub.maxTools ?? 10),
|
||||
TOOLHUB_MCP_SERVERS_JSON: JSON.stringify(normalizedBackendServers),
|
||||
TOOLHUB_OPENAI_API_KEY: options.resolver?.apiKey ?? toolHub.llm?.apiKey ?? "",
|
||||
TOOLHUB_OPENAI_BASE_URL: options.resolver?.baseUrl ?? toolHub.llm?.baseUrl ?? "https://api.openai.com/v1",
|
||||
TOOLHUB_OPENAI_MODEL: options.resolver?.model ?? toolHub.llm?.model ?? "",
|
||||
TOOLHUB_REQUEST_TIMEOUT_MS: String(requestTimeoutMs)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function toolHubRequestTimeoutMs(config: AppConfig | undefined, backendServers?: unknown[]): number {
|
||||
const configuredTimeout = positiveInteger(config?.toolHub?.requestTimeoutMs, TOOL_HUB_DEFAULT_REQUEST_TIMEOUT_MS);
|
||||
const backendTimeouts = (backendServers ?? toolHubBackendServers(config))
|
||||
.map((server) => isRecord(server) ? positiveInteger(server.requestTimeoutMs, 0) : 0);
|
||||
return Math.max(configuredTimeout, ...backendTimeouts);
|
||||
}
|
||||
|
||||
export function toolHubClaudeCodeMcpConfig(
|
||||
config: AppConfig | undefined,
|
||||
options: Parameters<typeof toolHubMcpRuntimeConfig>[2] = {}
|
||||
): ToolHubClaudeCodeMcpConfig | undefined {
|
||||
const toolHub = config?.toolHub;
|
||||
if (!toolHub?.enabled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const backendServers = toolHubBackendServers(config, [], {
|
||||
apiKey: options.resolver?.apiKey
|
||||
});
|
||||
if (backendServers.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const runtimeConfig = toolHubMcpRuntimeConfig(config, backendServers, options);
|
||||
return runtimeConfig
|
||||
? { mcpServers: { [TOOL_HUB_MCP_SERVER_NAME]: runtimeConfig } }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function bundledToolHubMcpEntryPath(): string {
|
||||
return pathJoin(__dirname, TOOL_HUB_MCP_RUNTIME_FILE_NAME);
|
||||
}
|
||||
|
||||
export function bundledToolHubMcpEntryPathCandidates(): string[] {
|
||||
const resourcesPath = (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath;
|
||||
return uniqueStrings([
|
||||
bundledToolHubMcpEntryPath(),
|
||||
...(resourcesPath
|
||||
? [
|
||||
pathJoin(resourcesPath, "app.asar", "dist", "main", TOOL_HUB_MCP_RUNTIME_FILE_NAME),
|
||||
pathJoin(resourcesPath, "app", "dist", "main", TOOL_HUB_MCP_RUNTIME_FILE_NAME)
|
||||
]
|
||||
: []),
|
||||
pathJoin(process.cwd(), "packages", "electron", "dist", "main", TOOL_HUB_MCP_RUNTIME_FILE_NAME),
|
||||
pathJoin(process.cwd(), "packages", "cli", "dist", "main", TOOL_HUB_MCP_RUNTIME_FILE_NAME),
|
||||
pathJoin(process.cwd(), "packages", "core", "dist", "main", TOOL_HUB_MCP_RUNTIME_FILE_NAME),
|
||||
pathJoin(process.cwd(), "dist", "main", TOOL_HUB_MCP_RUNTIME_FILE_NAME)
|
||||
]);
|
||||
}
|
||||
|
||||
function isToolHubBackendServer(value: unknown): value is Record<string, unknown> {
|
||||
return isRecord(value) && stringValue(value.name)?.toLowerCase() !== TOOL_HUB_MCP_SERVER_NAME;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function firstConfiguredApiKey(config: AppConfig): string | undefined {
|
||||
return (Array.isArray(config.APIKEYS) ? config.APIKEYS : [])
|
||||
.find((apiKey) => apiKey.key.trim())?.key.trim() || stringValue(config.APIKEY);
|
||||
}
|
||||
|
||||
function positiveInteger(value: unknown, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
|
||||
}
|
||||
|
||||
function gatewayEndpoint(config: AppConfig): string {
|
||||
return `http://${formatHost(clientGatewayHost(config.gateway.host))}:${config.gateway.port}`;
|
||||
}
|
||||
|
||||
function hasGatewayEndpoint(config: AppConfig): boolean {
|
||||
const gateway = (config as Partial<AppConfig>).gateway;
|
||||
return Boolean(gateway && stringValue(gateway.host) && Number.isFinite(gateway.port));
|
||||
}
|
||||
|
||||
function formatHost(host: string): string {
|
||||
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
}
|
||||
|
||||
function clientGatewayHost(host: string): string {
|
||||
const value = stringValue(host) ?? "127.0.0.1";
|
||||
if (value === "0.0.0.0") {
|
||||
return "127.0.0.1";
|
||||
}
|
||||
if (value === "::" || value === "[::]") {
|
||||
return "::1";
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function uniqueStrings(values: string[]): string[] {
|
||||
const seen = new Set<string>();
|
||||
const result: string[] = [];
|
||||
for (const value of values) {
|
||||
if (!value || seen.has(value)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(value);
|
||||
result.push(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
2944
packages/core/src/mcp/toolhub-mcp.ts
Normal file
2944
packages/core/src/mcp/toolhub-mcp.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -24,8 +24,11 @@ export function modelCatalogPathCandidates(): string[] {
|
|||
process.env.CCR_MODEL_CATALOG_PATH?.trim() || "",
|
||||
process.env.CCR_MODELS_JSON_PATH?.trim() || "",
|
||||
pathResolve(process.cwd(), "models.json"),
|
||||
pathResolve(process.cwd(), "packages", "core", "models.json"),
|
||||
pathResolve(process.cwd(), "packages", "cli", "models.json"),
|
||||
pathResolve(__dirname, "..", "models.json"),
|
||||
pathResolve(__dirname, "..", "assets", "models.json"),
|
||||
pathResolve(__dirname, "..", "..", "models.json"),
|
||||
pathResolve(__dirname, "..", "..", "..", "models.json")
|
||||
]);
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { fetchWithSystemProxy } from "./system-proxy-fetch";
|
||||
import { fetchWithSystemProxy } from "@ccr/core/proxy/system-proxy-fetch";
|
||||
|
||||
type ModelPricingSource = "litellm" | "models.dev" | "openrouter";
|
||||
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
import { mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
import { REQUEST_LOGS_DB_FILE } from "./constants";
|
||||
import { estimateUsageCostUsd } from "./model-pricing-service";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase } from "./sqlite-native";
|
||||
import { normalizeUsageInputTokens } from "./usage-normalization";
|
||||
import { REQUEST_LOGS_DB_FILE } from "@ccr/core/config/constants";
|
||||
import { estimateUsageCostUsd } from "@ccr/core/models/pricing-service";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase } from "@ccr/core/storage/sqlite-native";
|
||||
import { normalizeUsageInputTokens } from "@ccr/core/usage/normalization";
|
||||
import type {
|
||||
AgentAnalysisAgentRow,
|
||||
AgentAnalysisFilter,
|
||||
|
|
@ -38,7 +38,7 @@ import type {
|
|||
RequestLogRetryAttempt,
|
||||
RequestLogStatusFilter,
|
||||
UsageStatsRange
|
||||
} from "../shared/app";
|
||||
} from "@ccr/core/contracts/app";
|
||||
|
||||
type SqlDatabase = BetterSqliteDatabase;
|
||||
type SqlValue = bigint | Buffer | number | string | null;
|
||||
|
|
@ -2,7 +2,7 @@ import { spawnSync } from "node:child_process";
|
|||
import { readdirSync, statSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { windowsSystemCommand } from "./windows-system";
|
||||
import { windowsSystemCommand } from "@ccr/core/platform/windows-system";
|
||||
|
||||
export type WindowsDesktopAppDiscoveryOptions = {
|
||||
appDirs: string[];
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { copyFileSync, existsSync, mkdirSync, rmSync } from "node:fs";
|
||||
import http, { type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
||||
import path from "node:path";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase, type BetterSqliteStatement } from "../main/sqlite-native";
|
||||
import { createBetterSqliteDatabase, type BetterSqliteDatabase, type BetterSqliteStatement } from "@ccr/core/storage/sqlite-native";
|
||||
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
export type SqliteValue = bigint | Buffer | number | string | Uint8Array | null;
|
||||
|
|
@ -14,9 +14,9 @@ import type {
|
|||
ProviderAccountMeter,
|
||||
ProviderAccountPluginConnectorConfig,
|
||||
ProviderAccountSnapshot
|
||||
} from "../../shared/app";
|
||||
import { backendService, type RegisteredHttpBackend, type SqliteStore, type SqliteStoreOptions } from "../../server/backend-service";
|
||||
import { CONFIGDIR, DATADIR } from "../constants";
|
||||
} from "@ccr/core/contracts/app";
|
||||
import { backendService, type RegisteredHttpBackend, type SqliteStore, type SqliteStoreOptions } from "@ccr/core/plugins/backend-service";
|
||||
import { CONFIGDIR, DATADIR } from "@ccr/core/config/constants";
|
||||
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
type PluginLogger = {
|
||||
|
|
@ -144,6 +144,18 @@ type LoadedPlugin = {
|
|||
stop?: () => MaybePromise<void>;
|
||||
};
|
||||
|
||||
type PluginServiceStateSnapshot = {
|
||||
apps: InstalledBrowserApp[];
|
||||
coreGatewayConfig: Record<string, unknown>;
|
||||
coreProviderPlugins: unknown[];
|
||||
gatewayRoutes: RegisteredGatewayRoute[];
|
||||
providerAccountConnectors: Map<string, GatewayPluginProviderAccountConnector>;
|
||||
proxyRoutes: RegisteredProxyRoute[];
|
||||
resourceOwnerIds: Set<string>;
|
||||
stopHooks: Array<() => MaybePromise<void>>;
|
||||
virtualModelProfiles: unknown[];
|
||||
};
|
||||
|
||||
const requireFromHere = createRequire(__filename);
|
||||
const builtInMarketplacePluginModules = new Map<string, string>([
|
||||
["claude-design", path.join(__dirname, "..", "marketplace", "plugins", "claude-design-plugin.cjs")],
|
||||
|
|
@ -172,8 +184,14 @@ class GatewayPluginService {
|
|||
if (pluginConfig.enabled === false) {
|
||||
continue;
|
||||
}
|
||||
const snapshot = this.createStateSnapshot();
|
||||
this.resourceOwnerIds.add(pluginConfig.id);
|
||||
await this.loadConfiguredPlugin(pluginConfig);
|
||||
try {
|
||||
await this.loadConfiguredPlugin(pluginConfig);
|
||||
} catch (error) {
|
||||
await this.rollbackConfiguredPluginLoad(pluginConfig.id, snapshot);
|
||||
console.warn(`[plugin:${pluginConfig.id}] Disabled after startup failure: ${formatError(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -513,6 +531,47 @@ class GatewayPluginService {
|
|||
): Promise<PluginSqliteStore> {
|
||||
return backendService.openSqliteStore(pluginId, pluginDataDir, options);
|
||||
}
|
||||
|
||||
private createStateSnapshot(): PluginServiceStateSnapshot {
|
||||
return {
|
||||
apps: [...this.apps],
|
||||
coreGatewayConfig: { ...this.coreGatewayConfig },
|
||||
coreProviderPlugins: [...this.coreProviderPlugins],
|
||||
gatewayRoutes: [...this.gatewayRoutes],
|
||||
providerAccountConnectors: new Map(this.providerAccountConnectors),
|
||||
proxyRoutes: [...this.proxyRoutes],
|
||||
resourceOwnerIds: new Set(this.resourceOwnerIds),
|
||||
stopHooks: [...this.stopHooks],
|
||||
virtualModelProfiles: [...this.virtualModelProfiles]
|
||||
};
|
||||
}
|
||||
|
||||
private async rollbackConfiguredPluginLoad(pluginId: string, snapshot: PluginServiceStateSnapshot): Promise<void> {
|
||||
const newStopHooks = this.stopHooks.slice(snapshot.stopHooks.length).reverse();
|
||||
this.apps = snapshot.apps;
|
||||
this.coreGatewayConfig = snapshot.coreGatewayConfig;
|
||||
this.coreProviderPlugins = snapshot.coreProviderPlugins;
|
||||
this.gatewayRoutes = snapshot.gatewayRoutes;
|
||||
this.providerAccountConnectors = snapshot.providerAccountConnectors;
|
||||
this.proxyRoutes = snapshot.proxyRoutes;
|
||||
this.resourceOwnerIds = snapshot.resourceOwnerIds;
|
||||
this.stopHooks = snapshot.stopHooks;
|
||||
this.virtualModelProfiles = snapshot.virtualModelProfiles;
|
||||
|
||||
for (const stopHook of newStopHooks) {
|
||||
try {
|
||||
await stopHook();
|
||||
} catch (error) {
|
||||
console.warn(`[plugin:${pluginId}] Rollback stop hook failed: ${formatError(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await backendService.stopOwner(pluginId);
|
||||
} catch (error) {
|
||||
console.warn(`[plugin:${pluginId}] Rollback resource cleanup failed: ${formatError(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const pluginService = new GatewayPluginService();
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue