Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat: select a native sandbox per OS and run more agent CLIs (#116)
crispinhu2789d5ed4856f5
diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsxindex 52353417..42f259c5 100644--- a/chatbot/src/App.jsx+++ b/chatbot/src/App.jsx@@ -1975,7 +1975,7 @@ export default function App() {}}/><PermissionPicker- label="执行器"+ label="CLI"options={chat.executors}value={chat.executor}onSelect={(id) => {@@ -1996,16 +1996,14 @@ export default function App() {input.current?.focus();}}/>- {chat.executor === "codebuddy" ? (- <PermissionPicker- label="思考强度"- options={effortOptions(selectedModel)}- value={chat.effort}- onSelect={chat.setEffort}- open={menu?.type === "effort"}- onOpenChange={(open) => setMenu(open ? { type: "effort" } : null)}- />- ) : null}+ <PermissionPicker+ label="思考强度"+ options={effortOptions(selectedModel)}+ value={chat.effort}+ onSelect={chat.setEffort}+ open={menu?.type === "effort"}+ onOpenChange={(open) => setMenu(open ? { type: "effort" } : null)}+ /><PermissionPickervalue={approval}onSelect={setApproval}diff --git a/chatbot/src/engines.js b/chatbot/src/engines.jsnew file mode 100644index 00000000..02601146--- /dev/null+++ b/chatbot/src/engines.js@@ -0,0 +1,67 @@+// CLIs that AI 对话 can run on. The list comes from GET /api/assistant/models+// (`engines`); models without `engine` run on CodeBuddy.+export const defaultEngine = "codebuddy";++// 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: "gemini", kimi: "kimi", pi: "pi", dsh: "deepseek",+};+export const engineBrand = (id) => brands[id] || "";++export const modelEngine = (model) => model?.engine || defaultEngine;++/** The CLI an ID runs on: the catalog entry, else the "cli:model" prefix. */+export function engineOfModel(id, models = []) {+ const listed = models.find((m) => m.id === id);+ if (listed) return modelEngine(listed);+ const prefix = /^([a-z][a-z0-9-]*):./.exec(id || "")?.[1];+ return prefix || defaultEngine;+}++export const engineModels = (models, engine) =>+ (models || []).filter((m) => modelEngine(m) === engine);++// Mirrors assistantEngineMissingKey in internal/httpapi/assistant_engines.go;+// credentialHint turns it into a "去配置" button.+export function engineMissingKeyMessage(engine) {+ if (engine.id === defaultEngine) return "请先在个人配置中配置自己的 CodeBuddy API Key";+ return `请先在个人配置中配置 ${engine.name} API Key 后再使用 ${engine.name} 模型`;+}++// CLIs a session Executor can name when the reply was saved before model prefixes.+const legacyEngines = new Set(["codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh"]);++function modelHasEnginePrefix(id) {+ const prefix = /^([a-z][a-z0-9-]*):./.exec(id || "")?.[1];+ return prefix === defaultEngine || legacyEngines.has(prefix);+}++function legacyEngine(id) {+ if (id === "claude") return "claude-code";+ return legacyEngines.has(id) ? id : "";+}++/**+ * The CLI that wrote a conversation's latest own reply, "" before the first.+ * Mirrors assistantConversationEngine: a conversation stays on that CLI,+ * because its native session holds tool calls another CLI cannot resume.+ * An unprefixed model falls back to the session's stored executor.+ */+export function conversationEngine(messages, models = [], legacyExecutor = "") {+ for (let i = (messages?.length || 0) - 1; i >= 0; i--) {+ const m = messages[i];+ if (m?.role !== "assistant" || m.speakerAgentId || !m.model) continue;+ if (modelHasEnginePrefix(m.model)) return engineOfModel(m.model, models);+ const legacy = legacyEngine(legacyExecutor);+ if (legacy) return legacy;+ return engineOfModel(m.model, models);+ }+ return "";+}++export function engineDetail(engine, models) {+ if (!engine.configured) return `未配置 ${engine.name} API Key,选择后去个人配置填写`;+ const count = engineModels(models, engine.id).length;+ return count ? `${count} 个可用模型` : "暂无可用模型";+}diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.jsindex 9e494d3e..5223dbc7 100644--- a/chatbot/src/useChat.js+++ b/chatbot/src/useChat.js@@ -13,6 +13,7 @@ import {import { reviewedOperation, operationError } from "./operations.js";import { credentialHint } from "./credentials.js";import { modelEffort } from "./effort.js";+import { conversationEngine, engineModels } from "./engines.js";import {enqueue,holdQueue,@@ -27,13 +28,22 @@ import {export const EXECUTORS = [{ id: "codebuddy", icon: "sparkles", label: "CodeBuddy", detail: "使用 CodeBuddy 模型与个人 API Key。" },{ id: "codex", icon: "terminal", label: "Codex", detail: "使用 Codex CLI 与个人 Codex API Key。" },- { id: "claude", icon: "brain", label: "Claude Code", detail: "使用 Claude Code CLI 与个人 Claude Code API Key。" },+ { id: "claude-code", icon: "brain", label: "Claude Code", detail: "使用 Claude Code CLI 与个人 Claude Code API Key。" },+ { id: "opencode", icon: "terminal", label: "OpenCode", detail: "使用 OpenCode 与个人 API Key。" },+ { id: "cursor", icon: "terminal", label: "Cursor", detail: "使用 Cursor CLI 与个人 API Key。" },+ { id: "agy", icon: "sparkles", label: "Antigravity", detail: "使用 Antigravity 与个人 API Key。" },+ { id: "kimi", icon: "sparkles", label: "Kimi Code", detail: "使用 Kimi Code 与个人 API Key。" },+ { id: "pi", icon: "terminal", label: "Pi", detail: "使用 Pi 与个人 API Key。" },+ { id: "dsh", icon: "terminal", label: "DeepSeek Harness", detail: "使用 DeepSeek Harness 与个人 API Key。" },];const EXECUTOR_KEY = "loopforge.assistant.executor";+function knownExecutor(id) {+ if (id === "claude") return "claude-code";+ return EXECUTORS.some((item) => item.id === id) ? id : "codebuddy";+}function storedExecutor() {try {- const id = localStorage.getItem(EXECUTOR_KEY);- return EXECUTORS.some((item) => item.id === id) ? id : "codebuddy";+ return knownExecutor(localStorage.getItem(EXECUTOR_KEY));} catch {return "codebuddy";}@@ -156,8 +166,9 @@ export function useChat() {if (!id) {const preferred = storedExecutor();setExecutorState(preferred);- if (preferred !== "codebuddy") setModel("default");- else if (defaultModel.current) setModel(defaultModel.current);+ const next = engineModels(models, preferred);+ if (preferred === "codebuddy") setModel(defaultModel.current || next[0]?.id || "");+ else setModel(next[0]?.id || "default");}setEffort("");setSandboxProfileId("");@@ -166,7 +177,7 @@ export function useChat() {if (id) setRevealId(id);changeURL(id);},- [changeURL],+ [changeURL, models],);const newChat = useCallback(() => {setDraftIssueId("");@@ -227,8 +238,10 @@ export function useChat() {if (!current || currentId.current !== activeId) return;setSession(stored);changeURL(stored.id);- // A conversation stays on the CLI that answered it; older ones are CodeBuddy.- setExecutorState(EXECUTORS.some((item) => item.id === stored.executor) ? stored.executor : "codebuddy");+ // A conversation stays on the CLI that answered it. Replies saved before+ // model prefixes keep that CLI on the session executor.+ const locked = conversationEngine(stored.messages, models, stored.executor);+ setExecutorState(knownExecutor(locked || stored.executor));setModel(stored.model || defaultModel.current || models[0]?.id || "");setEffort(stored.effort || "");setProjectId(stored.projectId || "");@@ -477,7 +490,10 @@ export function useChat() {return () => window.removeEventListener("message", listener);}, [ready]);const codeBuddy = executor === "codebuddy";- const executorModels = codeBuddy ? models : providerCatalogs[executor]?.models || [];+ const listedForEngine = engineModels(models, executor);+ const executorModels = listedForEngine.length || codeBuddy+ ? (codeBuddy ? models.filter((m) => !m.engine || m.engine === "codebuddy") : listedForEngine)+ : providerCatalogs[executor]?.models || [];const missingKey = !!user && !user.codeBuddyApiKeyConfigured;// Without their own key users chat on the platform's shared key, limited to// the models the administrator allowed (the first is the default).@@ -485,10 +501,9 @@ export function useChat() {const sponsored = codeBuddy && missingKey && !user.isGuest && !!sponsoredModel;const sharedModelFor = (id) => (sponsoredModels.includes(id) ? id : sponsoredModel);const activeModel = sponsored ? sharedModelFor(model) : model;- // Reasoning effort is a CodeBuddy model option; the other CLIs use their defaults.- const activeEffort = codeBuddy ? modelEffort(models.find((m) => m.id === activeModel), effort) : "";+ const activeEffort = modelEffort(executorModels.find((m) => m.id === activeModel), effort);useEffect(() => {- if (codeBuddy || providerCatalogs[executor]) return;+ if (codeBuddy || listedForEngine.length || providerCatalogs[executor]) return;let current = true;api(`/api/assistant/models?executor=${encodeURIComponent(executor)}`).then((catalog) => {@@ -500,19 +515,23 @@ export function useChat() {return () => {current = false;};- }, [codeBuddy, executor, providerCatalogs]);+ }, [codeBuddy, executor, listedForEngine.length, providerCatalogs]);const chooseExecutor = useCallback((id) => {+ if (id === "claude") id = "claude-code";if (!EXECUTORS.some((item) => item.id === id) || id === executor) return;- setExecutorState(id);+ const locked = conversationEngine(sessionRef.current?.messages, models, sessionRef.current?.executor);try {localStorage.setItem(EXECUTOR_KEY, id);} catch {}setEffort("");+ const next = engineModels(models, id);const catalog = id === "codebuddy" ? { default: defaultModel.current } : providerCatalogs[id];- setModel(catalog?.default || (id === "codebuddy" ? defaultModel.current : "default"));+ setExecutorState(id);+ setModel(next[0]?.id || catalog?.default || (id === "codebuddy" ? defaultModel.current : "default"));+ if (locked && locked !== id) open(null);},- [executor, providerCatalogs],+ [executor, models, open, providerCatalogs],);const chooseModel = useCallback((id) => {diff --git a/chatbot/tests/app-render.test.jsx b/chatbot/tests/app-render.test.jsxindex 2dd2e114..299bf57c 100644--- a/chatbot/tests/app-render.test.jsx+++ b/chatbot/tests/app-render.test.jsx@@ -312,18 +312,18 @@ describe("App", () => {Object.assign(chat, previous);});- test("the composer switches Main Bot executors and hides CodeBuddy-only effort", async () => {+ test("the composer switches CLI and keeps the effort picker", async () => {const user = userEvent.setup();const previous = { ...chat };chat.setExecutor = vi.fn();const view = render(<App />);- await user.click(screen.getByRole("button", { name: /执行器/ }));- await user.click(await screen.findByRole("menuitemradio", { name: /Codex/ }));+ await user.click(screen.getByRole("button", { name: "CLI" }));+ await user.click(await screen.findByRole("menuitemradio", { name: "Codex" }));expect(chat.setExecutor).toHaveBeenCalledWith("codex");- expect(screen.getByRole("button", { name: /思考强度/ })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "思考强度" })).toBeInTheDocument();chat.executor = "codex";view.rerender(<App />);- expect(screen.queryByRole("button", { name: /思考强度/ })).toBeNull();+ expect(screen.getByRole("button", { name: "思考强度" })).toBeInTheDocument();Object.assign(chat, previous);});diff --git a/chatbot/tests/engines.test.mjs b/chatbot/tests/engines.test.mjsnew file mode 100644index 00000000..419ba04c--- /dev/null+++ b/chatbot/tests/engines.test.mjs@@ -0,0 +1,15 @@+import { test } from "vitest";+import assert from "node:assert/strict";+import { conversationEngine } from "../src/engines.js";++const reply = [{ role: "user", content: "hi" }, { role: "assistant", model: "gpt-5.4", content: "ok" }];++test("an unprefixed reply stays on the session executor saved before model prefixes", () => {+ assert.equal(conversationEngine(reply, [], "codex"), "codex");+ assert.equal(conversationEngine(reply, [], "claude"), "claude-code");+ assert.equal(conversationEngine(reply, [], "agy"), "agy");+ assert.equal(conversationEngine(reply, [], "codebuddy"), "codebuddy");+ assert.equal(conversationEngine(reply), "codebuddy");+ assert.equal(conversationEngine([{ role: "assistant", model: "codex:gpt-5.4", content: "ok" }], [], "codebuddy"), "codex");+ assert.equal(conversationEngine([{ role: "assistant", model: "gpt-5.4", speakerAgentId: "role", content: "ok" }], [], "codex"), "");+});diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsxindex b4bd1ae6..8301bc80 100644--- a/chatbot/tests/hooks.test.jsx+++ b/chatbot/tests/hooks.test.jsx@@ -43,7 +43,7 @@ vi.mock("../src/api.js", async (original) => ({newId: () => "new-session",}));-import { useChat } from "../src/useChat.js";+import { EXECUTORS, useChat } from "../src/useChat.js";import {isLocalConversation,useLocalConversations,@@ -79,7 +79,7 @@ describe("conversation hooks", () => {const { result } = renderHook(() => useChat());await waitFor(() => expect(result.current.ready).toBe(true));expect(result.current.executor).toBe("codebuddy");- expect(result.current.executors.map((item) => item.id)).toEqual(["codebuddy", "codex", "claude"]);+ expect(result.current.executors.map((item) => item.id)).toEqual(EXECUTORS.map((item) => item.id));act(() => result.current.setExecutor("codex"));await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(["default", "gpt-5"]));expect(localStorage.getItem("loopforge.assistant.executor")).toBe("codex");diff --git a/docs/api/registry.md b/docs/api/registry.mdindex 0341ae5c..92fd4f1d 100644--- a/docs/api/registry.md+++ b/docs/api/registry.md@@ -203,7 +203,7 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X POST \### `GET /api/sandboxes`-返回 `SandboxProfile[]`,`200`。字段为 `id`、`name`、`driver`(`local|seatbelt|bwrap|docker`)、`dockerfileId`、`environmentId`、`readOnlyRootFS`、`environment`。+返回 `SandboxProfile[]`,`200`。字段为 `id`、`name`、`driver`(`local|native|docker`;保存 `seatbelt` 或 `bwrap` 会归一成 `native`,运行时在 macOS 解析为 seatbelt、在 Linux 解析为 bwrap)、`dockerfileId`、`environmentId`、`readOnlyRootFS`、`environment`。### `PUT /api/sandboxes`diff --git a/e2e/public/executors.spec.mjs b/e2e/public/executors.spec.mjsindex a4af341f..24d8cc89 100644--- a/e2e/public/executors.spec.mjs+++ b/e2e/public/executors.spec.mjs@@ -3,6 +3,10 @@ import {signInUnconfigured, switchProject, chat, openHome, fitsFrame} from './hetest.use({trace:'off',screenshot:'off'});+// first-run drives the published image, whose picker is still labeled 执行器 and+// lists three CLIs. The browser job builds this checkout, which labels it CLI.+const executorButton = (frame) => frame.getByRole('button', { name: /^(执行器|CLI)$/ });+for(const viewport of [{width:1280,height:400},{width:390,height:600}]){test(`the executor and model menus stay usable at ${viewport.width}x${viewport.height}`,async({page})=>{const errors=[];page.on('pageerror',e=>errors.push(e.message));@@ -12,8 +16,8 @@ for(const viewport of [{width:1280,height:400},{width:390,height:600}]){await signInUnconfigured(page);await openHome(page);const frame=chat(page);- for(const [name,menu] of [['执行器','.permission-menu[role="menu"]'],['选择模型','.grasp-model-menu']]){- await frame.getByRole('button',{name,exact:true}).click();+ for(const [button,menu,name] of [[executorButton(frame),'.permission-menu[role="menu"]','执行器'],[frame.getByRole('button',{name:'选择模型',exact:true}),'.grasp-model-menu','选择模型']]){+ await button.click();const open=frame.locator(menu);await expect(open).toBeVisible();await expect.poll(()=>fitsFrame(open),{message:`${name} menu at ${viewport.width}x${viewport.height}`}).toBe(true);@@ -40,14 +44,15 @@ test('executor selection has independent models, credentials and a persistent chconst draft='Keep this draft while choosing an executor';const input=await openHome(page);const frame=chat(page);- const executor=frame.getByRole('button',{name:'执行器',exact:true});+ const executor=executorButton(frame);const choose=async label=>{await executor.click();await frame.locator('.permission-menu [role="menuitemradio"]').filter({hasText:label}).click();await expect(executor).toContainText(label);};await executor.click();- await expect(frame.locator('.permission-menu [role="menuitemradio"]')).toHaveCount(3);+ const options=frame.locator('.permission-menu [role="menuitemradio"]');+ for(const label of ['CodeBuddy','Codex','Claude Code'])await expect(options.filter({hasText:label})).toHaveCount(1);await page.keyboard.press('Escape');await input.fill(draft);for(const [id,label] of [['codex','Codex'],['claude','Claude Code'],['codebuddy','CodeBuddy']]){@@ -63,7 +68,7 @@ test('executor selection has independent models, credentials and a persistent chawait choose('Codex');await page.reload();await expect(composer()).toBeEditable();- await expect(chat(page).getByRole('button',{name:'执行器',exact:true})).toContainText('Codex');+ await expect(executorButton(chat(page))).toContainText('Codex');await choose('CodeBuddy');expect((await page.request.get('/api/assistant/models?executor=shell')).status()).toBe(400);function composer(){return chat(page).locator('.composer-column textarea')}diff --git a/internal/domain/agent.go b/internal/domain/agent.goindex 1aa6cd28..a600fb9a 100644--- a/internal/domain/agent.go+++ b/internal/domain/agent.go@@ -12,6 +12,25 @@ var ExecutorEffortLevels = map[string][]string{"claude-code": {"low", "medium", "high", "xhigh", "max", "ultracode"},"codebuddy": {"low", "medium", "high", "xhigh", "max", "ultracode"},"codex": {"low", "medium", "high", "xhigh", "max", "ultra"},+ "opencode": {"low", "medium", "high"},+ "cursor": {"none", "minimal", "low", "medium", "high", "xhigh", "max"},+ "agy": {"low", "medium", "high", "xhigh", "max"},+ "pi": {"minimal", "low", "medium", "high", "xhigh", "max"},+}++// 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"}++func IsAgentCLIKind(kind string) bool {+ kind = strings.TrimSpace(kind)+ for _, k := range AgentCLIExecutorKinds {+ if strings.EqualFold(k, kind) {+ return true+ }+ }+ return false}// ValidateAgentEffort checks a role's reasoning-effort choice against thediff --git a/internal/domain/assets.go b/internal/domain/assets.goindex d25c9c42..28cb7227 100644--- a/internal/domain/assets.go+++ b/internal/domain/assets.go@@ -148,13 +148,45 @@ type SandboxProfile struct {Name string `json:"name"`ProjectID string `json:"projectId,omitempty"`Shared bool `json:"shared,omitempty"`- Driver string `json:"driver"` // local, seatbelt, bwrap, docker+ Driver string `json:"driver"` // local, native, docker (seatbelt / bwrap are resolved native values)DockerfileID string `json:"dockerfileId,omitempty"`EnvironmentID string `json:"environmentId,omitempty"`ReadOnlyRootFS bool `json:"readOnlyRootFS"`Environment map[string]string `json:"environment,omitempty"`}+// Sandbox drivers. Profiles store local, native or docker; native is the OS+// lightweight process sandbox and resolves on the executing machine to+// seatbelt (macOS) or bwrap (Linux). seatbelt / bwrap remain valid resolved+// values (runner task payloads, rows written before the native option).+const (+ SandboxDriverLocal = "local"+ SandboxDriverNative = "native"+ SandboxDriverDocker = "docker"+ SandboxDriverSeatbelt = "seatbelt"+ SandboxDriverBwrap = "bwrap"+)++// ResolveSandboxDriver maps native onto the lightweight sandbox of goos and+// returns every other driver unchanged. An empty goos (a runner that never+// reported its OS) leaves native for that machine to resolve itself.+func ResolveSandboxDriver(driver, goos string) (string, error) {+ driver = strings.TrimSpace(driver)+ if driver != SandboxDriverNative {+ return driver, nil+ }+ switch strings.ToLower(strings.TrimSpace(goos)) {+ case "darwin":+ return SandboxDriverSeatbelt, nil+ case "linux":+ return SandboxDriverBwrap, nil+ case "":+ return driver, nil+ default:+ return "", fmt.Errorf("系统轻量隔离(native)仅支持 macOS 与 Linux,当前执行机器为 %s", goos)+ }+}+func ValidateDockerfile(v DockerfileDefinition) error {if strings.TrimSpace(v.ID) == "" || strings.TrimSpace(v.Name) == "" {return fmt.Errorf("Dockerfile 需要 id 和 name")diff --git a/internal/domain/runner.go b/internal/domain/runner.goindex 88011e76..536a2e79 100644--- a/internal/domain/runner.go+++ b/internal/domain/runner.go@@ -231,9 +231,13 @@ func (r Runner) SupportsProvider(provider string) bool {}// RuntimeAuthMode returns the configured credential source for a provider.-// CodeBuddy has no reusable local-login flow, so its default is the-// responsible user's personal credential; other CLIs default to local login.+// CodeBuddy and the extra agent CLIs have no reusable local-login flow, so+// they always use the responsible user's personal credential. Codex and+// Claude Code default to local login.func (r Runner) RuntimeAuthMode(provider string) string {+ if IsAgentCLIKind(provider) {+ return RuntimeAuthPersonal+ }provider = strings.TrimSpace(provider)for _, rt := range r.Runtimes {if strings.EqualFold(rt.Provider, provider) {@@ -372,6 +376,9 @@ func PublicRunnerTask(task RunnerTask) RunnerTask {copyInvocation.CodexBaseURL = ""copyInvocation.ClaudeCodeAPIKey = ""copyInvocation.ClaudeCodeBaseURL = ""+ copyInvocation.AgentCLIAPIKey = ""+ copyInvocation.AgentCLIBaseURL = ""+ copyInvocation.AgentCLIProtocol = ""if copyInvocation.Repository != nil {copyRepository := *copyInvocation.RepositorycopyRepository.GitToken = ""@@ -428,6 +435,9 @@ type RunnerInvocation struct {CodexBaseURL string `json:"codexBaseUrl,omitempty"`ClaudeCodeAPIKey string `json:"claudeCodeApiKey,omitempty"`ClaudeCodeBaseURL string `json:"claudeCodeBaseUrl,omitempty"`+ AgentCLIAPIKey string `json:"agentCliApiKey,omitempty"`+ AgentCLIBaseURL string `json:"agentCliBaseUrl,omitempty"`+ AgentCLIProtocol string `json:"agentCliProtocol,omitempty"`// MCPCallServers is the project/personal HTTP MCP set for `agentflow mcp call`// in scripts, verification gates, and Agent hooks. It is unbound; personal// credentials are applied in memory on the runner. Agent Assets staydiff --git a/internal/domain/runner_test.go b/internal/domain/runner_test.goindex f84b5424..51a88060 100644--- a/internal/domain/runner_test.go+++ b/internal/domain/runner_test.go@@ -49,6 +49,22 @@ func TestPublicRunnerTaskScrubsMultiRepositoryTokens(t *testing.T) {}}+func TestAgentCLIRuntimeAuthModeIsPersonal(t *testing.T) {+ r := Runner{Runtimes: []RunnerRuntime{+ {Provider: "opencode", AuthMode: RuntimeAuthLocal},+ {Provider: "codex", AuthMode: RuntimeAuthLocal},+ }}+ if r.RuntimeAuthMode("opencode") != RuntimeAuthPersonal {+ t.Fatal("agent CLI must use personal credentials even when a local mode is stored")+ }+ if r.RuntimeAuthMode("codex") != RuntimeAuthLocal {+ t.Fatal("codex local login must stay local")+ }+ if r.RuntimeAuthMode("codebuddy") != RuntimeAuthPersonal {+ t.Fatal("codebuddy still defaults to personal credentials")+ }+}+func TestRunnerSupportsWorkBranchSync(t *testing.T) {for version, want := range map[string]bool{"": false, "dev": false, "0.1.0": false, "0.1.9": false,diff --git a/internal/domain/user.go b/internal/domain/user.goindex d1a1b96c..d8406a93 100644--- a/internal/domain/user.go+++ b/internal/domain/user.go@@ -13,12 +13,20 @@ type User struct {ClaudeCodeAPIKey string `json:"claudeCodeApiKey,omitempty"`ClaudeCodeAPIKeyConfigured bool `json:"claudeCodeApiKeyConfigured,omitempty"`ClaudeCodeBaseURL string `json:"claudeCodeBaseUrl,omitempty"`- ID int64 `json:"id"`- StaffID int `json:"staffId"`- LoginName string `json:"loginName"`- ChineseName string `json:"chineseName"`- DeptID int `json:"deptId"`- DeptName string `json:"deptName"`+ // CodexModels and ClaudeCodeModels are the model catalogs AI 对话 offers+ // for that CLI, in display order. Empty means the models the Base URL's+ // /models endpoint publishes.+ CodexModels []CLIModel `json:"codexModels,omitempty"`+ ClaudeCodeModels []CLIModel `json:"claudeCodeModels,omitempty"`+ // AgentCLICredentials holds the credentials of the agent CLIs+ // (AgentCLIExecutorKinds) by kind.+ AgentCLICredentials map[string]AgentCLICredential `json:"agentCliCredentials,omitempty"`+ ID int64 `json:"id"`+ StaffID int `json:"staffId"`+ LoginName string `json:"loginName"`+ ChineseName string `json:"chineseName"`+ DeptID int `json:"deptId"`+ DeptName string `json:"deptName"`// PlatformRole is a platform-wide role, independent of project membership.// "admin" may edit generic SOP templates; empty is a regular user.PlatformRole string `json:"platformRole,omitempty"`@@ -71,9 +79,69 @@ func PublicUser(u User) User {u.GongfengTokenExpiresAt = time.Time{}u.CodeBuddyAPIKeyConfigured = strings.TrimSpace(u.CodeBuddyAPIKey) != ""u.CodeBuddyAPIKey = ""+ if len(u.AgentCLICredentials) > 0 {+ public := make(map[string]AgentCLICredential, len(u.AgentCLICredentials))+ for kind, cred := range u.AgentCLICredentials {+ cred.APIKeyConfigured = strings.TrimSpace(cred.APIKey) != ""+ cred.APIKey = ""+ public[kind] = cred+ }+ u.AgentCLICredentials = public+ }return u}+// CLIModel is one entry of a CLI model catalog. ID is passed to the CLI+// as-is; an empty Name shows the ID.+type CLIModel struct {+ ID string `json:"id"`+ Name string `json:"name,omitempty"`+}++// AgentCLICredential is the personal configuration of one agent CLI. An+// empty BaseURL means the CLI's official endpoint; Protocol is the wire+// protocol BaseURL speaks (AgentCLIProtocolOptions).+type AgentCLICredential struct {+ APIKey string `json:"apiKey,omitempty"`+ APIKeyConfigured bool `json:"apiKeyConfigured,omitempty"`+ BaseURL string `json:"baseUrl,omitempty"`+ Protocol string `json:"protocol,omitempty"`+ Models []CLIModel `json:"models,omitempty"`+}++// Wire protocols an agent CLI can speak to a user Base URL.+const (+ AgentCLIProtocolChat = "chat" // OpenAI Chat Completions+ AgentCLIProtocolResponses = "responses" // OpenAI Responses+ AgentCLIProtocolMessages = "messages" // Anthropic Messages+ AgentCLIProtocolGemini = "gemini" // Google Gemini API+)++// AgentCLIProtocolOptions lists the protocols each agent CLI speaks against a+// user Base URL; the first one is the default. Cursor only talks to Cursor.+var AgentCLIProtocolOptions = map[string][]string{+ "opencode": {AgentCLIProtocolChat, AgentCLIProtocolResponses, AgentCLIProtocolMessages},+ "kimi": {AgentCLIProtocolChat, AgentCLIProtocolResponses, AgentCLIProtocolMessages},+ "pi": {AgentCLIProtocolChat, AgentCLIProtocolResponses, AgentCLIProtocolMessages},+ "dsh": {AgentCLIProtocolChat, AgentCLIProtocolResponses, AgentCLIProtocolMessages},+ "agy": {AgentCLIProtocolGemini, AgentCLIProtocolChat},+}++// NormalizeAgentCLIProtocol returns a supported protocol choice; unknown+// values fall back to the CLI's default.+func NormalizeAgentCLIProtocol(kind, protocol string) string {+ options := AgentCLIProtocolOptions[strings.TrimSpace(kind)]+ for _, option := range options {+ if option == strings.TrimSpace(protocol) {+ return option+ }+ }+ if len(options) == 0 {+ return ""+ }+ return options[0]+}+func PublicUsers(items []User) []User {out := make([]User, len(items))for i, u := range items {diff --git a/internal/engine/run_environment.go b/internal/engine/run_environment.goindex 7ed98b5a..159f8c57 100644--- a/internal/engine/run_environment.go+++ b/internal/engine/run_environment.go@@ -229,6 +229,7 @@ func (e *Engine) resolveRunCredentials(run domain.Run) runtime.RunCredentials {if user, ok := e.repo.User(userID); ok {credentials.Codex = runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL}credentials.ClaudeCode = runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL}+ credentials.AgentCLI = runtime.AgentCLIUserCredentials(user)}scriptAssets, _, _ := runtime.PrepareMCPServers(e.resolveScriptMCPAssets(run.ExecutionContext.ProjectID, userID), runtime.MCPTarget{GitToken: credentials.GitToken})credentials.MCPServers = scriptAssets.MCPServersdiff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.goindex b770db62..af1a864c 100644--- a/internal/engine/runner_dispatch.go+++ b/internal/engine/runner_dispatch.go@@ -213,6 +213,16 @@ func (e *Engine) dispatchRunnerTask(ctx context.Context, runnerID string, run do}invocation.CodeBuddyAPIKey = sb.credentialSnapshot().CodeBuddy.APIKeyinvocation.CodeBuddyInternetEnvironment = sb.credentialSnapshot().CodeBuddy.InternetEnvironment+ default:+ if runtime.IsAgentCLI(ex.Kind) {+ cred := sb.credentialSnapshot().AgentCLI[ex.Kind]+ if strings.TrimSpace(cred.APIKey) == "" {+ return "", fmt.Errorf("当前责任人未配置 %s API Key:请先在个人配置中配置", runtime.AgentCLILabel(ex.Kind))+ }+ invocation.AgentCLIAPIKey = cred.APIKey+ invocation.AgentCLIBaseURL = cred.BaseURL+ invocation.AgentCLIProtocol = cred.Protocol+ }}}bindRunnerRepositories(invocation, run, sb.credentialSnapshot().GitToken, sb.credentialSnapshot().GitUserName, sb.credentialSnapshot().GitUserEmail)diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.goindex e4c537e1..16fd3896 100644--- a/internal/httpapi/assistant.go+++ b/internal/httpapi/assistant.go@@ -95,24 +95,15 @@ func (h *assistantHandlers) chat(c *gin.Context) {return}req.Executor = assistantExecutor(req.Executor)- user, sharedModels := stored, []string(nil)- if req.Executor == "codebuddy" {- if user, sharedModels, ok = h.assistantChatUser(stored); !ok {- c.JSON(400, gin.H{"error": "请先在个人配置中配置自己的 CodeBuddy API Key"})- return- }- } else if err := validateAssistantProvider(&req, stored); err != nil {- c.JSON(400, gin.H{"error": err.Error()})+ req.Model = assistantRequestModel(req.Executor, req.Model)+ user, model, refusal := h.assistantTurnUser(stored, req.Model)+ if refusal != "" {+ c.JSON(400, gin.H{"error": refusal})return}- if sharedModels != nil {- model, allowed := assistantSponsoredModelFor(sharedModels, req.Model)- if !allowed {- c.JSON(400, gin.H{"error": errAssistantSponsoredModel(sharedModels)})- return- }- req.Model = model- }+ req.Model = model+ cliEngine, _ := assistantModelEngine(req.Model)+ req.Executor = cliEngineif len(req.Messages) == 0 {c.JSON(400, gin.H{"error": "请提供对话消息"})return@@ -176,16 +167,25 @@ func (h *assistantHandlers) chat(c *gin.Context) {c.JSON(400, gin.H{"error": err.Error()})return}- if req.Executor == "codebuddy" {- catalog := h.chatCatalog(c.Request.Context(), user)- req.Model = assistantAllowedModel(req.Model, catalog)- if err := validateAssistantEffort(req.Model, req.Effort); err != nil {- c.JSON(400, gin.H{"error": err.Error()})- return- }- } else {- // Reasoning effort is a CodeBuddy model option; the other CLIs use their defaults.- req.Effort = ""+ catalogEngine, _ := assistantModelEngine(req.Model)+ catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil)+ if catalogEngine == assistantEngineCodeBuddy {+ catalog = h.chatCatalog(c.Request.Context(), user)+ }+ req.Model = assistantAllowedUserModel(req.Model, catalog, user)+ cliEngine, _ = assistantModelEngine(req.Model)+ req.Executor = cliEngine+ if err := validateAssistantEffort(req.Model, req.Effort); err != nil {+ c.JSON(400, gin.H{"error": err.Error()})+ return+ }+ legacyExecutor := ""+ if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {+ legacyExecutor = old.Executor+ }+ if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(req.Messages, legacyExecutor), req.Model); refusal != "" {+ c.JSON(409, gin.H{"error": refusal})+ return}req.SessionID = strings.TrimSpace(req.SessionID)if req.SessionID == "" {@@ -334,18 +334,16 @@ func (h *assistantHandlers) chat(c *gin.Context) {resume := falsebranch := falserewritten := false- differentProvider := falseif saved, err := loadAssistantConversation(h.repo, assistantStorageOwner(h.repo, req.SessionID, user.ID), req.SessionID); err == nil {- differentProvider = assistantExecutor(saved.Executor) != req.Executorbranch = saved.ParentSessionID != ""rewritten = saved.HistoryRevision > 0}- if saved, err := loadAssistantConversation(h.repo, user.ID, req.SessionID); req.Executor == "codebuddy" && err == nil && saved.ParentSessionID == "" && len(req.Messages) > 1 && !shared && !rewritten {+ if saved, err := loadAssistantConversation(h.repo, user.ID, req.SessionID); err == nil && saved.ParentSessionID == "" && len(req.Messages) > 1 && !shared && !rewritten {resume = trueturn = h.turnPrompt(req, sourceRoot, true)}cliSessionID := req.SessionID- if shared || branch || rewritten || differentProvider || req.Executor != "codebuddy" || c.Request.Context().Value(assistantFreshCLIKey{}) == true {+ if shared || branch || rewritten || c.Request.Context().Value(assistantFreshCLIKey{}) == true {resume = falseturn = fullPromptcliSessionID = newAssistantSessionID()@@ -374,14 +372,25 @@ func (h *assistantHandlers) chat(c *gin.Context) {}cliRoot = nativeSession.root}+ // A conversation stays on one CLI. A mismatch is a transcript from+ // before that rule, and it starts a fresh CLI session.+ turnEngine, _ := assistantModelEngine(req.Model)+ if nativeSession == nil {+ if state := readAssistantEngineState(cliRoot); state.Engine != turnEngine {+ if resume {+ resume = false+ turn = fullPrompt+ }+ cliSessionID = newAssistantSessionID()+ } else if resume && state.SessionID != "" {+ cliSessionID = state.SessionID+ }+ }if err := h.writeConversationAssets(cliRoot, req); err != nil {log.Printf("assistant skills/agents session=%s: %v", req.SessionID, err)}generate = func(ctx context.Context, prompt string, u domain.User) (string, error) {cliReq := assistantCLIRequest{Executor: req.Executor, Prompt: prompt, Model: req.Model, Effort: req.Effort, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: toolFiles.MCPConfig, Settings: toolFiles.Settings, SystemPrompt: assistantSystemPromptForRequest(req, approvalMode), SessionRoot: cliRoot, OnUsage: turnUsage.add}- if req.Executor != "codebuddy" && prompt != fullPrompt {- cliReq.Prompt = fullPrompt + "\n\n" + prompt- }relay := func(ev assistantStreamEvent) {finished := toolSession.trackDispatch(ev)if !streaming {@@ -405,6 +414,11 @@ func (h *assistantHandlers) chat(c *gin.Context) {cliReq.Prompt = fullPromptraw, _, err = runAssistantCLI(ctx, cliReq, u, relay)}+ if err == nil && nativeSession == nil {+ if stateErr := writeAssistantEngineState(cliRoot, assistantEngineState{Engine: turnEngine, SessionID: cliReq.SessionID}); stateErr != nil {+ log.Printf("assistant engine state session=%s: %v", req.SessionID, stateErr)+ }+ }resume = truenativeContinuationReady = err == nilreturn raw, err@@ -1192,10 +1206,12 @@ type assistantCLIRequest struct {}func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.User, onEvent func(assistantStreamEvent)) (string, string, error) {- if req.Executor != "" && req.Executor != "codebuddy" {- return runAlternateAssistantCLI(ctx, req, user, onEvent)+ req.Model = assistantRequestModel(req.Executor, req.Model)+ engine, engineModel := assistantModelEngine(req.Model)+ if engine != assistantEngineCodeBuddy && (req.ReportOnly || (!req.Native && !req.ReviewOnly)) {+ return "", "", errAssistantEngineUnsupported}- bin, err := resolveCodeBuddyBin()+ bin, err := resolveAssistantEngineBin(engine)if err != nil {log.Printf("assistant CLI resolve failed: %v", err)return "", "", err@@ -1234,11 +1250,32 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Uif sessionID == "" {sessionID = newAssistantSessionID()}- command, err := prepareAssistantCommand(assistantCommandOpts{Bin: bin, Config: config, Prompt: req.Prompt, Model: req.Model, Effort: req.Effort, SessionID: sessionID, Resume: req.Resume, SystemPrompt: req.SystemPrompt, Native: req.Native, Settings: req.Settings, ReportOnly: req.ReportOnly, ReviewOnly: req.ReviewOnly})+ var inv assistantCLIInvocation+ engineOpts := assistantEngineInvocationOpts{Bin: bin, Root: root, Config: config, Prompt: req.Prompt, Model: engineModel, Effort: req.Effort, SessionID: sessionID, Resume: req.Resume, SystemPrompt: req.SystemPrompt, ReviewOnly: req.ReviewOnly}+ switch engine {+ case assistantEngineClaude:+ engineOpts.User = runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL}+ inv, err = prepareAssistantClaudeInvocation(engineOpts)+ case assistantEngineCodex:+ engineOpts.User = runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL}+ inv, err = prepareAssistantCodexInvocation(engineOpts)+ default:+ if runtime.IsAgentCLI(engine) {+ engineOpts.User = runtime.AgentCLIUserCredentials(user)[engine]+ inv, err = prepareAssistantAgentCLIInvocation(engine, engineOpts)+ break+ }+ inv.command, err = prepareAssistantCommand(assistantCommandOpts{Bin: bin, Config: config, Prompt: req.Prompt, Model: req.Model, Effort: req.Effort, SessionID: sessionID, Resume: req.Resume, SystemPrompt: req.SystemPrompt, Native: req.Native, Settings: req.Settings, ReportOnly: req.ReportOnly, ReviewOnly: req.ReviewOnly})+ inv.credentials = runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment}}+ inv.sessionRef = sessionID+ }if err != nil {return "", "", err}- command = command.WithPrivateHomeDir(filepath.Join(root, "home"))+ if inv.resumeMissing {+ return "", sessionID, errAssistantSessionMissing+ }+ command := inv.command.WithPrivateHomeDir(filepath.Join(root, "home"))workspace := filepath.Join(root, "ws")if req.ReportOnly {workspace = reportRoot@@ -1250,10 +1287,12 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Uvar stderrTail []stringvar missingSession, modelStarted, credentialRejected boolvar usage domain.TokenUsage+ missingText := "No conversation found with session ID: " + inv.sessionRef+ var handle func(string)sink := func(event domain.TelemetryEvent) {if event.Name == "process.stderr" {if line := strings.TrimSpace(event.Message); line != "" {- missingSession = missingSession || strings.Contains(line, "No conversation found with session ID: "+sessionID)+ missingSession = missingSession || strings.Contains(line, missingText)stderrTail = append(stderrTail, line)if len(stderrTail) > 20 {stderrTail = stderrTail[len(stderrTail)-20:]@@ -1264,7 +1303,16 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Uif event.Name != "process.stdout" {return}- line := strings.TrimSpace(event.Message)+ if inv.translate == nil {+ handle(event.Message)+ return+ }+ for _, line := range inv.translate(event.Message) {+ handle(line)+ }+ }+ handle = func(line string) {+ line = strings.TrimSpace(line)if failure := assistantCLIStreamFailure(line); failure != nil {streamError = failure}@@ -1294,7 +1342,7 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Ufinal, resultError = result.Result, result.IsErrorusage = runtime.ParseTokenUsage(result.Usage)case "error":- missingSession = missingSession || strings.Contains(result.Error, "No conversation found with session ID: "+sessionID)+ missingSession = missingSession || strings.Contains(result.Error, missingText)case "assistant", "user", "stream_event":modelStarted = trueif result.Type == "assistant" {@@ -1305,13 +1353,24 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U}}}- _, err = runtime.ExecuteLocalCommand(ctx, workspace, command, runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment}}, sink)+ _, err = runtime.ExecuteLocalCommand(ctx, workspace, command, inv.credentials, sink)if req.OnUsage != nil && assistantUsageReported(usage) {req.OnUsage(usage)}+ if inv.finish != nil {+ inv.finish(err == nil && !resultError && final != "")+ }+ failed := err != nil || (runtime.IsAgentCLI(engine) && streamError != nil)+ if (engine == assistantEngineCodex || runtime.IsAgentCLI(engine)) && req.Resume && failed && !modelStarted {+ missingSession = true+ }if req.Resume && missingSession && !modelStarted && final == "" && ctx.Err() == nil {return "", sessionID, errAssistantSessionMissing}+ if engine != assistantEngineCodeBuddy && ctx.Err() == nil && strings.TrimSpace(final) == "" &&+ (credentialRejected || (streamError != nil && assistantAuthFailureText(streamError.Error()))) {+ return "", sessionID, assistantCredentialError{engine: engine}+ }if credentialRejected && strings.TrimSpace(final) == "" && err == nil && ctx.Err() == nil {return "", sessionID, errAssistantCredentialRejected}diff --git a/internal/httpapi/assistant_effort.go b/internal/httpapi/assistant_effort.goindex 75286b3d..f7fbde99 100644--- a/internal/httpapi/assistant_effort.go+++ b/internal/httpapi/assistant_effort.go@@ -4,6 +4,9 @@ import ("fmt""slices""strings"++ "agentflow/internal/domain"+ "agentflow/internal/runtime")// Mirrors CodeBuddy Code 2.180.0's product reasoning.supportedEfforts and@@ -12,6 +15,13 @@ import (// Keep this snapshot alongside the fixed chat model catalog when updating it.// Empty effort always leaves the model's native default untouched.func assistantModelEfforts(model string) []string {+ if engine, id := assistantModelEngine(model); engine == runtime.AgentCLICursor {+ return runtime.CursorModelEfforts(id)+ } else if engine == runtime.AgentCLIAntigravity {+ return runtime.AgyModelEfforts(id)+ } else if runtime.IsAgentCLI(engine) {+ return domain.ExecutorEffortLevels[engine]+ }switch model {case "hy4std", "hy4-preview-ioa":return []string{"high"}diff --git a/internal/httpapi/assistant_engine_agentcli.go b/internal/httpapi/assistant_engine_agentcli.gonew file mode 100644index 00000000..d0b4d002--- /dev/null+++ b/internal/httpapi/assistant_engine_agentcli.go@@ -0,0 +1,144 @@+package httpapi++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "sync"++ "agentflow/internal/runtime"+)++// prepareAssistantAgentCLIInvocation runs one chat turn on an agent CLI in+// its own headless mode, read-only: the session's MCP gateway stays+// available while the CLI's shell, edit and web tools are denied.+func prepareAssistantAgentCLIInvocation(kind string, o assistantEngineInvocationOpts) (assistantCLIInvocation, error) {+ servers, err := readAssistantMCPServers(o.Config)+ if err != nil {+ return assistantCLIInvocation{}, err+ }+ entries := make(map[string]any, len(servers))+ for id, server := range servers {+ entry := map[string]any{}+ for key, value := range server {+ // CodeBuddy's per-tool defer_loading extension.+ if key != "tools" {+ entry[key] = value+ }+ }+ if url, _ := entry["url"].(string); strings.TrimSpace(url) != "" {+ entry["type"] = "http"+ }+ entries[id] = entry+ }+ if err := runtime.WriteAgentCLIMCPConfig(kind, filepath.Join(o.Root, "home"), entries, runtime.AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ return assistantCLIInvocation{}, err+ }+ resume := ""+ if o.Resume {+ if resume = readAgentCLISession(o.Root, kind, o.SessionID); !agentCLISessionValid(resume) {+ return assistantCLIInvocation{resumeMissing: true}, nil+ }+ }+ systemFile := filepath.Join(o.Root, kind+"-system.md")+ if err := os.WriteFile(systemFile, []byte(o.SystemPrompt), 0o600); err != nil {+ return assistantCLIInvocation{}, err+ }+ agentFile := ""+ if kind == runtime.AgentCLIKimi && resume == "" {+ agentFile = filepath.Join(o.Root, "kimi-agent.md")+ if err := runtime.WriteKimiChatAgent(agentFile, o.SystemPrompt); err != nil {+ return assistantCLIInvocation{}, err+ }+ }+ command := runtime.AgentCLICommand(kind, runtime.AgentCLICommandOptions{+ Binary: o.Bin, Model: o.Model, Effort: o.Effort, Resume: resume, Prompt: o.Prompt,+ SystemPrompt: o.SystemPrompt, SystemPromptFile: systemFile, Chat: true, AgentFile: agentFile,+ })+ command.CredentialBindings = []runtime.CredentialBinding{runtime.BindAgentCLI}+ translate := runtime.NewAgentCLITranslator(kind)+ native := ""+ return assistantCLIInvocation{+ command: command,+ credentials: runtime.RunCredentials{AgentCLI: map[string]runtime.ProviderCredential{kind: o.User}},+ sessionRef: resume,+ translate: func(line string) []string {+ out := translate(line)+ for i, translated := range out {+ out[i] = assistantAgentCLILine(kind, translated, &native)+ }+ return out+ },+ finish: func(ok bool) {+ if ok && agentCLISessionValid(native) {+ _ = writeAgentCLISession(o.Root, kind, o.SessionID, native)+ }+ },+ }, nil+}++// assistantAgentCLILine records the native session a translated line names+// and turns a failed result into an error line: the pipeline reports error+// lines (and recognises a rejected key in them), while a failed result would+// read as an empty reply.+func assistantAgentCLILine(kind, line string, native *string) string {+ var event struct {+ Type string `json:"type"`+ SessionID string `json:"session_id"`+ IsError bool `json:"is_error"`+ Result string `json:"result"`+ }+ if json.Unmarshal([]byte(line), &event) != nil {+ return line+ }+ if id := strings.TrimSpace(event.SessionID); id != "" {+ *native = id+ }+ if event.Type != "result" || !event.IsError {+ return line+ }+ message := strings.TrimSpace(event.Result)+ if message == "" {+ message = assistantEngineLabel(kind) + " 本轮执行失败"+ }+ return codexLine(map[string]any{"type": "error", "error": message, "session_id": *native})+}++// agent-cli-sessions.json maps "<kind>:<chat session>" onto the CLI's own+// session ID, which each CLI assigns itself.+var agentCLISessionsMu sync.Mutex++// agentCLISessionValid guards the native ID before it reaches an argument.+func agentCLISessionValid(id string) bool {+ return id != "" && id[0] != '-' && codexConfigKeyRe.MatchString(id)+}++func agentCLISessionsPath(root string) string {+ return filepath.Join(root, "agent-cli-sessions.json")+}++func readAgentCLISession(root, kind, sessionID string) string {+ agentCLISessionsMu.Lock()+ defer agentCLISessionsMu.Unlock()+ sessions := map[string]string{}+ if data, err := os.ReadFile(agentCLISessionsPath(root)); err == nil {+ _ = json.Unmarshal(data, &sessions)+ }+ return sessions[kind+":"+sessionID]+}++func writeAgentCLISession(root, kind, sessionID, native string) error {+ agentCLISessionsMu.Lock()+ defer agentCLISessionsMu.Unlock()+ sessions := map[string]string{}+ if data, err := os.ReadFile(agentCLISessionsPath(root)); err == nil {+ _ = json.Unmarshal(data, &sessions)+ }+ sessions[kind+":"+sessionID] = native+ data, err := json.Marshal(sessions)+ if err != nil {+ return err+ }+ return os.WriteFile(agentCLISessionsPath(root), data, 0o600)+}diff --git a/internal/httpapi/assistant_engine_cli.go b/internal/httpapi/assistant_engine_cli.gonew file mode 100644index 00000000..ff674ced--- /dev/null+++ b/internal/httpapi/assistant_engine_cli.go@@ -0,0 +1,292 @@+package httpapi++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "sort"+ "strconv"+ "strings"+ "sync"++ "agentflow/internal/managedcli"+ "agentflow/internal/runtime"+)++// assistantCLIInvocation is one prepared chat CLI process. translate turns a+// CLI's own stdout line into CodeBuddy-style stream-json lines; nil means the+// CLI already speaks stream-json. sessionRef is the ID the CLI names in+// "No conversation found with session ID: …".+type assistantCLIInvocation struct {+ command runtime.CommandSpec+ credentials runtime.RunCredentials+ sessionRef string+ translate func(string) []string+ // resumeMissing is true when the CLI cannot resume before it even+ // starts (Codex without a recorded thread for the session).+ resumeMissing bool+ // finish runs after the process exits; ok reports a usable result.+ finish func(ok bool)+}++type assistantEngineInvocationOpts struct {+ Bin, Root, Config, Prompt, Model, Effort, SessionID, SystemPrompt string+ Resume bool+ // ReviewOnly is a one-shot call without MCP servers or session history,+ // such as a title summary.+ ReviewOnly bool+ User runtime.ProviderCredential+}++func assistantEngineConfigDir(engine string) string {+ switch engine {+ case assistantEngineCodex:+ return ".codex"+ case assistantEngineClaude:+ return ".claude"+ default:+ return ".codebuddy"+ }+}++// resolveAssistantEngineBin locates the codex / claude executable the same+// way resolveCodeBuddyBin does: explicit override, managed inventory, PATH,+// then well-known install locations.+func resolveAssistantEngineBin(engine string) (string, error) {+ if engine == assistantEngineCodeBuddy {+ return resolveCodeBuddyBin()+ }+ binary, override, managed := "codex", "AGENTFLOW_CODEX_BIN", "codex"+ if engine == assistantEngineClaude {+ binary, override, managed = "claude", "AGENTFLOW_CLAUDE_BIN", "claude-code"+ } else if runtime.IsAgentCLI(engine) {+ binary, override, managed = runtime.AgentCLIBinary(engine), "AGENTFLOW_"+strings.ToUpper(strings.ReplaceAll(engine, "-", "_"))+"_BIN", ""+ }+ if path := strings.TrimSpace(os.Getenv(override)); path != "" && fileExecutable(path) {+ return path, nil+ }+ if root := strings.TrimSpace(os.Getenv("AGENTFLOW_MANAGED_CLI_ROOT")); root != "" && managed != "" {+ if inventory, err := managedcli.ReadInventory(root); err == nil {+ if path, ok := inventory.BinaryFor(managed); ok {+ return path, nil+ }+ }+ }+ if path, err := exec.LookPath(binary); err == nil {+ return path, nil+ }+ home, _ := os.UserHomeDir()+ if strings.TrimSpace(home) == "" {+ home = "/root"+ }+ for _, candidate := range []string{filepath.Join(home, ".local", "bin", binary), "/usr/local/bin/" + binary, "/usr/bin/" + binary} {+ if fileExecutable(candidate) {+ return candidate, nil+ }+ }+ return "", assistantCLIMissingError{engine: engine, binary: binary}+}++var errAssistantCLIMissing = errors.New("assistant CLI not installed")++// assistantCLIMissingError names the CLI the server lacks; it carries no path+// or credential, so callers show it to the user as is.+type assistantCLIMissingError struct{ engine, binary string }++func (e assistantCLIMissingError) Error() string {+ label := assistantEngineLabel(e.engine)+ return fmt.Sprintf("服务器未安装 %s CLI(%s),请联系管理员安装后再使用 %s 模型", label, e.binary, label)+}++func (e assistantCLIMissingError) Is(target error) bool {+ return target == errAssistantCLIMissing+}++// assistantCredentialError is the authorization failure of a CLI other than CodeBuddy;+// it matches errAssistantCredentialRejected so callers stop retrying.+type assistantCredentialError struct{ engine string }++func (e assistantCredentialError) Error() string {+ label := assistantEngineLabel(e.engine)+ return fmt.Sprintf("%s 拒绝了你的 API Key(401/403),请在「设置」里检查 %s API Key 和 Base URL", label, label)+}++func (e assistantCredentialError) Is(target error) bool {+ return target == errAssistantCredentialRejected+}++var assistantAuthFailureRe = regexp.MustCompile(`(?i)\b(401|403)\b|unauthorized|invalid api key|invalid x-api-key|authentication_error|incorrect api key`)++func assistantAuthFailureText(text string) bool {+ return assistantAuthFailureRe.MatchString(text)+}++// Claude Code adds tools CodeBuddy does not have. Task is its subagent tool,+// so it stays available for project roles.+const claudeAssistantDisallowedTools = "Bash,PowerShell,Monitor,Write,Edit,MultiEdit,NotebookEdit,WebFetch,WebSearch,KillShell,CronCreate,CronList,CronDelete,EnterWorktree,ExitWorktree,Workflow,ScheduleWakeup,DesignSync,RemoteTrigger,PushNotification"++// assistantClaudeSessionID maps a chat CLI session ID onto the UUID Claude+// Code requires. The mapping is stable, so --resume finds the transcript.+func assistantClaudeSessionID(id string) string {+ sum := sha256.Sum256([]byte("agentflow-assistant/" + id))+ sum[6] = sum[6]&0x0f | 0x40+ sum[8] = sum[8]&0x3f | 0x80+ h := hex.EncodeToString(sum[:16])+ return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32]+}++// readAssistantMCPServers reads the session MCP config written by+// writeAgentToolFiles.+func readAssistantMCPServers(path string) (map[string]map[string]any, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, err+ }+ var config struct {+ MCPServers map[string]map[string]any `json:"mcpServers"`+ }+ if err := json.Unmarshal(data, &config); err != nil {+ return nil, err+ }+ return config.MCPServers, nil+}++func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistantCLIInvocation, error) {+ servers, err := readAssistantMCPServers(o.Config)+ if err != nil {+ return assistantCLIInvocation{}, err+ }+ // Claude Code rejects CodeBuddy's per-tool defer_loading extension.+ for _, server := range servers {+ delete(server, "tools")+ }+ mcpPath := filepath.Join(o.Root, "claude-mcp.json")+ settingsPath := filepath.Join(o.Root, "claude-settings.json")+ mcp, _ := json.Marshal(map[string]any{"mcpServers": servers})+ settings, _ := json.Marshal(map[string]any{"permissions": map[string]any{"deny": strings.Split(claudeAssistantDisallowedTools, ",")}})+ if err := os.WriteFile(mcpPath, mcp, 0o600); err != nil {+ return assistantCLIInvocation{}, err+ }+ if err := os.WriteFile(settingsPath, settings, 0o600); err != nil {+ return assistantCLIInvocation{}, err+ }+ sessionID := assistantClaudeSessionID(o.SessionID)+ argv := []string{o.Bin, "-p", "--verbose", "--output-format", "stream-json", "--include-partial-messages",+ "--max-turns", nativeAssistantUnlimitedTurns, "--system-prompt", o.SystemPrompt,+ "--mcp-config", mcpPath, "--strict-mcp-config", "--settings", settingsPath, "--setting-sources", "user",+ "--permission-mode", "bypassPermissions", "--disallowedTools", claudeAssistantDisallowedTools,+ "--model", o.Model}+ if effort := strings.TrimSpace(o.Effort); effort != "" {+ argv = append(argv, "--effort", effort)+ }+ if o.ReviewOnly {+ argv = append(argv, "--tools", "", "--no-session-persistence")+ }+ if o.Resume {+ argv = append(argv, "--resume", sessionID)+ } else {+ argv = append(argv, "--session-id", sessionID)+ }+ // --disallowedTools is variadic: end option parsing before the prompt.+ argv = append(argv, "--", o.Prompt)+ command := runtime.CommandSpec{Argv: argv, Provider: "claude-code", CredentialBindings: []runtime.CredentialBinding{runtime.BindClaudeCode}}+ return assistantCLIInvocation{+ command: command.WithClaudeBypassAccepted(),+ credentials: runtime.RunCredentials{ClaudeCode: o.User},+ sessionRef: sessionID,+ }, nil+}++// Codex tools that act outside the platform gateway. The chat runs on the+// control plane, so they are switched off together with the shell. Feature+// flags alone do not stop every built-in tool, so the app-server path also+// installs assistantCodexGuard.+var codexAssistantDisabledFeatures = []string{+ "shell_tool", "unified_exec", "apply_patch_freeform", "multi_agent", "multi_agent_v2",+ "js_repl", "code_mode", "apps", "plugins", "memories", "image_generation",+ "browser_use", "browser_use_external", "computer_use", "in_app_browser",+ "tool_suggest", "skill_search", "view_image", "goals", "collab", "sleep_tool", "worktrees",+}++// codexAssistantGuardArgs forces the PreToolUse denial hook. app-server has+// no --dangerously-bypass-hook-trust flag; hooks.bypass_hook_trust is the+// config override it accepts.+func codexAssistantGuardArgs(guardPath string) []string {+ command := "python3 " + strconv.Quote(guardPath)+ hook := "hooks.PreToolUse=[{hooks=[{type=\"command\",command=" + strconv.Quote(command) + ",timeout=5}]}]"+ return []string{"-c", "features.hooks=true", "-c", "hooks.bypass_hook_trust=true", "-c", hook}+}++var codexConfigKeyRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)++func codexAssistantMCPArgs(servers map[string]map[string]any) []string {+ ids := make([]string, 0, len(servers))+ for id := range servers {+ if codexConfigKeyRe.MatchString(id) {+ ids = append(ids, id)+ }+ }+ sort.Strings(ids)+ var args []string+ for _, id := range ids {+ server := servers[id]+ prefix := "mcp_servers." + id + "."+ if url, _ := server["url"].(string); strings.TrimSpace(url) != "" {+ args = append(args, "-c", prefix+"url="+strconv.Quote(url))+ } else if command, _ := server["command"].(string); strings.TrimSpace(command) != "" {+ args = append(args, "-c", prefix+"command="+strconv.Quote(command))+ if list, ok := server["args"].([]any); ok && len(list) > 0 {+ parts := make([]string, 0, len(list))+ for _, value := range list {+ parts = append(parts, strconv.Quote(fmt.Sprint(value)))+ }+ args = append(args, "-c", prefix+"args=["+strings.Join(parts, ",")+"]")+ }+ } else {+ continue+ }+ // The session gateway lists upstream tools before answering, which+ // can take longer than Codex's default MCP startup wait.+ // The platform gateway applies the user's approval mode itself; Codex+ // would otherwise refuse every MCP call under approval_policy=never.+ args = append(args, "-c", prefix+"startup_timeout_sec="+strconv.Itoa(int(agentToolSessionMCPStartupWait.Seconds())), "-c", prefix+"tool_timeout_sec=600", "-c", prefix+`default_tools_approval_mode="approve"`)+ }+ return args+}++var codexThreadsMu sync.Mutex++func codexThreadsPath(root string) string { return filepath.Join(root, "codex-threads.json") }++func readCodexThread(root, sessionID string) string {+ codexThreadsMu.Lock()+ defer codexThreadsMu.Unlock()+ threads := map[string]string{}+ if data, err := os.ReadFile(codexThreadsPath(root)); err == nil {+ _ = json.Unmarshal(data, &threads)+ }+ return threads[sessionID]+}++func writeCodexThread(root, sessionID, threadID string) error {+ codexThreadsMu.Lock()+ defer codexThreadsMu.Unlock()+ threads := map[string]string{}+ if data, err := os.ReadFile(codexThreadsPath(root)); err == nil {+ _ = json.Unmarshal(data, &threads)+ }+ threads[sessionID] = threadID+ data, err := json.Marshal(threads)+ if err != nil {+ return err+ }+ return os.WriteFile(codexThreadsPath(root), data, 0o600)+}++var errAssistantEngineUnsupported = errors.New("该调用只支持 CodeBuddy 模型")diff --git a/internal/httpapi/assistant_engine_codex.go b/internal/httpapi/assistant_engine_codex.gonew file mode 100644index 00000000..152ddae4--- /dev/null+++ b/internal/httpapi/assistant_engine_codex.go@@ -0,0 +1,354 @@+package httpapi++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "sync"++ "agentflow/internal/runtime"+)++// prepareAssistantCodexInvocation runs one chat turn on `codex app-server`.+// `codex exec --json` reports only finished items; the app server also+// streams reasoning and reply deltas over its stdio JSON-RPC.+func prepareAssistantCodexInvocation(o assistantEngineInvocationOpts) (assistantCLIInvocation, error) {+ servers, err := readAssistantMCPServers(o.Config)+ if err != nil {+ return assistantCLIInvocation{}, err+ }+ thread := ""+ if o.Resume {+ if thread = readCodexThread(o.Root, o.SessionID); thread == "" || !codexConfigKeyRe.MatchString(thread) {+ return assistantCLIInvocation{resumeMissing: true}, nil+ }+ }+ guard := filepath.Join(o.Root, "codex-native-guard.py")+ if err = os.WriteFile(guard, []byte(assistantCodexGuard), 0o600); err != nil {+ return assistantCLIInvocation{}, err+ }+ argv := []string{o.Bin, "app-server", "-c", `web_search="disabled"`}+ for _, feature := range codexAssistantDisabledFeatures {+ argv = append(argv, "-c", "features."+feature+"=false")+ }+ argv = append(argv, codexAssistantGuardArgs(guard)...)+ argv = append(argv, codexAssistantMCPArgs(servers)...)+ if effort := strings.TrimSpace(o.Effort); effort != "" {+ argv = append(argv, "-c", "model_reasoning_effort="+strconv.Quote(effort))+ }+ // BindCodex inserts its provider overrides before the last argument.+ argv = append(argv, "--stdio")+ stdin, input, err := os.Pipe()+ if err != nil {+ return assistantCLIInvocation{}, err+ }+ server := &codexAppServer{input: input, opts: o, resume: thread, pending: map[string]string{}, started: map[string]bool{}}+ server.request("initialize", map[string]any{"clientInfo": map[string]string{"name": "agentflow", "title": "AgentFlow", "version": "1"}})+ return assistantCLIInvocation{+ command: runtime.CommandSpec{Argv: argv, Provider: "codex", CredentialBindings: []runtime.CredentialBinding{runtime.BindCodex}, Stdin: stdin},+ credentials: runtime.RunCredentials{Codex: o.User},+ sessionRef: thread,+ translate: server.translate,+ finish: func(ok bool) {+ server.closeInput()+ _ = stdin.Close()+ if ok && server.threadID != "" && codexConfigKeyRe.MatchString(server.threadID) {+ _ = writeCodexThread(o.Root, o.SessionID, server.threadID)+ }+ },+ }, nil+}++// codexAppServer drives one turn: initialize, thread/start (or+// thread/resume), turn/start, then closes stdin on turn/completed so the+// server exits. translate runs on the process's stdout goroutine and rewrites+// notifications as the CodeBuddy-style stream-json lines the chat pipeline+// parses: deltas become stream_event blocks, finished messages and reasoning+// become assistant blocks, tool items become tool_use / tool_result, and the+// turn's end becomes the result line.+type codexAppServer struct {+ input *os.File+ inputOnce sync.Once+ opts assistantEngineInvocationOpts+ resume string+ nextID int+ pending map[string]string+ threadID string+ lastMessage string+ turnError string+ usage map[string]any+ started map[string]bool+ // block is the key of the open stream_event content block.+ block string+}++type codexRPCMessage struct {+ ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ Params json.RawMessage `json:"params"`+ Result json.RawMessage `json:"result"`+ Error *struct {+ Message string `json:"message"`+ } `json:"error"`+}++type codexAppItem struct {+ ID string `json:"id"`+ Type string `json:"type"`+ Text string `json:"text"`+ Summary []string `json:"summary"`+ Content []string `json:"content"`+ Server string `json:"server"`+ Tool string `json:"tool"`+ Arguments json.RawMessage `json:"arguments"`+ Status string `json:"status"`+ Error json.RawMessage `json:"error"`+ Command string `json:"command"`+ Query string `json:"query"`+ ExitCode *int `json:"exitCode"`+}++func codexLine(v any) string {+ data, _ := json.Marshal(v)+ return string(data)+}++func (s *codexAppServer) write(message map[string]any) {+ data, err := json.Marshal(message)+ if err != nil {+ return+ }+ // A failed write means the server already exited; its exit status reports why.+ _, _ = s.input.Write(append(data, '\n'))+}++func (s *codexAppServer) request(method string, params any) {+ s.nextID+++ s.pending[strconv.Itoa(s.nextID)] = method+ s.write(map[string]any{"id": s.nextID, "method": method, "params": params})+}++func (s *codexAppServer) closeInput() {+ s.inputOnce.Do(func() { _ = s.input.Close() })+}++// fail ends the turn with an error line the pipeline reports.+func (s *codexAppServer) fail(message string) []string {+ s.closeInput()+ return append(s.closeBlock(), codexLine(map[string]any{"type": "error", "error": message}))+}++func (s *codexAppServer) translate(line string) []string {+ line = strings.TrimSpace(line)+ if line == "" || line[0] != '{' {+ return nil+ }+ var message codexRPCMessage+ if json.Unmarshal([]byte(line), &message) != nil {+ return nil+ }+ switch {+ case message.Method != "" && len(message.ID) > 0:+ // Approvals and elicitations cannot be answered in a chat turn; the+ // platform gateway applies the user's approval mode itself.+ s.write(map[string]any{"id": message.ID, "error": map[string]any{"code": -32601, "message": "AgentFlow 对话不支持该请求"}})+ return nil+ case message.Method == "":+ return s.response(message)+ default:+ return s.notification(message.Method, message.Params)+ }+}++func (s *codexAppServer) response(message codexRPCMessage) []string {+ id := string(message.ID)+ method := s.pending[id]+ delete(s.pending, id)+ failure := ""+ if message.Error != nil {+ failure = strings.TrimSpace(message.Error.Message)+ if failure == "" {+ failure = method + " failed"+ }+ }+ switch method {+ case "initialize":+ if failure != "" {+ return s.fail("Codex app-server 初始化失败:" + failure)+ }+ s.write(map[string]any{"method": "initialized", "params": map[string]any{}})+ params := map[string]any{"model": s.opts.Model, "developerInstructions": s.opts.SystemPrompt, "sandbox": "read-only", "approvalPolicy": "never"}+ if s.resume != "" {+ params["threadId"] = s.resume+ s.request("thread/resume", params)+ } else {+ s.request("thread/start", params)+ }+ case "thread/start", "thread/resume":+ if failure != "" {+ if method == "thread/resume" {+ // runAssistantCLI recognises this text as a missing session.+ return s.fail("No conversation found with session ID: " + s.resume)+ }+ return s.fail(failure)+ }+ var result struct {+ Thread struct {+ ID string `json:"id"`+ } `json:"thread"`+ }+ _ = json.Unmarshal(message.Result, &result)+ s.threadID = strings.TrimSpace(result.Thread.ID)+ s.request("turn/start", map[string]any{"threadId": s.threadID, "input": []map[string]any{{"type": "text", "text": s.opts.Prompt, "text_elements": []any{}}}})+ return []string{codexLine(map[string]any{"type": "system", "subtype": "init", "session_id": s.threadID})}+ case "turn/start":+ if failure != "" {+ return s.fail(failure)+ }+ }+ return nil+}++func (s *codexAppServer) notification(method string, raw json.RawMessage) []string {+ var params struct {+ ItemID string `json:"itemId"`+ Delta string `json:"delta"`+ SummaryIndex int `json:"summaryIndex"`+ ContentIndex int `json:"contentIndex"`+ Item codexAppItem `json:"item"`+ WillRetry bool `json:"willRetry"`+ Error struct {+ Message string `json:"message"`+ } `json:"error"`+ TokenUsage struct {+ Last struct {+ InputTokens int64 `json:"inputTokens"`+ CachedInputTokens int64 `json:"cachedInputTokens"`+ OutputTokens int64 `json:"outputTokens"`+ } `json:"last"`+ } `json:"tokenUsage"`+ Turn struct {+ Status string `json:"status"`+ Error *struct {+ Message string `json:"message"`+ } `json:"error"`+ } `json:"turn"`+ }+ if json.Unmarshal(raw, ¶ms) != nil {+ return nil+ }+ switch method {+ case "item/agentMessage/delta":+ return s.delta(params.ItemID, "text", params.Delta)+ case "item/reasoning/summaryTextDelta":+ return s.delta(fmt.Sprintf("%s#%d", params.ItemID, params.SummaryIndex), "thinking", params.Delta)+ case "item/reasoning/textDelta":+ return s.delta(fmt.Sprintf("%s#raw%d", params.ItemID, params.ContentIndex), "thinking", params.Delta)+ case "item/started":+ return s.item(params.Item, false)+ case "item/completed":+ return s.item(params.Item, true)+ case "thread/tokenUsage/updated":+ last := params.TokenUsage.Last+ s.usage = map[string]any{"input_tokens": last.InputTokens, "cached_input_tokens": last.CachedInputTokens, "output_tokens": last.OutputTokens}+ case "error":+ if !params.WillRetry {+ s.turnError = strings.TrimSpace(params.Error.Message)+ }+ case "turn/completed":+ if params.Turn.Status == "completed" {+ s.closeInput()+ return append(s.closeBlock(), codexLine(map[string]any{"type": "result", "result": s.lastMessage, "is_error": false, "usage": s.usage, "session_id": s.threadID}))+ }+ message := s.turnError+ if params.Turn.Error != nil && strings.TrimSpace(params.Turn.Error.Message) != "" {+ message = strings.TrimSpace(params.Turn.Error.Message)+ }+ if message == "" {+ message = "Codex turn " + params.Turn.Status+ }+ return s.fail(message)+ }+ return nil+}++// delta streams text into the content block key, opening it first.+func (s *codexAppServer) delta(key, kind, text string) []string {+ if text == "" {+ return nil+ }+ var out []string+ if s.block != key {+ out = append(s.closeBlock(), codexLine(map[string]any{"type": "stream_event", "event": map[string]any{"type": "content_block_start", "content_block": map[string]any{"type": kind}}}))+ s.block = key+ }+ delta := map[string]any{"type": "text_delta", "text": text}+ if kind == "thinking" {+ delta = map[string]any{"type": "thinking_delta", "thinking": text}+ }+ return append(out, codexLine(map[string]any{"type": "stream_event", "event": map[string]any{"type": "content_block_delta", "delta": delta}}))+}++func (s *codexAppServer) closeBlock() []string {+ if s.block == "" {+ return nil+ }+ s.block = ""+ return []string{codexLine(map[string]any{"type": "stream_event", "event": map[string]any{"type": "content_block_stop"}})}+}++func codexAssistantBlock(block map[string]any) string {+ return codexLine(map[string]any{"type": "assistant", "message": map[string]any{"content": []map[string]any{block}}})+}++func (s *codexAppServer) item(item codexAppItem, completed bool) []string {+ id := strings.TrimSpace(item.ID)+ var name string+ var input any+ switch item.Type {+ case "agentMessage":+ if !completed || strings.TrimSpace(item.Text) == "" {+ return nil+ }+ s.lastMessage = item.Text+ return append(s.closeBlock(), codexAssistantBlock(map[string]any{"type": "text", "text": item.Text}))+ case "reasoning":+ // Models without reasoning summaries (e.g. DeepSeek) return raw reasoning text instead.+ text := strings.Join(item.Summary, "\n\n")+ if strings.TrimSpace(text) == "" {+ text = strings.Join(item.Content, "\n\n")+ }+ if !completed || strings.TrimSpace(text) == "" {+ return nil+ }+ return append(s.closeBlock(), codexAssistantBlock(map[string]any{"type": "thinking", "thinking": text}))+ case "mcpToolCall":+ name = "mcp__" + item.Server + "__" + item.Tool+ input = item.Arguments+ if len(item.Arguments) == 0 || string(item.Arguments) == "null" {+ input = map[string]any{}+ }+ case "commandExecution":+ name, input = "Bash", map[string]string{"command": item.Command}+ case "webSearch":+ name, input = "WebSearch", map[string]string{"query": item.Query}+ default:+ return nil+ }+ if id == "" {+ return nil+ }+ out := s.closeBlock()+ if !s.started[id] {+ s.started[id] = true+ out = append(out, codexAssistantBlock(map[string]any{"type": "tool_use", "id": id, "name": name, "input": input}))+ }+ if completed {+ failed := item.Status == "failed" || item.Status == "declined" || (len(item.Error) > 0 && string(item.Error) != "null") || (item.ExitCode != nil && *item.ExitCode != 0)+ out = append(out, codexLine(map[string]any{"type": "user", "message": map[string]any{"content": []map[string]any{{"type": "tool_result", "tool_use_id": id, "is_error": failed, "content": ""}}}}))+ }+ return out+}diff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.gonew file mode 100644index 00000000..18319b42--- /dev/null+++ b/internal/httpapi/assistant_engines.go@@ -0,0 +1,552 @@+package httpapi++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/runtime"+)++// AI 对话 runs on CodeBuddy by default. A model ID prefixed with another CLI+// ("codex:", "claude-code:" or an agent CLI kind such as "opencode:") runs the+// turn on that CLI with the caller's own key and Base URL from 个人配置; the+// part after the prefix is passed to the CLI as-is.+const (+ assistantEngineCodeBuddy = "codebuddy"+ assistantEngineCodex = "codex"+ assistantEngineClaude = "claude-code"+)++// assistantCLIEngines are the CLIs other than CodeBuddy, in switch order.+func assistantCLIEngines() []string {+ return append([]string{assistantEngineCodex, assistantEngineClaude}, runtime.AgentCLIKinds...)+}++func assistantModelEngine(id string) (engine, model string) {+ id = strings.TrimSpace(id)+ for _, engine := range assistantCLIEngines() {+ if rest, ok := strings.CutPrefix(id, engine+":"); ok {+ return engine, strings.TrimSpace(rest)+ }+ }+ return assistantEngineCodeBuddy, id+}++// assistantEngineOption is one entry of the chat composer's CLI switch.+// Credential names the 个人配置 field that enables it.+type assistantEngineOption struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Configured bool `json:"configured"`+ Credential string `json:"credential"`+}++// assistantEngineCredentialField is the 个人配置 field that enables a CLI.+func assistantEngineCredentialField(engine string) string {+ switch engine {+ case assistantEngineCodeBuddy:+ return "codeBuddyApiKey"+ case assistantEngineCodex:+ return "codexApiKey"+ case assistantEngineClaude:+ return "claudeCodeApiKey"+ }+ return "agentCli." + engine+}++// assistantEngineOptions lists every CLI, configured or not, so the switch+// also shows where to add a key. CodeBuddy counts as configured when the+// platform sponsors chats without one.+func assistantEngineOptions(user domain.User, sponsored bool) []assistantEngineOption {+ engines := append([]string{assistantEngineCodeBuddy}, assistantCLIEngines()...)+ out := make([]assistantEngineOption, 0, len(engines))+ for _, engine := range engines {+ key, _ := assistantEngineCredential(user, engine)+ out = append(out, assistantEngineOption{+ ID: engine,+ Name: assistantEngineLabel(engine),+ Configured: key != "" || (engine == assistantEngineCodeBuddy && sponsored),+ Credential: assistantEngineCredentialField(engine),+ })+ }+ return out+}++func assistantEngineLabel(engine string) string {+ switch engine {+ case assistantEngineCodex:+ return "Codex"+ case assistantEngineClaude:+ return "Claude Code"+ case assistantEngineCodeBuddy, "":+ return "CodeBuddy"+ }+ return runtime.AgentCLILabel(engine)+}++func assistantEngineCredential(user domain.User, engine string) (apiKey, baseURL string) {+ switch engine {+ case assistantEngineCodex:+ return strings.TrimSpace(user.CodexAPIKey), strings.TrimSpace(user.CodexBaseURL)+ case assistantEngineClaude:+ return strings.TrimSpace(user.ClaudeCodeAPIKey), strings.TrimSpace(user.ClaudeCodeBaseURL)+ case assistantEngineCodeBuddy:+ return strings.TrimSpace(user.CodeBuddyAPIKey), ""+ }+ cred := user.AgentCLICredentials[engine]+ if runtime.IsAgentCLI(engine) && engine != runtime.AgentCLICursor {+ baseURL = strings.TrimSpace(cred.BaseURL)+ }+ return strings.TrimSpace(cred.APIKey), baseURL+}++// assistantEngineProtocol is the API protocol an agent CLI speaks; "" for+// the other CLIs.+func assistantEngineProtocol(user domain.User, engine string) string {+ if !runtime.IsAgentCLI(engine) {+ return ""+ }+ return runtime.AgentCLIProtocol(engine, user.AgentCLICredentials[engine].Protocol)+}++// assistantEngineAnthropicModels reports whether the model list behind a+// Base URL is the Anthropic one ({base}/v1/models, x-api-key).+func assistantEngineAnthropicModels(engine, protocol string) bool {+ return engine == assistantEngineClaude || protocol == runtime.AgentCLIProtocolMessages+}++func assistantEngineCustomModels(user domain.User, engine string) []domain.CLIModel {+ switch engine {+ case assistantEngineCodex:+ return user.CodexModels+ case assistantEngineClaude:+ return user.ClaudeCodeModels+ }+ return user.AgentCLICredentials[engine].Models+}++// assistantEngineBuiltinModels is the executor catalog for a CLI, used on the+// official endpoint (no Base URL) or when the Base URL lists no model.+func assistantEngineBuiltinModels(engine string) []assistantDiscoveredModel {+ catalogKey := engine+ if engine == assistantEngineClaude {+ catalogKey = "claude"+ }+ var out []assistantDiscoveredModel+ for _, model := range executorModelCatalogs()[catalogKey].Models {+ out = append(out, assistantDiscoveredModel{ID: model.ID, Name: model.Name})+ }+ return out+}++// assistantValidEngineModel guards model IDs that reach a CLI argument or a+// TOML config override.+func assistantValidEngineModel(model string) bool {+ if model == "" || len(model) > 128 {+ return false+ }+ for _, r := range model {+ if r <= ' ' || r == 0x7f || r == '"' || r == '\'' || r == '`' || r == '\\' {+ return false+ }+ }+ return true+}++// assistantConversationEngine is the CLI that wrote the conversation's latest+// own reply, "" before the first one. Role replies (SpeakerAgentID) run on+// their own executors and do not count. A turn that failed before producing+// anything leaves no reply, so it does not pin the CLI.+//+// Replies saved before model prefixes carry the CLI on the session Executor+// (legacyExecutor) instead. An unprefixed model is not itself proof of CodeBuddy.+func assistantConversationEngine(messages []assistantMessage, legacyExecutor ...string) string {+ for i := len(messages) - 1; i >= 0; i-- {+ m := messages[i]+ if m.Role != "assistant" || m.SpeakerAgentID != "" || strings.TrimSpace(m.Model) == "" {+ continue+ }+ if assistantModelHasEnginePrefix(m.Model) {+ engine, _ := assistantModelEngine(m.Model)+ return engine+ }+ if legacy := assistantLegacyExecutor(legacyExecutor...); legacy != "" && legacy != assistantEngineCodeBuddy {+ return legacy+ }+ engine, _ := assistantModelEngine(m.Model)+ return engine+ }+ return ""+}++func assistantModelHasEnginePrefix(id string) bool {+ id = strings.TrimSpace(id)+ for _, engine := range append([]string{assistantEngineCodeBuddy}, assistantCLIEngines()...) {+ if _, ok := strings.CutPrefix(id, engine+":"); ok {+ return true+ }+ }+ return false+}++// assistantLegacyExecutor maps a session Executor saved before model prefixes.+// CodeBuddy and an empty value stay unset so an unprefixed model remains CodeBuddy.+func assistantLegacyExecutor(candidates ...string) string {+ for _, raw := range candidates {+ switch id := strings.ToLower(strings.TrimSpace(raw)); id {+ case assistantEngineCodex:+ return assistantEngineCodex+ case "claude", assistantEngineClaude:+ return assistantEngineClaude+ case "", assistantEngineCodeBuddy:+ continue+ default:+ for _, kind := range domain.AgentCLIExecutorKinds {+ if strings.EqualFold(kind, id) {+ return kind+ }+ }+ }+ }+ return ""+}++// assistantEngineSwitchRefusal keeps a conversation on one CLI. Its native+// session holds tool calls and reasoning that no other CLI can resume, so a+// switch would silently drop them; a new conversation is the only way.+func assistantEngineSwitchRefusal(locked, model string) string {+ engine, _ := assistantModelEngine(model)+ if locked == "" || locked == engine {+ return ""+ }+ return fmt.Sprintf("这个对话由 %s 回复,不能中途切换 CLI;请新建对话后使用 %s", assistantEngineLabel(locked), assistantEngineLabel(engine))+}++func assistantEngineMissingKey(engine string) string {+ return fmt.Sprintf("请先在个人配置中配置 %s API Key 后再使用 %s 模型", assistantEngineLabel(engine), assistantEngineLabel(engine))+}++// assistantTurnUser resolves the identity and model of one chat turn. Codex+// and Claude Code models need the caller's own key for that CLI and are never+// sponsored; CodeBuddy models keep the sponsor fallback. The returned user+// still carries a lent CodeBuddy key when there is one, so approval reviews+// keep working on Codex / Claude Code turns.+func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string) (domain.User, string, string) {+ engine, _ := assistantModelEngine(model)+ if engine != assistantEngineCodeBuddy {+ if key, _ := assistantEngineCredential(stored, engine); key == "" {+ return stored, "", assistantEngineMissingKey(engine)+ }+ user, _, _ := h.assistantChatUser(stored)+ return user, model, ""+ }+ user, shared, ok := h.assistantChatUser(stored)+ if !ok {+ return stored, "", "请先在个人配置中配置自己的 CodeBuddy API Key"+ }+ if len(shared) > 0 {+ forced, allowed := assistantSponsoredModelFor(shared, model)+ if !allowed {+ return stored, "", errAssistantSponsoredModel(shared)+ }+ model = forced+ }+ return user, model, ""+}++// assistantAllowedUserModel is assistantAllowedModel plus the caller's CLI+// models. Any well-formed model ID is accepted for a configured CLI: the+// gateway behind the Base URL decides what exists, and a discovery outage+// must not silently move the conversation back to CodeBuddy.+func assistantAllowedUserModel(id string, catalog assistantModelCatalog, user domain.User) string {+ engine, model := assistantModelEngine(id)+ if engine == assistantEngineCodeBuddy {+ return assistantAllowedModel(id, catalog)+ }+ if key, _ := assistantEngineCredential(user, engine); key == "" || !assistantValidEngineModel(model) {+ return catalog.Default+ }+ return engine + ":" + model+}++// assistantEngineModels lists the Codex / Claude Code models the user can+// chat with: the list from 个人配置 when set, otherwise the models the Base+// URL publishes, otherwise the built-in executor catalog.+func assistantEngineModels(ctx context.Context, user domain.User) []assistantModel {+ var out []assistantModel+ for _, engine := range assistantCLIEngines() {+ key, baseURL := assistantEngineCredential(user, engine)+ if key == "" {+ continue+ }+ protocol := assistantEngineProtocol(user, engine)+ if protocol == runtime.AgentCLIProtocolGemini {+ // A Gemini endpoint publishes no OpenAI-style model list.+ baseURL = ""+ }+ // The official endpoint serves the CLI's own models, so a catalog+ // only applies behind a Base URL.+ var listed []assistantDiscoveredModel+ if baseURL != "" {+ for _, model := range assistantEngineCustomModels(user, engine) {+ if assistantValidEngineModel(model.ID) {+ listed = append(listed, assistantDiscoveredModel{ID: model.ID, Name: model.Name})+ }+ }+ if len(listed) == 0 {+ listed = cachedAssistantEngineDiscovery(ctx, assistantEngineAnthropicModels(engine, protocol), key, baseURL)+ }+ }+ if engine == runtime.AgentCLICursor {+ listed = cachedCursorModels(key)+ }+ if len(listed) == 0 {+ listed = assistantEngineBuiltinModels(engine)+ }+ for _, model := range listed {+ name := strings.TrimSpace(model.Name)+ if name == "" {+ name = model.ID+ }+ id := engine + ":" + model.ID+ out = append(out, assistantModel{+ ID: id,+ Name: name,+ Family: assistantModelFamily(model.ID),+ Engine: engine,+ Efforts: assistantModelEfforts(id),+ })+ }+ }+ return out+}++type assistantDiscoveredModel struct {+ ID string+ Name string+}++type assistantDiscoveryEntry struct {+ models []assistantDiscoveredModel+ expires time.Time+}++const (+ assistantDiscoveryTTL = 10 * time.Minute+ assistantDiscoveryFailureTTL = time.Minute+ assistantDiscoveryTimeout = 4 * time.Second+ assistantDiscoveryMaxModels = 100+)++var (+ assistantDiscoveryCache sync.Map // sha256(engine, baseURL, key) -> assistantDiscoveryEntry+ // assistantEngineDiscover is a variable so tests can stub the network.+ assistantEngineDiscover = discoverAssistantEngineModels+)++func cachedAssistantEngineDiscovery(ctx context.Context, anthropic bool, apiKey, baseURL string) []assistantDiscoveredModel {+ sum := sha256.Sum256([]byte(fmt.Sprint(anthropic) + "\x00" + baseURL + "\x00" + apiKey))+ cacheKey := hex.EncodeToString(sum[:])+ now := time.Now()+ if cached, ok := assistantDiscoveryCache.Load(cacheKey); ok {+ if entry := cached.(assistantDiscoveryEntry); now.Before(entry.expires) {+ return entry.models+ }+ }+ ctx, cancel := context.WithTimeout(ctx, assistantDiscoveryTimeout)+ defer cancel()+ models, err := assistantEngineDiscover(ctx, anthropic, apiKey, baseURL)+ ttl := assistantDiscoveryTTL+ if err != nil || len(models) == 0 {+ models, ttl = nil, assistantDiscoveryFailureTTL+ }+ assistantDiscoveryCache.Store(cacheKey, assistantDiscoveryEntry{models: models, expires: now.Add(ttl)})+ return models+}++var (+ assistantCursorModelsCache sync.Map // sha256(key) -> assistantDiscoveryEntry+ assistantCursorModelsInflight sync.Map+ // assistantCursorModels is a variable so tests can stub cursor-agent.+ assistantCursorModels = cursorAgentModels+)++// cachedCursorModels lists the models the key's Cursor plan offers. The CLI+// takes seconds, so a miss answers with the built-in catalog (nil) while a+// background refresh fills the cache; a stale list is served meanwhile.+func cachedCursorModels(apiKey string) []assistantDiscoveredModel {+ sum := sha256.Sum256([]byte("cursor\x00" + apiKey))+ cacheKey := hex.EncodeToString(sum[:])+ var stale []assistantDiscoveredModel+ if cached, ok := assistantCursorModelsCache.Load(cacheKey); ok {+ entry := cached.(assistantDiscoveryEntry)+ if time.Now().Before(entry.expires) {+ return entry.models+ }+ stale = entry.models+ }+ if _, running := assistantCursorModelsInflight.LoadOrStore(cacheKey, true); !running {+ go func() {+ defer assistantCursorModelsInflight.Delete(cacheKey)+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ found, err := assistantCursorModels(ctx, apiKey)+ var models []assistantDiscoveredModel+ for _, model := range found {+ if assistantValidEngineModel(model.ID) && len(models) < assistantDiscoveryMaxModels {+ models = append(models, assistantDiscoveredModel{ID: model.ID, Name: model.Name})+ }+ }+ ttl := assistantDiscoveryTTL+ if err != nil || len(models) == 0 {+ models, ttl = stale, assistantDiscoveryFailureTTL+ }+ assistantCursorModelsCache.Store(cacheKey, assistantDiscoveryEntry{models: models, expires: time.Now().Add(ttl)})+ }()+ }+ return stale+}++// discoverAssistantEngineModels reads the OpenAI-style model list behind a+// Base URL: {base}/models for OpenAI-style Base URLs (which already end in+// /v1) and {base}/v1/models for Anthropic ones. Gateways answer both with+// {"data":[{"id":…,"display_name"|"name":…}]}.+func discoverAssistantEngineModels(ctx context.Context, anthropic bool, apiKey, baseURL string) ([]assistantDiscoveredModel, error) {+ endpoint := strings.TrimRight(baseURL, "/")+ if anthropic {+ endpoint += "/v1/models"+ } else {+ endpoint += "/models"+ }+ if !strings.HasPrefix(endpoint, "https://") && !strings.HasPrefix(endpoint, "http://") {+ return nil, fmt.Errorf("Base URL 必须以 http:// 或 https:// 开头")+ }+ schemes := []string{"bearer"}+ if anthropic {+ schemes = append(schemes, "x-api-key")+ }+ var lastErr error+ for _, scheme := range schemes {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)+ if err != nil {+ return nil, err+ }+ if scheme == "bearer" {+ req.Header.Set("Authorization", "Bearer "+apiKey)+ } else {+ req.Header.Set("x-api-key", apiKey)+ req.Header.Set("anthropic-version", "2023-06-01")+ }+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ var urlErr *url.Error+ if errors.As(err, &urlErr) {+ err = urlErr.Err+ }+ return nil, fmt.Errorf("无法连接 %s:%w", endpoint, err)+ }+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))+ resp.Body.Close()+ if err != nil {+ return nil, err+ }+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ lastErr = fmt.Errorf("%s 拒绝了 API Key(HTTP %d)", endpoint, resp.StatusCode)+ continue+ }+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("%s 返回 HTTP %d", endpoint, resp.StatusCode)+ }+ var payload struct {+ Data []struct {+ ID string `json:"id"`+ Name string `json:"name"`+ DisplayName string `json:"display_name"`+ } `json:"data"`+ }+ if err := json.Unmarshal(body, &payload); err != nil {+ return nil, fmt.Errorf("%s 返回的不是模型列表", endpoint)+ }+ var out []assistantDiscoveredModel+ seen := map[string]bool{}+ for _, item := range payload.Data {+ id := strings.TrimSpace(item.ID)+ if !assistantValidEngineModel(id) || seen[id] {+ continue+ }+ seen[id] = true+ name := strings.TrimSpace(item.DisplayName)+ if name == "" {+ name = strings.TrimSpace(item.Name)+ }+ out = append(out, assistantDiscoveredModel{ID: id, Name: truncateRunes(name, 64)})+ if len(out) == assistantDiscoveryMaxModels {+ break+ }+ }+ return out, nil+ }+ return nil, lastErr+}++// assistantEngineState records which CLI holds a personal conversation's+// native transcript. A turn on another CLI cannot resume it: it starts a new+// CLI session from the full transcript, so switching back never continues a+// transcript that misses the turns in between.+type assistantEngineState struct {+ Engine string `json:"engine"`+ SessionID string `json:"sessionId"`+}++func readAssistantEngineState(root string) assistantEngineState {+ state := assistantEngineState{Engine: assistantEngineCodeBuddy}+ data, err := os.ReadFile(filepath.Join(root, "engine.json"))+ if err != nil || json.Unmarshal(data, &state) != nil || state.Engine == "" {+ return assistantEngineState{Engine: assistantEngineCodeBuddy}+ }+ return state+}++func writeAssistantEngineState(root string, state assistantEngineState) error {+ data, err := json.Marshal(state)+ if err != nil {+ return err+ }+ if err := os.MkdirAll(root, 0o700); err != nil {+ return err+ }+ return os.WriteFile(filepath.Join(root, "engine.json"), data, 0o600)+}++// assistantRequestModel maps a legacy executor field onto the model prefix+// the conversation engines use. A model that already names its CLI is kept.+func assistantRequestModel(executor, model string) string {+ model = strings.TrimSpace(model)+ if engine, _ := assistantModelEngine(model); engine != assistantEngineCodeBuddy {+ return model+ }+ switch assistantExecutor(executor) {+ case assistantEngineCodex:+ return assistantEngineCodex + ":" + model+ case "claude", assistantEngineClaude:+ return assistantEngineClaude + ":" + model+ default:+ if runtime.IsAgentCLI(executor) {+ return strings.TrimSpace(executor) + ":" + model+ }+ }+ return model+}diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.goindex 8024a8a4..cc8c1f41 100644--- a/internal/httpapi/assistant_generation.go+++ b/internal/httpapi/assistant_generation.go@@ -35,25 +35,15 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {if !decode(c, &req) {return}- req.Executor = assistantExecutor(req.Executor)- user, sharedModels := stored, []string(nil)- if req.Executor == "codebuddy" {- if user, sharedModels, ok = h.assistantChatUser(stored); !ok {- c.JSON(400, gin.H{"error": "请先配置个人 CodeBuddy API Key"})- return- }- } else if err := validateAssistantProvider(&req, stored); err != nil {- c.JSON(400, gin.H{"error": err.Error()})+ req.Model = assistantRequestModel(req.Executor, req.Model)+ user, model, refusal := h.assistantTurnUser(stored, req.Model)+ if refusal != "" {+ c.JSON(400, gin.H{"error": refusal})return}- if sharedModels != nil {- model, allowed := assistantSponsoredModelFor(sharedModels, req.Model)- if !allowed {- c.JSON(400, gin.H{"error": errAssistantSponsoredModel(sharedModels)})- return- }- req.Model = model- }+ req.Model = model+ cliEngine, _ := assistantModelEngine(req.Model)+ req.Executor = cliEngineif len(req.Messages) == 0 || req.Messages[len(req.Messages)-1].Role != "user" {c.JSON(400, gin.H{"error": "请提供用户消息"})return@@ -104,18 +94,29 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {c.JSON(403, gin.H{"error": err.Error()})return}- if req.Executor == "codebuddy" {- req.Model = assistantAllowedModel(req.Model, h.chatCatalog(c.Request.Context(), user))- if err := validateAssistantEffort(req.Model, req.Effort); err != nil {- c.JSON(400, gin.H{"error": err.Error()})- return- }- } else {- req.Effort = ""+ catalogEngine, _ := assistantModelEngine(req.Model)+ catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil)+ if catalogEngine == assistantEngineCodeBuddy {+ catalog = h.chatCatalog(c.Request.Context(), user)+ }+ req.Model = assistantAllowedUserModel(req.Model, catalog, user)+ cliEngine, _ = assistantModelEngine(req.Model)+ req.Executor = cliEngine+ if err := validateAssistantEffort(req.Model, req.Effort); err != nil {+ c.JSON(400, gin.H{"error": err.Error()})+ return+ }+ legacyExecutor := ""+ if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {+ legacyExecutor = old.Executor+ }+ if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(req.Messages, legacyExecutor), req.Model); refusal != "" {+ c.JSON(409, gin.H{"error": refusal})+ return}freshCLI := falseif old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {- freshCLI = assistantExecutor(old.Executor) != req.Executor+ freshCLI = assistantConversationEngine(old.Messages, old.Executor) != cliEngine}if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {if len(req.Messages) < len(old.Messages) {@@ -177,7 +178,8 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {// Keep the authenticated identity, but disconnect model execution from the// lifetime of the browser request. Only explicit cancellation stops a turn.parent := context.WithValue(context.WithoutCancel(c.Request.Context()), assistantFreshCLIKey{}, freshCLI)- h.scheduleAssistantTitle(parent, ownerID, user, old, req.SessionID, req.Messages, sharedModels)+ _, sharedModels, _ := h.assistantChatUser(stored)+ h.scheduleAssistantTitle(parent, ownerID, user, old, req.SessionID, req.Messages, req.Model, sharedModels)done := inflightTasks.Add()go func() {defer done()diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.goindex 01e675e0..4e562bd1 100644--- a/internal/httpapi/assistant_models.go+++ b/internal/httpapi/assistant_models.go@@ -30,6 +30,8 @@ type assistantModel struct {Family string `json:"family"`Credits string `json:"credits"`Efforts []string `json:"efforts"`+ // Engine is set for models that run on a CLI other than CodeBuddy.+ Engine string `json:"engine,omitempty"`}type assistantModelCatalog struct {@@ -40,6 +42,8 @@ type assistantModelCatalog struct {// SponsoredModel is the first (the default).SponsoredModel string `json:"sponsoredModel,omitempty"`SponsoredModels []string `json:"sponsoredModels,omitempty"`+ // Engines lists the CLIs a signed-in user can switch between.+ Engines []assistantEngineOption `json:"engines,omitempty"`}func prefetchAssistantModels() {}@@ -177,7 +181,8 @@ func cachedCLIModels(environment string) []string {// environment. Guests get the configured models only; actually chatting still// requires login plus a configured or sponsored CodeBuddy key.func (h *assistantHandlers) models(c *gin.Context) {- if id := assistantExecutor(c.Query("executor")); id != "codebuddy" {+ if raw := strings.TrimSpace(c.Query("executor")); raw != "" && assistantExecutor(raw) != "codebuddy" {+ id := assistantExecutor(raw)catalog, ok := executorModelCatalogs()[id]if !ok {c.JSON(400, gin.H{"error": "不支持的执行器"})@@ -213,6 +218,10 @@ func (h *assistantHandlers) models(c *gin.Context) {if shared {catalog.SponsoredModel, catalog.SponsoredModels = key.Models[0], key.Models}+ if signedIn {+ catalog.Models = append(catalog.Models, assistantEngineModels(c.Request.Context(), user)...)+ catalog.Engines = assistantEngineOptions(user, shared && strings.TrimSpace(user.CodeBuddyAPIKey) == "")+ }c.JSON(200, catalog)}diff --git a/internal/httpapi/assistant_provider.go b/internal/httpapi/assistant_provider.goindex 4322028d..62dfa2ea 100644--- a/internal/httpapi/assistant_provider.go+++ b/internal/httpapi/assistant_provider.go@@ -32,9 +32,13 @@ func validateAssistantProvider(req *assistantRequest, user domain.User) error {key, label = user.CodeBuddyAPIKey, "CodeBuddy"case "codex":key, label = user.CodexAPIKey, "Codex"- case "claude":+ case "claude", "claude-code":key, label = user.ClaudeCodeAPIKey, "Claude Code"default:+ if runtime.IsAgentCLI(req.Executor) {+ key, label = user.AgentCLICredentials[req.Executor].APIKey, runtime.AgentCLILabel(req.Executor)+ break+ }return fmt.Errorf("不支持的执行器")}if strings.TrimSpace(key) == "" {@@ -56,6 +60,7 @@ func assistantProviderCredentials(user domain.User) runtime.RunCredentials {CodeBuddy: runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment},Codex: runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL},ClaudeCode: runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL},+ AgentCLI: runtime.AgentCLIUserCredentials(user),}}@@ -118,7 +123,7 @@ func prepareAlternateAssistantCommand(ctx context.Context, req assistantCLIRequereturn runtime.CommandSpec{}, err}args = []string{"exec", "--json", "--ephemeral", "--skip-git-repo-check", "--ignore-rules", "--sandbox", "read-only", "-c", "approval_policy=\"never\"", "-c", "developer_instructions=" + strconv.Quote(sys), "-c", "web_search=\"disabled\""}- for _, feature := range []string{"shell_tool", "unified_exec", "apply_patch_freeform", "multi_agent", "multi_agent_v2", "js_repl", "code_mode", "apps", "plugins", "memories", "image_generation", "browser_use", "computer_use", "tool_suggest", "skill_search", "view_image", "goals", "collab", "sleep_tool", "worktrees"} {+ for _, feature := range codexAssistantDisabledFeatures {args = append(args, "-c", "features."+feature+"=false")}args = append(args, "-c", "features.hooks=true", "--dangerously-bypass-hook-trust", "-c", "hooks.PreToolUse=[{hooks=[{type=\"command\",command="+strconv.Quote("python3 '"+strings.ReplaceAll(guard, "'", "'\\''")+"'")+",timeout=5}]}]")diff --git a/internal/httpapi/assistant_provider_test.go b/internal/httpapi/assistant_provider_test.goindex c21aaa30..d571cd81 100644--- a/internal/httpapi/assistant_provider_test.go+++ b/internal/httpapi/assistant_provider_test.go@@ -46,6 +46,10 @@ func TestAssistantGenerationWithOnlySelectedProviderCredentials(t *testing.T) {if response.Code != 202 {t.Fatalf("start: %d %s", response.Code, response.Body.String())}+ wantEngine, wantModel := "codex", "codex:custom-model"+ if provider == "claude" {+ wantEngine, wantModel = "claude-code", "claude-code:custom-model"+ }deadline := time.Now().Add(5 * time.Second)for time.Now().Before(deadline) {generation, _ := h.repo.AssistantGeneration(user.ID, "provider-test")@@ -54,8 +58,8 @@ func TestAssistantGenerationWithOnlySelectedProviderCredentials(t *testing.T) {t.Fatalf("generation failed: %s", generation.Error)}session, _ := h.repo.AssistantSession(user.ID, "provider-test")- if session.Executor != provider || session.Model != "custom-model" || len(session.Messages) != 2 {- t.Fatalf("provider conversation lost: executor=%s messages=%d", session.Executor, len(session.Messages))+ if session.Executor != wantEngine || session.Model != wantModel || len(session.Messages) != 2 {+ t.Fatalf("provider conversation lost: executor=%s model=%s messages=%d", session.Executor, session.Model, len(session.Messages))}return}@@ -250,7 +254,13 @@ func TestAssistantNativeProviderGateway(t *testing.T) {user := domain.User{CodexAPIKey: "fixture-provider-key", CodexBaseURL: gateway.URL + "/v1", ClaudeCodeAPIKey: "fixture-provider-key", ClaudeCodeBaseURL: gateway.URL}ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)defer cancel()- out, _, err := runAlternateAssistantCLI(ctx, assistantCLIRequest{Executor: provider, Model: "gateway-test-model", Prompt: "Read demo then reply JSON.", MCPConfig: config}, user, nil)+ var out string+ var err error+ if provider == "codex" {+ out, _, err = runAssistantCLI(ctx, assistantCLIRequest{Executor: provider, Model: "gateway-test-model", Prompt: "Read demo then reply JSON.", MCPConfig: config, Native: true, SessionRoot: dir}, user, nil)+ } else {+ out, _, err = runAlternateAssistantCLI(ctx, assistantCLIRequest{Executor: provider, Model: "gateway-test-model", Prompt: "Read demo then reply JSON.", MCPConfig: config}, user, nil)+ }if err != nil {t.Fatal(err)}@@ -265,3 +275,67 @@ func TestAssistantNativeProviderGateway(t *testing.T) {})}}++func TestAssistantConversationEngineKeepsLegacyExecutor(t *testing.T) {+ reply := []assistantMessage{{Role: "user", Content: "hi"}, {Role: "assistant", Model: "gpt-5.4", Content: "ok"}}+ if got := assistantConversationEngine(reply, "codex"); got != assistantEngineCodex {+ t.Fatalf("codex legacy = %q", got)+ }+ if got := assistantConversationEngine(reply, "claude"); got != assistantEngineClaude {+ t.Fatalf("claude legacy = %q", got)+ }+ if got := assistantConversationEngine(reply, "agy"); got != "agy" {+ t.Fatalf("agy legacy = %q", got)+ }+ if got := assistantConversationEngine(reply); got != assistantEngineCodeBuddy {+ t.Fatalf("unprefixed = %q", got)+ }+ if got := assistantConversationEngine(reply, "codebuddy"); got != assistantEngineCodeBuddy {+ t.Fatalf("codebuddy legacy = %q", got)+ }+ prefixed := []assistantMessage{{Role: "assistant", Model: "codex:gpt-5.4", Content: "ok"}}+ if got := assistantConversationEngine(prefixed, ""); got != assistantEngineCodex {+ t.Fatalf("prefix wins = %q", got)+ }+ role := []assistantMessage{{Role: "assistant", Model: "gpt-5.4", SpeakerAgentID: "role", Content: "ok"}}+ if got := assistantConversationEngine(role, "codex"); got != "" {+ t.Fatalf("role reply locked = %q", got)+ }+ if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(reply, "codex"), "codex:gpt-5.4"); refusal != "" {+ t.Fatal(refusal)+ }+ if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(reply, "codex"), "default"); refusal == "" {+ t.Fatal("expected refusal when a legacy codex session continues on CodeBuddy")+ }+}++func TestAssistantCodexAppServerDisablesNativeTools(t *testing.T) {+ dir := t.TempDir()+ config := filepath.Join(dir, "mcp.json")+ if err := os.WriteFile(config, []byte(`{"mcpServers":{}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ inv, err := prepareAssistantCodexInvocation(assistantEngineInvocationOpts{Bin: "codex", Root: dir, Config: config, Prompt: "hi", Model: "gpt", SessionID: "s1"})+ if err != nil {+ t.Fatal(err)+ }+ if closer, ok := inv.command.Stdin.(interface{ Close() error }); ok {+ closer.Close()+ }+ joined := strings.Join(inv.command.Argv, "\n")+ for _, feature := range []string{"view_image", "goals", "shell_tool", "unified_exec"} {+ if !strings.Contains(joined, "features."+feature+"=false") {+ t.Fatalf("missing features.%s=false:\n%s", feature, joined)+ }+ }+ if !strings.Contains(joined, "features.hooks=true") || !strings.Contains(joined, "hooks.bypass_hook_trust=true") || !strings.Contains(joined, "hooks.PreToolUse=") {+ t.Fatalf("guard hook missing:\n%s", joined)+ }+ if strings.Contains(joined, "--dangerously-bypass-hook-trust") {+ t.Fatalf("app-server argv must not use the exec-only trust flag:\n%s", joined)+ }+ guard, err := os.ReadFile(filepath.Join(dir, "codex-native-guard.py"))+ if err != nil || !strings.Contains(string(guard), "native tools are disabled") {+ t.Fatalf("guard script = %q err=%v", guard, err)+ }+}diff --git a/internal/httpapi/assistant_title.go b/internal/httpapi/assistant_title.goindex 9e0cc8b9..dab04043 100644--- a/internal/httpapi/assistant_title.go+++ b/internal/httpapi/assistant_title.go@@ -75,8 +75,15 @@ func assistantPromptTitleMatches(session domain.AssistantSession, title string)return false}-// shared lists the allowed models when the turn runs on the shared key.-func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerID int64, user domain.User, old domain.AssistantSession, sessionID string, messages []domain.AssistantMessage, shared []string) {+// assistantTitleTimeout bounds the background summary; a cold CLI start can+// take most of it. On failure the first-prompt title stays.+const assistantTitleTimeout = 180 * time.Second++// scheduleAssistantTitle summarizes the first prompt on the CLI of the+// session's model. shared lists the models a CodeBuddy turn on the platform+// key may use. There is no cross-CLI fallback: a failed summary keeps the+// first-prompt title.+func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerID int64, user domain.User, old domain.AssistantSession, sessionID string, messages []domain.AssistantMessage, model string, shared []string) {if h == nil || h.repo == nil {return}@@ -88,17 +95,17 @@ func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerIDgo func() {defer done()defer func() { _ = recover() }()- runCtx, cancel := context.WithTimeout(ctx, 25*time.Second)+ runCtx, cancel := context.WithTimeout(ctx, assistantTitleTimeout)defer cancel()var title stringvar err errorif h.titleSummary != nil {title, err = h.titleSummary(runCtx, user, prompt)} else {- title, err = summarizeAssistantTitle(runCtx, user, prompt, shared)+ title, err = summarizeAssistantTitle(runCtx, user, model, prompt, shared)}if err != nil || strings.TrimSpace(title) == "" {- log.Printf("assistant title summary skipped session=%s: %v", sessionID, err)+ log.Printf("assistant title summary skipped session=%s: %v", sessionID, redactAssistantSecrets(fmt.Sprint(err), user))return}if err := h.repo.SetAssistantSessionGeneratedTitle(ownerID, sessionID, title); err != nil {@@ -107,20 +114,38 @@ func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerID}()}-// A shared-key title uses the cheapest allowed model, or the shared default.-func summarizeAssistantTitle(ctx context.Context, user domain.User, prompt string, shared []string) (string, error) {- if len(shared) == 0 {- return runAssistantTitleSummary(ctx, user, assistantApprovalReviewModel(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil)), prompt)+// assistantTitleModel picks the model and effort that name a session.+// CodeBuddy uses its cheapest model, limited to shared when the turn borrows+// the platform key. Other CLIs reuse the session's model at its weakest+// effort; the gateway behind a Base URL may serve nothing else.+func assistantTitleModel(ctx context.Context, user domain.User, model string, shared []string) (string, string) {+ if engine, _ := assistantModelEngine(model); engine != assistantEngineCodeBuddy {+ if efforts := assistantModelEfforts(model); len(efforts) > 0 {+ return model, efforts[0]+ }+ return model, ""+ }+ catalog := assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil)+ if len(shared) > 0 {+ catalog = restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, shared), shared)}- model := assistantApprovalReviewModel(restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, shared), shared))- if model == "" {- model = shared[0]+ if chosen := assistantApprovalReviewModel(catalog); chosen != "" {+ return chosen, ""}- return runAssistantTitleSummary(ctx, user, model, prompt)+ if len(shared) > 0 {+ return shared[0], ""+ }+ return catalog.Default, ""+}++func summarizeAssistantTitle(ctx context.Context, user domain.User, model, prompt string, shared []string) (string, error) {+ model, effort := assistantTitleModel(ctx, user, model, shared)+ return runAssistantTitleSummary(ctx, user, model, effort, prompt)}-func runAssistantTitleSummary(ctx context.Context, user domain.User, model, prompt string) (string, error) {- if model == "" || strings.TrimSpace(user.CodeBuddyAPIKey) == "" {+func runAssistantTitleSummary(ctx context.Context, user domain.User, model, effort, prompt string) (string, error) {+ engine, _ := assistantModelEngine(model)+ if key, _ := assistantEngineCredential(user, engine); model == "" || key == "" {return "", fmt.Errorf("title model or credential unavailable")}prompt = strings.TrimSpace(prompt)@@ -141,6 +166,7 @@ func runAssistantTitleSummary(ctx context.Context, user domain.User, model, promraw, _, err := runAssistantCLI(ctx, assistantCLIRequest{Prompt: redactAgentToolResult(string(payload), user),Model: model,+ Effort: effort,SystemPrompt: assistantTitleSummaryPolicy,SessionRoot: root,ReviewOnly: true,diff --git a/internal/httpapi/assistant_title_test.go b/internal/httpapi/assistant_title_test.goindex c41faca8..32da6754 100644--- a/internal/httpapi/assistant_title_test.go+++ b/internal/httpapi/assistant_title_test.go@@ -2,6 +2,8 @@ package httpapiimport ("context"+ "os"+ "path/filepath""strings""testing""time"@@ -51,6 +53,54 @@ func TestDecodeAssistantTitleSummary(t *testing.T) {}}+func TestAssistantTitleModelReusesSessionModelOnOtherCLIs(t *testing.T) {+ for _, tc := range []struct{ model, wantEffort string }{+ {"codex:gpt-5.5", "low"},+ {"claude-code:claude-opus-5", "low"},+ {"cursor:gpt-5.6-sol", "none"},+ {"agy:gemini-3.1-pro", "low"},+ {"agy:gateway-model", ""},+ {"pi:deepseek-v4-flash", "minimal"},+ {"opencode:glm-5", "low"},+ {"kimi:kimi-k3", ""},+ {"dsh:deepseek-v4-pro", ""},+ } {+ model, effort := assistantTitleModel(context.Background(), domain.User{}, tc.model, nil)+ if model != tc.model || effort != tc.wantEffort {+ t.Errorf("%s: got %q/%q, want same model at %q", tc.model, model, effort, tc.wantEffort)+ }+ }+ if model, effort := assistantTitleModel(context.Background(), domain.User{}, assistantChatDefaultModel, []string{assistantSponsoredModel}); model != assistantSponsoredModel || effort != "" {+ t.Fatalf("sponsored CodeBuddy title = %q/%q", model, effort)+ }+ if model, effort := assistantTitleModel(context.Background(), domain.User{}, assistantChatDefaultModel, nil); model == "" || effort != "" {+ t.Fatalf("CodeBuddy title without prices = %q/%q", model, effort)+ }+}++func TestAssistantTitleSummaryNeedsTheSessionCLICredential(t *testing.T) {+ user := domain.User{CodeBuddyAPIKey: "cb-key"}+ if _, err := runAssistantTitleSummary(context.Background(), user, "codex:gpt-5.5", "low", "梳理需求"); err == nil || !strings.Contains(err.Error(), "credential unavailable") {+ t.Fatalf("a Codex session must not fall back to CodeBuddy: %v", err)+ }+}++func TestAssistantClaudeReviewOnlyHasNoTools(t *testing.T) {+ root := t.TempDir()+ config := filepath.Join(root, "mcp.json")+ if err := os.WriteFile(config, []byte(`{"mcpServers":{}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ inv, err := prepareAssistantClaudeInvocation(assistantEngineInvocationOpts{Bin: "claude", Root: root, Config: config, Prompt: "p", Model: "claude-haiku-5.5", Effort: "low", SessionID: "s", ReviewOnly: true})+ if err != nil {+ t.Fatal(err)+ }+ argv := strings.Join(inv.command.Argv, "\x00")+ if !strings.Contains(argv, "\x00--tools\x00\x00--no-session-persistence\x00") || !strings.Contains(argv, "\x00--effort\x00low\x00") {+ t.Fatalf("review-only Claude argv: %q", inv.command.Argv)+ }+}+func TestAssistantPromptTitleMatchesTruncation(t *testing.T) {text := strings.Repeat("需", 40)session := domain.AssistantSession{Messages: []domain.AssistantMessage{{Role: "user", Content: text}}}@@ -85,7 +135,7 @@ func TestScheduleAssistantTitleWritesSummary(t *testing.T) {t.Fatal(err)}old, _ := st.AssistantSession(1, id)- h.scheduleAssistantTitle(context.Background(), 1, domain.User{ID: 1}, old, id, []domain.AssistantMessage{{Role: "user", Content: prompt + ",请按模块列出缺口"}}, nil)+ h.scheduleAssistantTitle(context.Background(), 1, domain.User{ID: 1}, old, id, []domain.AssistantMessage{{Role: "user", Content: prompt + ",请按模块列出缺口"}}, assistantChatDefaultModel, nil)deadline := time.Now().Add(2 * time.Second)var got domain.AssistantSessionfor time.Now().Before(deadline) {diff --git a/internal/httpapi/cli_live_test.go b/internal/httpapi/cli_live_test.gonew file mode 100644index 00000000..4e390363--- /dev/null+++ b/internal/httpapi/cli_live_test.go@@ -0,0 +1,181 @@+//go:build clilive++package httpapi++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "testing"+ "time"++ "agentflow/internal/domain"+)++var liveCLIOrder = []string{"codebuddy", "codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh"}++type liveCLIConfig struct {+ Key string `json:"key"`+ BaseURL string `json:"baseUrl"`+ Protocol string `json:"protocol"`+ Model string `json:"model"`+ Environment string `json:"environment"`+}++func liveTimeout() time.Duration {+ seconds, _ := strconv.Atoi(os.Getenv("CLI_LIVE_TIMEOUT"))+ if seconds <= 0 {+ seconds = 90+ }+ return time.Duration(seconds) * time.Second+}++func loadLiveConfig(t *testing.T) map[string]liveCLIConfig {+ t.Helper()+ path := os.Getenv("CLI_LIVE_CONFIG")+ raw, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ var cfg map[string]liveCLIConfig+ if err := json.Unmarshal(raw, &cfg); err != nil {+ t.Fatal(err)+ }+ return cfg+}++func redactLive(text string) string {+ for _, prefix := range []string{"sk-", "crsr_", "ck_", "AQ."} {+ for {+ i := strings.Index(text, prefix)+ if i < 0 {+ break+ }+ end := i + len(prefix)+ for end < len(text) && end < i+len(prefix)+80 {+ r := text[end]+ if r == ' ' || r == '\n' || r == '\t' || r == '"' || r == '\'' || r == ',' || r == '\\' {+ break+ }+ end+++ }+ text = text[:i] + "[redacted]" + text[end:]+ }+ }+ return text+}++func clipLive(text string) string {+ text = strings.TrimSpace(text)+ if len(text) > 700 {+ return text[:700] + "…"+ }+ return text+}++func TestLiveCLIConversations(t *testing.T) {+ if os.Getenv("CLI_LIVE") != "1" {+ t.Skip("set CLI_LIVE=1 to run CLI conversations")+ }+ cfg := loadLiveConfig(t)+ root := os.Getenv("CLI_LIVE_WORKSPACE")+ if root == "" {+ t.Fatal("CLI_LIVE_WORKSPACE is required")+ }+ for _, kind := range liveCLIOrder {+ item, ok := cfg[kind]+ if !ok || strings.TrimSpace(item.Key) == "" {+ t.Run(kind, func(t *testing.T) { t.Skip("no key") })+ continue+ }+ t.Run(kind, func(t *testing.T) {+ runLiveChat(t, filepath.Join(root, "chat", kind), kind, item)+ })+ }+}++func runLiveChat(t *testing.T, root, kind string, item liveCLIConfig) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), liveTimeout())+ defer cancel()+ user, model := liveCLIUser(kind, item)+ text, session, err := runAssistantCLI(ctx, assistantCLIRequest{+ Prompt: "Reply with exactly the single word pong. Do not use tools.",+ Model: model,+ Executor: kind,+ SystemPrompt: "Reply with exactly the single word pong. Do not use tools.",+ Native: true,+ SessionRoot: root,+ UserID: user.ID,+ }, user, nil)+ text = redactLive(text + "\n" + session)+ if err != nil {+ t.Fatalf("对话失败: %s\n%s", redactLive(err.Error()), clipLive(text))+ }+ if !strings.Contains(strings.ToLower(text), "pong") {+ t.Fatalf("回复里没有 pong\n%s", clipLive(text))+ }+ t.Logf("ok %s", clipLive(text))+}++func TestLiveCLITitles(t *testing.T) {+ if os.Getenv("CLI_LIVE") != "1" {+ t.Skip("set CLI_LIVE=1 to run CLI title summaries")+ }+ cfg := loadLiveConfig(t)+ for _, kind := range liveCLIOrder {+ item, ok := cfg[kind]+ if !ok || strings.TrimSpace(item.Key) == "" {+ t.Run(kind, func(t *testing.T) { t.Skip("no key") })+ continue+ }+ t.Run(kind, func(t *testing.T) {+ if kind == "cursor" && strings.TrimSpace(item.Model) == "" {+ item.Model = "auto"+ }+ user, model := liveCLIUser(kind, item)+ ctx, cancel := context.WithTimeout(context.Background(), liveTimeout())+ defer cancel()+ started := time.Now()+ title, err := summarizeAssistantTitle(ctx, user, model, "帮我梳理一下积分商城的需求,按模块列出现有缺口,并给出两周的排期建议", nil)+ if err != nil || strings.TrimSpace(title) == "" {+ t.Fatalf("标题总结失败: %s", redactLive(fmt.Sprint(err)))+ }+ t.Logf("ok %s (%s)", title, time.Since(started).Round(time.Second))+ })+ }+}++func liveCLIUser(kind string, item liveCLIConfig) (domain.User, string) {+ user := domain.User{ID: 1, LoginName: "live"}+ model := item.Model+ switch kind {+ case "codebuddy":+ user.CodeBuddyAPIKey = item.Key+ user.CodeBuddyInternetEnvironment = item.Environment+ case "codex":+ user.CodexAPIKey = item.Key+ user.CodexBaseURL = item.BaseURL+ if model != "" {+ model = "codex:" + model+ }+ case "claude-code":+ user.ClaudeCodeAPIKey = item.Key+ user.ClaudeCodeBaseURL = item.BaseURL+ if model != "" {+ model = "claude-code:" + model+ }+ default:+ user.AgentCLICredentials = map[string]domain.AgentCLICredential{+ kind: {APIKey: item.Key, BaseURL: item.BaseURL, Protocol: item.Protocol},+ }+ if model != "" {+ model = kind + ":" + model+ }+ }+ return user, model+}diff --git a/internal/httpapi/cli_models_probe.go b/internal/httpapi/cli_models_probe.gonew file mode 100644index 00000000..e1621b34--- /dev/null+++ b/internal/httpapi/cli_models_probe.go@@ -0,0 +1,211 @@+package httpapi++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "os"+ "os/exec"+ "regexp"+ "slices"+ "strconv"+ "strings"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/runtime"++ "github.com/gin-gonic/gin"+)++type cliModelProbeResult struct {+ Models []domain.CLIModel `json:"models"`+ // Source is "remote" for the Base URL's model list and "builtin" for the+ // executor catalog used when no Base URL is set.+ Source string `json:"source,omitempty"`+ Error string `json:"error,omitempty"`+}++// probeCLIModels backs 「获取可用模型」 for the model catalog of a CLI other+// than CodeBuddy. The form's unsaved API Key, Base URL and protocol win over the stored ones+// so a user can probe before saving; nothing is stored. Like+// verifyGitToken it answers 200 with a structured result.+func (h *usersHandlers) probeCLIModels(c *gin.Context) {+ id, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil || id <= 0 {+ c.JSON(http.StatusBadRequest, cliModelProbeResult{Error: "valid user id is required"})+ return+ }+ current, ok := h.requestUser(c.Request, false)+ if !ok || current.ID != id {+ c.JSON(http.StatusForbidden, cliModelProbeResult{Error: "只能使用当前登录用户的凭据获取模型"})+ return+ }+ var req struct {+ Engine string `json:"engine"`+ APIKey string `json:"apiKey"`+ // BaseURL is the form's value; null falls back to the stored one,+ // while "" means the official endpoint.+ BaseURL *string `json:"baseUrl"`+ // Protocol is the agent CLI's form value; null keeps the stored one.+ Protocol *string `json:"protocol"`+ }+ if !decode(c, &req) {+ return+ }+ engine := strings.TrimSpace(req.Engine)+ if engine == assistantEngineCodeBuddy || !slices.Contains(assistantCLIEngines(), engine) {+ c.JSON(http.StatusBadRequest, cliModelProbeResult{Error: "不支持的 CLI:" + engine})+ return+ }+ if req.BaseURL != nil && !validCLIBaseURL(*req.BaseURL) {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: errInvalidCLIBaseURL})+ return+ }+ apiKey, baseURL, protocol := strings.TrimSpace(req.APIKey), "", ""+ if h.repo != nil {+ if stored, found := h.repo.User(id); found {+ storedKey, storedURL := assistantEngineCredential(stored, engine)+ if apiKey == "" {+ apiKey = storedKey+ }+ baseURL, protocol = storedURL, assistantEngineProtocol(stored, engine)+ }+ }+ if req.BaseURL != nil {+ baseURL = strings.TrimSpace(*req.BaseURL)+ }+ if req.Protocol != nil && runtime.IsAgentCLI(engine) {+ protocol = runtime.AgentCLIProtocol(engine, *req.Protocol)+ }+ if engine == runtime.AgentCLICursor {+ h.probeCursorModels(c, apiKey)+ return+ }+ if protocol == runtime.AgentCLIProtocolGemini {+ baseURL = ""+ }+ if baseURL == "" {+ c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(assistantEngineBuiltinModels(engine)), Source: "builtin"})+ return+ }+ if apiKey == "" {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "请先填写 " + assistantEngineLabel(engine) + " API Key"})+ return+ }+ ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second)+ defer cancel()+ models, err := assistantEngineDiscover(ctx, assistantEngineAnthropicModels(engine, protocol), apiKey, baseURL)+ if err != nil {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "获取模型列表失败:" + err.Error()})+ return+ }+ if len(models) == 0 {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "服务没有返回可用模型,可以手动添加模型"})+ return+ }+ c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(models), Source: "remote"})+}++// probeCursorModels asks cursor-agent itself: Cursor has no Base URL, and+// the models a key may use depend on its account plan.+func (h *usersHandlers) probeCursorModels(c *gin.Context, apiKey string) {+ if apiKey == "" {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "请先填写 " + assistantEngineLabel(runtime.AgentCLICursor) + " API Key"})+ return+ }+ ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)+ defer cancel()+ models, err := cursorAgentModels(ctx, apiKey)+ if errors.Is(err, errAssistantCLIMissing) {+ c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(assistantEngineBuiltinModels(runtime.AgentCLICursor)), Source: "builtin"})+ return+ }+ if err != nil {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "获取模型列表失败:" + err.Error()})+ return+ }+ if len(models) == 0 {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "Cursor CLI 没有返回可用模型,可以手动添加模型"})+ return+ }+ c.JSON(http.StatusOK, cliModelProbeResult{Models: models, Source: "remote"})+}++var cursorModelLine = regexp.MustCompile(`^([A-Za-z0-9][A-Za-z0-9._-]*) - (.+)$`)++// cursorAgentModels runs `cursor-agent models` in a throwaway HOME with only+// the user's key, so no server token or stored CLI login is visible to it.+func cursorAgentModels(ctx context.Context, apiKey string) ([]domain.CLIModel, error) {+ bin, err := resolveAssistantEngineBin(runtime.AgentCLICursor)+ if err != nil {+ return nil, err+ }+ home, err := os.MkdirTemp("", "agentflow-cursor-models-")+ if err != nil {+ return nil, err+ }+ defer os.RemoveAll(home)+ env := []string{"HOME=" + home, "CURSOR_API_KEY=" + apiKey, "NO_COLOR=1", "CI=1"}+ for _, key := range []string{"PATH", "LANG", "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "NO_PROXY", "https_proxy", "http_proxy", "all_proxy", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR"} {+ if value, ok := os.LookupEnv(key); ok {+ env = append(env, key+"="+value)+ }+ }+ cmd := exec.CommandContext(ctx, bin, "models")+ cmd.Dir, cmd.Env = home, env+ out, err := cmd.CombinedOutput()+ if err != nil {+ if ctx.Err() != nil {+ return nil, errors.New("Cursor CLI 响应超时")+ }+ if strings.Contains(strings.ToLower(string(out)), "unauthorized") || strings.Contains(string(out), "401") {+ return nil, assistantCredentialError{engine: runtime.AgentCLICursor}+ }+ return nil, fmt.Errorf("cursor-agent models 退出:%v", err)+ }+ return cursorModelFamilies(parseCursorModels(string(out))), nil+}++// cursorModelFamilies folds the effort variants cursor-agent lists into the+// families of the built-in table, in table order; IDs outside it follow as+// they are.+func cursorModelFamilies(models []domain.CLIModel) []domain.CLIModel {+ present, seen := map[string]bool{}, map[string]bool{}+ var unknown []domain.CLIModel+ for _, model := range models {+ if family, ok := runtime.CursorModelFamily(model.ID); ok {+ present[family.ID] = true+ } else if !seen[model.ID] {+ seen[model.ID] = true+ unknown = append(unknown, model)+ }+ }+ out := []domain.CLIModel{}+ for _, family := range runtime.CursorModels() {+ if present[family.ID] {+ out = append(out, domain.CLIModel{ID: family.ID, Name: family.Name})+ }+ }+ return append(out, unknown...)+}++func parseCursorModels(output string) []domain.CLIModel {+ models := []domain.CLIModel{}+ for _, line := range strings.Split(output, "\n") {+ line = strings.Join(strings.Fields(strings.ReplaceAll(line, "\u200b", "")), " ")+ if match := cursorModelLine.FindStringSubmatch(line); match != nil {+ models = append(models, domain.CLIModel{ID: match[1], Name: strings.TrimSuffix(match[2], " (default)")})+ }+ }+ return models+}++func cliModelsOf(models []assistantDiscoveredModel) []domain.CLIModel {+ out := make([]domain.CLIModel, 0, len(models))+ for _, model := range models {+ out = append(out, domain.CLIModel{ID: model.ID, Name: model.Name})+ }+ return out+}diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.goindex 28ab21bd..cee3e24b 100644--- a/internal/httpapi/executor_models.go+++ b/internal/httpapi/executor_models.go@@ -4,6 +4,7 @@ import ("net/http""agentflow/internal/domain"+ "agentflow/internal/runtime""github.com/gin-gonic/gin")@@ -32,6 +33,7 @@ type executorModelCatalog struct {}var effortOptionLabels = map[string]string{+ "none": "关闭 none","minimal": "最低 minimal","low": "低 low","medium": "中 medium",@@ -100,7 +102,50 @@ func executorModelCatalogs() map[string]executorModelCatalog {},Efforts: effortOptions(domain.ExecutorEffortLevels["claude-code"]),},+ // Official-endpoint catalogs. OpenCode and Pi have none, so their+ // models come from the Base URL.+ "opencode": {CustomModel: true, Efforts: effortOptions(domain.ExecutorEffortLevels["opencode"])},+ "cursor": {+ CustomModel: true,+ Models: cursorCatalogModels(),+ Efforts: effortOptions(domain.ExecutorEffortLevels["cursor"]),+ },+ "agy": {+ CustomModel: true,+ Models: []executorModelInfo{+ {ID: "gemini-3.8-flash-medium", Name: "Gemini 3.8 Flash"},+ {ID: "gemini-4-argon-medium", Name: "Gemini 4 Argon"},+ },+ Efforts: effortOptions(domain.ExecutorEffortLevels["agy"]),+ },+ "kimi": {+ CustomModel: true,+ Models: []executorModelInfo{+ {ID: "k3.1-pro", Name: "K3.1 Pro"},+ {ID: "k3.1-pro-highspeed", Name: "K3.1 Pro Highspeed"},+ {ID: "k3", Name: "K3"},+ {ID: "k3-256k", Name: "K3 256K"},+ {ID: "kimi-for-coding", Name: "K2.8 Preview"},+ {ID: "kimi-for-coding-highspeed", Name: "K2.7 Code Highspeed"},+ },+ },+ "pi": {CustomModel: true, Efforts: effortOptions(domain.ExecutorEffortLevels["pi"])},+ "dsh": {+ CustomModel: true,+ Models: []executorModelInfo{+ {ID: "deepseek-flash", Name: "DeepSeek V4.1 Flash"},+ {ID: "deepseek-v4-pro", Name: "DeepSeek V4 Pro"},+ },+ },+ }+}++func cursorCatalogModels() []executorModelInfo {+ var out []executorModelInfo+ for _, model := range runtime.CursorModels() {+ out = append(out, executorModelInfo{ID: model.ID, Name: model.Name})}+ return out}// executorModels serves the built-in model/effort catalog. It is a static,diff --git a/internal/httpapi/issues_test.go b/internal/httpapi/issues_test.goindex a3aa36ff..4cb08b72 100644--- a/internal/httpapi/issues_test.go+++ b/internal/httpapi/issues_test.go@@ -534,9 +534,15 @@ func TestAssetAPIAcceptsSandboxEnvironmentButExecutorsAreReadOnly(t *testing.T)requestJSON[map[string]string](t, h, http.MethodPut, "/api/executors", map[string]any{"id": "legacy", "name": "Legacy", "kind": "mock"}, http.StatusMethodNotAllowed)executors := requestEmptyJSON[[]domain.ExecutorDefinition](t, h, http.MethodGet, "/api/executors", http.StatusOK)- if len(executors) != 3 || executors[0].ID != "codebuddy" || executors[1].ID != "codex" || executors[2].ID != "claude" {+ want := repo.BuiltInExecutors()+ if len(executors) != len(want) {t.Fatalf("built-in CLI catalog = %+v", executors)}+ for i := range want {+ if executors[i].ID != want[i].ID || executors[i].Kind != want[i].Kind {+ t.Fatalf("built-in CLI catalog[%d] = %+v, want %+v", i, executors[i], want[i])+ }+ }requestJSON[map[string]bool](t, h, http.MethodPut, "/api/sandboxes", map[string]any{"id": "configured", "name": "Configured", "projectId": "platform", "driver": "local", "environment": map[string]string{"TOOL_MODE": "test"}}, http.StatusOK)profile, ok := s.Sandbox("configured")if !ok || profile.Environment["TOOL_MODE"] != "test" {diff --git a/internal/httpapi/runner_sandbox_resolve_test.go b/internal/httpapi/runner_sandbox_resolve_test.gonew file mode 100644index 00000000..a07d5b7c--- /dev/null+++ b/internal/httpapi/runner_sandbox_resolve_test.go@@ -0,0 +1,28 @@+package httpapi++import (+ "testing"++ "agentflow/internal/domain"+)++func TestResolveRunnerTaskSandboxByRunnerOS(t *testing.T) {+ stored := &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{ID: "box", Driver: "native"}}+ task := domain.RunnerTask{ID: "t", Sandbox: stored}+ for goos, want := range map[string]string{"linux": "bwrap", "darwin": "seatbelt", "": "native", "windows": "native"} {+ got := resolveRunnerTaskSandbox(task, goos)+ if got.Sandbox.Profile.Driver != want {+ t.Fatalf("%q runner got driver %q, want %q", goos, got.Sandbox.Profile.Driver, want)+ }+ }+ if stored.Profile.Driver != "native" {+ t.Fatal("resolution must not mutate the stored task sandbox")+ }+ docker := domain.RunnerTask{Sandbox: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: "docker"}}}+ if resolveRunnerTaskSandbox(docker, "darwin").Sandbox.Profile.Driver != "docker" {+ t.Fatal("non-native drivers must pass through")+ }+ if resolveRunnerTaskSandbox(domain.RunnerTask{}, "linux").Sandbox != nil {+ t.Fatal("tasks without a sandbox stay without one")+ }+}diff --git a/internal/httpapi/runners.go b/internal/httpapi/runners.goindex cc42b744..7e06301b 100644--- a/internal/httpapi/runners.go+++ b/internal/httpapi/runners.go@@ -677,7 +677,9 @@ func normalizeRunnerRuntimes(reported, existing []domain.RunnerRuntime) []domainif previous.Status == domain.RuntimeStatusDisabled {out[i].Status = domain.RuntimeStatusDisabled}- if previous.AuthMode == domain.RuntimeAuthLocal || previous.AuthMode == domain.RuntimeAuthPersonal {+ if domain.IsAgentCLIKind(out[i].Provider) {+ out[i].AuthMode = domain.RuntimeAuthPersonal+ } else if previous.AuthMode == domain.RuntimeAuthLocal || previous.AuthMode == domain.RuntimeAuthPersonal {out[i].AuthMode = previous.AuthMode} else if strings.EqualFold(out[i].Provider, "codebuddy") {out[i].AuthMode = domain.RuntimeAuthPersonal@@ -843,7 +845,7 @@ func (h *runnersHandlers) runnerTaskClaim(c *gin.Context) {c.JSON(http.StatusOK, map[string]bool{"taskAvailable": true})return}- c.JSON(http.StatusOK, map[string]any{"task": task})+ c.JSON(http.StatusOK, map[string]any{"task": resolveRunnerTaskSandbox(task, runner.OS)})}deadline := time.Now().Add(runnerLongPollTimeout())for {@@ -921,7 +923,26 @@ func (h *runnersHandlers) runnerTaskGet(c *gin.Context) {c.Status(http.StatusNotFound)return}- c.JSON(http.StatusOK, domain.PublicRunnerTask(task))+ c.JSON(http.StatusOK, domain.PublicRunnerTask(resolveRunnerTaskSandbox(task, runner.OS)))+}++// resolveRunnerTaskSandbox hands the runner a concrete sandbox driver: the+// native option becomes seatbelt or bwrap by the OS the runner reported, so+// runner builds that predate native keep working. A runner on an+// unsupported OS keeps native and reports the error when it opens the+// sandbox.+func resolveRunnerTaskSandbox(task domain.RunnerTask, runnerOS string) domain.RunnerTask {+ if task.Sandbox == nil {+ return task+ }+ driver, err := domain.ResolveSandboxDriver(task.Sandbox.Profile.Driver, runnerOS)+ if err != nil || driver == task.Sandbox.Profile.Driver {+ return task+ }+ spec := *task.Sandbox+ spec.Profile.Driver = driver+ task.Sandbox = &spec+ return task}// runnerMaySeeTask limits task reads to the runner it is targeted at ordiff --git a/internal/httpapi/runners_cases_test.go b/internal/httpapi/runners_cases_test.goindex 527184c0..fa254291 100644--- a/internal/httpapi/runners_cases_test.go+++ b/internal/httpapi/runners_cases_test.go@@ -104,10 +104,10 @@ func TestRunnerManagementAndMachineLifecycle(t *testing.T) {}func TestRunnerNormalizationAndBindCodeBranches(t *testing.T) {- reported := []domain.RunnerRuntime{{Provider: "codebuddy", Status: "online"}, {Provider: "codex", Status: "online"}}- existing := []domain.RunnerRuntime{{Provider: "codebuddy", Status: domain.RuntimeStatusDisabled, AuthMode: domain.RuntimeAuthLocal}, {Provider: "codex", AuthMode: domain.RuntimeAuthPersonal}}+ reported := []domain.RunnerRuntime{{Provider: "codebuddy", Status: "online"}, {Provider: "codex", Status: "online"}, {Provider: "opencode", Status: "online"}}+ existing := []domain.RunnerRuntime{{Provider: "codebuddy", Status: domain.RuntimeStatusDisabled, AuthMode: domain.RuntimeAuthLocal}, {Provider: "codex", AuthMode: domain.RuntimeAuthPersonal}, {Provider: "opencode", AuthMode: domain.RuntimeAuthLocal}}got := normalizeRunnerRuntimes(reported, existing)- if got[0].Status != domain.RuntimeStatusDisabled || got[0].AuthMode != domain.RuntimeAuthLocal || got[1].AuthMode != domain.RuntimeAuthPersonal {+ if got[0].Status != domain.RuntimeStatusDisabled || got[0].AuthMode != domain.RuntimeAuthLocal || got[1].AuthMode != domain.RuntimeAuthPersonal || got[2].AuthMode != domain.RuntimeAuthPersonal {t.Fatalf("normalized = %+v", got)}f := cvBNewHTTPFixture(t)diff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 14eaee71..5a898cd1 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -273,6 +273,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv// 工蜂 Git Token 校验:只允许当前登录用户校验自己的令牌。g.GET("/api/users/:id/git-token/verify", api.users.verifyGitToken)g.POST("/api/users/:id/git-token/verify", api.users.verifyGitToken)+ g.POST("/api/users/:id/cli-models/probe", api.users.probeCLIModels)g.Any("/api/users/:id", func(c *gin.Context) {c.JSON(http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})})diff --git a/internal/httpapi/users.go b/internal/httpapi/users.goindex cf54eb99..f3a7880e 100644--- a/internal/httpapi/users.go+++ b/internal/httpapi/users.go@@ -47,13 +47,13 @@ func (h *usersHandlers) user(c *gin.Context) {}body.CodeBuddyInternetEnvironment = &environment}- for _, raw := range []*string{body.CodexBaseURL, body.ClaudeCodeBaseURL} {- if raw == nil || strings.TrimSpace(*raw) == "" {- continue- }- u, err := url.Parse(strings.TrimSpace(*raw))- if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || len(*raw) > 2048 {- c.JSON(http.StatusBadRequest, map[string]string{"error": "Base URL 必须为 HTTP(S) 服务地址,不能包含账号密码、查询参数或片段"})+ baseURLs := []*string{body.CodexBaseURL, body.ClaudeCodeBaseURL}+ for _, cred := range body.AgentCLICredentials {+ baseURLs = append(baseURLs, cred.BaseURL)+ }+ for _, raw := range baseURLs {+ if raw != nil && !validCLIBaseURL(*raw) {+ c.JSON(http.StatusBadRequest, map[string]string{"error": errInvalidCLIBaseURL})return}}@@ -65,6 +65,19 @@ func (h *usersHandlers) user(c *gin.Context) {c.JSON(http.StatusOK, domain.PublicUser(saved))}+const errInvalidCLIBaseURL = "Base URL 必须为 HTTP(S) 服务地址,不能包含账号密码、查询参数或片段"++// validCLIBaseURL accepts an empty value (the CLI's official endpoint) or a+// plain HTTP(S) service address.+func validCLIBaseURL(raw string) bool {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return true+ }+ u, err := url.Parse(raw)+ return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Hostname() != "" && u.User == nil && u.RawQuery == "" && u.Fragment == "" && len(raw) <= 2048+}+func (h *usersHandlers) platformAdmins(c *gin.Context) {if !h.isPlatformAdmin(c.Request) {c.JSON(http.StatusForbidden, map[string]string{"error": "只有平台管理员可以管理该名单"})diff --git a/internal/repo/catalog.go b/internal/repo/catalog.goindex be8e52d3..889baf33 100644--- a/internal/repo/catalog.go+++ b/internal/repo/catalog.go@@ -237,6 +237,12 @@ func BuiltInExecutors() []domain.ExecutorDefinition {{ID: "codebuddy", Name: "CodeBuddy", Kind: "codebuddy", Binary: "codebuddy", Args: []string{"-p", "--output-format", "stream-json", "--include-partial-messages", "-y", "--setting-sources", "none"}, Protocol: "stream-json"},{ID: "codex", Name: "Codex", Kind: "codex", Binary: "codex", Args: []string{"exec", "--json", "--sandbox", "workspace-write", "--skip-git-repo-check"}, Protocol: "jsonl"},{ID: "claude", Name: "Claude Code", Kind: "claude-code", Binary: "claude", Args: []string{"-p", "--output-format", "stream-json", "--permission-mode", "dontAsk"}, Protocol: "stream-json"},+ {ID: "opencode", Name: "OpenCode", Kind: "opencode", Binary: "opencode", Protocol: "stream-json"},+ {ID: "cursor", Name: "Cursor CLI", Kind: "cursor", Binary: "cursor-agent", Protocol: "stream-json"},+ {ID: "agy", Name: "Antigravity", Kind: "agy", Binary: "agy", Protocol: "stream-json"},+ {ID: "kimi", Name: "Kimi Code", Kind: "kimi", Binary: "kimi", Protocol: "stream-json"},+ {ID: "pi", Name: "Pi", Kind: "pi", Binary: "pi", Protocol: "stream-json"},+ {ID: "dsh", Name: "DeepSeek Harness", Kind: "dsh", Binary: "dsh", Protocol: "stream-json"},}}@@ -326,7 +332,7 @@ func (r *CatalogRepo) PutSandbox(v domain.SandboxProfile) error {return fmt.Errorf("sandbox environment: %w", err)}switch strings.TrimSpace(v.Driver) {- case "local", "seatbelt", "bwrap", "docker":+ case "local", "native", "seatbelt", "bwrap", "docker":default:return fmt.Errorf("unsupported sandbox driver %q", v.Driver)}@@ -764,7 +770,8 @@ func normalizeSandboxProfile(profile domain.SandboxProfile) domain.SandboxProfilcase "local":profile.DockerfileID = ""profile.ReadOnlyRootFS = false- case "seatbelt", "bwrap":+ case "native", "seatbelt", "bwrap":+ profile.Driver = domain.SandboxDriverNativeprofile.DockerfileID = ""profile.ReadOnlyRootFS = falsecase "docker":diff --git a/internal/repo/models.go b/internal/repo/models.goindex 23931235..78ec9aff 100644--- a/internal/repo/models.go+++ b/internal/repo/models.go@@ -43,6 +43,7 @@ type userConfigRow struct {CodexBaseURL *string `gorm:"column:codex_base_url;type:text"`ClaudeCodeAPIKey *string `gorm:"column:claude_code_api_key;type:text"`ClaudeCodeBaseURL *string `gorm:"column:claude_code_base_url;type:text"`+ AgentCLICredentials *string `gorm:"column:agent_cli_credentials;type:text"`Created *time.Time `gorm:"column:created_at"`Updated *time.Time `gorm:"column:updated_at"`}diff --git a/internal/repo/opentest.go b/internal/repo/opentest.goindex c4f01892..8a50afc5 100644--- a/internal/repo/opentest.go+++ b/internal/repo/opentest.go@@ -67,8 +67,7 @@ func seedTestDefaults(s *Store) error {executors := append(BuiltInExecutors(), domain.ExecutorDefinition{ID: "mock", Name: "演示执行器", Kind: "mock", Protocol: "events-v1"})sandboxes := []domain.SandboxProfile{{ID: "local", Name: "本地开发沙箱", ProjectID: "platform", Shared: true, Driver: "local"},- {ID: "skillhub-macos-seatbelt", Name: "Skillhub macOS 轻量沙箱", ProjectID: "platform", Driver: "seatbelt"},- {ID: "skillhub-linux-bwrap", Name: "Skillhub Linux 轻量沙箱", ProjectID: "platform", Driver: "bwrap"},+ {ID: "skillhub-native", Name: "Skillhub 轻量沙箱", ProjectID: "platform", Driver: "native"},}for _, v := range []domain.RuleDefinition{{ID: "engineering", Name: "工程约束", ProjectID: "platform", Shared: true, Description: "通用代码变更规则", Priority: 100, Content: "先阅读现有实现;保持改动范围最小;不得用跳过测试掩盖失败;完成声明必须附带新鲜验证证据。", UpdatedAt: now},diff --git a/internal/repo/provider_credentials_test.go b/internal/repo/provider_credentials_test.goindex a54eb1a0..244791d6 100644--- a/internal/repo/provider_credentials_test.go+++ b/internal/repo/provider_credentials_test.go@@ -10,6 +10,65 @@ import ("time")+func TestAgentCLICredentialsRoundTrip(t *testing.T) {+ st, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ defer st.Close()+ if err := st.PutUser(domain.User{LoginName: "agent-cli-owner"}); err != nil {+ t.Fatal(err)+ }+ user, ok := st.UserByLoginName("agent-cli-owner")+ if !ok {+ t.Fatal("missing user")+ }+ base := "https://gateway.example/v1"+ protocol := "chat"+ models := []domain.CLIModel{{ID: "model-a", Name: "Model A"}}+ updated, err := st.UpdateUserCredentials(user.ID, UserCredentialUpdate{AgentCLICredentials: map[string]AgentCLICredentialUpdate{+ "opencode": {APIKey: "oc-secret", BaseURL: &base, Protocol: &protocol, Models: &models},+ "shell": {APIKey: "nope"},+ }})+ if err == nil || updated.ID != 0 {+ t.Fatal("unknown CLI was accepted")+ }+ updated, err = st.UpdateUserCredentials(user.ID, UserCredentialUpdate{AgentCLICredentials: map[string]AgentCLICredentialUpdate{+ "opencode": {APIKey: "oc-secret", BaseURL: &base, Protocol: &protocol, Models: &models},+ }})+ if err != nil {+ t.Fatal(err)+ }+ if err := st.PutUser(domain.User{ID: user.ID, LoginName: "agent-cli-owner", ChineseName: "刷新"}); err != nil {+ t.Fatal(err)+ }+ got, ok := st.User(user.ID)+ if !ok {+ t.Fatal("missing saved user")+ }+ cred := got.AgentCLICredentials["opencode"]+ if cred.APIKey != "oc-secret" || cred.BaseURL != base || cred.Protocol != "chat" || len(cred.Models) != 1 || cred.Models[0].ID != "model-a" {+ t.Fatalf("agent CLI credential = %+v", cred)+ }+ if got.CodexAPIKey != "" {+ t.Fatal("agent CLI credential wrote a Codex column")+ }+ public := domain.PublicUser(got)+ raw, _ := json.Marshal(public)+ if strings.Contains(string(raw), "oc-secret") || !public.AgentCLICredentials["opencode"].APIKeyConfigured {+ t.Fatal("public user leaked the agent CLI key or lost the configured flag")+ }+ cleared, err := st.UpdateUserCredentials(user.ID, UserCredentialUpdate{AgentCLICredentials: map[string]AgentCLICredentialUpdate{+ "opencode": {APIKeyClear: true, BaseURL: new(string), Protocol: new(string), Models: &[]domain.CLIModel{}},+ }})+ if err != nil {+ t.Fatal(err)+ }+ if len(cleared.AgentCLICredentials) != 0 {+ t.Fatalf("clear left %+v", cleared.AgentCLICredentials)+ }+}+func TestProviderUserCredentials(t *testing.T) {for _, driver := range []string{"memory", "mysql"} {t.Run(driver, func(t *testing.T) {diff --git a/internal/repo/runner_scrub_test.go b/internal/repo/runner_scrub_test.goindex 610a45dc..49b0dd5b 100644--- a/internal/repo/runner_scrub_test.go+++ b/internal/repo/runner_scrub_test.go@@ -34,6 +34,8 @@ func TestRunnerTaskPayloadScrubbedOnTerminalTransitions(t *testing.T) {CodeBuddyAPIKey: "cb-secret",ClaudeCodeAPIKey: "cc-secret",ClaudeCodeBaseURL: "https://cc.example.com",+ AgentCLIAPIKey: "agy-secret",+ AgentCLIBaseURL: "https://agy.example.com",Repository: &domain.RunnerRepository{CloneURL: "[email protected]/a.git", GitToken: "legacy-token"},Repositories: []domain.RunnerRepository{{CloneURL: "[email protected]/a.git", GitToken: "token-a", Dir: "a"},@@ -94,7 +96,7 @@ func TestRunnerTaskPayloadScrubbedOnTerminalTransitions(t *testing.T) {t.Fatalf("task with attempts left must be requeued: %+v", recovered)}payload := readRawPayload(t, st, "task-requeued")- if !strings.Contains(string(payload), "token-a") || !strings.Contains(string(payload), "token-b") {+ if !strings.Contains(string(payload), "token-a") || !strings.Contains(string(payload), "token-b") || !strings.Contains(string(payload), "agy-secret") {t.Fatalf("requeued task must keep checkout credentials: %s", payload)}@@ -118,7 +120,7 @@ func TestRunnerTaskPayloadScrubbedOnTerminalTransitions(t *testing.T) {func assertPayloadScrubbed(t *testing.T, st *Store, id string) {t.Helper()raw := readRawPayload(t, st, id)- for _, secret := range []string{"cb-secret", "cc-secret", "legacy-token", "token-a", "token-b"} {+ for _, secret := range []string{"cb-secret", "cc-secret", "agy-secret", "https://agy.example.com", "legacy-token", "token-a", "token-b"} {if strings.Contains(string(raw), secret) {t.Fatalf("credential %q leaked into durable payload of %s: %s", secret, id, raw)}diff --git a/internal/repo/runner_store_test.go b/internal/repo/runner_store_test.goindex 094b7e50..fcdfca20 100644--- a/internal/repo/runner_store_test.go+++ b/internal/repo/runner_store_test.go@@ -86,6 +86,28 @@ func TestRunnerHeartbeatPreservesRuntimeAuthMode(t *testing.T) {}}+func TestAgentCLIHeartbeatForcesPersonalAuth(t *testing.T) {+ s := newTestRunner(t)+ now := time.Now().UTC()+ if err := s.PutRunner(domain.Runner{ID: "runner-agy", Status: domain.RunnerStatusOnline, Runtimes: []domain.RunnerRuntime{{Provider: "opencode", Status: domain.RuntimeStatusOnline, AuthMode: domain.RuntimeAuthLocal}}}); err != nil {+ t.Fatal(err)+ }+ runner, _ := s.Runner("runner-agy")+ if got := runner.RuntimeAuthMode("opencode"); got != domain.RuntimeAuthPersonal {+ t.Fatalf("stored local agent CLI auth = %q", got)+ }+ if err := s.SetRunnerRuntimeAuthMode("runner-agy", "opencode", domain.RuntimeAuthLocal, now); err == nil {+ t.Fatal("local auth accepted for opencode")+ }+ if err := s.RunnerHeartbeat("runner-agy", []domain.RunnerRuntime{{Provider: "opencode", Status: domain.RuntimeStatusOnline}}, "1", now, now.Add(time.Hour)); err != nil {+ t.Fatal(err)+ }+ runner, _ = s.Runner("runner-agy")+ if len(runner.Runtimes) != 1 || runner.Runtimes[0].AuthMode != domain.RuntimeAuthPersonal {+ t.Fatalf("heartbeat = %+v", runner.Runtimes)+ }+}+func TestRunnerTaskClaimRespectsProviderAndTargeting(t *testing.T) {s := newTestRunner(t)putQueuedTask(t, s, "rt-codex", "codex", "", 0)diff --git a/internal/repo/runners.go b/internal/repo/runners.goindex 6699b286..d733f2a6 100644--- a/internal/repo/runners.go+++ b/internal/repo/runners.go@@ -310,7 +310,9 @@ func (r *RunnersRepo) RunnerHeartbeat(id string, runtimes []domain.RunnerRuntimeif disabled[runtimes[i].Provider] {runtimes[i].Status = domain.RuntimeStatusDisabled}- if mode := authModes[runtimes[i].Provider]; mode != "" {+ if domain.IsAgentCLIKind(runtimes[i].Provider) {+ runtimes[i].AuthMode = domain.RuntimeAuthPersonal+ } else if mode := authModes[runtimes[i].Provider]; mode != "" {runtimes[i].AuthMode = mode} else if strings.EqualFold(runtimes[i].Provider, "codebuddy") {runtimes[i].AuthMode = domain.RuntimeAuthPersonal@@ -349,6 +351,9 @@ func (r *RunnersRepo) SetRunnerRuntimeAuthMode(runnerID, provider, authMode striif strings.EqualFold(provider, "codebuddy") && authMode != domain.RuntimeAuthPersonal {return fmt.Errorf("CodeBuddy 仅支持个人凭证")}+ if domain.IsAgentCLIKind(provider) && authMode != domain.RuntimeAuthPersonal {+ return fmt.Errorf("%s 仅支持个人凭证", provider)+ }return r.updateRunnerRuntimes(runnerID, func(runtimes []domain.RunnerRuntime) (bool, error) {found := falsefor i := range runtimes {@@ -664,6 +669,8 @@ func scrubRunnerTaskCredentials(task *domain.RunnerTask) {task.Invocation.CodexBaseURL = ""task.Invocation.ClaudeCodeAPIKey = ""task.Invocation.ClaudeCodeBaseURL = ""+ task.Invocation.AgentCLIAPIKey = ""+ task.Invocation.AgentCLIBaseURL = ""if task.Invocation.Repository != nil {task.Invocation.Repository.GitToken = ""}diff --git a/internal/repo/store_test.go b/internal/repo/store_test.goindex b6ce6b25..94413acb 100644--- a/internal/repo/store_test.go+++ b/internal/repo/store_test.go@@ -117,11 +117,8 @@ func TestSeedPopulatesDefaultsForAnEmptyStore(t *testing.T) {if _, ok := s.Sandbox("local"); !ok {t.Fatal("expected seeded local sandbox")}- if _, ok := s.Sandbox("skillhub-macos-seatbelt"); !ok {- t.Fatal("expected seeded skillhub-macos-seatbelt sandbox")- }- if _, ok := s.Sandbox("skillhub-linux-bwrap"); !ok {- t.Fatal("expected seeded skillhub-linux-bwrap sandbox")+ if sandbox, ok := s.Sandbox("skillhub-native"); !ok || sandbox.Driver != domain.SandboxDriverNative {+ t.Fatalf("expected seeded native skillhub sandbox, got %+v", sandbox)}if _, ok := s.Sandbox("container"); ok {t.Fatal("legacy container sandbox must not be seeded")diff --git a/internal/repo/users.go b/internal/repo/users.goindex 81b1d473..a475a975 100644--- a/internal/repo/users.go+++ b/internal/repo/users.go@@ -1,10 +1,13 @@package repoimport (+ "encoding/json""errors"+ "fmt""sort""strings""time"+ "unicode/utf8""agentflow/internal/domain")@@ -28,6 +31,7 @@ type userWithConfig struct {CodexBaseURL *string `gorm:"column:codex_base_url"`ClaudeCodeAPIKey *string `gorm:"column:claude_code_api_key"`ClaudeCodeBaseURL *string `gorm:"column:claude_code_base_url"`+ AgentCLICredentials *string `gorm:"column:agent_cli_credentials"`Created *time.Time `gorm:"column:created_at"`Updated *time.Time `gorm:"column:updated_at"`}@@ -36,6 +40,7 @@ const userSelectColumns = `u.id, u.staff_id, u.login_name, u.chinese_name, u.depCOALESCE(u.platform_role, '') AS platform_role,c.git_token, c.gongfeng_refresh_token, c.gongfeng_token_expires_at, c.codebuddy_api_key, COALESCE(c.codebuddy_internet_environment, '') AS codebuddy_internet_environment,c.codex_api_key, c.codex_base_url, c.claude_code_api_key, c.claude_code_base_url,+ c.agent_cli_credentials,u.created_at, u.updated_at`func (r userWithConfig) toDomain() domain.User {@@ -68,6 +73,9 @@ func (r userWithConfig) toDomain() domain.User {if r.ClaudeCodeBaseURL != nil {u.ClaudeCodeBaseURL = *r.ClaudeCodeBaseURL}+ if r.AgentCLICredentials != nil {+ _ = json.Unmarshal([]byte(*r.AgentCLICredentials), &u.AgentCLICredentials)+ }if r.Created != nil {u.CreatedAt = *r.Created}@@ -144,6 +152,7 @@ func (r *UsersRepo) PutUser(v domain.User) error {v.ClaudeCodeAPIKey, v.ClaudeCodeBaseURL = old.ClaudeCodeAPIKey, old.ClaudeCodeBaseURLv.CodeBuddyAPIKey = old.CodeBuddyAPIKeyv.CodeBuddyInternetEnvironment = old.CodeBuddyInternetEnvironment+ v.AgentCLICredentials = old.AgentCLICredentialsif strings.TrimSpace(v.PlatformRole) == "" {v.PlatformRole = old.PlatformRole}@@ -214,7 +223,8 @@ func userHasConfig(user domain.User) bool {user.CodexAPIKey != "" ||user.CodexBaseURL != "" ||user.ClaudeCodeAPIKey != "" ||- user.ClaudeCodeBaseURL != ""+ user.ClaudeCodeBaseURL != "" ||+ len(user.AgentCLICredentials) > 0}type UserCredentialUpdate struct {@@ -229,6 +239,17 @@ type UserCredentialUpdate struct {ClaudeCodeAPIKey string `json:"claudeCodeApiKey"`ClaudeCodeAPIKeyClear bool `json:"claudeCodeApiKeyClear"`ClaudeCodeBaseURL *string `json:"claudeCodeBaseUrl"`+ // AgentCLICredentials updates the agent CLIs by kind; absent fields keep+ // the stored value. CodeBuddy, Codex and Claude Code stay on their own columns.+ AgentCLICredentials map[string]AgentCLICredentialUpdate `json:"agentCliCredentials"`+}++type AgentCLICredentialUpdate struct {+ APIKey string `json:"apiKey"`+ APIKeyClear bool `json:"apiKeyClear"`+ BaseURL *string `json:"baseUrl"`+ Protocol *string `json:"protocol"`+ Models *[]domain.CLIModel `json:"models"`}func (r *UsersRepo) UpdateUserCredentials(id int64, update UserCredentialUpdate) (domain.User, error) {@@ -271,6 +292,9 @@ func (r *UsersRepo) UpdateUserCredentials(id int64, update UserCredentialUpdate)if update.ClaudeCodeBaseURL != nil {user.ClaudeCodeBaseURL = strings.TrimSpace(*update.ClaudeCodeBaseURL)}+ if err := applyAgentCLICredentialUpdates(&user, update.AgentCLICredentials); err != nil {+ return domain.User{}, err+ }user.UpdatedAt = time.Now().UTC()if err := r.writeUserConfig(user); err != nil {return domain.User{}, err@@ -304,7 +328,8 @@ func (r *UsersRepo) writeUserConfig(v domain.User) error {"codebuddy_internet_environment": v.CodeBuddyInternetEnvironment,"codex_api_key": nullableString(v.CodexAPIKey), "codex_base_url": nullableString(v.CodexBaseURL),"claude_code_api_key": nullableString(v.ClaudeCodeAPIKey), "claude_code_base_url": nullableString(v.ClaudeCodeBaseURL),- "created_at": timePtr(v.CreatedAt), "updated_at": timePtr(v.UpdatedAt),+ "agent_cli_credentials": encodeAgentCLICredentials(v.AgentCLICredentials),+ "created_at": timePtr(v.CreatedAt), "updated_at": timePtr(v.UpdatedAt),})}@@ -314,3 +339,108 @@ func nullableString(v string) any {}return v}++func applyAgentCLICredentialUpdates(user *domain.User, updates map[string]AgentCLICredentialUpdate) error {+ if len(updates) == 0 {+ return nil+ }+ merged := make(map[string]domain.AgentCLICredential, len(user.AgentCLICredentials)+len(updates))+ for kind, cred := range user.AgentCLICredentials {+ merged[kind] = cred+ }+ for kind, update := range updates {+ kind = strings.TrimSpace(kind)+ if !domain.IsAgentCLIKind(kind) {+ return fmt.Errorf("不支持的 CLI:%s", kind)+ }+ cred := merged[kind]+ if update.APIKeyClear {+ cred.APIKey = ""+ } else if value := strings.TrimSpace(update.APIKey); value != "" {+ cred.APIKey = value+ }+ if update.BaseURL != nil {+ cred.BaseURL = strings.TrimSpace(*update.BaseURL)+ }+ if update.Protocol != nil {+ protocol := strings.TrimSpace(*update.Protocol)+ if protocol != "" && domain.NormalizeAgentCLIProtocol(kind, protocol) != protocol {+ return fmt.Errorf("%s 不支持协议 %s", kind, protocol)+ }+ cred.Protocol = protocol+ }+ if update.Models != nil {+ models, err := normalizeCLIModels(*update.Models)+ if err != nil {+ return err+ }+ cred.Models = models+ }+ if cred.APIKey == "" && cred.BaseURL == "" && cred.Protocol == "" && len(cred.Models) == 0 {+ delete(merged, kind)+ continue+ }+ merged[kind] = cred+ }+ if len(merged) == 0 {+ merged = nil+ }+ user.AgentCLICredentials = merged+ return nil+}++func encodeAgentCLICredentials(creds map[string]domain.AgentCLICredential) any {+ if len(creds) == 0 {+ return nil+ }+ raw, err := json.Marshal(creds)+ if err != nil || string(raw) == "{}" || string(raw) == "null" {+ return nil+ }+ return string(raw)+}++const (+ maxCLIModels = 100+ maxCLIModelIDLen = 128+ maxCLIModelNameRune = 64+)++func normalizeCLIModels(models []domain.CLIModel) ([]domain.CLIModel, error) {+ if len(models) > maxCLIModels {+ return nil, fmt.Errorf("模型目录最多 %d 个", maxCLIModels)+ }+ out := make([]domain.CLIModel, 0, len(models))+ seen := map[string]bool{}+ for _, model := range models {+ id, name := strings.TrimSpace(model.ID), strings.TrimSpace(model.Name)+ if id == "" {+ return nil, errors.New("模型 ID 不能为空")+ }+ if len(id) > maxCLIModelIDLen {+ return nil, fmt.Errorf("模型 ID 长度不能超过 %d 个字符", maxCLIModelIDLen)+ }+ for _, r := range id {+ if r <= ' ' || r == 0x7f || r == '"' || r == '\'' || r == '`' || r == '\\' {+ return nil, fmt.Errorf("模型 ID %q 不能包含空格、引号、反斜杠或控制字符", id)+ }+ }+ if seen[id] {+ return nil, fmt.Errorf("模型 ID %s 重复", id)+ }+ seen[id] = true+ if utf8.RuneCountInString(name) > maxCLIModelNameRune {+ return nil, fmt.Errorf("显示名称长度不能超过 %d 个字符", maxCLIModelNameRune)+ }+ for _, r := range name {+ if r < ' ' || r == 0x7f {+ return nil, errors.New("显示名称不能包含控制字符")+ }+ }+ if name == id {+ name = ""+ }+ out = append(out, domain.CLIModel{ID: id, Name: name})+ }+ return out, nil+}diff --git a/internal/repo/workflow_test.go b/internal/repo/workflow_test.goindex 83b5f728..b022f129 100644--- a/internal/repo/workflow_test.go+++ b/internal/repo/workflow_test.go@@ -114,9 +114,14 @@ func TestNormalizeSandboxProfileKeepsOnlyDriverRelevantFields(t *testing.T) {t.Fatalf("local lost sandbox environment: %+v", local)}light := normalizeSandboxProfile(func() domain.SandboxProfile { p := base; p.Driver = "seatbelt"; return p }())- if light.ReadOnlyRootFS {+ if light.ReadOnlyRootFS || light.Driver != domain.SandboxDriverNative {t.Fatalf("seatbelt normalization mismatch: %+v", light)}+ for _, driver := range []string{"bwrap", " native "} {+ if got := normalizeSandboxProfile(domain.SandboxProfile{Driver: driver}).Driver; got != domain.SandboxDriverNative {+ t.Fatalf("%q stored as %q, want native", driver, got)+ }+ }docker := normalizeSandboxProfile(func() domain.SandboxProfile { p := base; p.Driver = "docker"; p.DockerfileID = "runtime"; return p }())if docker.DockerfileID != "runtime" || !docker.ReadOnlyRootFS || docker.EnvironmentID != "" {t.Fatalf("docker lost relevant sandbox fields: %+v", docker)diff --git a/internal/runner/core_cases_test.go b/internal/runner/core_cases_test.goindex 6a8c2a4d..2916f20d 100644--- a/internal/runner/core_cases_test.go+++ b/internal/runner/core_cases_test.go@@ -278,6 +278,27 @@ func TestReadRunnerWorkspaceDispatch(t *testing.T) {}}+func TestDetectRuntimesReportsAgentCLIs(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ bin := filepath.Join(home, "bin")+ if err := os.MkdirAll(bin, 0o755); err != nil {+ t.Fatal(err)+ }+ tool := filepath.Join(bin, "opencode")+ if err := os.WriteFile(tool, []byte("#!/bin/sh\nprintf 'opencode 1.0\\n'\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PATH", bin)+ runtimes := DetectRuntimes(context.Background(), nil)+ for _, rt := range runtimes {+ if rt.Provider == "opencode" && rt.BinaryPath == tool && rt.Status == domain.RuntimeStatusOnline {+ return+ }+ }+ t.Fatalf("opencode not detected: %+v", runtimes)+}+func TestDetectionProviderAndDaemonBasics(t *testing.T) {home := t.TempDir()t.Setenv("HOME", home)diff --git a/internal/runner/daemon.go b/internal/runner/daemon.goindex 55dbec3a..44c1786b 100644--- a/internal/runner/daemon.go+++ b/internal/runner/daemon.go@@ -847,7 +847,17 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)if err != nil {return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil}- if sandbox != nil && inv.CredentialSource == domain.RuntimeAuthPersonal && prepared.Command.PrivateHome {+ if runtime.IsAgentCLI(prepared.Command.Provider) {+ cred := runtime.ProviderCredential{APIKey: inv.AgentCLIAPIKey, BaseURL: inv.AgentCLIBaseURL, Protocol: inv.AgentCLIProtocol}+ var agentEnv map[string]string+ argv, agentEnv, err = runtime.BindAgentCLICommand(sandbox, workspace, prepared.Command, cred, argv)+ if err != nil {+ return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil+ }+ for key, value := range agentEnv {+ credentialEnv[key] = value+ }+ } else if sandbox != nil && inv.CredentialSource == domain.RuntimeAuthPersonal && prepared.Command.PrivateHome {credentialEnv, err = bindSandboxPrivateHome(workspace, task.Sandbox.Profile.Driver, task.Provider, credentialEnv)if err != nil {return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil@@ -1051,7 +1061,7 @@ func bindInvocationCredentials(inv *domain.RunnerInvocation, bindings []runtime.baseURL = "https://api.anthropic.com"}env["ANTHROPIC_BASE_URL"] = baseURL- case runtime.BindGit, runtime.BindMCP:+ case runtime.BindGit, runtime.BindMCP, runtime.BindAgentCLI:continue}}diff --git a/internal/runner/detect.go b/internal/runner/detect.goindex 96dac41b..9fdf6881 100644--- a/internal/runner/detect.go+++ b/internal/runner/detect.go@@ -33,6 +33,15 @@ var defaultProviders = []providerSpec{{Kind: "claude-code", Binary: "claude"},{Kind: "codex", Binary: "codex"},{Kind: "codebuddy", Binary: "codebuddy"},+ // Agent CLIs (domain.AgentCLIExecutorKinds) always run with the+ // responsible user's key in a private HOME. cursor and agy have no npm+ // package and are found on PATH only.+ {Kind: "opencode", Binary: "opencode"},+ {Kind: "cursor", Binary: "cursor-agent"},+ {Kind: "agy", Binary: "agy"},+ {Kind: "kimi", Binary: "kimi"},+ {Kind: "pi", Binary: "pi"},+ {Kind: "dsh", Binary: "dsh"},}// terminalProviderKind is the built-in remote-terminal capability: thediff --git a/internal/runner/managed_cli_selection_test.go b/internal/runner/managed_cli_selection_test.goindex 0cb497ba..f0451e5a 100644--- a/internal/runner/managed_cli_selection_test.go+++ b/internal/runner/managed_cli_selection_test.go@@ -81,7 +81,7 @@ func TestManagedDetectionReportsRealVersionAndRespectsExplicitBinary(t *testing.inventory[provider] = managedcli.Installation{Version: "1.0.0", Binary: managedTestBinary(t, root, provider, "1.0.0")}}for _, rt := range detectRuntimes(context.Background(), nil, inventory) {- if rt.Provider == "mock" || rt.Provider == "terminal" {+ if _, managed := inventory[rt.Provider]; !managed {continue}if !strings.HasPrefix(rt.Version, "actual-1.0.0|") || rt.BinaryPath != inventory[rt.Provider].Binary {diff --git a/internal/runtime/agent_cli.go b/internal/runtime/agent_cli.gonew file mode 100644index 00000000..3a1012a6--- /dev/null+++ b/internal/runtime/agent_cli.go@@ -0,0 +1,444 @@+package runtime++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "regexp"+ "sort"+ "strconv"+ "strings"++ "agentflow/internal/domain"+)++// Agent CLIs beyond CodeBuddy / Codex / Claude Code. Each one runs with the+// responsible user's own key from 个人配置 inside a private HOME that also+// holds the CLI's MCP and model configuration, so neither the host login nor+// the host configuration leaks into a run.+const (+ AgentCLIOpenCode = "opencode"+ AgentCLICursor = "cursor"+ AgentCLIAntigravity = "agy"+ AgentCLIKimi = "kimi"+ AgentCLIPi = "pi"+ AgentCLIDeepSeek = "dsh"+)++// AgentCLIKinds is the display order of the agent CLIs.+var AgentCLIKinds = domain.AgentCLIExecutorKinds++func IsAgentCLI(kind string) bool { return domain.IsAgentCLIKind(kind) }++const (+ AgentCLIProtocolChat = domain.AgentCLIProtocolChat+ AgentCLIProtocolResponses = domain.AgentCLIProtocolResponses+ AgentCLIProtocolMessages = domain.AgentCLIProtocolMessages+ AgentCLIProtocolGemini = domain.AgentCLIProtocolGemini+)++func AgentCLIProtocols(kind string) []string { return domain.AgentCLIProtocolOptions[kind] }++// AgentCLIProtocol normalizes a stored protocol choice; unknown values fall+// back to the CLI's default.+func AgentCLIProtocol(kind, protocol string) string {+ return domain.NormalizeAgentCLIProtocol(kind, protocol)+}++// AgentCLINeedsBaseURL reports whether a credential is unusable without a+// Base URL: OpenCode and Pi have no official endpoint of their own, and+// Antigravity only reaches an OpenAI-compatible gateway through one.+func AgentCLINeedsBaseURL(kind, protocol string) bool {+ switch kind {+ case AgentCLIOpenCode, AgentCLIPi:+ return true+ case AgentCLIAntigravity:+ return AgentCLIProtocol(kind, protocol) == AgentCLIProtocolChat+ }+ return false+}++// agentCLIModelOptional reports whether a CLI picks its own model when+// neither the executor nor the chat names one: Cursor and Antigravity always+// can, DeepSeek Harness on the official endpoint.+func agentCLIModelOptional(kind, baseURL string) bool {+ switch kind {+ case AgentCLICursor:+ return true+ case AgentCLIAntigravity, AgentCLIDeepSeek:+ return baseURL == ""+ }+ return false+}++// AgentCLIOptions carries the per-invocation facts the credential binding+// needs to render a CLI's model configuration.+type AgentCLIOptions struct {+ Model string+ // SystemPromptFile is the system prompt path as the process sees it+ // (relative paths resolve against the working directory).+ SystemPromptFile string+ // ReadOnly is AgentCLICommandOptions.Chat.+ ReadOnly bool+}++// agentCLIKeyEnv holds the user's key for CLIs whose configuration names+// the variable instead of the secret.+const agentCLIKeyEnv = "AGENTFLOW_CLI_API_KEY"++// agentCLIHostEnv is cleared for every child: these variables would select+// the host's own login, key, gateway or configuration directory.+var agentCLIHostEnv = []string{+ agentCLIKeyEnv, "CURSOR_API_KEY", "CURSOR_AUTH_TOKEN", "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL", "GEMINI_BASE_URL",+ "AGY_LLM_GATEWAY_URL", "AGY_LLM_GATEWAY_API_KEY", "AGY_LLM_GATEWAY_WIRE_PROTOCOL", "AGY_LLM_GATEWAY_MODELS",+ "DEEPSEEK_API_KEY", "DSH_HOME", "MOONSHOT_API_KEY", "KIMI_API_KEY", "KIMI_BASE_URL", "KIMI_CODE_HOME",+ "KIMI_MODEL_NAME", "KIMI_MODEL_API_KEY", "KIMI_MODEL_BASE_URL", "KIMI_MODEL_PROVIDER_TYPE",+ "OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT", "OPENCODE_CONFIG_DIR", "PI_CODING_AGENT_DIR",+}++// agentCLIConfigPaths are the HOME-relative files an agent CLI reads its MCP+// servers from.+var agentCLIMCPPaths = map[string]string{+ AgentCLIOpenCode: ".config/opencode/opencode.json",+ AgentCLICursor: ".cursor/mcp.json",+ AgentCLIAntigravity: ".gemini/config/mcp_config.json",+ AgentCLIKimi: ".kimi-code/mcp.json",+ AgentCLIPi: ".pi/agent/mcp.json",+ AgentCLIDeepSeek: ".dsh/agentflow-mcp.json",+}++// AgentCLIMCPOptions shapes the MCP configuration of one invocation.+type AgentCLIMCPOptions struct {+ // ReadOnly denies the CLI's own shell, edit and web tools (AI 对话 runs on+ // the control plane); MCP tools stay available.+ ReadOnly bool+}++var dshServerNameRe = regexp.MustCompile(`[^A-Za-z0-9_-]`)++// WriteAgentCLIMCPConfig renders MCP entries (the mcpConfigEntries shape:+// {"type":"http","url","headers"} or {"command","args","cwd","env"}) in the+// CLI's own format under home, replacing whatever an earlier invocation left.+func WriteAgentCLIMCPConfig(kind, home string, entries map[string]any, options AgentCLIMCPOptions) error {+ rel, ok := agentCLIMCPPaths[kind]+ if !ok {+ return fmt.Errorf("unknown agent CLI %q", kind)+ }+ ids := make([]string, 0, len(entries))+ for id := range entries {+ ids = append(ids, id)+ }+ sort.Strings(ids)+ servers := map[string]any{}+ var dshInserts []any+ for _, id := range ids {+ entry, _ := entries[id].(map[string]any)+ if entry == nil {+ continue+ }+ url, _ := entry["url"].(string)+ command, _ := entry["command"].(string)+ headers := entry["headers"]+ switch {+ case kind == AgentCLIOpenCode && url != "":+ server := map[string]any{"type": "remote", "url": url, "enabled": true, "timeout": 600000}+ if headers != nil {+ server["headers"] = headers+ }+ servers[id] = server+ case kind == AgentCLIOpenCode && command != "":+ argv := []any{command}+ if args, ok := entry["args"].([]string); ok {+ for _, arg := range args {+ argv = append(argv, arg)+ }+ } else if args, ok := entry["args"].([]any); ok {+ argv = append(argv, args...)+ }+ server := map[string]any{"type": "local", "command": argv, "enabled": true, "timeout": 600000}+ if env := entry["env"]; env != nil {+ server["environment"] = env+ }+ servers[id] = server+ case kind == AgentCLIDeepSeek && (url != "" || command != ""):+ name := dshServerNameRe.ReplaceAllString(id, "_")+ if len(name) > 32 {+ name = name[:32]+ }+ config := map[string]any{"serverName": name, "toolCallTimeoutMs": 600000}+ if url != "" {+ config["transport"], config["url"] = "streamable-http", url+ if headers != nil {+ config["headers"] = headers+ }+ } else {+ config["transport"], config["command"] = "stdio", command+ for _, key := range []string{"args", "env", "cwd"} {+ if value := entry[key]; value != nil {+ config[key] = value+ }+ }+ }+ dshInserts = append(dshInserts, map[string]any{"id": "agentflow-mcp-" + name, "name": "@deepseek-ai/dsh-mcp-client", "config": config})+ case url != "":+ key := "url"+ if kind == AgentCLIAntigravity {+ key = "serverUrl"+ }+ server := map[string]any{key: url}+ if headers != nil {+ server["headers"] = headers+ }+ servers[id] = server+ case command != "":+ server := map[string]any{"command": command}+ for _, key := range []string{"args", "env", "cwd"} {+ if value := entry[key]; value != nil && !(key == "cwd" && (kind == AgentCLICursor || kind == AgentCLIAntigravity)) {+ server[key] = value+ }+ }+ servers[id] = server+ }+ }+ var document any+ switch kind {+ case AgentCLIOpenCode:+ permission := map[string]any{"edit": "allow", "bash": "allow", "webfetch": "allow", "external_directory": "allow", "doom_loop": "allow"}+ if options.ReadOnly {+ permission = map[string]any{"edit": "deny", "bash": "deny", "webfetch": "deny", "websearch": "deny", "external_directory": "deny", "task": "deny"}+ }+ document = map[string]any{"$schema": "https://opencode.ai/config.json", "mcp": servers, "permission": permission, "autoupdate": false, "share": "disabled"}+ case AgentCLIDeepSeek:+ if len(dshInserts) == 0 {+ document = []any{}+ } else {+ document = []any{map[string]any{"insert": dshInserts}}+ }+ default:+ document = map[string]any{"mcpServers": servers}+ }+ data, err := json.MarshalIndent(document, "", " ")+ if err != nil {+ return err+ }+ if kind == AgentCLICursor {+ // --force approves everything these rules do not deny.+ deny := []string{}+ if options.ReadOnly {+ deny = []string{"Shell(**)", "Write(**)", "Delete(**)", "WebFetch(*)"}+ }+ config, _ := json.Marshal(map[string]any{"version": 1, "permissions": map[string]any{"allow": []string{}, "deny": deny}})+ if err := writeAgentCLIFile(home, ".cursor/cli-config.json", config); err != nil {+ return err+ }+ }+ return writeAgentCLIFile(home, rel, data)+}++// agyChatPermissions are the Antigravity deny rules of AI 对话.+var agyChatPermissions = map[string]any{"allow": []string{"mcp(*)"}, "deny": []string{"command(*)", "write_file(*)", "read_url(*)"}}++func writeAgentCLIFile(home, rel string, data []byte) error {+ path := filepath.Join(home, filepath.FromSlash(rel))+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ return err+ }+ return os.WriteFile(path, data, 0o600)+}++// ApplyAgentCLICredential writes the credential-dependent model configuration of an+// agent CLI into home (host path; homeEnv is the same directory as the+// process sees it) and returns argv and the environment to run it with. The+// key itself stays in the environment; configuration files only name the+// variable.+func ApplyAgentCLICredential(kind string, cred ProviderCredential, options AgentCLIOptions, home, homeEnv string, argv []string) ([]string, map[string]string, error) {+ key := strings.TrimSpace(cred.APIKey)+ if key == "" {+ return nil, nil, fmt.Errorf("需求责任人未配置 %s API Key,请在个人配置中配置", AgentCLILabel(kind))+ }+ baseURL := strings.TrimRight(strings.TrimSpace(cred.BaseURL), "/")+ protocol := AgentCLIProtocol(kind, cred.Protocol)+ if baseURL == "" && AgentCLINeedsBaseURL(kind, protocol) {+ return nil, nil, fmt.Errorf("%s 需要在个人配置中填写 Base URL", AgentCLILabel(kind))+ }+ model := strings.TrimSpace(options.Model)+ if model == "" && !agentCLIModelOptional(kind, baseURL) {+ return nil, nil, fmt.Errorf("%s 需要指定模型", AgentCLILabel(kind))+ }+ homeEnv = filepath.ToSlash(homeEnv)+ env := map[string]string{}+ switch kind {+ case AgentCLIOpenCode:+ npm := map[string]string{AgentCLIProtocolChat: "@ai-sdk/openai-compatible", AgentCLIProtocolResponses: "@ai-sdk/openai", AgentCLIProtocolMessages: "@ai-sdk/anthropic"}[protocol]+ endpoint := baseURL+ if protocol == AgentCLIProtocolMessages && !strings.HasSuffix(endpoint, "/v1") {+ // Base URLs follow the Claude Code convention; the AI SDK wants /v1.+ endpoint += "/v1"+ }+ config := map[string]any{+ "provider": map[string]any{"agentflow": map[string]any{+ "npm": npm,+ "name": "AgentFlow",+ "options": map[string]any{"baseURL": endpoint, "apiKey": "{env:" + agentCLIKeyEnv + "}"},+ "models": map[string]any{model: map[string]any{"name": model}},+ }},+ "model": "agentflow/" + model,+ "autoupdate": false,+ "share": "disabled",+ }+ if prompt := strings.TrimSpace(options.SystemPromptFile); prompt != "" {+ config["instructions"] = []string{prompt}+ }+ content, _ := json.Marshal(config)+ env[agentCLIKeyEnv] = key+ env["OPENCODE_CONFIG_CONTENT"] = string(content)+ env["OPENCODE_DISABLE_AUTOUPDATE"] = "1"+ case AgentCLICursor:+ env["CURSOR_API_KEY"] = key+ case AgentCLIAntigravity:+ settings := map[string]any{}+ if protocol == AgentCLIProtocolChat {+ env["AGY_LLM_GATEWAY_URL"] = baseURL+ env["AGY_LLM_GATEWAY_API_KEY"] = key+ env["AGY_LLM_GATEWAY_WIRE_PROTOCOL"] = "openai"+ env["AGY_LLM_GATEWAY_MODELS"] = model+ } else {+ settings["modelProvider"] = "gemini"+ env["GEMINI_API_KEY"] = key+ if baseURL != "" {+ env["GOOGLE_GEMINI_BASE_URL"] = baseURL+ env["GEMINI_BASE_URL"] = baseURL+ }+ }+ data, _ := json.Marshal(settings)+ if err := writeAgentCLIFile(home, ".gemini/antigravity-cli/settings.json", data); err != nil {+ return nil, nil, err+ }+ if options.ReadOnly {+ // Inline settings replace the file's for the session, so they+ // repeat the provider.+ settings["permissions"] = agyChatPermissions+ inline, _ := json.Marshal(settings)+ argv = insertBeforeFlag(argv, "-p", "--settings", string(inline))+ }+ case AgentCLIKimi:+ providerType := map[string]string{AgentCLIProtocolChat: "openai", AgentCLIProtocolResponses: "openai_responses", AgentCLIProtocolMessages: "anthropic"}[protocol]+ lines := []string{`default_model = "agentflow"`, "", "[providers.agentflow]"}+ if baseURL == "" {+ lines = append(lines, `type = "kimi"`)+ } else {+ lines = append(lines, "type = "+strconv.Quote(providerType), "base_url = "+strconv.Quote(baseURL))+ }+ lines = append(lines, "api_key_env = "+strconv.Quote(agentCLIKeyEnv), "",+ "[models.agentflow]", `provider = "agentflow"`, "model = "+strconv.Quote(model),+ "max_context_size = 262144", `capabilities = ["thinking", "tool_use"]`, "")+ if err := writeAgentCLIFile(home, ".kimi-code/config.toml", []byte(strings.Join(lines, "\n"))); err != nil {+ return nil, nil, err+ }+ env[agentCLIKeyEnv] = key+ env["KIMI_CODE_HOME"] = homeEnv + "/.kimi-code"+ env["KIMI_DISABLE_TELEMETRY"] = "1"+ case AgentCLIPi:+ api := map[string]string{AgentCLIProtocolChat: "openai-completions", AgentCLIProtocolResponses: "openai-responses", AgentCLIProtocolMessages: "anthropic-messages"}[protocol]+ models, _ := json.MarshalIndent(map[string]any{"providers": map[string]any{"agentflow": map[string]any{+ "baseUrl": baseURL, "api": api, "apiKey": "$" + agentCLIKeyEnv,+ "models": []map[string]any{{"id": model, "reasoning": true}},+ }}}, "", " ")+ if err := writeAgentCLIFile(home, ".pi/agent/models.json", models); err != nil {+ return nil, nil, err+ }+ env[agentCLIKeyEnv] = key+ env["PI_CODING_AGENT_DIR"] = homeEnv + "/.pi/agent"+ case AgentCLIDeepSeek:+ patch := []any{}+ if baseURL == "" {+ env["DEEPSEEK_API_KEY"] = key+ if model != "" {+ patch = append(patch, map[string]any{"id": "agent-default-model", "config": map[string]any{"provider": "deepseek-official", "model": model}})+ }+ } else {+ api := map[string]string{AgentCLIProtocolChat: "openai-completions", AgentCLIProtocolResponses: "openai-responses", AgentCLIProtocolMessages: "anthropic-messages"}[protocol]+ env[agentCLIKeyEnv] = key+ patch = []any{+ map[string]any{"id": "llm-pi-ai", "config": map[string]any{"providers": map[string]any{"agentflow": map[string]any{+ "displayName": "AgentFlow", "apiKeyEnv": agentCLIKeyEnv, "api": api, "baseURL": baseURL,+ "models": []map[string]any{{"id": model}},+ }}}},+ map[string]any{"id": "agent-default-model", "config": map[string]any{"provider": "agentflow", "model": model}},+ }+ }+ data, _ := json.MarshalIndent(patch, "", " ")+ if err := writeAgentCLIFile(home, ".dsh/agentflow-model.json", data); err != nil {+ return nil, nil, err+ }+ env["DSH_HOME"] = homeEnv + "/.dsh"+ // Launcher flags precede the profile's own arguments: dsh --profile <name> --patch … app-args.+ if len(argv) < 3 {+ return nil, nil, errors.New("invalid DeepSeek Harness invocation")+ }+ patches := []string{"--patch", homeEnv + "/.dsh/agentflow-model.json"}+ if _, err := os.Stat(filepath.Join(home, ".dsh", "agentflow-mcp.json")); err == nil {+ patches = append(patches, "--patch", homeEnv+"/.dsh/agentflow-mcp.json")+ }+ head := append([]string{}, argv[:3]...)+ argv = append(append(head, patches...), argv[3:]...)+ default:+ return nil, nil, fmt.Errorf("unknown agent CLI %q", kind)+ }+ return argv, env, nil+}++// insertBeforeFlag inserts values ahead of the last occurrence of flag, or+// appends them when flag is absent.+func insertBeforeFlag(argv []string, flag string, values ...string) []string {+ for i := len(argv) - 1; i > 0; i-- {+ if argv[i] == flag {+ out := append(append([]string{}, argv[:i]...), values...)+ return append(out, argv[i:]...)+ }+ }+ return append(append([]string{}, argv...), values...)+}++// AgentCLIUserCredentials maps a user's saved agent CLI credentials onto the+// form command bindings use.+func AgentCLIUserCredentials(user domain.User) map[string]ProviderCredential {+ if len(user.AgentCLICredentials) == 0 {+ return nil+ }+ out := make(map[string]ProviderCredential, len(user.AgentCLICredentials))+ for kind, cred := range user.AgentCLICredentials {+ out[kind] = ProviderCredential{APIKey: cred.APIKey, BaseURL: cred.BaseURL, Protocol: cred.Protocol}+ }+ return out+}++// AgentCLILabel is the product name shown in errors and settings.+func AgentCLILabel(kind string) string {+ switch kind {+ case AgentCLIOpenCode:+ return "OpenCode"+ case AgentCLICursor:+ return "Cursor CLI"+ case AgentCLIAntigravity:+ return "Antigravity"+ case AgentCLIKimi:+ return "Kimi Code"+ case AgentCLIPi:+ return "Pi"+ case AgentCLIDeepSeek:+ return "DeepSeek Harness"+ }+ return kind+}++// AgentCLIBinary is the executable each agent CLI installs.+func AgentCLIBinary(kind string) string {+ switch kind {+ case AgentCLICursor:+ return "cursor-agent"+ }+ return kind+}diff --git a/internal/runtime/agent_cli_integration_test.go b/internal/runtime/agent_cli_integration_test.gonew file mode 100644index 00000000..fb5eb0af--- /dev/null+++ b/internal/runtime/agent_cli_integration_test.go@@ -0,0 +1,175 @@+package runtime++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "sync"+ "testing"+ "time"++ "agentflow/internal/domain"+)++// credentialSandbox binds credentials the way managedSandbox does.+type credentialSandbox struct {+ *localSandbox+ credentials RunCredentials+}++func (s credentialSandbox) Exec(ctx context.Context, command CommandSpec, sink EventSink) (string, error) {+ bound, err := bindCommand(s.localSandbox, s.workspace, command, s.credentials)+ if err != nil {+ return "", err+ }+ return s.localSandbox.Exec(ctx, bound, sink)+}++// probeMCPServer is a minimal Streamable HTTP MCP server with one tool.+func probeMCPServer(t *testing.T) (*httptest.Server, func() int) {+ var mu sync.Mutex+ calls := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ w.WriteHeader(http.StatusMethodNotAllowed)+ return+ }+ body, _ := io.ReadAll(r.Body)+ var req map[string]any+ if json.Unmarshal(body, &req) != nil {+ http.Error(w, "bad request", http.StatusBadRequest)+ return+ }+ id, hasID := req["id"]+ if !hasID {+ w.WriteHeader(http.StatusAccepted)+ return+ }+ var result any+ switch req["method"] {+ case "initialize":+ version := "2025-03-26"+ if params, ok := req["params"].(map[string]any); ok {+ if v, ok := params["protocolVersion"].(string); ok && v != "" {+ version = v+ }+ }+ result = map[string]any{"protocolVersion": version, "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "probe", "version": "1.0.0"}}+ case "tools/list":+ result = map[string]any{"tools": []any{map[string]any{+ "name": "read_secret", "description": "Returns the secret value.",+ "inputSchema": map[string]any{"type": "object", "properties": map[string]any{}},+ }}}+ case "tools/call":+ mu.Lock()+ calls+++ mu.Unlock()+ result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "secret=42"}}}+ case "ping":+ result = map[string]any{}+ default:+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": id, "error": map[string]any{"code": -32601, "message": "method not found"}})+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": id, "result": result})+ }))+ t.Cleanup(server.Close)+ return server, func() int {+ mu.Lock()+ defer mu.Unlock()+ return calls+ }+}++// Opt-in: runs the installed agent CLIs through the SOP node path with real+// keys. Per kind: AGENTFLOW_TEST_<KIND>_KEY, _BASE_URL, _PROTOCOL, _MODEL.+func TestAgentCLINodeInvocation(t *testing.T) {+ if os.Getenv("AGENTFLOW_TEST_AGENT_CLIS") != "1" {+ t.Skip("set AGENTFLOW_TEST_AGENT_CLIS=1 to exercise installed agent CLIs")+ }+ for _, kind := range AgentCLIKinds {+ prefix := "AGENTFLOW_TEST_" + strings.ToUpper(kind) + "_"+ key := os.Getenv(prefix + "KEY")+ t.Run(kind, func(t *testing.T) {+ if key == "" {+ t.Skip("no " + prefix + "KEY")+ }+ mcp, mcpCalls := probeMCPServer(t)+ workspace := t.TempDir()+ sb := credentialSandbox{+ localSandbox: &localSandbox{id: "agent-cli-test", workspace: workspace},+ credentials: RunCredentials{AgentCLI: map[string]ProviderCredential{kind: {+ APIKey: key, BaseURL: os.Getenv(prefix + "BASE_URL"), Protocol: os.Getenv(prefix + "PROTOCOL"),+ }}},+ }+ ex := domain.ExecutorDefinition{ID: kind, Kind: kind, Binary: AgentCLIBinary(kind), Protocol: "stream-json", Model: os.Getenv(prefix + "MODEL")}+ agent := domain.AgentDefinition{ID: "probe", Name: "probe", Prompt: "You are a terse test agent. Follow the task exactly."}+ assets := domain.AgentAssetBundle{MCPServers: []domain.MCPServerDefinition{{ID: "probe", Name: "probe", Transport: "http", URL: mcp.URL + "/mcp"}}}+ run := func(prompt, resume string) (string, []domain.TelemetryEvent) {+ var mu sync.Mutex+ var events []domain.TelemetryEvent+ sink := func(event domain.TelemetryEvent) {+ mu.Lock()+ events = append(events, event)+ mu.Unlock()+ }+ ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)+ defer cancel()+ output, err := NewExecutorRunner().Run(ctx, sb, fmt.Sprintf("inv-%d", time.Now().UnixNano()), ex, agent, assets, prompt, InvocationOptions{ResumeSessionID: resume}, sink)+ if err != nil {+ t.Fatalf("run failed: %v\n%s", err, output)+ }+ mu.Lock()+ defer mu.Unlock()+ return output, append([]domain.TelemetryEvent(nil), events...)+ }+ output, events := run("Call the read_secret tool of the probe MCP server, then reply with only the number after 'secret='.", "")+ session, toolSeen, usage := "", false, false+ for _, event := range events {+ if event.SessionID != "" {+ session = event.SessionID+ }+ if event.Tool != nil && strings.Contains(event.Tool.Name, "read_secret") {+ toolSeen = true+ }+ if event.Usage != nil && event.Usage.OutputTokens > 0 {+ usage = true+ }+ }+ t.Logf("%s first turn: output=%q session=%q tool=%v usage=%v mcpCalls=%d", kind, output, session, toolSeen, usage, mcpCalls())+ if mcpCalls() == 0 || !strings.Contains(output, "42") {+ t.Fatalf("MCP tool was not used: calls=%d output=%q", mcpCalls(), output)+ }+ if !toolSeen {+ var tools []string+ for _, event := range events {+ if event.Tool != nil {+ tools = append(tools, event.Name+":"+event.Tool.Name+":"+event.Message)+ }+ }+ t.Errorf("no tool telemetry for read_secret: %q", tools)+ }+ if session == "" {+ t.Fatalf("no session id reported")+ }+ output, events = run("What number did the tool return earlier in this conversation? Reply with only the number and do not call any tool.", session)+ resumed := ""+ for _, event := range events {+ if event.SessionID != "" {+ resumed = event.SessionID+ }+ }+ t.Logf("%s resumed turn: output=%q session=%q", kind, output, resumed)+ if !strings.Contains(output, "42") {+ t.Errorf("resumed turn lost the conversation: %q", output)+ }+ })+ }+}diff --git a/internal/runtime/agent_cli_stream.go b/internal/runtime/agent_cli_stream.gonew file mode 100644index 00000000..82f6ab6d--- /dev/null+++ b/internal/runtime/agent_cli_stream.go@@ -0,0 +1,630 @@+package runtime++import (+ "encoding/json"+ "fmt"+ "strings"+)++// ClaudeStream renders the Claude-style stream-json lines that both the SOP+// protocol adapter (handleClaudeStream) and AI 对话 parse: deltas become+// stream_event content blocks, finished text / thinking / tool calls become+// assistant blocks, tool outputs become user tool_result blocks and the turn+// ends with a result line. Every line carries the CLI's session ID once it is+// known, so a node can resume the session.+type ClaudeStream struct {+ SessionID string+ // LastText is the latest finished assistant text, the turn's answer when+ // the CLI reports none of its own.+ LastText string+ block string+ started map[string]bool+ usage map[string]int64+ done bool+}++func (s *ClaudeStream) line(v map[string]any) string {+ if s.SessionID != "" {+ v["session_id"] = s.SessionID+ }+ data, _ := json.Marshal(v)+ return string(data)+}++// Init announces the session; model may be empty.+func (s *ClaudeStream) Init(sessionID, model string) []string {+ if sessionID = strings.TrimSpace(sessionID); sessionID != "" {+ s.SessionID = sessionID+ }+ event := map[string]any{"type": "system", "subtype": "init"}+ if model != "" {+ event["model"] = model+ }+ return []string{s.line(event)}+}++// Delta streams text into the content block key (kind "text" or+// "thinking"), opening it first.+func (s *ClaudeStream) Delta(key, kind, text string) []string {+ if text == "" {+ return nil+ }+ var out []string+ if s.block != key {+ out = append(s.CloseBlock(), s.line(map[string]any{"type": "stream_event", "event": map[string]any{"type": "content_block_start", "content_block": map[string]any{"type": kind}}}))+ s.block = key+ }+ delta := map[string]any{"type": "text_delta", "text": text}+ if kind == "thinking" {+ delta = map[string]any{"type": "thinking_delta", "thinking": text}+ }+ return append(out, s.line(map[string]any{"type": "stream_event", "event": map[string]any{"type": "content_block_delta", "delta": delta}}))+}++func (s *ClaudeStream) CloseBlock() []string {+ if s.block == "" {+ return nil+ }+ s.block = ""+ return []string{s.line(map[string]any{"type": "stream_event", "event": map[string]any{"type": "content_block_stop"}})}+}++func (s *ClaudeStream) assistant(block map[string]any) []string {+ return append(s.CloseBlock(), s.line(map[string]any{"type": "assistant", "message": map[string]any{"role": "assistant", "content": []map[string]any{block}}}))+}++// Text records a finished assistant text block.+func (s *ClaudeStream) Text(text string) []string {+ if strings.TrimSpace(text) == "" {+ return s.CloseBlock()+ }+ s.LastText = text+ return s.assistant(map[string]any{"type": "text", "text": text})+}++// Thinking records a finished reasoning block.+func (s *ClaudeStream) Thinking(text string) []string {+ if strings.TrimSpace(text) == "" {+ return s.CloseBlock()+ }+ return s.assistant(map[string]any{"type": "thinking", "thinking": text})+}++// ToolUse records a tool call once per id.+func (s *ClaudeStream) ToolUse(id, name string, input any) []string {+ if id == "" || name == "" {+ return nil+ }+ if s.started == nil {+ s.started = map[string]bool{}+ }+ if s.started[id] {+ return nil+ }+ s.started[id] = true+ if input == nil {+ input = map[string]any{}+ }+ return s.assistant(map[string]any{"type": "tool_use", "id": id, "name": name, "input": input})+}++// ToolResult records a finished tool call.+func (s *ClaudeStream) ToolResult(id string, failed bool, content string) []string {+ if id == "" {+ return nil+ }+ return append(s.CloseBlock(), s.line(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": []map[string]any{{"type": "tool_result", "tool_use_id": id, "is_error": failed, "content": content}}}}))+}++// AddUsage accumulates token counts reported per step.+func (s *ClaudeStream) AddUsage(input, output, cacheRead, cacheWrite, reasoning int64) {+ if s.usage == nil {+ s.usage = map[string]int64{}+ }+ s.usage["input_tokens"] += input+ s.usage["output_tokens"] += output+ s.usage["cache_read_input_tokens"] += cacheRead+ s.usage["cache_creation_input_tokens"] += cacheWrite+ s.usage["reasoning_tokens"] += reasoning+}++// SetUsage replaces the accumulated usage with a turn total.+func (s *ClaudeStream) SetUsage(input, output, cacheRead, cacheWrite, reasoning int64) {+ s.usage = nil+ s.AddUsage(input, output, cacheRead, cacheWrite, reasoning)+}++// Result ends the turn once; an empty text falls back to LastText.+func (s *ClaudeStream) Result(text string, failed bool) []string {+ if s.done {+ return nil+ }+ s.done = true+ if strings.TrimSpace(text) == "" && !failed {+ text = s.LastText+ }+ subtype := "success"+ if failed {+ subtype = "error"+ }+ event := map[string]any{"type": "result", "subtype": subtype, "is_error": failed, "result": text}+ if s.usage != nil {+ event["usage"] = s.usage+ }+ return append(s.CloseBlock(), s.line(event))+}++// Finished reports whether Result was emitted.+func (s *ClaudeStream) Finished() bool { return s.done }++// NewAgentCLITranslator returns the translator from an agent CLI's native+// headless output (one JSON object per line) to ClaudeStream lines.+func NewAgentCLITranslator(kind string) func(string) []string {+ var translate func(*ClaudeStream, map[string]any) []string+ switch kind {+ case AgentCLIOpenCode:+ translate = (&openCodeStream{}).translate+ case AgentCLICursor:+ translate = (&cursorStream{}).translate+ case AgentCLIAntigravity:+ translate = (&antigravityStream{}).translate+ case AgentCLIKimi:+ translate = (&kimiStream{}).translate+ case AgentCLIPi:+ translate = (&piStream{}).translate+ case AgentCLIDeepSeek:+ translate = (&dshStream{}).translate+ default:+ return nil+ }+ stream := &ClaudeStream{}+ 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 translate(stream, raw)+ }+}++func jsonText(value any) string {+ switch v := value.(type) {+ case nil:+ return ""+ case string:+ return v+ }+ data, _ := json.Marshal(value)+ return string(data)+}++// contentText joins the text parts of an MCP / chat content value.+func contentText(value any) string {+ if text, ok := value.(string); ok {+ return text+ }+ var parts []string+ for _, item := range sliceValue(value) {+ part, _ := item.(map[string]any)+ if text := stringValue(part["text"]); text != "" {+ parts = append(parts, text)+ }+ }+ if len(parts) == 0 && value != nil {+ return jsonText(value)+ }+ return strings.Join(parts, "\n")+}++func errorText(value any) string {+ switch v := value.(type) {+ case string:+ return v+ case map[string]any:+ for _, key := range []string{"message", "error"} {+ if text := errorText(v[key]); text != "" {+ return text+ }+ }+ if data, ok := v["data"].(map[string]any); ok {+ if text := errorText(data); text != "" {+ return text+ }+ }+ if name := stringValue(v["name"]); name != "" {+ return name+ }+ }+ return ""+}++// openCodeStream: `opencode run --format json` reports finished parts.+type openCodeStream struct {+ started bool+ failure string+}++func (o *openCodeStream) translate(s *ClaudeStream, raw map[string]any) []string {+ var out []string+ if !o.started {+ if session := stringValue(raw["sessionID"]); session != "" {+ o.started = true+ out = s.Init(session, "")+ }+ }+ part, _ := raw["part"].(map[string]any)+ switch stringValue(raw["type"]) {+ case "reasoning":+ out = append(out, s.Thinking(stringValue(part["text"]))...)+ case "text":+ out = append(out, s.Text(stringValue(part["text"]))...)+ case "tool_use":+ state, _ := part["state"].(map[string]any)+ id := stringValue(part["callID"])+ out = append(out, s.ToolUse(id, stringValue(part["tool"]), state["input"])...)+ switch stringValue(state["status"]) {+ case "completed":+ out = append(out, s.ToolResult(id, false, jsonText(state["output"]))...)+ case "error":+ out = append(out, s.ToolResult(id, true, jsonText(state["error"]))...)+ }+ case "step_finish":+ tokens, _ := part["tokens"].(map[string]any)+ cache, _ := tokens["cache"].(map[string]any)+ s.AddUsage(int64Value(tokens["input"]), int64Value(tokens["output"]), int64Value(cache["read"]), int64Value(cache["write"]), int64Value(tokens["reasoning"]))+ if reason := stringValue(part["reason"]); reason != "tool-calls" && reason != "" {+ out = append(out, s.Result("", o.failure != "" && s.LastText == "")...)+ }+ case "error":+ o.failure = errorText(raw["error"])+ if o.failure == "" {+ o.failure = "OpenCode 运行失败"+ }+ out = append(out, s.Result(o.failure, true)...)+ }+ return out+}++// cursorStream: `cursor-agent -p --output-format stream-json+// --stream-partial-output`. Partial assistant events carry timestamp_ms and+// one text chunk each; the final assistant event repeats the whole text.+type cursorStream struct {+ segment int+ partial strings.Builder+ thinking strings.Builder+}++func (c *cursorStream) flushText(s *ClaudeStream) []string {+ text := c.partial.String()+ c.partial.Reset()+ c.segment+++ return s.Text(text)+}++func (c *cursorStream) flushThinking(s *ClaudeStream) []string {+ text := c.thinking.String()+ c.thinking.Reset()+ if text == "" {+ return nil+ }+ c.segment+++ return s.Thinking(text)+}++func cursorToolCall(raw map[string]any) (name string, input any, result map[string]any) {+ call, _ := raw["tool_call"].(map[string]any)+ for key, value := range call {+ if !strings.HasSuffix(key, "ToolCall") {+ continue+ }+ body, _ := value.(map[string]any)+ args, _ := body["args"].(map[string]any)+ result, _ = body["result"].(map[string]any)+ switch key {+ case "mcpToolCall":+ server := stringValue(args["providerIdentifier"])+ if server == "" {+ server = stringValue(args["serverIdentifier"])+ }+ return "mcp__" + server + "__" + stringValue(args["toolName"]), args["args"], result+ case "shellToolCall":+ return "Bash", map[string]any{"command": args["command"]}, result+ }+ name = strings.TrimSuffix(key, "ToolCall")+ if name != "" {+ name = strings.ToUpper(name[:1]) + name[1:]+ }+ delete(args, "toolCallId")+ return name, args, result+ }+ return "", nil, nil+}++func (c *cursorStream) translate(s *ClaudeStream, raw map[string]any) []string {+ switch stringValue(raw["type"]) {+ case "system":+ if stringValue(raw["subtype"]) == "init" {+ return s.Init(stringValue(raw["session_id"]), stringValue(raw["model"]))+ }+ case "thinking":+ if stringValue(raw["subtype"]) == "delta" {+ text := stringValue(raw["text"])+ c.thinking.WriteString(text)+ return s.Delta(fmt.Sprintf("thinking#%d", c.segment), "thinking", text)+ }+ return c.flushThinking(s)+ case "assistant":+ message, _ := raw["message"].(map[string]any)+ text := contentText(message["content"])+ out := c.flushThinking(s)+ if _, partial := raw["timestamp_ms"]; partial {+ c.partial.WriteString(text)+ return append(out, s.Delta(fmt.Sprintf("text#%d", c.segment), "text", text)...)+ }+ c.partial.Reset()+ c.segment+++ return append(out, s.Text(text)...)+ case "tool_call":+ out := append(c.flushThinking(s), c.flushText(s)...)+ id := stringValue(raw["call_id"])+ name, input, result := cursorToolCall(raw)+ out = append(out, s.ToolUse(id, name, input)...)+ if stringValue(raw["subtype"]) == "completed" {+ success, ok := result["success"]+ failure := result["error"]+ if !ok && failure == nil {+ failure = result["rejected"]+ }+ if failure != nil {+ out = append(out, s.ToolResult(id, true, jsonText(failure))...)+ } else {+ body, _ := success.(map[string]any)+ content := body["content"]+ if content == nil {+ content = success+ }+ out = append(out, s.ToolResult(id, false, contentText(content))...)+ }+ }+ return out+ case "result":+ out := append(c.flushThinking(s), c.flushText(s)...)+ usage, _ := raw["usage"].(map[string]any)+ s.SetUsage(int64Value(usage["inputTokens"]), int64Value(usage["outputTokens"]), int64Value(usage["cacheReadTokens"]), int64Value(usage["cacheWriteTokens"]), 0)+ failed, _ := raw["is_error"].(bool)+ text := stringValue(raw["result"])+ if failed && text == "" {+ text = errorText(raw["error"])+ }+ return append(out, s.Result(text, failed)...)+ }+ return nil+}++// antigravityStream: `agy -p --output-format stream-json`.+type antigravityStream struct {+ text strings.Builder+ failure string+}++func (a *antigravityStream) translate(s *ClaudeStream, raw map[string]any) []string {+ switch stringValue(raw["event"]) {+ case "init":+ init, _ := raw["init"].(map[string]any)+ return s.Init(stringValue(raw["conversation_id"]), stringValue(init["model"]))+ case "step_update":+ step, _ := raw["step_update"].(map[string]any)+ index := int64Value(step["step_index"])+ done := stringValue(step["state"]) == "DONE"+ switch stringValue(step["step_type"]) {+ case "agent_response":+ delta := stringValue(step["text_delta"])+ a.text.WriteString(delta)+ out := s.Delta(fmt.Sprintf("text#%d", index), "text", delta)+ if done {+ if usage, ok := step["usage"].(map[string]any); ok {+ s.AddUsage(int64Value(usage["input_tokens"]), int64Value(usage["output_tokens"]), int64Value(usage["cache_read_tokens"]), 0, int64Value(usage["thinking_tokens"]))+ }+ out = append(out, s.Text(a.text.String())...)+ a.text.Reset()+ }+ return out+ case "tool":+ info, _ := step["tool_info"].(map[string]any)+ id := fmt.Sprintf("%s#%d", stringValue(step["conversation_id"]), index)+ name := stringValue(info["name"])+ input := info["parameters"]+ if params, ok := input.(map[string]any); ok && name == "call_mcp_tool" {+ name, input = "mcp__"+stringValue(params["ServerName"])+"__"+stringValue(params["ToolName"]), params["Arguments"]+ }+ out := s.ToolUse(id, name, input)+ if done {+ failure := errorText(info["error"])+ if failure != "" {+ out = append(out, s.ToolResult(id, true, failure)...)+ } else {+ out = append(out, s.ToolResult(id, false, jsonText(info["output"]))...)+ }+ }+ return out+ case "error_message":+ if text := errorText(step["error"]); text != "" {+ a.failure = text+ }+ }+ case "result":+ result, _ := raw["result"].(map[string]any)+ failed := stringValue(result["status"]) != "SUCCESS"+ text := stringValue(result["response"])+ if failed {+ if text = errorText(result["error"]); text == "" {+ text = a.failure+ }+ if text == "" {+ text = "Antigravity 运行失败"+ }+ }+ if usage, ok := result["usage"].(map[string]any); ok {+ s.SetUsage(int64Value(usage["input_tokens"]), int64Value(usage["output_tokens"]), int64Value(usage["cache_read_tokens"]), 0, int64Value(usage["thinking_tokens"]))+ }+ return s.Result(text, failed)+ }+ return nil+}++// kimiStream: `kimi -p --output-format stream-json` prints whole messages;+// the session ID only arrives with the closing resume hint.+type kimiStream struct{ started bool }++func (k *kimiStream) translate(s *ClaudeStream, raw map[string]any) []string {+ var out []string+ if !k.started {+ k.started = true+ out = s.Init("", "")+ }+ switch stringValue(raw["role"]) {+ case "assistant":+ if text, ok := raw["content"].(string); ok {+ out = append(out, s.Text(text)...)+ }+ for _, item := range sliceValue(raw["content"]) {+ part, _ := item.(map[string]any)+ switch stringValue(part["type"]) {+ case "text":+ out = append(out, s.Text(stringValue(part["text"]))...)+ case "think", "thinking":+ text := stringValue(part["think"])+ if text == "" {+ text = stringValue(part["thinking"])+ }+ out = append(out, s.Thinking(text)...)+ }+ }+ for _, item := range sliceValue(raw["tool_calls"]) {+ call, _ := item.(map[string]any)+ function, _ := call["function"].(map[string]any)+ var input any = map[string]any{}+ if arguments := stringValue(function["arguments"]); arguments != "" {+ _ = json.Unmarshal([]byte(arguments), &input)+ }+ out = append(out, s.ToolUse(stringValue(call["id"]), stringValue(function["name"]), input)...)+ }+ case "tool":+ out = append(out, s.ToolResult(stringValue(raw["tool_call_id"]), false, contentText(raw["content"]))...)+ case "meta":+ if stringValue(raw["type"]) == "session.resume_hint" {+ s.SessionID = stringValue(raw["session_id"])+ out = append(out, s.Init(s.SessionID, "")...)+ out = append(out, s.Result("", false)...)+ }+ }+ return out+}++// piStream: `pi --mode json` streams deltas per content index and reports+// finished messages and tool executions.+type piStream struct {+ turn int+ failure string+}++func (p *piStream) translate(s *ClaudeStream, raw map[string]any) []string {+ switch stringValue(raw["type"]) {+ case "session":+ return s.Init(stringValue(raw["id"]), "")+ case "turn_start":+ p.turn+++ case "message_update":+ event, _ := raw["assistantMessageEvent"].(map[string]any)+ key := fmt.Sprintf("%d#%d", p.turn, int64Value(event["contentIndex"]))+ switch stringValue(event["type"]) {+ case "text_delta":+ return s.Delta(key, "text", stringValue(event["delta"]))+ case "thinking_delta":+ return s.Delta(key, "thinking", stringValue(event["delta"]))+ }+ case "message_end":+ message, _ := raw["message"].(map[string]any)+ if stringValue(message["role"]) != "assistant" {+ return nil+ }+ usage, _ := message["usage"].(map[string]any)+ s.AddUsage(int64Value(usage["input"]), int64Value(usage["output"]), int64Value(usage["cacheRead"]), int64Value(usage["cacheWrite"]), int64Value(usage["reasoning"]))+ if stringValue(message["stopReason"]) == "error" {+ p.failure = stringValue(message["errorMessage"])+ }+ var out []string+ for _, item := range sliceValue(message["content"]) {+ part, _ := item.(map[string]any)+ switch stringValue(part["type"]) {+ case "text":+ out = append(out, s.Text(stringValue(part["text"]))...)+ case "thinking":+ out = append(out, s.Thinking(stringValue(part["thinking"]))...)+ case "toolCall":+ out = append(out, s.ToolUse(stringValue(part["id"]), stringValue(part["name"]), part["arguments"])...)+ }+ }+ return append(out, s.CloseBlock()...)+ case "tool_execution_start":+ // Top-level calls are reported from the assistant message; nested ones+ // (MCP tools called from codemode) only appear here.+ if stringValue(raw["parentToolCallId"]) == "" {+ return nil+ }+ return s.ToolUse(stringValue(raw["toolCallId"]), stringValue(raw["toolName"]), raw["args"])+ case "tool_execution_end":+ result, _ := raw["result"].(map[string]any)+ failed, _ := raw["isError"].(bool)+ return s.ToolResult(stringValue(raw["toolCallId"]), failed, contentText(result["content"]))+ case "agent_end":+ if p.failure != "" && s.LastText == "" {+ return s.Result(p.failure, true)+ }+ return s.Result("", false)+ }+ return nil+}++// dshStream: `dsh --profile headless --json` run events.+type dshStream struct{ failure string }++func (d *dshStream) translate(s *ClaudeStream, raw map[string]any) []string {+ switch stringValue(raw["type"]) {+ case "session":+ return s.Init(stringValue(raw["sessionId"]), "")+ case "thinking":+ return s.Thinking(stringValue(raw["text"]))+ case "text":+ return s.Text(stringValue(raw["text"]))+ case "tool_call":+ return s.ToolUse(stringValue(raw["callId"]), stringValue(raw["tool"]), raw["input"])+ case "tool_result":+ return s.ToolResult(stringValue(raw["callId"]), stringValue(raw["status"]) != "completed", jsonText(raw["result"]))+ case "status":+ if stringValue(raw["phase"]) == "step_end" {+ usage, _ := raw["usage"].(map[string]any)+ s.AddUsage(int64Value(usage["inputTokens"]), int64Value(usage["outputTokens"]), int64Value(usage["cacheReadTokens"]), int64Value(usage["cacheWriteTokens"]), int64Value(usage["reasoningTokens"]))+ }+ case "error":+ d.failure = errorText(raw)+ case "final":+ if session := stringValue(raw["sessionId"]); session != "" {+ s.SessionID = session+ }+ reason, _ := raw["reason"].(map[string]any)+ failed := stringValue(reason["kind"]) != "completed"+ text := stringValue(raw["text"])+ if failed && text == "" {+ if text = d.failure; text == "" {+ text = "DeepSeek Harness 运行结束:" + stringValue(reason["kind"])+ }+ }+ return s.Result(text, failed)+ }+ return nil+}diff --git a/internal/runtime/agent_cli_test.go b/internal/runtime/agent_cli_test.gonew file mode 100644index 00000000..087bedac--- /dev/null+++ b/internal/runtime/agent_cli_test.go@@ -0,0 +1,230 @@+package runtime++import (+ "encoding/json"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "testing"++ "agentflow/internal/domain"+)++func TestAgentCLICommandChatRestrictions(t *testing.T) {+ chat := func(kind string, o AgentCLICommandOptions) CommandSpec {+ o.Chat, o.Prompt, o.SystemPrompt = true, "hello", "SYSTEM"+ if o.Model == "" {+ o.Model = "m1"+ }+ return AgentCLICommand(kind, o)+ }+ cases := []struct {+ kind string+ o AgentCLICommandOptions+ want []string+ }{+ {AgentCLICursor, AgentCLICommandOptions{}, []string{"--force", "--approve-mcps", "--model", "m1"}},+ {AgentCLIPi, AgentCLICommandOptions{SystemPromptFile: "/s.md"}, []string{"--exclude-tools", "bash,edit,write", "--append-system-prompt", "/s.md"}},+ {AgentCLIDeepSeek, AgentCLICommandOptions{}, []string{"--permission-mode", "read-only"}},+ {AgentCLIKimi, AgentCLICommandOptions{AgentFile: "/a.md"}, []string{"--agent-file", "/a.md"}},+ {AgentCLIOpenCode, AgentCLICommandOptions{Resume: "ses_1"}, []string{"-s", "ses_1", "-m", "agentflow/m1"}},+ }+ for _, c := range cases {+ command := chat(c.kind, c.o)+ if command.Provider != c.kind || !command.AgentCLI.ReadOnly {+ t.Fatalf("%s: provider=%q readOnly=%v", c.kind, command.Provider, command.AgentCLI.ReadOnly)+ }+ for _, arg := range c.want {+ if !slices.Contains(command.Argv, arg) {+ t.Errorf("%s argv misses %q: %q", c.kind, arg, command.Argv)+ }+ }+ }+ // The system prompt is inlined on the first turn only; OpenCode and Pi+ // load it themselves and Kimi carries it in its agent file.+ if argv := chat(AgentCLICursor, AgentCLICommandOptions{}).Argv; !strings.Contains(argv[len(argv)-1], "SYSTEM") {+ t.Errorf("first cursor turn lacks the system prompt: %q", argv[len(argv)-1])+ }+ if argv := chat(AgentCLICursor, AgentCLICommandOptions{Resume: "c1"}).Argv; argv[len(argv)-1] != "hello" {+ t.Errorf("resumed cursor turn repeats the system prompt: %q", argv[len(argv)-1])+ }+ for _, kind := range []string{AgentCLIKimi, AgentCLIPi, AgentCLIOpenCode} {+ if argv := chat(kind, AgentCLICommandOptions{}).Argv; argv[len(argv)-1] != "hello" {+ t.Errorf("%s inlines the system prompt: %q", kind, argv[len(argv)-1])+ }+ }+ // A resumed Kimi session keeps its agent; -S cannot be combined with it.+ if argv := chat(AgentCLIKimi, AgentCLICommandOptions{AgentFile: "/a.md", Resume: "session_1"}).Argv; slices.Contains(argv, "--agent-file") || !slices.Contains(argv, "session_1") {+ t.Errorf("resumed kimi argv: %q", argv)+ }+ if argv := AgentCLICommand(AgentCLIDeepSeek, AgentCLICommandOptions{Prompt: "x"}).Argv; !slices.Contains(argv, "danger-full-access") {+ t.Errorf("SOP dsh argv: %q", argv)+ }+}++func TestAgentCLICommandAgyEffortSuffix(t *testing.T) {+ for _, tc := range []struct{ model, effort, want string }{+ {"gemini-3.8-flash-medium", "low", "gemini-3.8-flash-low"},+ {"gemini-3.8-flash-medium", "", "gemini-3.8-flash-medium"},+ {"gemini-3.8-flash", "low", "gemini-3.8-flash"},+ {"gemini-4-argon-xhigh", "max", "gemini-4-argon-max"},+ {"gateway-model", "low", "gateway-model"},+ } {+ argv := AgentCLICommand(AgentCLIAntigravity, AgentCLICommandOptions{Model: tc.model, Effort: tc.effort, Prompt: "p"}).Argv+ if i := slices.Index(argv, "--model"); i < 0 || argv[i+1] != tc.want {+ t.Errorf("%s at %q: %q", tc.model, tc.effort, argv)+ }+ if want := tc.effort != "" && AgyModelEfforts(tc.model) != nil; slices.Contains(argv, "--effort") != want {+ t.Errorf("%s at %q: --effort passed=%v: %q", tc.model, tc.effort, !want, argv)+ }+ }+}++func TestApplyAgentCLICredential(t *testing.T) {+ home := t.TempDir()+ if _, _, err := ApplyAgentCLICredential(AgentCLIOpenCode, ProviderCredential{}, AgentCLIOptions{Model: "m"}, home, home, nil); err == nil || !strings.Contains(err.Error(), "API Key") {+ t.Fatalf("missing key: %v", err)+ }+ if _, _, err := ApplyAgentCLICredential(AgentCLIPi, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, home, home, nil); err == nil || !strings.Contains(err.Error(), "Base URL") {+ t.Fatalf("pi without Base URL: %v", err)+ }+ if _, _, err := ApplyAgentCLICredential(AgentCLIKimi, ProviderCredential{APIKey: "k"}, AgentCLIOptions{}, home, home, nil); err == nil || !strings.Contains(err.Error(), "模型") {+ t.Fatalf("kimi without model: %v", err)+ }++ // The key travels in the environment; config files only name the variable.+ _, env, err := ApplyAgentCLICredential(AgentCLIOpenCode, ProviderCredential{APIKey: "secret-key", BaseURL: "https://gw.example/", Protocol: "messages"}, AgentCLIOptions{Model: "m"}, home, home, []string{"opencode", "run", "x"})+ if err != nil {+ t.Fatal(err)+ }+ if env[agentCLIKeyEnv] != "secret-key" || strings.Contains(env["OPENCODE_CONFIG_CONTENT"], "secret-key") || !strings.Contains(env["OPENCODE_CONFIG_CONTENT"], `"baseURL":"https://gw.example/v1"`) || !strings.Contains(env["OPENCODE_CONFIG_CONTENT"], "@ai-sdk/anthropic") {+ t.Fatalf("opencode env: %v", env)+ }++ _, env, err = ApplyAgentCLICredential(AgentCLIKimi, ProviderCredential{APIKey: "secret-key", BaseURL: "https://api.example/v1", Protocol: "responses"}, AgentCLIOptions{Model: "m"}, home, "/w/home", nil)+ if err != nil {+ t.Fatal(err)+ }+ toml, _ := os.ReadFile(filepath.Join(home, ".kimi-code", "config.toml"))+ if env["KIMI_CODE_HOME"] != "/w/home/.kimi-code" || !strings.Contains(string(toml), `type = "openai_responses"`) || strings.Contains(string(toml), "secret-key") {+ t.Fatalf("kimi config: %v\n%s", env, toml)+ }++ // Chat on Antigravity adds deny rules inline, repeating the provider.+ argv, env, err := ApplyAgentCLICredential(AgentCLIAntigravity, ProviderCredential{APIKey: "g"}, AgentCLIOptions{ReadOnly: true}, home, home, []string{"agy", "--output-format", "stream-json", "-p", "hi"})+ if err != nil {+ t.Fatal(err)+ }+ i := slices.Index(argv, "--settings")+ if i < 0 || argv[i+2] != "-p" || env["GEMINI_API_KEY"] != "g" {+ t.Fatalf("agy chat argv: %q env=%v", argv, env)+ }+ var settings struct {+ ModelProvider string `json:"modelProvider"`+ Permissions struct {+ Deny []string `json:"deny"`+ } `json:"permissions"`+ }+ if err := json.Unmarshal([]byte(argv[i+1]), &settings); err != nil || settings.ModelProvider != "gemini" || !slices.Contains(settings.Permissions.Deny, "command(*)") {+ t.Fatalf("agy inline settings: %s (%v)", argv[i+1], err)+ }+ if argv, _, _ := ApplyAgentCLICredential(AgentCLIAntigravity, ProviderCredential{APIKey: "g"}, AgentCLIOptions{}, home, home, []string{"agy", "-p", "hi"}); slices.Contains(argv, "--settings") {+ t.Fatalf("SOP agy argv carries chat settings: %q", argv)+ }++ argv, _, err = ApplyAgentCLICredential(AgentCLIDeepSeek, ProviderCredential{APIKey: "d"}, AgentCLIOptions{Model: "deepseek-v4-flash"}, home, "/h", []string{"dsh", "--profile", "headless", "--json", "x"})+ if err != nil {+ t.Fatal(err)+ }+ if !slices.Equal(argv[:5], []string{"dsh", "--profile", "headless", "--patch", "/h/.dsh/agentflow-model.json"}) {+ t.Fatalf("dsh argv: %q", argv)+ }+}++func TestWriteAgentCLIMCPConfigChat(t *testing.T) {+ entries := map[string]any{"gw": map[string]any{"type": "http", "url": "http://127.0.0.1:1/mcp", "headers": map[string]any{"Authorization": "Bearer t"}}}+ read := func(home, rel string) map[string]any {+ t.Helper()+ data, err := os.ReadFile(filepath.Join(home, rel))+ if err != nil {+ t.Fatal(err)+ }+ var doc map[string]any+ if err := json.Unmarshal(data, &doc); err != nil {+ t.Fatal(err)+ }+ return doc+ }+ home := t.TempDir()+ if err := WriteAgentCLIMCPConfig(AgentCLICursor, home, entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ t.Fatal(err)+ }+ if deny := read(home, ".cursor/cli-config.json")["permissions"].(map[string]any)["deny"].([]any); !slices.Contains(deny, any("Shell(**)")) {+ t.Fatalf("cursor chat deny: %v", deny)+ }+ if server := read(home, ".cursor/mcp.json")["mcpServers"].(map[string]any)["gw"].(map[string]any); server["url"] != "http://127.0.0.1:1/mcp" {+ t.Fatalf("cursor mcp: %v", server)+ }+ // An SOP invocation in the same home lifts the chat rules again.+ if err := WriteAgentCLIMCPConfig(AgentCLICursor, home, entries, AgentCLIMCPOptions{}); err != nil {+ t.Fatal(err)+ }+ if deny := read(home, ".cursor/cli-config.json")["permissions"].(map[string]any)["deny"].([]any); len(deny) != 0 {+ t.Fatalf("cursor SOP deny: %v", deny)+ }+ if err := WriteAgentCLIMCPConfig(AgentCLIOpenCode, home, entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ t.Fatal(err)+ }+ doc := read(home, ".config/opencode/opencode.json")+ if permission := doc["permission"].(map[string]any); permission["bash"] != "deny" || permission["edit"] != "deny" {+ t.Fatalf("opencode chat permission: %v", permission)+ }+ if server := doc["mcp"].(map[string]any)["gw"].(map[string]any); server["type"] != "remote" {+ t.Fatalf("opencode mcp: %v", server)+ }+ if err := WriteAgentCLIMCPConfig(AgentCLIAntigravity, home, entries, AgentCLIMCPOptions{}); err != nil {+ t.Fatal(err)+ }+ if server := read(home, ".gemini/config/mcp_config.json")["mcpServers"].(map[string]any)["gw"].(map[string]any); server["serverUrl"] == nil {+ t.Fatalf("agy mcp: %v", server)+ }+}++func TestWriteKimiChatAgent(t *testing.T) {+ path := filepath.Join(t.TempDir(), "agent.md")+ if err := WriteKimiChatAgent(path, "Be terse."); err != nil {+ t.Fatal(err)+ }+ data, _ := os.ReadFile(path)+ if text := string(data); !strings.HasPrefix(text, "---\nname: agentflow-chat\n") || !strings.Contains(text, "disallowedTools: [Bash, Edit, Write") || !strings.HasSuffix(text, "---\nBe terse.\n") {+ t.Fatalf("kimi agent:\n%s", text)+ }+}++func TestAgentCLITranslatorPiNestedTools(t *testing.T) {+ translate := NewAgentCLITranslator(AgentCLIPi)+ var lines []string+ for _, raw := range []string{+ `{"type":"session","id":"s-1"}`,+ `{"type":"tool_execution_start","toolCallId":"outer","toolName":"codemode","args":{}}`,+ `{"type":"tool_execution_start","toolCallId":"inner","toolName":"probe_read_secret","args":{},"parentToolCallId":"outer"}`,+ `{"type":"tool_execution_end","toolCallId":"inner","result":{"content":[{"type":"text","text":"secret=42"}]},"isError":false,"parentToolCallId":"outer"}`,+ } {+ lines = append(lines, translate(raw)...)+ }+ joined := strings.Join(lines, "\n")+ if !strings.Contains(joined, `"name":"probe_read_secret"`) || !strings.Contains(joined, `"tool_use_id":"inner"`) {+ t.Fatalf("nested pi tool calls are not reported:\n%s", joined)+ }+}++func TestAgentCLIUserCredentials(t *testing.T) {+ creds := AgentCLIUserCredentials(domain.User{AgentCLICredentials: map[string]domain.AgentCLICredential{"kimi": {APIKey: "k", BaseURL: "u", Protocol: "messages"}}})+ if creds["kimi"] != (ProviderCredential{APIKey: "k", BaseURL: "u", Protocol: "messages"}) {+ t.Fatalf("credentials: %+v", creds)+ }+ if AgentCLIUserCredentials(domain.User{}) != nil {+ t.Fatal("empty user has agent CLI credentials")+ }+}diff --git a/internal/runtime/cli_live_config.go b/internal/runtime/cli_live_config.gonew file mode 100644index 00000000..67dc4598--- /dev/null+++ b/internal/runtime/cli_live_config.go@@ -0,0 +1,89 @@+//go:build clilive++package runtime++import (+ "encoding/json"+ "os"+ "strconv"+ "strings"+ "testing"+ "time"+)++var liveCLIOrder = []string{"codebuddy", "codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh"}++type liveCLIConfig struct {+ Key string `json:"key"`+ BaseURL string `json:"baseUrl"`+ Protocol string `json:"protocol"`+ Model string `json:"model"`+ Environment string `json:"environment"`+}++func liveExecutorArgs(kind string) []string {+ switch kind {+ case "codebuddy":+ return []string{"-p", "--output-format", "stream-json", "--include-partial-messages", "-y", "--setting-sources", "none"}+ case "codex":+ return []string{"exec", "--json", "--sandbox", "workspace-write", "--skip-git-repo-check"}+ case "claude-code":+ return []string{"-p", "--output-format", "stream-json", "--permission-mode", "dontAsk"}+ default:+ return nil+ }+}++func liveTimeout() time.Duration {+ seconds, _ := strconv.Atoi(os.Getenv("CLI_LIVE_TIMEOUT"))+ if seconds <= 0 {+ seconds = 90+ }+ return time.Duration(seconds) * time.Second+}++func loadLiveConfig(t *testing.T) map[string]liveCLIConfig {+ t.Helper()+ path := os.Getenv("CLI_LIVE_CONFIG")+ if path == "" {+ t.Fatal("CLI_LIVE_CONFIG is required")+ }+ raw, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ var cfg map[string]liveCLIConfig+ if err := json.Unmarshal(raw, &cfg); err != nil {+ t.Fatal(err)+ }+ return cfg+}++func redactLive(text string) string {+ for _, prefix := range []string{"sk-", "crsr_", "ck_", "AQ."} {+ for {+ i := strings.Index(text, prefix)+ if i < 0 {+ break+ }+ end := i + len(prefix)+ for end < len(text) && end < i+len(prefix)+80 {+ r := text[end]+ if r == ' ' || r == '\n' || r == '\t' || r == '"' || r == '\'' || r == ',' || r == '\\' {+ break+ }+ end+++ }+ text = text[:i] + "[redacted]" + text[end:]+ }+ }+ return text+}++func clipLive(text string) string {+ text = strings.TrimSpace(text)+ if len(text) > 700 {+ return text[:700] + "…"+ }+ return text+}diff --git a/internal/runtime/cli_live_test.go b/internal/runtime/cli_live_test.gonew file mode 100644index 00000000..b2b6e12c--- /dev/null+++ b/internal/runtime/cli_live_test.go@@ -0,0 +1,121 @@+//go:build clilive++package runtime++import (+ "context"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "agentflow/internal/domain"+)++// Opt-in live check. It runs inside a Linux container that already has the+// CLIs; it does not install anything on the developer machine.+func TestLiveSOPSandboxes(t *testing.T) {+ if os.Getenv("CLI_LIVE") != "1" {+ t.Skip("set CLI_LIVE=1 to run CLI sandbox conversations")+ }+ cfg := loadLiveConfig(t)+ root := os.Getenv("CLI_LIVE_WORKSPACE")+ if root == "" {+ t.Fatal("CLI_LIVE_WORKSPACE is required so a docker sandbox can mount a host path")+ }+ for _, kind := range liveCLIOrder {+ item, ok := cfg[kind]+ if !ok || strings.TrimSpace(item.Key) == "" {+ t.Run(kind, func(t *testing.T) { t.Skip("no key") })+ continue+ }+ for _, driver := range []string{"local", "native", "docker"} {+ t.Run(kind+"/"+driver, func(t *testing.T) {+ runLiveSOP(t, root, kind, driver, item)+ })+ }+ }+}++func runLiveSOP(t *testing.T, root, kind, driver string, item liveCLIConfig) {+ t.Helper()+ binary := AgentCLIBinary(kind)+ if kind == "claude-code" {+ binary = "claude"+ }+ bin, err := exec.LookPath(binary)+ if err != nil {+ t.Fatalf("CLI 不在镜像 PATH 中: %v", err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), liveTimeout())+ defer cancel()+ id := "live-" + strings.ReplaceAll(kind, "/", "-") + "-" + driver+ mgr := NewManager(filepath.Join(root, "sop"))+ _ = mgr.DestroyRun(id)+ profile := domain.SandboxProfile{Driver: driver}+ var resources SandboxResources+ if driver == "docker" {+ resources.Dockerfile = domain.DockerfileDefinition{ID: "isolated", Content: IsolatedDockerfile}+ }+ creds := liveRunCredentials(kind, item)+ sb, err := mgr.AcquireRun(ctx, id, profile, SandboxRequirements{}, creds, resources)+ if err != nil {+ t.Fatalf("打开沙箱: %v", err)+ }+ defer func() {+ _ = sb.Close(context.Background())+ _ = mgr.DestroyRun(id)+ }()+ workspace := sb.Workspace()+ agentRoot := ".agentflow/test"+ if err := os.MkdirAll(filepath.Join(workspace, agentRoot), 0o700); err != nil {+ t.Fatal(err)+ }+ system := "Reply with exactly the single word pong. Do not use tools."+ if err := os.WriteFile(filepath.Join(workspace, agentRoot, "agent-system.md"), []byte(system), 0o600); err != nil {+ t.Fatal(err)+ }+ resolved, _ := domain.ResolveSandboxDriver(driver, "linux")+ ex := domain.ExecutorDefinition{Kind: kind, Binary: bin, Model: item.Model, Args: liveExecutorArgs(kind)}+ command, err := providerForKind(kind).Prepare(providerInvocation{+ Executor: ex,+ Compiled: compiledConfig{AgentRoot: agentRoot, AgentID: "live", SystemPrompt: system},+ Prompt: "Reply with exactly the single word pong.",+ Driver: resolved,+ })+ if err != nil {+ t.Fatalf("准备命令: %v", err)+ }+ // Exec 自己绑定凭证。这里再绑一次会把已经包进 sh -c 的 DeepSeek+ // 参数再次拆开,--patch 会变成 $0。+ out, err := sb.Exec(ctx, command, nil)+ out = redactLive(out)+ if err != nil {+ shown := command.Argv+ if bound, berr := bindCommand(sb, workspace, command, creds); berr == nil {+ shown = bound.Argv+ }+ t.Fatalf("执行失败: %s\nargv=%q\n%s", redactLive(err.Error()), shown, clipLive(out))+ }+ if !strings.Contains(strings.ToLower(out), "pong") {+ t.Fatalf("回复里没有 pong\n%s", clipLive(out))+ }+ t.Logf("ok %s", clipLive(out))+}++func liveRunCredentials(kind string, item liveCLIConfig) RunCredentials {+ cred := ProviderCredential{APIKey: item.Key, BaseURL: item.BaseURL, Protocol: item.Protocol}+ creds := RunCredentials{AgentCLI: map[string]ProviderCredential{}}+ switch kind {+ case "codebuddy":+ creds.CodeBuddy = CodeBuddyCredential{APIKey: item.Key, InternetEnvironment: item.Environment}+ case "codex":+ creds.Codex = cred+ case "claude-code":+ creds.ClaudeCode = cred+ default:+ creds.AgentCLI[kind] = cred+ }+ return creds+}diff --git a/internal/runtime/command_binding.go b/internal/runtime/command_binding.goindex 01581b74..1cb39399 100644--- a/internal/runtime/command_binding.go+++ b/internal/runtime/command_binding.go@@ -98,6 +98,26 @@ func bindCommand(sandbox Sandbox, workspace string, command CommandSpec, credentbaseURL = "https://api.anthropic.com"}bound.environment["ANTHROPIC_BASE_URL"] = baseURL+ case BindAgentCLI:+ home, homeEnv := privateHomePaths(sandbox, workspace, command)+ if !command.PrivateHome {+ home = command.environment["HOME"]+ homeEnv = home+ }+ if strings.TrimSpace(home) == "" {+ return CommandSpec{}, fmt.Errorf("%s 需要独立的 HOME 目录", AgentCLILabel(command.Provider))+ }+ argv, env, err := ApplyAgentCLICredential(command.Provider, credentials.AgentCLI[command.Provider], command.AgentCLI, home, homeEnv, bound.Argv)+ if err != nil {+ return CommandSpec{}, err+ }+ bound.Argv = argv+ for _, key := range agentCLIHostEnv {+ bound.environment[key] = ""+ }+ for key, value := range env {+ bound.environment[key] = value+ }default:return CommandSpec{}, fmt.Errorf("unsupported credential binding %q", binding)}@@ -118,10 +138,7 @@ func bindCommand(sandbox Sandbox, workspace string, command CommandSpec, credentbound.environment["OTEL_RESOURCE_ATTRIBUTES"] = fmt.Sprintf("agentflow.run_id=%s,agentflow.node_id=%s,service.name=agentflow-codebuddy", runID, nodeID)}if command.PrivateHome {- provider := safeID(command.Provider)- if provider == "" {- provider = "process"- }+ provider := PrivateHomeName(command)hostHome := filepath.Join(workspace, ".agentflow", "private-home", provider)hostTmp := filepath.Join(workspace, ".agentflow", "tmp", provider)if err := os.MkdirAll(hostHome, 0o700); err != nil {@@ -151,6 +168,69 @@ func bindCommand(sandbox Sandbox, workspace string, command CommandSpec, credentreturn bound, nil}+// PrivateHomeName is the directory under .agentflow/private-home that a+// PrivateHome command runs with as HOME.+func PrivateHomeName(command CommandSpec) string {+ name := safeID(command.PrivateHomeKey)+ if name == "" {+ name = safeID(command.Provider)+ }+ if name == "" {+ name = "process"+ }+ return name+}++// AgentCLIPrivateHomeKey is the PrivateHomeKey of an agent CLI invocation:+// one HOME per CLI and Agent, so concurrent Agents keep their own MCP+// configuration and sessions.+func AgentCLIPrivateHomeKey(kind, agentID string) string {+ return safeID(kind + "-" + agentID)+}++// BindAgentCLICommand is the runner-side BindAgentCLI: it renders the agent+// CLI's configuration into the command's private HOME and returns argv with+// the environment (HOME and TMPDIR included) to run it with. Agent CLIs always+// run in that HOME, sandboxed or not, because their MCP configuration is there.+func BindAgentCLICommand(sandbox Sandbox, workspace string, command CommandSpec, cred ProviderCredential, argv []string) ([]string, map[string]string, error) {+ name := PrivateHomeName(command)+ home, homeEnv := privateHomePaths(sandbox, workspace, command)+ tmp := filepath.Join(workspace, ".agentflow", "tmp", name)+ for _, dir := range []string{home, tmp} {+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return nil, nil, fmt.Errorf("create private home: %w", err)+ }+ }+ argv, bound, err := ApplyAgentCLICredential(command.Provider, cred, command.AgentCLI, home, homeEnv, argv)+ if err != nil {+ return nil, nil, err+ }+ env := map[string]string{}+ for _, key := range agentCLIHostEnv {+ env[key] = ""+ }+ for key, value := range bound {+ env[key] = value+ }+ env["HOME"] = homeEnv+ env["TMPDIR"] = tmp+ if sandboxDriver(sandbox) == "docker" {+ env["TMPDIR"] = filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "tmp", name))+ }+ return argv, env, nil+}++// privateHomePaths returns a PrivateHome command's HOME on the host and as+// the process sees it.+func privateHomePaths(sandbox Sandbox, workspace string, command CommandSpec) (host, env string) {+ name := PrivateHomeName(command)+ host = filepath.Join(workspace, ".agentflow", "private-home", name)+ if sandboxDriver(sandbox) == "docker" {+ return host, filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "private-home", name))+ }+ return host, host+}+// GitEnvironment is the git environment a child process needs to reach// private remotes with token without the token touching any git config.func GitEnvironment(sandbox Sandbox, workspace, token string) (map[string]string, error) {diff --git a/internal/runtime/core_cases_test.go b/internal/runtime/core_cases_test.goindex 40f24098..84d21929 100644--- a/internal/runtime/core_cases_test.go+++ b/internal/runtime/core_cases_test.go@@ -87,7 +87,7 @@ func TestProtocolAdaptersCoverNativeFrames(t *testing.T) {func TestProtocolHelpersAndMetadata(t *testing.T) {spec := ObservabilitySpec()- if spec.Version == "" || len(spec.Adapters) != 3 {+ if spec.Version == "" || len(spec.Adapters) != 4 {t.Fatalf("spec=%+v", spec)}metrics := usageMetrics(domain.TokenUsage{InputTokens: 1, OutputTokens: 2, CacheReadTokens: 3, CacheWriteTokens: 4, ReasoningTokens: 5, CostUSD: 1.25})diff --git a/internal/runtime/cursor_models.go b/internal/runtime/cursor_models.gonew file mode 100644index 00000000..c8804a2f--- /dev/null+++ b/internal/runtime/cursor_models.go@@ -0,0 +1,166 @@+package runtime++import (+ "slices"++ "agentflow/internal/domain"+)++// CursorModel is one model family of cursor-agent. The CLI has no effort+// flag; every reasoning effort is its own model ID, so the family picks the+// ID for the chosen effort.+type CursorModel struct {+ ID, Name string+ // Default is the effort cursor-agent presents as the plain model; empty+ // for a model without effort variants.+ Default string+ // Variants maps an effort to the cursor-agent model ID; the only key of+ // a model without effort variants is "".+ Variants map[string]string+}++// cursorModels mirrors `cursor-agent models` (2026.11). Fast variants are+// families of their own: speed is not a reasoning effort.+var cursorModels = []CursorModel{+ {ID: "auto", Name: "Auto", Default: "", Variants: map[string]string{"": "auto"}},+ {ID: "composer-2.5", Name: "Composer 2.5", Default: "", Variants: map[string]string{"": "composer-2.5"}},+ {ID: "composer-2.5-fast", Name: "Composer 2.5 Fast", Default: "", Variants: map[string]string{"": "composer-2.5-fast"}},+ {ID: "grok-4.7", Name: "Grok 4.7", Default: "medium", Variants: map[string]string{"low": "grok-4.7-low", "medium": "grok-4.7-medium", "high": "grok-4.7-high", "xhigh": "grok-4.7-xhigh"}},+ {ID: "grok-4.7-fast", Name: "Grok 4.7 Fast", Default: "medium", Variants: map[string]string{"low": "grok-4.7-low-fast", "medium": "grok-4.7-medium-fast", "high": "grok-4.7-high-fast", "xhigh": "grok-4.7-xhigh-fast"}},+ {ID: "cursor-grok-4.6", Name: "Grok 4.6", Default: "high", Variants: map[string]string{"low": "cursor-grok-4.6-low", "medium": "cursor-grok-4.6-medium", "high": "cursor-grok-4.6-high", "xhigh": "cursor-grok-4.6-xhigh"}},+ {ID: "cursor-grok-4.6-fast", Name: "Grok 4.6 Fast", Default: "high", Variants: map[string]string{"low": "cursor-grok-4.6-low-fast", "medium": "cursor-grok-4.6-medium-fast", "high": "cursor-grok-4.6-high-fast", "xhigh": "cursor-grok-4.6-xhigh-fast"}},+ {ID: "cursor-grok-4.5", Name: "Grok 4.5", Default: "high", Variants: map[string]string{"low": "cursor-grok-4.5-low", "medium": "cursor-grok-4.5-medium", "high": "cursor-grok-4.5-high"}},+ {ID: "cursor-grok-4.5-fast", Name: "Grok 4.5 Fast", Default: "high", Variants: map[string]string{"low": "cursor-grok-4.5-low-fast", "medium": "cursor-grok-4.5-medium-fast", "high": "cursor-grok-4.5-high-fast"}},+ {ID: "claude-fable-5-1", Name: "Claude Fable 5.1 (NO ZDR)", Default: "high", Variants: map[string]string{"low": "claude-fable-5-1-low", "medium": "claude-fable-5-1-medium", "high": "claude-fable-5-1-high", "xhigh": "claude-fable-5-1-xhigh", "max": "claude-fable-5-1-max"}},+ {ID: "claude-fable-5-1-thinking", Name: "Claude Fable 5.1 Thinking (NO ZDR)", Default: "high", Variants: map[string]string{"low": "claude-fable-5-1-thinking-low", "medium": "claude-fable-5-1-thinking-medium", "high": "claude-fable-5-1-thinking-high", "xhigh": "claude-fable-5-1-thinking-xhigh", "max": "claude-fable-5-1-thinking-max"}},+ {ID: "claude-fable-5", Name: "Claude Fable 5 (NO ZDR)", Default: "high", Variants: map[string]string{"low": "claude-fable-5-low", "medium": "claude-fable-5-medium", "high": "claude-fable-5-high", "xhigh": "claude-fable-5-xhigh", "max": "claude-fable-5-max"}},+ {ID: "claude-fable-5-thinking", Name: "Claude Fable 5 Thinking (NO ZDR)", Default: "high", Variants: map[string]string{"low": "claude-fable-5-thinking-low", "medium": "claude-fable-5-thinking-medium", "high": "claude-fable-5-thinking-high", "xhigh": "claude-fable-5-thinking-xhigh", "max": "claude-fable-5-thinking-max"}},+ {ID: "claude-opus-5-5", Name: "Claude Opus 5.5", Default: "medium", Variants: map[string]string{"low": "claude-opus-5-5-low", "medium": "claude-opus-5-5-medium", "high": "claude-opus-5-5-high", "xhigh": "claude-opus-5-5-xhigh", "max": "claude-opus-5-5-max"}},+ {ID: "claude-opus-5-5-fast", Name: "Claude Opus 5.5 Fast", Default: "medium", Variants: map[string]string{"low": "claude-opus-5-5-low-fast", "medium": "claude-opus-5-5-medium-fast", "high": "claude-opus-5-5-high-fast", "xhigh": "claude-opus-5-5-xhigh-fast", "max": "claude-opus-5-5-max-fast"}},+ {ID: "claude-opus-5", Name: "Claude Opus 5", Default: "high", Variants: map[string]string{"low": "claude-opus-5-low", "medium": "claude-opus-5-medium", "high": "claude-opus-5-high"}},+ {ID: "claude-opus-5-thinking", Name: "Claude Opus 5 Thinking", Default: "high", Variants: map[string]string{"low": "claude-opus-5-thinking-low", "medium": "claude-opus-5-thinking-medium", "high": "claude-opus-5-thinking-high", "xhigh": "claude-opus-5-thinking-xhigh", "max": "claude-opus-5-thinking-max"}},+ {ID: "claude-opus-5-fast", Name: "Claude Opus 5 Fast", Default: "high", Variants: map[string]string{"low": "claude-opus-5-low-fast", "medium": "claude-opus-5-medium-fast", "high": "claude-opus-5-high-fast"}},+ {ID: "claude-opus-5-thinking-fast", Name: "Claude Opus 5 Thinking Fast", Default: "high", Variants: map[string]string{"low": "claude-opus-5-thinking-low-fast", "medium": "claude-opus-5-thinking-medium-fast", "high": "claude-opus-5-thinking-high-fast", "xhigh": "claude-opus-5-thinking-xhigh-fast", "max": "claude-opus-5-thinking-max-fast"}},+ {ID: "claude-opus-4-8", Name: "Claude Opus 4.8", Default: "high", Variants: map[string]string{"low": "claude-opus-4-8-low", "medium": "claude-opus-4-8-medium", "high": "claude-opus-4-8-high", "xhigh": "claude-opus-4-8-xhigh", "max": "claude-opus-4-8-max"}},+ {ID: "claude-opus-4-8-thinking", Name: "Claude Opus 4.8 Thinking", Default: "high", Variants: map[string]string{"low": "claude-opus-4-8-thinking-low", "medium": "claude-opus-4-8-thinking-medium", "high": "claude-opus-4-8-thinking-high", "xhigh": "claude-opus-4-8-thinking-xhigh", "max": "claude-opus-4-8-thinking-max"}},+ {ID: "claude-opus-4-8-fast", Name: "Claude Opus 4.8 Fast", Default: "high", Variants: map[string]string{"low": "claude-opus-4-8-low-fast", "medium": "claude-opus-4-8-medium-fast", "high": "claude-opus-4-8-high-fast", "xhigh": "claude-opus-4-8-xhigh-fast", "max": "claude-opus-4-8-max-fast"}},+ {ID: "claude-opus-4-8-thinking-fast", Name: "Claude Opus 4.8 Thinking Fast", Default: "high", Variants: map[string]string{"low": "claude-opus-4-8-thinking-low-fast", "medium": "claude-opus-4-8-thinking-medium-fast", "high": "claude-opus-4-8-thinking-high-fast", "xhigh": "claude-opus-4-8-thinking-xhigh-fast", "max": "claude-opus-4-8-thinking-max-fast"}},+ {ID: "claude-opus-4-7", Name: "Claude Opus 4.7", Default: "xhigh", Variants: map[string]string{"low": "claude-opus-4-7-low", "medium": "claude-opus-4-7-medium", "high": "claude-opus-4-7-high", "xhigh": "claude-opus-4-7-xhigh", "max": "claude-opus-4-7-max"}},+ {ID: "claude-opus-4-7-thinking", Name: "Claude Opus 4.7 Thinking", Default: "xhigh", Variants: map[string]string{"low": "claude-opus-4-7-thinking-low", "medium": "claude-opus-4-7-thinking-medium", "high": "claude-opus-4-7-thinking-high", "xhigh": "claude-opus-4-7-thinking-xhigh", "max": "claude-opus-4-7-thinking-max"}},+ {ID: "claude-opus-4-7-fast", Name: "Claude Opus 4.7 Fast", Default: "xhigh", Variants: map[string]string{"low": "claude-opus-4-7-low-fast", "medium": "claude-opus-4-7-medium-fast", "high": "claude-opus-4-7-high-fast", "xhigh": "claude-opus-4-7-xhigh-fast", "max": "claude-opus-4-7-max-fast"}},+ {ID: "claude-opus-4-7-thinking-fast", Name: "Claude Opus 4.7 Thinking Fast", Default: "xhigh", Variants: map[string]string{"low": "claude-opus-4-7-thinking-low-fast", "medium": "claude-opus-4-7-thinking-medium-fast", "high": "claude-opus-4-7-thinking-high-fast", "xhigh": "claude-opus-4-7-thinking-xhigh-fast", "max": "claude-opus-4-7-thinking-max-fast"}},+ {ID: "claude-4.6-opus", Name: "Claude Opus 4.6", Default: "high", Variants: map[string]string{"high": "claude-4.6-opus-high", "max": "claude-4.6-opus-max"}},+ {ID: "claude-4.6-opus-thinking", Name: "Claude Opus 4.6 Thinking", Default: "high", Variants: map[string]string{"high": "claude-4.6-opus-high-thinking", "max": "claude-4.6-opus-max-thinking"}},+ {ID: "claude-4.5-opus", Name: "Claude Opus 4.5", Default: "high", Variants: map[string]string{"high": "claude-4.5-opus-high"}},+ {ID: "claude-4.5-opus-thinking", Name: "Claude Opus 4.5 Thinking", Default: "high", Variants: map[string]string{"high": "claude-4.5-opus-high-thinking"}},+ {ID: "claude-sonnet-5-5", Name: "Claude Sonnet 5.5", Default: "medium", Variants: map[string]string{"low": "claude-sonnet-5-5-low", "medium": "claude-sonnet-5-5-medium", "high": "claude-sonnet-5-5-high", "xhigh": "claude-sonnet-5-5-xhigh", "max": "claude-sonnet-5-5-max"}},+ {ID: "claude-sonnet-5", Name: "Claude Sonnet 5", Default: "high", Variants: map[string]string{"low": "claude-sonnet-5-low", "medium": "claude-sonnet-5-medium", "high": "claude-sonnet-5-high", "xhigh": "claude-sonnet-5-xhigh", "max": "claude-sonnet-5-max"}},+ {ID: "claude-sonnet-5-thinking", Name: "Claude Sonnet 5 Thinking", Default: "high", Variants: map[string]string{"low": "claude-sonnet-5-thinking-low", "medium": "claude-sonnet-5-thinking-medium", "high": "claude-sonnet-5-thinking-high", "xhigh": "claude-sonnet-5-thinking-xhigh", "max": "claude-sonnet-5-thinking-max"}},+ {ID: "claude-4.6-sonnet", Name: "Claude Sonnet 4.6", Default: "medium", Variants: map[string]string{"medium": "claude-4.6-sonnet-medium"}},+ {ID: "claude-4.6-sonnet-thinking", Name: "Claude Sonnet 4.6 Thinking", Default: "medium", Variants: map[string]string{"medium": "claude-4.6-sonnet-medium-thinking"}},+ {ID: "claude-4.5-sonnet", Name: "Claude Sonnet 4.5", Default: "", Variants: map[string]string{"": "claude-4.5-sonnet"}},+ {ID: "claude-4.5-sonnet-thinking", Name: "Claude Sonnet 4.5 Thinking", Default: "", Variants: map[string]string{"": "claude-4.5-sonnet-thinking"}},+ {ID: "claude-4-sonnet", Name: "Claude Sonnet 4", Default: "", Variants: map[string]string{"": "claude-4-sonnet"}},+ {ID: "claude-4-sonnet-thinking", Name: "Claude Sonnet 4 Thinking", Default: "", Variants: map[string]string{"": "claude-4-sonnet-thinking"}},+ {ID: "claude-haiku-5-5", Name: "Claude Haiku 5.5", Default: "medium", Variants: map[string]string{"low": "claude-haiku-5-5-low", "medium": "claude-haiku-5-5-medium", "high": "claude-haiku-5-5-high", "xhigh": "claude-haiku-5-5-xhigh", "max": "claude-haiku-5-5-max"}},+ {ID: "claude-haiku-5-5-thinking", Name: "Claude Haiku 5.5 Thinking", Default: "medium", Variants: map[string]string{"low": "claude-haiku-5-5-thinking-low", "medium": "claude-haiku-5-5-thinking-medium", "high": "claude-haiku-5-5-thinking-high", "xhigh": "claude-haiku-5-5-thinking-xhigh", "max": "claude-haiku-5-5-thinking-max"}},+ {ID: "gpt-5.6-sol", Name: "GPT-5.6 Sol", Default: "medium", Variants: map[string]string{"none": "gpt-5.6-sol-none", "low": "gpt-5.6-sol-low", "medium": "gpt-5.6-sol-medium", "high": "gpt-5.6-sol-high", "xhigh": "gpt-5.6-sol-xhigh", "max": "gpt-5.6-sol-max"}},+ {ID: "gpt-5.6-sol-fast", Name: "GPT-5.6 Sol Fast", Default: "medium", Variants: map[string]string{"none": "gpt-5.6-sol-none-fast", "low": "gpt-5.6-sol-low-fast", "medium": "gpt-5.6-sol-medium-fast", "high": "gpt-5.6-sol-high-fast", "xhigh": "gpt-5.6-sol-xhigh-fast", "max": "gpt-5.6-sol-max-fast"}},+ {ID: "gpt-5.6-terra", Name: "GPT-5.6 Terra", Default: "medium", Variants: map[string]string{"none": "gpt-5.6-terra-none", "low": "gpt-5.6-terra-low", "medium": "gpt-5.6-terra-medium", "high": "gpt-5.6-terra-high", "xhigh": "gpt-5.6-terra-xhigh", "max": "gpt-5.6-terra-max"}},+ {ID: "gpt-5.6-terra-fast", Name: "GPT-5.6 Terra Fast", Default: "medium", Variants: map[string]string{"none": "gpt-5.6-terra-none-fast", "low": "gpt-5.6-terra-low-fast", "medium": "gpt-5.6-terra-medium-fast", "high": "gpt-5.6-terra-high-fast", "xhigh": "gpt-5.6-terra-xhigh-fast", "max": "gpt-5.6-terra-max-fast"}},+ {ID: "gpt-5.6-luna", Name: "GPT-5.6 Luna", Default: "medium", Variants: map[string]string{"none": "gpt-5.6-luna-none", "low": "gpt-5.6-luna-low", "medium": "gpt-5.6-luna-medium", "high": "gpt-5.6-luna-high", "xhigh": "gpt-5.6-luna-xhigh", "max": "gpt-5.6-luna-max"}},+ {ID: "gpt-5.6-luna-fast", Name: "GPT-5.6 Luna Fast", Default: "medium", Variants: map[string]string{"none": "gpt-5.6-luna-none-fast", "low": "gpt-5.6-luna-low-fast", "medium": "gpt-5.6-luna-medium-fast", "high": "gpt-5.6-luna-high-fast", "xhigh": "gpt-5.6-luna-xhigh-fast", "max": "gpt-5.6-luna-max-fast"}},+ {ID: "gpt-5.5", Name: "GPT-5.5", Default: "medium", Variants: map[string]string{"none": "gpt-5.5-none", "low": "gpt-5.5-low", "medium": "gpt-5.5-medium", "high": "gpt-5.5-high", "xhigh": "gpt-5.5-extra-high"}},+ {ID: "gpt-5.5-fast", Name: "GPT-5.5 Fast", Default: "medium", Variants: map[string]string{"none": "gpt-5.5-none-fast", "low": "gpt-5.5-low-fast", "medium": "gpt-5.5-medium-fast", "high": "gpt-5.5-high-fast", "xhigh": "gpt-5.5-extra-high-fast"}},+ {ID: "gpt-5.4", Name: "GPT-5.4", Default: "medium", Variants: map[string]string{"low": "gpt-5.4-low", "medium": "gpt-5.4-medium", "high": "gpt-5.4-high", "xhigh": "gpt-5.4-xhigh"}},+ {ID: "gpt-5.4-fast", Name: "GPT-5.4 Fast", Default: "medium", Variants: map[string]string{"medium": "gpt-5.4-medium-fast", "high": "gpt-5.4-high-fast", "xhigh": "gpt-5.4-xhigh-fast"}},+ {ID: "gpt-5.4-mini", Name: "GPT-5.4 Mini", Default: "medium", Variants: map[string]string{"none": "gpt-5.4-mini-none", "low": "gpt-5.4-mini-low", "medium": "gpt-5.4-mini-medium", "high": "gpt-5.4-mini-high", "xhigh": "gpt-5.4-mini-xhigh"}},+ {ID: "gpt-5.4-nano", Name: "GPT-5.4 Nano", Default: "medium", Variants: map[string]string{"none": "gpt-5.4-nano-none", "low": "gpt-5.4-nano-low", "medium": "gpt-5.4-nano-medium", "high": "gpt-5.4-nano-high", "xhigh": "gpt-5.4-nano-xhigh"}},+ {ID: "gpt-5.3-codex", Name: "Codex 5.3", Default: "medium", Variants: map[string]string{"low": "gpt-5.3-codex-low", "medium": "gpt-5.3-codex", "high": "gpt-5.3-codex-high", "xhigh": "gpt-5.3-codex-xhigh"}},+ {ID: "gpt-5.3-codex-fast", Name: "Codex 5.3 Fast", Default: "medium", Variants: map[string]string{"low": "gpt-5.3-codex-low-fast", "medium": "gpt-5.3-codex-fast", "high": "gpt-5.3-codex-high-fast", "xhigh": "gpt-5.3-codex-xhigh-fast"}},+ {ID: "gpt-5.2", Name: "GPT-5.2", Default: "medium", Variants: map[string]string{"low": "gpt-5.2-low", "medium": "gpt-5.2", "high": "gpt-5.2-high", "xhigh": "gpt-5.2-xhigh"}},+ {ID: "gpt-5.2-fast", Name: "GPT-5.2 Fast", Default: "medium", Variants: map[string]string{"low": "gpt-5.2-low-fast", "medium": "gpt-5.2-fast", "high": "gpt-5.2-high-fast", "xhigh": "gpt-5.2-xhigh-fast"}},+ {ID: "gpt-5.1", Name: "GPT-5.1", Default: "medium", Variants: map[string]string{"low": "gpt-5.1-low", "medium": "gpt-5.1", "high": "gpt-5.1-high"}},+ {ID: "gpt-5-mini", Name: "GPT-5 Mini", Default: "", Variants: map[string]string{"": "gpt-5-mini"}},+ {ID: "gemini-4-argon", Name: "Gemini 4 Argon", Default: "medium", Variants: map[string]string{"low": "gemini-4-argon-low", "medium": "gemini-4-argon-medium", "high": "gemini-4-argon-high"}},+ {ID: "gemini-3.8-flash", Name: "Gemini 3.8 Flash", Default: "medium", Variants: map[string]string{"low": "gemini-3.8-flash-low", "medium": "gemini-3.8-flash-medium", "high": "gemini-3.8-flash-high"}},+ {ID: "gemini-3.7-flash", Name: "Gemini 3.7 Flash", Default: "high", Variants: map[string]string{"low": "gemini-3.7-flash-low", "medium": "gemini-3.7-flash-medium", "high": "gemini-3.7-flash-high"}},+ {ID: "gemini-3.6-flash", Name: "Gemini 3.6 Flash", Default: "high", Variants: map[string]string{"minimal": "gemini-3.6-flash-minimal", "low": "gemini-3.6-flash-low", "medium": "gemini-3.6-flash-medium", "high": "gemini-3.6-flash-high"}},+ {ID: "gemini-3.5-flash", Name: "Gemini 3.5 Flash", Default: "", Variants: map[string]string{"": "gemini-3.5-flash"}},+ {ID: "gemini-3.1-pro", Name: "Gemini 3.1 Pro", Default: "", Variants: map[string]string{"": "gemini-3.1-pro"}},+ {ID: "gemini-3-flash", Name: "Gemini 3 Flash", Default: "", Variants: map[string]string{"": "gemini-3-flash"}},+ {ID: "kimi-k3", Name: "Kimi K3", Default: "max", Variants: map[string]string{"low": "kimi-k3-low", "high": "kimi-k3-high", "max": "kimi-k3-max"}},+ {ID: "kimi-k2.7-code", Name: "Kimi K2.7 Code", Default: "", Variants: map[string]string{"": "kimi-k2.7-code"}},+ {ID: "deepseek-v41-flash-1017", Name: "DeepSeek V4.1 Flash 1017", Default: "medium", Variants: map[string]string{"none": "deepseek-v41-flash-1017-none", "low": "deepseek-v41-flash-1017-low", "medium": "deepseek-v41-flash-1017-medium", "high": "deepseek-v41-flash-1017-high", "max": "deepseek-v41-flash-1017-max"}},+ {ID: "glm-5.2", Name: "GLM 5.2", Default: "high", Variants: map[string]string{"high": "glm-5.2-high", "max": "glm-5.2-max"}},+ {ID: "muse-spark-1.3", Name: "Muse Spark 1.3", Default: "high", Variants: map[string]string{"minimal": "muse-spark-1.3-minimal", "low": "muse-spark-1.3-low", "medium": "muse-spark-1.3-medium", "high": "muse-spark-1.3-high", "xhigh": "muse-spark-1.3-xhigh", "max": "muse-spark-1.3-max"}},+ {ID: "muse-wonder-1.0", Name: "Muse Wonder", Default: "medium", Variants: map[string]string{"minimal": "muse-wonder-1.0-minimal", "low": "muse-wonder-1.0-low", "medium": "muse-wonder-1.0-medium", "high": "muse-wonder-1.0-high", "xhigh": "muse-wonder-1.0-xhigh", "max": "muse-wonder-1.0-max"}},+}++var cursorModelByID, cursorModelByVariant = func() (map[string]CursorModel, map[string]CursorModel) {+ byID, byVariant := map[string]CursorModel{}, map[string]CursorModel{}+ for _, model := range cursorModels {+ byID[model.ID] = model+ for _, id := range model.Variants {+ byVariant[id] = model+ }+ }+ return byID, byVariant+}()++// CursorModels is the built-in family table, in display order.+func CursorModels() []CursorModel { return slices.Clone(cursorModels) }++// CursorModelFamily finds the family a cursor-agent model ID belongs to.+func CursorModelFamily(id string) (CursorModel, bool) {+ model, ok := cursorModelByVariant[id]+ return model, ok+}++// CursorModelEfforts lists the efforts of a family, weakest first; nil for+// a model ID outside the table or without effort variants.+func CursorModelEfforts(id string) []string {+ var out []string+ for _, effort := range domain.ExecutorEffortLevels[AgentCLICursor] {+ if _, ok := cursorModelByID[id].Variants[effort]; ok {+ out = append(out, effort)+ }+ }+ return out+}++// CursorModelID resolves a family and effort to the cursor-agent model ID.+// An empty effort takes the family default and an effort the family lacks+// the closest one (the stronger on a tie); IDs outside the table, including+// raw cursor-agent IDs, pass through.+func CursorModelID(id, effort string) string {+ model, ok := cursorModelByID[id]+ if !ok {+ return id+ }+ if raw, ok := model.Variants[""]; ok {+ return raw+ }+ if raw, ok := model.Variants[effort]; ok {+ return raw+ }+ levels := domain.ExecutorEffortLevels[AgentCLICursor]+ want := slices.Index(levels, effort)+ if want < 0 {+ return model.Variants[model.Default]+ }+ best, distance := model.Default, len(levels)+ for i, level := range levels {+ if _, ok := model.Variants[level]; ok && abs(i-want) <= distance {+ best, distance = level, abs(i-want)+ }+ }+ return model.Variants[best]+}++func abs(n int) int {+ if n < 0 {+ return -n+ }+ return n+}diff --git a/internal/runtime/cursor_models_test.go b/internal/runtime/cursor_models_test.gonew file mode 100644index 00000000..8bde0a2a--- /dev/null+++ b/internal/runtime/cursor_models_test.go@@ -0,0 +1,67 @@+package runtime++import (+ "slices"+ "testing"++ "agentflow/internal/domain"+)++func TestCursorModelTable(t *testing.T) {+ levels := domain.ExecutorEffortLevels[AgentCLICursor]+ ids, raws := map[string]bool{}, map[string]bool{}+ for _, model := range cursorModels {+ if ids[model.ID] || model.Name == "" {+ t.Fatalf("duplicate or unnamed family %+v", model)+ }+ ids[model.ID] = true+ for effort, raw := range model.Variants {+ if (effort != "" && !slices.Contains(levels, effort)) || raws[raw] {+ t.Fatalf("%s: bad variant %q=%q", model.ID, effort, raw)+ }+ raws[raw] = true+ }+ if _, ok := model.Variants[model.Default]; !ok || (model.Default == "") != (len(model.Variants) == 1 && model.Variants[""] != "") {+ t.Fatalf("%s: default %q outside %v", model.ID, model.Default, model.Variants)+ }+ }+}++func TestCursorModelID(t *testing.T) {+ cases := []struct{ id, effort, want string }{+ {"cursor-grok-4.6", "", "cursor-grok-4.6-high"},+ {"cursor-grok-4.6", "low", "cursor-grok-4.6-low"},+ {"gpt-5.5", "xhigh", "gpt-5.5-extra-high"},+ {"gpt-5.3-codex", "medium", "gpt-5.3-codex"},+ {"gpt-5.6-sol-fast", "none", "gpt-5.6-sol-none-fast"},+ {"claude-4.6-opus-thinking", "max", "claude-4.6-opus-max-thinking"},+ {"claude-opus-5-5", "", "claude-opus-5-5-medium"},+ // Missing efforts take the closest one, the stronger on a tie.+ {"kimi-k3", "medium", "kimi-k3-high"},+ {"glm-5.2", "none", "glm-5.2-high"},+ {"gemini-4-argon", "max", "gemini-4-argon-high"},+ {"composer-2.5", "high", "composer-2.5"},+ {"auto", "", "auto"},+ // Raw IDs and unknown models pass through.+ {"claude-opus-5-high", "low", "claude-opus-5-high"},+ {"some-new-model", "high", "some-new-model"},+ }+ for _, c := range cases {+ if got := CursorModelID(c.id, c.effort); got != c.want {+ t.Errorf("CursorModelID(%q, %q) = %q, want %q", c.id, c.effort, got, c.want)+ }+ }+ if got := CursorModelEfforts("kimi-k3"); !slices.Equal(got, []string{"low", "high", "max"}) {+ t.Errorf("kimi-k3 efforts: %v", got)+ }+ if got := CursorModelEfforts("composer-2.5"); got != nil {+ t.Errorf("composer efforts: %v", got)+ }+ if family, ok := CursorModelFamily("gpt-5.6-terra-xhigh-fast"); !ok || family.ID != "gpt-5.6-terra-fast" {+ t.Errorf("family of a fast variant: %+v %v", family, ok)+ }+ argv := AgentCLICommand(AgentCLICursor, AgentCLICommandOptions{Model: "claude-opus-4-8-thinking", Effort: "xhigh", Prompt: "p"}).Argv+ if i := slices.Index(argv, "--model"); i < 0 || argv[i+1] != "claude-opus-4-8-thinking-xhigh" {+ t.Errorf("cursor argv: %q", argv)+ }+}diff --git a/internal/runtime/materialize.go b/internal/runtime/materialize.goindex e4beb0ef..eb007b6a 100644--- a/internal/runtime/materialize.go+++ b/internal/runtime/materialize.go@@ -21,6 +21,10 @@ type compiledConfig struct {Hooks []compiledHookHasSkills boolHasMCP bool+ AgentID string+ // SystemPrompt is the agent-system.md body for providers that send it+ // with the task.+ SystemPrompt string}func materialize(workspace, invocationID string, ex domain.ExecutorDefinition, a domain.AgentDefinition, assets domain.AgentAssetBundle) (compiledConfig, error) {@@ -49,7 +53,7 @@ func materializeInvocationForDriver(workspace, invocationID string, ex domain.Ex}agentRel := filepath.Join(".agentflow", agentID)runtimeRel := filepath.Join(".agentflow", "runtime", invocationID)- compiled := compiledConfig{AgentRoot: filepath.ToSlash(agentRel), RuntimeRoot: filepath.ToSlash(runtimeRel), HasSkills: len(assets.Skills) > 0}+ compiled := compiledConfig{AgentRoot: filepath.ToSlash(agentRel), RuntimeRoot: filepath.ToSlash(runtimeRel), HasSkills: len(assets.Skills) > 0, AgentID: agentID}// run-context.json is a debugging artifact; keep binary skill payloads// out of it (they travel with the bundle, not the workspace dump).slimAssets := assetsdiff --git a/internal/runtime/protocol.go b/internal/runtime/protocol.goindex cdd3cada..b86c4663 100644--- a/internal/runtime/protocol.go+++ b/internal/runtime/protocol.go@@ -20,6 +20,9 @@ const (protocolGeneric protocolParser = iotaprotocolAnthropicprotocolCodex+ // protocolTranslated rewrites each native line into Claude-style+ // stream-json (NewAgentCLITranslator) and parses that.+ protocolTranslated)type protocolAdapter struct {@@ -36,6 +39,7 @@ type protocolAdapter struct {once sync.Oncetools map[string]*toolUseBufcurrentToolID string+ translate func(string) []string}// ProtocolObserver normalizes process output from a remotely executed Agent@@ -117,6 +121,7 @@ func ObservabilitySpec() domain.ObservabilitySpec {Adapters: []domain.AdapterDescriptor{{ID: "anthropic-stream-v1", SpecVersion: domain.ObservabilitySpecVersion, ExecutorKinds: []string{"claude-code", "codebuddy"}, NativeProtocols: []string{"stream-json"}, Capabilities: []string{"session", "model", "reasoning", "output-delta", "tool-lifecycle", "token-usage", "cache-usage", "cost", "duration"}, RawEventPolicy: "discard-after-normalization"},{ID: "codex-jsonl-v1", SpecVersion: domain.ObservabilitySpecVersion, ExecutorKinds: []string{"codex"}, NativeProtocols: []string{"jsonl"}, Capabilities: []string{"session", "reasoning", "output", "tool-lifecycle", "token-usage", "cache-usage"}, RawEventPolicy: "discard-after-normalization"},+ {ID: "agent-cli-stream-v1", SpecVersion: domain.ObservabilitySpecVersion, ExecutorKinds: append([]string(nil), AgentCLIKinds...), NativeProtocols: []string{"stream-json", "jsonl"}, Capabilities: []string{"session", "reasoning", "output", "tool-lifecycle", "token-usage", "cache-usage"}, RawEventPolicy: "discard-after-normalization"},{ID: "generic-json-v1", SpecVersion: domain.ObservabilitySpecVersion, ExecutorKinds: []string{"custom"}, NativeProtocols: []string{"jsonl", "stream-json"}, Capabilities: []string{"lifecycle", "message", "extensible-metrics"}, RawEventPolicy: "sanitized-attributes-only"},},}@@ -179,6 +184,18 @@ func (a *protocolAdapter) Handle(event domain.TelemetryEvent) {a.emit(event)return}+ if a.parser == protocolTranslated {+ if a.translate == nil {+ a.translate = NewAgentCLITranslator(a.ex.Kind)+ }+ for _, line := range a.translate(event.Message) {+ var raw map[string]any+ if json.Unmarshal([]byte(line), &raw) == nil {+ a.handleClaudeStream(raw)+ }+ }+ return+ }var raw map[string]anyif json.Unmarshal([]byte(event.Message), &raw) != nil {a.emit(event)diff --git a/internal/runtime/provider.go b/internal/runtime/provider.goindex 3a257404..3b031276 100644--- a/internal/runtime/provider.go+++ b/internal/runtime/provider.go@@ -126,6 +126,12 @@ var providers = map[string]Provider{"mock": mockProvider{},}+func init() {+ for _, kind := range AgentCLIKinds {+ providers[kind] = newAgentCLIProvider(kind)+ }+}+func providerForKind(kind string) Provider {if provider := providers[strings.TrimSpace(kind)]; provider != nil {return providerdiff --git a/internal/runtime/provider_agentcli.go b/internal/runtime/provider_agentcli.gonew file mode 100644index 00000000..bcf2e10f--- /dev/null+++ b/internal/runtime/provider_agentcli.go@@ -0,0 +1,247 @@+package runtime++import (+ "crypto/rand"+ "encoding/hex"+ "os"+ "path/filepath"+ "strings"++ "agentflow/internal/domain"+)++// agentCLIProvider runs one of the agent CLIs (AgentCLIKinds) in its native+// headless mode. The role's MCP servers go into the CLI's own configuration+// inside a per-Agent private HOME; ApplyAgentCLICredential adds the model configuration+// and the user's key there at launch.+type agentCLIProvider struct{ baseProvider }++func newAgentCLIProvider(kind string) agentCLIProvider {+ return agentCLIProvider{baseProvider{kind: kind, parser: protocolTranslated, adapter: "agent-cli-stream-v1"}}+}++func (p agentCLIProvider) Materialize(ctx *providerMaterializeContext) error {+ entries, err := mcpConfigEntries(ctx.MCPServers)+ if err != nil {+ return err+ }+ home := filepath.Join(ctx.Workspace, ".agentflow", "private-home", AgentCLIPrivateHomeKey(p.kind, ctx.AgentID))+ if err := WriteAgentCLIMCPConfig(p.kind, home, entries, AgentCLIMCPOptions{}); err != nil {+ return err+ }+ ctx.Compiled.SystemPrompt = string(ctx.Content)+ return nil+}++// agentCLINativeSystemPrompt marks CLIs that load the system prompt file+// themselves; the others receive it ahead of the task.+func agentCLINativeSystemPrompt(kind string) bool {+ return kind == AgentCLIOpenCode || kind == AgentCLIPi+}++// AgentCLITaskPrompt prefixes the system prompt for CLIs without a system+// prompt option. An oversized prompt is referenced by path instead.+func AgentCLITaskPrompt(system, systemFile, task string) string {+ system = strings.TrimSpace(system)+ if system == "" {+ return task+ }+ if len(system)+len(task) > maxArgvPromptBytes && systemFile != "" {+ return "先完整阅读并严格遵守 `" + systemFile + "` 中的系统指令,然后完成下面的任务。\n\n" + task+ }+ return "<system_instructions>\n" + system + "\n</system_instructions>\n\n" + task+}++func newAgentCLISessionID() string {+ var b [16]byte+ _, _ = rand.Read(b[:])+ b[6] = b[6]&0x0f | 0x40+ b[8] = b[8]&0x3f | 0x80+ h := hex.EncodeToString(b[:])+ return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32]+}++func (p agentCLIProvider) Prepare(in providerInvocation) (CommandSpec, error) {+ systemFile := ""+ if in.Compiled.AgentRoot != "" {+ systemFile = filepath.ToSlash(filepath.Join(in.Compiled.AgentRoot, "agent-system.md"))+ }+ command := AgentCLICommand(p.kind, AgentCLICommandOptions{+ Binary: in.Executor.Binary, Model: in.Executor.Model, Effort: in.Executor.Effort,+ Resume: in.Options.ResumeSessionID, Prompt: positionalPrompt(in),+ SystemPrompt: in.Compiled.SystemPrompt, SystemPromptFile: systemFile, Extra: in.Executor.Args,+ })+ command.CredentialBindings = []CredentialBinding{BindAgentCLI, BindGit, BindMCP}+ command.PrivateHome = true+ command.PrivateHomeKey = AgentCLIPrivateHomeKey(p.kind, in.Compiled.AgentID)+ return command, nil+}++// AgentCLICommandOptions describes one headless agent CLI turn.+type AgentCLICommandOptions struct {+ Binary, Model, Effort string+ // Resume is the CLI's own session ID to continue; empty starts one.+ Resume string+ Prompt string+ // SystemPrompt is the system prompt body; SystemPromptFile is the same+ // text as a path the process can read.+ SystemPrompt, SystemPromptFile string+ Extra []string+ // Chat runs the CLI for AI 对话 on the control plane: MCP tools stay+ // available, shell, file writes and web access do not. The MCP+ // configuration (WriteAgentCLIMCPConfig ReadOnly) completes the policy.+ Chat bool+ // AgentFile is Kimi Code's chat agent definition (WriteKimiChatAgent).+ AgentFile string+}++// AgentCLICommand builds the argv of an agent CLI turn; the caller adds+// credential bindings and the HOME policy.+func AgentCLICommand(kind string, o AgentCLICommandOptions) CommandSpec {+ binary := strings.TrimSpace(o.Binary)+ if binary == "" {+ binary = AgentCLIBinary(kind)+ }+ model := strings.TrimSpace(o.Model)+ effort := strings.TrimSpace(o.Effort)+ resume := strings.TrimSpace(o.Resume)+ prompt := o.Prompt+ // A chat session keeps the prompt of its first turn; SOP invocations+ // are independent processes that each receive it.+ inline := !agentCLINativeSystemPrompt(kind) && !(o.Chat && kind == AgentCLIKimi)+ if inline && !(o.Chat && resume != "") {+ prompt = AgentCLITaskPrompt(o.SystemPrompt, o.SystemPromptFile, prompt)+ }+ extra := append([]string{}, o.Extra...)+ var argv []string+ options := AgentCLIOptions{Model: model, ReadOnly: o.Chat}+ switch kind {+ case AgentCLIOpenCode:+ argv = []string{binary, "run", "--format", "json", "--thinking"}+ if model != "" {+ argv = append(argv, "-m", "agentflow/"+model)+ }+ if resume != "" {+ argv = append(argv, "-s", resume)+ }+ if effort != "" {+ argv = append(argv, "--variant", effort)+ }+ options.SystemPromptFile = o.SystemPromptFile+ argv = append(append(argv, extra...), prompt)+ case AgentCLICursor:+ // Chat relies on the deny rules of .cursor/cli-config.json; --force+ // still approves the MCP tools.+ argv = []string{binary, "-p", "--output-format", "stream-json", "--stream-partial-output", "--trust", "--force", "--approve-mcps"}+ if model != "" {+ argv = append(argv, "--model", CursorModelID(model, effort))+ }+ if resume != "" {+ argv = append(argv, "--resume", resume)+ }+ argv = append(append(argv, extra...), prompt)+ case AgentCLIAntigravity:+ // Chat deny rules travel as --settings (ApplyAgentCLICredential);+ // they hold even with --dangerously-skip-permissions.+ argv = []string{binary, "--output-format", "stream-json", "--dangerously-skip-permissions", "--disable-slash-commands"}+ if model != "" && AgyModelEfforts(model) == nil {+ effort = ""+ }+ if model != "" {+ argv = append(argv, "--model", agyModelForEffort(model, effort))+ }+ if effort != "" {+ argv = append(argv, "--effort", effort)+ }+ if resume != "" {+ argv = append(argv, "--conversation", resume)+ }+ argv = append(append(argv, extra...), "-p", prompt)+ case AgentCLIKimi:+ argv = []string{binary, "--output-format", "stream-json"}+ if resume != "" {+ argv = append(argv, "-S", resume)+ } else if o.AgentFile != "" {+ // The session keeps the agent, so resumed turns cannot pass it again.+ argv = append(argv, "--agent-file", o.AgentFile)+ }+ argv = append(append(argv, extra...), "-p", prompt)+ case AgentCLIPi:+ session := resume+ if session == "" {+ session = newAgentCLISessionID()+ }+ argv = []string{binary, "--mode", "json", "--session-id", session}+ if model != "" {+ argv = append(argv, "--model", "agentflow/"+model)+ }+ if effort != "" {+ argv = append(argv, "--thinking", effort)+ }+ if o.SystemPromptFile != "" {+ argv = append(argv, "--append-system-prompt", o.SystemPromptFile)+ }+ if o.Chat {+ argv = append(argv, "--exclude-tools", "bash,edit,write")+ }+ argv = append(append(argv, extra...), prompt)+ case AgentCLIDeepSeek:+ mode := "danger-full-access"+ if o.Chat {+ mode = "read-only"+ }+ argv = []string{binary, "--profile", "headless", "--json", "--permission-mode", mode, "--approval-policy", "never"}+ if resume != "" {+ argv = append(argv, "--session-id", resume)+ }+ argv = append(append(argv, extra...), prompt)+ }+ return CommandSpec{Argv: argv, Provider: kind, AgentCLI: options}+}++// AgyModelEfforts lists the efforts agy accepts for a model, weakest first.+// Only its Gemini models take --effort; agy rejects the flag for any other+// model a Base URL serves ("--effort is not supported for model …").+func AgyModelEfforts(model string) []string {+ if strings.HasPrefix(strings.TrimSpace(model), "gemini-") {+ return domain.ExecutorEffortLevels[AgentCLIAntigravity]+ }+ return nil+}++// agyModelForEffort replaces the effort suffix of an Antigravity model ID+// (gemini-3.8-flash-medium) with the requested effort: agy rejects a model+// whose suffix differs from --effort.+func agyModelForEffort(model, effort string) string {+ if effort == "" {+ return model+ }+ for _, level := range domain.ExecutorEffortLevels[AgentCLIAntigravity] {+ if base, ok := strings.CutSuffix(model, "-"+level); ok {+ return base + "-" + effort+ }+ }+ return model+}++// kimiChatDisallowedTools are Kimi Code's tools that act outside the chat's+// MCP gateway or spawn further agents.+var kimiChatDisallowedTools = []string{"Bash", "Edit", "Write", "FetchURL", "WebSearch", "Agent", "AgentSwarm", "CronCreate", "CronDelete", "CronList", "TaskOutput", "TaskStop", "WaitFor"}++// WriteKimiChatAgent writes the Kimi Code agent definition for AI 对话: the+// system prompt as its body and the chat's tool restrictions.+func WriteKimiChatAgent(path, systemPrompt string) error {+ body := strings.TrimSpace(systemPrompt)+ if body == "" {+ body = "You are the AgentFlow assistant."+ }+ content := "---\nname: agentflow-chat\ndescription: AgentFlow AI 对话\ndisallowedTools: [" + strings.Join(kimiChatDisallowedTools, ", ") + "]\n---\n" + body + "\n"+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ return err+ }+ return os.WriteFile(path, []byte(content), 0o600)+}++func (agentCLIProvider) SandboxRequirements() SandboxRequirements {+ return SandboxRequirements{PrivateHome: true}+}diff --git a/internal/runtime/provider_claude.go b/internal/runtime/provider_claude.goindex 8f57499c..aceb80c6 100644--- a/internal/runtime/provider_claude.go+++ b/internal/runtime/provider_claude.go@@ -79,9 +79,11 @@ func (claudeProvider) Prepare(in providerInvocation) (CommandSpec, error) {argv = append(argv, "--resume", sessionID)}spec := CommandSpec{Argv: append(argv, positionalPrompt(in)), Provider: "claude-code", CredentialBindings: []CredentialBinding{BindClaudeCode, BindGit, BindMCP}, PrivateHome: true}- if in.Driver == "docker" {- // Sandbox containers run as root, where Claude Code refuses- // bypassPermissions unless told the container is the sandbox.+ if in.Driver == "docker" || in.Driver == "bwrap" || in.Driver == "seatbelt" || os.Geteuid() == 0 {+ // Claude Code refuses bypassPermissions for root unless the process+ // is told that an outer sandbox is the isolation boundary. Docker and+ // the lightweight sandboxes are that boundary; a root local process is+ // too, which is how the platform container runs.spec.environment = map[string]string{"IS_SANDBOX": "1"}}return spec, nildiff --git a/internal/runtime/provider_codex.go b/internal/runtime/provider_codex.goindex 1eaf6777..345db285 100644--- a/internal/runtime/provider_codex.go+++ b/internal/runtime/provider_codex.go@@ -30,17 +30,11 @@ func (codexProvider) Prepare(in providerInvocation) (CommandSpec, error) {if len(in.Compiled.Hooks) > 0 && !hasArg(argv, "--dangerously-bypass-hook-trust") {argv = append(argv, "--dangerously-bypass-hook-trust")}- if in.Driver == "local" {- for _, flag := range []string{"--ignore-user-config", "--ignore-rules"} {- if !hasArg(argv, flag) {- argv = append(argv, flag)- }- }- }- if in.Driver == "docker" {- // The container is the isolation boundary. Codex's own bubblewrap sandbox- // cannot create user namespaces inside it, which fails every shell command,- // file write and MCP call (including submit_gate_result).+ // A private CODEX_HOME keeps the host login and config out of the run.+ // Current Codex rejects --ignore-user-config and --ignore-rules.+ if in.Driver == "docker" || in.Driver == "bwrap" {+ // Docker and bwrap are the isolation boundary. Codex's own bubblewrap+ // sandbox cannot create another user namespace inside them.argv = withCodexSandboxMode(argv, "danger-full-access")}if sessionID := strings.TrimSpace(in.Options.ResumeSessionID); sessionID != "" {diff --git a/internal/runtime/provider_test.go b/internal/runtime/provider_test.goindex 057fc1dc..1d207650 100644--- a/internal/runtime/provider_test.go+++ b/internal/runtime/provider_test.go@@ -15,7 +15,7 @@ func TestProvidersBuildFinalArgvWithoutDuplicateManagedFlags(t *testing.T) {}{{kind: "claude-code", driver: "local", key: "--system-prompt-file"},{kind: "codebuddy", driver: "local", key: "--permission-mode"},- {kind: "codex", driver: "local", key: "--ignore-user-config"},+ {kind: "codex", driver: "docker", key: "--sandbox"},}for _, test := range tests {t.Run(test.kind, func(t *testing.T) {diff --git a/internal/runtime/remote_sandbox.go b/internal/runtime/remote_sandbox.goindex b2c471a0..3d8e2a7a 100644--- a/internal/runtime/remote_sandbox.go+++ b/internal/runtime/remote_sandbox.go@@ -4,6 +4,7 @@ import ("context""fmt""os"+ goruntime "runtime""strings""agentflow/internal/domain"@@ -16,6 +17,10 @@ func OpenRemoteSandbox(ctx context.Context, id, workspace string, profile domainif strings.TrimSpace(workspace) == "" {return nil, fmt.Errorf("runner sandbox workspace is required")}+ var err error+ if profile.Driver, err = domain.ResolveSandboxDriver(profile.Driver, goruntime.GOOS); err != nil {+ return nil, err+ }if err := os.MkdirAll(workspace, 0o700); err != nil {return nil, err}diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.goindex 88e377f1..d12cdc4d 100644--- a/internal/runtime/runtime.go+++ b/internal/runtime/runtime.go@@ -2,6 +2,8 @@ package runtimeimport ("context"+ "io"+ "os""path/filepath""strconv""strings"@@ -20,6 +22,9 @@ const (BindClaudeCode CredentialBinding = "claude-code"BindGit CredentialBinding = "git"BindMCP CredentialBinding = "mcp"+ // BindAgentCLI injects the responsible user's key for the command's agent+ // CLI and writes that CLI's model configuration into its private HOME.+ BindAgentCLI CredentialBinding = "agent-cli")type CodeBuddyCredential struct {@@ -38,6 +43,7 @@ type RunCredentials struct {CodeBuddy CodeBuddyCredentialCodex ProviderCredentialClaudeCode ProviderCredential+ AgentCLI map[string]ProviderCredentialGitToken stringGitUserName stringGitUserEmail string@@ -45,8 +51,9 @@ type RunCredentials struct {}type ProviderCredential struct {- APIKey string- BaseURL string+ APIKey string+ BaseURL string+ Protocol string}type InvocationOptions struct {@@ -67,9 +74,18 @@ type CommandSpec struct {Provider stringCredentialBindings []CredentialBindingPrivateHome bool- HookOutput string- Telemetry *InvocationOptions- environment map[string]string+ // PrivateHomeKey names the private HOME directory; empty uses Provider.+ // Agent CLIs keep one HOME per Agent because their MCP configuration+ // lives there.+ PrivateHomeKey string+ // AgentCLI is what BindAgentCLI needs besides the credential.+ AgentCLI AgentCLIOptions+ HookOutput string+ Telemetry *InvocationOptions+ // Stdin feeds the process on the control-plane local sandbox only.+ // Codex chat uses it for the app-server JSON-RPC session.+ Stdin io.Reader+ environment map[string]string}// WithPrivateHomeDir keeps CodeBuddy/Claude isolated from the operator HOME@@ -84,21 +100,41 @@ func (c CommandSpec) WithPrivateHomeDir(dir string) CommandSpec {env[key] = value}env["HOME"] = dir+ env["TMPDIR"] = filepath.Join(dir, "tmp")+ _ = os.MkdirAll(env["TMPDIR"], 0o700)if c.Provider == "codex" {env["CODEX_HOME"] = filepath.Join(dir, ".codex")+ _ = os.MkdirAll(env["CODEX_HOME"], 0o700)}if c.Provider == "claude-code" {env["CLAUDE_CONFIG_DIR"] = filepath.Join(dir, ".claude")+ _ = os.MkdirAll(env["CLAUDE_CONFIG_DIR"], 0o700)}- env["TMPDIR"] = filepath.Join(dir, "tmp")if c.Provider == "codebuddy" {env["CODEBUDDY_CONFIG_DIR"] = filepath.Join(dir, ".codebuddy")+ _ = os.MkdirAll(env["CODEBUDDY_CONFIG_DIR"], 0o700)}c.environment = envc.PrivateHome = falsereturn c}+// WithClaudeBypassAccepted lets a Claude Code command that passes+// --permission-mode bypassPermissions start when the host runs it as root.+// The caller's tool policy is what limits the process.+func (c CommandSpec) WithClaudeBypassAccepted() CommandSpec {+ if c.Provider != "claude-code" {+ return c+ }+ env := make(map[string]string, len(c.environment)+1)+ for key, value := range c.environment {+ env[key] = value+ }+ env["IS_SANDBOX"] = "1"+ c.environment = env+ return c+}+// WithMCPStartupWait lets a CodeBuddy -p process wait up to timeout for MCP// servers that expose always-loaded tools before its first model request.// The headless default is about 2s; a server that connects later is missingdiff --git a/internal/runtime/runtime_test.go b/internal/runtime/runtime_test.goindex bd40c09a..544bbd9c 100644--- a/internal/runtime/runtime_test.go+++ b/internal/runtime/runtime_test.go@@ -692,12 +692,13 @@ func TestBwrapProvidesWritableRuntimeInfrastructure(t *testing.T) {if err := os.MkdirAll(stateDir, 0o700); err != nil {t.Fatal(err)}+ bunfs := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "$bunfs"))args, err := bwrapArgsRequirements(workspace, ProviderRequirements("codebuddy"))if err != nil {t.Fatal(err)}text := strings.Join(args, " ")- for _, needle := range []string{"--die-with-parent", "--tmpfs /tmp", "--dev-bind /dev /dev", "--proc /proc", "--tmpfs /$bunfs"} {+ for _, needle := range []string{"--die-with-parent", "--tmpfs /tmp", "--dev-bind /dev /dev", "--proc /proc", "--tmpfs " + bunfs} {if !strings.Contains(text, needle) {t.Fatalf("bwrap args missing %q: %v", needle, args)}@@ -2038,7 +2039,7 @@ func TestIsolateClaudeFlagsUsesHostUserSettings(t *testing.T) {}func TestCodexInDockerUsesTheContainerAsItsSandbox(t *testing.T) {- for driver, want := range map[string]string{"docker": "danger-full-access", "bwrap": "workspace-write", "local": "workspace-write"} {+ for driver, want := range map[string]string{"docker": "danger-full-access", "bwrap": "danger-full-access", "local": "workspace-write"} {ex := domain.ExecutorDefinition{Kind: "codex", Binary: "codex", Args: []string{"exec", "--json", "--sandbox", "workspace-write", "--skip-git-repo-check"}}command, err := PrepareProviderCommand(ex, "probe", driver, InvocationOptions{ResumeSessionID: "thread-1"})if err != nil {@@ -2069,7 +2070,7 @@ func TestClaudeNodesCanUseToolsUnattended(t *testing.T) {if containsArg(command.Argv, "dontAsk") || !containsArgPair(command.Argv, "--permission-mode", "bypassPermissions") {t.Fatalf("%s: want bypassPermissions only: %v", driver, command.Argv)}- if got, want := command.environment["IS_SANDBOX"], map[bool]string{true: "1"}[driver == "docker"]; got != want {+ if got, want := command.environment["IS_SANDBOX"], map[bool]string{true: "1"}[driver != "local" || os.Geteuid() == 0]; got != want {t.Fatalf("%s: IS_SANDBOX=%q, want %q", driver, got, want)}}@@ -2103,13 +2104,13 @@ func TestExecutorRunnerAppliesDriverSpecificUserConfigPolicy(t *testing.T) {}}},{name: "local codex", driver: "local", kind: "codex", check: func(t *testing.T, argv []string) {- if !containsArg(argv, "--ignore-user-config") || !containsArg(argv, "--ignore-rules") {- t.Fatalf("local Codex compatibility flags missing: %v", argv)+ if containsArg(argv, "--ignore-user-config") || containsArg(argv, "--ignore-rules") {+ t.Fatalf("Codex no longer accepts the removed config flags: %v", argv)}}},{name: "sandboxed codex", driver: "bwrap", kind: "codex", check: func(t *testing.T, argv []string) {if containsArg(argv, "--ignore-user-config") || containsArg(argv, "--ignore-rules") {- t.Fatalf("sandboxed Codex should inherit user configuration: %v", argv)+ t.Fatalf("sandboxed Codex should not pass removed config flags: %v", argv)}}},}diff --git a/internal/runtime/sandbox_local.go b/internal/runtime/sandbox_local.goindex 6ec65e1b..739987d7 100644--- a/internal/runtime/sandbox_local.go+++ b/internal/runtime/sandbox_local.go@@ -51,6 +51,7 @@ func (s *localSandbox) command(ctx context.Context, command CommandSpec, base []cmd.Env = appendEnvironment(base, s.environment, command.environment)cmd.Env = upsertEnv(cmd.Env, "PWD", workspace)cmd.Env = upsertEnv(cmd.Env, "GIT_CEILING_DIRECTORIES", filepath.Dir(workspace))+ cmd.Stdin = command.Stdinreturn cmd, nil}diff --git a/internal/runtime/sandbox_manager.go b/internal/runtime/sandbox_manager.goindex cec009b7..0653250c 100644--- a/internal/runtime/sandbox_manager.go+++ b/internal/runtime/sandbox_manager.go@@ -6,6 +6,7 @@ import ("fmt""os""path/filepath"+ goruntime "runtime""strings""sync")@@ -78,6 +79,9 @@ func (m *Manager) open(ctx context.Context, id, dir string, profile domain.Sandb_ = unlockFile(lock)return nil, err}+ if profile.Driver, err = domain.ResolveSandboxDriver(profile.Driver, goruntime.GOOS); err != nil {+ return fail(err)+ }workspace := filepath.Join(m.root, dir)if wipe {if err := os.RemoveAll(workspace); err != nil {diff --git a/internal/runtime/sandbox_native_test.go b/internal/runtime/sandbox_native_test.gonew file mode 100644index 00000000..054d1d29--- /dev/null+++ b/internal/runtime/sandbox_native_test.go@@ -0,0 +1,85 @@+package runtime++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "agentflow/internal/domain"+)++func stubBunFSMountPoint(t *testing.T, path string) string {+ t.Helper()+ previous := bunFSMountPoint+ bunFSMountPoint = path+ t.Cleanup(func() { bunFSMountPoint = previous })+ return path+}++func TestBwrapBunFSMountPoint(t *testing.T) {+ workspace := t.TempDir()+ claude := ProviderRequirements("claude-code")++ // Missing but creatable: created once, then mounted.+ created := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "$bunfs"))+ args, err := bwrapArgsRequirements(workspace, claude)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(strings.Join(args, " "), "--tmpfs "+created) {+ t.Fatalf("creatable mount point not mounted: %v", args)+ }+ if info, err := os.Stat(created); err != nil || !info.IsDir() {+ t.Fatalf("mount point not created: %v", err)+ }++ // Cannot be created (parent missing / read-only root): skip the mount+ // instead of failing the whole sandbox.+ missing := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "absent", "$bunfs"))+ args, err = bwrapArgsRequirements(workspace, claude)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(strings.Join(args, " "), missing) {+ t.Fatalf("uncreatable mount point must be skipped: %v", args)+ }++ // CLIs without BunFS never touch it.+ untouched := stubBunFSMountPoint(t, filepath.Join(t.TempDir(), "$bunfs"))+ if _, err := bwrapArgsRequirements(workspace, ProviderRequirements("codex")); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(untouched); !os.IsNotExist(err) {+ t.Fatalf("codex created the BunFS mount point: %v", err)+ }+}++func TestNativeSandboxResolvesPerOS(t *testing.T) {+ for _, tc := range []struct{ driver, goos, want string }{+ {"native", "darwin", "seatbelt"},+ {"native", "linux", "bwrap"},+ {" native ", "Linux", "bwrap"},+ {"native", "", "native"},+ {"docker", "linux", "docker"},+ {"local", "darwin", "local"},+ {"bwrap", "darwin", "bwrap"},+ } {+ got, err := domain.ResolveSandboxDriver(tc.driver, tc.goos)+ if err != nil || got != tc.want {+ t.Fatalf("ResolveSandboxDriver(%q, %q) = %q, %v; want %q", tc.driver, tc.goos, got, err, tc.want)+ }+ }+ if _, err := domain.ResolveSandboxDriver("native", "windows"); err == nil {+ t.Fatal("native on windows must fail")+ }+}++func TestOpenRemoteSandboxResolvesNative(t *testing.T) {+ // On the test host native must become the host's lightweight sandbox,+ // never reach the driver switch as "native".+ _, err := OpenRemoteSandbox(t.Context(), "native", t.TempDir(), domain.SandboxProfile{ID: "n", Driver: "native"}, SandboxRequirements{}, SandboxResources{})+ if err != nil && strings.Contains(err.Error(), "unsupported runner sandbox driver") {+ t.Fatalf("native leaked to the driver switch: %v", err)+ }+}diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.goindex d816b28f..af079711 100644--- a/internal/runtime/sandbox_process.go+++ b/internal/runtime/sandbox_process.go@@ -388,6 +388,26 @@ func seatbeltProfileCommand(workspace string, requirements SandboxRequirements,return b.String(), nil}+// bunFSMountPoint is the virtual root Bun-compiled CLIs (Claude Code,+// CodeBuddy) resolve their embedded files under. A variable for tests.+var bunFSMountPoint = "/$bunfs"++// ensureBunFSMountPoint makes sure bwrap can mount a private tmpfs at+// bunFSMountPoint. bwrap binds the host root read-only, so it cannot create a+// missing mount point and the whole sandbox would fail ("Can't create file+// /$bunfs: Read-only file system"). The host directory is created once when+// the runner may (root, as the builtin runner); otherwise the mount is+// skipped and Bun falls back to its in-process virtual filesystem.+func ensureBunFSMountPoint() bool {+ if info, err := os.Stat(bunFSMountPoint); err == nil {+ return info.IsDir()+ }+ if err := os.Mkdir(bunFSMountPoint, 0o755); err != nil && !os.IsExist(err) {+ return false+ }+ return true+}+func bwrapArgsRequirements(workspace string, requirements SandboxRequirements) ([]string, error) {return bwrapArgsCommand(workspace, requirements, true)}@@ -407,8 +427,8 @@ func bwrapArgsCommand(workspace string, requirements SandboxRequirements, maskAg"--proc", "/proc","--dev-bind", "/dev", "/dev",}- if requirements.BunFS {- args = append(args, "--tmpfs", "/$bunfs")+ if requirements.BunFS && ensureBunFSMountPoint() {+ args = append(args, "--tmpfs", bunFSMountPoint)}stateDirs, err := agentStateDirectories(requirements)if err != nil {diff --git a/migrations/024_native_sandbox_driver.sql b/migrations/024_native_sandbox_driver.sqlnew file mode 100644index 00000000..940981ac--- /dev/null+++ b/migrations/024_native_sandbox_driver.sql@@ -0,0 +1,15 @@+-- Manual, idempotent MySQL migration: merge the seatbelt / bwrap sandbox+-- drivers into the single "native" option.+--+-- native is the OS lightweight process sandbox. The executing machine picks+-- seatbelt on macOS and bwrap on Linux (domain.ResolveSandboxDriver), so a+-- profile no longer has to match the runner's OS.+--+-- Safe to run before or after deploying: the new binary still executes rows+-- that keep seatbelt / bwrap, and stores native whenever such a profile is+-- saved again. Running this only makes the stored value and the UI agree.+-- Profile ids are unchanged, so workflows referencing them need no update.++UPDATE sandboxes+SET payload = JSON_SET(payload, '$.driver', 'native')+WHERE JSON_UNQUOTE(JSON_EXTRACT(payload, '$.driver')) IN ('seatbelt', 'bwrap');diff --git a/migrations/025_agent_cli_credentials.sql b/migrations/025_agent_cli_credentials.sqlnew file mode 100644index 00000000..00788111--- /dev/null+++ b/migrations/025_agent_cli_credentials.sql@@ -0,0 +1,6 @@+-- Personal credentials for the agent CLIs (OpenCode, Cursor, Antigravity,+-- Kimi, Pi, DeepSeek Harness). CodeBuddy, Codex and Claude Code keep their+-- existing columns. Apply manually; startup does not run this script.+-- gorm AutoMigrate also adds the column on process start.++ALTER TABLE user_configs ADD COLUMN agent_cli_credentials TEXT NULL;diff --git a/web/app/assets.js b/web/app/assets.jsindex ed1b9b3e..644afc76 100644--- a/web/app/assets.js+++ b/web/app/assets.js@@ -33,7 +33,7 @@ function assetMetaHTML(a){}if(state.assetType==='dockerfiles')meta.push(item('doc',`${(a.content||'').split('\n').length} 行`));if(state.assetType==='environments')meta.push(item('variable',`${Object.keys(a.variables||{}).length} 个变量`));- if(state.assetType==='sandboxes')meta.push(item('server',a.driver||'local'));+ if(state.assetType==='sandboxes')meta.push(item('server',sandboxDriverOption(a.driver)));const refs=assetReferenceNames(a).length;meta.push(item(assetRefIconName(),refs?`${refs} 个${assetRefKindLabel()}引用`:'未被引用'));return meta.join('');@@ -296,6 +296,8 @@ function renderRuleSOPPicker(){const host=$('#ruleSOPPicker');if(!host)return;cofunction bindRuleGlobalPicker(a){const host=$('#ruleSOPPicker');if(!host)return;const known=new Set(ruleSOPChoices().map(w=>w.id));host.dataset.ids=JSON.stringify((Array.isArray(a.workflowIds)?a.workflowIds:[]).filter(id=>known.has(id)));const toggle=document.querySelector('#assetForm [name="global"]');const wrap=$('#ruleSOPPickerWrap');const sync=()=>{if(wrap)wrap.hidden=!(toggle&&toggle.checked)};if(toggle)toggle.onchange=sync;sync();renderRuleSOPPicker()}function dockerfileOptions(selected){const items=(state.data.dockerfiles||[]).filter(x=>catalogVisible(x.projectId,x.shared));if(!items.length)return `<option value="">请先创建 Dockerfile</option>`;return `<option value="">选择 Dockerfile</option>`+items.map(x=>`<option value="${escapeHTML(x.id)}" ${x.id===selected?'selected':''}>${escapeHTML(x.name||x.id)}${catalogForeign(x.projectId)?' · 共享':''}</option>`).join('')}function environmentOptions(selected){const items=(state.data.environments||[]).filter(x=>catalogVisible(x.projectId,x.shared));return `<option value="">不选择(可用 workspace 的 agentflow-environment)</option>`+items.map(x=>`<option value="${escapeHTML(x.id)}" ${x.id===selected?'selected':''}>${escapeHTML(x.name||x.id)}${catalogForeign(x.projectId)?' · 共享':''}</option>`).join('')}+// seatbelt / bwrap are the per-OS forms of native; rows saved before the merge still carry them.+function sandboxDriverOption(driver){return ['seatbelt','bwrap','native'].includes(driver)?'native':driver==='docker'?'docker':'local'}function syncSandboxDriverFields(select){const driver=select?.value||'local';select?.form?.querySelectorAll('[data-sandbox-drivers]').forEach(el=>{el.hidden=!el.dataset.sandboxDrivers.split(' ').includes(driver)})}function resolveAssetSaveIdentity(items,selectedID,requestedID){if(selectedID!=='__new__'){const existing=(items||[]).find(item=>item.id===selectedID);return existing?{id:existing.id,existing,created:false}:{error:'选中的资产已不存在,请刷新后重试'}}if((items||[]).some(item=>item.id===requestedID))return {error:'该标识已存在,请换一个标识,或回到列表打开已有资产修改'};return {id:requestedID,existing:null,created:true}}function assetPaneTabs(type=state.assetType){return ({rules:[['edit','编辑'],['preview','预览']],skills:[['files','文件']],dockerfiles:[['content','Dockerfile'],['files','构建上下文']],environments:[['script','install.sh'],['vars','环境变量'],['path','PATH']],sandboxes:[['env','环境变量']]})[type]||[['edit','编辑']]}@@ -330,7 +332,7 @@ function assetBasicFieldsHTML(a,{creating}){const kind=assetKindLabel();let html=`<label class="asset-field-label" for="assetFieldName">名称</label><input id="assetFieldName" name="name" class="asset-input" value="${escapeHTML(a.name||'')}" required placeholder="给${escapeHTML(kind)}起个名字"><label class="asset-field-label" for="assetFieldId">标识</label><input id="assetFieldId" name="id" class="asset-input is-mono" value="${escapeHTML(a.id||'')}" required ${creating?'placeholder="如 loopforge-core"':'readonly aria-readonly="true"'}><div class="asset-field-hint">${creating?'创建后不可修改,用于资产引用。':'标识用于资产引用,创建后不可修改。'}</div><label class="asset-field-label" for="assetFieldDesc">描述</label><input id="assetFieldDesc" name="description" class="asset-input" value="${escapeHTML(a.description||'')}" placeholder="一句话说明用途">`;if(state.assetType==='rules')html+=`<label class="asset-field-label" for="assetFieldPriority">优先级</label><input id="assetFieldPriority" name="priority" class="asset-input" type="number" value="${a.priority||100}"><div class="asset-field-hint">数值越大越先注入。</div>${ruleGlobalFields(a)}`;- if(state.assetType==='sandboxes')html+=`<label class="asset-field-label">隔离方式</label><select name="driver" class="asset-select" aria-label="隔离方式"><option value="local" ${!['seatbelt','bwrap','docker'].includes(a.driver)?'selected':''}>local(本机直接执行)</option><option value="seatbelt" ${a.driver==='seatbelt'?'selected':''}>seatbelt(macOS 轻量隔离)</option><option value="bwrap" ${a.driver==='bwrap'?'selected':''}>bwrap(Linux 轻量隔离)</option><option value="docker" ${a.driver==='docker'?'selected':''}>docker(OCI 容器)</option></select><div data-sandbox-drivers="local" class="json-help">直接在本机 workspace 执行,并继承受控的宿主进程环境。</div><div data-sandbox-drivers="seatbelt bwrap"><label class="asset-field-label">执行环境</label><select name="environmentId" class="asset-select" aria-label="执行环境">${environmentOptions(a.environmentId)}</select><div class="json-help">选中后沙箱会执行该环境的 <code>install.sh</code>,把工具装进隔离的 <code>$PREFIX</code>,再用 PATH 切换。未选择时,若 workspace 存在 <code>agentflow-environment/</code> 也会自动启用。</div></div><div data-sandbox-drivers="docker"><label class="asset-field-label">Dockerfile</label><select name="dockerfileId" class="asset-select" aria-label="Dockerfile">${dockerfileOptions(a.dockerfileId)}</select><div class="json-help">沙箱只引用这条目录资产;初始化时用库里的内容构建临时镜像,结束后删除容器和镜像。</div><label class="asset-switch-row"><span><b>容器根文件系统只读</b><small>仅限制镜像自身的 /usr、/etc 等目录;/workspace 仍可写,/tmp 使用临时内存盘。部分工具可能不兼容,默认建议关闭。</small></span><input name="readOnlyRootFS" type="checkbox" class="asset-switch" role="switch" ${a.readOnlyRootFS?'checked':''}></label></div>`;+ if(state.assetType==='sandboxes')html+=`<label class="asset-field-label">隔离方式</label><select name="driver" class="asset-select" aria-label="隔离方式"><option value="local" ${sandboxDriverOption(a.driver)==='local'?'selected':''}>local(本机直接执行)</option><option value="native" ${sandboxDriverOption(a.driver)==='native'?'selected':''}>native(系统轻量隔离)</option><option value="docker" ${sandboxDriverOption(a.driver)==='docker'?'selected':''}>docker(OCI 容器)</option></select><div data-sandbox-drivers="local" class="json-help">直接在本机 workspace 执行,并继承受控的宿主进程环境。</div><div data-sandbox-drivers="native" class="json-help">按执行机器的系统自动选择:macOS 用 seatbelt,Linux 用 bwrap。</div><div data-sandbox-drivers="native"><label class="asset-field-label">执行环境</label><select name="environmentId" class="asset-select" aria-label="执行环境">${environmentOptions(a.environmentId)}</select><div class="json-help">选中后沙箱会执行该环境的 <code>install.sh</code>,把工具装进隔离的 <code>$PREFIX</code>,再用 PATH 切换。未选择时,若 workspace 存在 <code>agentflow-environment/</code> 也会自动启用。</div></div><div data-sandbox-drivers="docker"><label class="asset-field-label">Dockerfile</label><select name="dockerfileId" class="asset-select" aria-label="Dockerfile">${dockerfileOptions(a.dockerfileId)}</select><div class="json-help">沙箱只引用这条目录资产;初始化时用库里的内容构建临时镜像,结束后删除容器和镜像。</div><label class="asset-switch-row"><span><b>容器根文件系统只读</b><small>仅限制镜像自身的 /usr、/etc 等目录;/workspace 仍可写,/tmp 使用临时内存盘。部分工具可能不兼容,默认建议关闭。</small></span><input name="readOnlyRootFS" type="checkbox" class="asset-switch" role="switch" ${a.readOnlyRootFS?'checked':''}></label></div>`;return html;}function assetAsideHTML(a,{creating}){@@ -670,7 +672,7 @@ async function saveAsset(e){e.preventDefault();const f=e.currentTarget,items=staif(state.assetType==='skills'){/* 文件经独立上传接口承载;此处只提交元数据。服务端会强制保留 Content/Files/FileRefs。 */}if(state.assetType==='dockerfiles')Object.assign(value,{content:f.elements.content.value,files:JSON.parse(f.elements.files.value||'{}')});if(state.assetType==='environments')Object.assign(value,{variables:JSON.parse(f.elements.variables.value||'{}'),pathEntries:lines(f.elements.pathEntries.value),installScript:f.elements.installScript.value});- if(state.assetType==='sandboxes'){const driver=f.elements.driver.value,sandbox={driver,environment:JSON.parse(f.elements.environment.value||'{}')};if(driver==='docker')Object.assign(sandbox,{dockerfileId:f.elements.dockerfileId.value,readOnlyRootFS:f.elements.readOnlyRootFS.checked});if(driver==='seatbelt'||driver==='bwrap')Object.assign(sandbox,{environmentId:f.elements.environmentId.value});Object.assign(value,sandbox)}+ if(state.assetType==='sandboxes'){const driver=f.elements.driver.value,sandbox={driver,environment:JSON.parse(f.elements.environment.value||'{}')};if(driver==='docker')Object.assign(sandbox,{dockerfileId:f.elements.dockerfileId.value,readOnlyRootFS:f.elements.readOnlyRootFS.checked});if(driver==='native')Object.assign(sandbox,{environmentId:f.elements.environmentId.value});Object.assign(value,sandbox)}const endpoints={rules:'rules',skills:'skills',dockerfiles:'dockerfiles',environments:'environments',sandboxes:'sandboxes'};await api(`/api/${endpoints[state.assetType]}`,{method:'PUT',body:JSON.stringify(value)});const i=items.findIndex(x=>x.id===value.id);if(state.assetType==='skills'&&existing)value={...existing,...value,fileRefs:existing.fileRefs||[],content:existing.content||'',files:existing.files||{}};if(i>=0)items[i]=value;else items.push(value);state.selectedAsset=value.id;state.assetDirty=false;if(identity.created){history.replaceState(history.state,'',assetViewHash(state.assetType,value.id));state.assetDetailKey='';renderAssets()}else{renderAssetDetailHead(value);refreshAssetAside(value)}diff --git a/web/app/runners.js b/web/app/runners.jsindex fd09f298..2292444c 100644--- a/web/app/runners.js+++ b/web/app/runners.js@@ -53,15 +53,15 @@ function runnerStatusLabel(status){default:return `<span class="runner-status"><i></i>${escapeHTML(status||'unknown')}</span>`;}}-const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy'};-const runnerCLIGlyphs={'claude-code':'C','codex':'X','codebuddy':'B'};+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'};+const runnerCLIGlyphs={'claude-code':'C','codex':'X','codebuddy':'B',opencode:'O',cursor:'Cu',agy:'A',kimi:'K',pi:'P',dsh:'D'};const runnerOSLabels={darwin:'macOS',linux:'Linux',windows:'Windows'};function runnerPersonalCredentialConfigured(provider){const user=userById(state.currentUser?.id)||{};if(provider==='codex')return !!user.codexApiKeyConfigured;if(provider==='claude-code')return !!user.claudeCodeApiKeyConfigured;if(provider==='codebuddy')return !!user.codeBuddyApiKeyConfigured;- return false;+ return !!user.agentCliCredentials?.[provider]?.apiKeyConfigured;}function runnerLastSeen(value){if(!value)return '尚无心跳';diff --git a/web/app/sops.js b/web/app/sops.jsindex e8ee3f87..9be2126d 100644--- a/web/app/sops.js+++ b/web/app/sops.js@@ -94,10 +94,16 @@ 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'].includes(kind))providers.add(kind==='claude'?'claude-code':kind);+ if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh'].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'};for(const kind of providers){- const [label,field,flag]={codebuddy:['CodeBuddy','codeBuddyApiKey','codeBuddyApiKeyConfigured'],codex:['Codex','codexApiKey','codexApiKeyConfigured'],'claude-code':['Claude Code','claudeCodeApiKey','claudeCodeApiKeyConfigured']}[kind];+ 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'];+ if(!known){+ rows.push({key:'run-key-'+kind,field,fix:'settings',fixLabel:'去个人配置配置',label:label+' API Key',ok:!!user.agentCliCredentials?.[kind]?.apiKeyConfigured,hint:lfT('Agent 节点使用 '+label+',请在个人配置里配置对应 API Key。','Agent nodes use '+label+'. Configure its API key in Settings.')});+ continue;+ }rows.push({key:'run-key-'+kind,field,fix:'settings',fixLabel:'去个人配置配置',label:label+' API Key',ok:!!user[flag],hint:lfT('Agent 节点使用 '+label+',请在个人配置里配置对应 API Key。','Agent nodes use '+label+'. Configure its API key in Settings.')});}if(usesRepo)rows.push({key:'run-repo',fix:'',label:'GitHub 仓库(已绑定)',ok:true,hint:'使用项目已绑定的仓库。访问私有仓库或推送代码时需要在个人配置中配置 GitHub Token;未绑定仓库时可在任务工作区直接运行。'});diff --git a/web/app/workbench.js b/web/app/workbench.jsindex 3b725ac7..4872c8a8 100644--- a/web/app/workbench.js+++ b/web/app/workbench.js@@ -83,12 +83,51 @@ const CREDENTIAL_KINDS=[placeholder:'请输入 Claude Code API Key',extra:{name:'claudeCodeBaseUrl',label:'Base URL',placeholder:'https://api.anthropic.com',url:true,clearWithKey:true},impact:'以 Claude Code 运行的 SOP 节点将无法执行,Base URL 一并清空。'},+ agentCliCredentialKind('opencode',{name:'OpenCode',logo:'opencode',baseUrl:'https://api.example.com/v1',required:()=>true,+ note:'OpenCode 没有自己的模型服务,需要填写 Base URL。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),+ agentCliCredentialKind('cursor',{name:'Cursor CLI',logo:'cursor',monochrome:true,+ note:'Cursor CLI 只连接 Cursor 官方服务,使用 Cursor 自带的模型。',+ guide:[['登录 Cursor 控制台,在「Integrations → User API Keys」新建 Key','https://cursor.com/dashboard?tab=integrations','前往 Cursor 创建 API Key'],['复制以 <code>crsr_</code> 开头的 Key'],['粘贴到下方保存']]}),+ agentCliCredentialKind('agy',{name:'Antigravity',logo:'gemini',baseUrl:'https://gateway.example.com/v1',required:protocol=>protocol==='chat',+ note:'默认连接 Gemini 官方服务;选择 OpenAI 兼容网关时需要填写 Base URL。',extraNote:'OpenAI 兼容网关必填',+ guide:[['在 Google AI Studio 创建 Gemini API Key,或准备 OpenAI 兼容网关的 Key','https://aistudio.google.com/apikey','前往 Google AI Studio'],['走网关时记下网关地址'],['粘贴 Key,选择协议']],+ protocols:[['gemini','Gemini 官方 API'],['chat','OpenAI 兼容网关(Chat Completions)']]}),+ agentCliCredentialKind('kimi',{name:'Kimi Code',logo:'kimi',baseUrl:'https://api.moonshot.cn/v1',+ note:'未填写 Base URL 时连接 Moonshot 官方服务。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),+ agentCliCredentialKind('pi',{name:'Pi',logo:'pi',monochrome:true,baseUrl:'https://api.example.com/v1',required:()=>true,+ note:'Pi 没有自己的模型服务,需要填写 Base URL。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),+ agentCliCredentialKind('dsh',{name:'DeepSeek Harness',logo:'deepseek',baseUrl:'https://api.deepseek.com',+ note:'未填写 Base URL 时连接 DeepSeek 官方服务。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),];+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,+ use:`AI 对话的 ${o.name} 模型与以 ${o.name} 运行的 SOP 节点`,+ description:`AI 对话切换到 ${o.name} 后可选用它的模型,SOP 在执行机器上以 ${o.name} 运行的节点也使用它。${o.note||''}`,+ guide:o.guide||[['在模型服务商控制台创建 API Key'],['记下服务地址和它提供的接口协议'],['粘贴 Key,按需填写 Base URL 并选择协议']],+ 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},+ }:{}),+ impact:`AI 对话将不能再切换到 ${o.name},以 ${o.name} 运行的 SOP 节点将无法执行${configurable?',Base URL 与协议一并清空':''}。`};+}+function credentialValue(user,name){+ const [scope,cli,field]=String(name).split('.');+ return scope==='agentCli'&&field?user?.agentCliCredentials?.[cli]?.[field]:user?.[name];+}+function credentialProtocol(kind,user){+ const options=kind.protocol?.options||[],value=credentialValue(user,kind.protocol?.name||'');+ return options.some(([id])=>id===value)?value:(options[0]?.[0]||'');+}+function credentialProtocolHTML(kind,value){+ return `<label class="credential-field"><span>接口协议<em>Base URL 提供的 API</em></span><div class="credential-input is-plain is-select"><select name="protocol" aria-label="接口协议">${kind.protocol.options.map(([id,label])=>`<option value="${id}"${id===value?' selected':''}>${escapeHTML(label)}</option>`).join('')}</select></div></label>`;+}// Platform features depend on these, in the order people should configure them.const CREDENTIAL_RECOMMENDED=['gitToken','codeBuddyApiKey'];const CREDENTIAL_PAT_WARNING='请填写 GitHub <b>个人访问令牌(PAT)</b>,为目标仓库授予 <b>Contents</b> 和 <b>Pull requests</b> 的读写权限;少勾权限会导致克隆 / 推送仓库失败。';function credentialKind(key){return CREDENTIAL_KINDS.find(kind=>kind.key===key)||null}-function credentialConfigured(kind,user){return !!user?.[kind.key+'Configured']}+function credentialConfigured(kind,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 `<svg class="agent-icon harness-icon${cls?' '+cls:''}" data-icon="${name}" width="${size}" height="${size}" aria-hidden="true" focusable="false"></svg>`}@@ -131,19 +170,28 @@ function refreshCredentialEnvironmentLinks(scope,value){const hint=scope?.querySelector('[data-credential-env-hint]');if(hint)hint.innerHTML=codeBuddyEnvironmentHintHTML(value);scope?.querySelectorAll('[data-wizard-link][data-environment-link]').forEach(link=>{link.href=codeBuddyKeyURL(value);link.textContent=`${codeBuddyKeyLinkLabel(value)} ↗`});}-function credentialExtraError(kind,value){+function credentialExtraError(kind,value,protocol){const text=String(value||'').trim();+ if(!text&&kind.extra?.required?.(protocol))return '请填写 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:// 开头的地址';}// Only the fields of one credential are sent; the server leaves the rest alone.function credentialSavePayload(kind,values={}){+ if(kind.agentCli){+ const entry={},secret=String(values.secret||'').trim();+ if(secret)entry.apiKey=secret;+ if(kind.extra&&values.extra!==undefined)entry.baseUrl=String(values.extra||'').trim();+ if(kind.protocol&&values.protocol!==undefined)entry.protocol=values.protocol;+ return {agentCliCredentials:{[kind.agentCli]:entry}};+ }const payload={[kind.key]:String(values.secret||'').trim()};if(kind.extra&&values.extra!==undefined)payload[kind.extra.name]=String(values.extra||'').trim()||(kind.extra.fallback||'');return payload;}function credentialClearPayload(kind){+ if(kind.agentCli)return {agentCliCredentials:{[kind.agentCli]:{apiKeyClear:true,baseUrl:'',protocol:''}}};const payload={[kind.key+'Clear']:true};if(kind.extra?.clearWithKey)payload[kind.extra.name]='';return payload;@@ -183,7 +231,7 @@ function credentialSubline(kind,user){const raw=String(user.codeBuddyInternetEnvironment||'').trim(),env=codeBuddyEnvironment(raw);return `<span>网络环境</span>${env?`<span class="credential-mono">${escapeHTML(env.label)}</span>`:`<span class="is-err">「${escapeHTML(raw)}」无法识别,按国际站连接</span>`}${dot}${use}`;}- if(kind.extra)return (user[kind.extra.name]?`<span class="credential-mono">${escapeHTML(user[kind.extra.name])}</span>`:'<span>官方地址</span>')+dot+use;+ if(kind.extra){const extra=credentialValue(user,kind.extra.name);return (extra?`<span class="credential-mono">${escapeHTML(extra)}</span>`:'<span>官方地址</span>')+dot+use;}return use;}function credentialFieldHTML({label,note='',name,type='password',value='',placeholder='',hint='',hintTone='',id=''}){@@ -233,15 +281,17 @@ function gitTokenEditorHTML(kind,user){}function credentialEditorHTML(kind,user){if(kind.key==='gitToken')return gitTokenEditorHTML(kind,user);- const extraValue=kind.extra?credentialExtraValue(kind,user[kind.extra.name]):'';+ const extraStored=kind.extra?credentialValue(user,kind.extra.name):'';+ const extraValue=kind.extra?credentialExtraValue(kind,extraStored):'';const extraField=!kind.extra?''- :kind.extra.options?credentialSelectFieldHTML(kind,user[kind.extra.name],'与 Key 所在站点一致')- :credentialFieldHTML({label:kind.extra.label,note:kind.extra.url?'留空使用官方地址':'',name:'extra',type:kind.extra.url?'url':'text',value:extraValue,placeholder:kind.extra.placeholder,hint:null});- // A stored environment the CLI does not take as written (china, private-net…) can be saved as shown without retyping the key.+ :kind.extra.options?credentialSelectFieldHTML(kind,extraStored,'与 Key 所在站点一致')+ :credentialFieldHTML({label:kind.extra.label,note:kind.extra.note||(kind.extra.url?'留空使用官方地址':''),name:'extra',type:kind.extra.url?'url':'text',value:extraValue,placeholder:kind.extra.placeholder,hint:null});+ const protocolField=kind.protocol?credentialProtocolHTML(kind,credentialProtocol(kind,user)):'';const legacy=!!(kind.extra?.options&&codeBuddyEnvironmentLegacy(user[kind.extra.name]));return `<div class="credential-editor-form"${kind.extra?` data-original="${escapeHTML(extraValue)}"`:''}${legacy?' data-legacy="true"':''}>${credentialFieldHTML({label:kind.short,note:'已配置 · 留空则不改',name:'secret',placeholder:'输入新值以替换',hint:kind.hint||''})}${extraField}+ ${protocolField}<div class="credential-swap"><div class="credential-editor-foot" data-credential-pane="foot"><button type="button" class="credential-btn ghost danger credential-ink" data-credential-act="delete">${credentialGlyph('trash',14)}<span>删除</span></button><div><button type="button" class="credential-btn ghost credential-ink" data-credential-act="cancel">取消</button><button type="button" class="credential-btn primary credential-ink" data-credential-act="save"${legacy?'':' disabled'}>保存</button></div></div><div class="credential-confirm is-off" data-credential-pane="confirm" role="alert"><div>删除 <b>${escapeHTML(kind.short)}</b>?${escapeHTML(kind.impact)}</div><button type="button" class="credential-btn ghost credential-ink" data-credential-act="undelete">取消</button><button type="button" class="credential-btn danger-solid credential-ink" data-credential-act="confirm-delete">删除</button></div>@@ -423,8 +473,8 @@ function credentialSaved(key,message){}async function submitCredentialEditor(row,button){const key=row.dataset.credentialRow,kind=credentialKind(key),form=row.querySelector('.credential-editor-form');- const secret=form.querySelector('input[name="secret"]').value.trim(),extra=form.querySelector('[name="extra"]');- const secretError=credentialSecretError(kind,secret),extraError=extra?credentialExtraError(kind,extra.value):'';+ const secret=form.querySelector('input[name="secret"]').value.trim(),extra=form.querySelector('[name="extra"]'),protocol=form.querySelector('[name="protocol"]');+ const secretError=credentialSecretError(kind,secret),extraError=extra?credentialExtraError(kind,extra.value,protocol?.value):'';if(secretError){setCredentialHint(form,'secret',secretError,'err');return}if(extraError){toast(extraError,'err');extra.focus();return}setCredentialButtonBusy(button,key==='gitToken'?'校验中':'保存中');@@ -441,7 +491,7 @@ async function submitCredentialEditor(row,button){credentialSaved(key,'Git Token 校验通过,已保存');return;}- await saveCredential(key,{secret,...(extra?{extra:extra.value}:{})});+ await saveCredential(key,{secret,...(extra?{extra:extra.value}:{}),...(protocol?{protocol:protocol.value}:{})});credentialSaved(key,`${kind.short} 已保存`);}catch(err){toast(err.message,'err');setCredentialButtonBusy(button,'')}}@@ -534,7 +584,7 @@ function revealCredentialRow(key){// ---- 添加凭证向导 ----let credentialWizard=null;-function credentialWizardDefaults(kind,user){return kind?.extra?credentialExtraValue(kind,user[kind.extra.name]):''}+function credentialWizardDefaults(kind,user){return kind?.extra?credentialExtraValue(kind,credentialValue(user,kind.extra.name)):''}function openCredentialWizard(key){const user=credentialUser();if(!state.currentUser||state.currentUser.isGuest||!$('#credentialPanel'))return;@@ -543,7 +593,7 @@ function openCredentialWizard(key){const kind=preset||CREDENTIAL_RECOMMENDED.map(credentialKind).find(k=>!credentialConfigured(k,user))||CREDENTIAL_KINDS.find(k=>!credentialConfigured(k,user))||null;if(credentialWizard)closeCredentialWizard(true);credentialUI().open&&toggleCredentialRow(credentialUI().open,false);- credentialWizard={step:preset?2:1,kind:kind?.key||null,direct:!!preset,secret:'',extra:credentialWizardDefaults(kind,user),saving:false,error:'',done:false,guide:{},returnFocus:document.activeElement};+ credentialWizard={step:preset?2:1,kind:kind?.key||null,direct:!!preset,secret:'',extra:credentialWizardDefaults(kind,user),protocol:credentialProtocol(kind||{},user),saving:false,error:'',done:false,guide:{},returnFocus:document.activeElement};let scrim=$('#credentialWizard');if(scrim?.closeTimer){clearTimeout(scrim.closeTimer);scrim.closeTimer=0}if(!scrim){@@ -581,7 +631,7 @@ function closeCredentialWizard(immediate=false){}function credentialWizardValid(wizard=credentialWizard){const kind=credentialKind(wizard.kind);if(!kind)return {ok:false};- const secret=String(wizard.secret||'').trim(),error=credentialSecretError(kind,secret)||(kind.extra?credentialExtraError(kind,wizard.extra):'');+ const secret=String(wizard.secret||'').trim(),error=credentialSecretError(kind,secret)||(kind.extra?credentialExtraError(kind,wizard.extra,wizard.protocol):'');return {ok:!!secret&&!error,error};}function credentialWizardSecretHint(kind,wizard,validity=credentialWizardValid(wizard)){@@ -613,10 +663,11 @@ function credentialWizardStepTwoHTML(kind){const secretField=credentialFieldHTML({label:github?'个人访问令牌(PAT)':kind.short,name:'secret',id:'credentialWizardSecret',placeholder:kind.placeholder,hint:secretHint,hintTone:secretTone});const extraField=!kind.extra?'':kind.extra.options?credentialSelectFieldHTML(kind,wizard.extra)- :credentialFieldHTML({label:kind.extra.label,note:kind.extra.url?'可选 · 留空使用官方地址':'',name:'extra',type:kind.extra.url?'url':'text',value:wizard.extra,placeholder:kind.extra.placeholder,hint:''});+ :credentialFieldHTML({label:kind.extra.label,note:kind.extra.note||(kind.extra.url?'可选 · 留空使用官方地址':''),name:'extra',type:kind.extra.url?'url':'text',value:wizard.extra,placeholder:kind.extra.placeholder,hint:''});+ const protocolField=kind.protocol?credentialProtocolHTML(kind,wizard.protocol||credentialProtocol(kind,{})):'';// The network environment decides where the key comes from, so it is chosen first.return `<div class="credential-question">${credentialLogo(kind,'is-mini')}<span>${github?'使用访问令牌':'配置 '+escapeHTML(kind.short)}</span><small class="credential-description">${escapeHTML(kind.description)}</small></div>${methods}<ol class="credential-guide">${guide}</ol><div class="credential-fields">- ${kind.extra?.options?extraField+secretField:secretField+extraField}+ ${kind.extra?.options?extraField+secretField:secretField+extraField+protocolField}</div>`;}function credentialWizardStepThreeHTML(kind){@@ -699,11 +750,12 @@ function credentialWizardInput(event){const wizard=credentialWizard,input=event.target;if(!wizard||!input.name)return;const kind=credentialKind(wizard.kind),pane=input.closest('.credential-pane');if(input.name==='extra')wizard.extra=input.value;+ if(input.name==='protocol')wizard.protocol=input.value;if(input.name==='secret')wizard.secret=input.value;const valid=credentialWizardValid(),hint=credentialWizardSecretHint(kind,wizard,valid);setCredentialHint(pane,'secret',hint.text,hint.tone);if(kind.extra?.options){if(input.name==='extra')refreshCredentialEnvironmentLinks(pane,wizard.extra)}- else if(kind.extra){const extraError=credentialExtraError(kind,wizard.extra);setCredentialHint(pane,'extra',extraError,extraError?'err':'')}+ else if(kind.extra){const extraError=credentialExtraError(kind,wizard.extra,wizard.protocol);setCredentialHint(pane,'extra',extraError,extraError?'err':'')}if(valid.ok)kind.guide.forEach((_,index)=>markCredentialGuide(index));const next=$('#credentialWizard [data-wizard-next]');if(next)next.disabled=!valid.ok;}@@ -724,6 +776,7 @@ function selectCredentialWizardKind(key){// A secret typed for one kind must never be submitted as another kind's credential.wizard.kind=key;wizard.secret='';wizard.guide={};wizard.error='';wizard.extra=credentialWizardDefaults(credentialKind(key),credentialUser());+ wizard.protocol=credentialProtocol(credentialKind(key),credentialUser());}function credentialWizardClick(event){const wizard=credentialWizard,target=event.target;if(!wizard)return;@@ -758,7 +811,7 @@ async function advanceCredentialWizard(){if(kind.key==='gitToken'){const outcome=await verifyAndSaveGitToken(secret);if(!outcome.saved){wizard.error=`${gitTokenFailure(outcome.result)||'Git Token 校验未通过'}(未保存)`;return}- }else await saveCredential(kind.key,{secret,...(kind.extra?{extra:wizard.extra}:{})});+ }else await saveCredential(kind.key,{secret,...(kind.extra?{extra:wizard.extra}:{}),...(kind.protocol?{protocol:wizard.protocol}:{})});wizard.done=true;wizard.secret='';renderCredentialPanel();toast(kind.key==='gitToken'?'Git Token 校验通过,已保存':`${kind.short} 已保存`,'ok');diff --git a/web/i18n-en.js b/web/i18n-en.jsindex 9005446d..6680fc1b 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -43,3 +43,11 @@ Object.assign(window.LF_I18N_EN,{"AI 聊天和 Agent 任务需要模型 API KeyObject.assign(window.LF_I18N_EN,{"按":"Pulls issues from ","当前项目已绑定的 GitHub 仓库":"GitHub repositories bound to this project","拉取 Issue,使用个人设置里的 GitHub 访问令牌。自动同步间隔是平台级配置。":", using the GitHub access token from personal settings. The auto-sync interval is a platform-wide setting.","当前项目还没有绑定 GitHub 仓库,去「项目配置」添加。":"No GitHub repository is bound to this project yet. Add one in Project settings.","建单后按所选 SOP 启动。":"After creation, the selected SOP starts.","保存只改本平台记录,不会回写外部系统。":"Saving only updates this platform record; nothing is written back to external systems.","开启自动同步后,外部同步仍会按间隔把所有已配置来源拉进项目列表。":"With auto-sync on, every configured source is still pulled into the project list at the configured interval.","所有已配置来源":"All configured sources","需求交付明细":"Requirement delivery details","帮我梳理当前项目的待办需求":"Help me review the open requirements in this project","尚未同步。绑定 GitHub 仓库后,可在「需求列表」里点击「同步 GitHub」。":"Not synced yet. After binding a GitHub repository, click \"Sync GitHub\" in Requirements.","请在代码托管平台补充勾选":"; add the missing scopes on your code hosting platform","仓库路径":"Repository path","GitHub 令牌认证":"GitHub token auth","建单后会启动 SOP。":"The SOP starts after creation.","请选择建单方式":"Choose how to create the requirement","点下方「平台需求」":"Click \"Platform requirement\" below","你已确认可以建单。点下方按钮建单并启动 SOP。":"You confirmed it is ready. Use the button below to create it and start the SOP."});Object.assign(window.LF_I18N_EN,{"给同事开账号":"Create accounts for teammates","填好用户名和初始密码,点创建,再把登录信息发给同事。同事忘记密码时可以在下面重置。":"Enter a login name and an initial password, create the account, then send the sign-in details to your teammate. Reset the password below if they forget it.","登录页目前允许自助注册。也可以在这里直接创建账号,再把登录信息发给同事;同事忘记密码时可以在下面重置。":"Self sign-up is open on the login page. You can also create accounts here and send the sign-in details to your teammate; reset the password below if they forget it.","登录页的自助注册已关闭,同事的账号要在这里创建:填好用户名和初始密码,点创建,再把登录信息发给对方。忘记密码时可以在下面重置。":"Self sign-up is closed, so create teammates' accounts here: enter a login name and an initial password, create the account, then send them the sign-in details. Reset the password below if they forget it.","用户名,如 alice":"Login name, e.g. alice","初始密码,至少 6 位":"Initial password, at least 6 characters","新密码,至少 6 位":"New password, at least 6 characters","随机生成":"Generate","随机":"Generate","创建账号":"Create account","搜索用户名...":"Search login names...","用户名密码":"Password sign-in","GitHub / 网关登录":"GitHub / gateway sign-in","已配 CodeBuddy Key":"Has a CodeBuddy key","未配 CodeBuddy Key":"No CodeBuddy key","无平台密码":"No platform password","通过 GitHub 或网关登录的账号没有平台密码":"Accounts that sign in through GitHub or a gateway have no platform password","重置密码":"Reset password","确认重置":"Reset","没有匹配的账号":"No matching accounts","还没有账号":"No accounts yet","复制登录信息":"Copy sign-in details","已复制登录信息":"Sign-in details copied","账号已创建":"Account created","密码已重置":"Password reset","密码只显示这一次,请现在发给对方。":"The password is shown only once; send it now.","共享 CodeBuddy Key":"Shared CodeBuddy Key","给没配 Key 的成员用":"For members without their own key","成员没配自己的 CodeBuddy API Key 时,对话和 SOP 会用这里的 Key,并且只能用下面勾选的模型。成员配了自己的 Key 就用自己的,不受限制。":"Members without their own CodeBuddy API Key chat and run SOPs on this key, limited to the models checked below. Members with their own key keep using it without limits.","允许使用的模型":"Allowed models","列表里没有的模型":"Models not in the list","模型 ID,多个用逗号分隔":"Model IDs, separated by commas","默认模型":"Default model","请先勾选模型":"Check a model first","正在读取可用模型…":"Loading available models…","这个网络环境暂时没有读到模型列表,可以在下面直接填模型 ID。":"No model list was found for this network environment yet; enter model IDs below.","ck_ 开头的 CodeBuddy API Key":"CodeBuddy API Key starting with ck_","已配置,留空保持不变":"Configured; leave blank to keep it","停用共享 Key":"Stop sharing the key","使用旧配置":"Legacy setting","共享 Key 已保存":"Shared key saved","共享 Key 已停用":"Shared key turned off","还没有配置共享 Key,没配 Key 的成员需要先配自己的 Key 才能对话和跑 SOP。":"No shared key yet; members without their own key must add one before chatting or running SOPs.","停用后,没配自己 Key 的成员将不能再用共享 Key 对话和跑 SOP。确定停用?":"Members without their own key will no longer chat or run SOPs on the shared key. Turn it off?","请至少勾选一个允许使用的模型":"Check at least one allowed model","请填写 CodeBuddy API Key":"Enter the CodeBuddy API Key","平台管理分区":"Platform admin sections","没指定模型时用它;SOP 角色的模型不在允许范围内时也改用它。":"Used when no model is chosen, and for SOP roles whose model is not allowed."});Object.assign(window.LF_I18N_EN,{"统计":"Usage","切换项目":"Switch project","/ Agent 原生研发协作平台":"/ Agent-native delivery platform","全局导航":"Main navigation","展开导航":"Expand navigation","收起导航":"Collapse navigation","返回首页":"Back to home","展开设置导航":"Expand settings navigation","收起设置导航":"Collapse settings navigation","个人配置":"Personal settings","个人配置与模型":"Personal settings & models","个人信息与操作":"Profile & actions","点击查看个人信息":"Click to view your profile","认证换票未通过":"Sign-in token exchange failed","当前为访客身份":"Browsing as a guest","搜索任务…":"Search tasks…","搜索任务":"Search tasks","任务状态筛选":"Filter tasks by status","任务责任人筛选":"Filter tasks by assignee","我负责的":"Assigned to me","待处理 / 暂停":"Pending / paused","拖动调整侧栏宽度,双击恢复默认":"Drag to resize the sidebar; double-click to reset","调整侧栏宽度":"Resize sidebar","平台集成":"Platform integrations","代码仓库与统一认证":"Code repositories & sign-in","AI 对话与编码 CLI":"AI chat & coding CLIs","仓库授权":"Repository access","推荐凭证已全部就绪":"All recommended credentials are ready","克隆私有仓库、创建任务分支、推送交付产物":"Clone private repositories, create task branches, push deliverables","AI 对话与 SOP 的 CodeBuddy 执行器":"AI chat and the CodeBuddy executor in SOPs","AI 对话(含 Claude、GPT 等模型)和 SOP 的 CodeBuddy 执行器都使用它;网络环境按账号所在环境配置。":"Used by AI chat (including Claude, GPT and other models) and by the CodeBuddy executor in SOPs. Pick the network environment your account belongs to.","AI 对话选择 Codex 执行器,以及以 Codex 运行的 SOP 节点":"AI chat with the Codex executor, and SOP steps that run on Codex","AI 对话选择 Claude 执行器,以及以 Claude Code 运行的 SOP 节点":"AI chat with the Claude executor, and SOP steps that run on Claude Code","筛选凭证":"Filter credentials","添加凭证":"Add credential","SOP 使用需求责任人(未指定时为项目 Owner)的个人凭证,保存后对下一次任务生效。":"SOPs use the personal credentials of the requirement owner (the project owner when none is set). Changes apply from the next task.","GitHub 仓库(已绑定)":"GitHub repository (bound)","需由责任人本人在个人配置中配置":"The owner has to set this in their own Personal settings","最小接入配置需要绑定到你的账号:执行器 API Key 和 GitHub Git Token 保存在个人配置里;也可以绑定本机 CLI。":"The minimal setup is tied to your account: the executor API key and GitHub Git token are stored in Personal settings. You can also connect a local CLI.","个人配置 · 一次配齐":"Personal settings · all in one place","打开个人配置 →":"Open Personal settings →","CodeBuddy 使用个人配置中保存的 API Key":"CodeBuddy uses the API key saved in Personal settings","到个人配置补充 CodeBuddy API Key":"Add a CodeBuddy API key in Personal settings","到个人配置补充 Codex API Key":"Add a Codex API key in Personal settings","到个人配置补充 Claude Code API Key":"Add a Claude Code API key in Personal settings","将使用个人配置中的 API 凭证":"The API credentials in Personal settings will be used","已切换;请先到个人配置补充该 CLI 的 API Key":"Switched. Add this CLI's API key in Personal settings first","当前以访客身份访问平台。登录后可在左侧「个人配置」配置 GitHub Git Token 和 CodeBuddy API Key。":"You are browsing as a guest. After signing in, set your GitHub Git token and CodeBuddy API key under “Personal settings” on the left.","连接后可选择自己的仓库;公开仓库也可直接填写地址。访问令牌可在个人配置中设置。":"Once connected you can pick your own repositories; public repositories can also be entered by URL. The access token is set in Personal settings.","去个人配置配置":"Set it in Personal settings","使用项目已绑定的仓库。访问私有仓库或推送代码时需要在个人配置中配置 GitHub Token;未绑定仓库时可在任务工作区直接运行。":"Uses the repositories bound to the project. Private repositories and pushing code need a GitHub token in Personal settings; without a bound repository the run works directly in the task workspace.","请检查个人配置中的 CodeBuddy API Key 配置或网络状态后重新评测。":"Check the CodeBuddy API key in Personal settings and your network, then run the evaluation again.","请先在个人配置中配置自己的 CodeBuddy API Key":"Set your own CodeBuddy API key in Personal settings first","请先配置个人 CodeBuddy API Key":"Set your personal CodeBuddy API key first","未配置个人 CodeBuddy API Key 时只能使用平台管理员允许的模型":"Without a personal CodeBuddy API key you can only use the models a platform admin allowed","要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key":"To use other models, set your own CodeBuddy API key in Personal settings first"});+Object.assign(window.LF_I18N_EN,{+"AI 对话的 OpenCode 模型与以 OpenCode 运行的 SOP 节点":"OpenCode models in AI chat, and SOP steps that run on OpenCode",+"AI 对话的 Cursor CLI 模型与以 Cursor CLI 运行的 SOP 节点":"Cursor CLI models in AI chat, and SOP steps that run on Cursor CLI",+"AI 对话的 Antigravity 模型与以 Antigravity 运行的 SOP 节点":"Antigravity models in AI chat, and SOP steps that run on Antigravity",+"AI 对话的 Kimi Code 模型与以 Kimi Code 运行的 SOP 节点":"Kimi Code models in AI chat, and SOP steps that run on Kimi Code",+"AI 对话的 Pi 模型与以 Pi 运行的 SOP 节点":"Pi models in AI chat, and SOP steps that run on Pi",+"AI 对话的 DeepSeek Harness 模型与以 DeepSeek Harness 运行的 SOP 节点":"DeepSeek Harness models in AI chat, and SOP steps that run on DeepSeek Harness"+});diff --git a/web/images/credentials/cursor.svg b/web/images/credentials/cursor.svgnew file mode 100644index 00000000..61303fbc--- /dev/null+++ b/web/images/credentials/cursor.svg@@ -0,0 +1 @@+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cursor</title><path d="M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23"/></svg>\ No newline at end of filediff --git a/web/images/credentials/opencode.svg b/web/images/credentials/opencode.svgnew file mode 100644index 00000000..1e0da06f--- /dev/null+++ b/web/images/credentials/opencode.svg@@ -0,0 +1 @@+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenCode</title><path d="M22 24H2V0h20zM17 4.8H7v14.4h10z"/></svg>\ No newline at end of filediff --git a/web/images/credentials/pi.svg b/web/images/credentials/pi.svgnew file mode 100644index 00000000..6c81d7e2--- /dev/null+++ b/web/images/credentials/pi.svg@@ -0,0 +1 @@+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Pi</title><path d="M3 4.5h18v3h-3.2v8.6c0 .9.4 1.3 1.1 1.3.5 0 .9-.1 1.3-.3l.6 2.8c-.7.4-1.7.6-2.8.6-2.4 0-3.6-1.4-3.6-4V7.5H9.6V20H6.4V7.5H3z"/></svg>diff --git a/web/syntax_test.go b/web/syntax_test.goindex 1d035b5b..7f4051a5 100644--- a/web/syntax_test.go+++ b/web/syntax_test.go@@ -793,18 +793,18 @@ const count = (html, needle) => html.split(needle).length - 1;// Two groups list all four kinds in a fixed order.assert.deepEqual(cred.CREDENTIAL_GROUPS.map(g => g.id), ['platform', 'model']);assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'platform').map(k => k.key), ['gitToken']);-assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'model').map(k => k.key), ['codeBuddyApiKey', 'codexApiKey', 'claudeCodeApiKey']);+assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'model').map(k => k.key), ['codeBuddyApiKey', 'codexApiKey', 'claudeCodeApiKey', 'agentCli.opencode', 'agentCli.cursor', 'agentCli.agy', 'agentCli.kimi', 'agentCli.pi', 'agentCli.dsh']);// Progress, next-step hint, filter counts and per-group counts.const html = credentialPanelHTML(user);-assert.ok(html.includes('<b>2</b> / 4 已配置'));+assert.ok(html.includes('<b>2</b> / 10 已配置'));assert.ok(html.includes('data-credential-setup="codeBuddyApiKey"'), 'next step follows Git → CodeBuddy');-assert.ok(html.includes('1 / 1') && html.includes('1 / 3'));-assert.ok(html.includes('已配置<span>2</span>') && html.includes('未配置<span>2</span>'));-assert.equal(count(html, 'data-credential-row='), 4);+assert.ok(html.includes('1 / 1') && html.includes('1 / 9'));+assert.ok(html.includes('已配置<span>2</span>') && html.includes('未配置<span>8</span>'));+assert.equal(count(html, 'data-credential-row='), 10);assert.ok(!html.includes('credential-grid') && !html.includes('credential-savebar') && !html.includes('userCredentialForm'));// Unconfigured rows only offer 去配置; configured rows carry an inline editor with delete.-assert.equal(count(html, 'data-credential-act="setup"'), 2);+assert.equal(count(html, 'data-credential-act="setup"'), 8);assert.equal(count(html, 'credential-editor-form'), 2);assert.equal(count(html, 'data-credential-act="delete"'), 2);for (const key of ['codeBuddyApiKey', 'claudeCodeApiKey']) {