Compare commits

..

No commits in common. "main" and "v3.0.5" have entirely different histories.
main ... v3.0.5

330 changed files with 2611 additions and 32217 deletions

View file

@ -1,17 +0,0 @@
.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
View file

@ -13,8 +13,4 @@ release
tmp
release-local
logs
.opencat
test-results
playwright-report
blob-report
.tmp
.opencat

View file

@ -1,75 +0,0 @@
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"]

View file

@ -1,52 +1,19 @@
<h1 align="center">Claude Code Router</h1>
<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://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>
&nbsp;·&nbsp;
<a href="https://platform.kimi.ai?aff=ccr"><strong>API Global</strong></a>
&nbsp;·&nbsp;
<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.
@ -202,43 +169,6 @@ Codex support is powered by [musistudio/codexl](https://github.com/musistudio/co
<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://code0.ai/agent/register/9n9jOsSnYQoemIVL?utm_source=claudecoderouter&amp;utm_medium=partner&amp;utm_campaign=claudecoderouter_2026&amp;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&amp;utm_medium=partner&amp;utm_campaign=claudecoderouter_2026&amp;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&amp;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>

View file

@ -1,52 +1,19 @@
<h1 align="center">Claude Code Router</h1>
<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://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>
&nbsp;·&nbsp;
<a href="https://platform.kimi.com?aff=ccr"><strong>API 中文站</strong></a>
&nbsp;·&nbsp;
<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。
@ -201,43 +168,6 @@ CCR 可以完全通过桌面 UI 完成配置。首次使用建议按下面顺序
<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://code0.ai/agent/register/9n9jOsSnYQoemIVL?utm_source=claudecoderouter&amp;utm_medium=partner&amp;utm_campaign=claudecoderouter_2026&amp;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&amp;utm_medium=partner&amp;utm_campaign=claudecoderouter_2026&amp;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&amp;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>

View file

Before

Width:  |  Height:  |  Size: 992 KiB

After

Width:  |  Height:  |  Size: 992 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 102 KiB

After

Width:  |  Height:  |  Size: 102 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Before After
Before After

View file

@ -1,4 +1,4 @@
import { buildBrowserRenderer, buildMain, buildRenderer, buildStyles, buildTrayRenderer, buildWebClientBridge, cleanDist, copyAppAssets, copyBrowserRendererHtml, copyMarketplacePlugins, copyModelCatalog, copyRendererHtml, copyTrayRendererHtml, syncUiRendererToRuntimeDists } from "./esbuild.config.mjs";
import { buildBrowserRenderer, buildMain, buildRenderer, buildStyles, buildTrayRenderer, buildWebClientBridge, cleanDist, copyAppAssets, copyBrowserRendererHtml, copyMarketplacePlugins, copyModelCatalog, copyRendererHtml, copyTrayRendererHtml } from "./esbuild.config.mjs";
const mode = process.argv.includes("--dev") ? "development" : "production";
@ -19,6 +19,4 @@ await Promise.all([
buildStyles({ minify: mode === "production" })
]);
syncUiRendererToRuntimeDists();
console.log(`Built monorepo package assets in ${mode} mode.`);
console.log(`Built Electron app assets in ${mode} mode.`);

View file

@ -5,14 +5,12 @@ 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,
@ -23,12 +21,12 @@ import {
createRendererBuildOptions,
createTrayRendererBuildOptions,
createWebClientBridgeBuildOptions,
cssInput,
cssOutput,
appAssetsInput,
modelCatalogInput,
projectRoot,
rendererRoot,
rendererHtmlInput,
syncUiRendererToRuntimeDists,
trayRendererHtmlInput,
watchPlugin
} from "./esbuild.config.mjs";
@ -39,12 +37,7 @@ 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,
@ -53,32 +46,6 @@ 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}`);
@ -90,7 +57,6 @@ function relativePath(file) {
function readyState() {
return Object.entries(ready)
.filter(([name]) => activeReadyNames.has(name))
.map(([name, value]) => `${name}:${value ? "ready" : "pending"}`)
.join(" ");
}
@ -197,63 +163,7 @@ function handleWatchedInput(label, watchedPath, eventType, filename, options, on
}
onChange();
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);
}
scheduleRestart(reason);
}
function markReady(name, reason = `${name} esbuild completed`) {
@ -261,7 +171,7 @@ function markReady(name, reason = `${name} esbuild completed`) {
ready[name] = true;
}
logDev(`build ready: ${reason}; ${readyState()}`);
if (enabled.electron && Array.from(activeReadyNames).every((readyName) => ready[readyName])) {
if (ready.browser && ready.cli && ready.main && ready.renderer && ready.tray && ready.webBridge) {
scheduleRestart(reason);
}
}
@ -311,153 +221,114 @@ function restartElectron() {
});
}
logDev(`starting dev build target=${devTarget} ui=${enabled.ui ? "on" : "off"} cli=${enabled.cli ? "on" : "off"} electron=${enabled.electron ? "on" : "off"}`);
logDev("starting dev build");
cleanDist();
if (enabled.electron) {
copyAppAssets();
}
if (enabled.cli || enabled.electron) {
copyMarketplacePlugins();
copyModelCatalog();
}
copyAppAssets();
copyMarketplacePlugins();
copyModelCatalog();
copyBrowserRendererHtml();
copyRendererHtml();
copyTrayRendererHtml();
await buildStyles({ minify: false });
syncUiRendererToRuntimeDists();
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"}`);
});
rememberWatchSignature("home html", rendererHtmlInput);
rememberWatchSignature("browser html", browserRendererHtmlInput);
rememberWatchSignature("tray html", trayRendererHtmlInput);
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("app assets", appAssetsInput);
if (existsSync(modelCatalogInput)) {
rememberWatchSignature("model catalog", modelCatalogInput);
}
const htmlWatcher = watch(rendererHtmlInput, { persistent: true }, (eventType, filename) => {
handleWatchedInput("home html", rendererHtmlInput, eventType, filename, undefined, () => {
copyRendererHtml();
syncUiRendererToRuntimeDists();
});
handleWatchedInput("home html", rendererHtmlInput, eventType, filename, undefined, copyRendererHtml);
});
const browserHtmlWatcher = watch(browserRendererHtmlInput, { persistent: true }, (eventType, filename) => {
handleWatchedInput("browser html", browserRendererHtmlInput, eventType, filename, undefined, () => {
copyBrowserRendererHtml();
syncUiRendererToRuntimeDists();
});
handleWatchedInput("browser html", browserRendererHtmlInput, eventType, filename, undefined, copyBrowserRendererHtml);
});
const trayHtmlWatcher = watch(trayRendererHtmlInput, { persistent: true }, (eventType, filename) => {
handleWatchedInput("tray html", trayRendererHtmlInput, eventType, filename, undefined, () => {
copyTrayRendererHtml();
syncUiRendererToRuntimeDists();
});
handleWatchedInput("tray html", trayRendererHtmlInput, eventType, filename, undefined, copyTrayRendererHtml);
});
const stylePoller = setInterval(pollStyleWatchRoots, stylePollIntervalMs);
const appAssetsWatcher = watch(appAssetsInput, { persistent: true }, (eventType, filename) => {
handleWatchedInput("app assets", appAssetsInput, eventType, filename, { isDirectory: true }, copyAppAssets);
});
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)
const modelCatalogWatcher = existsSync(modelCatalogInput)
? watch(modelCatalogInput, { persistent: true }, (eventType, filename) => {
handleWatchedInput("model catalog", modelCatalogInput, eventType, filename, undefined, copyModelCatalog);
})
: { close: () => undefined };
const contexts = [];
const mainContext = await esbuild.context(
createMainBuildOptions({
mode: "development",
plugins: [watchPlugin("main", (name) => markReady(name))]
})
);
if (enabled.electron) {
contexts.push(
await esbuild.context(
createMainBuildOptions({
mode: "development",
plugins: [watchPlugin("main", (name) => markReady(name))]
})
)
);
}
const cliContext = await esbuild.context(
createCliBuildOptions({
mode: "development",
plugins: [watchPlugin("cli", (name) => markReady(name))]
})
);
if (enabled.cli) {
contexts.push(
await esbuild.context(
createCliBuildOptions({
mode: "development",
plugins: [
watchPlugin("cli", (name) => {
if (enabled.electron) {
copyCliRuntimeToElectronDist();
}
markReady(name);
})
]
const rendererContext = await esbuild.context(
createRendererBuildOptions({
mode: "development",
plugins: [
watchPlugin("renderer", (name) => {
copyRendererHtml();
markReady(name);
})
)
);
}
]
})
);
if (enabled.ui) {
contexts.push(
await esbuild.context(
createRendererBuildOptions({
mode: "development",
plugins: [
watchPlugin("renderer", (name) => {
copyRendererHtml();
syncUiRendererToRuntimeDists();
markReady(name);
})
]
const trayRendererContext = await esbuild.context(
createTrayRendererBuildOptions({
mode: "development",
plugins: [
watchPlugin("tray", (name) => {
copyTrayRendererHtml();
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);
})
]
})
)
);
}
]
})
);
await Promise.all(contexts.map((context) => context.watch()));
const browserRendererContext = await esbuild.context(
createBrowserRendererBuildOptions({
mode: "development",
plugins: [
watchPlugin("browser", (name) => {
copyBrowserRendererHtml();
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()]);
logDev("watchers are active");
async function shutdown() {
@ -469,16 +340,13 @@ async function shutdown() {
if (electronProcess) {
electronProcess.kill();
}
if (styleBuildTimer) {
clearTimeout(styleBuildTimer);
}
tailwindProcess.kill();
htmlWatcher.close();
browserHtmlWatcher.close();
trayHtmlWatcher.close();
clearInterval(stylePoller);
appAssetsWatcher.close();
modelCatalogWatcher.close();
await Promise.all(contexts.map((context) => context.dispose()));
await Promise.all([mainContext.dispose(), cliContext.dispose(), rendererContext.dispose(), trayRendererContext.dispose(), browserRendererContext.dispose(), webClientBridgeContext.dispose()]);
process.exit(0);
}

View file

@ -1,37 +0,0 @@
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.`);

View file

@ -1,63 +1,23 @@
import esbuild from "esbuild";
import { spawn } from "node:child_process";
import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { builtinModules, createRequire } from "node:module";
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { builtinModules } 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 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 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 rendererAssetsDir = path.join(rendererOutDir, "assets");
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 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 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");
@ -67,14 +27,11 @@ 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 lightweightMcpBundleNames = ["fusion-vision-mcp.js", "fusion-tool-fallback-mcp.js"];
const lightweightMcpBundleMaxBytes = 128 * 1024;
const forbiddenLightweightMcpInputs = [
{ 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: "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: "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" }
];
@ -88,28 +45,15 @@ const nodeExternals = [
];
export function cleanDist() {
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 });
rmSync(distDir, { force: true, recursive: true });
ensureDist();
}
export function ensureDist() {
mkdirSync(cliMainOutDir, { recursive: true });
mkdirSync(coreMainOutDir, { recursive: true });
mkdirSync(electronMainOutDir, { recursive: true });
mkdirSync(electronBotGatewaySdkDistDir, { recursive: true });
mkdirSync(electronBotGatewaySdkBinDir, { recursive: true });
mkdirSync(mainOutDir, { recursive: true });
mkdirSync(appAssetsDir, { recursive: true });
mkdirSync(cliMarketplacePluginsDir, { recursive: true });
mkdirSync(coreMarketplacePluginsDir, { recursive: true });
mkdirSync(electronMarketplacePluginsDir, { recursive: true });
mkdirSync(marketplacePluginsDir, { 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 });
@ -125,16 +69,12 @@ export function copyAppAssets() {
export function copyModelCatalog() {
ensureDist();
if (existsSync(modelCatalogInput)) {
cpSync(modelCatalogInput, cliModelCatalogOutput);
cpSync(modelCatalogInput, coreModelCatalogOutput);
cpSync(modelCatalogInput, electronModelCatalogOutput);
cpSync(modelCatalogInput, modelCatalogOutput);
}
}
export function copyRendererHtml() {
copyRendererPageHtml(rendererHtmlInput, rendererHtmlOutput, "main.js", {
beforeModuleScriptTags: [' <script src="../../assets/web-client-bridge.js"></script>']
});
copyRendererPageHtml(rendererHtmlInput, rendererHtmlOutput, "main.js");
}
export function copyTrayRendererHtml() {
@ -149,25 +89,14 @@ 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, path.join(cliMarketplacePluginsDir, filename));
cpSync(source, path.join(coreMarketplacePluginsDir, filename));
cpSync(source, path.join(electronMarketplacePluginsDir, filename));
cpSync(source, target);
}
}
}
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 = {}) {
function copyRendererPageHtml(input, output, scriptName) {
ensureDist();
const source = readFileSync(input, "utf8");
const styleTag = ' <link rel="stylesheet" href="../../assets/main.css" />';
@ -176,12 +105,6 @@ function copyRendererPageHtml(input, output, scriptName, options = {}) {
? 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>`);
}
@ -189,38 +112,17 @@ function copyRendererPageHtml(input, output, scriptName, options = {}) {
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(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")
path.join(projectRoot, "src", "main", "main.ts"),
path.join(projectRoot, "src", "main", "browser-preload.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")
],
external: nodeExternals,
format: "cjs",
@ -228,9 +130,9 @@ export function createMainBuildOptions({ mode = "production", plugins = [] } = {
logLevel: "info",
metafile: true,
minify: mode === "production",
outdir: electronMainOutDir,
outdir: mainOutDir,
platform: "node",
plugins: [packageAliasPlugin(), ...plugins],
plugins,
sourcemap: mode !== "production",
target: "node22"
};
@ -241,44 +143,15 @@ export function createCliBuildOptions({ mode = "production", plugins = [] } = {}
absWorkingDir: projectRoot,
bundle: true,
entryNames: "[name]",
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")
],
entryPoints: [path.join(projectRoot, "src", "main", "cli.ts")],
external: nodeExternals.filter((moduleName) => moduleName !== "electron"),
format: "cjs",
legalComments: "none",
logLevel: "info",
minify: mode === "production",
outdir: cliMainOutDir,
outdir: mainOutDir,
platform: "node",
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],
plugins: [forbidCliElectronPlugin(), ...plugins],
sourcemap: mode !== "production",
target: "node22"
};
@ -309,7 +182,7 @@ export function createRendererBuildOptions({ mode = "production", plugins = [] }
minify: mode === "production",
outfile: path.join(rendererAssetsDir, "main.js"),
platform: "browser",
plugins: [rendererAliasPlugin(), packageAliasPlugin(), ...plugins],
plugins: [rendererAliasPlugin(), ...plugins],
publicPath: "../../assets",
sourcemap: mode !== "production",
target: "chrome120"
@ -336,37 +209,16 @@ export function createWebClientBridgeBuildOptions({ mode = "production", plugins
return {
absWorkingDir: projectRoot,
bundle: true,
entryPoints: [path.join(uiSourceRoot, "web-client-bridge.ts")],
entryPoints: [path.join(projectRoot, "src", "main", "web-client-bridge.ts")],
format: "iife",
legalComments: "none",
logLevel: "info",
minify: mode === "production",
outfile: webClientBridgeOutput,
platform: "browser",
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"
target: "chrome120"
};
}
@ -386,38 +238,11 @@ export function watchPlugin(name, onEnd) {
export async function buildMain(options = {}) {
const [mainBuildResult] = await Promise.all([
esbuild.build(createMainBuildOptions(options)),
buildBotGatewaySdkRuntime(options),
buildCoreServer(options),
buildCli(options)
esbuild.build(createCliBuildOptions(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));
}
@ -434,14 +259,6 @@ 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];
@ -487,26 +304,6 @@ 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",
@ -573,23 +370,19 @@ function normalizeBuildPath(value) {
}
function resolveRendererImport(importPath) {
return resolvePackageImport(rendererRoot, importPath);
}
function resolvePackageImport(rootDir, importPath) {
const packageBasePath = path.resolve(rootDir, importPath);
const basePath = path.resolve(rendererRoot, importPath);
const candidates = [
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")
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")
];
for (const candidate of candidates) {
@ -598,5 +391,5 @@ function resolvePackageImport(rootDir, importPath) {
}
}
return packageBasePath;
return basePath;
}

View file

@ -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}/*.test.js`], {
const child = spawn(electron, ["--test", `dist/tests/${suite}/*.js`], {
cwd: projectRoot,
env: {
...process.env,

View file

@ -6,9 +6,7 @@ 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, "packages", "ui", "src");
const cliSourceRoot = path.join(projectRoot, "packages", "cli", "src");
const coreSourceRoot = path.join(projectRoot, "packages", "core", "src");
const rendererRoot = path.join(projectRoot, "src", "renderer");
const testSuites = [
{ name: "main", testDir: path.join(projectRoot, "tests", "main") },
{ name: "renderer", testDir: path.join(projectRoot, "tests", "renderer") }
@ -27,10 +25,7 @@ if (unknownSuites.length > 0) {
rmSync(testsOutDir, { force: true, recursive: true });
for (const suite of selectedSuites) {
const entryPoints = [
...findTestFiles(suite.testDir),
...runtimeEntryPointsForSuite(suite.name)
];
const entryPoints = findTestFiles(suite.testDir);
if (entryPoints.length === 0) {
continue;
}
@ -58,21 +53,11 @@ for (const suite of selectedSuites) {
logLevel: "info",
outdir: path.join(testsOutDir, suite.name),
platform: "node",
plugins: [rendererAliasPlugin(), packageAliasPlugin()],
plugins: [rendererAliasPlugin()],
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 [];
@ -102,26 +87,8 @@ 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) {
return resolvePackageImport(rendererRoot, importPath);
}
function resolvePackageImport(rootDir, importPath) {
const basePath = path.resolve(rootDir, importPath);
const basePath = path.resolve(rendererRoot, importPath);
const candidates = [
basePath,
`${basePath}.tsx`,

View file

@ -9,19 +9,6 @@ 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;
@ -34,7 +21,6 @@ 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");
@ -55,13 +41,6 @@ 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");

View file

@ -5,7 +5,7 @@
"tsx": true,
"tailwind": {
"config": "",
"css": "packages/ui/src/styles/globals.css",
"css": "src/renderer/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""

View file

@ -1,15 +0,0 @@
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:

View file

@ -1,91 +0,0 @@
# 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.

View file

@ -1,207 +0,0 @@
#!/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

View file

@ -1,35 +0,0 @@
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"
}
]
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

View file

@ -2,37 +2,29 @@
title: Claude Code Router Detailed Configuration
pageTitle: Detailed Configuration
eyebrow: Detailed Configuration
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."
lead: Configure the overview dashboard, API keys, server, providers, routing, Agent Config, Fusion, Bots, tray, and the config database location in detail.
---
## 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. Main pages follow the app's left navigation order. Settings pages are grouped separately and follow the settings dialog order.
## Main Pages
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.
| 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 |
| 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 |
| 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 |
| 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 |
| Config Database Location | SQLite config database location maintained by the desktop app |
| Tray Configuration | Tray icon, balance progress, and tray window widgets |
| Config Database Location | SQLite config database location maintained by the desktop app |
## Content Relationships
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.
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.

View file

@ -11,20 +11,7 @@ Use `ccr-fusion-builtins / web_search`.
## Search Providers
Supported providers include In-app Browser, Brave, Bing, Google CSE, Serper, SerpAPI, Tavily, and Exa.
## In-app Browser
`In-app Browser` runs searches through a hidden built-in browser window in CCR Desktop, opens result pages, extracts visible content, and passes that evidence to the Fusion model. It does not require an external search API key, so it is useful when you want desktop-side browser retrieval.
Configuration options include search engine, language, country or region, and safe-search level:
- Search engine: Bing, Google, or DuckDuckGo.
- Language: for example `en` or `zh-CN`.
- Country or region: for example `US` or `CN`.
- Safe search: default, moderate, strict, or off.
> Note: `In-app Browser` depends on CCR Desktop's Electron built-in browser capability and is only available in the desktop app. CLI, server deployments, and pure web environments do not have the built-in browser integration; use Brave, Bing, Google CSE, Serper, SerpAPI, Tavily, or Exa instead.
Supported providers include Brave, Bing, Google CSE, Serper, SerpAPI, Tavily, and Exa.
## Troubleshooting

View file

@ -2,130 +2,52 @@
title: Overview Dashboard
pageTitle: Overview Dashboard
eyebrow: Detailed Configuration
lead: Customize the CCR home dashboard to inspect system status, account balance, requests, tokens, cost, and model distribution.
lead: Customize the CCR home dashboard for system status, account balance, requests, tokens, cost, model distribution, and share cards.
---
## When To Use It
## Top Controls
| Scenario | What to inspect |
| Field | Capability |
| --- | --- |
| Check gateway health | System status, success rate, errors, average latency |
| Estimate recent spend | Requests, input / output / cache tokens, estimated cost |
| Compare upstream usage | Provider analysis, model distribution, client analysis |
| Watch account quota | Balance, subscription quota, remaining quota, account status |
| Report or share usage | AI Usage Wrapped, CCR Route Map, Model Leaderboard, Spend Receipt, and other share cards |
| Usage over time | Changes the statistics range used by the dashboard. |
| Today / 24h / 7d / 30d | Available time windows. Widgets recalculate requests, tokens, cost, and trends for the selected range. |
| Edit widgets | Enters layout editing mode. |
| Reset layout | Restores the default overview layout. |
| Done | Leaves editing mode and keeps the current widget configuration. |
## Time Range
## Widget Editing
The `Usage over time` control at the top drives every widget that depends on usage stats. After you switch ranges, requests, tokens, cost, trends, distribution, and share cards are recomputed for the selected window.
In editing mode, the left `Components` panel adds widgets, the middle `Preview` panel shows the current layout, and the right `Component properties` panel edits the selected widget.
| Option | Window |
| Field | Capability |
| --- | --- |
| `Today` | Current local date from 00:00 to now, bucketed hourly. |
| `24h` | Last 24 hours, bucketed hourly. |
| `7d` | Last 7 days, bucketed daily. |
| `30d` | Last 30 days, bucketed daily. |
| Components | List of widgets that can be added. |
| Preview | Current dashboard layout. Widgets can be dragged to reorder. |
| Component properties | Configuration for the selected widget. |
| Component category | Changes the widget category, such as status, account, metric, trend, activity, breakdown, analysis, or share card. |
| Data | Selects the data shown by the widget, such as requests, tokens, cost, account, client analysis, or provider analysis. |
| Widget size | Controls the widget's grid width and height. |
| Style | Changes visual style, such as cards, compact, bar, line, ring, and more. |
| Remove widget | Removes the selected widget from the overview. |
The account balance widget does not use this time range. It shows the latest snapshot returned by provider account connectors.
## Widget Types
## Edit Layout
Click the pencil button in the upper-right corner to enter editing mode. Editing mode has three columns:
| Area | Purpose |
| Widget | Capability |
| --- | --- |
| Components | Left palette. Click a template to add it to the dashboard. |
| Preview | Middle layout preview. Drag widgets to reorder them or click a widget to select it. |
| Component properties | Right property panel for changing type, data, size, style, or removing the selected widget. |
| Status component | Shows a system status timeline for recent gateway health. |
| Account component | Shows provider account balance, quota, or usage. Requires provider `Fetch usage`. |
| Metric component | Shows requests, total tokens, input tokens, output tokens, cache tokens, cache ratio, estimated cost, success rate, errors, or average latency. |
| Trend component | Shows usage trend over time. |
| Activity component | Shows token activity as a heatmap. |
| Breakdown component | Shows Token mix or Model distribution. |
| Analysis component | Shows Client Analysis or Provider Analysis. |
| Share card | Generates shareable PNG cards such as AI Usage Wrapped, CCR Route Map, Model Leaderboard, AI Fuel Cockpit, Token Calendar Poster, and Spend Receipt. |
Common operations:
## Data Sources
1. Add a widget: click a template in `Components`.
2. Reorder widgets: drag them in `Preview`.
3. Resize a widget: select it, then drag the right, bottom, or bottom-right resize handle.
4. Change data: use `Component category` and `Data` in `Component properties`.
5. Change presentation: choose `Widget size` and `Style`.
6. Save the result: click `Done`; the layout is persisted in app configuration.
7. Restore defaults: click `Reset layout` while editing.
Removing a widget only removes that card from the overview layout. It does not delete request logs, providers, account connectors, or upstream configuration. If all widgets are removed, the page shows `No widgets configured`.
## Widget Catalog
Sizes are written as `width:height`, with both dimensions from `1` to `4`. The overview grid has up to 4 columns on desktop and collapses automatically on narrow screens.
| Widget | Data | Default size | Default style | Styles |
| --- | --- | --- | --- | --- |
| Status component | System status | `4:1` | Timeline | Timeline, Compact |
| Account component | All accounts or one account | `4:2` | Cards | Cards, Compact, Bars, Ring, Semicircle, Arc, Nested rings |
| Metric component | Requests, tokens, cost | `1:1` | Cards | Cards, Compact, Bar, Ring |
| Trend component | Usage over time | `3:2` | Composed | Composed, Area, Line, Bar |
| Activity component | Token activity | `4:2` | Heatmap | Heatmap |
| Breakdown component | Token distribution / Model distribution | Token distribution: `1:2`; Model distribution: `2:2` | Token distribution: Bars; Model distribution: Pie | Bars, Stacked, Donut, Pie |
| Analysis component | Client Analysis / Provider Analysis | `2:2` | Table | Table, Compact |
| Share card | AI Usage Wrapped, CCR Route Map, Model Leaderboard, AI Fuel Cockpit, Token Calendar Poster, Spend Receipt | `1:4` | Card | Card |
Size constraints:
| Rule | Reason |
| Data | Source |
| --- | --- |
| Share cards have a minimum size of `1:4`. | PNG export uses a vertical poster ratio and needs enough height. |
| The account widget has a minimum size of `2:2` when showing All accounts with the Compact style. | Multi-account lists need readable space. |
| Legacy aliases are still accepted: `small` -> `1:1`, `medium` / `large` -> `2:2`, `wide` -> `3:2`, `full` -> `4:1` or `4:2`. | Backward compatibility for older config. |
## Metric Data
`metric` widgets use the `metric` field to choose the displayed value.
| `metric` | Meaning |
| --- | --- |
| `requests` | Request count |
| `total-tokens` | Total tokens |
| `input-tokens` | Input tokens |
| `output-tokens` | Output tokens |
| `cache-tokens` | Cache tokens |
| `cache-ratio` | Cache ratio |
| `estimated-cost` | Estimated cost, calculated from model pricing data |
| `success-rate` | Success rate |
| `errors` | Error count |
| `avg-latency` | Average latency |
## Account Widget
The account widget reads provider account / usage connectors. To show balance or remaining quota, first enable and test `Fetch usage` in provider configuration.
| Data selection | Behavior |
| --- | --- |
| `All accounts` | Shows every available account snapshot. |
| One account | Shows only one provider or credential snapshot. The internal config value is usually `provider` or `provider::credentialId`. |
If the account widget is empty, check:
1. Whether the provider has an account / usage connector configured.
2. Whether the `Fetch usage` test succeeds.
3. Whether the API key or account endpoint is still valid.
4. Whether the selected account was deleted or renamed.
## Share Cards
Share card widgets can export PNGs through the download button in the card header. The desktop app uses native export when available; browser environments fall back to frontend canvas export. The exported image size is `1080 x 1350`.
| Card | `type` | Content |
| --- | --- | --- |
| AI Usage Wrapped | `share-usage-wrapped` | Total tokens, requests, estimated cost, cache ratio, longest activity streak, top model, top provider, peak day. |
| CCR Route Map | `share-route-map` | Main client-to-provider/model route relationships, plus client, provider, and model counts. |
| Model Leaderboard | `share-model-leaderboard` | Models ranked by tokens. |
| AI Fuel Cockpit | `share-fuel-cockpit` | Up to 3 account quota gauges. Requires account / usage connectors. |
| Token Calendar Poster | `share-token-calendar` | Contribution-calendar style token activity poster. |
| Spend Receipt | `share-spend-receipt` | Estimated cost, requests, tokens, latency, and success rate for the selected range. |
## Data Sources And Troubleshooting
| Symptom | Likely cause | What to do |
| --- | --- | --- |
| Requests, tokens, or cost are 0 | No requests went through CCR in the selected range, or usage capture has not recorded data yet. | Try `24h` / `7d`, and confirm the client is actually using CCR. |
| Cost shows `$0.00` | The model has no pricing data, or usage is very small. | Check model catalog matching and provider model names; values under 0.01 USD are shown with extra decimals. |
| Success rate or errors look unexpected | The overview only aggregates request results captured by CCR. | Compare with records on the Logs page. |
| Account balance is empty | No account connector exists, or `Fetch usage` failed. | Test account / usage field mapping in provider configuration. |
| Distribution charts have no data | Request logs lack model, provider, or token information. | Confirm requests go through CCR and upstream responses include token usage. |
| PNG export fails | Canvas export is unavailable, the element has no size, or the save dialog was canceled. | Retry in the desktop app, and make sure the card is visible and not resized too small. |
| Requests, tokens, cost, success rate, latency | Request logs and usage stats. |
| Account balance, quota, status messages | Provider `Fetch usage` configuration. |
| Client analysis, provider analysis, model distribution | Client, provider, model, and token data from request logs. |
| Agent analysis data | Agent observability settings and agent execution traces. |

View file

@ -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, ChatGPT (the renamed Codex desktop app), and ZCode App use user-data directories separated by config `id` |
| Separate app data directories | When opening App mode, Claude App, Codex 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,12 +74,10 @@ 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 ChatGPT. Claude Code-specific model discovery variables are not passed to Codex. |
| Bot | Applies only to the ChatGPT app entry. |
| 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. |
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.
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.
### ZCode
@ -114,7 +112,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 launches ChatGPT, uses a separate user-data directory, and passes the selected model and provider into the app.
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.
### ZCode

View file

@ -74,26 +74,6 @@ 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/runapi.jpg" alt="" loading="lazy" /></span>
<span class="provider-import-copy"><span class="provider-import-name">RunAPI</span><span class="provider-import-meta">Responses / Chat Completions</span></span>
</a>
<a class="provider-import-button provider-teamorouter" href="ccr://provider?name=TeamoRouter&amp;base_url=https%3A%2F%2Fapi.teamorouter.com&amp;protocol=anthropic_messages&amp;source=https%3A%2F%2Fteamorouter.com%2F" aria-label="Import TeamoRouter provider">
<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&amp;base_url=https%3A%2F%2Fconsole.code0.ai&amp;protocol=anthropic_messages&amp;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&amp;base_url=https%3A%2F%2Fgw.claudeapi.com&amp;protocol=anthropic_messages&amp;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&amp;base_url=https%3A%2F%2Fapi.qnaigc.com&amp;protocol=openai_chat_completions&amp;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&amp;base_url=https%3A%2F%2Fapi.fenno.ai&amp;protocol=openai_chat_completions&amp;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
@ -153,7 +133,7 @@ For larger configs, pass a manifest:
| `name` | Provider display name |
| `base_url` | Provider API Base URL, required for direct imports |
| `api_key` | Optional provider API key |
| `protocol` | Protocol, one of `openai_chat_completions`, `openai_responses`, `anthropic_messages`, `gemini_generate_content`, `gemini_interactions` |
| `protocol` | Protocol, one of `openai_chat_completions`, `openai_responses`, `anthropic_messages`, `gemini_generate_content` |
| `models` | Model list. Use comma/newline-separated text in HTML, or a string/array in JavaScript |
| `icon` | Provider icon URL |
| `source` | Provider website or config source |
@ -281,7 +261,7 @@ Complete manifest example:
| `name` | Provider display name |
| `base_url` | Provider API Base URL, required |
| `api_key` | Optional provider API key |
| `protocol` | Protocol, one of `openai_chat_completions`, `openai_responses`, `anthropic_messages`, `gemini_generate_content`, `gemini_interactions` |
| `protocol` | Protocol, one of `openai_chat_completions`, `openai_responses`, `anthropic_messages`, `gemini_generate_content` |
| `models` | Model list, comma-separated, newline-separated, or repeated |
| `icon` | Provider icon URL |
| `source` | Provider website or config source |

View file

@ -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` |
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.
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.
**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.

View file

@ -1,167 +0,0 @@
---
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.

View file

@ -13,7 +13,7 @@ The top navigation is split into four standalone pages:
| --- | --- |
| [Documentation](./) | Product positioning, architecture overview, and reading path |
| [Quick Start](guides/) | From installation and provider setup to connecting an agent |
| [Detailed Configuration](configuration/overview/) | Overview dashboard, API keys, server, providers, routing, Agent Config, Fusion, Bots, tray, and config database location |
| [Detailed Configuration](configuration/providers/) | Overview dashboard, API keys, server, providers, routing, Agent Config, Fusion, Bots, tray, and config database location |
| [Q&A](troubleshooting/) | Request logs, observability panel, and common questions |
Bot platform guides are child pages under Detailed Configuration. Each platform has its own page so platform dashboard fields, callback URLs, signatures, and FAQs can be expanded independently.
@ -24,5 +24,5 @@ If this is your first time using CCR:
1. Start with [Quick Start](guides/) to connect a provider and Agent Config.
2. Use the app's request logs to confirm whether requests are passing through CCR.
3. Open [Detailed Configuration](configuration/overview/) for the overview dashboard, API keys, server, providers, vision, web search, MCP tools, tray, and IM relay.
3. Open [Detailed Configuration](configuration/providers/) for the overview dashboard, API keys, server, providers, vision, web search, MCP tools, tray, and IM relay.
4. Use [Q&A](troubleshooting/) for 401, 404, timeout, wrong-routing, or Bot delivery questions.

View file

@ -2,37 +2,29 @@
title: Claude Code Router 详细配置
pageTitle: 详细配置
eyebrow: 详细配置
lead: 按应用中的实际顺序将主页页面和设置页分开说明主页覆盖概览、供应商、Agent配置、路由、Fusion、API 密钥、日志&观测、服务和扩展;设置页覆盖 ToolHub、Bot、数据和托盘
lead: 深入配置概览仪表盘、API 密钥、服务、供应商、路由、Agent配置、Fusion、Bot、托盘和配置数据库位置。这里是按功能查字段和扩展能力的地方
---
## 页面结构
详细配置文档已经拆成独立页面。左侧目录中的每一项都会进入一个页面;当前页面内的标题由右侧大纲负责。主页页面跟随应用左侧主导航顺序;设置页单独分组,并按设置弹窗顺序排列。
## 主页页面
详细配置文档已经拆成独立页面。左侧目录中的每一项都会进入一个页面;当前页面内的标题由右侧大纲负责。
| 页面 | 内容 |
| --- | --- |
| 概览仪表盘 | 系统状态、账户余额、用量组件、布局编辑和分享卡片 |
| API 密钥 | 客户端访问 Key、过期时间和本地限额 |
| 服务配置 | Host、Port、代理模式、系统代理、网络捕获和 CA 证书 |
| 供应商配置 | 上游服务、协议、基础 URL、模型列表和凭据 |
| 一键导入供应商 | Provider deeplink 协议、Manifest 导入、一键导入按钮和安全边界 |
| Agent配置 | Agent 启动方式、模型、作用范围、多开和 Bot 绑定 |
| 路由配置 | 条件规则、fallback 和请求改写 |
| Fusion 组合模型 | 把基础模型与视觉、搜索、MCP 工具组合成新的可选模型 |
| API 密钥 | 客户端访问 Key、过期时间和本地限额 |
| 日志&观测 | 请求日志、Agent 执行追踪、工具调用和工具结果 |
| 服务配置 | Host、Port、代理模式、系统代理、网络捕获和 CA 证书 |
| Fusion 组合模型 | 把基础模型与视觉、搜索、MCP 工具组合成新的可选模型 |
| Agent配置 | Agent 启动方式、模型、作用范围、多开和 Bot 绑定 |
| 扩展机制 | Wrapper plugin、Core gateway plugin、自定义扩展创建和调试 |
## 设置页
| 页面 | 内容 |
| --- | --- |
| ToolHub | 将多个 MCP server 收束成一个 Agent 可用的动态工具检索入口 |
| Bot 与 IM 接力 Agent | Bot 转发、接力模式和平台页面 |
| 配置数据库位置 | 桌面 App 维护的 SQLite 配置数据库位置 |
| 托盘配置 | 托盘图标、余额进度条和托盘窗口组件 |
| 配置数据库位置 | 桌面 App 维护的 SQLite 配置数据库位置 |
## 内容关系
概览仪表盘用于查看系统状态和用量;供应商配置和一键导入供应商页面覆盖上游模型服务如何进入 CCRAgent配置页面覆盖 Claude Code、Codex 和 ZCode 的启动、多开与模型选择;路由决定模型请求的上游去向;Fusion 页面覆盖图像、搜索和 MCP 工具;API 密钥控制客户端访问 CCR日志&观测覆盖请求日志和 Agent 执行链路服务配置控制本地网关监听和代理能力扩展机制覆盖本地插件的创建、安装和调试。ToolHub、Bot、配置数据库位置和托盘配置对应设置弹窗中的同名配置页
概览仪表盘用于查看系统状态和用量;API 密钥控制客户端访问 CCR服务配置控制本地网关监听和代理能力供应商配置和一键导入供应商页面覆盖上游模型服务如何进入 CCR路由决定模型请求的上游去向;Agent配置页面覆盖 Claude Code、Codex 和 ZCode 的启动、多开与模型选择Fusion 页面覆盖图像、搜索和 MCP 工具;扩展机制页面覆盖本地插件的创建、安装和调试Bot 页面覆盖 IM 平台接力;托盘配置覆盖菜单栏图标和托盘窗口

View file

@ -11,20 +11,7 @@ lead: 使用 CCR 内置 Web Search 工具为模型提供联网检索能力。
## 搜索服务
支持 In-app Browser、Brave、Bing、Google CSE、Serper、SerpAPI、Tavily、Exa 等搜索服务。
## In-app Browser
`In-app Browser` 会通过 CCR Desktop 的隐藏内置浏览器窗口执行搜索,打开搜索结果页面并提取可见内容,再把证据提供给 Fusion 模型。它不需要外部搜索 API Key适合希望用桌面端内置浏览器完成联网检索的场景。
可配置项包括搜索引擎、语言、地区和安全搜索级别:
- 搜索引擎Bing、Google、DuckDuckGo。
- 语言:例如 `en``zh-CN`
- 地区:例如 `US``CN`
- 安全搜索:默认、中等、严格或关闭。
> 注意:`In-app Browser` 依赖 CCR Desktop 的 Electron 内置浏览器能力只在桌面端可用。CLI、服务器部署或纯 Web 环境没有内置浏览器集成,请改用 Brave、Bing、Google CSE、Serper、SerpAPI、Tavily 或 Exa 等搜索服务。
支持 Brave、Bing、Google CSE、Serper、SerpAPI、Tavily、Exa 等搜索服务。
## 排查要点

View file

@ -2,130 +2,52 @@
title: 概览仪表盘
pageTitle: 概览仪表盘
eyebrow: 详细配置
lead: 自定义 CCR 首页仪表盘,查看系统状态、账户余额、请求量、令牌、成本和模型分布
lead: 自定义 CCR 首页组件查看系统状态、账户余额、请求量、tokens、成本、模型分布和可分享卡片
---
## 适用场景
## 顶部控件
| 场景 | 看什么 |
| 字段 | 代表的能力 |
| --- | --- |
| 检查网关是否正常 | 系统状态、成功率、错误数、平均延迟 |
| 估算今日或近期消耗 | 请求数、输入 / 输出 / 缓存令牌、估算成本 |
| 比较上游使用情况 | 供应商分析、模型分布、客户端分析 |
| 关注账户额度 | 账户余额、套餐额度、剩余额度、账户状态 |
| 汇报或分享用量 | AI 用量年报、CCR 路由图、模型排行榜、消费小票等分享卡片 |
| 按时间查看用量 | 切换仪表盘使用的统计时间范围。 |
| 今天 / 24 小时 / 7 天 / 30 天 | 可选统计窗口。不同组件会根据这个窗口重新计算请求、tokens、成本和趋势。 |
| 编辑组件 | 进入布局编辑模式。 |
| 重置布局 | 恢复默认概览布局。 |
| 完成 | 退出布局编辑模式并保留当前组件配置。 |
## 时间范围
## 组件区
顶部的 `按时间查看用量` 控制所有依赖用量统计的组件。切换后,请求、令牌、成本、趋势、分布和分享卡片会按新的窗口重新聚合
编辑模式下,左侧“组件”用于添加组件,中间“预览”展示当前布局,右侧“组件属性”编辑选中组件
| 选项 | 统计窗口 |
| 字段 | 代表的能力 |
| --- | --- |
| `今天` | 当前本地日期从 00:00 到现在,按小时分桶。 |
| `24 小时` | 最近 24 小时,按小时分桶。 |
| `7 天` | 最近 7 天,按天分桶。 |
| `30 天` | 最近 30 天,按天分桶。 |
| 组件 | 可添加组件列表。 |
| 预览 | 当前仪表盘布局。组件可以拖拽排序。 |
| 组件属性 | 当前选中组件的配置区域。 |
| 组件类型 | 切换组件大类,例如状态、账户、指标、趋势、活跃度、构成、分析或分享卡片。 |
| 数据 | 选择组件展示的数据例如请求数、tokens、成本、账户、客户端分析或供应商分析。 |
| 组件大小 | 控制组件占用的网格宽高。 |
| 样式 | 切换组件展示样式,例如卡片、紧凑、柱状图、折线图、圆环等。 |
| 移除组件 | 从概览中移除当前组件。 |
账户余额组件不按这个时间窗口重算,它展示供应商账户连接器最近一次获取到的快照。
## 组件类型
## 编辑布局
点击右上角铅笔按钮进入编辑模式。编辑模式分为三栏:
| 区域 | 作用 |
| 组件 | 代表的能力 |
| --- | --- |
| 组件 | 左侧组件库,点击任一组件即可添加到当前仪表盘。 |
| 预览 | 中间布局预览。可以拖拽组件排序,也可以点击组件选中它。 |
| 组件属性 | 右侧属性面板,用于修改类型、数据、尺寸、样式或移除组件。 |
| 状态组件 | 展示系统状态时间线,帮助判断网关近期是否正常。 |
| 账户组件 | 展示供应商账户余额、套餐额度或用量。需要供应商开启“获取用量”。 |
| 指标组件 | 展示请求数、总 tokens、输入 tokens、输出 tokens、缓存 tokens、缓存比例、估算成本、成功率、错误数或平均延迟。 |
| 趋势组件 | 展示按时间聚合的用量趋势。 |
| 活跃度组件 | 展示 token 活跃度热力图。 |
| 构成组件 | 展示 Token 构成或模型分布。 |
| 分析组件 | 展示客户端分析或供应商分析。 |
| 分享卡片 | 生成适合分享的 PNG 卡片,例如 AI Usage Wrapped、CCR Route Map、Model Leaderboard、AI Fuel Cockpit、Token Calendar Poster 和 Spend Receipt。 |
常用操作:
## 数据来源
1. 添加组件:在左侧 `组件` 中点击组件模板。
2. 调整顺序:在 `预览` 中拖拽组件。
3. 调整尺寸:选中组件后拖动右侧、底部或右下角的缩放手柄。
4. 修改数据:在 `组件属性` 里切换 `组件类型``数据`
5. 修改展示:在 `组件大小``样式` 中选择合适的布局。
6. 保存结果:点击 `完成` 退出编辑模式;布局会保存在应用配置中。
7. 恢复默认:编辑模式下点击 `重置布局`
移除组件只会从概览布局中删除该卡片,不会删除请求日志、供应商、账户连接器或任何上游配置。如果所有组件都被移除,页面会显示 `未配置组件`
## 组件目录
尺寸使用 `宽:高` 表示,宽高范围都是 `1``4`。概览网格在桌面端最多 4 列,在窄屏上会自动折叠。
| 组件 | 可选数据 | 默认尺寸 | 默认样式 | 可选样式 |
| --- | --- | --- | --- | --- |
| 状态组件 | 系统状态 | `4:1` | 时间线 | 时间线、紧凑 |
| 账户组件 | 所有账户或指定账户 | `4:2` | 卡片 | 卡片、紧凑、横条、圆环、半圆、弧形、内外圆 |
| 指标组件 | 请求、Token、成本 | `1:1` | 卡片 | 卡片、紧凑、柱状图、圆环 |
| 趋势组件 | 按时间查看用量 | `3:2` | 组合图 | 组合图、面积图、折线图、柱状图 |
| 活跃度组件 | Token 活跃度 | `4:2` | 热力图 | 热力图 |
| 构成组件 | Token 分布 / 模型分布 | Token 分布:`1:2`;模型分布:`2:2` | Token 分布:横条;模型分布:饼图 | 横条、堆叠、环形图、饼图 |
| 分析组件 | 客户端分析 / 供应商分析 | `2:2` | 表格 | 表格、紧凑 |
| 分享卡片 | AI 用量年报、CCR 路由图、模型排行榜、AI 燃料仪表、Token 日历海报、消费小票 | `1:4` | 卡片 | 卡片 |
尺寸约束:
| 规则 | 原因 |
| 数据 | 来源 |
| --- | --- |
| 分享卡片最小高度是 `1:4`。 | 导出图片使用竖版海报比例,需要足够高度。 |
| 账户组件在展示所有账户且使用“紧凑”样式时,最小尺寸是 `2:2`。 | 多账户列表需要保留可读空间。 |
| 旧版尺寸别名仍可被解析:`small` -> `1:1``medium` / `large` -> `2:2``wide` -> `3:2``full` -> `4:1``4:2`。 | 用于兼容旧配置。 |
## 指标数据
`metric` 组件通过 `metric` 字段选择要展示的指标。
| `metric` | 含义 |
| --- | --- |
| `requests` | 请求数 |
| `total-tokens` | 总令牌 |
| `input-tokens` | 输入令牌 |
| `output-tokens` | 输出令牌 |
| `cache-tokens` | 缓存令牌 |
| `cache-ratio` | 缓存率 |
| `estimated-cost` | 估算成本,按模型价格信息计算 |
| `success-rate` | 成功率 |
| `errors` | 错误数 |
| `avg-latency` | 平均延迟 |
## 账户组件
账户组件读取供应商配置里的账户 / 用量连接器。要让它显示余额或剩余额度,需要先在供应商配置中启用并测试 `获取用量`
| 数据选择 | 行为 |
| --- | --- |
| `所有账户` | 展示所有可用账户快照。 |
| 指定账户 | 只展示某个供应商或某个凭据的账户快照。内部配置值格式通常是 `provider``provider::credentialId`。 |
如果账户组件为空,优先检查:
1. 供应商是否配置了账户 / 用量连接器。
2. `获取用量` 测试是否成功。
3. API Key 或账户接口是否仍有效。
4. 当前选择的指定账户是否已经被删除或重命名。
## 分享卡片
分享卡片组件可以通过右上角下载按钮导出 PNG。桌面 App 会优先使用原生导出能力,浏览器环境会退回到前端 canvas 导出。导出图片尺寸为 `1080 x 1350`
| 卡片 | `type` | 内容 |
| --- | --- | --- |
| AI 用量年报 | `share-usage-wrapped` | 总令牌、请求数、估算成本、缓存率、最长连续、最高频模型、最高频供应商、峰值日期。 |
| CCR 路由图 | `share-route-map` | 客户端到供应商 / 模型的主要路由关系,以及客户端、供应商、模型数量。 |
| 模型排行榜 | `share-model-leaderboard` | 按令牌排序的模型排行榜。 |
| AI 燃料仪表 | `share-fuel-cockpit` | 最多 3 个账户额度仪表,依赖账户 / 用量连接器。 |
| Token 日历海报 | `share-token-calendar` | 类似贡献日历的 Token 活跃度海报。 |
| 消费小票 | `share-spend-receipt` | 当前时间范围内的估算成本、请求、令牌、延迟和成功率小票。 |
## 数据来源与排障
| 现象 | 可能原因 | 处理方式 |
| --- | --- | --- |
| 请求、令牌或成本为 0 | 当前时间范围内没有经过 CCR 的请求,或用量捕获尚未记录。 | 切换到 `24h` / `7d`,确认客户端请求确实走 CCR。 |
| 成本显示为 `$0.00` | 模型没有价格信息,或用量过小。 | 检查模型目录和供应商模型名是否能匹配价格;低于 0.01 美元会显示更多小数。 |
| 成功率、错误数不符合预期 | 只统计 CCR 捕获到的请求结果。 | 对照日志页面中的请求记录。 |
| 账户余额为空 | 没有账户连接器,或 `获取用量` 失败。 | 到供应商配置中测试账户 / 用量字段映射。 |
| 分布图没有数据 | 请求日志里缺少模型、供应商或 token 信息。 | 确认请求经过 CCR并检查上游响应是否返回 token usage。 |
| PNG 导出失败 | 浏览器不支持 canvas 导出、元素尺寸为空,或用户取消了保存。 | 在桌面 App 中重试,确保卡片可见且没有被缩到过小。 |
| 请求数、tokens、成本、成功率、延迟 | 请求日志和用量统计。 |
| 账户余额、套餐额度、状态消息 | 供应商“获取用量”配置。 |
| 客户端分析、供应商分析、模型分布 | 请求日志中的客户端、供应商、模型和 token 信息。 |
| Agent 分析相关数据 | 设置中的“Agent 观测”和 Agent 执行链路数据。 |

View file

@ -24,7 +24,7 @@ lead: 为 Claude Code、Codex、ZCode 创建可复用的启动配置,并通过
| --- | --- |
| 独立配置文件 | 选择“仅从 CCR 打开时生效”时Claude Code 和 Codex 会写入 CCR 管理的独立配置目录,路径按配置 `id` 区分 |
| 独立启动器 | Claude Code 使用独立启动包装器Codex 和 ZCode 使用独立中间层启动器,文件名同样按配置 `id` 或名称区分 |
| 独立 App 数据目录 | 从 App 打开时Claude App、ChatGPTCodex 桌面端的新名称)、ZCode App 都会使用按配置 `id` 区分的用户数据目录 |
| 独立 App 数据目录 | 从 App 打开时Claude App、Codex App、ZCode App 都会使用按配置 `id` 区分的用户数据目录 |
| 运行状态 | CCR 按打开入口和配置 `id` 记录运行中的 App 实例;同一个配置再次打开会激活已有窗口,不同配置可以打开不同实例 |
这意味着你可以为同一个 Agent 建多个配置例如“Claude Code - 工作项目”“Claude Code - 测试模型”“Codex - Fusion 图像能力”。它们可以选择不同模型、不同作用范围和不同 Bot打开后就是不同的 Agent 实例。
@ -74,12 +74,10 @@ Claude App 和 Claude Code CLI 的模型列表适配方式不同:
| Codex model | 写入 Codex 默认模型。可以选择普通供应商模型或 Fusion 模型;留空时 CCR 使用可用模型中的默认值。 |
| Show all sessions | 让 Codex 显示所有会话。ZCode 不提供该项。 |
| 配置文件 | 默认是 `~/.codex/config.toml`。仅从 CCR 打开时生效会写入 CCR 管理的独立配置目录。 |
| 环境变量 | 注入 Codex CLI 或 ChatGPT。Claude Code 专用的模型发现变量不会传给 Codex。 |
| Bot | 只在 ChatGPT App 入口生效。 |
| 环境变量 | 注入 Codex CLI 或 Codex App。Claude Code 专用的模型发现变量不会传给 Codex。 |
| Bot | 只在 Codex App 入口生效。 |
保存后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 marketplaceCCR 只在进程启动阶段创建精确的 `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 不会拿它替代远端目录。
保存后Codex CLI 使用配置卡片里的终端图标复制命令,例如 `ccr "Codex - Work"`。Codex App 使用播放图标打开。CCR 会生成 `config.toml`、模型目录文件和中间层启动器,让 Codex CLI 与 Codex App 都使用同一套 CCR 模型和供应商信息。
### ZCode
@ -114,7 +112,7 @@ Claude Code CLI 配置会写入设置文件。选择“仅从 CCR 打开时生
Codex 配置会写入 `config.toml`,并生成模型目录文件。选择“仅从 CCR 打开时生效”时CCR 会把这些文件放在按配置 `id` 区分的目录中。
Codex 支持 CLI 和 App。CLI 会通过对应配置的启动器打开App 会启动 ChatGPT、使用独立用户数据目录,并把当前配置中的模型和供应商信息带入 App。
Codex 支持 CLI 和 App。CLI 会通过对应配置的启动器打开App 会使用独立用户数据目录,并把当前配置中的模型和供应商信息带入 Codex App。
### ZCode

View file

@ -74,26 +74,6 @@ lead: 快速添加常见模型供应商,确认无误后即可保存,减少
<span class="provider-import-icon-shell"><img src="../../provider-icons/runapi.jpg" alt="" loading="lazy" /></span>
<span class="provider-import-copy"><span class="provider-import-name">RunAPI</span><span class="provider-import-meta">Responses / Chat Completions</span></span>
</a>
<a class="provider-import-button provider-teamorouter" href="ccr://provider?name=TeamoRouter&amp;base_url=https%3A%2F%2Fapi.teamorouter.com&amp;protocol=anthropic_messages&amp;source=https%3A%2F%2Fteamorouter.com%2F" aria-label="导入 TeamoRouter 供应商">
<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&amp;base_url=https%3A%2F%2Fconsole.code0.ai&amp;protocol=anthropic_messages&amp;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&amp;base_url=https%3A%2F%2Fgw.claudeapi.com&amp;protocol=anthropic_messages&amp;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&amp;base_url=https%3A%2F%2Fapi.qnaigc.com&amp;protocol=openai_chat_completions&amp;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&amp;base_url=https%3A%2F%2Fapi.fenno.ai&amp;protocol=openai_chat_completions&amp;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>
## 嵌入式按钮组件
@ -153,7 +133,7 @@ CCR 也提供了一个无框架的按钮脚本,供应商可以嵌入到自己
| `name` | Provider 展示名称 |
| `base_url` | Provider API Base URL直链导入时必填 |
| `api_key` | 可选 Provider API Key |
| `protocol` | 协议类型,支持 `openai_chat_completions``openai_responses``anthropic_messages``gemini_generate_content``gemini_interactions` |
| `protocol` | 协议类型,支持 `openai_chat_completions``openai_responses``anthropic_messages``gemini_generate_content` |
| `models` | 模型列表。HTML 中用逗号或换行分隔JS 中可传字符串或数组 |
| `icon` | Provider 图标 URL |
| `source` | Provider 官网或配置来源 |
@ -281,7 +261,7 @@ Manifest 可以把供应商信息放在顶层 `provider` 对象中:
| `name` | Provider 展示名称 |
| `base_url` | Provider API Base URL必填 |
| `api_key` | 可选 Provider API Key |
| `protocol` | 协议类型,支持 `openai_chat_completions``openai_responses``anthropic_messages``gemini_generate_content``gemini_interactions` |
| `protocol` | 协议类型,支持 `openai_chat_completions``openai_responses``anthropic_messages``gemini_generate_content` |
| `models` | 模型列表,支持逗号或换行分隔,也可以重复传入 |
| `icon` | Provider 图标 URL |
| `source` | Provider 官网或配置来源 |

View file

@ -162,7 +162,7 @@ Fallback 处理请求失败后的降级。第一次选模型由路由完成;
| 继续重试 | `408``409``429``5xx` |
| 失败降级目标 | 任意 `4xx``5xx` |
进入下一次尝试前CCR 会对每个触发 Fallback 的失败进行等待,包括网络错误。上游提供正数 `Retry-After` 时会优先遵守;否则使用从 1 秒开始、单次最多 30 秒的指数退避。
对于 `429` 限流响应CCR 会在下一次尝试前等待。上游提供 `Retry-After` 时会优先遵守;否则使用从 1 秒开始、单次最多 30 秒的指数退避。
**失败降级目标** 对 `4xx` 也会切换,是因为模型不存在、鉴权或供应商侧拒绝等错误可能只影响当前目标。切换后如果备用模型可用,请求仍然可以成功。

View file

@ -1,167 +0,0 @@
---
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 KeyCCR 会使用本地网关鉴权连接它。
启用步骤:
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 serverCCR 不会生成 ToolHub MCP 配置。 |
| 内置浏览器自动化 | 仅在启用 ToolHub 后显示。开启后让 Agent 可以使用 CCR Desktop 的内置浏览器完成网页操作。 |
| 检索模型 | 从已配置供应商模型中选择。建议使用 `deepseek-v4-flash`,或同等 Flash 价位、响应稳定、工具理解能力足够的轻量模型。 |
| 最大工具数 | 单次解析最多返回的工具数量,范围 `1``20`,默认 `10`。 |
| 超时毫秒 | ToolHub 解析和调用的基础超时时间,范围 `8000``300000`,默认 `60000`。如果后端 MCP server 需要更长 request timeoutCCR 会按后端超时自动抬高实际调用超时。 |
| 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。

View file

@ -13,7 +13,7 @@ lead: 了解 CCR 的定位、能力边界和文档结构。需要动手配置时
| --- | --- |
| [文档](./) | 产品定位、架构概览、阅读路径 |
| [快速开始](guides/) | 从安装、接供应商,到接入 Agent 的上手流程 |
| [详细配置](configuration/overview/) | 概览仪表盘、API 密钥、服务、供应商、路由、Agent配置、Fusion、Bot、托盘和配置数据库位置 |
| [详细配置](configuration/provider/) | 概览仪表盘、API 密钥、服务、供应商、路由、Agent配置、Fusion、Bot、托盘和配置数据库位置 |
| [Q&A](troubleshooting/) | 请求日志、观测面板和常见问题 |
Bot 平台教程是「详细配置」分类下的子页面,每个平台有独立页面,方便逐步补齐平台后台字段、回调 URL、签名和 FAQ。
@ -24,7 +24,7 @@ Bot 平台教程是「详细配置」分类下的子页面,每个平台有独
1. [快速开始](guides/) 覆盖供应商接入和 Agent配置。
2. App 的请求日志页面展示请求是否经过 CCR。
3. [详细配置](configuration/overview/) 覆盖概览仪表盘、API 密钥、服务、供应商、图像、联网搜索、MCP 工具、托盘和 IM 接力。
3. [详细配置](configuration/provider/) 覆盖概览仪表盘、API 密钥、服务、供应商、图像、联网搜索、MCP 工具、托盘和 IM 接力。
4. [Q&A](troubleshooting/) 覆盖 401、404、超时、路由不对或 Bot 收不到消息等常见问题。
这样文档不会挤在一个长页面里,后续也能按顶部分类逐步扩展。

View file

@ -15,7 +15,7 @@ export const docsContent = {
navItems: [
{ label: "文档", href: "/", pageKey: "documentation" },
{ label: "快速开始", href: "/guides/", pageKey: "guides" },
{ label: "详细配置", href: "/configuration/overview/", pageKey: "configuration" },
{ label: "详细配置", href: "/configuration/provider/", pageKey: "configuration" },
{ label: "Q&A", href: "/troubleshooting/", pageKey: "troubleshooting" },
],
pages: {
@ -60,32 +60,24 @@ export const docsContent = {
configuration: {
sidebarGroups: [
{
label: "主页页面",
label: "详细配置",
icon: "wand",
items: [
"概览仪表盘",
"供应商配置",
"一键导入供应商",
"Agent配置",
"路由配置",
"Fusion 组合模型",
"API 密钥",
"日志&观测",
"Fusion 组合模型",
"Agent配置",
"API 密钥",
"服务配置",
"托盘配置",
"扩展机制",
],
active: "概览仪表盘",
},
{
label: "设置页",
icon: "book",
items: [
"ToolHub",
"Bot 与 IM 接力 Agent",
"配置数据库位置",
"托盘配置",
],
active: "",
active: "供应商配置",
},
],
expandableSidebarItems: ["Fusion 组合模型", "Bot 与 IM 接力 Agent"],
@ -113,7 +105,6 @@ 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/",
@ -172,7 +163,7 @@ export const docsContent = {
navItems: [
{ label: "Documentation", href: "/en/", pageKey: "documentation" },
{ label: "Quick Start", href: "/en/guides/", pageKey: "guides" },
{ label: "Detailed Configuration", href: "/en/configuration/overview/", pageKey: "configuration" },
{ label: "Detailed Configuration", href: "/en/configuration/providers/", pageKey: "configuration" },
{ label: "Q&A", href: "/en/troubleshooting/", pageKey: "troubleshooting" },
],
pages: {
@ -217,32 +208,24 @@ export const docsContent = {
configuration: {
sidebarGroups: [
{
label: "Main Pages",
label: "Detailed Configuration",
icon: "wand",
items: [
"Overview Dashboard",
"Provider Config",
"One click import",
"Agent Config",
"Routing Config",
"Fusion Models",
"API Keys",
"Logs & Observability",
"Fusion Models",
"Agent Config",
"API Keys",
"Server",
"Tray Configuration",
"Extension Mechanism",
],
active: "Overview Dashboard",
},
{
label: "Settings Pages",
icon: "book",
items: [
"ToolHub",
"Bots And IM Agent Relay",
"Config Database Location",
"Tray Configuration",
],
active: "",
active: "Provider Config",
},
],
expandableSidebarItems: ["Fusion Models", "Bots And IM Agent Relay"],
@ -260,7 +243,6 @@ 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/",

View file

@ -291,11 +291,6 @@ 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;

View file

@ -1,5 +1,5 @@
---
const target = "/configuration/overview/";
const target = "/configuration/provider/";
---
<html lang="zh-CN">
@ -8,10 +8,10 @@ const target = "/configuration/overview/";
<meta http-equiv="refresh" content={`0;url=${target}`} />
<link rel="canonical" href={target} />
<script is:inline>
window.location.replace("/configuration/overview/");
window.location.replace("/configuration/provider/");
</script>
</head>
<body>
<a href={target}>概览仪表盘</a>
<a href={target}>供应商配置</a>
</body>
</html>

View file

@ -15,7 +15,6 @@ export function getStaticPaths() {
"fusion-vision": "内置图像能力",
"fusion-web-search": "内置联网搜索",
"fusion-mcp-tool": "自定义 MCP 工具",
toolhub: "ToolHub",
extensions: "扩展机制",
server: "服务配置",
tray: "托盘配置",

View file

@ -1,5 +1,5 @@
---
const target = "/en/configuration/overview/";
const target = "/en/configuration/providers/";
---
<html lang="en">
@ -8,10 +8,10 @@ const target = "/en/configuration/overview/";
<meta http-equiv="refresh" content={`0;url=${target}`} />
<link rel="canonical" href={target} />
<script is:inline>
window.location.replace("/en/configuration/overview/");
window.location.replace("/en/configuration/providers/");
</script>
</head>
<body>
<a href={target}>Overview Dashboard</a>
<a href={target}>Provider Config</a>
</body>
</html>

View file

@ -15,7 +15,6 @@ 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",

View file

@ -642,26 +642,28 @@ pre {
}
.directory-group {
margin: 8px 0 14px;
margin: 2px 0 9px;
}
.directory-group:last-child {
margin-bottom: 4px;
}
.directory-group + .directory-group {
margin-top: 20px;
.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-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;
.directory-group-label .group-icon {
width: 14px;
height: 14px;
}
.sidebar-group h2 {
@ -766,7 +768,7 @@ pre {
}
.sidebar-directory .sidebar-children {
padding-left: 18px;
padding-left: 24px;
}
.sidebar-children::before {
@ -784,14 +786,6 @@ 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,24 +1306,6 @@ h1 {
--provider-brand-3: #f3f3f3;
}
.doc-markdown a.provider-import-button.provider-teamorouter {
--provider-brand: #0c0c0f;
--provider-brand-2: #555b64;
--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;

View file

@ -5,7 +5,6 @@
"asarUnpack": [
"**/*.node"
],
"electronLanguages": ["en-US", "zh-CN", "zh-TW", "zh_CN", "zh_TW"],
"npmRebuild": true,
"publish": [
{
@ -16,7 +15,6 @@
}
],
"directories": {
"app": "packages/electron",
"output": "release/${version}"
},
"afterPack": "build/verify-packaged-app.cjs",
@ -29,14 +27,7 @@
],
"files": [
"dist",
"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/**"
"package.json"
],
"mac": {
"icon": "build/icon.icns",
@ -61,7 +52,6 @@
"artifactName": "Claude-Code-Router_${version}.${ext}"
},
"linux": {
"executableName": "claude-code-router",
"target": ["AppImage"],
"artifactName": "Claude-Code-Router_${version}.${ext}"
},

View file

@ -1,23 +0,0 @@
# 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.

View file

@ -1,262 +0,0 @@
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);
}

View file

@ -1,46 +0,0 @@
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);
}

