Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(cli): add 'multica agent copy' to fork an agent across runtimes (MUL-5279) (#5961)

Bohan Jiang3d4c5c7da2eb
diff --git a/server/cmd/multica/cmd_agent_copy.go b/server/cmd/multica/cmd_agent_copy.go
new file mode 100644
index 0000000000..289d00cf74
--- /dev/null
+++ b/server/cmd/multica/cmd_agent_copy.go
@@ -0,0 +1,278 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// agentCopyCmd forks an existing agent's portable configuration into a brand-new
+// agent, optionally on a different runtime, leaving the source untouched. It is
+// the CLI/headless equivalent of the web "Duplicate" action (MUL-5279). The
+// command is a thin composition over existing endpoints — GET the source, then
+// POST a create — so it needs no dedicated server API: `POST /api/agents`
+// already binds skill_ids in the same DB transaction as the agent row, so the
+// copy never becomes visible in a partially configured state.
+var agentCopyCmd = &cobra.Command{
+ Use: "copy <source-agent-id>",
+ Short: "Copy an existing agent into a new one (optionally on a different runtime)",
+ Long: `Copy an existing agent's portable configuration into a brand-new agent.
+
+The source agent is left untouched. By default the copy lands on the same
+runtime as the source; pass --runtime-id to fork it onto a different runtime.
+
+Copied by default, each overridable with the matching flag: name (suffixed
+" (copy)"), description, instructions, avatar, custom_args, max_concurrent_tasks,
+invocation permission (permission_mode + allow-list), assigned workspace skills,
+and — only when the target runtime is unchanged — model, thinking_level and
+service_tier.
+
+Secret and machine-local fields are never copied: custom_env, mcp_config and
+runtime_config. Supply fresh values for the copy with the same secret-safe flags
+as 'agent create' when the target machine needs them.
+
+Runtime-specific fields do not travel across a runtime change: when --runtime-id
+selects a different runtime, --model is required (pass --model "" to accept the
+target runtime's default), and thinking_level / service_tier are dropped unless
+set explicitly.`,
+ Args: exactArgs(1),
+ RunE: runAgentCopy,
+}
+
+func init() {
+ agentCmd.AddCommand(agentCopyCmd)
+ registerAgentCopyFlags(agentCopyCmd)
+}
+
+// registerAgentCopyFlags registers every flag runAgentCopy reads. It is shared
+// between init() and the tests so both stay in lockstep.
+func registerAgentCopyFlags(cmd *cobra.Command) {
+ cmd.Flags().String("name", "", "Name for the new agent (default: \"<source name> (copy)\")")
+ cmd.Flags().String("runtime-id", "", "Target runtime ID (default: the source agent's runtime). A different value forks the agent onto that runtime.")
+ cmd.Flags().String("description", "", "Override the copied description")
+ cmd.Flags().String("instructions", "", "Override the copied instructions")
+ cmd.Flags().String("model", "", "Model identifier for the copy. Required when --runtime-id selects a different runtime (pass \"\" to accept the target runtime default). Empty otherwise = runtime default.")
+ cmd.Flags().String("thinking-level", "", "Override thinking level. Not carried across a runtime change unless set here.")
+ cmd.Flags().String("service-tier", "", "Override Codex service tier. Not carried across a runtime change unless set here.")
+ cmd.Flags().String("custom-args", "", "Override custom CLI arguments as a JSON array.")
+ cmd.Flags().Int32("max-concurrent-tasks", 6, "Override maximum concurrent tasks")
+ cmd.Flags().String("visibility", "", "Override visibility: private or workspace (legacy; mapped to --permission-mode)")
+ cmd.Flags().String("permission-mode", "", "Override invocation permission mode: private or public_to. Authoritative over --visibility.")
+ cmd.Flags().Bool("public-to-workspace", false, "public_to: allow every workspace member to invoke the copy.")
+ cmd.Flags().StringSlice("public-to-member", nil, "public_to: allow the given member user id(s) to invoke the copy. Repeatable.")
+ cmd.Flags().Bool("no-skills", false, "Do not copy the source agent's workspace skill assignments.")
+ // Secret / machine-local fields are never copied from the source; these
+ // flags provide fresh values for the copy, mirroring 'agent create'.
+ cmd.Flags().String("custom-env", "", "Set custom_env on the copy as a JSON object (never copied from the source). Prefer --custom-env-stdin/--custom-env-file for secrets. Pass '{}' for an empty map.")
+ cmd.Flags().Bool("custom-env-stdin", false, "Read --custom-env from stdin. Mutually exclusive with --custom-env and --custom-env-file.")
+ cmd.Flags().String("custom-env-file", "", "Read --custom-env from a file path (suggested mode: 0600). Mutually exclusive with --custom-env and --custom-env-stdin.")
+ cmd.Flags().String("mcp-config", "", "Set mcp_config on the copy as a JSON object (never copied from the source). Prefer --mcp-config-stdin/--mcp-config-file for secrets.")
+ cmd.Flags().Bool("mcp-config-stdin", false, "Read --mcp-config from stdin. Mutually exclusive with --mcp-config and --mcp-config-file.")
+ cmd.Flags().String("mcp-config-file", "", "Read --mcp-config from a file path (suggested mode: 0600). Mutually exclusive with --mcp-config and --mcp-config-stdin.")
+ cmd.Flags().String("runtime-config", "", "Set runtime_config on the copy as a JSON string (never copied from the source).")
+ cmd.Flags().String("output", "json", "Output format: table or json")
+}
+
+// runAgentCopy reads the source agent and assembles a create request from its
+// portable fields, then POSTs it. custom_env, mcp_config and runtime_config are
+// never read back from the source — GET redacts / masks them anyway — and are
+// set only when supplied explicitly on the command line.
+func runAgentCopy(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ var src map[string]any
+ if err := client.GetJSON(ctx, "/api/agents/"+args[0], &src); err != nil {
+ return fmt.Errorf("get source agent: %w", err)
+ }
+
+ srcRuntimeID := strVal(src, "runtime_id")
+
+ // Resolve the target runtime: default to the source's runtime, override
+ // with --runtime-id. A different value is a cross-runtime fork.
+ targetRuntimeID := srcRuntimeID
+ if cmd.Flags().Changed("runtime-id") {
+ v, _ := cmd.Flags().GetString("runtime-id")
+ if v == "" {
+ return fmt.Errorf("--runtime-id must not be empty")
+ }
+ targetRuntimeID = v
+ }
+ if targetRuntimeID == "" {
+ return fmt.Errorf("source agent has no runtime; pass --runtime-id to choose a target runtime")
+ }
+ sameRuntime := targetRuntimeID == srcRuntimeID
+
+ // Name: default "<source name> (copy)", override with --name.
+ name := strVal(src, "name") + " (copy)"
+ if cmd.Flags().Changed("name") {
+ v, _ := cmd.Flags().GetString("name")
+ if v == "" {
+ return fmt.Errorf("--name must not be empty")
+ }
+ name = v
+ }
+
+ body := map[string]any{
+ "name": name,
+ "runtime_id": targetRuntimeID,
+ }
+
+ // Plain-text fields: copy from source, override with the matching flag.
+ body["description"] = strVal(src, "description")
+ if cmd.Flags().Changed("description") {
+ v, _ := cmd.Flags().GetString("description")
+ body["description"] = v
+ }
+ body["instructions"] = strVal(src, "instructions")
+ if cmd.Flags().Changed("instructions") {
+ v, _ := cmd.Flags().GetString("instructions")
+ body["instructions"] = v
+ }
+
+ // Avatar reference travels with the copy (both agents point at the same
+ // uploaded image URL), matching the web Duplicate flow.
+ if av, ok := src["avatar_url"]; ok && av != nil {
+ body["avatar_url"] = av
+ }
+
+ // custom_args: copy when present, override with --custom-args.
+ if ca, ok := src["custom_args"].([]any); ok && len(ca) > 0 {
+ body["custom_args"] = ca
+ }
+ if cmd.Flags().Changed("custom-args") {
+ v, _ := cmd.Flags().GetString("custom-args")
+ ca, err := parseCustomArgs(v)
+ if err != nil {
+ return err
+ }
+ body["custom_args"] = ca
+ }
+
+ // max_concurrent_tasks: copy the source's value, override with the flag.
+ if v, ok := src["max_concurrent_tasks"]; ok && v != nil {
+ body["max_concurrent_tasks"] = v
+ }
+ if cmd.Flags().Changed("max-concurrent-tasks") {
+ v, _ := cmd.Flags().GetInt32("max-concurrent-tasks")
+ body["max_concurrent_tasks"] = v
+ }
+
+ // Runtime-specific fields (model / thinking_level / service_tier) only make
+ // sense on the runtime they were chosen for. Copy them when staying on the
+ // same runtime; when forking to a different runtime, drop them and require
+ // an explicit --model (pass --model "" to accept the target default) —
+ // mirroring the web Duplicate clearing model on a runtime switch.
+ if sameRuntime {
+ if v := strVal(src, "model"); v != "" {
+ body["model"] = v
+ }
+ if v := strVal(src, "thinking_level"); v != "" {
+ body["thinking_level"] = v
+ }
+ if v := strVal(src, "service_tier"); v != "" {
+ body["service_tier"] = v
+ }
+ } else if !cmd.Flags().Changed("model") {
+ return fmt.Errorf("copying to a different runtime (--runtime-id) requires --model, because the source model may not exist on the target runtime; pass --model \"\" to accept the target runtime default")
+ }
+ if cmd.Flags().Changed("model") {
+ v, _ := cmd.Flags().GetString("model")
+ body["model"] = v
+ }
+ if cmd.Flags().Changed("thinking-level") {
+ v, _ := cmd.Flags().GetString("thinking-level")
+ body["thinking_level"] = v
+ }
+ if cmd.Flags().Changed("service-tier") {
+ v, _ := cmd.Flags().GetString("service-tier")
+ body["service_tier"] = v
+ }
+
+ // Invocation permission: copy the source's permission_mode + allow-list by
+ // default; any permission flag (or legacy --visibility) fully defines it
+ // instead, so the two never mix.
+ permOverride := cmd.Flags().Changed("permission-mode") ||
+ cmd.Flags().Changed("public-to-workspace") ||
+ cmd.Flags().Changed("public-to-member") ||
+ cmd.Flags().Changed("visibility")
+ if permOverride {
+ if cmd.Flags().Changed("visibility") {
+ v, _ := cmd.Flags().GetString("visibility")
+ body["visibility"] = v
+ }
+ applyAgentPermissionFlags(cmd, body)
+ } else {
+ if pm := strVal(src, "permission_mode"); pm != "" {
+ body["permission_mode"] = pm
+ }
+ if it, ok := src["invocation_targets"]; ok && it != nil {
+ body["invocation_targets"] = it
+ }
+ }
+
+ // Workspace skills: copy the source's bindings so they attach in the same
+ // create transaction, unless --no-skills.
+ if noSkills, _ := cmd.Flags().GetBool("no-skills"); !noSkills {
+ if skills, ok := src["skills"].([]any); ok {
+ ids := make([]string, 0, len(skills))
+ for _, s := range skills {
+ m, ok := s.(map[string]any)
+ if !ok {
+ continue
+ }
+ if id := strVal(m, "id"); id != "" {
+ ids = append(ids, id)
+ }
+ }
+ if len(ids) > 0 {
+ body["skill_ids"] = ids
+ }
+ }
+ }
+
+ // Secret / machine-local fields are never copied from the source (they are
+ // redacted or masked on GET). Set them only when supplied explicitly, via
+ // the same secret-safe channels as 'agent create'.
+ if ce, ok, err := resolveCustomEnv(cmd); err != nil {
+ return err
+ } else if ok {
+ body["custom_env"] = ce
+ }
+ if mc, ok, err := resolveMcpConfig(cmd); err != nil {
+ return err
+ } else if ok {
+ body["mcp_config"] = mc
+ }
+ if cmd.Flags().Changed("runtime-config") {
+ v, _ := cmd.Flags().GetString("runtime-config")
+ var rc any
+ if err := json.Unmarshal([]byte(v), &rc); err != nil {
+ return fmt.Errorf("--runtime-config must be valid JSON: %w", err)
+ }
+ body["runtime_config"] = rc
+ }
+
+ var result map[string]any
+ if err := client.PostJSON(ctx, "/api/agents", body, &result); err != nil {
+ return fmt.Errorf("copy agent: %w", err)
+ }
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, result)
+ }
+
+ fmt.Printf("Agent copied: %s (%s)\n", strVal(result, "name"), strVal(result, "id"))
+ return nil
+}
diff --git a/server/cmd/multica/cmd_agent_copy_test.go b/server/cmd/multica/cmd_agent_copy_test.go
new file mode 100644
index 0000000000..e406a28735
--- /dev/null
+++ b/server/cmd/multica/cmd_agent_copy_test.go
@@ -0,0 +1,306 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+// newAgentCopyTestCmd builds a standalone cobra.Command carrying the same flags
+// runAgentCopy reads (via the shared registrar), plus the persistent --profile
+// flag the API-client resolver needs. Tests mutate its flag state in isolation.
+func newAgentCopyTestCmd() *cobra.Command {
+ c := &cobra.Command{Use: "copy"}
+ registerAgentCopyFlags(c)
+ c.Flags().String("profile", "", "")
+ return c
+}
+
+// fullSourceAgent is a representative GET /api/agents/<id> response with every
+// portable field populated, so copy tests can assert the whole whitelist.
+func fullSourceAgent() map[string]any {
+ return map[string]any{
+ "id": "agent-src",
+ "name": "Src",
+ "runtime_id": "runtime-1",
+ "description": "a description",
+ "instructions": "some instructions",
+ "avatar_url": "https://img.example/a.png",
+ "custom_args": []any{"--foo", "--bar"},
+ "max_concurrent_tasks": 9,
+ "model": "claude-sonnet-4-6",
+ "thinking_level": "high",
+ "service_tier": "priority",
+ "permission_mode": "public_to",
+ "invocation_targets": []any{map[string]any{"target_type": "workspace"}},
+ "skills": []any{
+ map[string]any{"id": "skill-1", "name": "One"},
+ map[string]any{"id": "skill-2", "name": "Two"},
+ },
+ // Secret metadata the copy must never turn into real values.
+ "has_custom_env": true,
+ "custom_env_key_count": 2,
+ "mcp_config_redacted": true,
+ }
+}
+
+// copyMockServer serves the source agent on GET and captures the create body on
+// POST. The captured body pointer is filled in when the POST fires.
+func copyMockServer(t *testing.T, source map[string]any, gotBody *map[string]any) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/agents/"+source["id"].(string):
+ _ = json.NewEncoder(w).Encode(source)
+ case r.Method == http.MethodPost && r.URL.Path == "/api/agents":
+ if err := json.NewDecoder(r.Body).Decode(gotBody); err != nil {
+ t.Errorf("decode create body: %v", err)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "agent-new", "name": "Src (copy)"})
+ default:
+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+}
+
+func setCopyTestEnv(t *testing.T, serverURL string) {
+ t.Helper()
+ // Run from a fresh temp dir so no daemon-task marker sits in the cwd
+ // ancestry: the CLI then treats this as a normal (non-agent) context and
+ // accepts the plain test token instead of demanding a task-scoped mat_ one.
+ t.Chdir(t.TempDir())
+ t.Setenv("MULTICA_SERVER_URL", serverURL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+ t.Setenv("MULTICA_AGENT_ID", "")
+ t.Setenv("MULTICA_TASK_ID", "")
+}
+
+func TestAgentCopySameRuntimeCopiesPortableFields(t *testing.T) {
+ var gotBody map[string]any
+ srv := copyMockServer(t, fullSourceAgent(), &gotBody)
+ defer srv.Close()
+ setCopyTestEnv(t, srv.URL)
+
+ cmd := newAgentCopyTestCmd()
+ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {
+ t.Fatalf("runAgentCopy: %v", err)
+ }
+
+ if gotBody == nil {
+ t.Fatal("create was never called")
+ }
+ if gotBody["name"] != "Src (copy)" {
+ t.Errorf("name = %v, want \"Src (copy)\"", gotBody["name"])
+ }
+ // No --runtime-id: the copy stays on the source runtime.
+ if gotBody["runtime_id"] != "runtime-1" {
+ t.Errorf("runtime_id = %v, want runtime-1", gotBody["runtime_id"])
+ }
+ if gotBody["description"] != "a description" {
+ t.Errorf("description = %v", gotBody["description"])
+ }
+ if gotBody["instructions"] != "some instructions" {
+ t.Errorf("instructions = %v", gotBody["instructions"])
+ }
+ if gotBody["avatar_url"] != "https://img.example/a.png" {
+ t.Errorf("avatar_url = %v", gotBody["avatar_url"])
+ }
+ if !reflect.DeepEqual(gotBody["custom_args"], []any{"--foo", "--bar"}) {
+ t.Errorf("custom_args = %v", gotBody["custom_args"])
+ }
+ if gotBody["max_concurrent_tasks"] != float64(9) {
+ t.Errorf("max_concurrent_tasks = %v, want 9", gotBody["max_concurrent_tasks"])
+ }
+ // Same runtime: runtime-specific fields are carried over.
+ if gotBody["model"] != "claude-sonnet-4-6" {
+ t.Errorf("model = %v", gotBody["model"])
+ }
+ if gotBody["thinking_level"] != "high" {
+ t.Errorf("thinking_level = %v", gotBody["thinking_level"])
+ }
+ if gotBody["service_tier"] != "priority" {
+ t.Errorf("service_tier = %v", gotBody["service_tier"])
+ }
+ // Invocation permission is copied verbatim.
+ if gotBody["permission_mode"] != "public_to" {
+ t.Errorf("permission_mode = %v", gotBody["permission_mode"])
+ }
+ if !reflect.DeepEqual(gotBody["invocation_targets"], []any{map[string]any{"target_type": "workspace"}}) {
+ t.Errorf("invocation_targets = %v", gotBody["invocation_targets"])
+ }
+ // Skills bind in the same create request.
+ if !reflect.DeepEqual(gotBody["skill_ids"], []any{"skill-1", "skill-2"}) {
+ t.Errorf("skill_ids = %v, want [skill-1 skill-2]", gotBody["skill_ids"])
+ }
+ // Secrets / machine-local config must never be copied.
+ for _, k := range []string{"custom_env", "mcp_config", "runtime_config", "has_custom_env"} {
+ if _, ok := gotBody[k]; ok {
+ t.Errorf("body must not contain %q, got %v", k, gotBody[k])
+ }
+ }
+}
+
+func TestAgentCopyCrossRuntimeRequiresModel(t *testing.T) {
+ postCalled := false
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodGet {
+ _ = json.NewEncoder(w).Encode(fullSourceAgent())
+ return
+ }
+ postCalled = true
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "agent-new"})
+ }))
+ defer srv.Close()
+ setCopyTestEnv(t, srv.URL)
+
+ cmd := newAgentCopyTestCmd()
+ _ = cmd.Flags().Set("runtime-id", "runtime-2")
+
+ err := runAgentCopy(cmd, []string{"agent-src"})
+ if err == nil {
+ t.Fatal("expected error when copying across runtimes without --model")
+ }
+ if !strings.Contains(err.Error(), "--model") {
+ t.Errorf("error = %q, want it to mention --model", err.Error())
+ }
+ if postCalled {
+ t.Error("create must not be called when validation fails")
+ }
+}
+
+func TestAgentCopyCrossRuntimeDropsRuntimeSpecificFields(t *testing.T) {
+ var gotBody map[string]any
+ srv := copyMockServer(t, fullSourceAgent(), &gotBody)
+ defer srv.Close()
+ setCopyTestEnv(t, srv.URL)
+
+ cmd := newAgentCopyTestCmd()
+ _ = cmd.Flags().Set("runtime-id", "runtime-2")
+ _ = cmd.Flags().Set("model", "openai/gpt-4o")
+
+ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {
+ t.Fatalf("runAgentCopy: %v", err)
+ }
+ if gotBody["runtime_id"] != "runtime-2" {
+ t.Errorf("runtime_id = %v, want runtime-2", gotBody["runtime_id"])
+ }
+ if gotBody["model"] != "openai/gpt-4o" {
+ t.Errorf("model = %v, want openai/gpt-4o", gotBody["model"])
+ }
+ // thinking_level / service_tier are runtime-specific and must NOT ride
+ // across a runtime change unless set explicitly.
+ if _, ok := gotBody["thinking_level"]; ok {
+ t.Errorf("thinking_level must be dropped on a runtime change, got %v", gotBody["thinking_level"])
+ }
+ if _, ok := gotBody["service_tier"]; ok {
+ t.Errorf("service_tier must be dropped on a runtime change, got %v", gotBody["service_tier"])
+ }
+ // Skills still travel across the runtime change.
+ if !reflect.DeepEqual(gotBody["skill_ids"], []any{"skill-1", "skill-2"}) {
+ t.Errorf("skill_ids = %v", gotBody["skill_ids"])
+ }
+}
+
+// Passing --model "" across a runtime change is an explicit "accept the target
+// runtime default" and must satisfy the required-model gate.
+func TestAgentCopyCrossRuntimeEmptyModelIsAllowed(t *testing.T) {
+ var gotBody map[string]any
+ srv := copyMockServer(t, fullSourceAgent(), &gotBody)
+ defer srv.Close()
+ setCopyTestEnv(t, srv.URL)
+
+ cmd := newAgentCopyTestCmd()
+ _ = cmd.Flags().Set("runtime-id", "runtime-2")
+ _ = cmd.Flags().Set("model", "")
+
+ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {
+ t.Fatalf("runAgentCopy: %v", err)
+ }
+ if gotBody["model"] != "" {
+ t.Errorf("model = %v, want empty string", gotBody["model"])
+ }
+}
+
+func TestAgentCopyNoSkillsOmitsSkillIDs(t *testing.T) {
+ var gotBody map[string]any
+ srv := copyMockServer(t, fullSourceAgent(), &gotBody)
+ defer srv.Close()
+ setCopyTestEnv(t, srv.URL)
+
+ cmd := newAgentCopyTestCmd()
+ _ = cmd.Flags().Set("no-skills", "true")
+
+ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {
+ t.Fatalf("runAgentCopy: %v", err)
+ }
+ if _, ok := gotBody["skill_ids"]; ok {
+ t.Errorf("skill_ids must be omitted with --no-skills, got %v", gotBody["skill_ids"])
+ }
+}
+
+// A permission override flag fully defines the copy's permission and must not
+// mix with the source's copied permission_mode / allow-list.
+func TestAgentCopyPermissionOverrideReplacesSource(t *testing.T) {
+ var gotBody map[string]any
+ srv := copyMockServer(t, fullSourceAgent(), &gotBody)
+ defer srv.Close()
+ setCopyTestEnv(t, srv.URL)
+
+ cmd := newAgentCopyTestCmd()
+ _ = cmd.Flags().Set("permission-mode", "private")
+
+ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {
+ t.Fatalf("runAgentCopy: %v", err)
+ }
+ if gotBody["permission_mode"] != "private" {
+ t.Errorf("permission_mode = %v, want private", gotBody["permission_mode"])
+ }
+ // applyAgentPermissionFlags emits an explicit empty allow-list; the source's
+ // workspace target must be gone.
+ if got, ok := gotBody["invocation_targets"].([]any); !ok || len(got) != 0 {
+ t.Errorf("invocation_targets = %v, want empty list", gotBody["invocation_targets"])
+ }
+}
+
+// custom_env is never read from the source, but an explicit --custom-env sets a
+// fresh map on the copy.
+func TestAgentCopyAcceptsExplicitCustomEnv(t *testing.T) {
+ var gotBody map[string]any
+ srv := copyMockServer(t, fullSourceAgent(), &gotBody)
+ defer srv.Close()
+ setCopyTestEnv(t, srv.URL)
+
+ cmd := newAgentCopyTestCmd()
+ _ = cmd.Flags().Set("custom-env", `{"API_KEY":"fresh"}`)
+
+ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {
+ t.Fatalf("runAgentCopy: %v", err)
+ }
+ ce, ok := gotBody["custom_env"].(map[string]any)
+ if !ok {
+ t.Fatalf("custom_env = %v, want a JSON object", gotBody["custom_env"])
+ }
+ if ce["API_KEY"] != "fresh" {
+ t.Errorf("custom_env[API_KEY] = %v, want fresh", ce["API_KEY"])
+ }
+}
+
+// The copy command must expose the same secret-safe input channels as create so
+// scripts can keep secrets off the command line.
+func TestAgentCopyExposesSecretSafeFlags(t *testing.T) {
+ for _, name := range []string{
+ "custom-env-stdin", "custom-env-file",
+ "mcp-config-stdin", "mcp-config-file",
+ } {
+ if agentCopyCmd.Flag(name) == nil {
+ t.Errorf("agent copy is missing the %q flag", name)
+ }
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
index d2425a70a6..ca8d9a8e33 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md
@@ -64,7 +64,37 @@ flags fall through to server defaults rather than sending empty strings.
The HTTP body (`CreateAgentRequest`) accepts: `name`, `description`,
`instructions`, `avatar_url`, `runtime_id`, `runtime_config`, `custom_env`,
`custom_args`, `model`, `thinking_level`, `service_tier`, `visibility`,
-`max_concurrent_tasks`, `mcp_config`.
+`max_concurrent_tasks`, `mcp_config`, `skill_ids`.
+
+## Copying an agent
+
+`multica agent copy <source-agent-id>` forks an existing agent's portable
+configuration into a brand-new agent, leaving the source untouched. It is the
+CLI/headless equivalent of the web "Duplicate" action. No dedicated server API
+is involved: `runAgentCopy` reads the source with `GET /api/agents/<id>`, then
+POSTs a `CreateAgentRequest` — passing the source's skill ids in `skill_ids` so
+the bindings attach in the SAME create transaction (unlike `agent create`, which
+binds nothing). The mutation is therefore a single atomic create.
+
+```bash
+multica agent copy <source-agent-id> --name "My Agent (copy)" # same runtime
+multica agent copy <source-agent-id> --runtime-id <target> --model <model> # cross-runtime fork
+```
+
+- Copied by default, each overridable with the matching flag: `name` (suffixed
+ `" (copy)"`), `description`, `instructions`, avatar, `custom_args`,
+ `max_concurrent_tasks`, invocation permission (`permission_mode` +
+ allow-list), and assigned workspace skills.
+- Runtime-specific fields (`model`, `thinking_level`, `service_tier`) are copied
+ ONLY when the target runtime is unchanged. `--runtime-id` selecting a
+ different runtime drops them and REQUIRES `--model` (pass `--model ""` to
+ accept the target runtime default), mirroring the web Duplicate clearing model
+ on a runtime switch.
+- Never copied: `custom_env`, `mcp_config`, `runtime_config` (secret /
+ machine-local; redacted or masked on read anyway). Supply fresh values with
+ the same secret-safe flags as `agent create` (`--custom-env*`, `--mcp-config*`,
+ `--runtime-config`), or with `agent env set` after the copy exists.
+- `--no-skills` skips copying the source's skill bindings.
## Field contracts
@@ -215,6 +245,8 @@ Read-only (safe): `agent get`, `agent skills list`, `agent env get`.
State-changing (require an explicit instruction — do not run speculatively):
- `multica agent create` — inserts a new agent row.
+- `multica agent copy` — inserts a new agent row (a fork of an existing agent);
+ the source is left untouched.
- `multica agent skills add` / `set` — mutate bindings (`set` is destructive:
it drops bindings not in the new list).
- `multica agent env set` — overwrites the full `custom_env` map and writes an
diff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
index 71fc04e02d..1e61b45a6e 100644
--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
+++ b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md
@@ -33,6 +33,16 @@ go test ./internal/service -run TestBuiltinSkillsConformToTemplate
| `agent env get` | 1018 | `GET /api/agents/{id}/env` (1028) | `multica agent env get --help` |
| `agent env set` | 1053 | `PUT /api/agents/{id}/env` with full `custom_env` map (1073) | `multica agent env set --help` |
+## Copy command — `server/cmd/multica/cmd_agent_copy.go`
+
+| Contract | Line | Behavior | Safe check |
+|---|---|---|---|
+| `agentCopyCmd` (`copy <source-agent-id>`) + flag registrar | 21, 47, 54 | Own file with its own `init()` so `cmd_agent.go` line refs stay stable; `registerAgentCopyFlags` is shared with the tests | `multica agent copy --help` |
+| Reads source via `GET /api/agents/<id>` | 95 | Composes over existing endpoints — no dedicated copy API | read `runAgentCopy` |
+| Same-runtime vs cross-runtime rule | 114, 187 | `sameRuntime` copies `model`/`thinking_level`/`service_tier`; a different `--runtime-id` drops them and requires `--model` (empty allowed) | `multica agent copy --help` |
+| Skills copied in the create transaction | 239 | Source skill ids sent as `skill_ids`, bound in the same `POST /api/agents` tx (267); `--no-skills` opts out | read `runAgentCopy` |
+| Secrets never copied | 240–266 | `custom_env`/`mcp_config`/`runtime_config` set only from explicit secret-safe flags, never read from the source | `multica agent copy --help` |
+
Note: the CLI no longer exposes `--from-template`. The agent-template backend
still exists (registry `server/internal/agenttmpl/`, handler `agent_template.go`,
routes `GET /api/agent-templates` and `POST /api/agents/from-template`, plus the