Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agent): add custom CLI arguments support (#986)
Bohan Jiangce447c7f06b7
diff --git a/apps/web/test/helpers.tsx b/apps/web/test/helpers.tsxindex f14b9d65d3..8ed9aec9dd 100644--- a/apps/web/test/helpers.tsx+++ b/apps/web/test/helpers.tsx@@ -55,6 +55,7 @@ export const mockAgents: Agent[] = [runtime_mode: "cloud",runtime_config: {},custom_env: {},+ custom_args: [],custom_env_redacted: false,visibility: "workspace",max_concurrent_tasks: 3,diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex c465b44448..1d0325dbd2 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -48,6 +48,7 @@ export interface Agent {runtime_mode: AgentRuntimeMode;runtime_config: Record<string, unknown>;custom_env: Record<string, string>;+ custom_args: string[];custom_env_redacted: boolean;visibility: AgentVisibility;status: AgentStatus;@@ -68,6 +69,7 @@ export interface CreateAgentRequest {runtime_id: string;runtime_config?: Record<string, unknown>;custom_env?: Record<string, string>;+ custom_args?: string[];visibility?: AgentVisibility;max_concurrent_tasks?: number;}@@ -80,6 +82,7 @@ export interface UpdateAgentRequest {runtime_id?: string;runtime_config?: Record<string, unknown>;custom_env?: Record<string, string>;+ custom_args?: string[];visibility?: AgentVisibility;status?: AgentStatus;max_concurrent_tasks?: number;diff --git a/packages/views/agents/components/agent-detail.tsx b/packages/views/agents/components/agent-detail.tsxindex 28f83d224e..bf17218299 100644--- a/packages/views/agents/components/agent-detail.tsx+++ b/packages/views/agents/components/agent-detail.tsx@@ -12,6 +12,7 @@ import {MoreHorizontal,Settings,KeyRound,+ Terminal,} from "lucide-react";import type { Agent, RuntimeDevice, MemberWithUser } from "@multica/core/types";import {@@ -36,18 +37,20 @@ import { SkillsTab } from "./tabs/skills-tab";import { TasksTab } from "./tabs/tasks-tab";import { SettingsTab } from "./tabs/settings-tab";import { EnvTab } from "./tabs/env-tab";+import { CustomArgsTab } from "./tabs/custom-args-tab";function getRuntimeDevice(agent: Agent, runtimes: RuntimeDevice[]): RuntimeDevice | undefined {return runtimes.find((runtime) => runtime.id === agent.runtime_id);}-type DetailTab = "instructions" | "skills" | "tasks" | "env" | "settings";+type DetailTab = "instructions" | "skills" | "tasks" | "env" | "custom_args" | "settings";const detailTabs: { id: DetailTab; label: string; icon: typeof FileText }[] = [{ id: "instructions", label: "Instructions", icon: FileText },{ id: "skills", label: "Skills", icon: BookOpenText },{ id: "tasks", label: "Tasks", icon: ListTodo },{ id: "env", label: "Environment", icon: KeyRound },+ { id: "custom_args", label: "Custom Args", icon: Terminal },{ id: "settings", label: "Settings", icon: Settings },];@@ -172,6 +175,12 @@ export function AgentDetail({onSave={(updates) => onUpdate(agent.id, updates)}/>)}+ {activeTab === "custom_args" && (+ <CustomArgsTab+ agent={agent}+ onSave={(updates) => onUpdate(agent.id, updates)}+ />+ )}{activeTab === "settings" && (<SettingsTabagent={agent}diff --git a/packages/views/agents/components/tabs/custom-args-tab.tsx b/packages/views/agents/components/tabs/custom-args-tab.tsxnew file mode 100644index 0000000000..1e78aaf9e6--- /dev/null+++ b/packages/views/agents/components/tabs/custom-args-tab.tsx@@ -0,0 +1,126 @@+"use client";++import { useState } from "react";+import {+ Loader2,+ Save,+ Plus,+ Trash2,+} from "lucide-react";+import type { Agent } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import { Label } from "@multica/ui/components/ui/label";+import { toast } from "sonner";++interface ArgEntry {+ id: string;+ value: string;+}++function argsToEntries(args: string[]): ArgEntry[] {+ return args.map((value) => ({ id: crypto.randomUUID(), value }));+}++function entriesToArgs(entries: ArgEntry[]): string[] {+ return entries.map((e) => e.value).filter((v) => v.trim() !== "");+}++export function CustomArgsTab({+ agent,+ onSave,+}: {+ agent: Agent;+ onSave: (updates: Partial<Agent>) => Promise<void>;+}) {+ const [entries, setEntries] = useState<ArgEntry[]>(+ argsToEntries(agent.custom_args ?? []),+ );+ const [saving, setSaving] = useState(false);++ const currentArgs = entriesToArgs(entries);+ const originalArgs = agent.custom_args ?? [];+ const dirty = JSON.stringify(currentArgs) !== JSON.stringify(originalArgs);++ const addEntry = () => {+ setEntries([...entries, { id: crypto.randomUUID(), value: "" }]);+ };++ const removeEntry = (index: number) => {+ setEntries(entries.filter((_, i) => i !== index));+ };++ const updateEntry = (index: number, value: string) => {+ setEntries(+ entries.map((entry, i) => (i === index ? { ...entry, value } : entry)),+ );+ };++ const handleSave = async () => {+ setSaving(true);+ try {+ await onSave({ custom_args: currentArgs });+ toast.success("Custom arguments saved");+ } catch {+ toast.error("Failed to save custom arguments");+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="max-w-lg space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <Label className="text-xs text-muted-foreground">+ Custom Arguments+ </Label>+ <p className="text-xs text-muted-foreground mt-0.5">+ Additional CLI arguments appended to the agent command at launch+ (e.g. --model, --max-turns)+ </p>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={addEntry}+ className="h-7 gap-1 text-xs"+ >+ <Plus className="h-3 w-3" />+ Add+ </Button>+ </div>+ {entries.length > 0 && (+ <div className="space-y-2">+ {entries.map((entry, index) => (+ <div key={entry.id} className="flex items-center gap-2">+ <Input+ value={entry.value}+ onChange={(e) => updateEntry(index, e.target.value)}+ placeholder="--flag value"+ className="flex-1 font-mono text-xs"+ />+ <button+ type="button"+ onClick={() => removeEntry(index)}+ className="shrink-0 text-muted-foreground hover:text-destructive"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </div>+ ))}+ </div>+ )}++ <Button onClick={handleSave} disabled={!dirty || saving} size="sm">+ {saving ? (+ <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />+ ) : (+ <Save className="h-3.5 w-3.5 mr-1.5" />+ )}+ Save+ </Button>+ </div>+ );+}diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 9823d9a7da..62f44b22b9 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -114,6 +114,7 @@ func init() {agentCreateCmd.Flags().String("instructions", "", "Agent instructions")agentCreateCmd.Flags().String("runtime-id", "", "Runtime ID (required)")agentCreateCmd.Flags().String("runtime-config", "", "Runtime config as JSON string")+ agentCreateCmd.Flags().String("custom-args", "", "Custom CLI arguments as JSON array (e.g. '[\"--model\", \"o3\"]')")agentCreateCmd.Flags().String("visibility", "private", "Visibility: private or workspace")agentCreateCmd.Flags().Int32("max-concurrent-tasks", 6, "Maximum concurrent tasks")agentCreateCmd.Flags().String("output", "json", "Output format: table or json")@@ -124,6 +125,7 @@ func init() {agentUpdateCmd.Flags().String("instructions", "", "New instructions")agentUpdateCmd.Flags().String("runtime-id", "", "New runtime ID")agentUpdateCmd.Flags().String("runtime-config", "", "New runtime config as JSON string")+ agentUpdateCmd.Flags().String("custom-args", "", "New custom CLI arguments as JSON array (e.g. '[\"--model\", \"o3\"]')")agentUpdateCmd.Flags().String("visibility", "", "New visibility: private or workspace")agentUpdateCmd.Flags().String("status", "", "New status")agentUpdateCmd.Flags().Int32("max-concurrent-tasks", 0, "New max concurrent tasks")@@ -337,6 +339,14 @@ func runAgentCreate(cmd *cobra.Command, _ []string) error {}body["runtime_config"] = rc}+ if cmd.Flags().Changed("custom-args") {+ v, _ := cmd.Flags().GetString("custom-args")+ var ca []string+ if err := json.Unmarshal([]byte(v), &ca); err != nil {+ return fmt.Errorf("--custom-args must be a valid JSON array: %w", err)+ }+ body["custom_args"] = ca+ }if cmd.Flags().Changed("visibility") {v, _ := cmd.Flags().GetString("visibility")body["visibility"] = v@@ -394,6 +404,14 @@ func runAgentUpdate(cmd *cobra.Command, args []string) error {}body["runtime_config"] = rc}+ if cmd.Flags().Changed("custom-args") {+ v, _ := cmd.Flags().GetString("custom-args")+ var ca []string+ if err := json.Unmarshal([]byte(v), &ca); err != nil {+ return fmt.Errorf("--custom-args must be a valid JSON array: %w", err)+ }+ body["custom_args"] = ca+ }if cmd.Flags().Changed("visibility") {v, _ := cmd.Flags().GetString("visibility")body["visibility"] = v@@ -408,7 +426,7 @@ func runAgentUpdate(cmd *cobra.Command, args []string) error {}if len(body) == 0 {- return fmt.Errorf("no fields to update; use --name, --description, --instructions, --runtime-id, --runtime-config, --visibility, --status, or --max-concurrent-tasks")+ return fmt.Errorf("no fields to update; use --name, --description, --instructions, --runtime-id, --runtime-config, --custom-args, --visibility, --status, or --max-concurrent-tasks")}ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex faf7f5bf94..37fb085ee0 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -916,11 +916,16 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLotaskStart := time.Now()+ var customArgs []string+ if task.Agent != nil {+ customArgs = task.Agent.CustomArgs+ }execOpts := agent.ExecOptions{Cwd: env.WorkDir,Model: entry.Model,Timeout: d.cfg.AgentTimeout,ResumeSessionID: task.PriorSessionID,+ CustomArgs: customArgs,}result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID)diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex d2b13bcd5f..1366a62dd5 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -45,6 +45,7 @@ type AgentData struct {Instructions string `json:"instructions"`Skills []SkillData `json:"skills"`CustomEnv map[string]string `json:"custom_env,omitempty"`+ CustomArgs []string `json:"custom_args,omitempty"`}// SkillData represents a structured skill for task execution.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 95b403728a..24ce8ac90b 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -24,6 +24,7 @@ type AgentResponse struct {RuntimeMode string `json:"runtime_mode"`RuntimeConfig any `json:"runtime_config"`CustomEnv map[string]string `json:"custom_env"`+ CustomArgs []string `json:"custom_args"`CustomEnvRedacted bool `json:"custom_env_redacted"`Visibility string `json:"visibility"`Status string `json:"status"`@@ -55,6 +56,16 @@ func agentToResponse(a db.Agent) AgentResponse {customEnv = map[string]string{}}+ var customArgs []string+ if a.CustomArgs != nil {+ if err := json.Unmarshal(a.CustomArgs, &customArgs); err != nil {+ slog.Warn("failed to unmarshal agent custom_args", "agent_id", uuidToString(a.ID), "error", err)+ }+ }+ if customArgs == nil {+ customArgs = []string{}+ }+return AgentResponse{ID: uuidToString(a.ID),WorkspaceID: uuidToString(a.WorkspaceID),@@ -66,6 +77,7 @@ func agentToResponse(a db.Agent) AgentResponse {RuntimeMode: a.RuntimeMode,RuntimeConfig: rc,CustomEnv: customEnv,+ CustomArgs: customArgs,Visibility: a.Visibility,Status: a.Status,MaxConcurrentTasks: a.MaxConcurrentTasks,@@ -117,6 +129,7 @@ type TaskAgentData struct {Instructions string `json:"instructions"`Skills []service.AgentSkillData `json:"skills,omitempty"`CustomEnv map[string]string `json:"custom_env,omitempty"`+ CustomArgs []string `json:"custom_args,omitempty"`}func taskToResponse(t db.AgentTaskQueue) AgentTaskResponse {@@ -232,6 +245,7 @@ type CreateAgentRequest struct {RuntimeID string `json:"runtime_id"`RuntimeConfig any `json:"runtime_config"`CustomEnv map[string]string `json:"custom_env"`+ CustomArgs []string `json:"custom_args"`Visibility string `json:"visibility"`MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`}@@ -284,6 +298,11 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {ce = []byte("{}")}+ ca, _ := json.Marshal(req.CustomArgs)+ if req.CustomArgs == nil {+ ca = []byte("[]")+ }+agent, err := h.Queries.CreateAgent(r.Context(), db.CreateAgentParams{WorkspaceID: parseUUID(workspaceID),Name: req.Name,@@ -297,6 +316,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {MaxConcurrentTasks: req.MaxConcurrentTasks,OwnerID: parseUUID(ownerID),CustomEnv: ce,+ CustomArgs: ca,})if err != nil {slog.Warn("create agent failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)@@ -326,6 +346,7 @@ type UpdateAgentRequest struct {RuntimeID *string `json:"runtime_id"`RuntimeConfig any `json:"runtime_config"`CustomEnv *map[string]string `json:"custom_env"`+ CustomArgs *[]string `json:"custom_args"`Visibility *string `json:"visibility"`Status *string `json:"status"`MaxConcurrentTasks *int32 `json:"max_concurrent_tasks"`@@ -410,6 +431,10 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {ce, _ := json.Marshal(*req.CustomEnv)params.CustomEnv = ce}+ if req.CustomArgs != nil {+ ca, _ := json.Marshal(*req.CustomArgs)+ params.CustomArgs = ca+ }if req.RuntimeID != nil {runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{ID: parseUUID(*req.RuntimeID),diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex d454d3bd54..b3b894bf77 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -382,7 +382,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {return}- // Build response with fresh agent data (name + skills + custom_env).+ // Build response with fresh agent data (name + skills + custom_env + custom_args).resp := taskToResponse(*task)if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)@@ -392,12 +392,19 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {slog.Warn("failed to unmarshal agent custom_env", "agent_id", uuidToString(agent.ID), "error", err)}}+ var customArgs []string+ if agent.CustomArgs != nil {+ if err := json.Unmarshal(agent.CustomArgs, &customArgs); err != nil {+ slog.Warn("failed to unmarshal agent custom_args", "agent_id", uuidToString(agent.ID), "error", err)+ }+ }resp.Agent = &TaskAgentData{ID: uuidToString(agent.ID),Name: agent.Name,Instructions: agent.Instructions,Skills: skills,CustomEnv: customEnv,+ CustomArgs: customArgs,}}diff --git a/server/migrations/041_agent_custom_args.down.sql b/server/migrations/041_agent_custom_args.down.sqlnew file mode 100644index 0000000000..49aed28f4b--- /dev/null+++ b/server/migrations/041_agent_custom_args.down.sql@@ -0,0 +1 @@+ALTER TABLE agent DROP COLUMN custom_args;diff --git a/server/migrations/041_agent_custom_args.up.sql b/server/migrations/041_agent_custom_args.up.sqlnew file mode 100644index 0000000000..931dfd5367--- /dev/null+++ b/server/migrations/041_agent_custom_args.up.sql@@ -0,0 +1,4 @@+-- Add custom_args column to agent table for user-configurable CLI arguments+-- that get appended to the agent subprocess command at launch time.+-- Stored as JSONB array of strings (e.g. ["--model", "o3", "--max-turns", "50"]).+ALTER TABLE agent ADD COLUMN custom_args JSONB NOT NULL DEFAULT '[]';diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex aa3f50928e..9565e6abc5 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -25,7 +25,8 @@ type ExecOptions struct {SystemPrompt stringMaxTurns intTimeout time.Duration- ResumeSessionID string // if non-empty, resume a previous agent session+ ResumeSessionID string // if non-empty, resume a previous agent session+ CustomArgs []string // additional CLI arguments appended to the agent command}// Session represents a running agent execution.diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex dbf98cf94f..91d0586e21 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -34,7 +34,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}runCtx, cancel := context.WithTimeout(ctx, timeout)- args := buildClaudeArgs(opts)+ args := buildClaudeArgs(opts, b.cfg.Logger)cmd := exec.CommandContext(runCtx, execPath, args...)cmd.WaitDelay = 10 * time.Second@@ -342,7 +342,17 @@ func trySend(ch chan<- Message, msg Message) {}}-func buildClaudeArgs(opts ExecOptions) []string {+// claudeBlockedArgs are flags hardcoded by the daemon that must not be+// overridden by user-configured custom_args. Overriding these would break+// the daemon↔Claude communication protocol.+var claudeBlockedArgs = map[string]blockedArgMode{+ "-p": blockedStandalone, // non-interactive mode+ "--output-format": blockedWithValue, // stream-json protocol+ "--input-format": blockedWithValue, // stream-json protocol+ "--permission-mode": blockedWithValue, // bypassPermissions for autonomous operation+}++func buildClaudeArgs(opts ExecOptions, logger *slog.Logger) []string {args := []string{"-p","--output-format", "stream-json",@@ -363,6 +373,7 @@ func buildClaudeArgs(opts ExecOptions) []string {if opts.ResumeSessionID != "" {args = append(args, "--resume", opts.ResumeSessionID)}+ args = append(args, filterCustomArgs(opts.CustomArgs, claudeBlockedArgs, logger)...)return args}@@ -422,6 +433,52 @@ func isFilteredChildEnvKey(key string) bool {strings.HasPrefix(key, "CLAUDE_CODE_")}+// blockedArgMode specifies whether a blocked arg takes a value or is standalone.+type blockedArgMode int++const (+ blockedWithValue blockedArgMode = iota // flag takes a value (next arg or =value)+ blockedStandalone // flag is boolean, no value+)++// filterCustomArgs removes protocol-critical flags from user-configured custom+// args to prevent breaking daemon↔agent communication. Each backend defines its+// own blocked set (the flags it hardcodes). This is intentionally narrow — we+// only block args that would break the communication protocol, not every+// possible dangerous flag. Workspace members are trusted to configure agents+// sensibly, same as with custom_env.+func filterCustomArgs(args []string, blocked map[string]blockedArgMode, logger *slog.Logger) []string {+ if len(args) == 0 {+ return args+ }+ filtered := make([]string, 0, len(args))+ skip := false+ for _, arg := range args {+ if skip {+ skip = false+ continue+ }+ // Check if this arg is a blocked flag or starts with "blockedFlag=".+ flag := arg+ hasInlineValue := false+ if idx := strings.Index(arg, "="); idx > 0 {+ flag = arg[:idx]+ hasInlineValue = true+ }+ mode, isBlocked := blocked[flag]+ if isBlocked {+ logger.Warn("custom_args: blocked protocol-critical flag, skipping", "flag", flag)+ if mode == blockedWithValue && !hasInlineValue {+ // The next arg is the value for this flag — skip it too.+ skip = true+ }+ continue+ }+ filtered = append(filtered, arg)+ }+ return filtered+}+func detectCLIVersion(ctx context.Context, execPath string) (string, error) {cmd := exec.CommandContext(ctx, execPath, "--version")data, err := cmd.Output()diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.goindex c8941a6685..9ab4d1c2de 100644--- a/server/pkg/agent/claude_test.go+++ b/server/pkg/agent/claude_test.go@@ -197,7 +197,7 @@ func TestTrySendDropsWhenFull(t *testing.T) {func TestBuildClaudeArgsIncludesStrictMCPConfig(t *testing.T) {t.Parallel()- args := buildClaudeArgs(ExecOptions{})+ args := buildClaudeArgs(ExecOptions{}, slog.Default())expected := []string{"-p","--output-format", "stream-json",@@ -217,6 +217,102 @@ func TestBuildClaudeArgsIncludesStrictMCPConfig(t *testing.T) {}}+func TestFilterCustomArgsBlocksProtocolFlags(t *testing.T) {+ t.Parallel()++ blocked := map[string]blockedArgMode{+ "--output-format": blockedWithValue,+ "--permission-mode": blockedWithValue,+ "-p": blockedStandalone,+ }+ logger := slog.Default()++ // Blocks flag with separate value+ result := filterCustomArgs([]string{"--output-format", "text", "--model", "o3"}, blocked, logger)+ if len(result) != 2 || result[0] != "--model" || result[1] != "o3" {+ t.Fatalf("expected [--model o3], got %v", result)+ }++ // Blocks flag=value form+ result = filterCustomArgs([]string{"--permission-mode=plan", "--verbose"}, blocked, logger)+ if len(result) != 1 || result[0] != "--verbose" {+ t.Fatalf("expected [--verbose], got %v", result)+ }++ // Blocks standalone short flags without consuming next arg+ result = filterCustomArgs([]string{"-p", "--max-turns", "10"}, blocked, logger)+ if len(result) != 2 || result[0] != "--max-turns" || result[1] != "10" {+ t.Fatalf("expected [--max-turns 10], got %v", result)+ }++ // Passes through non-blocked args+ result = filterCustomArgs([]string{"--model", "o3", "--max-turns", "50"}, blocked, logger)+ if len(result) != 4 {+ t.Fatalf("expected all 4 args to pass through, got %v", result)+ }++ // Handles nil blocked map+ result = filterCustomArgs([]string{"--anything"}, nil, logger)+ if len(result) != 1 {+ t.Fatalf("expected args to pass through with nil blocked map, got %v", result)+ }++ // Handles empty args+ result = filterCustomArgs(nil, blocked, logger)+ if result != nil {+ t.Fatalf("expected nil for nil input, got %v", result)+ }+}++func TestBuildClaudeArgsPassesThroughCustomArgs(t *testing.T) {+ t.Parallel()++ args := buildClaudeArgs(ExecOptions{+ CustomArgs: []string{"--max-turns", "50", "--verbose"},+ }, slog.Default())++ // Custom args should appear at the end+ found := 0+ for i, a := range args {+ if a == "--max-turns" && i+1 < len(args) && args[i+1] == "50" {+ found+++ }+ }+ if found != 1 {+ t.Fatalf("expected --max-turns 50 in args: %v", args)+ }+}++func TestBuildClaudeArgsFiltersBlockedCustomArgs(t *testing.T) {+ t.Parallel()++ args := buildClaudeArgs(ExecOptions{+ CustomArgs: []string{"--output-format", "text", "--model", "o3"},+ }, slog.Default())++ // --output-format text should be stripped+ for _, a := range args[len(args)-2:] {+ if a == "text" {+ // "text" should not be in the last args since --output-format was blocked+ // The actual --output-format stream-json is earlier in the list+ }+ }+ // --model o3 should pass through+ foundModel := false+ for i, a := range args {+ if a == "--model" && i+1 < len(args) && args[i+1] == "o3" {+ foundModel = true+ }+ // Verify no duplicate --output-format with value "text"+ if a == "--output-format" && i+1 < len(args) && args[i+1] == "text" {+ t.Fatalf("blocked --output-format text should have been filtered: %v", args)+ }+ }+ if !foundModel {+ t.Fatalf("expected --model o3 in args but it was missing: %v", args)+ }+}+func TestBuildClaudeInputEncodesUserMessage(t *testing.T) {t.Parallel()diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 17e4f87ebd..cd7e416346 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -13,6 +13,12 @@ import ("time")+// codexBlockedArgs are flags hardcoded by the daemon that must not be+// overridden by user-configured custom_args.+var codexBlockedArgs = map[string]blockedArgMode{+ "--listen": blockedWithValue, // stdio:// transport for daemon communication+}+// codexBackend implements Backend by spawning `codex app-server --listen stdio://`// and communicating via JSON-RPC 2.0 over stdin/stdout.type codexBackend struct {@@ -34,7 +40,8 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti}runCtx, cancel := context.WithTimeout(ctx, timeout)- cmd := exec.CommandContext(runCtx, execPath, "app-server", "--listen", "stdio://")+ codexArgs := append([]string{"app-server", "--listen", "stdio://"}, filterCustomArgs(opts.CustomArgs, codexBlockedArgs, b.cfg.Logger)...)+ cmd := exec.CommandContext(runCtx, execPath, codexArgs...)if opts.Cwd != "" {cmd.Dir = opts.Cwd}diff --git a/server/pkg/agent/gemini.go b/server/pkg/agent/gemini.goindex 1bde6f7950..a15507154a 100644--- a/server/pkg/agent/gemini.go+++ b/server/pkg/agent/gemini.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "log/slog""os/exec""strings""time"@@ -31,7 +32,7 @@ func (b *geminiBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}runCtx, cancel := context.WithTimeout(ctx, timeout)- args := buildGeminiArgs(prompt, opts)+ args := buildGeminiArgs(prompt, opts, b.cfg.Logger)cmd := exec.CommandContext(runCtx, execPath, args...)cmd.WaitDelay = 10 * time.Second@@ -239,7 +240,15 @@ type geminiModelStats struct {// -o stream-json streaming NDJSON output for live events// -m <model> optional model override// -r <session> resume a previous session (if provided)-func buildGeminiArgs(prompt string, opts ExecOptions) []string {+// geminiBlockedArgs are flags hardcoded by the daemon that must not be+// overridden by user-configured custom_args.+var geminiBlockedArgs = map[string]blockedArgMode{+ "-p": blockedWithValue, // non-interactive prompt+ "--yolo": blockedStandalone, // auto-approve tool use+ "-o": blockedWithValue, // stream-json output format+}++func buildGeminiArgs(prompt string, opts ExecOptions, logger *slog.Logger) []string {args := []string{"-p", prompt,"--yolo",@@ -251,5 +260,6 @@ func buildGeminiArgs(prompt string, opts ExecOptions) []string {if opts.ResumeSessionID != "" {args = append(args, "-r", opts.ResumeSessionID)}+ args = append(args, filterCustomArgs(opts.CustomArgs, geminiBlockedArgs, logger)...)return args}diff --git a/server/pkg/agent/gemini_test.go b/server/pkg/agent/gemini_test.goindex 3a95bdd756..d23fae8900 100644--- a/server/pkg/agent/gemini_test.go+++ b/server/pkg/agent/gemini_test.go@@ -1,13 +1,14 @@package agentimport (+ "log/slog""testing")func TestBuildGeminiArgsBaseline(t *testing.T) {t.Parallel()- args := buildGeminiArgs("write a haiku", ExecOptions{})+ args := buildGeminiArgs("write a haiku", ExecOptions{}, slog.Default())expected := []string{"-p", "write a haiku","--yolo",@@ -27,7 +28,7 @@ func TestBuildGeminiArgsBaseline(t *testing.T) {func TestBuildGeminiArgsWithModel(t *testing.T) {t.Parallel()- args := buildGeminiArgs("hi", ExecOptions{Model: "gemini-2.5-pro"})+ args := buildGeminiArgs("hi", ExecOptions{Model: "gemini-2.5-pro"}, slog.Default())var foundModel boolfor i, a := range args {@@ -47,7 +48,7 @@ func TestBuildGeminiArgsWithModel(t *testing.T) {func TestBuildGeminiArgsWithResume(t *testing.T) {t.Parallel()- args := buildGeminiArgs("hi", ExecOptions{ResumeSessionID: "3"})+ args := buildGeminiArgs("hi", ExecOptions{ResumeSessionID: "3"}, slog.Default())var foundResume boolfor i, a := range args {@@ -67,7 +68,7 @@ func TestBuildGeminiArgsWithResume(t *testing.T) {func TestBuildGeminiArgsOmitsModelWhenEmpty(t *testing.T) {t.Parallel()- args := buildGeminiArgs("hi", ExecOptions{})+ args := buildGeminiArgs("hi", ExecOptions{}, slog.Default())for _, a := range args {if a == "-m" {t.Fatalf("expected no -m flag when Model is empty, got args=%v", args)@@ -77,3 +78,33 @@ func TestBuildGeminiArgsOmitsModelWhenEmpty(t *testing.T) {}}}++func TestBuildGeminiArgsPassesThroughCustomArgs(t *testing.T) {+ t.Parallel()++ args := buildGeminiArgs("hi", ExecOptions{+ CustomArgs: []string{"--sandbox"},+ }, slog.Default())++ if args[len(args)-1] != "--sandbox" {+ t.Fatalf("expected --sandbox at end of args, got %v", args)+ }+}++func TestBuildGeminiArgsFiltersBlockedCustomArgs(t *testing.T) {+ t.Parallel()++ args := buildGeminiArgs("hi", ExecOptions{+ CustomArgs: []string{"-o", "text", "--sandbox"},+ }, slog.Default())++ // -o text should be filtered, --sandbox should pass through+ for i, a := range args {+ if a == "-o" && i+1 < len(args) && args[i+1] == "text" {+ t.Fatalf("blocked -o text should have been filtered: %v", args)+ }+ }+ if args[len(args)-1] != "--sandbox" {+ t.Fatalf("expected --sandbox to pass through, got %v", args)+ }+}diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 244d5799a0..4a73b01286 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -34,7 +34,8 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}runCtx, cancel := context.WithTimeout(ctx, timeout)- cmd := exec.CommandContext(runCtx, execPath, "acp")+ hermesArgs := append([]string{"acp"}, opts.CustomArgs...)+ cmd := exec.CommandContext(runCtx, execPath, hermesArgs...)if opts.Cwd != "" {cmd.Dir = opts.Cwd}diff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.goindex 525ae12190..895d55f504 100644--- a/server/pkg/agent/openclaw.go+++ b/server/pkg/agent/openclaw.go@@ -11,6 +11,15 @@ import ("time")+// openclawBlockedArgs are flags hardcoded by the daemon that must not be+// overridden by user-configured custom_args.+var openclawBlockedArgs = map[string]blockedArgMode{+ "--local": blockedStandalone, // local mode for daemon execution+ "--json": blockedStandalone, // JSON output for daemon communication+ "--session-id": blockedWithValue, // managed by daemon for session resumption+ "--message": blockedWithValue, // prompt is set by daemon+}+// openclawBackend implements Backend by spawning `openclaw agent --message <prompt>// --output-format stream-json --yes` and reading streaming NDJSON events from// stdout — similar to the opencode backend.@@ -47,6 +56,7 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecOif opts.Timeout > 0 {args = append(args, "--timeout", fmt.Sprintf("%d", int(opts.Timeout.Seconds())))}+ args = append(args, filterCustomArgs(opts.CustomArgs, openclawBlockedArgs, b.cfg.Logger)...)args = append(args, "--message", prompt)cmd := exec.CommandContext(runCtx, execPath, args...)diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.goindex 8901ea8ffb..e97da2379b 100644--- a/server/pkg/agent/opencode.go+++ b/server/pkg/agent/opencode.go@@ -11,6 +11,12 @@ import ("time")+// opencodeBlockedArgs are flags hardcoded by the daemon that must not be+// overridden by user-configured custom_args.+var opencodeBlockedArgs = map[string]blockedArgMode{+ "--format": blockedWithValue, // json output format for daemon communication+}+// opencodeBackend implements Backend by spawning `opencode run --format json`// and reading streaming JSON events from stdout — the same pattern as Claude.type opencodeBackend struct {@@ -45,6 +51,7 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOif opts.ResumeSessionID != "" {args = append(args, "--session", opts.ResumeSessionID)}+ args = append(args, filterCustomArgs(opts.CustomArgs, opencodeBlockedArgs, b.cfg.Logger)...)args = append(args, prompt)cmd := exec.CommandContext(runCtx, execPath, args...)diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 4cf70ad135..24c71ca941 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -14,7 +14,7 @@ import (const archiveAgent = `-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args`type ArchiveAgentParams struct {@@ -44,6 +44,7 @@ func (q *Queries) ArchiveAgent(ctx context.Context, arg ArchiveAgentParams) (Age&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,)return i, err}@@ -217,9 +218,9 @@ const createAgent = `-- name: CreateAgent :oneINSERT INTO agent (workspace_id, name, description, avatar_url, runtime_mode,runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id,- instructions, custom_env-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env+ instructions, custom_env, custom_args+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args`type CreateAgentParams struct {@@ -235,6 +236,7 @@ type CreateAgentParams struct {OwnerID pgtype.UUID `json:"owner_id"`Instructions string `json:"instructions"`CustomEnv []byte `json:"custom_env"`+ CustomArgs []byte `json:"custom_args"`}func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) {@@ -251,6 +253,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agentarg.OwnerID,arg.Instructions,arg.CustomEnv,+ arg.CustomArgs,)var i Agenterr := row.Scan(@@ -272,6 +275,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,)return i, err}@@ -403,7 +407,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)}const getAgent = `-- name: GetAgent :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agentWHERE id = $1`@@ -429,12 +433,13 @@ func (q *Queries) GetAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,)return i, err}const getAgentInWorkspace = `-- name: GetAgentInWorkspace :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agentWHERE id = $1 AND workspace_id = $2`@@ -465,6 +470,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,)return i, err}@@ -665,7 +671,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag}const listAgents = `-- name: ListAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agentWHERE workspace_id = $1 AND archived_at IS NULLORDER BY created_at ASC`@@ -698,6 +704,7 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,); err != nil {return nil, err}@@ -710,7 +717,7 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag}const listAllAgents = `-- name: ListAllAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args FROM agentWHERE workspace_id = $1ORDER BY created_at ASC`@@ -743,6 +750,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,); err != nil {return nil, err}@@ -847,7 +855,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]const restoreAgent = `-- name: RestoreAgent :oneUPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args`func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -872,6 +880,7 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,)return i, err}@@ -922,9 +931,10 @@ UPDATE agent SETmax_concurrent_tasks = COALESCE($10, max_concurrent_tasks),instructions = COALESCE($11, instructions),custom_env = COALESCE($12, custom_env),+ custom_args = COALESCE($13, custom_args),updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args`type UpdateAgentParams struct {@@ -940,6 +950,7 @@ type UpdateAgentParams struct {MaxConcurrentTasks pgtype.Int4 `json:"max_concurrent_tasks"`Instructions pgtype.Text `json:"instructions"`CustomEnv []byte `json:"custom_env"`+ CustomArgs []byte `json:"custom_args"`}func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent, error) {@@ -956,6 +967,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentarg.MaxConcurrentTasks,arg.Instructions,arg.CustomEnv,+ arg.CustomArgs,)var i Agenterr := row.Scan(@@ -977,6 +989,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,)return i, err}@@ -984,7 +997,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentconst updateAgentStatus = `-- name: UpdateAgentStatus :oneUPDATE agent SET status = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args`type UpdateAgentStatusParams struct {@@ -1014,6 +1027,7 @@ func (q *Queries) UpdateAgentStatus(ctx context.Context, arg UpdateAgentStatusPa&i.ArchivedAt,&i.ArchivedBy,&i.CustomEnv,+ &i.CustomArgs,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex b35dbbe51d..a7b0931abd 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -38,6 +38,7 @@ type Agent struct {ArchivedAt pgtype.Timestamptz `json:"archived_at"`ArchivedBy pgtype.UUID `json:"archived_by"`CustomEnv []byte `json:"custom_env"`+ CustomArgs []byte `json:"custom_args"`}type AgentRuntime struct {diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 09e216adb1..b89d3efc85 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -20,8 +20,8 @@ WHERE id = $1 AND workspace_id = $2;INSERT INTO agent (workspace_id, name, description, avatar_url, runtime_mode,runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id,- instructions, custom_env-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)+ instructions, custom_env, custom_args+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)RETURNING *;-- name: UpdateAgent :one@@ -37,6 +37,7 @@ UPDATE agent SETmax_concurrent_tasks = COALESCE(sqlc.narg('max_concurrent_tasks'), max_concurrent_tasks),instructions = COALESCE(sqlc.narg('instructions'), instructions),custom_env = COALESCE(sqlc.narg('custom_env'), custom_env),+ custom_args = COALESCE(sqlc.narg('custom_args'), custom_args),updated_at = now()WHERE id = $1RETURNING *;