View file

@ -1,35 +0,0 @@
{
"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://*/*"
]
}

View file

@ -1,110 +0,0 @@
<!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>

View file

@ -1,297 +0,0 @@
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

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,6 @@
{
"name": "claude-code-router-monorepo",
"version": "3.0.11",
"private": true,
"name": "claude-code-router",
"version": "3.0.5",
"license": "MIT",
"description": "Local Claude Code Router gateway with CLI and web management UI.",
"repository": {
@ -19,9 +18,15 @@
"gateway",
"router"
],
"main": "packages/electron/dist/main/main.js",
"workspaces": [
"packages/*"
"main": "dist/main/main.js",
"bin": {
"ccr": "dist/main/cli.js"
},
"files": [
"dist",
"LICENSE",
"README.md",
"README_zh.md"
],
"engines": {
"node": ">=22"
@ -30,13 +35,9 @@
"access": "public"
},
"scripts": {
"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",
"dev": "node build/dev.mjs",
"build": "npm run build:assets && 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",
@ -44,31 +45,24 @@
"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.7",
"@the-next-ai/ai-gateway": "^1.0.3",
"@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",

View file

@ -1,21 +0,0 @@
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.

View file

@ -1,375 +0,0 @@
<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>
&nbsp;·&nbsp;
<a href="https://platform.kimi.ai?aff=ccr"><strong>API Global</strong></a>
&nbsp;·&nbsp;
<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&amp;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&amp;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&amp;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).

View file

@ -1,374 +0,0 @@
<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>
&nbsp;·&nbsp;
<a href="https://platform.kimi.com?aff=ccr"><strong>API 中文站</strong></a>
&nbsp;·&nbsp;
<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&amp;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&amp;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&amp;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) 发布。

View file

@ -1,48 +0,0 @@
{
"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"
}
}

