在个人配置中填写个人访问令牌(PAT)与 HTTPS 克隆账号,返回后继续。
+
- {repo.provider === "github" && repo.webUrl
+ {["github", "codeup"].includes(repo.provider) && repo.webUrl
? repo.webUrl.replace(
/^https?:\/\//,
"",
@@ -2098,8 +2309,8 @@ export default function QuickAccessWizard({
{projectMode === "existing" && projectRepos.length
- ? "为该项目添加 GitHub 仓库"
- : "绑定默认 GitHub 仓库"}
+ ? "为该项目添加代码仓库"
+ : "绑定默认代码仓库"}
) : (
- 支持 Git HTTPS 链接或 Git SSH 地址,例如 git@gitlab.com:group/repo.git。
+ 支持 Git HTTPS 链接或 Git SSH 地址,例如 git@gitlab.com:group/repo.git;云效仓库粘贴 https://codeup.aliyun.com/组织ID/分组/仓库.git。
)}
{selectedSSHRepo?.provider === "ssh" && sshKeysLoaded && !sshReady ? (
@@ -2346,10 +2557,10 @@ export default function QuickAccessWizard({
凭据
- {sshRepository ? "Git SSH" : "GitHub"} {(sshRepository ? sshReady : gitReady) ? "已配置" : "未配置"} ·
+ {sshRepository ? "Git SSH" : codeupRepository ? "云效 Codeup" : "GitHub"} {(sshRepository ? sshReady : codeupRepository ? codeupReady : gitReady) ? "已配置" : "未配置"} ·
CodeBuddy{" "}
{codeBuddyReady
? "已配置"
diff --git a/chatbot/src/assets/provider-logos/README.md b/chatbot/src/assets/provider-logos/README.md
index f732e7e7b..b4112f180 100644
--- a/chatbot/src/assets/provider-logos/README.md
+++ b/chatbot/src/assets/provider-logos/README.md
@@ -10,8 +10,17 @@ The interface uses these bundled assets in both chat and configuration.
and the pinned assets were downloaded from the corresponding
`cdn.jsdelivr.net/npm/simple-icons@v16/icons/.svg` URLs.
- `pi.svg` is the official primary color mark from the [Pi press kit](https://pi.dev/press-kit).
+- `codeup.svg` is an original LoopForge monochrome placeholder glyph (a cloud
+ with code brackets) for the Yunxiao Codeup credential card, following the
+ monochrome-glyph precedent of `pi.svg`. It is not an official Alibaba Cloud
+ or Codeup mark; replace it if an official brand asset becomes available.
+ The same file is mirrored at `web/images/credentials/codeup.svg`.
- `antigravity.svg` is the full-color icon from the [Google Antigravity press assets](https://antigravity.google/press).
- `kimi-code.png` is the icon published by Moonshot AI for the [Kimi Code extension](https://marketplace.visualstudio.com/items?itemName=moonshot-ai.kimi-code).
+- `qoder.svg` is the official Qoder CN brand mark, extracted from the installed
+ Qoder CN client's `qoderCnIdeLogo` vector asset and recolored to a monochrome
+ glyph (background removed). It is the same mark as
+ `web/images/credentials/qoder.svg`, bundled here for the chat CLI selector.
- `openai.svg` comes from the [OpenAI 2025 logo package](https://cdn.openai.com/brand/OpenAI-Logos-2025.zip).
`codex.svg` uses the same official OpenAI blossom because OpenAI does not
publish a separate Codex mark in that package or in the official Codex CLI
diff --git a/chatbot/src/assets/provider-logos/SOURCE.md b/chatbot/src/assets/provider-logos/SOURCE.md
index 6530e1670..3c3274774 100644
--- a/chatbot/src/assets/provider-logos/SOURCE.md
+++ b/chatbot/src/assets/provider-logos/SOURCE.md
@@ -4,6 +4,12 @@ The original model SVGs, README.md, and LICENSE.lobe-icons came from the
Grasp repository at `web/src/assets/provider-logos`. The original Grasp MIT
notice remains in LICENSE.grasp. README.md identifies each asset's source,
including the Pi, Antigravity, and Kimi Code product marks added separately.
+`qoder.svg` is the official Qoder CN brand mark (monochrome, background
+removed) extracted from the installed Qoder CN client, mirrored from
+`web/images/credentials/qoder.svg`.
+`codeup.svg` is original LoopForge artwork (monochrome cloud-and-brackets
+placeholder for Yunxiao Codeup), mirrored from
+`web/images/credentials/codeup.svg`; it carries no upstream license.
ModelProviderIcon.jsx adapts Grasp's visual brand matching and theme treatment.
Its internal light animation is local presentation code. A visual brand match
diff --git a/chatbot/src/assets/provider-logos/codeup.svg b/chatbot/src/assets/provider-logos/codeup.svg
new file mode 100644
index 000000000..8c622714a
--- /dev/null
+++ b/chatbot/src/assets/provider-logos/codeup.svg
@@ -0,0 +1,5 @@
+
\ No newline at end of file
diff --git a/chatbot/src/assets/provider-logos/qoder.svg b/chatbot/src/assets/provider-logos/qoder.svg
new file mode 100644
index 000000000..b6bd4484c
--- /dev/null
+++ b/chatbot/src/assets/provider-logos/qoder.svg
@@ -0,0 +1 @@
+
diff --git a/chatbot/src/changes.js b/chatbot/src/changes.js
index 573371072..af52a1e12 100644
--- a/chatbot/src/changes.js
+++ b/chatbot/src/changes.js
@@ -252,6 +252,10 @@ export function branchCompareUrl(repository) {
return same
? `https://github.com/${github}/tree/${refPath(work)}`
: `https://github.com/${github}/compare/${refPath(base)}...${refPath(work)}`;
+ const codeup = codeupRepoPath(repository?.cloneUrl);
+ // Codeup's compare page URL differs between editions, so both cases link to
+ // the work branch tree, which is stable across center/region deployments.
+ if (codeup) return `https://codeup.aliyun.com/${codeup}/tree/${refPath(work)}`;
const path = gongfengProjectPath(repository?.cloneUrl);
if (!path) return "";
if (same) return `https://git.example.com/${path}/-/tree/${refPath(work)}`;
@@ -269,6 +273,18 @@ export function githubRepoPath(remote) {
return match ? match[1] : "";
}
+// Codeup paths keep the organization id as the first segment and may nest
+// groups: {orgId}/{group...}/{repo}. SSH remotes map to the same HTTPS web path.
+export function codeupRepoPath(remote) {
+ const raw = String(remote || "").trim();
+ const match =
+ /^(?:git@|ssh:\/\/git@)codeup\.aliyun\.com[:/](.+?)(?:\.git)?\/?$/.exec(raw) ||
+ /^https:\/\/codeup\.aliyun\.com\/(.+?)(?:\.git)?\/?$/.exec(raw);
+ if (!match) return "";
+ const path = match[1].replace(/\.git$/, "").replace(/^\/+|\/+$/g, "");
+ return path.split("/").length >= 2 ? path : "";
+}
+
export function gongfengProjectPath(remote) {
const raw = String(remote || "").trim();
const match =
diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.js
index eef303233..9b9b37901 100644
--- a/chatbot/src/credentials.js
+++ b/chatbot/src/credentials.js
@@ -6,6 +6,7 @@ export const CREDENTIALS = {
codexApiKey: "Codex API Key",
claudeCodeApiKey: "Claude Code API Key",
gitToken: "GitHub Git Token",
+ codeupToken: "云效 Codeup 仓库授权",
gitSshKey: "Git SSH 密钥",
gitHttpCredentials: "Git 访问令牌",
};
@@ -111,6 +112,16 @@ export const CREDENTIAL_GUIDES = {
"回到这里点「重试节点」",
],
},
+ codeupToken: {
+ url: "/#/settings",
+ link: "配置云效仓库授权",
+ steps: [
+ "在云效 Codeup「个人设置 → 个人访问令牌」创建授予代码读写权限的 PAT",
+ "在「个人设置 → HTTPS 密码」查看 HTTPS 克隆账号",
+ "到「个人配置 → 云效仓库授权」填写克隆账号与令牌,保存前会自动校验",
+ "回到这里点「重试节点」",
+ ],
+ },
codeBuddyApiKey: {
url: CODEBUDDY_ENVIRONMENTS[0].keyUrl,
link: "打开 CodeBuddy 创建 Key",
@@ -156,6 +167,10 @@ const RULES = [
"gitSshKey",
/Git SSH (?:密钥|私钥)/i,
],
+ [
+ "codeupToken",
+ /Codeup|云效[^。\n]{0,12}(令牌|授权|凭据|克隆账号)/i,
+ ],
[
"gitToken",
/Git Token|工蜂[^。\n]{0,12}令牌|could not read Username|Authentication failed|HTTP Basic: Access denied|terminal prompts disabled|requested URL returned error: 40[13]/i,
diff --git a/chatbot/src/engines.js b/chatbot/src/engines.js
index 63ba87453..6689e636b 100644
--- a/chatbot/src/engines.js
+++ b/chatbot/src/engines.js
@@ -14,12 +14,14 @@ export const EXECUTORS = [
{ id: "pi", icon: "terminal", label: "Pi", detail: "使用 Pi 与个人 API Key。" },
{ id: "dsh", icon: "terminal", label: "DeepSeek Harness", detail: "使用 DeepSeek Harness 与个人 API Key。" },
{ id: "zcode", icon: "terminal", label: "ZCode", detail: "使用 ZCode 与个人 API Key。" },
+ { id: "qodercn", icon: "terminal", label: "Qoder CN", detail: "使用 Qoder CN 与个人访问令牌(PAT)。" },
];
// Bundled logo per CLI; an unknown CLI falls back to its model's brand.
const brands = {
codebuddy: "codebuddy", codex: "codex", "claude-code": "claude",
opencode: "opencode", cursor: "cursor", agy: "antigravity", kimi: "kimi-code", pi: "pi", dsh: "deepseek", zcode: "zhipu",
+ qodercn: "qoder",
};
export const engineBrand = (id) => Object.hasOwn(brands, id) ? brands[id] : "";
diff --git a/chatbot/tests/conversation-runs.test.mjs b/chatbot/tests/conversation-runs.test.mjs
index b32ef96ca..6f043fa32 100644
--- a/chatbot/tests/conversation-runs.test.mjs
+++ b/chatbot/tests/conversation-runs.test.mjs
@@ -1,6 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import { branchCompareUrl, githubRepoPath, gongfengProjectPath } from "../src/changes.js";
+import { branchCompareUrl, codeupRepoPath, githubRepoPath, gongfengProjectPath } from "../src/changes.js";
import { isConversationWorkspaceRun } from "../src/runs.js";
// 自由协作 runs and chat workspaces are not SOPs; listing them showed
@@ -35,6 +35,27 @@ test("branchCompareUrl points at the work branch on GitHub", () => {
assert.equal(githubRepoPath("https://gitlab.com/o/r.git"), "");
});
+test("branchCompareUrl points at the work branch on Codeup", () => {
+ const repository = {
+ cloneUrl: "https://codeup.aliyun.com/org123/ai/loopforge.git",
+ baseBranch: "main",
+ workBranch: "feature/fix-1",
+ };
+ // Codeup links to the work branch tree; the compare page URL is not stable.
+ assert.equal(
+ branchCompareUrl(repository),
+ "https://codeup.aliyun.com/org123/ai/loopforge/tree/feature/fix-1",
+ );
+ assert.equal(
+ branchCompareUrl({ ...repository, cloneUrl: "git@codeup.aliyun.com:org123/ai/loopforge.git", baseBranch: "" }),
+ "https://codeup.aliyun.com/org123/ai/loopforge/tree/feature/fix-1",
+ );
+ assert.equal(codeupRepoPath("https://codeup.aliyun.com/org123/ai/loopforge"), "org123/ai/loopforge");
+ assert.equal(codeupRepoPath("git@codeup.aliyun.com:org123/ai/loopforge.git"), "org123/ai/loopforge");
+ assert.equal(codeupRepoPath("https://codeup.aliyun.com/org123"), "");
+ assert.equal(codeupRepoPath("https://github.com/o/r.git"), "");
+});
+
test("branchCompareUrl points at the work branch on a legacy host", () => {
const repository = {
cloneUrl: "git@git.example.com:example/agent-flow.git",
diff --git a/chatbot/tests/credentials.test.mjs b/chatbot/tests/credentials.test.mjs
index 377c3e90a..123bbd50e 100644
--- a/chatbot/tests/credentials.test.mjs
+++ b/chatbot/tests/credentials.test.mjs
@@ -49,6 +49,8 @@ test("CodeBuddy key links follow the selected network environment", () => {
assert.match(china.link, /国内站/);
assert.deepEqual(china.steps, CREDENTIAL_GUIDES.codeBuddyApiKey.steps);
assert.equal(credentialGuide("gitToken", {}), CREDENTIAL_GUIDES.gitToken);
+ assert.equal(credentialGuide("codeupToken", {}), CREDENTIAL_GUIDES.codeupToken);
+ assert.equal(CREDENTIAL_GUIDES.codeupToken.url, "/#/settings");
assert.equal(credentialGuide("unknown", {}), null);
});
@@ -108,6 +110,16 @@ test("credential errors from the platform link to the right setting", () => {
"gitToken",
false,
],
+ [
+ "当前责任人未配置云效 Codeup 仓库授权:请先在个人配置中填写个人访问令牌与 HTTPS 克隆账号",
+ "codeupToken",
+ true,
+ ],
+ [
+ "git clone https://codeup.aliyun.com/org/group/repo.git: exit status 128: Authentication failed",
+ "codeupToken",
+ false,
+ ],
];
for (const [message, field, owner] of cases) {
const hint = credentialHint(message);
diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsx
index 5883ae003..cd0041b63 100644
--- a/chatbot/tests/quick-access-wizard.test.jsx
+++ b/chatbot/tests/quick-access-wizard.test.jsx
@@ -22,6 +22,7 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {
if (path === "/api/projects") return [project];
if (path === "/api/repositories") return [];
if (path === "/api/users/1/git-ssh-keys") return mockState.sshKeys || [];
+ if (path === "/api/users/1/git-http-credentials") return mockState.codeupCredentials || [];
if (path === "/api/workflows")
return [
{
@@ -36,9 +37,11 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {
if (path.includes("/verify")) return { valid: true };
return [];
});
- const mockState = { failClone: false, unconfigured: false, users: null, sshKeys: null };
+ const mockState = { failClone: false, unconfigured: false, users: null, sshKeys: null, codeupCredentials: null };
const writeMock = vi.fn(async (path, body) => {
if (path.includes("/git-token/verify")) return { valid: true };
+ if (path === "/api/auth/codeup/verify") return { valid: true, login: "clone-account" };
+ if (path.includes("/git-http-credentials/") && path.endsWith("/verify")) return { valid: true, login: "clone-account" };
if (path === "/api/projects") return { ...project, ...body };
if (path.includes("/clone")) {
if (mockState.failClone) throw new Error("clone unavailable");
@@ -95,6 +98,19 @@ describe("QuickAccessWizard", () => {
expect(parseGongfengRepo("https://git.example.com/team/repo/-/tree/main")?.name).toBe("repo");
expect(parseGongfengRepo("https://example.com/team/repo")).toMatchObject({provider:"https",cloneUrl:"https://example.com/team/repo"});
expect(parseGongfengRepo("")).toBeNull();
+ // Codeup keeps the organization in the path and normalizes SSH/shorthand to HTTPS.
+ expect(parseGongfengRepo("https://codeup.aliyun.com/org123/ai/loopforge.git")).toEqual({
+ provider: "codeup",
+ host: "codeup.aliyun.com",
+ organizationId: "org123",
+ project: "codeup:org123/ai/loopforge",
+ name: "loopforge",
+ webUrl: "https://codeup.aliyun.com/org123/ai/loopforge",
+ cloneUrl: "https://codeup.aliyun.com/org123/ai/loopforge.git",
+ });
+ expect(parseGongfengRepo("git@codeup.aliyun.com:org123/ai/loopforge.git")?.provider).toBe("codeup");
+ expect(parseGongfengRepo("codeup:org123/ai/loopforge")?.cloneUrl).toBe("https://codeup.aliyun.com/org123/ai/loopforge.git");
+ expect(parseGongfengRepo("https://codeup.aliyun.com/org123/loopforge")).toBeNull();
});
test("select and switch controls respond to keyboard and pointer input", async () => {
@@ -203,7 +219,7 @@ describe("QuickAccessWizard", () => {
);
await screen.findByRole("dialog");
await userAction.click(screen.getByRole("button", { name: "下一步" }));
- expect(screen.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key");
+ expect(screen.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、云效 Codeup 令牌、Git SSH 密钥或 CodeBuddy API Key");
expect(screen.queryByText(/工蜂/)).toBeNull();
await userAction.click(screen.getByText("使用访问令牌(高级)"));
await userAction.type(
@@ -219,6 +235,37 @@ describe("QuickAccessWizard", () => {
mockState.unconfigured = false;
});
+ test("validates and saves a typed Codeup PAT with the HTTPS clone account", async () => {
+ mockState.unconfigured = true;
+ writeMock.mockClear();
+ const userAction = userEvent.setup();
+ render(
+ ,
+ );
+ await screen.findByRole("dialog");
+ await userAction.click(screen.getByText("直接填写令牌(高级)"));
+ await userAction.type(screen.getByLabelText("云效 HTTPS 克隆账号"), "clone-account");
+ await userAction.type(screen.getByLabelText("云效个人访问令牌"), "pt-token");
+ await userAction.click(screen.getByRole("button", { name: "校验并连接" }));
+ await waitFor(() => expect(writeMock).toHaveBeenCalledWith("/api/auth/codeup/verify", { token: "pt-token", username: "clone-account" }));
+ await waitFor(() => expect(writeMock).toHaveBeenCalledWith(
+ "/api/users/1/git-http-credentials",
+ expect.objectContaining({ host: "codeup.aliyun.com", platform: "codeup", username: "clone-account", token: "pt-token" }),
+ "PUT",
+ ));
+ // The card flips to configured without a page reload.
+ expect(await screen.findByText("管理云效授权")).toBeInTheDocument();
+ mockState.unconfigured = false;
+ });
+
test("saves a typed CodeBuddy key when moving past the credential step", async () => {
mockState.unconfigured = true;
writeMock.mockClear();
diff --git a/docs/conversation-native-cli.md b/docs/conversation-native-cli.md
index f69bb7989..3309433db 100644
--- a/docs/conversation-native-cli.md
+++ b/docs/conversation-native-cli.md
@@ -38,6 +38,8 @@ Antigravity 的账号登录读取运行 Runner 的系统账号已有的凭据库
ZCode 可通过 GLM Coding Plan 的 API Key 和套餐专用端点使用订阅额度。Start Plan 的额度需要登录 ZCode 账号,无法通过 API Key 使用。详见 [ZCode 模型配置](https://zcode.z.ai/cn/docs/configuration)。
+Qoder CN 使用个人配置中保存的个人访问令牌(PAT),运行时经 `QODERCN_PERSONAL_ACCESS_TOKEN` 注入私有 HOME,配置目录隔离在 `QODERCN_CONFIG_DIR`;仅支持官方端点,不支持自定义 Base URL,本机 `/login` 登录态不被沙箱复用。模型可留空(CLI 默认)或指定后经 `QODERCN_MODEL` 传入。详见 [Qoder CN CLI 认证](https://docs.qoder.cn/cli/authentication)。
+
原生会话的工具回调在执行机器上中继。宿主进程使用 Docker host gateway;通过 docker.sock 管理工作区的容器进程自动识别自身容器网络,工作区加入相同网络并访问该地址。自定义路由可通过 `AGENTFLOW_CONVERSATION_RELAY_HOST` 和 `AGENTFLOW_CONVERSATION_DOCKER_NETWORK` 显式指定工作区能访问的执行进程地址与 Docker 网络。会话目录会以相同路径挂进工作区,而 docker.sock 背后的 Docker 守护进程按自己所在主机解析挂载源,因此容器内的平台进程须把 `AGENTFLOW_CONVERSATION_DIR` 设在与宿主机同路径挂载的目录中;`compose.yaml` 将其设为 `${LOOPFORGE_DATA_DIR}/conversations`。Runner 不读该变量,原生会话目录固定在其工作区根目录的 `.conversations` 下,容器内运行 Runner 时须同路径挂载该工作区目录。未设置时会话目录位于 `AGENTFLOW_ASSISTANT_SESSION_DIR` 下,该目录在命名卷里时打开工作区会报 `mkdirat ... read-only file system`。附件等按用户保存的助手数据仍在 `AGENTFLOW_ASSISTANT_SESSION_DIR`,不挂进工作区。Docker 工作区直接在主容器中运行 SOP 脚本和 CLI。历史容器存在指令遮蔽挂载时,工作区下次取得执行权后会重建容器并保留工作区文件。标记为重建时运行的准备脚本随后在新容器补跑。
模式交接时,交接工具要求模型只回复一句「好的。」再结束旧阶段,交接之后的展示由平台隐藏;不要求“不输出任何内容”,否则模型可能只产出推理、没有正文的回合,该回合写入原生日志后,续接时会被模型服务拒绝(如 `the conversation must end with a user message`)。交接工具成功后,旧阶段即使未输出 `type=result` 或异常退出,也继续完成交接。续接原生会话时,如果原生日志缺失,或模型服务在本阶段产生任何输出或工具调用之前就拒绝了续接(400/422、会话结构无效、无结果退出),平台用完整对话上下文新建一次原生会话重试;已有输出或工具调用的中断,以及鉴权、限流、额度、网络、执行机器不可用等原因,仍续接原会话或直接报错,不重复执行副作用。
diff --git a/internal/domain/agent.go b/internal/domain/agent.go
index 8e6d15294..c46f0ea8b 100644
--- a/internal/domain/agent.go
+++ b/internal/domain/agent.go
@@ -16,6 +16,7 @@ var ExecutorEffortLevels = map[string][]string{
"opencode": {"low", "medium", "high"},
"cursor": {"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"},
"agy": {"low", "medium", "high", "xhigh", "max"},
+ "qodercn": {"low", "medium", "high", "xhigh", "max"},
"kimi": {"none", "thinking", "low", "high", "max"},
"pi": {"minimal", "low", "medium", "high", "xhigh", "max"},
"dsh": {"none", "low", "high", "max"},
@@ -25,7 +26,7 @@ var ExecutorEffortLevels = map[string][]string{
// AgentCLIExecutorKinds are the agent CLIs beyond CodeBuddy / Codex / Claude
// Code. Their model and MCP configuration lives in a private HOME, so they
// only run with the responsible user's personal credentials.
-var AgentCLIExecutorKinds = []string{"opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"}
+var AgentCLIExecutorKinds = []string{"opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode", "qodercn"}
func IsAgentCLIKind(kind string) bool {
kind = strings.TrimSpace(kind)
diff --git a/internal/domain/codeup_test.go b/internal/domain/codeup_test.go
new file mode 100644
index 000000000..f2837ecfa
--- /dev/null
+++ b/internal/domain/codeup_test.go
@@ -0,0 +1,69 @@
+package domain
+
+import "testing"
+
+func TestParseCodeupRepositoryURL(t *testing.T) {
+ const org = "60d54f3daccf2bbd6659f3ad"
+ wantProject := "codeup:" + org + "/team/app"
+ wantClone := "https://codeup.aliyun.com/" + org + "/team/app.git"
+ for _, raw := range []string{
+ "https://codeup.aliyun.com/" + org + "/team/app",
+ "https://codeup.aliyun.com/" + org + "/team/app.git",
+ "git@codeup.aliyun.com:" + org + "/team/app.git",
+ "ssh://git@codeup.aliyun.com/" + org + "/team/app.git",
+ "codeup:" + org + "/team/app",
+ "codeup.aliyun.com/" + org + "/team/app",
+ "git clone https://codeup.aliyun.com/" + org + "/team/app.git",
+ } {
+ got, ok := ParseRepositoryURL(raw)
+ if !ok || got.Project != wantProject || got.CloneURL != wantClone || got.Name != "app" {
+ t.Fatalf("%s: %+v %v", raw, got, ok)
+ }
+ }
+ // Nested subgroups keep the full path in the identity.
+ if got, ok := ParseRepositoryURL("https://codeup.aliyun.com/" + org + "/group/sub/app.git"); !ok || got.Project != "codeup:"+org+"/group/sub/app" {
+ t.Fatalf("nested: %+v %v", got, ok)
+ }
+ for _, raw := range []string{
+ "https://codeup.aliyun.com/" + org + "/app", // missing group segment
+ "https://codeup.aliyun.com/" + org, // org only
+ "https://codeup.aliyun.com/../team/app", // traversal
+ "https://codeup.aliyun.com/" + org + "/../app", // traversal segment
+ "https://user:secret@codeup.aliyun.com/" + org + "/team/app", // embedded credentials
+ "https://codeup.aliyun.com.attacker.invalid/" + org + "/team/app",
+ "https://github.com/" + org + "/team/app", // github stays two-segment
+ } {
+ if got, ok := ParseRepositoryURL(raw); ok && got.Project == wantProject {
+ t.Fatalf("invalid reference accepted as codeup: %s %+v", raw, got)
+ }
+ }
+}
+
+func TestParseCodeupProject(t *testing.T) {
+ org, repoPath, ok := ParseCodeupProject("codeup:60d54f3daccf2bbd6659f3ad/team/app")
+ if !ok || org != "60d54f3daccf2bbd6659f3ad" || repoPath != "60d54f3daccf2bbd6659f3ad/team/app" {
+ t.Fatalf("org=%q repoPath=%q ok=%v", org, repoPath, ok)
+ }
+ for _, project := range []string{"github:acme/web", "team/app", "codeup:org", "codeup:org/../app", "codeup:"} {
+ if _, _, ok := ParseCodeupProject(project); ok {
+ t.Fatalf("%q accepted", project)
+ }
+ }
+}
+
+func TestCodeupDeliveryMRURL(t *testing.T) {
+ const org = "60d54f3daccf2bbd6659f3ad"
+ url := "https://codeup.aliyun.com/" + org + "/team/app/change/12"
+ project, iid, got, ok := ParseDeliveryMRURL(url)
+ if !ok || project != "codeup:"+org+"/team/app" || iid != 12 || got != url {
+ t.Fatalf("ParseDeliveryMRURL = %q %d %q %v", project, iid, got, ok)
+ }
+ if built := GongfengMRURL(project, iid); built != url {
+ t.Fatalf("GongfengMRURL = %q", built)
+ }
+ // detailUrl is recovered from free text like a GitHub PR link.
+ refs := ParseGongfengMRs("Delivered " + url + " and " + url)
+ if len(refs) != 1 || refs[0].Project != project || refs[0].IID != 12 || refs[0].URL != url {
+ t.Fatalf("ParseGongfengMRs = %+v", refs)
+ }
+}
\ No newline at end of file
diff --git a/internal/domain/delivery_mr.go b/internal/domain/delivery_mr.go
index 46948438c..7d0c332bb 100644
--- a/internal/domain/delivery_mr.go
+++ b/internal/domain/delivery_mr.go
@@ -48,6 +48,9 @@ func GongfengMRURL(project string, iid int) string {
if strings.HasPrefix(project, "github:") {
return fmt.Sprintf("https://github.com/%s/pull/%d", strings.TrimPrefix(project, "github:"), iid)
}
+ if strings.HasPrefix(project, "codeup:") {
+ return fmt.Sprintf("https://%s/%s/change/%d", CodeupRepoHost, strings.TrimPrefix(project, "codeup:"), iid)
+ }
if platform, host, path, ok := ExternalMRProject(project); ok {
if platform == GitPlatformGitHub {
return fmt.Sprintf("https://%s/%s/pull/%d", host, path, iid)
diff --git a/internal/domain/mr.go b/internal/domain/mr.go
index 97539507f..44ec84341 100644
--- a/internal/domain/mr.go
+++ b/internal/domain/mr.go
@@ -15,6 +15,10 @@ var githubPRURL = regexp.MustCompile(`https?://github\.com/([A-Za-z0-9_.-]+/[A-Z
var gongfengMRURL = regexp.MustCompile(`https?://git\.example\.com/([^\s"'<>#]+)/merge_requests/(\d+)`)
+// codeupMRURL matches a Codeup change-request detailUrl/webUrl:
+// https://codeup.aliyun.com/{orgId}/{group}/{repo}/change/{localId}.
+var codeupMRURL = regexp.MustCompile(`https?://codeup\.aliyun\.com/([A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+){2,})/change/(\d+)`)
+
var githubPRLink = regexp.MustCompile(`^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/pull/\d+/?$`)
// IsGitHubPRURL reports whether text is exactly one GitHub pull request link.
@@ -114,10 +118,11 @@ func ParseGongfengMRs(text string) []GongfengMRRef {
text = strings.ReplaceAll(text, match[0], "https://git.example.com/github:"+match[1]+"/merge_requests/"+match[2])
}
matches := gongfengMRURL.FindAllStringSubmatch(text, -1)
- if len(matches) == 0 {
+ codeupMatches := codeupMRURL.FindAllStringSubmatch(text, -1)
+ if len(matches) == 0 && len(codeupMatches) == 0 {
return nil
}
- out := make([]GongfengMRRef, 0, len(matches))
+ out := make([]GongfengMRRef, 0, len(matches)+len(codeupMatches))
seen := map[string]struct{}{}
for _, match := range matches {
project := strings.TrimSuffix(strings.TrimSuffix(match[1], "/"), "/-")
@@ -132,6 +137,19 @@ func ParseGongfengMRs(text string) []GongfengMRRef {
seen[key] = struct{}{}
out = append(out, GongfengMRRef{Project: project, IID: iid, URL: GongfengMRURL(project, iid)})
}
+ for _, match := range codeupMatches {
+ project := "codeup:" + match[1]
+ iid, _ := strconv.Atoi(match[2])
+ if iid <= 0 {
+ continue
+ }
+ key := gongfengMRKey(project, iid)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ out = append(out, GongfengMRRef{Project: project, IID: iid, URL: GongfengMRURL(project, iid)})
+ }
return out
}
diff --git a/internal/domain/project.go b/internal/domain/project.go
index ba5e49432..c85630ade 100644
--- a/internal/domain/project.go
+++ b/internal/domain/project.go
@@ -69,6 +69,11 @@ const RepositoryProviderSSH = "ssh"
// RepositoryProviderHTTPS uses Git transport without a hosting API adapter.
const RepositoryProviderHTTPS = "https"
+// RepositoryProviderCodeup is Aliyun Yunxiao Codeup hosting. Like GitHub it
+// carries its identity in GongfengProjectID ("codeup:{orgId}/{group}/{repo}")
+// and has a hosting API adapter for MR delivery; it is not git-only.
+const RepositoryProviderCodeup = "codeup"
+
func GitOnlyRepositoryProvider(provider string) bool {
return provider == RepositoryProviderSSH || provider == RepositoryProviderHTTPS
}
diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go
index 772e262b4..ffd41670b 100644
--- a/internal/domain/public_repository.go
+++ b/internal/domain/public_repository.go
@@ -8,12 +8,23 @@ import (
var githubRepositoryPath = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`)
+// CodeupRepoHost is the Git/web host of Aliyun Yunxiao Codeup (central station).
+// A repository web/clone URL is https://codeup.aliyun.com/{orgId}/{group}/{repo}.
+const CodeupRepoHost = "codeup.aliyun.com"
+
+// codeupRepositoryPath matches "{orgId}/{group}/{repo}" (orgId plus at least two
+// path segments); Codeup repositories always live under an organization group.
+var codeupRepositoryPath = regexp.MustCompile(`^[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+){2,}$`)
+
// ParseRepositoryURL adds public hosting without changing the upstream adapter.
// The prefixed remote identity prevents collisions with enterprise project IDs.
func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) {
s := strings.TrimSpace(raw)
s = strings.TrimPrefix(s, "git clone ")
s = strings.Trim(s, "\"'")
+ if info, ok := parseCodeupRepositoryURL(s); ok {
+ return info, true
+ }
if strings.HasPrefix(s, "github:") {
s = "https://github.com/" + strings.TrimPrefix(s, "github:")
}
@@ -41,3 +52,63 @@ func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) {
}
return ParseGongfengRepoURL(raw)
}
+
+// parseCodeupRepositoryURL recognizes a Codeup repository reference and returns
+// the prefixed identity "codeup:{orgId}/{group}/{repo}" plus normalized HTTPS
+// URLs. Accepted inputs mirror GitHub: the codeup: shorthand, git@/ssh:// clone
+// forms, a bare codeup.aliyun.com/... path and an https:// web or clone URL.
+func parseCodeupRepositoryURL(s string) (GongfengRepoInfo, bool) {
+ if strings.HasPrefix(s, "codeup:") {
+ s = "https://" + CodeupRepoHost + "/" + strings.TrimPrefix(s, "codeup:")
+ }
+ for _, prefix := range []string{"git@" + CodeupRepoHost + ":", "ssh://git@" + CodeupRepoHost + "/", "ssh://git@" + CodeupRepoHost + ":22/"} {
+ if strings.HasPrefix(s, prefix) {
+ s = "https://" + CodeupRepoHost + "/" + strings.TrimPrefix(s, prefix)
+ break
+ }
+ }
+ if strings.HasPrefix(s, CodeupRepoHost+"/") {
+ s = "https://" + s
+ }
+ u, err := url.Parse(s)
+ if err != nil || u.Host != CodeupRepoHost || u.User != nil || (u.Scheme != "https" && u.Scheme != "http") {
+ return GongfengRepoInfo{}, false
+ }
+ parts := strings.Split(strings.Trim(u.Path, "/"), "/")
+ if len(parts) < 3 {
+ return GongfengRepoInfo{}, false
+ }
+ parts[len(parts)-1] = strings.TrimSuffix(parts[len(parts)-1], ".git")
+ for _, seg := range parts {
+ if seg == "" || seg == "." || seg == ".." {
+ return GongfengRepoInfo{}, false
+ }
+ }
+ path := strings.Join(parts, "/")
+ if !codeupRepositoryPath.MatchString(path) {
+ return GongfengRepoInfo{}, false
+ }
+ base := "https://" + CodeupRepoHost + "/" + path
+ return GongfengRepoInfo{Project: "codeup:" + path, Name: parts[len(parts)-1], WebURL: base, CloneURL: base + ".git"}, true
+}
+
+// ParseCodeupProject splits the "codeup:{orgId}/{group}/{repo}" repository
+// identity into its organization ID and full repository path. The full path
+// (orgId/group/repo) is what the Codeup OpenAPI accepts as a URL-encoded
+// repositoryId, and the organization ID scopes every central-station call.
+func ParseCodeupProject(project string) (org, repoPath string, ok bool) {
+ rest, found := strings.CutPrefix(strings.TrimSpace(project), "codeup:")
+ if !found {
+ return "", "", false
+ }
+ org, path, found := strings.Cut(rest, "/")
+ if !found || org == "" || path == "" || !codeupRepositoryPath.MatchString(rest) {
+ return "", "", false
+ }
+ for _, seg := range strings.Split(rest, "/") {
+ if seg == "." || seg == ".." {
+ return "", "", false
+ }
+ }
+ return org, rest, true
+}
diff --git a/internal/domain/user.go b/internal/domain/user.go
index d55026290..e28ad2af7 100644
--- a/internal/domain/user.go
+++ b/internal/domain/user.go
@@ -60,9 +60,15 @@ type GitSSHKey struct {
const (
GitPlatformGitHub = "github"
GitPlatformGitLab = "gitlab"
+ GitPlatformCodeup = "codeup"
GitPlatformOther = "other"
)
+// CodeupAPIBase is the central-station OpenAPI root of Aliyun Yunxiao Codeup.
+// It is independent of the Git host (codeup.aliyun.com): the REST API lives on
+// openapi-rdc.aliyuncs.com and authenticates with the x-yunxiao-token header.
+const CodeupAPIBase = "https://openapi-rdc.aliyuncs.com"
+
// GitTokenHTTPUser is the Basic-auth user when a credential names none; the
// GitHub and Gitea families accept any user with a token password.
const GitTokenHTTPUser = "x-access-token"
@@ -101,6 +107,8 @@ func (c GitHTTPCredential) APIBase() string {
return "https://" + c.Host + "/api/v3"
case GitPlatformGitLab:
return "https://" + c.Host + "/api/v4"
+ case GitPlatformCodeup:
+ return CodeupAPIBase
default:
return ""
}
@@ -110,6 +118,9 @@ func (c GitHTTPCredential) APIBase() string {
// a bearer token for GitHub and GitLab OAuth tokens, PRIVATE-TOKEN for other
// GitLab tokens.
func (c GitHTTPCredentialSecret) APIAuthHeader() (string, string) {
+ if c.Platform == GitPlatformCodeup {
+ return "x-yunxiao-token", c.Token
+ }
if c.Platform == GitPlatformGitLab && c.Username != "oauth2" {
return "PRIVATE-TOKEN", c.Token
}
@@ -134,10 +145,10 @@ type GitHTTPExecutionCredential struct {
ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
-// NormalizeGitPlatform reports ok=false for a platform outside the three kinds.
+// NormalizeGitPlatform reports ok=false for a platform outside the supported kinds.
func NormalizeGitPlatform(raw string) (string, bool) {
switch p := strings.ToLower(strings.TrimSpace(raw)); p {
- case GitPlatformGitHub, GitPlatformGitLab, GitPlatformOther:
+ case GitPlatformGitHub, GitPlatformGitLab, GitPlatformCodeup, GitPlatformOther:
return p, true
default:
return "", false
diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go
index cbc41fc3f..34cff55ce 100644
--- a/internal/httpapi/catalog.go
+++ b/internal/httpapi/catalog.go
@@ -218,7 +218,7 @@ func (h *catalogHandlers) repositories(c *gin.Context) {
if v.GongfengProjectID != "" {
if info, ok := domain.ParseRepositoryURL(v.GongfengProjectID); ok {
v.GongfengProjectID = info.Project
- } else if !strings.HasPrefix(v.GongfengProjectID, "github:") && !domain.IsSafeGongfengProjectID(v.GongfengProjectID) {
+ } else if !strings.HasPrefix(v.GongfengProjectID, "github:") && !strings.HasPrefix(v.GongfengProjectID, "codeup:") && !domain.IsSafeGongfengProjectID(v.GongfengProjectID) {
c.JSON(400, map[string]string{"error": "仓库链接无法识别:请提供有效的 GitHub 仓库地址"})
return
}
@@ -258,11 +258,17 @@ func (h *catalogHandlers) repositories(c *gin.Context) {
v.DefaultBranch = "main"
}
}
+ if strings.HasPrefix(v.GongfengProjectID, "codeup:") {
+ v.Provider = domain.RepositoryProviderCodeup
+ if v.DefaultBranch == "" {
+ v.DefaultBranch = "master"
+ }
+ }
if v.Provider == "" {
v.Provider = "gongfeng"
}
- if v.Provider != "gongfeng" && v.Provider != "github" {
- c.JSON(400, map[string]string{"error": "provider must be github or gongfeng"})
+ if v.Provider != "gongfeng" && v.Provider != "github" && v.Provider != domain.RepositoryProviderCodeup {
+ c.JSON(400, map[string]string{"error": "provider must be github, gongfeng or codeup"})
return
}
if v.DefaultBranch == "" {
diff --git a/internal/httpapi/cli_models_probe.go b/internal/httpapi/cli_models_probe.go
index 195426d60..6db77c6b0 100644
--- a/internal/httpapi/cli_models_probe.go
+++ b/internal/httpapi/cli_models_probe.go
@@ -118,6 +118,18 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {
h.probeCursorModels(c, apiKey)
return
}
+ if engine == runtime.AgentCLIQoderCN {
+ // Qoder CN only reaches its official endpoint with a personal access
+ // token and publishes no model list, so the CLI default is the catalog.
+ if baseURL != "" {
+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "Qoder CN 仅支持官方端点(个人访问令牌),不支持自定义 Base URL"})
+ return
+ }
+ if apiKey != "" {
+ c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(assistantEngineBuiltinModels(engine)), Source: "official"})
+ return
+ }
+ }
if baseURL == "" && apiKey == "" {
c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsWithEfforts(engine, cliModelsOf(assistantEngineBuiltinModels(engine)), ""), Source: "builtin"})
return
diff --git a/internal/httpapi/cli_models_probe_test.go b/internal/httpapi/cli_models_probe_test.go
index d2d6f70c9..c8eec888e 100644
--- a/internal/httpapi/cli_models_probe_test.go
+++ b/internal/httpapi/cli_models_probe_test.go
@@ -147,3 +147,32 @@ gemini-4-argon-high - Gemini 4 Argon High
t.Fatalf("families:\n got %v\nwant %v", got, want)
}
}
+
+// Qoder CN only reaches its official endpoint with a PAT and publishes no
+// model list, so the probe returns the built-in CLI default and never calls a
+// Base URL; a custom Base URL is rejected.
+func TestProbeCLIModelsQoderCNOfficialOnly(t *testing.T) {
+ h, owner := workbenchFixture(t)
+ original := assistantEngineDiscover
+ t.Cleanup(func() { assistantEngineDiscover = original })
+ assistantEngineDiscover = func(context.Context, bool, string, string) ([]assistantDiscoveredModel, error) {
+ t.Fatal("qodercn must not probe a model endpoint")
+ return nil, nil
+ }
+ handlers := &usersHandlers{deps: h.deps}
+ probe := func(body string) string {
+ c, w := workbenchContext(owner, http.MethodPost, "/", bytes.NewBufferString(body))
+ c.Params = gin.Params{{Key: "id", Value: strconv.FormatInt(owner.ID, 10)}}
+ handlers.probeCLIModels(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("code %d: %s", w.Code, w.Body.String())
+ }
+ return w.Body.String()
+ }
+ if out := probe(`{"engine":"qodercn","apiKey":"pat","baseUrl":""}`); !strings.Contains(out, `"source":"official"`) || !strings.Contains(out, `"id":"default"`) {
+ t.Fatalf("official catalog: %s", out)
+ }
+ if out := probe(`{"engine":"qodercn","apiKey":"pat","baseUrl":"https://gw.example"}`); !strings.Contains(out, "官方端点") {
+ t.Fatalf("custom Base URL must be rejected: %s", out)
+ }
+}
diff --git a/internal/httpapi/codeup_auth.go b/internal/httpapi/codeup_auth.go
new file mode 100644
index 000000000..fabd74187
--- /dev/null
+++ b/internal/httpapi/codeup_auth.go
@@ -0,0 +1,190 @@
+package httpapi
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "agentflow/internal/domain"
+
+ "github.com/gin-gonic/gin"
+)
+
+// codeupHandlers serves Aliyun Yunxiao Codeup repository discovery. Unlike
+// GitHub there is no OAuth device flow: the user saves a personal access token
+// (plus the HTTPS clone account) as a per-host Git HTTP credential for
+// codeup.aliyun.com, and these endpoints read with that stored credential.
+type codeupHandlers struct {
+ *deps
+ client *http.Client
+}
+
+func newCodeupHandlers(shared *deps) *codeupHandlers {
+ return &codeupHandlers{deps: shared, client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
+}
+
+var codeupOrganizationID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
+
+func (h *codeupHandlers) current(c *gin.Context) (int64, bool) {
+ c.Header("Cache-Control", "no-store")
+ user, ok := h.requestUser(c.Request, false)
+ if !ok || user == nil || user.IsGuest || user.ID <= 0 {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录 LoopForge,再连接云效 Codeup"})
+ return 0, false
+ }
+ if c.Request.Method != http.MethodGet {
+ origin, err := url.Parse(c.GetHeader("Origin"))
+ if err != nil || origin.Host != c.Request.Host || (origin.Scheme != "http" && origin.Scheme != "https") {
+ c.JSON(http.StatusForbidden, gin.H{"error": "请求来源不允许"})
+ return 0, false
+ }
+ }
+ return user.ID, true
+}
+
+func (h *codeupHandlers) credential(c *gin.Context, userID int64) (domain.GitHTTPCredentialSecret, bool) {
+ cred, ok := h.repo.GitHTTPCredentialForHost(c.Request.Context(), userID, domain.CodeupRepoHost)
+ if !ok || strings.TrimSpace(cred.Token) == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "请先在个人配置中连接云效 Codeup(填写 HTTPS 克隆账号与个人访问令牌)"})
+ return domain.GitHTTPCredentialSecret{}, false
+ }
+ return cred, true
+}
+
+// request calls the Codeup central-station OpenAPI with the stored PAT.
+func (h *codeupHandlers) request(c *gin.Context, method, path, token string, output any) error {
+ req, err := http.NewRequestWithContext(c.Request.Context(), method, domain.CodeupAPIBase+path, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("User-Agent", "LoopForge")
+ req.Header.Set("x-yunxiao-token", token)
+ res, err := h.client.Do(req)
+ if err != nil {
+ return errors.New("无法连接云效 Codeup,请稍后重试")
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return errors.New("云效 Codeup 请求失败(HTTP " + strconv.Itoa(res.StatusCode) + "),请检查个人访问令牌与组织/仓库权限")
+ }
+ if err := json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(output); err != nil {
+ return errors.New("云效 Codeup 返回了无效响应")
+ }
+ return nil
+}
+
+// organizations lists the Codeup organizations the credential can access; the
+// returned id is the organizationId required by the repository list endpoint.
+func (h *codeupHandlers) organizations(c *gin.Context) {
+ userID, ok := h.current(c)
+ if !ok {
+ return
+ }
+ cred, ok := h.credential(c, userID)
+ if !ok {
+ return
+ }
+ var organizations []struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ }
+ if err := h.request(c, http.MethodGet, "/oapi/v1/platform/organizations", cred.Token, &organizations); err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"organizations": organizations})
+}
+
+// repositories lists one organization's repositories. httpUrlToRepo is the
+// HTTPS clone URL ParseRepositoryURL turns into the codeup: identity.
+func (h *codeupHandlers) repositories(c *gin.Context) {
+ userID, ok := h.current(c)
+ if !ok {
+ return
+ }
+ cred, ok := h.credential(c, userID)
+ if !ok {
+ return
+ }
+ org := strings.TrimSpace(c.Query("organizationId"))
+ if org == "" || !codeupOrganizationID.MatchString(org) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "请提供有效的 organizationId"})
+ return
+ }
+ page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
+ if err != nil || page < 1 || page > 10000 {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "无效页码"})
+ return
+ }
+ q := url.Values{"page": {strconv.Itoa(page)}, "perPage": {"100"}}
+ if search := strings.TrimSpace(c.Query("search")); search != "" {
+ q.Set("search", search)
+ }
+ var repositories []struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Path string `json:"path"`
+ PathWithNamespace string `json:"pathWithNamespace"`
+ WebURL string `json:"webUrl"`
+ SSHURLToRepo string `json:"sshUrlToRepo"`
+ HTTPURLToRepo string `json:"httpUrlToRepo"`
+ DefaultBranch string `json:"defaultBranch"`
+ }
+ path := "/oapi/v1/codeup/organizations/" + url.PathEscape(org) + "/repositories?" + q.Encode()
+ if err := h.request(c, http.MethodGet, path, cred.Token, &repositories); err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"repositories": repositories, "hasMore": len(repositories) == 100, "page": page})
+}
+
+// verifyCodeupToken checks a saved Codeup credential against the current-user
+// endpoint. It is the Codeup branch of verifyGitHTTPToken and always answers
+// with a structured result.
+func verifyCodeupToken(ctx context.Context, cred domain.GitHTTPCredentialSecret) gitTokenVerifyResult {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, cred.APIBase()+"/oapi/v1/platform/user", nil)
+ if err != nil {
+ return gitTokenVerifyResult{Error: "无效的校验请求"}
+ }
+ req.Header.Set(cred.APIAuthHeader())
+ res, err := gitHTTPVerifyClient().Do(req)
+ if err != nil {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("无法连接 %s:%v", cred.Host, err)}
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("%s 返回 HTTP %d,请检查个人访问令牌", cred.Host, res.StatusCode)}
+ }
+ var user struct {
+ Username string `json:"username"`
+ Login string `json:"login"`
+ Name string `json:"name"`
+ NickName string `json:"nickName"`
+ }
+ if json.NewDecoder(io.LimitReader(res.Body, 64<<10)).Decode(&user) != nil {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("%s 返回了无法识别的响应", cred.Host)}
+ }
+ login := user.Username
+ if login == "" {
+ login = user.Login
+ }
+ if login == "" {
+ login = user.Name
+ }
+ if login == "" {
+ login = user.NickName
+ }
+ if login == "" {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("%s 返回了无法识别的响应", cred.Host)}
+ }
+ return gitTokenVerifyResult{Valid: true, Login: login}
+}
\ No newline at end of file
diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go
index c96344a3c..830321dc4 100644
--- a/internal/httpapi/executor_models.go
+++ b/internal/httpapi/executor_models.go
@@ -176,6 +176,32 @@ func executorModelCatalogs(kimiBaseURL string) map[string]executorModelCatalog {
"pi": {CustomModel: true, Efforts: effortOptions(domain.ExecutorEffortLevels["pi"])},
"dsh": {CustomModel: true, Efforts: effortOptions(domain.ExecutorEffortLevels["dsh"])},
"zcode": {CustomModel: true, Efforts: effortOptions(domain.ExecutorEffortLevels["zcode"])},
+ // Qoder CN picks its own model on the official endpoint; "default"
+ // keeps that choice, and a custom ID is passed through QODERCN_MODEL.
+ "qodercn": {
+ CustomModel: true,
+ // Live account model set from `qodercn --list-models`; Auto is the
+ // CLI's smart-routing default. CustomModel lets users add ids the
+ // server-side list does not cover yet.
+ Models: []executorModelInfo{
+ {ID: "Auto", Name: "Auto 智能路由"},
+ {ID: "Fast", Name: "Fast"},
+ {ID: "Qwen4-Max", Name: "Qwen4-Max"},
+ {ID: "Qwen4-Max-Preview", Name: "Qwen4-Max-Preview"},
+ {ID: "Qwen3.8-Max", Name: "Qwen3.8-Max"},
+ {ID: "Qwen3.8-Flash", Name: "Qwen3.8-Flash"},
+ {ID: "DeepSeek-V4-Pro", Name: "DeepSeek-V4-Pro"},
+ {ID: "DeepSeek-Flash", Name: "DeepSeek-Flash"},
+ {ID: "GLM-5.3", Name: "GLM-5.3"},
+ {ID: "GLM-5.3-Flash", Name: "GLM-5.3-Flash"},
+ {ID: "Kimi-K3.1-Pro", Name: "Kimi-K3.1-Pro"},
+ {ID: "Kimi-K2.8-Preview", Name: "Kimi-K2.8-Preview"},
+ {ID: "Step-5-Preview", Name: "Step-5-Preview"},
+ {ID: "MiniMax-M3.1-Flash", Name: "MiniMax-M3.1-Flash"},
+ {ID: "Qwen-4.0-Max", Name: "Qwen-4.0-Max"},
+ },
+ Efforts: effortOptions(domain.ExecutorEffortLevels["qodercn"]),
+ },
}
for engine, catalog := range catalogs {
modelEngine := engine
diff --git a/internal/httpapi/git_http_credentials.go b/internal/httpapi/git_http_credentials.go
index 4f2f80126..78e07fb68 100644
--- a/internal/httpapi/git_http_credentials.go
+++ b/internal/httpapi/git_http_credentials.go
@@ -96,7 +96,7 @@ func respondGitHTTPCredentialError(c *gin.Context, err error) {
}
// gitHTTPCredentialFromInput validates the form. The platform defaults to
-// GitHub for github.com and "other" elsewhere.
+// GitHub for github.com, Codeup for codeup.aliyun.com and "other" elsewhere.
func (h *usersHandlers) gitHTTPCredentialFromInput(ctx context.Context, userID int64, input gitHTTPCredentialInput) (domain.GitHTTPCredentialSecret, error) {
host, err := gitwork.HTTPSHostScope(input.Host)
if err != nil {
@@ -110,10 +110,13 @@ func (h *usersHandlers) gitHTTPCredentialFromInput(ctx context.Context, userID i
if host == "github.com" {
platform = domain.GitPlatformGitHub
}
+ if host == domain.CodeupRepoHost {
+ platform = domain.GitPlatformCodeup
+ }
if strings.TrimSpace(input.Platform) != "" {
var ok bool
if platform, ok = domain.NormalizeGitPlatform(input.Platform); !ok {
- return domain.GitHTTPCredentialSecret{}, errors.New("平台只能是 github、gitlab 或 other")
+ return domain.GitHTTPCredentialSecret{}, errors.New("平台只能是 github、gitlab、codeup 或 other")
}
}
username := strings.TrimSpace(input.Username)
@@ -153,6 +156,9 @@ func verifyGitHTTPToken(ctx context.Context, cred domain.GitHTTPCredentialSecret
if cred.Managed {
return verifyGongfengToken(ctx, cred.Token)
}
+ if cred.Platform == domain.GitPlatformCodeup {
+ return verifyCodeupToken(ctx, cred)
+ }
base := cred.APIBase()
if base == "" {
return gitTokenVerifyResult{Error: "该平台不支持在线校验,令牌会在 Git 操作时使用"}
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index 1f4ef7a0e..6c05c9621 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -70,6 +70,7 @@ type Server struct {
*deps
auth *authHandlers // auth.go
github *githubHandlers
+ codeup *codeupHandlers // codeup_auth.go
users *usersHandlers // users.go
sshHostTrust *sshHostTrustHandlers
projects *projectsHandlers
@@ -155,6 +156,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
notifications: ¬ificationHandlers{deps: d, service: notifications},
auth: &authHandlers{deps: d},
github: newGitHubHandlers(d),
+ codeup: newCodeupHandlers(d),
users: &usersHandlers{deps: d},
sshHostTrust: &sshHostTrustHandlers{deps: d, hosts: s.SSHHostTrustRepo, runnerControls: runnerControls},
catalog: &catalogHandlers{deps: d},
@@ -253,6 +255,8 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
g.POST("/api/auth/github/device", api.github.start)
g.POST("/api/auth/github/poll", api.github.poll)
g.GET("/api/auth/github/repositories", api.github.repositories)
+ g.GET("/api/auth/codeup/organizations", api.codeup.organizations)
+ g.GET("/api/auth/codeup/repositories", api.codeup.repositories)
g.GET("/api/auth/exchange", api.auth.authExchange)
g.POST("/api/auth/exchange", api.auth.authExchange)
g.POST("/api/auth/logout", api.auth.authLogout)
diff --git a/internal/repo/catalog.go b/internal/repo/catalog.go
index 369eb6c85..eae69bfd2 100644
--- a/internal/repo/catalog.go
+++ b/internal/repo/catalog.go
@@ -244,6 +244,7 @@ func BuiltInExecutors() []domain.ExecutorDefinition {
{ID: "pi", Name: "Pi", Kind: "pi", Binary: "pi", Protocol: "stream-json"},
{ID: "dsh", Name: "DeepSeek Harness", Kind: "dsh", Binary: "dsh", Protocol: "stream-json"},
{ID: "zcode", Name: "ZCode", Kind: "zcode", Binary: "zcode", Protocol: "stream-json"},
+ {ID: "qodercn", Name: "Qoder CN", Kind: "qodercn", Binary: "qodercn", Protocol: "stream-json"},
}
}
diff --git a/internal/runner/detect.go b/internal/runner/detect.go
index df7ab9137..6cdc7e77c 100644
--- a/internal/runner/detect.go
+++ b/internal/runner/detect.go
@@ -48,6 +48,9 @@ var defaultProviders = []providerSpec{
// The official ZCode has no npm package and its --help omits
// --output-format, so compatibility is probed with the flags we pass.
{Kind: "zcode", Binary: "zcode", VersionFlags: []string{"--output-format", "stream-json", "--mode", "yolo"}},
+ // Qoder CN ships an npm package and is found on PATH; it has no reliable
+ // non-interactive update subcommand.
+ {Kind: "qodercn", Binary: "qodercn"},
}
// terminalProviderKind is the built-in remote-terminal capability: the
diff --git a/internal/runtime/agent_cli.go b/internal/runtime/agent_cli.go
index 4efb03764..e05976e0f 100644
--- a/internal/runtime/agent_cli.go
+++ b/internal/runtime/agent_cli.go
@@ -27,6 +27,7 @@ const (
AgentCLIPi = "pi"
AgentCLIDeepSeek = "dsh"
AgentCLIZCode = "zcode"
+ AgentCLIQoderCN = "qodercn"
)
// AgentCLIKinds is the display order of the agent CLIs.
@@ -67,8 +68,9 @@ func AgentCLINeedsBaseURL(kind, protocol string) bool {
// can, DeepSeek Harness on the official endpoint.
func agentCLIModelOptional(kind, baseURL string) bool {
switch kind {
- case AgentCLICursor, AgentCLIZCode:
- // ZCode resolves an unset model itself (applyZCodeCredential).
+ case AgentCLICursor, AgentCLIZCode, AgentCLIQoderCN:
+ // ZCode resolves an unset model itself (applyZCodeCredential); Qoder CN
+ // falls back to the CLI's own model on its official endpoint.
return true
case AgentCLIAntigravity, AgentCLIDeepSeek:
return baseURL == ""
@@ -105,6 +107,8 @@ var agentCLIHostEnv = append([]string{
"KIMI_MODEL_NAME", "KIMI_MODEL_API_KEY", "KIMI_MODEL_BASE_URL", "KIMI_MODEL_PROVIDER_TYPE", kimiThinkingEffortEnv,
"OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT", "OPENCODE_CONFIG_DIR", "PI_CODING_AGENT_DIR",
"ZCODE_DATA_BASE_DIR", zcodePersonalFileEnv,
+ "QODERCN_PERSONAL_ACCESS_TOKEN", "QODERCN_CONFIG_DIR", "QODERCN_MODEL", "QODERCN_PERMISSION_MODE",
+ "QODERCN_SESSION_ID", "QODERCN_SESSION_NAME", "QODERCN_WORKING_DIR", "QODERCN_SUBAGENT_MODEL",
}, zcodeHostEnv...)
// agentCLIConfigPaths are the HOME-relative files an agent CLI reads its MCP
@@ -117,6 +121,7 @@ var agentCLIMCPPaths = map[string]string{
AgentCLIPi: ".pi/agent/mcp.json",
AgentCLIDeepSeek: ".dsh/agentflow-mcp.json",
AgentCLIZCode: zcodeConfigPath,
+ AgentCLIQoderCN: qoderCNConfigPath,
}
// AgentCLIMCPOptions shapes the MCP configuration of one invocation.
@@ -186,6 +191,13 @@ func WriteAgentCLIMCPConfig(kind string, home AgentCLIHome, entries map[string]a
}
}
}
+ if kind == AgentCLIQoderCN {
+ // Qoder CN keeps model, permissions and hooks beside mcpServers in one
+ // settings.json, so merge instead of replacing the whole document.
+ return mergeQoderCNSettings(home, func(document map[string]any) {
+ document["mcpServers"] = servers
+ })
+ }
var document any
switch kind {
case AgentCLIOpenCode:
@@ -512,6 +524,8 @@ func ApplyAgentCLICredential(kind string, cred ProviderCredential, options Agent
return applyDeepSeekCredential(home, homeEnv, key, baseURL, protocol, model, strings.TrimSpace(options.Effort), argv)
case AgentCLIZCode:
return applyZCodeCredential(home, homeEnv, key, baseURL, protocol, model, strings.TrimSpace(options.Effort), argv)
+ case AgentCLIQoderCN:
+ return applyQoderCNCredential(home, homeEnv, key, baseURL, protocol, model, argv)
default:
return nil, nil, fmt.Errorf("unknown agent CLI %q", kind)
}
@@ -644,6 +658,8 @@ func AgentCLILabel(kind string) string {
return "DeepSeek Harness"
case AgentCLIZCode:
return "ZCode"
+ case AgentCLIQoderCN:
+ return "Qoder CN"
}
return kind
}
diff --git a/internal/runtime/agent_cli_qodercn.go b/internal/runtime/agent_cli_qodercn.go
new file mode 100644
index 000000000..a58972b31
--- /dev/null
+++ b/internal/runtime/agent_cli_qodercn.go
@@ -0,0 +1,103 @@
+package runtime
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "slices"
+ "strings"
+)
+
+const (
+ // qoderCNConfigPath is Qoder CN's user-level settings file below HOME. It
+ // keeps mcpServers beside model, permissions and hooks, so every writer
+ // (MCP, credential, native approval) merges into it instead of replacing
+ // the whole document.
+ qoderCNConfigPath = ".qoder-cn/settings.json"
+
+ // qoderCNSOPDisallowedTools are the tools that wait for a person.
+ qoderCNSOPDisallowedTools = "AskUserQuestion EnterPlanMode ExitPlanMode"
+ // qoderCNChatDisallowedTools adds what acts outside the chat's MCP gateway:
+ // shell, edits, web, sub-agents and background tasks. Qoder CN is a
+ // Claude-Code-family CLI, so the tool names are the capitalized ones
+ // (Read, Write, Edit, Bash, WebFetch, Agent, ...).
+ qoderCNChatDisallowedTools = qoderCNSOPDisallowedTools + " Bash Edit Write WebFetch WebSearch Agent TaskOutput TaskStop"
+)
+
+// applyQoderCNCredential binds the responsible user's personal access token.
+// Qoder CN only reaches its official endpoint with a PAT: a custom Base URL is
+// rejected, and the model is optional (the CLI picks its own when unset or
+// "default"). The key stays in the environment; settings.json only names the
+// model, never the token.
+func applyQoderCNCredential(home AgentCLIHome, homeEnv, key, baseURL, protocol, model string, argv []string) ([]string, map[string]string, error) {
+ if baseURL != "" {
+ return nil, nil, errors.New("Qoder CN 仅支持官方端点(个人访问令牌),不支持自定义 Base URL")
+ }
+ if key == "" {
+ return nil, nil, fmt.Errorf("需求责任人未配置 %s 个人访问令牌(PAT),请在个人配置中配置", AgentCLILabel(AgentCLIQoderCN))
+ }
+ env := map[string]string{
+ "QODERCN_PERSONAL_ACCESS_TOKEN": key,
+ "QODERCN_CONFIG_DIR": homeEnv + "/.qoder-cn",
+ }
+ // An unset or "default" model keeps the CLI's own choice; a named one
+ // travels both as QODERCN_MODEL and as settings.json model.name.
+ model = strings.TrimSpace(model)
+ named := model != "" && model != "default"
+ if named {
+ env["QODERCN_MODEL"] = model
+ }
+ if err := mergeQoderCNSettings(home, func(document map[string]any) {
+ if !named {
+ return
+ }
+ settings, _ := document["model"].(map[string]any)
+ if settings == nil {
+ settings = map[string]any{}
+ }
+ settings["name"] = model
+ document["model"] = settings
+ }); err != nil {
+ return nil, nil, err
+ }
+ // AgentCLICommand supplies -p and the read-only / --yolo tool
+ // policy; guarantee the print format here so a minimal argv still emits
+ // Claude-Code-compatible stream-json.
+ argv = append([]string{}, argv...)
+ if i := slices.Index(argv, "--output-format"); i >= 0 && i+1 < len(argv) {
+ argv[i+1] = "stream-json"
+ } else {
+ argv = append(argv, "--output-format", "stream-json")
+ }
+ return argv, env, nil
+}
+
+// mergeQoderCNSettings reads the existing settings.json (when present), applies
+// mutate and writes it back, so MCP servers, the model selection and the native
+// approval hooks never clobber one another.
+func mergeQoderCNSettings(home AgentCLIHome, mutate func(map[string]any)) error {
+ root, err := openAgentCLIHome(home)
+ if err != nil {
+ return err
+ }
+ data, err := root.ReadFile(qoderCNConfigPath)
+ root.Close()
+ document := map[string]any{}
+ if err == nil {
+ if err = json.Unmarshal(data, &document); err != nil {
+ return err
+ }
+ } else if !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ if document == nil {
+ document = map[string]any{}
+ }
+ mutate(document)
+ out, err := json.MarshalIndent(document, "", " ")
+ if err != nil {
+ return err
+ }
+ return writeAgentCLIFile(home, qoderCNConfigPath, out)
+}
\ No newline at end of file
diff --git a/internal/runtime/agent_cli_qodercn_test.go b/internal/runtime/agent_cli_qodercn_test.go
new file mode 100644
index 000000000..d6c5d6531
--- /dev/null
+++ b/internal/runtime/agent_cli_qodercn_test.go
@@ -0,0 +1,184 @@
+package runtime
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+)
+
+func TestQoderCNCommand(t *testing.T) {
+ sop := AgentCLICommand(AgentCLIQoderCN, AgentCLICommandOptions{Prompt: "do it", SystemPrompt: "SYS", Model: "m"}).Argv
+ if sop[0] != "qodercn" || sop[1] != "-p" || !strings.Contains(sop[2], "SYS") || !strings.HasSuffix(sop[2], "do it") {
+ t.Fatalf("sop argv: %q", sop)
+ }
+ for _, arg := range []string{"--output-format", "stream-json", "--yolo", "--disallowed-tools", qoderCNSOPDisallowedTools} {
+ if !slices.Contains(sop, arg) {
+ t.Errorf("sop argv misses %q: %q", arg, sop)
+ }
+ }
+ if strings.Contains(qoderCNSOPDisallowedTools, "Bash") {
+ t.Errorf("SOP keeps native tools: %q", qoderCNSOPDisallowedTools)
+ }
+
+ chat := AgentCLICommand(AgentCLIQoderCN, AgentCLICommandOptions{Prompt: "hi", SystemPrompt: "SYS", Chat: true, Resume: "sess_1"})
+ if !chat.AgentCLI.ReadOnly || chat.Provider != AgentCLIQoderCN {
+ t.Fatalf("chat spec: %+v", chat)
+ }
+ i := slices.Index(chat.Argv, "--disallowed-tools")
+ if i < 0 || chat.Argv[i+1] != qoderCNChatDisallowedTools {
+ t.Fatalf("chat argv: %q", chat.Argv)
+ }
+ if slices.Contains(chat.Argv, "--yolo") {
+ t.Errorf("chat must not bypass permissions: %q", chat.Argv)
+ }
+ for _, tool := range strings.Fields("Bash Edit Write WebFetch WebSearch Agent AskUserQuestion EnterPlanMode ExitPlanMode") {
+ if !slices.Contains(strings.Fields(chat.Argv[i+1]), tool) {
+ t.Errorf("chat does not disallow %s", tool)
+ }
+ }
+ if j := slices.Index(chat.Argv, "--resume"); j < 0 || chat.Argv[j+1] != "sess_1" {
+ t.Fatalf("chat resume: %q", chat.Argv)
+ }
+ // A resumed chat session keeps the system prompt of its first turn.
+ if chat.Argv[2] != "hi" {
+ t.Fatalf("resumed prompt: %q", chat.Argv[2])
+ }
+ workspace := AgentCLICommand(AgentCLIQoderCN, AgentCLICommandOptions{Chat: true, Workspace: true, Prompt: "edit", Resume: "sess_1"})
+ i = slices.Index(workspace.Argv, "--disallowed-tools")
+ if workspace.AgentCLI.ReadOnly || i < 0 || workspace.Argv[i+1] != qoderCNSOPDisallowedTools || !slices.Contains(workspace.Argv, "--yolo") {
+ t.Fatalf("workspace retains native tools: %q", workspace.Argv)
+ }
+}
+
+func TestApplyQoderCNCredential(t *testing.T) {
+ home := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(home, ".qoder-cn"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ seed := `{"mcpServers":{"gw":{"url":"http://127.0.0.1:1/mcp"}},"permissions":{"allow":["mcp__gw"]},"hooks":{"PreToolUse":[]},"general":{"defaultPermissionMode":"bypass_permissions"}}`
+ if err := os.WriteFile(filepath.Join(home, ".qoder-cn", "settings.json"), []byte(seed), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ argv := []string{"qodercn", "-p", "do it", "--output-format", "stream-json", "--yolo"}
+ bound, env, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: " pat-secret "}, AgentCLIOptions{Model: "qoder-model"}, HostAgentCLIHome(home), "/w/home", argv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if env["QODERCN_PERSONAL_ACCESS_TOKEN"] != "pat-secret" || env["QODERCN_CONFIG_DIR"] != "/w/home/.qoder-cn" || env["QODERCN_MODEL"] != "qoder-model" {
+ t.Fatalf("env: %v", env)
+ }
+ if !slices.Equal(bound, argv) {
+ t.Fatalf("argv changed: %q", bound)
+ }
+ doc := readJSONFile(t, filepath.Join(home, ".qoder-cn", "settings.json"))
+ if doc["model"].(map[string]any)["name"] != "qoder-model" {
+ t.Fatalf("model not written: %v", doc)
+ }
+ // The merge keeps every other top-level key the CLI relies on.
+ if doc["mcpServers"].(map[string]any)["gw"] == nil || doc["permissions"] == nil || doc["hooks"] == nil || doc["general"] == nil {
+ t.Fatalf("merge lost keys: %v", doc)
+ }
+ data, _ := os.ReadFile(filepath.Join(home, ".qoder-cn", "settings.json"))
+ if strings.Contains(string(data), "pat-secret") {
+ t.Fatalf("PAT leaked into settings.json:\n%s", data)
+ }
+
+ // An unset or "default" model keeps the CLI's own choice.
+ for _, model := range []string{"", "default"} {
+ h := t.TempDir()
+ _, env, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: model}, HostAgentCLIHome(h), "/h", []string{"qodercn", "-p", "x"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := env["QODERCN_MODEL"]; ok {
+ t.Errorf("model %q must keep the CLI default: %v", model, env)
+ }
+ if doc := readJSONFile(t, filepath.Join(h, ".qoder-cn", "settings.json")); doc["model"] != nil {
+ t.Errorf("model %q wrote a selection: %v", model, doc)
+ }
+ }
+
+ // A custom Base URL is rejected: Qoder CN only reaches its official endpoint.
+ if _, _, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: "k", BaseURL: "https://gw.example"}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(t.TempDir()), "/h", nil); err == nil || !strings.Contains(err.Error(), "官方端点") {
+ t.Fatalf("baseURL must be rejected: %v", err)
+ }
+ // A missing PAT is rejected.
+ if _, _, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(t.TempDir()), "/h", nil); err == nil || !strings.Contains(err.Error(), "Qoder CN") {
+ t.Fatalf("missing PAT must be rejected: %v", err)
+ }
+ if _, _, err := applyQoderCNCredential(HostAgentCLIHome(t.TempDir()), "/h", "", "", "", "m", nil); err == nil || !strings.Contains(err.Error(), "PAT") {
+ t.Fatalf("direct missing PAT: %v", err)
+ }
+}
+
+func TestWriteAgentCLIMCPConfigQoderCN(t *testing.T) {
+ home := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(home, ".qoder-cn"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(home, ".qoder-cn", "settings.json"), []byte(`{"model":{"name":"keep"},"permissions":{"deny":["Bash"]},"hooks":{"Stop":[]}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ entries := map[string]any{"gw": map[string]any{"type": "http", "url": "https://m.example/mcp", "headers": map[string]any{"Authorization": "Bearer t"}}}
+ if err := WriteAgentCLIMCPConfig(AgentCLIQoderCN, HostAgentCLIHome(home), entries, AgentCLIMCPOptions{}); err != nil {
+ t.Fatal(err)
+ }
+ doc := readJSONFile(t, filepath.Join(home, ".qoder-cn", "settings.json"))
+ servers := doc["mcpServers"].(map[string]any)
+ if servers["gw"].(map[string]any)["url"] != "https://m.example/mcp" {
+ t.Fatalf("mcp server: %v", servers)
+ }
+ if doc["model"].(map[string]any)["name"] != "keep" || doc["permissions"] == nil || doc["hooks"] == nil {
+ t.Fatalf("MCP write clobbered other keys: %v", doc)
+ }
+}
+
+func TestQoderCNConversationApprovalPreservesMCPAndModel(t *testing.T) {
+ root := t.TempDir()
+ home := AgentCLIHome{Base: root, Rel: "home"}
+ if err := WriteAgentCLIMCPConfig(AgentCLIQoderCN, home, map[string]any{"agentflow_session": map[string]any{"type": "http", "url": "http://127.0.0.1/mcp"}}, AgentCLIMCPOptions{}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := InstallConversationApproval(root, AgentCLIQoderCN, CommandSpec{Argv: []string{"qodercn"}}); err != nil {
+ t.Fatal(err)
+ }
+ doc := readJSONFile(t, filepath.Join(root, "home", ".qoder-cn", "settings.json"))
+ if doc["hooks"].(map[string]any)["PreToolUse"] == nil || doc["mcpServers"] == nil {
+ t.Fatalf("lost approval or MCP: %v", doc)
+ }
+ // Credential binding happens after approval and must retain the guard.
+ if _, _, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, home, filepath.Join(root, "home"), []string{"qodercn"}); err != nil {
+ t.Fatal(err)
+ }
+ doc = readJSONFile(t, filepath.Join(root, "home", ".qoder-cn", "settings.json"))
+ if doc["hooks"].(map[string]any)["PreToolUse"] == nil || doc["mcpServers"] == nil || doc["model"].(map[string]any)["name"] != "m" {
+ t.Fatalf("binding replaced approval/MCP/model: %v", doc)
+ }
+}
+
+func TestQoderCNTranslatorPassthrough(t *testing.T) {
+ translate := NewAgentCLITranslator(AgentCLIQoderCN)
+ if translate == nil {
+ t.Fatal("no translator for qodercn")
+ }
+ samples := []string{
+ `{"type":"system","subtype":"init","session_id":"sess_1","model":"qoder"}`,
+ `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"done"}]},"session_id":"sess_1"}`,
+ `{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"sess_1"}`,
+ }
+ for _, line := range samples {
+ if out := translate(line); len(out) != 1 || out[0] != line {
+ t.Fatalf("passthrough changed line: %q -> %q", line, out)
+ }
+ }
+ if out := translate(" " + samples[0] + " "); len(out) != 1 || out[0] != samples[0] {
+ t.Fatalf("trim: %q", out)
+ }
+ for _, bad := range []string{"", "not json", "[1,2]", `{"broken":`} {
+ if out := translate(bad); out != nil {
+ t.Fatalf("garbage %q -> %q", bad, out)
+ }
+ }
+}
\ No newline at end of file
diff --git a/internal/runtime/agent_cli_stream.go b/internal/runtime/agent_cli_stream.go
index 079798cac..989fe28db 100644
--- a/internal/runtime/agent_cli_stream.go
+++ b/internal/runtime/agent_cli_stream.go
@@ -176,6 +176,20 @@ func NewAgentCLITranslator(kind string) func(string) []string {
translate = (&dshStream{}).translate
case AgentCLIZCode:
translate = (&zcodeStream{}).translate
+ case AgentCLIQoderCN:
+ // Qoder CN already prints Claude-Code-compatible stream-json NDJSON, so
+ // every well-formed line passes through unchanged.
+ return func(line string) []string {
+ line = strings.TrimSpace(line)
+ if line == "" || line[0] != '{' {
+ return nil
+ }
+ var raw map[string]any
+ if json.Unmarshal([]byte(line), &raw) != nil {
+ return nil
+ }
+ return []string{line}
+ }
default:
return nil
}
diff --git a/internal/runtime/cli_ondemand.go b/internal/runtime/cli_ondemand.go
index c96694e58..8fc7cb278 100644
--- a/internal/runtime/cli_ondemand.go
+++ b/internal/runtime/cli_ondemand.go
@@ -52,6 +52,7 @@ func onDemandCLICatalog() map[string]onDemandCLI {
"kimi": {Engine: "kimi", Binary: "kimi", Package: "@moonshot-ai/kimi-code"},
"pi": {Engine: "pi", Binary: "pi", Package: "@earendil-works/pi-coding-agent"},
"dsh": {Engine: "dsh", Binary: "dsh", Package: "@deepseek-ai/dsh@" + DeepSeekHarnessVersion, RelaxEngines: true, Bundled: true},
+ "qodercn": {Engine: "qodercn", Binary: "qodercn", Package: "@qodercn-ai/qoderclicn"},
}
}
diff --git a/internal/runtime/conversation_approval.go b/internal/runtime/conversation_approval.go
index 9de5b7051..1760c7156 100644
--- a/internal/runtime/conversation_approval.go
+++ b/internal/runtime/conversation_approval.go
@@ -78,6 +78,21 @@ func InstallConversationApproval(root, provider string, command CommandSpec) (Co
if err := writeAgentCLIFile(home, zcodeConfigPath, data); err != nil {
return command, err
}
+ case AgentCLIQoderCN:
+ // Qoder CN reads Claude-Code-style hooks from settings.json. Merge the
+ // PreToolUse guard so the MCP servers and model selection survive.
+ if err := mergeQoderCNSettings(home, func(document map[string]any) {
+ configured, _ := document["hooks"].(map[string]any)
+ if configured == nil {
+ configured = map[string]any{}
+ }
+ for event, entry := range hooks {
+ configured[event] = entry
+ }
+ document["hooks"] = configured
+ }); err != nil {
+ return command, err
+ }
case "codex":
entry := "hooks.PreToolUse=[{hooks=[{type=\"command\",command=" + strconv.Quote(launch) + ",timeout=" + strconv.Itoa(conversationApprovalHookWatchdog) + "}]}]"
command.Argv = append(command.Argv[:len(command.Argv)-1], "-c", "features.hooks=true", "-c", entry, command.Argv[len(command.Argv)-1])
diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.go
index 0ceca3933..cd624ffc5 100644
--- a/internal/runtime/conversation_process.go
+++ b/internal/runtime/conversation_process.go
@@ -596,7 +596,7 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str
}
// Some CLIs continue after a hook interpreter cannot be spawned. Both
// the platform guard and the native approval hook must fail closed.
- if (spec == nil || spec.Profile.Driver != domain.SandboxDriverDocker) && (command.Provider == AgentCLIKimi || command.Provider == "codex" || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode) {
+ if (spec == nil || spec.Profile.Driver != domain.SandboxDriverDocker) && (command.Provider == AgentCLIKimi || command.Provider == "codex" || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode || command.Provider == AgentCLIQoderCN) {
check := exec.CommandContext(procCtx, "python3", "-c", "import json,urllib.request")
if err = check.Run(); err != nil {
return ConversationProcessResult{}, fmt.Errorf("原生工具审批需要 Python3:%w", err)
@@ -605,7 +605,7 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str
// These providers load hooks/extensions from persistent HOME in platform
// mode too. Refresh them on every start so returning from a workspace never
// runs a stale hook (Pi's codemode wrapper must reach its concrete tools).
- if spec != nil || command.Provider == AgentCLIKimi || command.Provider == AgentCLIPi || command.Provider == AgentCLIOpenCode || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode {
+ if spec != nil || command.Provider == AgentCLIKimi || command.Provider == AgentCLIPi || command.Provider == AgentCLIOpenCode || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode || command.Provider == AgentCLIQoderCN {
command, err = InstallConversationApproval(root, command.Provider, command)
if err != nil {
return ConversationProcessResult{}, err
diff --git a/internal/runtime/provider_agentcli.go b/internal/runtime/provider_agentcli.go
index 600d4a649..9d1c97a1c 100644
--- a/internal/runtime/provider_agentcli.go
+++ b/internal/runtime/provider_agentcli.go
@@ -228,6 +228,24 @@ func AgentCLICommand(kind string, o AgentCLICommandOptions) CommandSpec {
argv = append(argv, "--resume", resume)
}
argv = append(argv, extra...)
+ case AgentCLIQoderCN:
+ disallowed := qoderCNSOPDisallowedTools
+ if readOnly {
+ disallowed = qoderCNChatDisallowedTools
+ }
+ argv = []string{binary, "-p", prompt, "--output-format", "stream-json", "--disallowed-tools", disallowed}
+ if !readOnly {
+ // SOP and workspace turns bypass permissions; AI 对话 keeps the
+ // native approval hook and denies the chat tool set instead.
+ argv = append(argv, "--yolo")
+ }
+ if resume != "" {
+ argv = append(argv, "--resume", resume)
+ }
+ if options.Effort != "" {
+ argv = append(argv, "--reasoning-effort", options.Effort)
+ }
+ argv = append(argv, extra...)
}
return CommandSpec{Argv: argv, Provider: kind, AgentCLI: options}
}
diff --git a/internal/tracker/codeup.go b/internal/tracker/codeup.go
new file mode 100644
index 000000000..4571c264c
--- /dev/null
+++ b/internal/tracker/codeup.go
@@ -0,0 +1,388 @@
+package tracker
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "agentflow/internal/domain"
+)
+
+// codeupClient talks to the Aliyun Yunxiao Codeup central-station OpenAPI. It
+// mirrors githubClient: the token is the project owner's per-host HTTPS Git
+// credential for codeup.aliyun.com (the PAT doubles as the API token), and the
+// repository is addressed by its URL-encoded full path orgId/group/repo.
+type codeupClient struct {
+ base, org, repoPath, token string
+ http *http.Client
+ repoID int // cached integer repository id resolved on first write/list
+}
+
+func (s *Service) codeupClient(project string) (*codeupClient, error) {
+ org, repoPath, ok := domain.ParseCodeupProject(project)
+ if !ok {
+ return nil, fmt.Errorf("invalid Codeup repository")
+ }
+ var token string
+ if s.projectAuth != nil {
+ for _, repo := range s.projectAuth.Repositories() {
+ if repo.Provider != domain.RepositoryProviderCodeup || repo.GongfengProjectID != project {
+ continue
+ }
+ if p, found := s.projectAuth.Project(repo.ProjectID); found {
+ token = s.codeupTokenForUser(p.OwnerID)
+ }
+ break
+ }
+ }
+ base := s.codeupAPIBase
+ if base == "" {
+ base = domain.CodeupAPIBase
+ }
+ return &codeupClient{base: base, org: org, repoPath: repoPath, token: token, http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}}, nil
+}
+
+// codeupClientForRun authenticates as the run did: its push token when set,
+// else the Owner of the run's project when that project binds the repository.
+func (s *Service) codeupClientForRun(project, localProjectID, gitToken string) (*codeupClient, string, error) {
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return nil, "", err
+ }
+ if token := strings.TrimSpace(gitToken); token != "" {
+ c.token = token
+ return c, "本轮责任人的 Git Token", nil
+ }
+ local := strings.TrimSpace(localProjectID)
+ if s.projectAuth == nil || local == "" {
+ return c, "首个绑定该仓库的项目 Owner 的 Git Token", nil
+ }
+ for _, repo := range s.projectAuth.Repositories() {
+ if repo.Provider != domain.RepositoryProviderCodeup || repo.GongfengProjectID != project || repo.ProjectID != local {
+ continue
+ }
+ c.token = ""
+ if p, found := s.projectAuth.Project(local); found {
+ c.token = s.codeupTokenForUser(p.OwnerID)
+ }
+ return c, "项目 " + local + " Owner 的 Git Token", nil
+ }
+ return c, "首个绑定该仓库的项目 Owner 的 Git Token", nil
+}
+
+func (s *Service) codeupTokenForUser(userID int64) string {
+ if credentials, ok := s.projectAuth.(GitHTTPCredentialStore); ok {
+ if credential, ok := credentials.GitHTTPCredentialForHost(context.Background(), userID, domain.CodeupRepoHost); ok {
+ return credential.Token
+ }
+ }
+ return ""
+}
+
+func (c *codeupClient) request(method, path string, input, output any) error {
+ var body io.Reader
+ if input != nil {
+ b, err := json.Marshal(input)
+ if err != nil {
+ return err
+ }
+ body = bytes.NewReader(b)
+ }
+ r, err := http.NewRequest(method, c.base+path, body)
+ if err != nil {
+ return err
+ }
+ r.Header.Set("Accept", "application/json")
+ r.Header.Set("Content-Type", "application/json")
+ if c.token != "" {
+ r.Header.Set("x-yunxiao-token", c.token)
+ }
+ res, err := c.http.Do(r)
+ if err != nil {
+ return fmt.Errorf("Codeup request failed")
+ }
+ defer res.Body.Close()
+ if res.StatusCode < 200 || res.StatusCode >= 300 {
+ return fmt.Errorf("Codeup returned HTTP %d; check the project owner's Codeup token and repository permissions", res.StatusCode)
+ }
+ if output == nil {
+ _, err = io.Copy(io.Discard, io.LimitReader(res.Body, 4<<20))
+ return err
+ }
+ return json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(output)
+}
+
+func (c *codeupClient) repoPathEscape() string { return url.PathEscape(c.repoPath) }
+
+// repositoryID resolves the integer repository id the create/list APIs require.
+// The repositoryId path parameter accepts the URL-encoded full path, so no
+// separate lookup table is needed; the result is cached for the client's life.
+func (c *codeupClient) repositoryID() (int, error) {
+ if c.repoID != 0 {
+ return c.repoID, nil
+ }
+ var repo struct {
+ ID int `json:"id"`
+ }
+ if err := c.request("GET", "/oapi/v1/codeup/organizations/"+c.org+"/repositories/"+c.repoPathEscape(), nil, &repo); err != nil {
+ return 0, err
+ }
+ if repo.ID == 0 {
+ return 0, fmt.Errorf("Codeup repository %s has no id", c.repoPath)
+ }
+ c.repoID = repo.ID
+ return repo.ID, nil
+}
+
+// codeupChangeRequest is one merge request (变更) in a Codeup repository.
+type codeupChangeRequest struct {
+ LocalID int `json:"localId"`
+ State string `json:"state"`
+ DetailURL string `json:"detailUrl"`
+ WebURL string `json:"webUrl"`
+ SourceBranch string `json:"sourceBranch"`
+ TargetBranch string `json:"targetBranch"`
+ MergedRevision string `json:"mergedRevision"`
+ ProjectID int `json:"projectId"`
+ SourceProjectID int `json:"sourceProjectId"`
+ TargetProjectID int `json:"targetProjectId"`
+ Title string `json:"title"`
+}
+
+// codeupMRState maps the Codeup change-request status onto the platform's
+// opened/merged/closed delivery vocabulary.
+func codeupMRState(state string) string {
+ switch strings.ToUpper(strings.TrimSpace(state)) {
+ case "UNDER_DEV", "UNDER_REVIEW", "TO_BE_MERGED":
+ return "opened"
+ case "MERGED":
+ return "merged"
+ case "CLOSED":
+ return "closed"
+ default:
+ return ""
+ }
+}
+
+// ref is the "!N" reference returned to delivery callers (localId is per-repo).
+func (cr codeupChangeRequest) ref() string { return "!" + strconv.Itoa(cr.LocalID) }
+
+func (cr codeupChangeRequest) webURL(project string) string {
+ if u := strings.TrimSpace(cr.DetailURL); u != "" {
+ return u
+ }
+ if u := strings.TrimSpace(cr.WebURL); u != "" {
+ return u
+ }
+ return domain.GongfengMRURL(project, cr.LocalID)
+}
+
+// delivery converts a change request into a delivery MR. Codeup's list response
+// exposes no source-branch head commit, so HeadSHA stays empty: an open MR then
+// satisfies the coverage gate, and merged MRs are classified by state alone.
+func (cr codeupChangeRequest) delivery(project string) domain.DeliveryMR {
+ state := codeupMRState(cr.State)
+ return domain.DeliveryMR{
+ Project: project,
+ IID: cr.LocalID,
+ URL: cr.webURL(project),
+ State: state,
+ GongfengState: state,
+ TargetBranch: strings.TrimSpace(cr.TargetBranch),
+ }
+}
+
+// listChangeRequests lists the repository's change requests, most recently
+// updated first. The central-station list endpoint is organization-scoped and
+// filters by projectIds/state only, so source/target branch matching is done by
+// the caller. An empty state queries every status.
+func (c *codeupClient) listChangeRequests(state string) ([]codeupChangeRequest, error) {
+ id, err := c.repositoryID()
+ if err != nil {
+ return nil, err
+ }
+ var out []codeupChangeRequest
+ for page := 1; page <= 20; page++ {
+ q := url.Values{"projectIds": {strconv.Itoa(id)}, "perPage": {"100"}, "page": {strconv.Itoa(page)}, "orderBy": {"updated_at"}, "sort": {"desc"}}
+ if state != "" {
+ q.Set("state", state)
+ }
+ var list []codeupChangeRequest
+ if err := c.request("GET", "/oapi/v1/codeup/organizations/"+c.org+"/changeRequests?"+q.Encode(), nil, &list); err != nil {
+ return nil, err
+ }
+ out = append(out, list...)
+ if len(list) < 100 {
+ break
+ }
+ }
+ return out, nil
+}
+
+func (c *codeupClient) createChangeRequest(sourceBranch, targetBranch, title, description string) (codeupChangeRequest, error) {
+ id, err := c.repositoryID()
+ if err != nil {
+ return codeupChangeRequest{}, err
+ }
+ body := map[string]any{
+ "sourceBranch": sourceBranch,
+ "targetBranch": targetBranch,
+ "title": title,
+ "sourceProjectId": id,
+ "targetProjectId": id,
+ }
+ if strings.TrimSpace(description) != "" {
+ body["description"] = description
+ }
+ var cr codeupChangeRequest
+ if err := c.request("POST", "/oapi/v1/codeup/organizations/"+c.org+"/repositories/"+c.repoPathEscape()+"/changeRequests", body, &cr); err != nil {
+ return codeupChangeRequest{}, err
+ }
+ return cr, nil
+}
+
+// mergeChangeRequest merges with a merge commit (no-fast-forward) and keeps the
+// source branch, matching the Gongfeng/GitHub delivery convention.
+func (c *codeupClient) mergeChangeRequest(localID int, message string) error {
+ body := map[string]any{
+ "mergeType": "no-fast-forward",
+ "removeSourceBranch": false,
+ }
+ if strings.TrimSpace(message) != "" {
+ body["mergeMessage"] = message
+ }
+ return c.request("POST", "/oapi/v1/codeup/organizations/"+c.org+"/repositories/"+c.repoPathEscape()+"/changeRequests/"+strconv.Itoa(localID)+"/merge", body, nil)
+}
+
+func findCodeupChangeRequest(items []codeupChangeRequest, branch, target string) (codeupChangeRequest, bool) {
+ for _, cr := range items {
+ if domain.SameGitBranch(cr.SourceBranch, branch) && (target == "" || domain.SameGitBranch(cr.TargetBranch, target)) {
+ return cr, true
+ }
+ }
+ return codeupChangeRequest{}, false
+}
+
+// pickCodeupBranchMR returns the newest non-closed change request whose source
+// is branch, else the newest closed one (mirrors pickBranchMR).
+func pickCodeupBranchMR(items []codeupChangeRequest, sourceBranch string) (codeupChangeRequest, bool) {
+ var best codeupChangeRequest
+ found, bestClosed := false, false
+ for _, item := range items {
+ if s := strings.TrimSpace(item.SourceBranch); s != "" && !domain.SameGitBranch(s, sourceBranch) {
+ continue
+ }
+ closed := codeupMRState(item.State) == "closed"
+ switch {
+ case !found:
+ case bestClosed && !closed:
+ case bestClosed == closed && item.LocalID > best.LocalID:
+ default:
+ continue
+ }
+ best, found, bestClosed = item, true, closed
+ }
+ return best, found
+}
+
+func (s *Service) codeupFindBranch(project, branch string) (domain.DeliveryMR, bool, error) {
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return domain.DeliveryMR{}, false, err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return domain.DeliveryMR{}, false, err
+ }
+ cr, ok := pickCodeupBranchMR(list, branch)
+ if !ok {
+ return domain.DeliveryMR{}, false, nil
+ }
+ return cr.delivery(project), true, nil
+}
+
+func (s *Service) codeupMergeBranch(project, branch, target, title, description string) (string, error) {
+ if branch == "" {
+ return "", fmt.Errorf("source branch is required")
+ }
+ if branch == target {
+ return "", nil
+ }
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return "", err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return "", err
+ }
+ cr, found := findCodeupChangeRequest(list, branch, target)
+ if found && codeupMRState(cr.State) == "merged" {
+ return cr.ref(), nil
+ }
+ if !found || codeupMRState(cr.State) == "closed" {
+ if target == "" {
+ return "", ErrNoOpenMR
+ }
+ if strings.TrimSpace(title) == "" {
+ title = "LoopForge: " + branch + " → " + target
+ }
+ cr, err = c.createChangeRequest(branch, target, title, description)
+ if err != nil {
+ return "", err
+ }
+ }
+ if err := c.mergeChangeRequest(cr.LocalID, title); err != nil {
+ return "", fmt.Errorf("merge MR !%d: %w", cr.LocalID, err)
+ }
+ return cr.ref(), nil
+}
+
+func (s *Service) codeupFindBranchMRsInto(q domain.BranchMRQuery) ([]domain.DeliveryMR, error) {
+ project := strings.TrimSpace(q.RemoteProject)
+ src, target := strings.TrimSpace(q.SourceBranch), strings.TrimSpace(q.TargetBranch)
+ c, identity, err := s.codeupClientForRun(project, q.ProjectID, q.GitToken)
+ if err != nil {
+ return nil, err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return nil, fmt.Errorf("以%s查询云效失败:%w", identity, err)
+ }
+ var out []domain.DeliveryMR
+ for _, cr := range list {
+ if !domain.SameGitBranch(cr.SourceBranch, src) || !domain.SameGitBranch(cr.TargetBranch, target) {
+ continue
+ }
+ out = append(out, cr.delivery(project))
+ }
+ return out, nil
+}
+
+// refreshCodeupDelivery re-reads one change request's state for the background
+// delivery sync. Codeup's list response carries no merge timestamp, so mergedAt
+// stays zero; the classified state and target branch are still refreshed.
+func (s *Service) refreshCodeupDelivery(store MRDeliveryStore, project string, localID int) error {
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return err
+ }
+ for _, cr := range list {
+ if cr.LocalID == localID {
+ d := cr.delivery(project)
+ return store.UpdateMRDeliveryState(project, localID, d.GongfengState, d.TargetBranch, time.Time{}, time.Now().UTC())
+ }
+ }
+ return fmt.Errorf("Codeup change request %s!%d not found", project, localID)
+}
\ No newline at end of file
diff --git a/internal/tracker/codeup_test.go b/internal/tracker/codeup_test.go
new file mode 100644
index 000000000..765442722
--- /dev/null
+++ b/internal/tracker/codeup_test.go
@@ -0,0 +1,195 @@
+package tracker
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "agentflow/internal/domain"
+ "agentflow/internal/repo"
+)
+
+func TestCodeupMRStateMapping(t *testing.T) {
+ cases := map[string]string{
+ "UNDER_DEV": "opened",
+ "UNDER_REVIEW": "opened",
+ "TO_BE_MERGED": "opened",
+ "MERGED": "merged",
+ "CLOSED": "closed",
+ "under_review": "opened",
+ "UNKNOWN": "",
+ "": "",
+ }
+ for state, want := range cases {
+ if got := codeupMRState(state); got != want {
+ t.Errorf("codeupMRState(%q) = %q want %q", state, got, want)
+ }
+ }
+}
+
+// codeupTestStore wires a project owner with a per-host Codeup credential and a
+// codeup repository, mirroring the GitHub adapter test fixtures.
+func codeupTestStore(t *testing.T) (*Service, domain.Repository) {
+ t.Helper()
+ st, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(st.Close)
+ if err := st.PutUser(domain.User{LoginName: "codeup-owner"}); err != nil {
+ t.Fatal(err)
+ }
+ u, _ := st.UserByLoginName("codeup-owner")
+ if err := st.SaveGitHTTPCredential(u.ID, "", domain.GitHTTPCredentialSecret{
+ GitHTTPCredential: domain.GitHTTPCredential{Name: "Codeup", Host: domain.CodeupRepoHost, Platform: domain.GitPlatformCodeup, Username: "clone-account"},
+ Token: "codeup-pat",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.PutProject(domain.Project{ID: "pub", Name: "Pub", OwnerID: u.ID}); err != nil {
+ t.Fatal(err)
+ }
+ r := domain.Repository{ID: "codeup-repo", ProjectID: "pub", Provider: domain.RepositoryProviderCodeup, Name: "app", GongfengProjectID: "codeup:60d54f3daccf2bbd6659f3ad/team/app", DefaultBranch: "master", WebURL: "https://codeup.aliyun.com/60d54f3daccf2bbd6659f3ad/team/app"}
+ if err := st.PutRepository(r); err != nil {
+ t.Fatal(err)
+ }
+ s := NewService()
+ s.ConfigureWithStore(domain.SyncConfig{}, st)
+ return s, r
+}
+
+const (
+ codeupTestOrg = "60d54f3daccf2bbd6659f3ad"
+ codeupTestRepoBase = "/oapi/v1/codeup/organizations/" + codeupTestOrg + "/repositories/" + codeupTestOrg + "%2Fteam%2Fapp"
+ codeupTestListPath = "/oapi/v1/codeup/organizations/" + codeupTestOrg + "/changeRequests"
+)
+
+// codeupTestServer simulates the Codeup OpenAPI: repository id resolution, the
+// organization-scoped change-request list, create and merge. It records writes
+// and the decoded create/merge bodies for assertions.
+func codeupTestServer(t *testing.T, listJSON string) (*httptest.Server, *[]string, *map[string]any, *map[string]any) {
+ t.Helper()
+ var writes []string
+ var createBody, mergeBody map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("x-yunxiao-token") != "codeup-pat" {
+ t.Errorf("missing or wrong Codeup token header: %q", r.Header.Get("x-yunxiao-token"))
+ }
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case r.Method == http.MethodGet && r.URL.EscapedPath() == codeupTestRepoBase:
+ _, _ = w.Write([]byte(`{"id":2813489}`))
+ case r.Method == http.MethodGet && r.URL.Path == codeupTestListPath:
+ if r.URL.Query().Get("projectIds") != "2813489" {
+ t.Errorf("list must filter by the resolved repository id, got %q", r.URL.RawQuery)
+ }
+ _, _ = w.Write([]byte(listJSON))
+ case r.Method == http.MethodPost && r.URL.EscapedPath() == codeupTestRepoBase+"/changeRequests":
+ writes = append(writes, "POST create")
+ _ = json.NewDecoder(r.Body).Decode(&createBody)
+ _, _ = w.Write([]byte(`{"localId":21,"state":"UNDER_REVIEW","sourceBranch":"feature/work","targetBranch":"master","detailUrl":"https://codeup.aliyun.com/` + codeupTestOrg + `/team/app/change/21"}`))
+ case r.Method == http.MethodPost && strings.HasPrefix(r.URL.EscapedPath(), codeupTestRepoBase+"/changeRequests/") && strings.HasSuffix(r.URL.EscapedPath(), "/merge"):
+ id := strings.TrimSuffix(strings.TrimPrefix(r.URL.EscapedPath(), codeupTestRepoBase+"/changeRequests/"), "/merge")
+ writes = append(writes, "POST merge "+id)
+ _ = json.NewDecoder(r.Body).Decode(&mergeBody)
+ _, _ = w.Write([]byte(`{}`))
+ default:
+ t.Errorf("unexpected request %s %s", r.Method, r.URL.EscapedPath())
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &writes, &createBody, &mergeBody
+}
+
+func TestCodeupEnsureAndMergeBranchMR(t *testing.T) {
+ project := "codeup:" + codeupTestOrg + "/team/app"
+
+ t.Run("create then merge", func(t *testing.T) {
+ s, _ := codeupTestStore(t)
+ srv, writes, createBody, mergeBody := codeupTestServer(t, `[]`)
+ s.codeupAPIBase = srv.URL
+ ref, err := s.EnsureAndMergeBranchMR(project, "feature/work", "master", "Title", "desc")
+ if err != nil || ref != "!21" {
+ t.Fatalf("ref=%q err=%v", ref, err)
+ }
+ if len(*writes) != 2 || (*writes)[0] != "POST create" || (*writes)[1] != "POST merge 21" {
+ t.Fatalf("writes=%v", *writes)
+ }
+ if (*createBody)["sourceProjectId"] != float64(2813489) || (*createBody)["targetProjectId"] != float64(2813489) {
+ t.Fatalf("create must bind integer repo ids: %v", *createBody)
+ }
+ if (*createBody)["sourceBranch"] != "feature/work" || (*createBody)["targetBranch"] != "master" || (*createBody)["title"] != "Title" {
+ t.Fatalf("create body: %v", *createBody)
+ }
+ if (*mergeBody)["mergeType"] != "no-fast-forward" || (*mergeBody)["removeSourceBranch"] != false {
+ t.Fatalf("merge body: %v", *mergeBody)
+ }
+ })
+
+ t.Run("merge existing open without create", func(t *testing.T) {
+ s, _ := codeupTestStore(t)
+ list := `[{"localId":7,"state":"TO_BE_MERGED","sourceBranch":"feature/work","targetBranch":"master","detailUrl":"https://codeup.aliyun.com/` + codeupTestOrg + `/team/app/change/7"}]`
+ srv, writes, _, mergeBody := codeupTestServer(t, list)
+ s.codeupAPIBase = srv.URL
+ ref, err := s.EnsureAndMergeBranchMR(project, "feature/work", "master", "", "")
+ if err != nil || ref != "!7" {
+ t.Fatalf("ref=%q err=%v", ref, err)
+ }
+ if len(*writes) != 1 || (*writes)[0] != "POST merge 7" {
+ t.Fatalf("open MR must be merged without re-create: %v", *writes)
+ }
+ if (*mergeBody)["mergeType"] != "no-fast-forward" {
+ t.Fatalf("merge body: %v", *mergeBody)
+ }
+ })
+
+ t.Run("short-circuit already merged", func(t *testing.T) {
+ s, _ := codeupTestStore(t)
+ list := `[{"localId":9,"state":"MERGED","sourceBranch":"feature/work","targetBranch":"master","mergedRevision":"abc"}]`
+ srv, writes, _, _ := codeupTestServer(t, list)
+ s.codeupAPIBase = srv.URL
+ ref, err := s.EnsureAndMergeBranchMR(project, "feature/work", "master", "", "")
+ if err != nil || ref != "!9" {
+ t.Fatalf("ref=%q err=%v", ref, err)
+ }
+ if len(*writes) != 0 {
+ t.Fatalf("merged MR must not be re-created or re-merged: %v", *writes)
+ }
+ })
+}
+
+func TestCodeupFindBranchMRAndInto(t *testing.T) {
+ s, r := codeupTestStore(t)
+ list := `[
+ {"localId":7,"state":"UNDER_REVIEW","sourceBranch":"feature/work","targetBranch":"master","detailUrl":"https://codeup.aliyun.com/` + codeupTestOrg + `/team/app/change/7"},
+ {"localId":5,"state":"MERGED","sourceBranch":"feature/work","targetBranch":"master","mergedRevision":"old"},
+ {"localId":8,"state":"CLOSED","sourceBranch":"feature/work","targetBranch":"master"},
+ {"localId":9,"state":"UNDER_DEV","sourceBranch":"other","targetBranch":"master"}
+ ]`
+ srv, _, _, _ := codeupTestServer(t, list)
+ s.codeupAPIBase = srv.URL
+
+ mr, ok, err := s.FindBranchMR(r.GongfengProjectID, "feature/work")
+ if err != nil || !ok {
+ t.Fatalf("FindBranchMR ok=%v err=%v", ok, err)
+ }
+ if mr.IID != 7 || mr.GongfengState != "opened" || mr.URL != "https://codeup.aliyun.com/"+codeupTestOrg+"/team/app/change/7" {
+ t.Fatalf("FindBranchMR = %+v", mr)
+ }
+
+ into, err := s.FindBranchMRsInto(domain.BranchMRQuery{ProjectID: "pub", RemoteProject: r.GongfengProjectID, SourceBranch: "feature/work", TargetBranch: "master"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(into) != 3 {
+ t.Fatalf("FindBranchMRsInto = %+v", into)
+ }
+ for _, mr := range into {
+ if mr.TargetBranch != "master" || mr.Project != r.GongfengProjectID {
+ t.Fatalf("unexpected MR in result: %+v", mr)
+ }
+ }
+}
\ No newline at end of file
diff --git a/internal/tracker/merge_mr.go b/internal/tracker/merge_mr.go
index e5c2593e2..5a2bf20c2 100644
--- a/internal/tracker/merge_mr.go
+++ b/internal/tracker/merge_mr.go
@@ -29,6 +29,9 @@ func (s *Service) EnsureAndMergeBranchMR(project, sourceBranch, targetBranch, ti
if strings.HasPrefix(project, "github:") {
return s.githubMergeBranch(project, sourceBranch, targetBranch, title, description)
}
+ if strings.HasPrefix(project, "codeup:") {
+ return s.codeupMergeBranch(project, sourceBranch, targetBranch, title, description)
+ }
project = strings.TrimSpace(project)
src := strings.TrimSpace(sourceBranch)
tgt := strings.TrimSpace(targetBranch)
@@ -141,6 +144,9 @@ func (s *Service) FindBranchMR(project, sourceBranch string) (domain.DeliveryMR,
if strings.HasPrefix(project, "github:") {
return s.githubFindBranch(project, sourceBranch)
}
+ if strings.HasPrefix(project, "codeup:") {
+ return s.codeupFindBranch(project, sourceBranch)
+ }
project = strings.TrimSpace(project)
src := strings.TrimSpace(sourceBranch)
if project == "" || src == "" {
@@ -201,6 +207,9 @@ func (s *Service) FindBranchMRsInto(q domain.BranchMRQuery) ([]domain.DeliveryMR
}
return githubPullsInto(pulls, project, src, target), nil
}
+ if strings.HasPrefix(project, "codeup:") {
+ return s.codeupFindBranchMRsInto(q)
+ }
client, source, err := s.gongfengClientForRun(project, q)
if err != nil {
return nil, err
diff --git a/internal/tracker/mr_delivery_sync.go b/internal/tracker/mr_delivery_sync.go
index 212d9d03c..fa5550eba 100644
--- a/internal/tracker/mr_delivery_sync.go
+++ b/internal/tracker/mr_delivery_sync.go
@@ -132,6 +132,14 @@ func (s *Service) syncMRDeliveryStates(store MRDeliveryStore) {
}
continue
}
+ if strings.HasPrefix(row.MRProject, "codeup:") {
+ if err := s.refreshCodeupDelivery(store, row.MRProject, row.MRIID); err != nil {
+ log.Printf("Codeup delivery refresh: %v", err)
+ } else {
+ updated++
+ }
+ continue
+ }
if strings.HasPrefix(row.MRProject, domain.MRProjectGHE) || strings.HasPrefix(row.MRProject, domain.MRProjectGitLab) {
if ok, err := s.refreshExternalDelivery(store, row); err != nil {
log.Printf("mr-delivery refresh %s!%d: %v", row.MRProject, row.MRIID, err)
@@ -170,7 +178,7 @@ func (s *Service) discoverPromoteMRs(store MRDeliveryStore) {
now := time.Now().UTC()
for _, repo := range store.Repositories() {
project := strings.TrimSpace(repo.GongfengProjectID)
- if strings.HasPrefix(project, "github:") {
+ if strings.HasPrefix(project, "github:") || strings.HasPrefix(project, "codeup:") {
continue
}
def := strings.TrimSpace(repo.DefaultBranch)
@@ -233,7 +241,7 @@ func (s *Service) syncWorkCommitsOnDefaultBranch(store MRDeliveryStore) {
}
for _, repo := range store.Repositories() {
project := strings.TrimSpace(repo.GongfengProjectID)
- if strings.HasPrefix(project, "github:") {
+ if strings.HasPrefix(project, "github:") || strings.HasPrefix(project, "codeup:") {
continue
}
def := strings.TrimSpace(repo.DefaultBranch)
diff --git a/internal/tracker/service.go b/internal/tracker/service.go
index 7edf45f75..e9037d150 100644
--- a/internal/tracker/service.go
+++ b/internal/tracker/service.go
@@ -20,6 +20,7 @@ import (
type Service struct {
githubAPIBase string // Tests inject an HTTP server; production uses api.github.com.
gitHostAPIBase string // Tests inject an HTTP server for every Git HTTP credential host.
+ codeupAPIBase string // Tests inject an HTTP server; production uses openapi-rdc.aliyuncs.com.
cfg *syncConfigHolder
gongfeng *MCPClient
tapd *MCPClient
diff --git a/web/app/access.js b/web/app/access.js
index 0a8530fe1..0d3453d4a 100644
--- a/web/app/access.js
+++ b/web/app/access.js
@@ -66,12 +66,13 @@ function gotoCredential(name,sshRemote){
}
// Personal credential fields and the errors they cause. Keep the rules in
// sync with chatbot/src/credentials.js.
-const CREDENTIAL_FIELDS={codeBuddyApiKey:'CodeBuddy API Key',codexApiKey:'Codex API Key',claudeCodeApiKey:'Claude Code API Key',gitToken:'GitHub Git Token',gitSshKey:'Git SSH 密钥',gitHttpCredentials:'Git 访问令牌'};
+const CREDENTIAL_FIELDS={codeBuddyApiKey:'CodeBuddy API Key',codexApiKey:'Codex API Key',claudeCodeApiKey:'Claude Code API Key',gitToken:'GitHub Git Token',codeupToken:'云效 Codeup 仓库授权',gitSshKey:'Git SSH 密钥',gitHttpCredentials:'Git 访问令牌'};
const CREDENTIAL_RULES=[
['codexApiKey',/Codex[^。\n]{0,16}API Key/i],
['claudeCodeApiKey',/Claude Code[^。\n]{0,16}API Key/i],
['codeBuddyApiKey',/CodeBuddy[^。\n]{0,20}(API Key|Key|凭据)|拒绝了你的 API Key/i],
['gitSshKey',/Git SSH (?:密钥|私钥)/i],
+ ['codeupToken',/Codeup|云效[^。\n]{0,12}(令牌|授权|凭据|克隆账号)/i],
['gitToken',/Git Token|工蜂[^。\n]{0,12}令牌|could not read Username|Authentication failed|HTTP Basic: Access denied|terminal prompts disabled|requested URL returned error: 40[13]/i],
];
function credentialHint(text){
diff --git a/web/app/agents.js b/web/app/agents.js
index aa9b56d4b..bc6a9eb0b 100644
--- a/web/app/agents.js
+++ b/web/app/agents.js
@@ -117,7 +117,7 @@ function syncAgentTabIndicators(){$$('#agentsView .agent-tabs, #agentModal .agen
if(typeof document!=='undefined'&&document.fonts?.ready)document.fonts.ready.then(()=>syncAgentTabIndicators()).catch(()=>{});
function pickerHTML(items,selected,prefix){return `${(items||[]).map(x=>``).join('')||'暂无可用资产,请先到对应的资产管理页面添加'}`}
function bindPickerFilters(root){(root||document).querySelectorAll('[data-picker-filter]').forEach(input=>input.oninput=()=>{const q=input.value.trim().toLowerCase();input.parentElement.querySelectorAll('.asset-check').forEach(row=>row.hidden=!!q&&!row.textContent.toLowerCase().includes(q))})}
-function executorOptions(selected){const allowed=new Set(['codebuddy','codex','claude','opencode','cursor','agy','kimi','pi','dsh','zcode']),items=(state.data.executors||[]).filter(x=>allowed.has(x.id)),legacy=selected&&!allowed.has(selected)?``:'';return legacy+items.map(x=>``).join('')}
+function executorOptions(selected){const allowed=new Set(['codebuddy','codex','claude','opencode','cursor','agy','kimi','pi','dsh','zcode','qodercn']),items=(state.data.executors||[]).filter(x=>allowed.has(x.id)),legacy=selected&&!allowed.has(selected)?``:'';return legacy+items.map(x=>``).join('')}
const AGENT_CUSTOM_MODEL='__custom__';
let executorModelCatalogUser, executorModelCatalogRequest, agentModelRevision=0;
function executorModelCatalogs(){
diff --git a/web/app/assistant-models.js b/web/app/assistant-models.js
index ee9f6daad..219e66b72 100644
--- a/web/app/assistant-models.js
+++ b/web/app/assistant-models.js
@@ -29,7 +29,7 @@
const CLI_ICON = {
codebuddy:'codebuddy.svg', codex:'codex.svg', 'claude-code':'claude.svg',
opencode:'opencode.svg', cursor:'cursor.svg', agy:'antigravity.svg',
- kimi:'kimi-code.png', pi:'pi.svg', dsh:'deepseek.svg', zcode:'glm.svg'
+ kimi:'kimi-code.png', pi:'pi.svg', dsh:'deepseek.svg', zcode:'glm.svg', qodercn:'qoder.svg'
};
let catalog = {
default: DEFAULT_MODEL,
diff --git a/web/app/codeup-connect.js b/web/app/codeup-connect.js
new file mode 100644
index 000000000..b5ea0162e
--- /dev/null
+++ b/web/app/codeup-connect.js
@@ -0,0 +1,152 @@
+// 云效 Codeup 仓库授权:PAT + HTTPS 克隆账号校验 → 组织选择 → 仓库选择器。
+// Mirrors github-connect.js, but Codeup has no OAuth device flow: the personal
+// access token is verified and saved as the per-host Git HTTPS credential for
+// codeup.aliyun.com (platform=codeup) before repositories can be listed.
+const CODEUP_HOST='codeup.aliyun.com';
+
+function codeupCredentialRecordForPicker(){
+ const user=state.currentUser;
+ if(!user?.id||user.isGuest)return null;
+ if(typeof codeupCredentialRecord==='function')return codeupCredentialRecord(user);
+ const cached=state.codeupCredential;
+ return cached&&Number(cached.userId)===Number(user.id)?cached.record||null:null;
+}
+function codeupPickerConfigured(){
+ return !!(userById(state.currentUser?.id)?.codeupCredentialConfigured||codeupCredentialRecordForPicker());
+}
+function codeupOrganizationKey(){return 'agentflow.codeup.organization.'+(state.currentUser?.id||'')}
+function codeupStoredOrganization(){try{return localStorage.getItem(codeupOrganizationKey())||''}catch{return ''}}
+function codeupRememberOrganization(id){try{id?localStorage.setItem(codeupOrganizationKey(),id):localStorage.removeItem(codeupOrganizationKey())}catch{}}
+
+function codeupConnectHTML(){
+ return `
+ 使用云效 Codeup 的个人访问令牌(PAT)与 HTTPS 克隆账号连接,即可选择组织内的仓库。令牌在「个人设置 → 个人访问令牌」创建,克隆账号在「个人设置 → HTTPS 密码」查看。
+
+
+
+
+ `;
+}
+
+function mountCodeupRepoPicker(host,onSelect){
+ if(!host)return;
+ const connected=codeupPickerConfigured();
+ host.innerHTML=(connected?'':codeupConnectHTML())
+ +``
+ +``
+ +`连接后可选择组织内的仓库;也可以直接粘贴 https://codeup.aliyun.com/组织ID/仓库.git 地址。
`
+ +'';
+ const orgRow=host.querySelector('[data-codeup-org-row]'),orgSelect=host.querySelector('[data-codeup-org]'),orgStatus=host.querySelector('[data-codeup-org-status]');
+ const load=host.querySelector('[data-codeup-load]'),list=host.querySelector('[data-codeup-repo-list]');
+ let repositories=[],page=1,busy=false,organizationId='';
+
+ // The Codeup OpenAPI returns pathWithNamespace/webUrl/httpUrlToRepo; normalize
+ // to the GitHub-picker shape (full_name/html_url/clone_url/default_branch).
+ const normalize=repo=>{
+ let full=String(repo.full_name||repo.pathWithNamespace||repo.path||repo.name||'');
+ if(organizationId&&!full.startsWith(organizationId+'/'))full=organizationId+'/'+full;
+ return {...repo,full_name:full,html_url:repo.html_url||repo.webUrl||`https://${CODEUP_HOST}/${full}`,clone_url:repo.clone_url||repo.httpUrlToRepo||`https://${CODEUP_HOST}/${full}.git`,default_branch:repo.default_branch||repo.defaultBranch||'main'};
+ };
+ const paint=hasMore=>{
+ list.innerHTML='未找到仓库,可手动填写地址;请确认令牌有组织内仓库的读取权限。
'+(hasMore?'':'');
+ const select=list.querySelector('[data-codeup-repo]'),search=list.querySelector('[data-codeup-search]'),empty=list.querySelector('[data-codeup-repo-empty]');
+ const filter=()=>{
+ select.replaceChildren(new Option('请选择仓库',''));
+ const visible=repositories.filter(repo=>String(repo.full_name||'').toLowerCase().includes(search.value.toLowerCase()));
+ for(const repository of visible){const option=document.createElement('option');option.value=repository.full_name;option.textContent=repository.full_name+(repository.private?' · 私有':'');select.append(option)}
+ empty.hidden=visible.length>0;
+ };
+ search.oninput=filter;
+ select.onchange=()=>{
+ const repository=repositories.find(repo=>repo.full_name===select.value);
+ if(repository)onSelect({...repository,clone_url:repository.clone_url||`https://${CODEUP_HOST}/${repository.full_name}.git`});
+ };
+ const more=list.querySelector('[data-codeup-more]');if(more)more.onclick=()=>fetchPage(page+1);
+ filter();
+ };
+ const fetchPage=async requested=>{
+ if(busy||!organizationId)return;
+ busy=true;load.disabled=true;
+ const actor=Number(state.currentUser?.id);
+ const more=list.querySelector('[data-codeup-more]');if(more)more.disabled=true;
+ try{
+ const result=await api(`/api/auth/codeup/repositories?organizationId=${encodeURIComponent(organizationId)}&page=`+requested);
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor)return;
+ const rows=(Array.isArray(result?.repositories)?result.repositories:[]).map(normalize);
+ page=requested;repositories=requested===1?rows:repositories.concat(rows);
+ paint(!!result?.hasMore);
+ }catch(error){list.textContent=error.message}
+ finally{busy=false;load.disabled=false;if(more)more.disabled=false}
+ };
+ const chooseOrganization=id=>{
+ organizationId=String(id||'').trim();
+ codeupRememberOrganization(organizationId);
+ repositories=[];page=1;list.innerHTML='';
+ if(organizationId)fetchPage(1);
+ };
+ const orgManualHTML=message=>`${escapeHTML(message||'')}
`;
+ const bindManualOrg=()=>{
+ const input=orgRow.querySelector('[data-codeup-org-manual]'),apply=orgRow.querySelector('[data-codeup-org-apply]');
+ if(!input||!apply)return;
+ const status=orgRow.querySelector('[data-codeup-org-status]');
+ apply.onclick=()=>{
+ const id=input.value.trim();
+ if(!id){if(status)status.textContent='请填写组织 ID';return}
+ chooseOrganization(id);
+ };
+ };
+ const fetchOrganizations=async()=>{
+ const actor=Number(state.currentUser?.id);
+ orgStatus.textContent='正在读取组织…';
+ try{
+ const result=await api('/api/auth/codeup/organizations',{silent:true});
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor)return;
+ const organizations=Array.isArray(result)?result:(Array.isArray(result?.organizations)?result.organizations:[]);
+ if(!organizations.length)throw new Error('没有可用的组织');
+ orgSelect.replaceChildren(new Option('请选择组织',''));
+ for(const organization of organizations){
+ const id=String(organization.id??organization.organizationId??'');
+ if(!id)continue;
+ orgSelect.append(new Option(organization.name?`${organization.name}(${id})`:id,id));
+ }
+ orgStatus.textContent='';
+ const stored=codeupStoredOrganization();
+ if(stored&&[...orgSelect.options].some(option=>option.value===stored)){orgSelect.value=stored;chooseOrganization(stored)}
+ orgSelect.onchange=()=>chooseOrganization(orgSelect.value);
+ }catch(error){
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor)return;
+ // The organization listing may be unavailable; a manually pasted organization ID keeps the picker usable.
+ orgRow.innerHTML=orgManualHTML(`组织列表暂不可用(${error.message}),可手动填写组织 ID。`);
+ bindManualOrg();
+ }
+ };
+ load.onclick=()=>{if(organizationId)fetchPage(1);else fetchOrganizations()};
+
+ const connect=host.querySelector('[data-codeup-connect]');
+ if(connect){
+ const button=connect.querySelector('[data-codeup-start]'),status=connect.querySelector('[data-codeup-status]');
+ const username=connect.querySelector('[data-codeup-username]'),token=connect.querySelector('[data-codeup-token]');
+ button.onclick=async()=>{
+ if(button.disabled)return;
+ const account=username.value.trim(),pat=token.value.trim();
+ if(!account||!pat){status.textContent='请填写 HTTPS 克隆账号和个人访问令牌';return}
+ button.disabled=true;status.textContent='正在校验令牌…';
+ try{
+ const outcome=typeof verifyAndSaveCodeupToken==='function'
+ ?await verifyAndSaveCodeupToken(pat,account)
+ :{saved:false,result:{error:'凭据模块尚未加载'}};
+ if(!outcome?.saved){status.textContent=(outcome?.result&&(outcome.result.error||gitTokenFailure(outcome.result)))||'云效令牌校验未通过';button.disabled=false;return}
+ token.value='';
+ connect.remove();
+ host.querySelector('[data-codeup-repo-hint]').hidden=true;
+ orgRow.hidden=false;load.hidden=false;
+ status.textContent='';
+ toast('云效 Codeup 授权已保存','ok');
+ host.dispatchEvent(new CustomEvent('codeup-connected',{bubbles:true}));
+ fetchOrganizations();
+ }catch(error){status.textContent=error.message;button.disabled=false}
+ };
+ }else if(connected){
+ fetchOrganizations();
+ }
+}
\ No newline at end of file
diff --git a/web/app/flow-canvas.css b/web/app/flow-canvas.css
index 32ba62c74..6c306ab8f 100644
--- a/web/app/flow-canvas.css
+++ b/web/app/flow-canvas.css
@@ -437,7 +437,7 @@ html[data-theme="dark"] #flowView .fd-toast button{background:rgba(0,0,0,.06);co
#aiOrchestrator .ai-model-toggle .ai-model-caret{flex:none;margin-left:auto;border-top-color:var(--hui-tertiary)}
#aiOrchestrator .ai-model-toggle:disabled{opacity:.45;cursor:default}
#aiOrchestrator #aiOrchestratorCLIPicker .ai-model-icon{background:transparent;color:var(--hui-muted)}
-html[data-theme="dark"] #aiOrchestrator :is([data-cli="codex"],[data-cli="claude-code"],[data-cli="opencode"],[data-cli="cursor"],[data-cli="pi"]) img{filter:invert(1)}
+html[data-theme="dark"] #aiOrchestrator :is([data-cli="codex"],[data-cli="claude-code"],[data-cli="opencode"],[data-cli="cursor"],[data-cli="pi"],[data-cli="qodercn"]) img{filter:invert(1)}
#aiOrchestrator .ai-model-menu{position:fixed;right:auto;z-index:var(--hui-z-popover);max-width:calc(100vw - 16px);overflow:auto;border:1px solid var(--hui-border);border-radius:12px;background:var(--hui-surface);color:var(--hui-text);box-shadow:var(--hui-popover-shadow)}
#aiOrchestrator .ai-model-menu [data-model-search]{position:sticky;top:0;z-index:1;box-sizing:border-box;width:100%;height:38px;margin:0;padding:0 12px;border:0;border-bottom:1px solid var(--hui-border);border-radius:0;outline:0;background:var(--hui-surface);color:var(--hui-text);font:inherit;font-size:13px;box-shadow:none}
#aiOrchestrator .ai-model-menu [role=listbox]{padding:4px}
diff --git a/web/app/git-http-credentials.js b/web/app/git-http-credentials.js
index 082b0b2f7..3c40b7aec 100644
--- a/web/app/git-http-credentials.js
+++ b/web/app/git-http-credentials.js
@@ -1,4 +1,4 @@
-const GIT_HTTP_PLATFORMS = [['github', 'GitHub / GitHub Enterprise'], ['gitlab', 'GitLab'], ['other', '其他平台']];
+const GIT_HTTP_PLATFORMS = [['github', 'GitHub / GitHub Enterprise'], ['gitlab', 'GitLab'], ['codeup', '云效 Codeup'], ['other', '其他平台']];
// Mirrors gitwork.HTTPSHostScope closely enough to prefill the form; the server
// remains the authority on what a host scope is.
@@ -9,6 +9,9 @@ function gitHTTPHostScope(raw) {
}
function gitHTTPDefaultUsername(platform) {
+ // Codeup authenticates with the personal HTTPS clone account; there is no
+ // shared placeholder username like x-access-token / oauth2.
+ if (platform === 'codeup') return '';
return platform === 'gitlab' ? 'oauth2' : 'x-access-token';
}
@@ -48,7 +51,7 @@ function openGitHTTPCredentials() {
${GIT_HTTP_PLATFORMS.map(([value, label]) => ``).join('')}
- GitHub 和 GitLab 支持 gh / glab 认证和 PR/MR 合并状态同步。其他平台也可由 Agent 创建 PR/MR,合并状态请到托管平台查看。
+ GitHub 和 GitLab 支持 gh / glab 认证和 PR/MR 合并状态同步。云效 Codeup 使用个人访问令牌(PAT)与 HTTPS 克隆账号。其他平台也可由 Agent 创建 PR/MR,合并状态请到托管平台查看。
${credentialFieldHTML({label:'名称', name:'name', type:'text', placeholder:'例如 公司 GitLab', hint:null})}
${credentialFieldHTML({label:'Git 认证用户名', name:'username', type:'text', placeholder:'x-access-token', hint:'按托管平台要求填写;这是 HTTPS 认证用户名,不是提交作者名,通常无法从 Token 推导。'})}
@@ -77,6 +80,16 @@ function openGitHTTPCredentials() {
status.hidden = !message;
}
+ // Codeup names its two secrets differently: the HTTPS clone account and the PAT.
+ function syncPlatformLabels() {
+ const codeup = platform.value === 'codeup';
+ const labelOf = input => input.closest('.credential-field')?.querySelector('span');
+ const usernameLabel = labelOf(username), tokenLabel = labelOf(token);
+ if (usernameLabel) usernameLabel.textContent = codeup ? 'HTTPS 克隆账号' : 'Git 认证用户名';
+ if (tokenLabel) tokenLabel.textContent = codeup ? '个人访问令牌 PAT' : '个人访问令牌';
+ username.placeholder = codeup ? '云效「个人设置 → HTTPS 密码」中的克隆账号' : gitHTTPDefaultUsername(platform.value);
+ }
+
function credentialSummary(cred) {
const platformLabel = (GIT_HTTP_PLATFORMS.find(([value]) => value === cred.platform) || [, cred.platform])[1];
const tags = [platformLabel, cred.managed ? '平台托管' : ''].filter(Boolean);
@@ -109,7 +122,7 @@ function openGitHTTPCredentials() {
platform.value = cred?.platform || 'github';
name.value = cred?.name || '';
username.value = cred?.username || '';
- username.placeholder = gitHTTPDefaultUsername(platform.value);
+ syncPlatformLabels();
token.required = !cred;
token.placeholder = cred ? '留空保留现有令牌' : '粘贴个人访问令牌';
(cred ? name : host).focus();
@@ -137,7 +150,9 @@ function openGitHTTPCredentials() {
creds = await api(id ? `${endpoint}/${encodeURIComponent(id)}` : endpoint, {
method, silent:true, ...(body ? {body:JSON.stringify(body)} : {}),
});
- storeCredentialUser({...credentialUser(), id:user.id, gitHttpCredentialsConfigured:creds.length > 0, gitHubCredentialConfigured:creds.some(credential=>credential.host==='github.com')});
+ const codeupRecord = creds.find(credential => credential.host === 'codeup.aliyun.com') || null;
+ state.codeupCredential = {userId:user.id, record:codeupRecord};
+ storeCredentialUser({...credentialUser(), id:user.id, gitHttpCredentialsConfigured:creds.length > 0, gitHubCredentialConfigured:creds.some(credential=>credential.host==='github.com'), codeupCredentialConfigured:!!codeupRecord});
renderCredentialPanel();
notifyCredentialsChanged();
deleting = '';
@@ -186,13 +201,25 @@ function openGitHTTPCredentials() {
if (editing) return;
const scope = gitHTTPHostScope(host.value);
if (scope === 'github.com') platform.value = 'github';
+ else if (scope === 'codeup.aliyun.com') platform.value = 'codeup';
else if (/(^|\.)gitlab\./.test(scope)) platform.value = 'gitlab';
- username.placeholder = gitHTTPDefaultUsername(platform.value);
- if (!name.value.trim()) name.value = scope;
+ syncPlatformLabels();
+ if (!name.value.trim()) name.value = platform.value === 'codeup' ? '云效 Codeup' : scope;
+ });
+ platform.addEventListener('change', () => {
+ if (!editing && platform.value === 'codeup') {
+ if (!host.value.trim()) host.value = 'codeup.aliyun.com';
+ if (!name.value.trim()) name.value = '云效 Codeup';
+ }
+ syncPlatformLabels();
});
- platform.addEventListener('change', () => { username.placeholder = gitHTTPDefaultUsername(platform.value); });
form.onsubmit = event => {
event.preventDefault();
+ if (platform.value === 'codeup' && !username.value.trim()) {
+ setStatus('请填写云效 HTTPS 克隆账号', true);
+ username.focus();
+ return;
+ }
const body = {
host:host.value, platform:platform.value, name:name.value,
username:username.value.trim() || gitHTTPDefaultUsername(platform.value),
diff --git a/web/app/git-ssh.js b/web/app/git-ssh.js
index 01ba6ebd3..89384ed8c 100644
--- a/web/app/git-ssh.js
+++ b/web/app/git-ssh.js
@@ -38,13 +38,36 @@ globalThis.LoopForgeGitSSH = function parseSSHRepository(raw) {
return { provider: 'ssh', host: endpoint, project: `${host.toLowerCase()}${port === '22' ? '' : ':' + port}/${segments.join('/')}`, name, cloneUrl, webUrl: '' };
};
+// Yunxiao Codeup keeps the organization in the first path segment:
+// https://codeup.aliyun.com/{orgId}/{group}/{repo}.git. Mirrors the server's
+// parseCodeupRepositoryURL: the codeup: shorthand and git@/ssh:// clone forms
+// normalize to the HTTPS identity, authenticated with the per-host Codeup
+// PAT + clone account.
+globalThis.LoopForgeCodeupRepo = function parseCodeupRepository(raw) {
+ let s = String(raw || '').trim().replace(/^git\s+clone\s+/i, '').trim().replace(/^['"]+|['"]+$/g, '');
+ if (!s) return null;
+ if (/^codeup:/i.test(s)) s = 'https://codeup.aliyun.com/' + s.slice('codeup:'.length);
+ s = s.replace(/^(?:git@codeup\.aliyun\.com:|ssh:\/\/git@codeup\.aliyun\.com(?::22)?\/)/i, 'https://codeup.aliyun.com/');
+ if (/^codeup\.aliyun\.com\//i.test(s)) s = 'https://' + s;
+ let u;
+ try { u = new URL(s); } catch { return null; }
+ if (u.hostname.toLowerCase() !== 'codeup.aliyun.com' || u.username || u.password || !['https:', 'http:'].includes(u.protocol)) return null;
+ const parts = u.pathname.replace(/^\/+|\/+$/g, '').split('/');
+ if (parts.length < 3) return null;
+ parts[parts.length - 1] = parts[parts.length - 1].replace(/\.git$/i, '');
+ const path = parts.join('/');
+ if (!/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+){2,}$/.test(path) || parts.some(seg => seg === '.' || seg === '..')) return null;
+ const name = parts[parts.length - 1];
+ return { provider: 'codeup', host: 'codeup.aliyun.com', organizationId: parts[0], project: 'codeup:' + path, name, webUrl: 'https://codeup.aliyun.com/' + path, cloneUrl: 'https://codeup.aliyun.com/' + path + '.git' };
+};
+
// Unknown HTTPS hosts use Git transport without identifying the hosting product.
globalThis.LoopForgeGitHTTPS = function parseHTTPSRepository(raw) {
const address=String(raw||'').trim().replace(/^git clone\s+/i,'');
if(!/^https:\/\//i.test(address)||/[\s\\]/.test(address))return null;
try{
const u=new URL(address),host=u.host.toLowerCase();
- if(u.username||u.password||u.search||u.hash||['github.com','git.example.com'].includes(u.hostname.toLowerCase()))return null;
+ if(u.username||u.password||u.search||u.hash||['github.com','git.example.com','codeup.aliyun.com'].includes(u.hostname.toLowerCase()))return null;
if(!/^[a-z0-9][a-z0-9.-]*(?::[0-9]+)?$/i.test(host)||u.hostname.includes('..')||/^\d+(?:\.\d+){3}$/.test(u.hostname))return null;
const parts=u.pathname.replace(/^\/+|\/+$/g,'').split('/');
if(parts.some(part=>!part||decodeURIComponent(part)==='.'||decodeURIComponent(part)==='..'))return null;
diff --git a/web/app/issues.js b/web/app/issues.js
index ec57b47bd..0be8b4c3b 100644
--- a/web/app/issues.js
+++ b/web/app/issues.js
@@ -544,8 +544,9 @@ function issueFromForm(){
// 就能完成仓库配置。
// repoDisplayPath shows host/path for a parsed repository, e.g. github.com/owner/name.
function repoDisplayPath(info,fallback=''){return info?.provider==='ssh'?(info.project||info.cloneUrl||fallback):info?.webUrl?String(info.webUrl).replace(/^https?:\/\//,''):String(fallback||'')}
-function repoProviderLabel(info){return info?.provider==='ssh'?'Git SSH':info?.provider==='github'?'GitHub':'工蜂'}
+function repoProviderLabel(info){return info?.provider==='ssh'?'Git SSH':info?.provider==='github'?'GitHub':info?.provider==='codeup'?'云效 Codeup':'工蜂'}
function parseGongfengRepoURL(raw){
+ const codeupInfo=globalThis.LoopForgeCodeupRepo?.(raw);if(codeupInfo)return codeupInfo;
const httpsInfo=globalThis.LoopForgeGitHTTPS?.(raw);if(httpsInfo)return httpsInfo;
const sshInfo=globalThis.LoopForgeGitSSH?.(raw);if(sshInfo)return sshInfo;
let publicURL=String(raw||'').trim().replace(/^git clone /,'').replace(/^github:/,'https://github.com/').replace(/^(?:git@github\.com:|ssh:\/\/git@github\.com(?::22)?\/)/,'https://github.com/');
@@ -601,13 +602,18 @@ function renderRepositoryCredentialHint(){
host.sshHintVersion=(host.sshHintVersion||0)+1;
host.hidden=false;
host.removeAttribute('role');
- const configured=!!user.gitHttpCredentialsConfigured;
- const title=configured?'已配置 Git 访问令牌':'仓库可以先保存,代码任务还需要 Token';
- const message=configured?'请确认 Token 已获得目标仓库的访问和写入权限。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。':'使用仓库进行需求分析、访问私有代码或提交 PR 前,请先配置 Git 访问令牌。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。';
+ const codeup=remote?.provider==='codeup';
+ const configured=codeup?!!(user.codeupCredentialConfigured||(typeof codeupCredentialRecord==='function'&&codeupCredentialRecord(user))):!!user.gitHttpCredentialsConfigured;
+ const title=codeup
+ ?(configured?'已配置云效仓库授权':'仓库可以先保存,代码任务还需要云效授权')
+ :(configured?'已配置 Git 访问令牌':'仓库可以先保存,代码任务还需要 Token');
+ const message=codeup
+ ?(configured?'请确认令牌已获得目标仓库的读写权限。SOP 使用需求责任人的令牌,未指定时使用项目 Owner 的令牌。':'使用云效仓库进行需求分析、访问私有代码或提交合并请求前,请先配置云效仓库授权(个人访问令牌 PAT + HTTPS 克隆账号)。SOP 使用需求责任人的凭据,未指定时使用项目 Owner 的凭据。')
+ :(configured?'请确认 Token 已获得目标仓库的访问和写入权限。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。':'使用仓库进行需求分析、访问私有代码或提交 PR 前,请先配置 Git 访问令牌。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。');
host.dataset.configured=String(configured);
- host.innerHTML=`${escapeHTML(title)}${escapeHTML(message)}
`;
+ host.innerHTML=`${escapeHTML(title)}${escapeHTML(message)}
`;
host.querySelector('[data-repository-configure-token]').onclick=()=>{
- $('#repositoryModal').classList.remove('open');gotoCredential('gitHttpCredentials');
+ $('#repositoryModal').classList.remove('open');gotoCredential(codeup?'codeupToken':'gitHttpCredentials');
};
}
function renderRepositoryList(){renderRepositoryCredentialHint();const project=(state.data.projects||[]).find(p=>p.id===state.projectFilter),repos=(state.data.repositories||[]).filter(r=>r.projectId===state.projectFilter);$('#repositoryProjectHint').textContent=`当前项目:${project?.name||'—'}。粘贴 GitHub 链接或 Git SSH 地址;集成分支用于检查多个 SOP 执行后是否存在合并冲突,可留空。`;$('#repositoryList').innerHTML=repos.map(r=>``).join('')||'当前项目还没有绑定代码仓库。
';$('#repositoryList').querySelectorAll('[data-edit-repo]').forEach(b=>b.onclick=()=>fillRepositoryForm((state.data.repositories||[]).find(r=>r.id===b.dataset.editRepo)))}
diff --git a/web/app/project-wizard.js b/web/app/project-wizard.js
index 17960c0b7..636055bcc 100644
--- a/web/app/project-wizard.js
+++ b/web/app/project-wizard.js
@@ -3,7 +3,7 @@
// and can be skipped. Progress lives only in memory.
const PROJECT_WIZARD_STEPS=[
{id:'basic',title:'基本信息',desc:'名称与默认 SOP'},
- {id:'repos',title:'代码仓库',desc:'绑定 GitHub 仓库'},
+ {id:'repos',title:'代码仓库',desc:'绑定 GitHub / 云效仓库'},
{id:'members',title:'项目成员',desc:'Owner 与协作成员'},
{id:'tapd',title:'TAPD 集成',desc:'可选,导入 TAPD 需求'},
{id:'done',title:'完成',desc:'开始使用新项目'},
@@ -104,7 +104,7 @@ async function projectWizardCreate(){
async function projectWizardAddRepo(){
const w=projectWizard,project=projectWizardProject();if(!w||w.saving||!project)return false;
const url=String(w.repo.url||'').trim(),info=parseGongfengRepoURL(url);
- if(!info)return projectWizardFail(url?'请输入 GitHub 链接或有效的 Git SSH 地址。CNB 只支持 HTTPS + 访问令牌。':'请先粘贴 GitHub 链接或 Git SSH 地址','repoUrl');
+ if(!info)return projectWizardFail(url?'请输入 GitHub 链接或有效的 Git SSH 地址。云效 Codeup 仓库请粘贴 HTTPS 链接;CNB 只支持 HTTPS + 访问令牌。':'请先粘贴 GitHub、云效 Codeup 链接或 Git SSH 地址','repoUrl');
if(projectWizardRepos().some(r=>info.provider==='ssh'?r.cloneUrl===info.cloneUrl:r.gongfengProjectId===info.project))return projectWizardFail(`仓库 ${info.project} 已经绑定到这个项目`,'repoUrl');
const payload={projectId:project.id,provider:info.provider||'gongfeng',name:info.name,gongfengProjectId:info.project,webUrl:info.webUrl,cloneUrl:info.cloneUrl,defaultBranch:String(w.repo.branch||'').trim()||'main',integrateBranch:String(w.repo.integrate||'').trim(),localPath:'',repoUrl:url};
const makeDefault=projectNeedsDefaultRepository(project);
@@ -244,16 +244,18 @@ function projectWizardBasicHTML(w){
}
function projectWizardRepoHint(url){
const raw=String(url||'').trim(),info=raw?parseGongfengRepoURL(raw):null;
- if(!raw)return '例如 https://github.com/owner/repo 或 git@gitlab.com:group/repo.git';
+ if(!raw)return '例如 https://github.com/owner/repo、https://codeup.aliyun.com/组织ID/仓库.git 或 git@gitlab.com:group/repo.git';
if(info?.provider==='ssh')return `识别为 Git SSH · ${escapeHTML(info.name)}。请平台管理员在「平台管理 → Git SSH 主机信任」登记主机公钥,并在个人配置中添加 Git SSH 密钥。`;
- return info?`识别为 ${escapeHTML(info.name)} · ${escapeHTML(repoDisplayPath(info,info.project))}`:'请输入 GitHub 链接或 Git SSH 地址';
+ if(info?.provider==='codeup')return `识别为云效 Codeup · ${escapeHTML(info.name)}。克隆与推送使用个人配置中的云效仓库授权(PAT + HTTPS 克隆账号)。`;
+ return info?`识别为 ${escapeHTML(info.name)} · ${escapeHTML(repoDisplayPath(info,info.project))}`:'请输入 GitHub、云效 Codeup 链接或 Git SSH 地址';
}
function projectWizardReposHTML(w){
const project=projectWizardProject()||{},repos=projectWizardRepos();
const list=repos.map(r=>{const path=r.cloneUrl||r.gongfengProjectId||'',name=r.name||path||r.id,shown=repoDisplayPath(parseGongfengRepoURL(r.provider==='ssh'?r.cloneUrl:r.webUrl||path),path);return `${pwIcon('repo',14,1.9)}${escapeHTML(name)}${escapeHTML(shown)}${escapeHTML(r.defaultBranch||'main')}${r.integrateBranch?`${escapeHTML(r.integrateBranch)}`:''}${r.id===project.defaultRepositoryId?'默认':''}`}).join('');
const body=(list?`${list}`:'')
+''
- +pwField('GitHub 链接或 Git SSH 地址',``,{for:'pwRepoUrl',hint:projectWizardRepoHint(w.repo.url),hintAttrs:' data-pw-repo-hint'})
+ +''
+ +pwField('GitHub / 云效链接或 Git SSH 地址',``,{for:'pwRepoUrl',hint:projectWizardRepoHint(w.repo.url),hintAttrs:' data-pw-repo-hint'})
+`${pwField('主分支',``,{for:'pwRepoBranch'})}${pwField('集成分支',``,{for:'pwRepoIntegrate'})}`
+``;
return projectWizardHeadHTML(w,'代码仓库','Agent 执行 SOP 时会克隆这些仓库并在工作分支上提交。第一个仓库会自动设为默认。')
@@ -342,6 +344,11 @@ function renderProjectWizard(){
const url=host.querySelector('[name="repoUrl"]'),branch=host.querySelector('[name="repoBranch"]');
url.value=w.repo.url;branch.value=w.repo.branch;syncProjectWizardField(url);
});
+ if(w.step==='repos'&&typeof mountCodeupRepoPicker==='function')mountCodeupRepoPicker(host.querySelector('[data-codeup-repositories]'),repository=>{
+ w.repo.url=repository.html_url||repository.clone_url;w.repo.branch=repository.default_branch||'main';
+ const url=host.querySelector('[name="repoUrl"]'),branch=host.querySelector('[name="repoBranch"]');
+ url.value=w.repo.url;branch.value=w.repo.branch;syncProjectWizardField(url);
+ });
focusProjectWizard();
}
function focusProjectWizard(){
diff --git a/web/app/repo_drawer.js b/web/app/repo_drawer.js
index b36393301..94b0baecb 100644
--- a/web/app/repo_drawer.js
+++ b/web/app/repo_drawer.js
@@ -53,6 +53,11 @@ function openRepoDrawer(repoId=''){
f.elements.defaultBranch.value=repository.default_branch||'main';
syncRepoDrawerDetect();
});
+ if(typeof mountCodeupRepoPicker==='function')mountCodeupRepoPicker(drawer.querySelector('[data-codeup-repositories]'),repository=>{
+ f.elements.repoUrl.value=repository.html_url||repository.clone_url;
+ f.elements.defaultBranch.value=repository.default_branch||'main';
+ syncRepoDrawerDetect();
+ });
setTimeout(()=>f.elements.repoUrl.focus(),120);
}
function closeRepoDrawer(opt){
diff --git a/web/app/runners.js b/web/app/runners.js
index f625de4da..adba4c4f5 100644
--- a/web/app/runners.js
+++ b/web/app/runners.js
@@ -56,12 +56,13 @@ function runnerStatusLabel(status,lastSeen){
const style=status==='online'?' online':status==='offline'?' offline':'';
return `${escapeHTML(label)}`;
}
-const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'};
+const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode',qodercn:'Qoder CN'};
const runnerAuthLabel={local:'账号登录',personal:'API Key'};
const runnerAuthDescription={local:'Claude Code、Codex 和 Antigravity 可以使用运行 Runner 的系统账号在这台机器上的已有登录,对话与 SOP 的 native、Docker 沙箱均可复用。共享对话中,只有机器所有者发言时会使用此登录。',personal:'读取「个人配置」中保存的 API Key。对话使用当前发言人的 Key,SOP 使用运行责任人的 Key。Antigravity 的 Gemini API Key 按 API 单独计费。'};
const runnerOSLabels={darwin:'macOS',linux:'Linux',windows:'Windows'};
function runnerKeyDescription(provider){
if(provider==='zcode')return 'GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。';
+ if(provider==='qodercn')return 'Qoder CN 使用个人访问令牌(PAT),请在「个人配置」中填写。模型可选,未选择时使用 CLI 默认模型。';
return '该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。';
}
function runnerPersonalCredentialConfigured(provider){
diff --git a/web/app/sops.js b/web/app/sops.js
index 0a125d6d4..d462198eb 100644
--- a/web/app/sops.js
+++ b/web/app/sops.js
@@ -99,9 +99,9 @@ function sopRunRequirements(w){
const role=(state.data?.agents||[]).find(a=>a.id===node.agentId);
const id=role?.executorId||node.executorId||'codebuddy';
const kind=(state.data?.executors||[]).find(e=>e.id===id)?.kind||id;
- if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh','zcode'].includes(kind))providers.add(kind==='claude'?'claude-code':kind);
+ if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh','zcode','qodercn'].includes(kind))providers.add(kind==='claude'?'claude-code':kind);
}
- const agentLabels={opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'};
+ const agentLabels={opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode',qodercn:'Qoder CN'};
for(const kind of providers){
const known={codebuddy:['CodeBuddy','codeBuddyApiKey','codeBuddyApiKeyConfigured'],codex:['Codex','codexApiKey','codexApiKeyConfigured'],'claude-code':['Claude Code','claudeCodeApiKey','claudeCodeApiKeyConfigured']}[kind];
const [label,field,flag]=known||[agentLabels[kind]||kind,'agentCli.'+kind,'agentCliConfigured'];
diff --git a/web/app/workbench.js b/web/app/workbench.js
index 1b210afda..a814325b4 100644
--- a/web/app/workbench.js
+++ b/web/app/workbench.js
@@ -62,6 +62,13 @@ const CREDENTIAL_KINDS=[
guide:[['打开 GitHub「Settings → Developer settings → Personal access tokens」','https://github.com/settings/tokens','前往 GitHub 申请个人访问令牌'],['新建令牌,为目标仓库授予 Contents 和 Pull requests 的读写权限'],['复制令牌粘贴到下方,保存前会自动校验权限']],
placeholder:'请输入个人访问令牌(PAT)',hint:'保存前会先校验令牌有效性与权限',
impact:'依赖私有仓库的 SOP 将无法克隆或推送仓库。'},
+ {key:'codeupToken',group:'platform',name:'云效 Codeup',short:'云效仓库授权',logo:'codeup',monochrome:true,
+ use:'克隆云效私有仓库、创建任务分支、推送交付产物',
+ description:'用于克隆云效 Codeup 私有仓库、创建任务分支及推送交付产物,使用个人访问令牌(PAT)与 HTTPS 克隆账号认证。',
+ guide:[['打开云效 Codeup「个人设置 → 个人访问令牌」,新建令牌并授予代码读写权限','https://help.aliyun.com/zh/yunxiao/user-guide/personal-authentication-settings/','查看云效认证设置说明'],['在「个人设置 → HTTPS 密码」查看 HTTPS 克隆账号'],['填写克隆账号并粘贴令牌,保存前会自动校验']],
+ placeholder:'请输入云效个人访问令牌(PAT)',hint:'保存前会先校验令牌有效性与权限',
+ extra:{name:'codeupCloneUsername',label:'HTTPS 克隆账号',placeholder:'云效「HTTPS 密码」页的克隆账号',required:()=>true,requiredMessage:'请填写 HTTPS 克隆账号'},
+ impact:'依赖云效私有仓库的 SOP 将无法克隆或推送仓库。'},
{key:'gitSshKey',group:'platform',name:'Git SSH',short:'Git SSH 密钥',icon:'key',
use:'SSH 密钥用于克隆和推送;创建 PR/MR 需要访问令牌',dialog:()=>openGitSSHKeys(),action:'管理密钥'},
{key:'gitHttpCredentials',group:'platform',name:'Git HTTPS',short:'Git 访问令牌',icon:'lock',
@@ -107,14 +114,18 @@ const CREDENTIAL_KINDS=[
note:'未填写 Base URL 时连接 DeepSeek 官方服务。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),
agentCliCredentialKind('zcode',{name:'ZCode',logo:'glm',baseUrl:'https://open.bigmodel.cn/api/anthropic',
note:'未填写 Base URL 时连接智谱 BigModel 的 Anthropic 兼容服务(Messages)。',protocols:[['messages','Messages(Anthropic)'],['chat','Chat Completions'],['responses','Responses']]}),
+ agentCliCredentialKind('qodercn',{name:'Qoder CN',logo:'qoder',monochrome:true,
+ short:'Qoder CN Personal Access Token',placeholder:'请输入 Qoder CN 个人访问令牌(PAT)',
+ note:'使用个人访问令牌(PAT)认证;模型可选,未选择时使用 CLI 默认模型。',
+ guide:[['在 Qoder CN 的个人设置中创建个人访问令牌(PAT)'],['复制令牌粘贴到下方保存']]}),
];
function agentCliCredentialKind(cli,o){
const field=`agentCli.${cli}.`,configurable=!!o.protocols;
- return {key:`agentCli.${cli}`,agentCli:cli,group:'model',name:o.name,short:`${o.name} API Key`,logo:o.logo,monochrome:!!o.monochrome,
+ return {key:`agentCli.${cli}`,agentCli:cli,group:'model',name:o.name,short:o.short||`${o.name} API Key`,logo:o.logo,monochrome:!!o.monochrome,
use:`AI 对话的 ${o.name} 模型与以 ${o.name} 运行的 SOP 节点`,
description:`AI 对话切换到 ${o.name} 后可选用它的模型,SOP 在执行机器上以 ${o.name} 运行的节点也使用它。${o.note||''}`,
guide:o.guide||[['在模型服务商控制台创建 API Key'],['记下服务地址和它提供的接口协议'],['粘贴 Key,按需填写 Base URL 并选择协议;保存后可在模型目录里挑选 AI 对话的模型']],
- placeholder:`请输入 ${o.name} API Key`,
+ placeholder:o.placeholder||`请输入 ${o.name} API Key`,
...(configurable?{
extra:{name:field+'baseUrl',label:'Base URL',placeholder:o.baseUrl,url:true,clearWithKey:true,required:o.required,note:o.extraNote||(o.required?'必填':'')},
protocol:{name:field+'protocol',options:o.protocols},
@@ -492,7 +503,12 @@ const CREDENTIAL_PAT_WARNING='请填写 GitHub 个人访问令牌(PAT)kind.key===key)||null}
// Kinds with a dialog manage several entries there instead of the inline editor.
function credentialDialog(key){return credentialKind(key)?.dialog||null}
-function credentialConfigured(kind,user){if(kind.key==='gitToken')return !!user.gitHubCredentialConfigured;return !!credentialValue(user,kind.agentCli?kind.key+'.apiKeyConfigured':kind.key+'Configured')}
+// The Codeup card reuses the per-host Git HTTPS credential for codeup.aliyun.com.
+// The user summary only carries a GitHub boolean, so the Codeup record is cached
+// from the credential list (and the flag is computed client-side after saves).
+function codeupCredentialRecord(user){const cached=state.codeupCredential;return cached&&Number(cached.userId)===Number(user?.id)?cached.record||null:null}
+function codeupVerifyFor(user){return state.codeupVerify&&Number(state.codeupVerify.userId)===Number(user?.id)?state.codeupVerify:null}
+function credentialConfigured(kind,user){if(kind.key==='gitToken')return !!user.gitHubCredentialConfigured;if(kind.key==='codeupToken')return !!user.codeupCredentialConfigured||!!codeupCredentialRecord(user);return !!credentialValue(user,kind.agentCli?kind.key+'.apiKeyConfigured':kind.key+'Configured')}
function credentialUser(){return userById(state.currentUser?.id)||{}}
function credentialUI(){return state.credentialUI||(state.credentialUI={open:null,filter:'all',closed:{}})}
function credentialGlyph(name,size=16,cls=''){return ``}
@@ -540,7 +556,7 @@ function refreshCredentialEnvironmentLinks(scope,value){
}
function credentialExtraError(kind,value,protocol){
const text=String(value||'').trim();
- if(!text&&kind.extra?.required?.(protocol))return '请填写 Base URL';
+ if(!text&&kind.extra?.required?.(protocol))return kind.extra.requiredMessage||'请填写 Base URL';
if(!kind.extra?.url||!text)return '';
try{const url=new URL(text);if(url.protocol==='http:'||url.protocol==='https:')return ''}catch{}
return '请填写以 http:// 或 https:// 开头的地址';
@@ -580,8 +596,8 @@ function gitTokenFailure(result){
}
function credentialStatus(kind,user){
if(!credentialConfigured(kind,user))return 'empty';
- if(kind.key!=='gitToken')return 'ok';
- const verify=gitTokenVerifyFor({id:state.currentUser?.id});
+ if(kind.key!=='gitToken'&&kind.key!=='codeupToken')return 'ok';
+ const verify=kind.key==='codeupToken'?codeupVerifyFor({id:state.currentUser?.id}):gitTokenVerifyFor({id:state.currentUser?.id});
if(verify?.busy)return 'busy';
return gitTokenFailure(verify?.result)?'err':'ok';
}
@@ -602,6 +618,15 @@ function credentialSubline(kind,user){
if(!result.valid)return source+dot+`缺少权限 ${escapeHTML((result.missing||[]).join('、'))}`;
return source+dot+'令牌有效'+(result.scopes?.length?dot+`${escapeHTML(result.scopes.join(' · '))}`:'');
}
+ if(kind.key==='codeupToken'){
+ const verify=codeupVerifyFor({id:state.currentUser?.id}),result=verify?.result,record=codeupCredentialRecord(user);
+ const source='个人访问令牌'+(record?.username?dot+`${escapeHTML(record.username)}`:'');
+ if(verify?.busy)return source+dot+'正在校验…';
+ if(!result)return source+dot+use;
+ if(result.error)return source+dot+`${escapeHTML(result.error)}`;
+ if(!result.valid)return source+dot+`缺少权限 ${escapeHTML((result.missing||[]).join('、'))}`;
+ return source+dot+'令牌有效';
+ }
if(kind.key==='codeBuddyApiKey'){
const raw=String(user.codeBuddyInternetEnvironment||'').trim(),env=codeBuddyEnvironment(raw);
return `网络环境${env?`${escapeHTML(env.label)}`:`「${escapeHTML(raw)}」无法识别,按国际站连接`}${dot}${use}`;
@@ -622,8 +647,9 @@ function credentialFieldHTML({label,note='',name,type='password',value='',placeh
function credentialOAuthHTML(label,note){
return (typeof githubConnectHTML==='function'?githubConnectHTML():'')+``;
}
-function credentialPatWarningHTML(show){return `${credentialGlyph('alert',14)}${CREDENTIAL_PAT_WARNING}`}
+function credentialPatWarningHTML(show,text=CREDENTIAL_PAT_WARNING){return `${credentialGlyph('alert',14)}${text}`}
const GIT_TOKEN_REPLACE_HINT='保存后替换当前的令牌,对下一次任务生效';
+const CODEUP_PAT_WARNING='请填写云效 个人访问令牌(PAT) 并授予代码读写权限;令牌权限不足会导致克隆 / 推送仓库失败。';
function credentialAgo(at){
const seconds=Math.max(0,Math.round((Date.now()-at)/1000));
if(seconds<60)return '刚刚';
@@ -659,8 +685,38 @@ function gitTokenEditorHTML(kind,user){
下一次运行你负责的任务时生效,可随时在列表中展开编辑。
${credentialGlyph('alert',13)}${escapeHTML(wizard.error)}
` - :wizard.saving&&kind.key==='gitToken'?`${credentialSpinner(13)}正在校验令牌有效性与权限…
` - :kind.key==='gitToken'?`${credentialGlyph('lock',13)}保存前会先校验令牌有效性与权限
` + :wizard.saving&&verifyFirst?`${credentialSpinner(13)}正在校验令牌有效性与权限…
` + :verifyFirst?`${credentialGlyph('lock',13)}保存前会先校验令牌有效性与权限
` :warning?`${credentialGlyph('alert',13)}${escapeHTML(warning)}
`:''; return `