diff --git a/.env.example b/.env.example index 6ea6e3cc5..557c1bce8 100644 --- a/.env.example +++ b/.env.example @@ -29,6 +29,11 @@ ARTEX_LLM_BASE_URL= ARTEX_LLM_PROXY= # Allow the UI model list to reach a local Ollama, e.g. host.docker.internal:11434 ARTEX_LLM_PRIVATE_ENDPOINTS= +# Claude Code CLI as the LLM (ARTEX_LLM_PROVIDER=claude-code, or a "Claude Code CLI" +# profile in the UI). Uses a Claude subscription: paste the output of `claude setup-token` +# here, or in the profile's token field. Concurrent CLI processes default to 4. +CLAUDE_CODE_OAUTH_TOKEN= +# ARTEX_CLAUDE_CODE_MAX_PROCS=4 # Untrusted-output boundary. Frames every tool output between nonce-tagged markers so # the model treats it as data, not instructions. On by default (unset or empty = on); diff --git a/Dockerfile b/Dockerfile index a29b48666..b815985bf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -274,6 +274,10 @@ RUN npm install -g "@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}" "@playwright/cli@ && playwright install --with-deps chromium \ && "$(npm root -g)/@playwright/mcp/node_modules/.bin/playwright-core" install chromium \ && rm -rf /var/lib/apt/lists/* +# Claude Code CLI for "claude-code" LLM profiles (agent/claude_code.go): the +# server runs it as the model, with every built-in tool disabled. +ARG CLAUDE_CODE_VERSION=2.1.332 +RUN npm install -g "@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}" && claude --version # Agent processes run as the executor with HOME and XDG_CACHE_HOME in the data # directory (server/execpriv_unix.go); the browsers installed above stay in root's # cache, which /root's 0711 lets the executor reach. diff --git a/README.md b/README.md index e59e922a3..75c69fde7 100644 --- a/README.md +++ b/README.md @@ -502,7 +502,7 @@ runtime supports it. **LLM**: `export ANTHROPIC_API_KEY=sk-...` (or `OPENAI_API_KEY`), or configure it in the UI's "LLM Configuration" page, which can also add a local Ollama server as a keyless provider (format "Ollama", default base URL `http://127.0.0.1:11434/v1`). Optional: -`ARTEX_LLM_PROVIDER` (`anthropic | openai | openai-responses | ollama | bedrock-gateway`), `ARTEX_LLM_MODEL`, +`ARTEX_LLM_PROVIDER` (`anthropic | openai | openai-responses | ollama | bedrock-gateway | claude-code`), `ARTEX_LLM_MODEL`, `ARTEX_LLM_BASE_URL`, `ARTEX_LLM_PROXY`. **Base URL gotcha**: for the Anthropic format, enter the host **without** `/v1` (for example @@ -536,6 +536,32 @@ For environment-based setup, set `ARTEX_LLM_PROVIDER=bedrock-gateway`, `ARTEX_LLM_BASE_URL`, `ARTEX_LLM_MODEL`, and `ARTEX_LLM_API_KEY`. Optional `ARTEX_LLM_CUSTOM_HEADERS` uses the same newline-separated `Name: Value` format. +**Claude Code CLI**: select **Claude Code CLI** in System → LLM to drive the agents with +the `claude` binary instead of an HTTP endpoint, using a Claude subscription. ARTEX keeps its +own agent loop: each model turn runs one `claude -p` process with every built-in Claude Code +tool, MCP server, settings file and slash command disabled, so the CLI only generates text. +ARTEX's tool definitions go into the system prompt with a JSON reply protocol, and the reply's +tool calls come back to ARTEX as ordinary `tool_use` blocks, so tools still run under ARTEX's +executor, permissions and transcripts. The process gets a minimal environment, never the +server's secrets. + +- **Model**: an alias (`opus`, `sonnet`, `haiku`; the ↻ button lists them) or a full model ID. + The default is `sonnet`. Base URL does not apply. +- **Login**: run `claude setup-token` on any machine and paste the token into the profile's + **Token** field (stored encrypted), or set `CLAUDE_CODE_OAUTH_TOKEN` in `.env`. Without a token, + the CLI uses its own login: in Docker, `docker compose exec artex sh -c + 'CLAUDE_CONFIG_DIR=/app/keys/claude-code claude'` and `/login` once; the config dir lives in + the root-only keys volume. An `sk-ant-api…` key is passed as `ANTHROPIC_API_KEY` instead. +- **Limits**: `ARTEX_CLAUDE_CODE_MAX_PROCS` (default 4) caps concurrent CLI processes, + `ARTEX_CLAUDE_CODE_TIMEOUT` (default `10m`) caps one turn, and `ARTEX_CLAUDE_CODE_BIN` points at + a binary that is not `claude` on `PATH`. Each turn resends the whole conversation, there is no + token-by-token streaming, and images in tool results are replaced by a placeholder. Usage + counts against the subscription's limits; a usage-limit reply is reported as HTTP 429, and a + missing login as 401. + +For environment-based setup, set `ARTEX_LLM_PROVIDER=claude-code`, optionally +`ARTEX_LLM_MODEL` and `CLAUDE_CODE_OAUTH_TOKEN`. + **Task archive storage**: local disk by default. Set `ARTEX_ARCHIVE_STORAGE=s3` to store cold task packages in an S3-compatible bucket and release their local package space after verification. Existing local archives remain usable. See diff --git a/agent/claude_code.go b/agent/claude_code.go new file mode 100644 index 000000000..14a54e75f --- /dev/null +++ b/agent/claude_code.go @@ -0,0 +1,742 @@ +package agent + +// Claude Code CLI provider ("claude-code" format). +// +// The profile drives agents with the local `claude` binary in headless print +// mode instead of an HTTP endpoint, so a Claude subscription logged in through +// Claude Code (or a `claude setup-token` OAuth token) can power ARTEX. +// +// Norma still speaks Anthropic Messages: NewProvider points it at a placeholder +// base URL and swaps the HTTP transport for claudeCodeTransport, which answers +// each /v1/messages request by running one `claude -p` process. ARTEX keeps its +// own agent loop, tools, permissions and transcripts; the CLI is only the model: +// +// - every built-in Claude Code tool, MCP server, setting source and slash +// command is disabled, so the process can do nothing but produce text; +// - ARTEX's tool definitions go into the system prompt with a small JSON reply +// protocol, and the reply's tool calls are turned back into tool_use blocks; +// - the conversation (text, tool calls, tool results) is rendered into the +// prompt on stdin, because each process is a fresh, stateless session. +// +// The process gets a minimal environment, never the server's: no database +// password, secret key or LLM key of another profile reaches it. + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/Autumn-27/norma/llm" +) + +// FormatClaudeCode marks a profile served by the local Claude Code CLI. +const FormatClaudeCode llm.Format = "claude-code" + +// claudeCodeBaseURL is the placeholder endpoint Norma is pointed at. It is never +// dialed: claudeCodeTransport answers every request itself. +const claudeCodeBaseURL = "http://claude-code.invalid" + +// DefaultClaudeCodeModel is the model alias used when a profile names none. +const DefaultClaudeCodeModel = "sonnet" + +// ClaudeCodeModels is the model list offered by the UI's model picker: the CLI's +// aliases, which always resolve to the current model of each family. +var ClaudeCodeModels = []string{"opus", "sonnet", "haiku"} + +// Environment knobs, read when a provider is built. +const ( + envClaudeCodeBin = "ARTEX_CLAUDE_CODE_BIN" // binary path; default "claude" on PATH + envClaudeCodeConfigDir = "ARTEX_CLAUDE_CODE_CONFIG_DIR" // CLAUDE_CONFIG_DIR for the CLI; empty = the server user's own + envClaudeCodeMaxProcs = "ARTEX_CLAUDE_CODE_MAX_PROCS" // concurrent CLI processes; default 4 + envClaudeCodeTimeout = "ARTEX_CLAUDE_CODE_TIMEOUT" // per-call cap (Go duration); default 10m +) + +const ( + defaultClaudeCodeMaxProcs = 4 + defaultClaudeCodeTimeout = 10 * time.Minute + // claudeCodeMaxOutput bounds what is read from one CLI process. + claudeCodeMaxOutput = 16 << 20 +) + +// claudeCodeSlots caps concurrent CLI processes across every claude-code +// provider in the process: each one is a full Node runtime. +var ( + claudeCodeSlotsOnce sync.Once + claudeCodeSlots chan struct{} +) + +func claudeCodeSemaphore() chan struct{} { + claudeCodeSlotsOnce.Do(func() { + n := defaultClaudeCodeMaxProcs + if v, err := strconv.Atoi(strings.TrimSpace(os.Getenv(envClaudeCodeMaxProcs))); err == nil && v > 0 { + n = v + } + claudeCodeSlots = make(chan struct{}, n) + }) + return claudeCodeSlots +} + +// IsKeylessFormat reports whether a stored profile format runs without an API +// key: Ollama (a local server) and Claude Code (the CLI can use its own login). +func IsKeylessFormat(format string) bool { + switch strings.TrimSpace(format) { + case string(FormatOllama), string(FormatClaudeCode): + return true + } + return false +} + +// claudeCodeTransport answers Norma's Anthropic Messages requests by running the +// Claude Code CLI. It never opens a network connection itself. +type claudeCodeTransport struct { + bin string + model string + token string // optional: OAuth token (sk-ant-oat…) or API key (sk-ant-api…) + configDir string // optional CLAUDE_CONFIG_DIR + proxy string // optional outbound proxy for the CLI + timeout time.Duration + slots chan struct{} + // run executes the CLI; replaced in tests. + run func(ctx context.Context, t *claudeCodeTransport, args []string, env []string, dir string, stdin []byte) ([]byte, []byte, error) +} + +func newClaudeCodeTransport(c Config) (*claudeCodeTransport, error) { + model := strings.TrimSpace(c.Model) + if model == "" { + model = DefaultClaudeCodeModel + } + if strings.HasPrefix(model, "-") || strings.ContainsAny(model, " \t\r\n") { + return nil, errors.New("claude-code: invalid model name") + } + bin := strings.TrimSpace(os.Getenv(envClaudeCodeBin)) + if bin == "" { + bin = "claude" + } + timeout := defaultClaudeCodeTimeout + if v, err := time.ParseDuration(strings.TrimSpace(os.Getenv(envClaudeCodeTimeout))); err == nil && v > 0 { + timeout = v + } + token := strings.TrimSpace(c.APIKey) + if !validHeaderValue(token) && token != "" { + return nil, errors.New("claude-code: the token contains invalid characters") + } + return &claudeCodeTransport{ + bin: bin, + model: model, + token: token, + configDir: strings.TrimSpace(os.Getenv(envClaudeCodeConfigDir)), + proxy: strings.TrimSpace(c.Proxy), + timeout: timeout, + slots: claudeCodeSemaphore(), + run: runClaudeCodeProcess, + }, nil +} + +// claudeCodeRequest is the part of an Anthropic Messages request the adapter uses. +type claudeCodeRequest struct { + System json.RawMessage `json:"system"` + Messages []claudeCodeMessage `json:"messages"` + Tools []claudeCodeTool `json:"tools"` + Stream bool `json:"stream"` + OutputConfig *struct { + Effort string `json:"effort"` + } `json:"output_config"` +} + +type claudeCodeMessage struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` +} + +type claudeCodeBlock struct { + Type string `json:"type"` + Text string `json:"text"` + ID string `json:"id"` + Name string `json:"name"` + Input json.RawMessage `json:"input"` + ToolUseID string `json:"tool_use_id"` + Content json.RawMessage `json:"content"` + IsError bool `json:"is_error"` +} + +type claudeCodeTool struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema json.RawMessage `json:"input_schema"` +} + +// claudeCodeResult is the CLI's --output-format json document. +type claudeCodeResult struct { + Type string `json:"type"` + Subtype string `json:"subtype"` + IsError bool `json:"is_error"` + Result string `json:"result"` + StopReason string `json:"stop_reason"` + APIErrorStatus *int `json:"api_error_status"` + Usage struct { + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + CacheReadInputTokens int `json:"cache_read_input_tokens"` + CacheCreationInputTokens int `json:"cache_creation_input_tokens"` + } `json:"usage"` +} + +// claudeCodeToolCall is one entry of the reply protocol's tool_calls array. +type claudeCodeToolCall struct { + Name string `json:"name"` + Input json.RawMessage `json:"input"` +} + +func (t *claudeCodeTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL == nil || req.URL.Host != "claude-code.invalid" || !strings.HasSuffix(req.URL.Path, "/v1/messages") { + return nil, errors.New("claude-code: unexpected request destination") + } + raw, err := io.ReadAll(req.Body) + _ = req.Body.Close() + if err != nil { + return nil, err + } + var body claudeCodeRequest + if err := json.Unmarshal(raw, &body); err != nil { + return claudeCodeError(req, http.StatusBadRequest, "invalid_request_error", "claude-code: decode request: "+err.Error()), nil + } + systemPrompt, err := renderClaudeCodeSystem(body.System, body.Tools) + if err != nil { + return claudeCodeError(req, http.StatusBadRequest, "invalid_request_error", "claude-code: "+err.Error()), nil + } + prompt, err := renderClaudeCodePrompt(body.Messages, len(body.Tools) > 0) + if err != nil { + return claudeCodeError(req, http.StatusBadRequest, "invalid_request_error", "claude-code: "+err.Error()), nil + } + effort := "" + if body.OutputConfig != nil { + switch e := strings.TrimSpace(body.OutputConfig.Effort); e { + case "low", "medium", "high", "xhigh", "max": + effort = e + } + } + + ctx := req.Context() + select { + case t.slots <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-t.slots }() + + res, status, msg := t.call(ctx, systemPrompt, prompt, effort) + if ctx.Err() != nil { + return nil, ctx.Err() + } + if status != 0 { + errType := "api_error" + switch status { + case http.StatusUnauthorized, http.StatusForbidden: + errType = "authentication_error" + case http.StatusTooManyRequests: + errType = "rate_limit_error" + } + return claudeCodeError(req, status, errType, msg), nil + } + + content, stopReason := claudeCodeContent(res.Result, body.Tools) + if res.StopReason == "max_tokens" && stopReason != "tool_use" { + stopReason = "max_tokens" + } + usage := map[string]int{ + "input_tokens": res.Usage.InputTokens, + "output_tokens": res.Usage.OutputTokens, + "cache_read_input_tokens": res.Usage.CacheReadInputTokens, + "cache_creation_input_tokens": res.Usage.CacheCreationInputTokens, + } + msgID := "msg_cc_" + randomHex(12) + if body.Stream { + return claudeCodeSSE(req, msgID, t.model, content, stopReason, usage), nil + } + out, err := json.Marshal(map[string]any{ + "id": msgID, "type": "message", "role": "assistant", "model": t.model, + "content": content, "stop_reason": stopReason, "stop_sequence": nil, "usage": usage, + }) + if err != nil { + return nil, err + } + return claudeCodeResponse(req, http.StatusOK, "application/json", out), nil +} + +// call runs one CLI process. A non-zero status means failure, with msg as the +// error text; otherwise res holds the CLI's result document. +func (t *claudeCodeTransport) call(ctx context.Context, systemPrompt, prompt, effort string) (res claudeCodeResult, status int, msg string) { + if t.configDir != "" { + // The CLI keeps its login and state here; private to the server user. + if err := os.MkdirAll(t.configDir, 0o700); err != nil { + return res, http.StatusInternalServerError, "claude-code: create config dir: " + err.Error() + } + } + dir, err := os.MkdirTemp("", "artex-claude-code-") + if err != nil { + return res, http.StatusInternalServerError, "claude-code: create work dir: " + err.Error() + } + defer os.RemoveAll(dir) + spFile := filepath.Join(dir, "system-prompt.txt") + if err := os.WriteFile(spFile, []byte(systemPrompt), 0o600); err != nil { + return res, http.StatusInternalServerError, "claude-code: write system prompt: " + err.Error() + } + args := []string{ + "-p", + "--output-format", "json", + "--model", t.model, + "--system-prompt-file", spFile, + // Nothing but text generation: no built-in tools, no MCP servers, no + // user/project/local settings (hooks, permissions), no slash commands + // or skills, and nothing written to the session store. + "--tools", "", + "--strict-mcp-config", + "--setting-sources", "", + "--disable-slash-commands", + "--no-session-persistence", + } + if effort != "" { + args = append(args, "--effort", effort) + } + + callCtx, cancel := context.WithTimeout(ctx, t.timeout) + defer cancel() + stdout, stderr, runErr := t.run(callCtx, t, args, t.env(dir), dir, []byte(prompt)) + if ctx.Err() != nil { + return res, http.StatusRequestTimeout, ctx.Err().Error() + } + if callCtx.Err() != nil { + return res, http.StatusGatewayTimeout, fmt.Sprintf("claude-code: the CLI did not answer within %s", t.timeout) + } + if err := json.Unmarshal(bytes.TrimSpace(stdout), &res); err != nil || res.Type != "result" { + detail := t.scrub(clipBody(string(stderr) + " " + string(stdout))) + if runErr != nil { + var execErr *exec.Error + if errors.As(runErr, &execErr) || errors.Is(runErr, fs.ErrNotExist) || errors.Is(runErr, fs.ErrPermission) { + return res, http.StatusBadGateway, fmt.Sprintf("claude-code: cannot run %q: %v (install Claude Code or set %s)", t.bin, runErr, envClaudeCodeBin) + } + return res, http.StatusBadGateway, fmt.Sprintf("claude-code: the CLI failed (%v): %s", runErr, detail) + } + return res, http.StatusBadGateway, "claude-code: unexpected CLI output: " + detail + } + if res.IsError || res.Subtype != "success" { + text := t.scrub(strings.TrimSpace(res.Result)) + if text == "" { + text = res.Subtype + } + return res, claudeCodeErrorStatus(res.APIErrorStatus, text), "claude-code: " + text + } + return res, 0, "" +} + +// claudeCodeErrorStatus picks the HTTP status for a failed CLI run, so Norma's +// retry loop and ARTEX's failover treat it like the matching API error. +func claudeCodeErrorStatus(apiStatus *int, text string) int { + if apiStatus != nil && *apiStatus >= 400 && *apiStatus <= 599 { + return *apiStatus + } + lower := strings.ToLower(text) + switch { + case strings.Contains(lower, "not logged in"), strings.Contains(lower, "/login"), + strings.Contains(lower, "invalid api key"), strings.Contains(lower, "oauth token"), + strings.Contains(lower, "authentication"): + return http.StatusUnauthorized + case strings.Contains(lower, "usage limit"), strings.Contains(lower, "limit reached"), + strings.Contains(lower, "hit your limit"): + return http.StatusTooManyRequests + } + return http.StatusBadGateway +} + +// env is the CLI's whole environment: never os.Environ(), which holds the +// server's own secrets until the startup scrub and the operator's shell values. +func (t *claudeCodeTransport) env(workDir string) []string { + env := []string{ + "PATH=" + claudeCodePath(), + "LANG=C.UTF-8", + "TMPDIR=" + workDir, + "DISABLE_AUTOUPDATER=1", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", + } + if home := os.Getenv("HOME"); home != "" { + env = append(env, "HOME="+home) + } + if user := os.Getenv("USER"); user != "" { + env = append(env, "USER="+user) + } + if t.configDir != "" { + env = append(env, "CLAUDE_CONFIG_DIR="+t.configDir) + } else if dir := os.Getenv("CLAUDE_CONFIG_DIR"); dir != "" { + env = append(env, "CLAUDE_CONFIG_DIR="+dir) + } + switch { + case strings.HasPrefix(t.token, "sk-ant-api"): + env = append(env, "ANTHROPIC_API_KEY="+t.token) + case t.token != "": + env = append(env, "CLAUDE_CODE_OAUTH_TOKEN="+t.token) + } + if t.proxy != "" { + env = append(env, "HTTPS_PROXY="+t.proxy, "HTTP_PROXY="+t.proxy) + } + return env +} + +func claudeCodePath() string { + if p := os.Getenv("PATH"); p != "" { + return p + } + return "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +} + +// scrub removes the profile token from text that may reach logs or the UI. +func (t *claudeCodeTransport) scrub(s string) string { + if t.token != "" { + s = strings.ReplaceAll(s, t.token, "[redacted]") + } + return s +} + +func runClaudeCodeProcess(ctx context.Context, t *claudeCodeTransport, args []string, env []string, dir string, stdin []byte) ([]byte, []byte, error) { + cmd := exec.CommandContext(ctx, t.bin, args...) + cmd.Env = env + cmd.Dir = dir + cmd.Stdin = bytes.NewReader(stdin) + stdout := &limitedBuffer{max: claudeCodeMaxOutput} + stderr := &limitedBuffer{max: 64 << 10} + cmd.Stdout, cmd.Stderr = stdout, stderr + cmd.WaitDelay = 5 * time.Second + err := cmd.Run() + return stdout.Bytes(), stderr.Bytes(), err +} + +// limitedBuffer keeps the first max bytes written and drops the rest. +type limitedBuffer struct { + bytes.Buffer + max int +} + +func (b *limitedBuffer) Write(p []byte) (int, error) { + if room := b.max - b.Len(); room > 0 { + if len(p) > room { + b.Buffer.Write(p[:room]) + } else { + b.Buffer.Write(p) + } + } + return len(p), nil +} + +const claudeCodeProtocol = `# Reply protocol + +You are the model behind an API adapter. You cannot run tools yourself: the +caller runs them and sends the results back in the next turn. + +The tools you may call are listed below as JSON (name, description, input JSON Schema): + + +%s + + +Answer with exactly ONE JSON object and nothing else (no code fence, no prose around it): + +{"text": "", "tool_calls": [{"name": "", "input": {}}]} + +Rules: +- Only use tool names from the list above; each input must satisfy that tool's schema. +- Several independent calls may share one reply; they run in the order given. +- When you need no tool, or the work is finished, send "tool_calls": []. +- Tool results arrive as elements in the next user turn.` + +// renderClaudeCodeSystem joins the request's system prompt and, when tools are +// offered, appends the tool list and reply protocol. +func renderClaudeCodeSystem(system json.RawMessage, tools []claudeCodeTool) (string, error) { + var sb strings.Builder + text, err := claudeCodeText(system) + if err != nil { + return "", fmt.Errorf("decode system prompt: %w", err) + } + sb.WriteString(strings.TrimSpace(text)) + if len(tools) > 0 { + list, err := json.MarshalIndent(tools, "", " ") + if err != nil { + return "", err + } + if sb.Len() > 0 { + sb.WriteString("\n\n") + } + fmt.Fprintf(&sb, claudeCodeProtocol, list) + } + if sb.Len() == 0 { + sb.WriteString("You are a helpful assistant.") + } + return sb.String(), nil +} + +// renderClaudeCodePrompt renders the whole conversation as one prompt, since +// each CLI process starts a fresh session. +func renderClaudeCodePrompt(msgs []claudeCodeMessage, withTools bool) (string, error) { + if len(msgs) == 0 { + return "", errors.New("request has no messages") + } + var sb strings.Builder + sb.WriteString("\n") + for _, m := range msgs { + role := m.Role + if role != "assistant" { + role = "user" + } + blocks, err := decodeBlocks(m.Content) + if err != nil { + return "", fmt.Errorf("decode %s message: %w", role, err) + } + fmt.Fprintf(&sb, "\n", role) + for _, b := range blocks { + switch b.Type { + case "text": + if s := strings.TrimSpace(b.Text); s != "" { + sb.WriteString(s) + sb.WriteString("\n") + } + case "tool_use": + in := b.Input + if len(bytes.TrimSpace(in)) == 0 { + in = json.RawMessage("{}") + } + fmt.Fprintf(&sb, "%s\n", b.ID, b.Name, compactJSON(in)) + case "tool_result": + text, err := claudeCodeText(b.Content) + if err != nil { + return "", fmt.Errorf("decode tool result: %w", err) + } + fmt.Fprintf(&sb, "\n%s\n\n", b.ToolUseID, b.IsError, strings.TrimSpace(text)) + case "image", "document": + fmt.Fprintf(&sb, "[%s omitted: not supported by the claude-code adapter]\n", b.Type) + } + // thinking / redacted_thinking blocks belong to another session's + // signatures and are dropped. + } + sb.WriteString("\n") + } + sb.WriteString("\n\n") + if withTools { + sb.WriteString("Write the assistant's next turn now, as one JSON object following the reply protocol.") + } else { + sb.WriteString("Write the assistant's next turn now.") + } + return sb.String(), nil +} + +// decodeBlocks accepts content as a plain string or an array of blocks. +func decodeBlocks(raw json.RawMessage) ([]claudeCodeBlock, error) { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || string(raw) == "null" { + return nil, nil + } + if raw[0] == '"' { + var s string + if err := json.Unmarshal(raw, &s); err != nil { + return nil, err + } + return []claudeCodeBlock{{Type: "text", Text: s}}, nil + } + var blocks []claudeCodeBlock + if err := json.Unmarshal(raw, &blocks); err != nil { + return nil, err + } + return blocks, nil +} + +// claudeCodeText flattens string-or-blocks content to text. +func claudeCodeText(raw json.RawMessage) (string, error) { + blocks, err := decodeBlocks(raw) + if err != nil { + return "", err + } + var parts []string + for _, b := range blocks { + switch b.Type { + case "text": + parts = append(parts, b.Text) + case "image", "document": + parts = append(parts, "["+b.Type+" omitted]") + } + } + return strings.Join(parts, "\n"), nil +} + +func compactJSON(raw json.RawMessage) string { + var buf bytes.Buffer + if err := json.Compact(&buf, raw); err != nil { + return string(raw) + } + return buf.String() +} + +// claudeCodeContent turns the CLI's reply text into Anthropic content blocks. +// Without tools the reply is plain text. With tools it should be the protocol's +// JSON object; a reply that is not falls back to plain text, so a model that +// answers in prose still ends its turn instead of failing the request. +func claudeCodeContent(result string, tools []claudeCodeTool) ([]map[string]any, string) { + result = strings.TrimSpace(result) + if len(tools) == 0 { + return textContent(result), "end_turn" + } + reply, ok := parseClaudeCodeReply(result) + if !ok { + return textContent(result), "end_turn" + } + content := textContent(strings.TrimSpace(reply.Text)) + stopReason := "end_turn" + for _, call := range reply.ToolCalls { + name := strings.TrimSpace(call.Name) + if name == "" { + continue + } + content = append(content, map[string]any{ + "type": "tool_use", "id": "toolu_cc_" + randomHex(12), "name": name, "input": toolInput(call.Input), + }) + stopReason = "tool_use" + } + return content, stopReason +} + +func textContent(s string) []map[string]any { + if s == "" { + return []map[string]any{} + } + return []map[string]any{{"type": "text", "text": s}} +} + +type claudeCodeReply struct { + Text string `json:"text"` + ToolCalls []claudeCodeToolCall `json:"tool_calls"` +} + +// parseClaudeCodeReply decodes the protocol object, tolerating a code fence or +// prose around it. +func parseClaudeCodeReply(s string) (claudeCodeReply, bool) { + candidates := []string{s} + if inner, ok := stripCodeFence(s); ok { + candidates = append(candidates, inner) + } + if i, j := strings.Index(s, "{"), strings.LastIndex(s, "}"); i >= 0 && j > i { + candidates = append(candidates, s[i:j+1]) + } + for _, c := range candidates { + var probe map[string]json.RawMessage + if json.Unmarshal([]byte(c), &probe) != nil { + continue + } + _, hasText := probe["text"] + _, hasCalls := probe["tool_calls"] + if !hasText && !hasCalls { + continue + } + var r claudeCodeReply + if json.Unmarshal([]byte(c), &r) == nil { + return r, true + } + } + return claudeCodeReply{}, false +} + +func stripCodeFence(s string) (string, bool) { + s = strings.TrimSpace(s) + if !strings.HasPrefix(s, "```") { + return "", false + } + s = strings.TrimPrefix(s, "```") + if nl := strings.IndexByte(s, '\n'); nl >= 0 { + s = s[nl+1:] + } + s = strings.TrimSpace(s) + s = strings.TrimSuffix(s, "```") + return strings.TrimSpace(s), true +} + +// toolInput normalizes a tool call's input to a JSON object: a string holding +// JSON is decoded, anything that is not an object becomes {}. +func toolInput(raw json.RawMessage) json.RawMessage { + raw = bytes.TrimSpace(raw) + if len(raw) > 0 && raw[0] == '"' { + var s string + if json.Unmarshal(raw, &s) == nil { + raw = bytes.TrimSpace([]byte(s)) + } + } + var obj map[string]json.RawMessage + if len(raw) == 0 || json.Unmarshal(raw, &obj) != nil { + return json.RawMessage("{}") + } + return json.RawMessage(compactJSON(raw)) +} + +// claudeCodeSSE renders a finished message as an Anthropic SSE stream. +func claudeCodeSSE(req *http.Request, id, model string, content []map[string]any, stopReason string, usage map[string]int) *http.Response { + var buf bytes.Buffer + event := func(name string, data any) { + b, _ := json.Marshal(data) + fmt.Fprintf(&buf, "event: %s\ndata: %s\n\n", name, b) + } + event("message_start", map[string]any{"type": "message_start", "message": map[string]any{ + "id": id, "type": "message", "role": "assistant", "model": model, "content": []any{}, + "stop_reason": nil, "stop_sequence": nil, "usage": usage, + }}) + for i, block := range content { + switch block["type"] { + case "text": + event("content_block_start", map[string]any{"type": "content_block_start", "index": i, "content_block": map[string]any{"type": "text", "text": ""}}) + event("content_block_delta", map[string]any{"type": "content_block_delta", "index": i, "delta": map[string]any{"type": "text_delta", "text": block["text"]}}) + case "tool_use": + event("content_block_start", map[string]any{"type": "content_block_start", "index": i, "content_block": map[string]any{"type": "tool_use", "id": block["id"], "name": block["name"], "input": map[string]any{}}}) + event("content_block_delta", map[string]any{"type": "content_block_delta", "index": i, "delta": map[string]any{"type": "input_json_delta", "partial_json": string(block["input"].(json.RawMessage))}}) + } + event("content_block_stop", map[string]any{"type": "content_block_stop", "index": i}) + } + event("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nil}, "usage": usage}) + event("message_stop", map[string]any{"type": "message_stop"}) + return claudeCodeResponse(req, http.StatusOK, "text/event-stream", buf.Bytes()) +} + +func claudeCodeError(req *http.Request, status int, errType, message string) *http.Response { + body, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": errType, "message": message}}) + return claudeCodeResponse(req, status, "application/json", body) +} + +func claudeCodeResponse(req *http.Request, status int, contentType string, body []byte) *http.Response { + h := make(http.Header) + h.Set("Content-Type", contentType) + return &http.Response{ + Status: fmt.Sprintf("%d %s", status, http.StatusText(status)), + StatusCode: status, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + Header: h, + Body: io.NopCloser(bytes.NewReader(body)), + ContentLength: int64(len(body)), + Request: req, + } +} + +func randomHex(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return strconv.FormatInt(time.Now().UnixNano(), 16) + } + return hex.EncodeToString(b) +} diff --git a/agent/claude_code_test.go b/agent/claude_code_test.go new file mode 100644 index 000000000..c474162b4 --- /dev/null +++ b/agent/claude_code_test.go @@ -0,0 +1,263 @@ +package agent + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/Autumn-27/norma/llm" +) + +// fakeClaudeCLI installs a shell script standing in for the claude binary. It +// records its arguments, environment, stdin and system prompt file under dir and +// prints dir/response.json, so tests drive the real exec path. +func fakeClaudeCLI(t *testing.T, response string) string { + t.Helper() + dir := t.TempDir() + script := `#!/bin/sh +D='` + dir + `' +: > "$D/args.txt" +sp="" +prev="" +for a in "$@"; do + printf '[%s]\n' "$a" >> "$D/args.txt" + if [ "$prev" = "--system-prompt-file" ]; then sp="$a"; fi + prev="$a" +done +env > "$D/env.txt" +cat > "$D/stdin.txt" +[ -n "$sp" ] && cp "$sp" "$D/system.txt" +echo x >> "$D/calls.txt" +cat "$D/response.json" +` + bin := filepath.Join(dir, "claude") + if err := os.WriteFile(bin, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "response.json"), []byte(response), 0o644); err != nil { + t.Fatal(err) + } + t.Setenv(envClaudeCodeBin, bin) + return dir +} + +func readFile(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func claudeResult(text string) string { + b, _ := json.Marshal(map[string]any{ + "type": "result", "subtype": "success", "is_error": false, "result": text, "stop_reason": "end_turn", + "usage": map[string]int{"input_tokens": 10, "output_tokens": 20, "cache_read_input_tokens": 3, "cache_creation_input_tokens": 5}, + }) + return string(b) +} + +func claudeCodeProvider(t *testing.T, token string) llm.Provider { + t.Helper() + c := ConfigFrom("claude-code", "opus", "", token, "") + c.Retry.ConnectAttempts = -1 + p, err := c.NewProvider() + if err != nil { + t.Fatal(err) + } + return p +} + +func toolRequest() llm.CompletionRequest { + return llm.CompletionRequest{ + System: []string{"You are the ARTEX worker."}, + Tools: []llm.ToolSchema{{Name: "Bash", Description: "Run a shell command", InputSchema: map[string]any{ + "type": "object", "properties": map[string]any{"command": map[string]any{"type": "string"}}, + }}}, + Messages: []llm.Message{ + llm.UserText("scan example.test"), + {Role: llm.RoleAssistant, Content: []llm.ContentBlock{ + llm.TextBlock("Checking DNS first."), + {Type: llm.BlockToolUse, ID: "toolu_1", Name: "Bash", Input: json.RawMessage(`{"command":"dig example.test"}`)}, + }}, + {Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText("toolu_1", "example.test. 300 IN A 10.0.0.1", false)}}, + }, + } +} + +func TestClaudeCodeConfig(t *testing.T) { + c := ConfigFrom("claude-code", "", "https://ignored.example", "", "") + if c.Format != FormatClaudeCode || c.Provider() != "claude-code" { + t.Fatalf("format = %q provider = %q", c.Format, c.Provider()) + } + if c.BaseURL != "" || c.Model != DefaultClaudeCodeModel { + t.Fatalf("base url = %q model = %q", c.BaseURL, c.Model) + } + if c.NeedsAPIKey() || !IsKeylessFormat("claude-code") || IsKeylessFormat("anthropic") { + t.Fatal("claude-code must be keyless and anthropic must not") + } + if _, err := ConfigFrom("claude-code", "--dangerous", "", "", "").NewProvider(); err == nil { + t.Fatal("a model name that looks like a flag must be rejected") + } +} + +func TestClaudeCodeFromEnv(t *testing.T) { + t.Setenv("ARTEX_LLM_PROVIDER", "claude-code") + t.Setenv("ARTEX_LLM_MODEL", "") + t.Setenv("ANTHROPIC_API_KEY", "sk-ant-api-should-not-be-used") + t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "sk-ant-oat-test") + c, ok := FromEnv() + if !ok || c.Format != FormatClaudeCode || c.APIKey != "sk-ant-oat-test" || c.Model != DefaultClaudeCodeModel { + t.Fatalf("FromEnv = %+v ok=%v", c, ok) + } +} + +func TestClaudeCodeToolCallRoundTrip(t *testing.T) { + dir := fakeClaudeCLI(t, claudeResult(`{"text":"Now the web port.","tool_calls":[{"name":"Bash","input":{"command":"curl -sI http://10.0.0.1"}}]}`)) + t.Setenv("ARTEX_PG_PASSWORD", "server-secret") + t.Setenv("ANTHROPIC_API_KEY", "sk-ant-api-server-key") + + msg, stop, usage, err := claudeCodeProvider(t, "sk-ant-oat-profile").Complete(context.Background(), toolRequest()) + if err != nil { + t.Fatal(err) + } + if stop != "tool_use" { + t.Fatalf("stop reason = %q", stop) + } + uses := msg.ToolUses() + if len(uses) != 1 || uses[0].Name != "Bash" || !strings.HasPrefix(uses[0].ID, "toolu_cc_") { + t.Fatalf("tool uses = %+v", uses) + } + var in map[string]string + if err := json.Unmarshal(uses[0].Input, &in); err != nil || in["command"] != "curl -sI http://10.0.0.1" { + t.Fatalf("tool input = %s (%v)", uses[0].Input, err) + } + if msg.Content[0].Text != "Now the web port." { + t.Fatalf("text = %+v", msg.Content[0]) + } + if usage.InputTokens != 18 || usage.OutputTokens != 20 || usage.CacheReadTokens != 3 { + t.Fatalf("usage = %+v", usage) + } + + args := readFile(t, filepath.Join(dir, "args.txt")) + for _, want := range []string{"[-p]", "[--tools]\n[]", "[--strict-mcp-config]", "[--setting-sources]\n[]", "[--disable-slash-commands]", "[--no-session-persistence]", "[--model]\n[opus]"} { + if !strings.Contains(args, want) { + t.Errorf("args missing %q:\n%s", want, args) + } + } + env := readFile(t, filepath.Join(dir, "env.txt")) + if strings.Contains(env, "server-secret") || strings.Contains(env, "sk-ant-api-server-key") { + t.Errorf("server secrets leaked into the CLI env:\n%s", env) + } + if !strings.Contains(env, "CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat-profile") { + t.Errorf("profile token missing from the CLI env:\n%s", env) + } + system := readFile(t, filepath.Join(dir, "system.txt")) + if !strings.HasPrefix(system, "You are the ARTEX worker.") || !strings.Contains(system, `"name": "Bash"`) || !strings.Contains(system, "tool_calls") { + t.Errorf("system prompt:\n%s", system) + } + stdin := readFile(t, filepath.Join(dir, "stdin.txt")) + for _, want := range []string{"scan example.test", `{"command":"dig example.test"}`, ``, "10.0.0.1"} { + if !strings.Contains(stdin, want) { + t.Errorf("prompt missing %q:\n%s", want, stdin) + } + } +} + +func TestClaudeCodeStream(t *testing.T) { + fakeClaudeCLI(t, claudeResult("```json\n{\"text\":\"\",\"tool_calls\":[{\"name\":\"Bash\",\"input\":\"{\\\"command\\\":\\\"id\\\"}\"}]}\n```")) + var sawTool bool + var toolJSON, stop string + for ev, err := range claudeCodeProvider(t, "").Stream(context.Background(), toolRequest()) { + if err != nil { + t.Fatal(err) + } + switch ev.Type { + case llm.SEToolUseStart: + sawTool = ev.ToolName == "Bash" + case llm.SEToolInputJSON: + toolJSON += ev.Text + case llm.SEMessageDelta: + stop = ev.StopReason + } + } + if !sawTool || toolJSON != `{"command":"id"}` || stop != "tool_use" { + t.Fatalf("tool=%v json=%q stop=%q", sawTool, toolJSON, stop) + } +} + +func TestClaudeCodeProseFallsBackToText(t *testing.T) { + fakeClaudeCLI(t, claudeResult("The scan is complete; no open ports.")) + msg, stop, _, err := claudeCodeProvider(t, "").Complete(context.Background(), toolRequest()) + if err != nil { + t.Fatal(err) + } + if stop != "end_turn" || len(msg.ToolUses()) != 0 || msg.Content[0].Text != "The scan is complete; no open ports." { + t.Fatalf("stop=%q content=%+v", stop, msg.Content) + } +} + +func TestClaudeCodeNoToolsIsPlainText(t *testing.T) { + dir := fakeClaudeCLI(t, claudeResult(`{"text":"looks like json"}`)) + req := llm.CompletionRequest{System: []string{"Reply OK."}, Messages: []llm.Message{llm.UserText("ping")}} + msg, _, _, err := claudeCodeProvider(t, "").Complete(context.Background(), req) + if err != nil { + t.Fatal(err) + } + if msg.Content[0].Text != `{"text":"looks like json"}` { + t.Fatalf("content = %+v", msg.Content) + } + if strings.Contains(readFile(t, filepath.Join(dir, "system.txt")), "Reply protocol") { + t.Fatal("the tool protocol must not be added when no tools are offered") + } +} + +func TestClaudeCodeAuthErrorIsNotRetried(t *testing.T) { + dir := fakeClaudeCLI(t, `{"type":"result","subtype":"success","is_error":true,"result":"Not logged in · Please run /login (token sk-ant-oat-secret)","api_error_status":null}`) + c := ConfigFrom("claude-code", "sonnet", "", "sk-ant-oat-secret", "") + p, err := c.NewProvider() // default retries: a 401 must still be sent once + if err != nil { + t.Fatal(err) + } + _, _, _, err = p.Complete(context.Background(), toolRequest()) + if err == nil || !strings.Contains(err.Error(), "status 401") || !strings.Contains(err.Error(), "Not logged in") { + t.Fatalf("err = %v", err) + } + if strings.Contains(err.Error(), "sk-ant-oat-secret") { + t.Fatalf("token leaked into the error: %v", err) + } + if calls := strings.Count(readFile(t, filepath.Join(dir, "calls.txt")), "x"); calls != 1 { + t.Fatalf("CLI ran %d times, want 1", calls) + } +} + +func TestClaudeCodeMissingBinary(t *testing.T) { + t.Setenv(envClaudeCodeBin, filepath.Join(t.TempDir(), "no-such-claude")) + _, _, _, err := claudeCodeProvider(t, "").Complete(context.Background(), toolRequest()) + if err == nil || !strings.Contains(err.Error(), "cannot run") { + t.Fatalf("err = %v", err) + } +} + +func TestParseClaudeCodeReply(t *testing.T) { + for _, in := range []string{ + `{"text":"a","tool_calls":[]}`, + "```json\n{\"text\":\"a\",\"tool_calls\":[]}\n```", + `Sure. {"text":"a","tool_calls":[]} done`, + } { + r, ok := parseClaudeCodeReply(in) + if !ok || r.Text != "a" { + t.Errorf("parse(%q) = %+v %v", in, r, ok) + } + } + if _, ok := parseClaudeCodeReply(`{"unrelated":1}`); ok { + t.Error("an object without text/tool_calls must not count as a reply") + } + if got := string(toolInput(json.RawMessage(`[1,2]`))); got != "{}" { + t.Errorf("non-object input = %s, want {}", got) + } +} diff --git a/agent/provider.go b/agent/provider.go index 96d92ee4d..96d290f12 100644 --- a/agent/provider.go +++ b/agent/provider.go @@ -175,8 +175,9 @@ func normalizeOllamaBaseURL(raw string) string { } // NeedsAPIKey reports whether this provider format requires an API key to be -// usable. Ollama (local server) is keyless; every cloud format needs one. -func (c Config) NeedsAPIKey() bool { return c.Format != FormatOllama } +// usable. Ollama (local server) and Claude Code (the CLI's own login) are +// keyless; every cloud format needs one. +func (c Config) NeedsAPIKey() bool { return !IsKeylessFormat(string(c.Format)) } // CompactionWindow returns the model context window in TOKENS for compaction // thresholds, resolved from the user-configured size (ContextWindowK). 0/unset → @@ -223,11 +224,12 @@ func compactionConfig(windowTokens int) *compaction.Config { // FromEnv resolves the LLM provider config: // -// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|ollama (default: inferred from keys) +// ARTEX_LLM_PROVIDER = anthropic|openai|openai-responses|ollama|bedrock-gateway|claude-code (default: inferred from keys) // ARTEX_LLM_MODEL = model id (default: per provider) // ARTEX_LLM_BASE_URL = endpoint (optional; ollama defaults to localhost:11434/v1) // ARTEX_LLM_PROXY = proxy URL (optional; http/https/socks5) // ANTHROPIC_API_KEY / OPENAI_API_KEY = credentials (unused for ollama) +// CLAUDE_CODE_OAUTH_TOKEN = optional token for claude-code (`claude setup-token`) func FromEnv() (Config, bool) { // Case- and space-insensitive: "Ollama" used to miss every case below and // fall through to anthropic, sending ANTHROPIC_API_KEY to the Ollama base URL. @@ -284,6 +286,15 @@ func FromEnv() (Config, bool) { if c.BaseURL == "" || c.Model == "" { return Config{}, false } + case "claude-code": + c.Format = FormatClaudeCode + // The CLI needs no endpoint. ANTHROPIC_API_KEY is deliberately not + // inherited: it would bill the API instead of the subscription login. + c.BaseURL = "" + c.APIKey = strings.TrimSpace(os.Getenv("CLAUDE_CODE_OAUTH_TOKEN")) + if c.Model == "" { + c.Model = DefaultClaudeCodeModel + } default: c.Format = llm.FormatAnthropic c.APIKey = anthKey @@ -339,6 +350,12 @@ func ConfigFrom(provider, model, baseURL, apiKey, proxy string) Config { c.Format = FormatBedrockGateway // No public-provider defaults: an absent URL, model or token fails closed. c.BaseURL = strings.TrimRight(strings.TrimSuffix(strings.TrimSuffix(c.BaseURL, "/invoke-with-response-stream"), "/invoke"), "/") + case "claude-code": + c.Format = FormatClaudeCode + c.BaseURL = "" // the CLI has no endpoint; a typed value is ignored + if c.Model == "" { + c.Model = DefaultClaudeCodeModel + } default: c.Format = llm.FormatAnthropic // provider appends "/v1/messages". @@ -361,7 +378,7 @@ func isFalsy(s string) bool { } // Provider returns the short provider name -// ("anthropic"/"openai"/"openai-responses"/"ollama"). +// ("anthropic"/"openai"/"openai-responses"/"ollama"/"bedrock-gateway"/"claude-code"). func (c Config) Provider() string { switch c.Format { case llm.FormatOpenAI: @@ -372,6 +389,8 @@ func (c Config) Provider() string { return "ollama" case FormatBedrockGateway: return "bedrock-gateway" + case FormatClaudeCode: + return "claude-code" } return "anthropic" } @@ -412,6 +431,20 @@ func (c Config) NewProvider() (llm.Provider, error) { client.Transport = qt client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } } + if wireFormat == FormatClaudeCode { + // Norma speaks Anthropic Messages to a placeholder URL; the transport + // answers by running the Claude Code CLI and never dials out itself. + ct, err := newClaudeCodeTransport(c) + if err != nil { + return nil, err + } + wireFormat = llm.FormatAnthropic + baseURL = claudeCodeBaseURL + apiKey = "claude-code" // placeholder x-api-key; the token travels in the CLI's env + qt := client.Transport.(quotaAwareTransport) + qt.base = ct + client.Transport = qt + } lc := llm.Config{ Format: wireFormat, BaseURL: baseURL, diff --git a/db/migrate_test.go b/db/migrate_test.go index d346638b4..f624e36a7 100644 --- a/db/migrate_test.go +++ b/db/migrate_test.go @@ -141,9 +141,9 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration { {8, "0008_traffic_evidence_rewrite_flag.sql"}, {9, "0009_llm_context.sql"}, {10, "0010_dashboard_usage_indexes.sql"}, {11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"}, {13, "0013_lesson_evidence_history.sql"}, {14, "0014_bedrock_gateway_profiles.sql"}, - {15, "0015_chat_bridges.sql"}} + {15, "0015_chat_bridges.sql"}, {16, "0016_claude_code_profiles.sql"}} if len(applied) != len(want) { - t.Fatalf("schema_migrations = %+v, want versions 1 to 15", applied) + t.Fatalf("schema_migrations = %+v, want versions 1 to 16", applied) } for i, w := range want { content, err := fs.ReadFile(migrationsFS(), w.name) diff --git a/db/migrations/0016_claude_code_profiles.sql b/db/migrations/0016_claude_code_profiles.sql new file mode 100644 index 000000000..43e75feba --- /dev/null +++ b/db/migrations/0016_claude_code_profiles.sql @@ -0,0 +1,5 @@ +-- The idempotent schema supplies the DDL; this migration records the feature version. +-- claude-code: profiles served by the local Claude Code CLI (agent/claude_code.go). +ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; +ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check + CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway','claude-code')); diff --git a/db/schema.sql b/db/schema.sql index 62331a3e9..d4b75fb63 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -370,7 +370,7 @@ CREATE TABLE IF NOT EXISTS settings ( CREATE TABLE IF NOT EXISTS llm_profiles ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL UNIQUE, - format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway')), + format TEXT NOT NULL CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway','claude-code')), base_url TEXT, proxy TEXT, model TEXT NOT NULL, @@ -431,7 +431,7 @@ ALTER TABLE llm_profiles ADD COLUMN IF NOT EXISTS streaming BOOLEAN NOT NULL -- Runs at every startup, idempotent: drop the old CHECK first, then create the current format CHECK. ALTER TABLE llm_profiles DROP CONSTRAINT IF EXISTS llm_profiles_format_check; ALTER TABLE llm_profiles ADD CONSTRAINT llm_profiles_format_check - CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway')); + CHECK (format IN ('openai','anthropic','openai-responses','ollama','bedrock-gateway','claude-code')); -- Output cap and its field name; backfills old databases. Defaults 0 / '' = send no cap and keep the max_tokens field name; -- old configs behave exactly as before. diff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.yml index 8ae32eed1..8c2ad5a94 100644 --- a/docker-compose.ghcr.yml +++ b/docker-compose.ghcr.yml @@ -56,6 +56,11 @@ services: # (e.g. host.docker.internal:11434 for Ollama). ARTEX_LLM_PRIVATE_ENDPOINTS: ${ARTEX_LLM_PRIVATE_ENDPOINTS:-} ARTEX_JWT_KEY_DIR: /app/keys + # claude-code LLM profiles: optional token from `claude setup-token`, and the CLI's + # config dir (its login), kept in the root-only keys volume, out of the agents' reach. + CLAUDE_CODE_OAUTH_TOKEN: ${CLAUDE_CODE_OAUTH_TOKEN:-} + ARTEX_CLAUDE_CODE_CONFIG_DIR: /app/keys/claude-code + ARTEX_CLAUDE_CODE_MAX_PROCS: ${ARTEX_CLAUDE_CODE_MAX_PROCS:-} # Optional: key for secrets at rest; empty = keys/secret.key (generated at # first start). ARTEX_SECRET_KEY: ${ARTEX_SECRET_KEY:-} diff --git a/docker-compose.yml b/docker-compose.yml index ec0924b74..3d80ae65e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -55,6 +55,11 @@ services: # Exact host:port list the model-list fetch may reach on private addresses (e.g. host.docker.internal:11434 for Ollama). ARTEX_LLM_PRIVATE_ENDPOINTS: ${ARTEX_LLM_PRIVATE_ENDPOINTS:-} ARTEX_JWT_KEY_DIR: /app/keys + # claude-code LLM profiles: optional token from `claude setup-token`, and the CLI's + # config dir (its login), kept in the root-only keys volume, out of the agents' reach. + CLAUDE_CODE_OAUTH_TOKEN: ${CLAUDE_CODE_OAUTH_TOKEN:-} + ARTEX_CLAUDE_CODE_CONFIG_DIR: /app/keys/claude-code + ARTEX_CLAUDE_CODE_MAX_PROCS: ${ARTEX_CLAUDE_CODE_MAX_PROCS:-} # Optional: key for secrets at rest; empty = keys/secret.key (generated at first start). ARTEX_SECRET_KEY: ${ARTEX_SECRET_KEY:-} ARTEX_TRUSTED_PROXIES: ${ARTEX_TRUSTED_PROXIES:-} diff --git a/server/env_scrub.go b/server/env_scrub.go index 5a1759168..6d2ee9461 100644 --- a/server/env_scrub.go +++ b/server/env_scrub.go @@ -19,7 +19,7 @@ import "os" // the environment: the scrub does not hide them from child processes. var secretEnv = []string{ "ARTEX_PG_DSN", "ARTEX_PG_PASSWORD", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", - "ARTEX_LLM_API_KEY", "ARTEX_LLM_CUSTOM_HEADERS", + "ARTEX_LLM_API_KEY", "ARTEX_LLM_CUSTOM_HEADERS", "CLAUDE_CODE_OAUTH_TOKEN", "ARTEX_LLM_PROXY", "ARTEX_LLM_BASE_URL", "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_SESSION_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "AWS_SECRET_KEY", "AWS_SESSION_TOKEN", diff --git a/server/server.go b/server/server.go index 662b8835e..97a75e457 100644 --- a/server/server.go +++ b/server/server.go @@ -1738,6 +1738,10 @@ func (s *Server) testLLM(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]any{"ok": false, "error": msg}) return } + } else if cfg.Format == agent.FormatClaudeCode && cfg.APIKey == "" && stored != nil && stored.Format == string(agent.FormatClaudeCode) { + // The token is optional for Claude Code, but a saved one must be used + // by the test exactly as a real run would use it. + cfg.APIKey = strings.TrimSpace(stored.APIKey) } // Retry params do [not] go into the connection test: the test has a 30s hard timeout, and stacking the configured retry counts/long intervals on top // would only turn a perfectly usable endpoint into a "timeout failure". The test asks "does this endpoint work at all"; retry pacing diff --git a/server/server_mgmt.go b/server/server_mgmt.go index a9ec26d92..a1897df3d 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -2697,6 +2697,12 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]any{"ok": false, "error": "enter the Bedrock model ID manually; this gateway has no model-list endpoint"}) return } + // The Claude Code CLI has no model-list endpoint: offer its aliases. A full + // model ID (e.g. claude-opus-5-5) can still be typed in. + if strings.TrimSpace(req.Provider) == string(agent.FormatClaudeCode) { + writeJSON(w, 200, map[string]any{"ok": true, "models": agent.ClaudeCodeModels}) + return + } // Resolve API key: form input > profile stored key. The stored key is only // sent to the endpoint it was saved for, since base_url comes from the form. apiKey := strings.TrimSpace(req.APIKey) diff --git a/server/task_resolution.go b/server/task_resolution.go index d79f7ee1b..be88dffc6 100644 --- a/server/task_resolution.go +++ b/server/task_resolution.go @@ -4,6 +4,7 @@ import ( "fmt" "net/http" + "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/db" ) @@ -29,8 +30,8 @@ func (s *Server) resolutionFromProfile(p *db.LLMProfile, source string) taskLLMR Model: p.Model, Source: source, } - // Ollama profiles are keyless by design; the other formats need a key. - if p.APIKey == "" && p.Format != "ollama" { + // Ollama and Claude Code profiles are keyless by design; the other formats need a key. + if p.APIKey == "" && !agent.IsKeylessFormat(p.Format) { result.Reason = "LLM profile has no API Key set" return result } diff --git a/web/src/app/(main)/system/llm/page.tsx b/web/src/app/(main)/system/llm/page.tsx index bf2630228..a587020bb 100644 --- a/web/src/app/(main)/system/llm/page.tsx +++ b/web/src/app/(main)/system/llm/page.tsx @@ -64,10 +64,13 @@ const MAX_TOKENS_FIELD_HINTS: Record = { anthropic: t("Only selectable for the openai format. Anthropic's field name is fixed as max_tokens."), "openai-responses": t("Only selectable for the openai format. The Responses API's field name is fixed as max_output_tokens."), ollama: t("Only selectable for the openai format. Ollama's field name is fixed as max_tokens."), + "claude-code": t("Only selectable for the openai format. The Claude Code CLI sets its own output cap."), }; // LLM profile formats. The default in the create form is "anthropic"; "ollama" is the // keyless local-server format (base URL defaults to http://127.0.0.1:11434/v1). -type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama" | "bedrock-gateway"; +type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama" | "bedrock-gateway" | "claude-code"; +// Formats that run without an API key: a local Ollama server, and the Claude Code CLI using its own login. +const KEYLESS_FORMATS: string[] = ["ollama", "claude-code"]; const OLLAMA_DEFAULT_BASE_URL = "http://127.0.0.1:11434/v1"; const EFFORT_LEVELS: { value: string; label: string }[] = [ { value: NONE, label: t("Not sent (default)") }, @@ -89,7 +92,7 @@ function cooldownText(secs: number) { // records (with polling off no new records appear, so "healthy" = no known failure). type Health = { label: string; cls: string; hint?: string }; function healthOf(p: LLMProfile, m?: LLMPoolMember): Health { - if (!p.api_key_hint && p.format !== "ollama") { + if (!p.api_key_hint && !KEYLESS_FORMATS.includes(p.format)) { return { label: t("No Key configured"), cls: "border-muted-foreground/40 text-muted-foreground", @@ -371,7 +374,11 @@ function ProfileSheet({ if (!open) return; setName(profile?.name ?? ""); setFormat( - profile?.format === "openai" || profile?.format === "openai-responses" || profile?.format === "ollama" || profile?.format === "bedrock-gateway" + profile?.format === "openai" || + profile?.format === "openai-responses" || + profile?.format === "ollama" || + profile?.format === "bedrock-gateway" || + profile?.format === "claude-code" ? profile.format : "anthropic", ); @@ -524,6 +531,9 @@ function ProfileSheet({ } } + let modelPlaceholder = "claude-opus-4-8"; + if (format === "ollama") modelPlaceholder = "llama3.2"; + else if (format === "claude-code") modelPlaceholder = "sonnet"; let keyPlaceholder = "sk-…"; let keyLabel = "API Key"; let basePlaceholder = "https://api.openai.com/v1"; @@ -531,6 +541,11 @@ function ProfileSheet({ keyPlaceholder = t("optional — a local Ollama server runs keyless"); keyLabel = t("API Key (optional for Ollama)"); basePlaceholder = OLLAMA_DEFAULT_BASE_URL; + } else if (format === "claude-code") { + keyLabel = t("Token (optional for Claude Code)"); + keyPlaceholder = keyHint + ? t("Set ({hint}); leave empty to keep it", { hint: keyHint }) + : t("optional — claude setup-token output; empty uses the CLI's own login"); } else if (format === "bedrock-gateway") { keyLabel = "Bearer token"; basePlaceholder = "https://gateway.example.com/bedrock"; @@ -584,6 +599,7 @@ function ProfileSheet({ OpenAI (Responses API) {t("Ollama (local, no key needed)")} Bedrock gateway + {t("Claude Code CLI (subscription, no key needed)")} @@ -595,7 +611,7 @@ function ProfileSheet({ setModel(e.target.value)} /> @@ -662,16 +678,26 @@ function ProfileSheet({ -
- - setBaseUrl(e.target.value)} - /> -
+ {format === "claude-code" && ( +

+ {t( + "Runs the local claude CLI with every built-in tool disabled; ARTEX's own tools are passed in the prompt. Use an alias (opus, sonnet, haiku) or a full model ID.", + )} +

+ )} + + {format !== "claude-code" && ( +
+ + setBaseUrl(e.target.value)} + /> +
+ )} {format === "bedrock-gateway" && (
diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.json index 661b88b75..e77f2806b 100644 --- a/web/src/i18n/locales/tr.json +++ b/web/src/i18n/locales/tr.json @@ -2752,5 +2752,10 @@ "Only for a self-hosted Bot API server or a relay. Changing it requires entering the token again.": "Yalnızca kendi barındırdığınız bir Bot API sunucusu veya aktarıcı için. Değiştirirseniz token'ı yeniden girmeniz gerekir.", "The bot uses long polling, so ARTEX opens no inbound port. Messages it sends contain summaries and links, never evidence bodies or credentials.": "Bot uzun yoklama kullanır, bu yüzden ARTEX gelen bağlantılar için port açmaz. Gönderdiği mesajlar yalnızca özet ve bağlantı içerir; asla kanıt gövdesi veya kimlik bilgisi içermez.", "The bot is off. Enter a token and switch it on.": "Bot kapalı. Bir token girin ve botu açın.", - "No chat is allowed yet: the bot refuses every chat and replies with its chat ID. Add your chat ID here to start using it.": "Henüz hiçbir sohbete izin verilmedi: bot her sohbeti reddeder ve sohbet kimliğini yanıtında bildirir. Kullanmaya başlamak için sohbet kimliğinizi buraya ekleyin." + "No chat is allowed yet: the bot refuses every chat and replies with its chat ID. Add your chat ID here to start using it.": "Henüz hiçbir sohbete izin verilmedi: bot her sohbeti reddeder ve sohbet kimliğini yanıtında bildirir. Kullanmaya başlamak için sohbet kimliğinizi buraya ekleyin.", + "Only selectable for the openai format. The Claude Code CLI sets its own output cap.": "Yalnızca openai biçiminde seçilebilir. Claude Code CLI kendi çıktı sınırını belirler.", + "Token (optional for Claude Code)": "Token (Claude Code için isteğe bağlı)", + "optional — claude setup-token output; empty uses the CLI's own login": "isteğe bağlı — claude setup-token çıktısı; boş bırakılırsa CLI'nin kendi oturumu kullanılır", + "Claude Code CLI (subscription, no key needed)": "Claude Code CLI (abonelik, anahtar gerekmez)", + "Runs the local claude CLI with every built-in tool disabled; ARTEX's own tools are passed in the prompt. Use an alias (opus, sonnet, haiku) or a full model ID.": "Yerel claude CLI'yi tüm yerleşik araçları kapalı olarak çalıştırır; ARTEX'in kendi araçları istemde iletilir. Bir takma ad (opus, sonnet, haiku) veya tam model kimliği kullanın." } diff --git a/web/src/i18n/locales/zh-CN.json b/web/src/i18n/locales/zh-CN.json index b832b5082..135e43d93 100644 --- a/web/src/i18n/locales/zh-CN.json +++ b/web/src/i18n/locales/zh-CN.json @@ -2752,5 +2752,10 @@ "Only for a self-hosted Bot API server or a relay. Changing it requires entering the token again.": "仅用于自托管的 Bot API 服务器或中转。修改后需要重新填写 Token。", "The bot uses long polling, so ARTEX opens no inbound port. Messages it sends contain summaries and links, never evidence bodies or credentials.": "机器人使用长轮询,因此 ARTEX 不会开放任何入站端口。它发送的消息只包含摘要和链接,绝不包含证据正文或凭据。", "The bot is off. Enter a token and switch it on.": "机器人已关闭。请填写 Token 并将其开启。", - "No chat is allowed yet: the bot refuses every chat and replies with its chat ID. Add your chat ID here to start using it.": "尚未允许任何聊天:机器人会拒绝所有聊天,并在回复中告知其聊天 ID。在此添加你的聊天 ID 即可开始使用。" + "No chat is allowed yet: the bot refuses every chat and replies with its chat ID. Add your chat ID here to start using it.": "尚未允许任何聊天:机器人会拒绝所有聊天,并在回复中告知其聊天 ID。在此添加你的聊天 ID 即可开始使用。", + "Only selectable for the openai format. The Claude Code CLI sets its own output cap.": "仅 openai 格式可选。Claude Code CLI 自行决定输出上限。", + "Token (optional for Claude Code)": "Token(Claude Code 可选)", + "optional — claude setup-token output; empty uses the CLI's own login": "可选 — claude setup-token 的输出;留空则使用 CLI 自身的登录", + "Claude Code CLI (subscription, no key needed)": "Claude Code CLI(订阅,无需 Key)", + "Runs the local claude CLI with every built-in tool disabled; ARTEX's own tools are passed in the prompt. Use an alias (opus, sonnet, haiku) or a full model ID.": "运行本地 claude CLI,并禁用其全部内置工具;ARTEX 自身的工具通过提示词传入。可填写别名(opus、sonnet、haiku)或完整模型 ID。" } diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 33bdb3a51..9994d5858 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -1160,7 +1160,7 @@ export interface NotificationDelivery { export interface LLMProfile { id: string; name: string; - format: "openai" | "anthropic" | "openai-responses" | "ollama" | "bedrock-gateway"; + format: "openai" | "anthropic" | "openai-responses" | "ollama" | "bedrock-gateway" | "claude-code"; base_url?: string; proxy?: string; model: string;