@letta-ai/letta-code 0.14.4 → 0.14.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,229 +0,0 @@
1
- #!/usr/bin/env npx tsx
2
- /**
3
- * Start Conversation - Start a new conversation with an agent and send a message
4
- *
5
- * This script is standalone and can be run outside the CLI process.
6
- * It reads auth from LETTA_API_KEY env var or ~/.letta/settings.json.
7
- * It reads sender agent ID from LETTA_AGENT_ID env var.
8
- *
9
- * Usage:
10
- * npx tsx start-conversation.ts --agent-id <id> --message "<text>"
11
- *
12
- * Options:
13
- * --agent-id <id> Target agent ID to message (required)
14
- * --message <text> Message to send (required)
15
- * --timeout <ms> Max wait time in ms (default: 120000)
16
- *
17
- * Output:
18
- * JSON with conversation_id, response, agent_id, agent_name
19
- */
20
-
21
- import { readFileSync } from "node:fs";
22
- import { createRequire } from "node:module";
23
- import { homedir } from "node:os";
24
- import { join } from "node:path";
25
- import {
26
- SYSTEM_REMINDER_CLOSE,
27
- SYSTEM_REMINDER_OPEN,
28
- } from "../../../../constants";
29
-
30
- // Use createRequire for @letta-ai/letta-client so NODE_PATH is respected
31
- // (ES module imports don't respect NODE_PATH, but require does)
32
- const require = createRequire(import.meta.url);
33
- const Letta = require("@letta-ai/letta-client")
34
- .default as typeof import("@letta-ai/letta-client").default;
35
- type LettaClient = InstanceType<typeof Letta>;
36
-
37
- interface StartConversationOptions {
38
- agentId: string;
39
- message: string;
40
- timeout?: number;
41
- }
42
-
43
- interface StartConversationResult {
44
- conversation_id: string;
45
- response: string;
46
- agent_id: string;
47
- agent_name: string;
48
- }
49
-
50
- /**
51
- * Get API key from env var or settings file
52
- */
53
- function getApiKey(): string {
54
- if (process.env.LETTA_API_KEY) {
55
- return process.env.LETTA_API_KEY;
56
- }
57
-
58
- const settingsPath = join(homedir(), ".letta", "settings.json");
59
- try {
60
- const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
61
- if (settings.env?.LETTA_API_KEY) {
62
- return settings.env.LETTA_API_KEY;
63
- }
64
- } catch {
65
- // Settings file doesn't exist or is invalid
66
- }
67
-
68
- throw new Error(
69
- "No LETTA_API_KEY found. Set the env var or run the Letta CLI to authenticate.",
70
- );
71
- }
72
-
73
- /**
74
- * Get the sender agent ID from env var
75
- */
76
- function getSenderAgentId(): string {
77
- if (process.env.LETTA_AGENT_ID) {
78
- return process.env.LETTA_AGENT_ID;
79
- }
80
- throw new Error(
81
- "No LETTA_AGENT_ID found. This script should be run from within a Letta Code session.",
82
- );
83
- }
84
-
85
- /**
86
- * Create a Letta client with auth from env/settings
87
- */
88
- function createClient(): LettaClient {
89
- return new Letta({ apiKey: getApiKey() });
90
- }
91
-
92
- /**
93
- * Build the system reminder prefix for the message
94
- */
95
- function buildSystemReminder(
96
- senderAgentName: string,
97
- senderAgentId: string,
98
- ): string {
99
- return `${SYSTEM_REMINDER_OPEN}
100
- This message is from "${senderAgentName}" (agent ID: ${senderAgentId}), an agent currently running inside the Letta Code CLI (docs.letta.com/letta-code).
101
- The sender will only see the final message you generate (not tool calls or reasoning).
102
- If you need to share detailed information, include it in your response text.
103
- ${SYSTEM_REMINDER_CLOSE}
104
-
105
- `;
106
- }
107
-
108
- /**
109
- * Start a new conversation with an agent and send a message
110
- * @param client - Letta client instance
111
- * @param options - Options including target agent ID and message
112
- * @returns Conversation result with response and metadata
113
- */
114
- export async function startConversation(
115
- client: LettaClient,
116
- options: StartConversationOptions,
117
- ): Promise<StartConversationResult> {
118
- const { agentId, message } = options;
119
-
120
- // 1. Fetch target agent to validate existence and get name
121
- const targetAgent = await client.agents.retrieve(agentId);
122
-
123
- // 2. Fetch sender agent to get name for system reminder
124
- const senderAgentId = getSenderAgentId();
125
- const senderAgent = await client.agents.retrieve(senderAgentId);
126
-
127
- // 3. Create new conversation
128
- const conversation = await client.conversations.create({
129
- agent_id: agentId,
130
- });
131
-
132
- // 4. Build message with system reminder prefix
133
- const systemReminder = buildSystemReminder(senderAgent.name, senderAgentId);
134
- const fullMessage = systemReminder + message;
135
-
136
- // 5. Send message and consume the stream
137
- // Note: conversations.messages.create always returns a Stream
138
- const stream = await client.conversations.messages.create(conversation.id, {
139
- input: fullMessage,
140
- });
141
-
142
- // 6. Consume stream and extract final assistant message
143
- let finalResponse = "";
144
- for await (const chunk of stream) {
145
- if (process.env.DEBUG) {
146
- console.error("Chunk:", JSON.stringify(chunk, null, 2));
147
- }
148
- if (chunk.message_type === "assistant_message") {
149
- // Content can be string or array of content parts
150
- const content = chunk.content;
151
- if (typeof content === "string") {
152
- finalResponse += content;
153
- } else if (Array.isArray(content)) {
154
- for (const part of content) {
155
- if (
156
- typeof part === "object" &&
157
- part !== null &&
158
- "type" in part &&
159
- part.type === "text" &&
160
- "text" in part
161
- ) {
162
- finalResponse += (part as { text: string }).text;
163
- }
164
- }
165
- }
166
- }
167
- }
168
-
169
- return {
170
- conversation_id: conversation.id,
171
- response: finalResponse,
172
- agent_id: targetAgent.id,
173
- agent_name: targetAgent.name,
174
- };
175
- }
176
-
177
- function parseArgs(args: string[]): StartConversationOptions {
178
- const agentIdIndex = args.indexOf("--agent-id");
179
- if (agentIdIndex === -1 || agentIdIndex + 1 >= args.length) {
180
- throw new Error("Missing required argument: --agent-id <agent-id>");
181
- }
182
- const agentId = args[agentIdIndex + 1] as string;
183
-
184
- const messageIndex = args.indexOf("--message");
185
- if (messageIndex === -1 || messageIndex + 1 >= args.length) {
186
- throw new Error("Missing required argument: --message <text>");
187
- }
188
- const message = args[messageIndex + 1] as string;
189
-
190
- const options: StartConversationOptions = { agentId, message };
191
-
192
- const timeoutIndex = args.indexOf("--timeout");
193
- if (timeoutIndex !== -1 && timeoutIndex + 1 < args.length) {
194
- const timeout = Number.parseInt(args[timeoutIndex + 1] as string, 10);
195
- if (!Number.isNaN(timeout)) {
196
- options.timeout = timeout;
197
- }
198
- }
199
-
200
- return options;
201
- }
202
-
203
- // CLI entry point - check if this file is being run directly
204
- const isMainModule = import.meta.url === `file://${process.argv[1]}`;
205
- if (isMainModule) {
206
- (async () => {
207
- try {
208
- const options = parseArgs(process.argv.slice(2));
209
- const client = createClient();
210
- const result = await startConversation(client, options);
211
- console.log(JSON.stringify(result, null, 2));
212
- process.exit(0);
213
- } catch (error) {
214
- console.error(
215
- "Error:",
216
- error instanceof Error ? error.message : String(error),
217
- );
218
- console.error(`
219
- Usage: npx tsx start-conversation.ts --agent-id <id> --message "<text>"
220
-
221
- Options:
222
- --agent-id <id> Target agent ID to message (required)
223
- --message <text> Message to send (required)
224
- --timeout <ms> Max wait time in ms (default: 120000)
225
- `);
226
- process.exit(1);
227
- }
228
- })();
229
- }
@@ -1,230 +0,0 @@
1
- #!/usr/bin/env npx tsx
2
- /**
3
- * Attach Block - Attaches an existing memory block to an agent (sharing)
4
- *
5
- * This script is standalone and can be run outside the CLI process.
6
- * It reads auth from LETTA_API_KEY env var or ~/.letta/settings.json.
7
- * It reads agent ID from LETTA_AGENT_ID env var or --agent-id arg.
8
- *
9
- * Usage:
10
- * npx tsx attach-block.ts --block-id <block-id> [--agent-id <agent-id>] [--read-only] [--override]
11
- *
12
- * This attaches an existing block to another agent, making it shared.
13
- * Changes to the block will be visible to all agents that have it attached.
14
- *
15
- * Options:
16
- * --agent-id Target agent ID (overrides LETTA_AGENT_ID env var)
17
- * --read-only Target agent can read but not modify the block
18
- * --override If you already have a block with the same label, detach it first
19
- * (on error, the original block is reattached)
20
- *
21
- * Output:
22
- * Raw API response from the attach operation
23
- */
24
-
25
- import { readFileSync } from "node:fs";
26
- import { createRequire } from "node:module";
27
- import { homedir } from "node:os";
28
- import { join } from "node:path";
29
-
30
- // Use createRequire for @letta-ai/letta-client so NODE_PATH is respected
31
- // (ES module imports don't respect NODE_PATH, but require does)
32
- const require = createRequire(import.meta.url);
33
- const Letta = require("@letta-ai/letta-client")
34
- .default as typeof import("@letta-ai/letta-client").default;
35
- type LettaClient = InstanceType<typeof Letta>;
36
-
37
- /**
38
- * Get API key from env var or settings file
39
- */
40
- function getApiKey(): string {
41
- if (process.env.LETTA_API_KEY) {
42
- return process.env.LETTA_API_KEY;
43
- }
44
-
45
- const settingsPath = join(homedir(), ".letta", "settings.json");
46
- try {
47
- const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
48
- if (settings.env?.LETTA_API_KEY) {
49
- return settings.env.LETTA_API_KEY;
50
- }
51
- } catch {
52
- // Settings file doesn't exist or is invalid
53
- }
54
-
55
- throw new Error(
56
- "No LETTA_API_KEY found. Set the env var or run the Letta CLI to authenticate.",
57
- );
58
- }
59
-
60
- /**
61
- * Get agent ID from CLI arg, env var, or throw
62
- */
63
- function getAgentId(cliArg?: string): string {
64
- if (cliArg) return cliArg;
65
- if (process.env.LETTA_AGENT_ID) {
66
- return process.env.LETTA_AGENT_ID;
67
- }
68
- throw new Error(
69
- "No agent ID provided. Use --agent-id or ensure LETTA_AGENT_ID env var is set.",
70
- );
71
- }
72
-
73
- /**
74
- * Create a Letta client with auth from env/settings
75
- */
76
- function createClient(): LettaClient {
77
- return new Letta({ apiKey: getApiKey() });
78
- }
79
-
80
- interface AttachBlockResult {
81
- attachResult: Awaited<ReturnType<LettaClient["agents"]["blocks"]["attach"]>>;
82
- detachedBlock?: Awaited<ReturnType<LettaClient["blocks"]["retrieve"]>>;
83
- }
84
-
85
- /**
86
- * Attach an existing block to the current agent (sharing it)
87
- * @param client - Letta client instance
88
- * @param blockId - The block ID to attach
89
- * @param options - readOnly, targetAgentId, override (detach existing block with same label)
90
- * @returns API response from the attach operation
91
- */
92
- export async function attachBlock(
93
- client: LettaClient,
94
- blockId: string,
95
- options?: { readOnly?: boolean; targetAgentId?: string; override?: boolean },
96
- ): Promise<AttachBlockResult> {
97
- const currentAgentId = getAgentId(options?.targetAgentId);
98
- let detachedBlock:
99
- | Awaited<ReturnType<LettaClient["blocks"]["retrieve"]>>
100
- | undefined;
101
-
102
- // If override is requested, check for existing block with same label and detach it
103
- if (options?.override) {
104
- // Get the block we're trying to attach to find its label
105
- const sourceBlock = await client.blocks.retrieve(blockId);
106
- const sourceLabel = sourceBlock.label;
107
-
108
- // Get current agent's blocks to check for label conflict
109
- const currentBlocksResponse =
110
- await client.agents.blocks.list(currentAgentId);
111
- // The response may be paginated or an array depending on SDK version
112
- const currentBlocks = Array.isArray(currentBlocksResponse)
113
- ? currentBlocksResponse
114
- : (currentBlocksResponse as { items?: unknown[] }).items || [];
115
- const conflictingBlock = currentBlocks.find(
116
- (b: { label?: string }) => b.label === sourceLabel,
117
- );
118
-
119
- if (conflictingBlock) {
120
- console.error(
121
- `Detaching existing block with label "${sourceLabel}" (${conflictingBlock.id})...`,
122
- );
123
- detachedBlock = conflictingBlock;
124
- try {
125
- await client.agents.blocks.detach(conflictingBlock.id, {
126
- agent_id: currentAgentId,
127
- });
128
- } catch (detachError) {
129
- throw new Error(
130
- `Failed to detach existing block "${sourceLabel}": ${detachError instanceof Error ? detachError.message : String(detachError)}`,
131
- );
132
- }
133
- }
134
- }
135
-
136
- // Attempt to attach the new block
137
- let attachResult: Awaited<ReturnType<typeof client.agents.blocks.attach>>;
138
- try {
139
- attachResult = await client.agents.blocks.attach(blockId, {
140
- agent_id: currentAgentId,
141
- });
142
- } catch (attachError) {
143
- // If attach failed and we detached a block, try to reattach it
144
- if (detachedBlock) {
145
- console.error(
146
- `Attach failed, reattaching original block "${detachedBlock.label}"...`,
147
- );
148
- try {
149
- await client.agents.blocks.attach(detachedBlock.id, {
150
- agent_id: currentAgentId,
151
- });
152
- console.error("Original block reattached successfully.");
153
- } catch {
154
- console.error(
155
- `WARNING: Failed to reattach original block! Block ID: ${detachedBlock.id}`,
156
- );
157
- }
158
- }
159
- throw attachError;
160
- }
161
-
162
- // If read-only is requested, note the limitation
163
- if (options?.readOnly) {
164
- console.warn(
165
- "Note: read_only flag is set on the block itself, not per-agent. " +
166
- "Use the block update API to set read_only if needed.",
167
- );
168
- }
169
-
170
- return { attachResult, detachedBlock };
171
- }
172
-
173
- function parseArgs(args: string[]): {
174
- blockId: string;
175
- readOnly: boolean;
176
- override: boolean;
177
- agentId?: string;
178
- } {
179
- const blockIdIndex = args.indexOf("--block-id");
180
- const agentIdIndex = args.indexOf("--agent-id");
181
- const readOnly = args.includes("--read-only");
182
- const override = args.includes("--override");
183
-
184
- if (blockIdIndex === -1 || blockIdIndex + 1 >= args.length) {
185
- throw new Error("Missing required argument: --block-id <block-id>");
186
- }
187
-
188
- return {
189
- blockId: args[blockIdIndex + 1] as string,
190
- readOnly,
191
- override,
192
- agentId:
193
- agentIdIndex !== -1 && agentIdIndex + 1 < args.length
194
- ? (args[agentIdIndex + 1] as string)
195
- : undefined,
196
- };
197
- }
198
-
199
- // CLI entry point - check if this file is being run directly
200
- const isMainModule = import.meta.url === `file://${process.argv[1]}`;
201
- if (isMainModule) {
202
- (async () => {
203
- try {
204
- const { blockId, readOnly, override, agentId } = parseArgs(
205
- process.argv.slice(2),
206
- );
207
- const client = createClient();
208
- const result = await attachBlock(client, blockId, {
209
- readOnly,
210
- override,
211
- targetAgentId: agentId,
212
- });
213
- console.log(JSON.stringify(result, null, 2));
214
- } catch (error) {
215
- console.error(
216
- "Error:",
217
- error instanceof Error ? error.message : String(error),
218
- );
219
- if (
220
- error instanceof Error &&
221
- error.message.includes("Missing required argument")
222
- ) {
223
- console.error(
224
- "\nUsage: npx tsx attach-block.ts --block-id <block-id> [--agent-id <agent-id>] [--read-only] [--override]",
225
- );
226
- }
227
- process.exit(1);
228
- }
229
- })();
230
- }