View file

@ -1,7 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src"
},
"include": ["src/**/*.ts", "src/**/*.d.ts"]
}

View file

@ -1,21 +0,0 @@
{
"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"
}
}

View file

@ -1,860 +0,0 @@
import os from "node:os";
import path from "node:path";
import type {
LocalAgentProviderCandidate,
LocalAgentProviderImportResult,
LocalAgentProviderProbeResult,
GatewayProviderConfig,
ProviderAccountConfig,
ProviderAccountConnectorConfig,
ProviderAccountMappingConfig,
ProviderAccountMeter,
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,
providerNameSlugPlaceholder,
providerPayload,
readBoolean,
readJsonRecord,
readString,
uniqueProviderName,
uniqueStrings,
type OAuthTokenSet
} 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;
export type LocalAgentModelCatalog = {
modelDisplayNames?: Record<string, string>;
modelMetadata?: Record<string, ProviderModelMetadata>;
models: string[];
};
const codexAccountRateLimitMapping: ProviderAccountMappingConfig = {
meters: [
{
id: "codex_primary_quota",
kind: "quota",
label: "Primary quota",
limit: 100,
remaining: [
"100 - $.rate_limit.primary_window.used_percent",
"100 - $.rate_limits.primary.used_percent"
],
resetAt: [
"$.rate_limit.primary_window.reset_at",
"$.rate_limit.primary_window.resets_at",
"$.rate_limits.primary.resets_at"
],
unit: "%",
used: [
"$.rate_limit.primary_window.used_percent",
"$.rate_limits.primary.used_percent"
],
window: "primary"
},
{
id: "codex_manual_resets",
kind: "requests",
label: "Manual resets",
remaining: [
"$.resetsAvailable",
"$.availableRateLimitResetCount",
"$.rate_limit_reset_credits.available_count",
"$.rate_limit.resetsAvailable",
"$.rate_limits.resetsAvailable",
"$.rate_limit.manual_resets.remaining",
"$.rate_limit.manual_resets.resetsAvailable",
"$.rate_limit.manual_reset.remaining",
"$.rate_limit.manual_reset.resetsAvailable",
"$.rate_limits.manual_resets.remaining",
"$.rate_limits.manual_resets.resetsAvailable",
"$.rate_limits.manual_reset.remaining",
"$.rate_limits.manual_reset.resetsAvailable",
"$.manual_resets.remaining",
"$.manual_resets.resetsAvailable",
"$.manual_reset.remaining",
"$.manual_reset.resetsAvailable",
"$.resets.remaining",
"$.resets.resetsAvailable",
"$.rate_limit.manual_resets.available",
"$.rate_limit.manual_reset.available",
"$.rate_limit.resets.available",
"$.rate_limits.resets.available",
"$.manual_resets.available",
"$.manual_reset.available",
"$.resets.available",
0
],
resetAt: [
"$.resetExpires",
"$.expires_at",
"$.resets_at",
"$.rate_limit.manual_resets.expires_at",
"$.rate_limit.manual_resets.expire_at",
"$.rate_limit.manual_resets.reset_at",
"$.rate_limit.manual_resets.resets_at",
"$.rate_limit.manual_reset.expires_at",
"$.rate_limit.manual_reset.expire_at",
"$.rate_limit.manual_reset.reset_at",
"$.rate_limit.manual_reset.resets_at",
"$.rate_limits.manual_resets.expires_at",
"$.rate_limits.manual_resets.expire_at",
"$.rate_limits.manual_resets.reset_at",
"$.rate_limits.manual_resets.resets_at",
"$.rate_limits.manual_reset.expires_at",
"$.rate_limits.manual_reset.expire_at",
"$.rate_limits.manual_reset.reset_at",
"$.rate_limits.manual_reset.resets_at",
"$.rate_limit.resets.expires_at",
"$.rate_limit.resets.expire_at",
"$.rate_limit.resets.reset_at",
"$.rate_limit.resets.resets_at",
"$.rate_limits.resets.expires_at",
"$.rate_limits.resets.expire_at",
"$.rate_limits.resets.reset_at",
"$.rate_limits.resets.resets_at",
"$.manual_resets.expires_at",
"$.manual_resets.expire_at",
"$.manual_resets.reset_at",
"$.manual_resets.resets_at",
"$.manual_reset.expires_at",
"$.manual_reset.expire_at",
"$.manual_reset.reset_at",
"$.manual_reset.resets_at",
"$.resets.expires_at",
"$.resets.expire_at",
"$.resets.reset_at",
"$.resets.resets_at"
],
unit: "resets",
used: [
"$.rate_limit.manual_resets.used",
"$.rate_limit.manual_reset.used",
"$.rate_limits.manual_resets.used",
"$.manual_resets.used",
"$.manual_reset.used",
"$.resets.used"
],
window: "manual-reset"
},
{
id: "codex_secondary_quota",
kind: "quota",
label: "Secondary quota",
limit: 100,
remaining: [
"100 - $.rate_limit.secondary_window.used_percent",
"100 - $.rate_limits.secondary.used_percent"
],
resetAt: [
"$.rate_limit.secondary_window.reset_at",
"$.rate_limit.secondary_window.resets_at",
"$.rate_limits.secondary.resets_at"
],
unit: "%",
used: [
"$.rate_limit.secondary_window.used_percent",
"$.rate_limits.secondary.used_percent"
],
window: "secondary"
},
{
id: "codex_individual_limit",
kind: "quota",
label: "Individual limit",
limit: "$.spend_control.individual_limit.limit",
remaining: "$.spend_control.individual_limit.remaining",
resetAt: "$.spend_control.individual_limit.reset_at",
unit: "credits",
used: "$.spend_control.individual_limit.used",
window: "monthly"
},
{
id: "codex_credit_balance",
kind: "balance",
label: "Credit balance",
remaining: "$.credits.balance",
unit: "credits"
}
]
};
const codexAccountRateLimitResetCreditsMapping: ProviderAccountMappingConfig = {
meters: [
{
id: "codex_manual_resets",
kind: "requests",
label: "Manual resets",
remaining: [
"$.available_count",
"$.rate_limit_reset_credits.available_count",
0
],
resetAt: [
"$.expires_at",
"$.expiresAt",
"$.reset_at",
"$.resetAt"
],
unit: "resets",
window: "manual-reset"
}
]
};
const codexAccountTokenUsageMapping: ProviderAccountMappingConfig = {
meters: [
{
id: "codex_lifetime_tokens",
kind: "tokens",
label: "Lifetime tokens",
unit: "tokens",
used: "$.stats.lifetime_tokens"
},
{
id: "codex_peak_daily_tokens",
kind: "tokens",
label: "Peak daily tokens",
unit: "tokens",
used: "$.stats.peak_daily_tokens",
window: "daily"
}
]
};
export function codexCandidate(): LocalAgentProviderCandidate {
const auth = readCodexAuth();
const catalog = readCodexLocalModelCatalog();
if (auth?.refreshToken || auth?.accessToken) {
return {
detail: "ChatGPT login detected. Click Import to add it as a gateway provider.",
id: "codex-api",
importable: true,
kind: "codex",
modelDisplayNames: catalog.modelDisplayNames,
modelMetadata: catalog.modelMetadata,
models: catalog.models,
name: "Codex API",
protocol: "openai_responses",
sourceFile: auth.sourceFile,
status: "available"
};
}
return missingCandidate("codex", "codex-api", "Codex API", "openai_responses", catalog.models, catalog.modelDisplayNames);
}
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 probedCandidate = await codexCandidateWithProbedModels(candidate).catch(() => candidate);
const provider = providerPayload(probedCandidate, uniqueProviderName(providerNames, "Codex API"), codexDefaultBaseUrl, codexProviderAccountConfig());
return {
candidate: probedCandidate,
provider,
providerPlugins: [
codexOauthPlugin("codex-oauth"),
codexOauthPlugin("codex-oauth-internal", providerInternalNamePlaceholder)
].map((plugin) => ({
...plugin,
...(auth.isFedrampAccount ? { auth: { headers: { "X-OpenAI-Fedramp": "true" } } } : {}),
codexOauth: {
accessToken: auth.accessToken,
...(auth.accountId ? { accountId: auth.accountId } : {}),
refreshIfMissingAccessToken: true,
refreshToken: auth.refreshToken,
required: true
}
}))
};
}
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(codexHomeDir(), ".codex", "auth.json");
const record = readJsonRecord(sourceFile);
if (!record) {
return undefined;
}
const tokens = isRecord(record.tokens) ? record.tokens : {};
const idToken = readString(tokens.id_token) || readString(tokens.idToken);
const idTokenClaims = readCodexIdTokenClaims(idToken);
return {
accountId:
readString(tokens.account_id) ||
readString(tokens.accountId) ||
idTokenClaims.accountId,
accessToken: readString(tokens.access_token) || readString(tokens.accessToken),
isFedrampAccount: idTokenClaims.isFedrampAccount,
refreshToken: readString(tokens.refresh_token) || readString(tokens.refreshToken),
sourceFile
};
}
export function codexProviderAccountConfig(): ProviderAccountConfig {
return {
connectors: [
{
auth: "provider-api-key",
endpoint: `${codexAccountBaseUrl}/wham/usage`,
headers: {
"User-Agent": "codex-cli"
},
mapping: codexAccountRateLimitMapping,
type: "http-json"
},
{
auth: "provider-api-key",
endpoint: `${codexAccountBaseUrl}/wham/rate-limit-reset-credits`,
headers: {
"User-Agent": "codex-cli"
},
mapping: codexAccountRateLimitResetCreditsMapping,
type: "http-json"
},
{
auth: "provider-api-key",
endpoint: `${codexAccountBaseUrl}/wham/profiles/me`,
headers: {
"User-Agent": "codex-cli"
},
mapping: codexAccountTokenUsageMapping,
type: "http-json"
}
],
enabled: true
};
}
export function attachCodexRateLimitResetCreditDetails(meters: ProviderAccountMeter[], payload: unknown): ProviderAccountMeter[] {
const details = codexRateLimitResetCreditDetails(payload);
if (details.length === 0) {
return meters;
}
const resetAt = firstCodexResetCreditExpiry(details);
return meters.map((meter) => {
if (!isCodexManualResetMeter(meter)) {
return meter;
}
return {
...meter,
details,
resetAt: meter.resetAt ?? resetAt
};
});
}
export function codexRateLimitResetCreditDetails(payload: unknown): ProviderAccountMeterDetail[] {
const records = codexRateLimitResetCreditRecords(payload);
if (records.length === 0) {
return [];
}
const availableRecords = records.filter(isAvailableCodexResetCreditRecord);
const sourceRecords = availableRecords.length > 0 ? availableRecords : records;
return sourceRecords
.map(codexRateLimitResetCreditDetail)
.filter((detail): detail is ProviderAccountMeterDetail => Boolean(detail))
.sort(compareCodexResetCreditDetails);
}
export function normalizeCodexProviderAccountConfig(provider: GatewayProviderConfig): GatewayProviderConfig {
if (!isLocalCodexProvider(provider) || !shouldUseCurrentCodexAccountConfig(provider.account)) {
return provider;
}
const account = codexProviderAccountConfig();
return {
...provider,
account: {
...account,
refreshIntervalMs: provider.account?.refreshIntervalMs ?? account.refreshIntervalMs
}
};
}
function isLocalCodexProvider(provider: GatewayProviderConfig): boolean {
return (
providerApiKey(provider) === localAgentProviderApiKey &&
normalizeProviderBaseUrl(providerBaseUrl(provider)) === normalizeProviderBaseUrl(codexDefaultBaseUrl)
);
}
function shouldUseCurrentCodexAccountConfig(account: ProviderAccountConfig | undefined): boolean {
if (account?.enabled === false) {
return false;
}
const connectors = account?.connectors ?? [];
if (connectors.length === 0) {
return true;
}
return connectors.every(isCodexAccountConnector);
}
function isCodexAccountConnector(connector: ProviderAccountConnectorConfig): boolean {
if (connector.type === "standard") {
return !connector.endpoint?.trim() && !connector.endpoints?.length && !connector.headers && !connector.id;
}
if (connector.type !== "http-json") {
return false;
}
return /^https:\/\/chatgpt\.com\/backend-api\/wham\//i.test(connector.endpoint.trim());
}
function codexRateLimitResetCreditRecords(payload: unknown): Record<string, unknown>[] {
if (!isRecord(payload)) {
return [];
}
const containers = [
payload.rate_limit_reset_credits,
payload.rateLimitResetCredits,
payload
].filter(isRecord);
for (const container of containers) {
const candidates = [
container.credits,
container.items,
container.data,
container.available,
container.available_credits,
container.availableCredits,
container.reset_credits,
container.resetCredits
];
for (const candidate of candidates) {
const records = readCodexResetCreditRecordArray(candidate);
if (records.length > 0) {
return records;
}
}
}
return [];
}
function readCodexResetCreditRecordArray(value: unknown): Record<string, unknown>[] {
if (Array.isArray(value)) {
return value.filter(isRecord);
}
if (!isRecord(value)) {
return [];
}
const nested = [value.credits, value.items, value.data];
for (const candidate of nested) {
if (Array.isArray(candidate)) {
return candidate.filter(isRecord);
}
}
return [];
}
function isAvailableCodexResetCreditRecord(record: Record<string, unknown>): boolean {
const status = readCodexStringFromKeys(record, ["status", "state"])?.toLowerCase();
return !status || status === "available" || status === "active";
}
function codexRateLimitResetCreditDetail(record: Record<string, unknown>, index: number): ProviderAccountMeterDetail | undefined {
const id = readCodexStringFromKeys(record, ["id", "credit_id", "creditId"]);
const status = readCodexStringFromKeys(record, ["status", "state"]);
const effectiveAt = readCodexDateFromKeys(record, [
"effective_at",
"effectiveAt",
"start_date",
"startDate",
"valid_from",
"validFrom",
"starts_at",
"startsAt",
"start_at",
"startAt",
"available_at",
"availableAt",
"granted_at",
"grantedAt",
"created_at",
"createdAt"
]);
const expiresAt = readCodexDateFromKeys(record, [
"expires_at",
"expiresAt",
"expire_at",
"expireAt",
"expiration_at",
"expirationAt",
"valid_until",
"validUntil",
"end_date",
"endDate",
"ends_at",
"endsAt",
"end_at",
"endAt"
]);
if (!effectiveAt && !expiresAt) {
return undefined;
}
return {
description: readCodexStringFromKeys(record, ["description", "message"]),
effectiveAt,
expiresAt,
id: id ?? `codex-reset-credit-${index + 1}`,
label: readCodexStringFromKeys(record, ["label", "name", "title"]),
redeemable: Boolean(id) && isAvailableCodexResetCreditRecord(record),
status
};
}
function readCodexStringFromKeys(record: Record<string, unknown>, keys: string[]): string | undefined {
for (const key of keys) {
const value = readString(record[key]);
if (value) {
return value;
}
}
return undefined;
}
function readCodexDateFromKeys(record: Record<string, unknown>, keys: string[]): string | undefined {
for (const key of keys) {
const value = codexDateString(record[key]);
if (value) {
return value;
}
}
return undefined;
}
function codexDateString(value: unknown): string | undefined {
if (typeof value === "number" && Number.isFinite(value)) {
const timestamp = value > 1_000_000_000_000 ? value : value * 1000;
return new Date(timestamp).toISOString();
}
const text = readString(value);
if (!text) {
return undefined;
}
const timestamp = new Date(text).getTime();
return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : text;
}
function compareCodexResetCreditDetails(a: ProviderAccountMeterDetail, b: ProviderAccountMeterDetail): number {
return codexDetailTimestamp(a.expiresAt) - codexDetailTimestamp(b.expiresAt)
|| codexDetailTimestamp(a.effectiveAt) - codexDetailTimestamp(b.effectiveAt);
}
function codexDetailTimestamp(value: string | undefined): number {
if (!value) {
return Number.MAX_SAFE_INTEGER;
}
const timestamp = new Date(value).getTime();
return Number.isFinite(timestamp) ? timestamp : Number.MAX_SAFE_INTEGER;
}
function firstCodexResetCreditExpiry(details: ProviderAccountMeterDetail[]): string | undefined {
return [...details]
.sort(compareCodexResetCreditDetails)
.find((detail) => detail.expiresAt)
?.expiresAt;
}
function isCodexManualResetMeter(meter: ProviderAccountMeter): boolean {
const text = `${meter.id} ${meter.label} ${meter.window ?? ""}`.toLowerCase();
return text.includes("manual_reset") || text.includes("manual reset") || text.includes("manual-reset");
}
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 codexOauthPlugin(suffix: string, providerName = providerNamePlaceholder): Record<string, unknown> {
return {
key: `ccr-local-agent-${providerNameSlugPlaceholder}-${suffix}`,
providerName,
request: codexBackendRequestTransform()
};
}
function codexBackendRequestTransform(): Record<string, unknown> {
return {
bodyRemove: ["max_output_tokens"]
};
}
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> = {};
const modelMetadata: Record<string, ProviderModelMetadata> = {};
for (const item of codexModelCatalogItems(payload)) {
const model = isRecord(item)
? 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.title) || readString(item.name);
if (displayName && displayName !== model) {
modelDisplayNames[model] = displayName;
}
const metadata = codexModelMetadataFromItem(item);
if (metadata) {
modelMetadata[model] = metadata;
}
}
}
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"])
? payload["https://api.openai.com/auth"]
: {};
return {
accountId: readString(auth.chatgpt_account_id) || readString(auth.account_id) || readString(auth.accountId),
isFedrampAccount: readBoolean(auth.chatgpt_account_is_fedramp)
};
}
function readJwtPayload(jwt: string | undefined): Record<string, unknown> | undefined {
const encoded = jwt?.split(".")[1];
if (!encoded) {
return undefined;
}
try {
const padded = encoded.padEnd(encoded.length + ((4 - encoded.length % 4) % 4), "=");
const decoded = Buffer.from(padded.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
const payload = JSON.parse(decoded) as unknown;
return isRecord(payload) ? payload : undefined;
} catch {
return undefined;
}
}

View file

@ -1,50 +0,0 @@
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.");
}

