From 362b9d8e1e71cdeebd57c66b9851a13d4394f840 Mon Sep 17 00:00:00 2001 From: Devansh Jain <31609257+devanshrj@users.noreply.github.com> Date: Fri, 19 Dec 2025 17:44:19 -0800 Subject: [PATCH] chore: Add cloning module (#329) --- src/agent/clone.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/agent/clone.ts diff --git a/src/agent/clone.ts b/src/agent/clone.ts new file mode 100644 index 0000000..4e10db2 --- /dev/null +++ b/src/agent/clone.ts @@ -0,0 +1,56 @@ +/** + * Clone an existing agent by exporting and re-importing it + */ + +import { toFile } from "@letta-ai/letta-client"; +import type { AgentState } from "@letta-ai/letta-client/resources/agents/agents"; +import { getClient } from "./client"; + +export interface CloneAgentOptions { + /** The ID of the agent to clone */ + agentId: string; +} + +export interface CloneAgentResult { + /** The newly created cloned agent */ + agent: AgentState; +} + +/** + * Clone an agent by exporting and re-importing it. + * The cloned agent will have a new ID and name (with "_copy" suffix). + * Message history is always preserved. + */ +export async function cloneAgent( + options: CloneAgentOptions, +): Promise { + const client = await getClient(); + + // Step 1: Export the source agent + const exportedData = await client.agents.exportFile(options.agentId); + + // Handle both string and object responses from exportFile + const jsonString = + typeof exportedData === "string" + ? exportedData + : JSON.stringify(exportedData); + + // Step 2: Create a File object from the exported data + const file = await toFile(Buffer.from(jsonString), "agent-export.af"); + + // Step 3: Import to create a new agent + const importResponse = await client.agents.importFile({ + file, + strip_messages: false, + override_existing_tools: false, + }); + + if (!importResponse.agent_ids || importResponse.agent_ids.length === 0) { + throw new Error("Clone failed: no agent IDs returned from import"); + } + + const newAgentId = importResponse.agent_ids[0] as string; + const agent = await client.agents.retrieve(newAgentId); + + return { agent }; +}