View file

@ -1,129 +0,0 @@
#!/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;
});

View file

@ -1,23 +0,0 @@
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)
);
}

View file

@ -1,146 +0,0 @@
const targetUrl = process.env.BROWSER_WEB_SEARCH_MCP_URL?.trim();
const requestTimeoutMs = clampInteger(Number(process.env.BROWSER_WEB_SEARCH_PROXY_TIMEOUT_MS), 1_000, 600_000, 120_000);
let stdinBuffer = Buffer.alloc(0);
if (!targetUrl) {
process.stderr.write("BROWSER_WEB_SEARCH_MCP_URL is required.\n");
process.exit(1);
}
process.stdin.on("data", (chunk: Buffer | string) => {
stdinBuffer = Buffer.concat([stdinBuffer, typeof chunk === "string" ? Buffer.from(chunk) : chunk]);
void drainFrames();
});
process.stdin.on("end", () => {
process.exit(0);
});
async function drainFrames(): Promise<void> {
while (true) {
const headerEnd = stdinBuffer.indexOf("\r\n\r\n");
if (headerEnd < 0) {
return;
}
const headerText = stdinBuffer.slice(0, headerEnd).toString("utf8");
const contentLength = readContentLength(headerText);
if (contentLength === undefined || contentLength < 0) {
stdinBuffer = Buffer.alloc(0);
writeFrame(jsonRpcError(null, -32600, "Invalid MCP frame header."));
return;
}
const payloadStart = headerEnd + 4;
const payloadEnd = payloadStart + contentLength;
if (stdinBuffer.length < payloadEnd) {
return;
}
const body = stdinBuffer.slice(payloadStart, payloadEnd).toString("utf8");
stdinBuffer = stdinBuffer.slice(payloadEnd);
await forwardPayload(body);
}
}
async function forwardPayload(body: string): Promise<void> {
const requestId = readJsonRpcId(body);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), requestTimeoutMs);
try {
const response = await fetch(targetUrl!, {
body,
headers: {
accept: "application/json, text/event-stream",
"content-type": "application/json"
},
method: "POST",
signal: controller.signal
});
if (response.status === 204) {
return;
}
const text = await response.text();
if (!response.ok) {
writeFrame(jsonRpcError(requestId, -32603, text || `In-app browser MCP returned HTTP ${response.status}.`));
return;
}
if (text.trim()) {
writeRawFrame(text);
}
} catch (error) {
writeFrame(jsonRpcError(requestId, -32603, formatError(error)));
} finally {
clearTimeout(timeout);
}
}
function readContentLength(headerText: string): number | undefined {
for (const line of headerText.split(/\r?\n/)) {
const match = /^content-length\s*:\s*(\d+)\s*$/i.exec(line);
if (match) {
return Number(match[1]);
}
}
return undefined;
}
function readJsonRpcId(body: string): null | number | string {
try {
const payload = JSON.parse(body) as unknown;
if (isRecord(payload)) {
return isJsonRpcId(payload.id) ? payload.id : null;
}
if (Array.isArray(payload)) {
const first = payload.find((item) => isRecord(item) && isJsonRpcId(item.id));
return isRecord(first) && isJsonRpcId(first.id) ? first.id : null;
}
} catch {
// The upstream MCP endpoint will return the parse error for valid JSON-RPC framing.
}
return null;
}
function isJsonRpcId(value: unknown): value is null | number | string {
return value === null || typeof value === "number" || typeof value === "string";
}
function jsonRpcError(id: null | number | string, code: number, message: string): Record<string, unknown> {
return {
error: {
code,
message
},
id,
jsonrpc: "2.0"
};
}
function writeFrame(payload: Record<string, unknown>): void {
writeRawFrame(JSON.stringify(payload));
}
function writeRawFrame(body: string): void {
process.stdout.write(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`);
}
function clampInteger(value: number, min: number, max: number, fallback: number): number {
if (!Number.isFinite(value)) {
return fallback;
}
return Math.min(max, Math.max(min, Math.trunc(value)));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function formatError(error: unknown): string {
if (error instanceof Error) {
return error.name === "AbortError" ? "In-app browser MCP proxy request timed out." : error.message;
}
return String(error);
}

View file

@ -1,226 +0,0 @@
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;
}

File diff suppressed because it is too large Load diff

View file

@ -1,92 +0,0 @@
import type { ProviderAccountConfig, ProviderAccountHttpJsonConnectorConfig } from "@ccr/core/contracts/app";
import { compactProviderUrl, providerUrlWithDefaultScheme } from "@ccr/core/providers/url";
export type DetectedProviderKind = "new-api";
const newApiHeaderNames = ["x-new-api-version", "x-oneapi-request-id"];
export function detectedProviderFromHeaders(headers: Record<string, string | undefined>): DetectedProviderKind | undefined {
return hasNewApiHeaders(headers) ? "new-api" : undefined;
}
export function hasNewApiHeaders(headers: Record<string, string | undefined>): boolean {
const normalized = new Set(Object.keys(headers).map((key) => key.toLowerCase()));
return newApiHeaderNames.some((header) => normalized.has(header));
}
export function newApiKeyUsageAccountConfig(baseUrl: string): ProviderAccountConfig {
return {
connectors: [
{
auth: "provider-api-key",
endpoint: newApiKeyUsageEndpoint(baseUrl),
mapping: {
message: "$.message",
meters: [
{
id: "new_api_key_quota",
kind: "quota",
label: "API key quota",
limit: "$.data.total_granted",
remaining: "$.data.total_available",
unit: "quota",
used: "$.data.total_used",
}
]
},
method: "GET",
parser: "new-api-key-usage",
type: "http-json"
}
],
enabled: true
};
}
export function newApiKeyUsageEndpoint(baseUrl: string): string {
const root = newApiRootBaseUrl(baseUrl);
return `${root}/api/usage/token/`;
}
export function newApiUserSelfConnectorConfig(baseUrl: string): ProviderAccountHttpJsonConnectorConfig {
return {
auth: "none",
endpoint: newApiUserSelfEndpoint(baseUrl),
headers: {
Authorization: "Bearer <new-api-access-token>",
"New-Api-User": "<user-id>"
},
mapping: {
meters: [
{
id: "new_api_user_balance",
kind: "balance",
label: "User balance",
remaining: "$.data.quota",
unit: "quota",
used: "$.data.used_quota"
}
]
},
method: "GET",
parser: "new-api-user-self",
type: "http-json"
};
}
export function newApiUserSelfEndpoint(baseUrl: string): string {
const root = newApiRootBaseUrl(baseUrl);
return `${root}/api/user/self`;
}
export function newApiRootBaseUrl(baseUrl: string): string {
try {
const url = new URL(providerUrlWithDefaultScheme(baseUrl.trim()));
url.pathname = url.pathname.replace(/\/+(v1|api)$/i, "").replace(/\/+$/, "") || "/";
url.search = "";
url.hash = "";
return compactProviderUrl(url);
} catch {
return baseUrl.trim().replace(/[?#].*$/, "").replace(/\/+$/, "").replace(/\/(v1|api)$/i, "");
}
}

View file

@ -1,15 +0,0 @@
import { defaultProviderAccountConfig, type ProviderPreset } from "@ccr/core/providers/presets/types";
export const claudeApiProviderPreset: ProviderPreset = {
account: defaultProviderAccountConfig,
aliases: ["claudeapi", "claudeapi.com", "www.claudeapi.com"],
endpoints: [
{
baseUrl: "https://gw.claudeapi.com",
protocols: ["anthropic_messages"]
}
],
id: "claudeapi",
name: "claudeapi",
websiteUrl: "https://console.claudeapi.com/agent/register/LbmB7Y9kPloyzhwF?utm_source=claudecoderouter&utm_medium=partner&utm_campaign=claudecoderouter_2026&utm_content=default"
};

View file

@ -1,15 +0,0 @@
import { defaultProviderAccountConfig, type ProviderPreset } from "@ccr/core/providers/presets/types";
export const code0ProviderPreset: ProviderPreset = {
account: defaultProviderAccountConfig,
aliases: ["code0", "code0.ai", "code 0"],
endpoints: [
{
baseUrl: "https://console.code0.ai",
protocols: ["anthropic_messages", "openai_chat_completions", "openai_responses"]
}
],
id: "code0",
name: "code0.ai",
websiteUrl: "https://code0.ai/agent/register/9n9jOsSnYQoemIVL?utm_source=claudecoderouter&utm_medium=partner&utm_campaign=claudecoderouter_2026&utm_content=default"
};

View file

@ -1,15 +0,0 @@
import { defaultProviderAccountConfig, type ProviderPreset } from "@ccr/core/providers/presets/types";
export const fennoProviderPreset: ProviderPreset = {
account: defaultProviderAccountConfig,
aliases: ["fenno", "fenno.ai", "fenno ai"],
endpoints: [
{
baseUrl: "https://api.fenno.ai",
protocols: ["openai_chat_completions", "openai_responses", "anthropic_messages"]
}
],
id: "fenno",
name: "Fenno.ai",
websiteUrl: "https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=9HHHAB5QLAES"
};

View file

@ -1,44 +0,0 @@
import type { ProviderPreset } from "@ccr/core/providers/presets/types";
import { standardProviderAccountConfig } from "@ccr/core/providers/presets/types";
export const minimaxGlobalProviderPreset: ProviderPreset = {
account: standardProviderAccountConfig,
aliases: ["minimax", "minimax global"],
defaultModels: ["MiniMax-M3"],
endpoints: [
{
baseUrl: "https://api.minimax.io/v1",
protocols: ["openai_chat_completions"],
websiteUrl: "https://platform.minimax.io/docs"
},
{
baseUrl: "https://api.minimax.io/anthropic/v1",
protocols: ["anthropic_messages"],
websiteUrl: "https://platform.minimax.io/docs"
}
],
id: "minimax-global",
name: "MiniMax (Global)",
websiteUrl: "https://platform.minimax.io/docs"
};
export const minimaxChinaProviderPreset: ProviderPreset = {
account: standardProviderAccountConfig,
aliases: ["minimax", "minimaxi", "minimax china"],
defaultModels: ["MiniMax-M3"],
endpoints: [
{
baseUrl: "https://api.minimaxi.com/v1",
protocols: ["openai_chat_completions"],
websiteUrl: "https://platform.minimaxi.com/docs"
},
{
baseUrl: "https://api.minimaxi.com/anthropic/v1",
protocols: ["anthropic_messages"],
websiteUrl: "https://platform.minimaxi.com/docs"
}
],
id: "minimax-cn",
name: "MiniMax (China)",
websiteUrl: "https://platform.minimaxi.com/docs"
};

View file

@ -1,35 +0,0 @@
import { defaultProviderAccountConfig, type ProviderPreset } from "@ccr/core/providers/presets/types";
export const qiniuAiProviderPreset: ProviderPreset = {
account: defaultProviderAccountConfig,
aliases: ["qiniu", "qiniu ai", "qiniu cloud ai", "qiniu yun ai", "qiniu yun", "七牛云", "七牛云ai", "七牛云 ai", "modelink"],
endpoints: [
{
baseUrl: "https://api.qnaigc.com",
label: "China mainland OpenAI",
protocols: ["openai_chat_completions"],
websiteUrl: "https://s.qiniu.com/AVjMVf"
},
{
baseUrl: "https://api.qnaigc.com/bypass/openai/v1",
label: "China mainland OpenAI Responses",
protocols: ["openai_responses"],
websiteUrl: "https://s.qiniu.com/AVjMVf"
},
{
baseUrl: "https://api.qnaigc.com",
label: "China mainland Anthropic",
protocols: ["anthropic_messages"],
websiteUrl: "https://s.qiniu.com/AVjMVf"
},
{
baseUrl: "https://api.qnaigc.com/bypass/vertex/v1",
label: "China mainland Gemini Generate",
protocols: ["gemini_generate_content"],
websiteUrl: "https://s.qiniu.com/AVjMVf"
}
],
id: "qiniu-ai",
name: "七牛云 AI",
websiteUrl: "https://s.qiniu.com/AVjMVf"
};

View file

@ -1,15 +0,0 @@
import { defaultProviderAccountConfig, type ProviderPreset } from "@ccr/core/providers/presets/types";
export const teamoRouterProviderPreset: ProviderPreset = {
account: defaultProviderAccountConfig,
aliases: ["teamorouter", "teamo router", "teamo"],
endpoints: [
{
baseUrl: "https://api.teamorouter.com",
protocols: ["anthropic_messages", "openai_chat_completions", "openai_responses"]
}
],
id: "teamorouter",
name: "TeamoRouter",
websiteUrl: "https://teamorouter.com/"
};

View file

@ -1,147 +0,0 @@
import {
customProviderPresetId,
type ProviderIdentitySafetyIssue,
type ProviderPreset,
type ProviderPresetEndpoint
} from "@ccr/core/providers/presets/types";
import { providerUrlWithDefaultScheme } from "@ccr/core/providers/url";
export function findProviderPresetInList(
presets: ProviderPreset[],
id: string | undefined
): ProviderPreset | undefined {
if (!id || id === customProviderPresetId) {
return undefined;
}
return presets.find((preset) => preset.id === id);
}
export function findProviderPresetByBaseUrlInList(
presets: ProviderPreset[],
baseUrl: string
): ProviderPreset | undefined {
return presets.find((preset) =>
providerPresetMatchesBaseUrl(preset, baseUrl)
);
}
export function findProviderPresetByIdentityInList(
presets: ProviderPreset[],
name: string | undefined
): ProviderPreset | undefined {
return findProviderPresetsByIdentity(presets, name)[0];
}
export function primaryProviderPresetEndpoint(preset: ProviderPreset): ProviderPresetEndpoint | undefined {
return preset.endpoints[0];
}
export function providerIdentitySafetyIssueInList(
_presets: ProviderPreset[],
input: {
baseUrl: string;
name?: string;
presetId?: string;
}
): ProviderIdentitySafetyIssue | undefined {
void input;
return undefined;
}
export function providerApiKeySafetyIssueInList(
_presets: ProviderPreset[],
input: {
apiKey?: string;
baseUrl: string;
name?: string;
presetId?: string;
}
): ProviderIdentitySafetyIssue | undefined {
void input;
return undefined;
}
export function providerPresetMatchesBaseUrl(preset: ProviderPreset, baseUrl: string): boolean {
return preset.endpoints.some((endpoint) => providerEndpointMatchesBaseUrl(endpoint.baseUrl, baseUrl));
}
export function providerEndpointCanReceiveProviderApiKeyInList(
_presets: ProviderPreset[],
input: {
apiKey?: string;
endpoint: string;
providerName?: string;
providerPresetId?: string;
}
): ProviderIdentitySafetyIssue | undefined {
void input;
return undefined;
}
function findProviderPresetsByIdentity(presets: ProviderPreset[], name: string | undefined): ProviderPreset[] {
const normalizedName = normalizeProviderIdentityText(name);
if (!normalizedName) {
return [];
}
return presets
.map((preset) => ({
preset,
score: providerPresetIdentityMatchScore(preset, normalizedName)
}))
.filter((item) => item.score > 0)
.sort((left, right) => right.score - left.score)
.map((item) => item.preset);
}
function providerPresetIdentityMatchScore(preset: ProviderPreset, normalizedName: string): number {
const identities = [preset.id, preset.name, ...preset.aliases]
.map(normalizeProviderIdentityText)
.filter(Boolean);
return Math.max(0, ...identities.map((identity) => {
if (normalizedName === identity) {
return 10_000 + identity.length;
}
if (identity.length >= 4 && normalizedName.includes(identity)) {
return identity.length;
}
return 0;
}));
}
function providerEndpointMatchesBaseUrl(endpointBaseUrl: string, baseUrl: string): boolean {
const endpoint = parseProviderPresetUrl(endpointBaseUrl);
const candidate = parseProviderPresetUrl(baseUrl);
if (!endpoint || !candidate) {
return false;
}
if (candidate.protocol !== endpoint.protocol || candidate.host !== endpoint.host) {
return false;
}
const endpointPath = normalizeProviderPresetPath(endpoint.pathname);
const candidatePath = normalizeProviderPresetPath(candidate.pathname);
return endpointPath === "/" ||
candidatePath === "/" ||
candidatePath === endpointPath ||
candidatePath.startsWith(`${endpointPath}/`) ||
endpointPath.startsWith(`${candidatePath}/`);
}
function parseProviderPresetUrl(value: string): URL | undefined {
try {
return new URL(providerUrlWithDefaultScheme(value.trim()));
} catch {
return undefined;
}
}
function normalizeProviderPresetPath(value: string): string {
const trimmed = value.replace(/\/+$/, "");
return trimmed || "/";
}
function normalizeProviderIdentityText(value: string | undefined): string {
return value?.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "") ?? "";
}

View file

@ -1 +0,0 @@
export { ProxyAgent } from "undici";

View file

@ -1,7 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src"
},
"include": ["src/**/*.ts", "src/**/*.d.ts"]
}

View file

@ -1,13 +0,0 @@
{
"name": "@claude-code-router/electron",
"version": "3.0.11",
"private": true,
"description": "Claude Code Router Electron desktop shell.",
"main": "dist/main/main.js",
"dependencies": {
"better-sqlite3": "^12.11.1"
},
"devDependencies": {
"electron-updater": "^6.8.9"
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,593 +0,0 @@
import { randomUUID } from "node:crypto";
import http, { type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { BrowserWindow, session, shell } from "electron";
import type {
ChromeLoginImportCookie,
ChromeLoginImportJob,
ChromeLoginImportLocalStorage,
ChromeLoginImportRequest,
ChromeLoginImportResult,
ChromeLoginImportTarget
} from "@ccr/core/contracts/app";
type ServerInfo = {
server: Server;
url: string;
};
type StoredChromeLoginImportJob = ChromeLoginImportJob;
type CookieSetDetails = Parameters<Electron.Cookies["set"]>[0];
const browserPartition = "persist:ccr-built-in-browser";
const webSearchPartition = "persist:ccr-browser-web-search-mcp";
const importJobTtlMs = 5 * 60_000;
const maxImportRequestBytes = 16 * 1024 * 1024;
const maxStoredErrors = 20;
const localStorageWriteTimeoutMs = 15_000;
class ChromeLoginImportService {
private readonly jobs = new Map<string, StoredChromeLoginImportJob>();
private serverInfo?: ServerInfo;
private serverStartPromise?: Promise<ServerInfo>;
async createJob(request: ChromeLoginImportRequest): Promise<ChromeLoginImportJob> {
const domains = uniqueStrings(request.domains.map(normalizeImportDomain).filter((item): item is string => Boolean(item)));
if (domains.length === 0) {
throw new Error("At least one Chrome import domain is required.");
}
const target = normalizeImportTarget(request.target);
const serverInfo = await this.ensureServer();
const id = randomUUID();
const now = Date.now();
const job: StoredChromeLoginImportJob = {
confirmUrl: `${serverInfo.url}/chrome-import/jobs/${id}/confirm`,
createdAt: now,
domains,
endpointUrl: serverInfo.url,
expiresAt: now + importJobTtlMs,
id,
importUrl: `${serverInfo.url}/chrome-import/jobs/${id}`,
status: "pending",
target
};
this.jobs.set(id, job);
this.pruneJobs();
if (request.openConfirmationPage) {
await this.openConfirmationPage(job.id);
}
return cloneJob(job);
}
getJob(id: string): ChromeLoginImportJob | undefined {
const job = this.jobs.get(id);
if (!job) {
return undefined;
}
this.refreshExpiredJob(job);
return cloneJob(job);
}
async openConfirmationPage(id: string): Promise<ChromeLoginImportJob> {
const job = this.jobs.get(id);
if (!job) {
throw new Error("Chrome login import job was not found.");
}
this.refreshExpiredJob(job);
if (job.status !== "pending") {
throw new Error(`Chrome login import job is ${job.status}.`);
}
await shell.openExternal(job.confirmUrl);
return cloneJob(job);
}
private async ensureServer(): Promise<ServerInfo> {
if (this.serverInfo) {
return this.serverInfo;
}
if (this.serverStartPromise) {
return this.serverStartPromise;
}
this.serverStartPromise = new Promise<ServerInfo>((resolve, reject) => {
const server = http.createServer((request, response) => {
void this.handleRequest(request, response).catch((error) => {
sendJson(response, 500, { error: { message: formatError(error) } });
});
});
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
server.off("error", reject);
const address = server.address();
if (!address || typeof address === "string") {
server.close();
reject(new Error("Chrome login import server failed to start."));
return;
}
const info = {
server,
url: `http://127.0.0.1:${address.port}`
};
this.serverInfo = info;
resolve(info);
});
}).finally(() => {
this.serverStartPromise = undefined;
});
return this.serverStartPromise;
}
private async handleRequest(request: IncomingMessage, response: ServerResponse): Promise<void> {
setCorsHeaders(response);
if (request.method === "OPTIONS") {
response.writeHead(204);
response.end();
return;
}
const path = request.url ? new URL(request.url, "http://127.0.0.1").pathname : "/";
const match = path.match(/^\/chrome-import\/jobs\/([^/]+)(?:\/(confirm|cookies))?$/);
if (!match) {
sendJson(response, 404, { error: { message: "Chrome login import endpoint not found." } });
return;
}
const id = decodeURIComponent(match[1]);
const job = this.jobs.get(id);
if (!job) {
sendJson(response, 404, { error: { message: "Chrome login import job was not found." } });
return;
}
this.refreshExpiredJob(job);
if (job.status === "expired") {
sendJson(response, 410, { error: { message: "Chrome login import job expired." }, job: cloneJob(job) });
return;
}
const action = match[2];
if (request.method === "GET" && action === "confirm") {
sendHtml(response, 200, confirmationPageHtml(job));
return;
}
if (request.method === "GET" && !action) {
sendJson(response, 200, { job: cloneJob(job) });
return;
}
if (request.method === "POST" && action === "cookies") {
if (job.status !== "pending") {
sendJson(response, 409, {
error: {
message: `Chrome login import job is ${job.status}.`
},
job: cloneJob(job)
});
return;
}
const payload = await readJsonRequest(request);
const result = await this.importLoginState(job, payload);
sendJson(response, 200, { job: cloneJob(job), result });
return;
}
sendJson(response, 405, { error: { message: "Unsupported Chrome login import method." } });
}
private async importLoginState(job: StoredChromeLoginImportJob, payload: unknown): Promise<ChromeLoginImportResult> {
const importPayload = readImportPayload(payload);
const partitions = targetPartitions(job.target);
const result: ChromeLoginImportResult = {
completedAt: Date.now(),
cookieImported: 0,
cookieSkipped: 0,
domains: [...job.domains],
imported: 0,
localStorageImported: 0,
localStorageSkipped: 0,
partitions,
skipped: 0
};
const errors: string[] = [];
for (const cookie of importPayload.cookies) {
const normalized = normalizeChromeCookie(cookie, job.domains);
if (!normalized) {
result.cookieSkipped += 1;
continue;
}
try {
await Promise.all(partitions.map((partition) => session.fromPartition(partition).cookies.set(normalized)));
result.cookieImported += 1;
} catch (error) {
result.cookieSkipped += 1;
if (errors.length < maxStoredErrors) {
errors.push(`${normalized.domain || new URL(normalized.url).hostname}:${normalized.name}: ${formatError(error)}`);
}
}
}
await Promise.all(partitions.map((partition) => session.fromPartition(partition).cookies.flushStore()));
for (const localStorageEntry of importPayload.localStorage) {
const normalized = normalizeLocalStorageEntry(localStorageEntry, job.domains);
if (!normalized) {
result.localStorageSkipped += 1;
continue;
}
const itemCount = Object.keys(normalized.items).length;
if (itemCount === 0) {
result.localStorageSkipped += 1;
continue;
}
try {
await Promise.all(partitions.map((partition) => writeLocalStorage(partition, normalized.origin, normalized.items)));
result.localStorageImported += itemCount;
} catch (error) {
result.localStorageSkipped += itemCount;
if (errors.length < maxStoredErrors) {
errors.push(`${normalized.origin}: localStorage: ${formatError(error)}`);
}
}
}
result.imported = result.cookieImported + result.localStorageImported;
result.skipped = result.cookieSkipped + result.localStorageSkipped;
if (errors.length > 0) {
result.errors = errors;
}
job.result = result;
job.status = result.imported > 0 || result.skipped > 0 ? "completed" : "failed";
return result;
}
private refreshExpiredJob(job: StoredChromeLoginImportJob): void {
if (job.status === "pending" && Date.now() > job.expiresAt) {
job.status = "expired";
}
}
private pruneJobs(): void {
const cutoff = Date.now() - importJobTtlMs;
for (const [id, job] of this.jobs) {
this.refreshExpiredJob(job);
if (job.expiresAt < cutoff) {
this.jobs.delete(id);
}
}
}
}
export const chromeLoginImportService = new ChromeLoginImportService();
function targetPartitions(target: ChromeLoginImportTarget): string[] {
return target === "browser-and-web-search"
? [browserPartition, webSearchPartition]
: [browserPartition];
}
function normalizeChromeCookie(cookie: ChromeLoginImportCookie, allowedDomains: string[]): CookieSetDetails | undefined {
if (!isRecord(cookie) || typeof cookie.name !== "string" || typeof cookie.value !== "string") {
return undefined;
}
if (cookie.partitionKey !== undefined) {
return undefined;
}
const rawDomain = readString(cookie.domain).toLowerCase();
const cookieHost = normalizeCookieHost(rawDomain);
if (!cookieHost || !allowedDomains.some((domain) => cookieDomainMatches(cookieHost, domain))) {
return undefined;
}
const path = normalizeCookiePath(cookie.path);
const expirationDate = typeof cookie.expirationDate === "number" && Number.isFinite(cookie.expirationDate)
? cookie.expirationDate
: undefined;
if (expirationDate !== undefined && expirationDate <= Date.now() / 1000) {
return undefined;
}
const secure = cookie.secure === true;
const details: CookieSetDetails = {
httpOnly: cookie.httpOnly === true,
name: cookie.name,
path,
secure,
url: cookieUrl(cookieHost, path, secure),
value: cookie.value
};
if (cookie.hostOnly !== true) {
details.domain = rawDomain || cookieHost;
}
if (expirationDate !== undefined && cookie.session !== true) {
details.expirationDate = expirationDate;
}
const sameSite = normalizeSameSite(cookie.sameSite);
if (sameSite) {
details.sameSite = sameSite;
}
return details;
}
function normalizeLocalStorageEntry(
entry: ChromeLoginImportLocalStorage,
allowedDomains: string[]
): ChromeLoginImportLocalStorage | undefined {
if (!isRecord(entry) || !isRecord(entry.items)) {
return undefined;
}
let origin: URL;
try {
origin = new URL(readString(entry.origin));
} catch {
return undefined;
}
if (!["http:", "https:"].includes(origin.protocol)) {
return undefined;
}
if (!allowedDomains.some((domain) => cookieDomainMatches(origin.hostname.toLowerCase(), domain))) {
return undefined;
}
const items: Record<string, string> = {};
for (const [key, value] of Object.entries(entry.items)) {
if (typeof key === "string" && typeof value === "string") {
items[key] = value;
}
}
return {
items,
origin: origin.origin
};
}
async function writeLocalStorage(partition: string, origin: string, items: Record<string, string>): Promise<void> {
const window = new BrowserWindow({
height: 480,
paintWhenInitiallyHidden: true,
show: false,
skipTaskbar: true,
title: "CCR Chrome Login Import",
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
partition,
sandbox: true,
webSecurity: true
},
width: 640
});
try {
await withTimeout(window.webContents.loadURL(`${origin}/`), localStorageWriteTimeoutMs, "Timed out loading localStorage origin.");
const loadedOrigin = new URL(window.webContents.getURL()).origin;
if (loadedOrigin !== origin) {
throw new Error(`Origin redirected to ${loadedOrigin}.`);
}
const entries = Object.entries(items);
await window.webContents.executeJavaScript(
`(() => {
const entries = ${JSON.stringify(entries)};
for (const [key, value] of entries) {
window.localStorage.setItem(key, value);
}
return entries.length;
})()`,
true
);
} finally {
if (!window.isDestroyed()) {
window.destroy();
}
}
}
function normalizeImportTarget(value: unknown): ChromeLoginImportTarget {
return value === "browser-and-web-search" ? "browser-and-web-search" : "browser";
}
function normalizeImportDomain(value: unknown): string | undefined {
const raw = readString(value).toLowerCase();
if (!raw) {
return undefined;
}
try {
const parsed = new URL(raw.includes("://") ? raw : `https://${raw}`);
return normalizeCookieHost(parsed.hostname);
} catch {
return normalizeCookieHost(raw.replace(/^\*\./, "").split("/")[0] || "");
}
}
function normalizeCookieHost(value: string): string | undefined {
const host = value.trim().replace(/^\./, "").toLowerCase();
if (!host || host.includes("*") || host.includes("/") || host.includes(" ")) {
return undefined;
}
return host;
}
function normalizeCookiePath(value: unknown): string {
const path = readString(value);
return path.startsWith("/") ? path : "/";
}
function cookieUrl(host: string, path: string, secure: boolean): string {
const normalizedPath = path.startsWith("/") ? path : "/";
return `${secure ? "https" : "http"}://${host}${normalizedPath}`;
}
function cookieDomainMatches(cookieHost: string, allowedDomain: string): boolean {
return cookieHost === allowedDomain || cookieHost.endsWith(`.${allowedDomain}`);
}
function normalizeSameSite(value: unknown): CookieSetDetails["sameSite"] | undefined {
return value === "lax" || value === "strict" || value === "no_restriction" || value === "unspecified"
? value
: undefined;
}
function readImportPayload(payload: unknown): {
cookies: ChromeLoginImportCookie[];
localStorage: ChromeLoginImportLocalStorage[];
} {
if (!isRecord(payload)) {
throw new Error("Chrome login import payload must be an object.");
}
const cookies = Array.isArray(payload.cookies)
? payload.cookies.filter(isRecord) as ChromeLoginImportCookie[]
: [];
const localStorage = Array.isArray(payload.localStorage)
? payload.localStorage.filter(isRecord) as ChromeLoginImportLocalStorage[]
: [];
if (cookies.length === 0 && localStorage.length === 0) {
throw new Error("Chrome login import payload must include cookies or localStorage.");
}
return { cookies, localStorage };
}
function cloneJob(job: StoredChromeLoginImportJob): ChromeLoginImportJob {
return {
...job,
domains: [...job.domains],
...(job.result
? {
result: {
...job.result,
domains: [...job.result.domains],
...(job.result.errors ? { errors: [...job.result.errors] } : {}),
partitions: [...job.result.partitions]
}
}
: {})
};
}
async function readJsonRequest(request: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
let total = 0;
for await (const chunk of request) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
total += buffer.byteLength;
if (total > maxImportRequestBytes) {
throw new Error("Chrome login import payload is too large.");
}
chunks.push(buffer);
}
return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
}
function sendJson(response: ServerResponse, statusCode: number, body: unknown): void {
if (!response.headersSent) {
response.writeHead(statusCode, { "content-type": "application/json" });
}
response.end(`${JSON.stringify(body)}\n`);
}
function sendHtml(response: ServerResponse, statusCode: number, body: string): void {
if (!response.headersSent) {
response.writeHead(statusCode, {
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'none'; connect-src http://127.0.0.1:* http://localhost:*",
"content-type": "text/html; charset=utf-8"
});
}
response.end(body);
}
function confirmationPageHtml(job: StoredChromeLoginImportJob): string {
const domains = job.domains.map((domain) => `<li>${escapeHtml(domain)}</li>`).join("");
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CCR Chrome 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 { align-items: center; background: Canvas; color: CanvasText; display: flex; justify-content: center; margin: 0; min-height: 100vh; padding: 24px; }
main { border: 1px solid color-mix(in srgb, CanvasText 14%, transparent); border-radius: 10px; box-shadow: 0 18px 44px color-mix(in srgb, CanvasText 10%, transparent); display: grid; gap: 16px; max-width: 560px; padding: 22px; width: min(560px, 100%); }
h1 { font-size: 20px; line-height: 1.2; margin: 0; }
p { color: color-mix(in srgb, CanvasText 72%, transparent); font-size: 13px; line-height: 1.45; margin: 0; }
ul { display: grid; gap: 6px; margin: 0; padding-left: 20px; }
li { font-size: 13px; }
button { background: #0f766e; border: 1px solid #0f766e; border-radius: 8px; color: white; cursor: pointer; font: inherit; font-weight: 750; height: 38px; padding: 0 14px; }
button:disabled { cursor: default; opacity: 0.52; }
.status { border-radius: 8px; color: color-mix(in srgb, CanvasText 68%, transparent); font-size: 12px; line-height: 1.4; min-height: 18px; overflow-wrap: anywhere; }
.status.error { color: #b91c1c; }
.status.ok { color: #15803d; }
</style>
</head>
<body>
<main
id="ccr-chrome-login-import"
data-import-url="${escapeHtml(job.importUrl)}"
data-job-id="${escapeHtml(job.id)}"
data-domains="${escapeHtml(job.domains.join(","))}"
>
<h1>Import Chrome Login State into CCR</h1>
<p>CCR is requesting permission to import cookies and localStorage for these domains into the in-app browser.</p>
<ul>${domains}</ul>
<button id="ccr-confirm-import" disabled type="button">Waiting for CCR Chrome extension</button>
<div id="ccr-import-status" class="status" role="status">Install or enable the CCR Login Import extension in Chrome to continue.</div>
</main>
</body>
</html>`;
}
function setCorsHeaders(response: ServerResponse): void {
response.setHeader("access-control-allow-headers", "content-type, x-ccr-login-import");
response.setHeader("access-control-allow-methods", "GET, POST, OPTIONS");
response.setHeader("access-control-allow-origin", "*");
}
function uniqueStrings(values: string[]): string[] {
return [...new Set(values)];
}
function readString(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (char) => {
switch (char) {
case "&":
return "&amp;";
case "<":
return "&lt;";
case ">":
return "&gt;";
case "\"":
return "&quot;";
default:
return "&#39;";
}
});
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
let timeout: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
});
return Promise.race([promise, timeoutPromise]).finally(() => {
if (timeout) {
clearTimeout(timeout);
}
});
}
function formatError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}

File diff suppressed because it is too large Load diff

View file

@ -1,33 +0,0 @@
import { app } from "electron";
import type { AppConfig } from "@ccr/core/contracts/app";
export function isLaunchAtLoginSupported(platform = process.platform): boolean {
return platform === "darwin" || platform === "win32";
}
export function syncLaunchAtLogin(config: Pick<AppConfig, "launchAtLogin">): void {
if (!isLaunchAtLoginSupported()) {
return;
}
const openAtLogin = Boolean(config.launchAtLogin);
const current = app.getLoginItemSettings();
if (current.openAtLogin === openAtLogin) {
return;
}
app.setLoginItemSettings(loginItemSettings(openAtLogin));
}
function loginItemSettings(openAtLogin: boolean): Electron.Settings {
const settings: Electron.Settings = {
openAtLogin
};
if (process.platform === "darwin") {
settings.openAsHidden = false;
return settings;
}
settings.path = process.execPath;
settings.args = process.defaultApp ? [app.getAppPath()] : [];
return settings;
}

View file

@ -1,7 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src"
},
"include": ["src/**/*.ts", "src/**/*.d.ts"]
}

View file

@ -1,21 +0,0 @@
{
"name": "@claude-code-router/ui",
"version": "3.0.11",
"private": true,
"description": "Claude Code Router web management UI.",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"baseui": "^16.1.1",
"clsx": "^2.1.1",
"lucide-react": "^1.17.0",
"motion": "^12.40.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"recharts": "^3.8.1",
"styletron-engine-atomic": "^1.6.2",
"styletron-react": "^6.1.1",
"tailwind-merge": "^3.6.0"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 992 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

View file

@ -1,7 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src"
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.d.ts"]
}

Some files were not shown because too many files have changed in this diff Show more