ai-sdk-letta 0.1.0

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +9 -0
  4. package/README.md +35 -0
  5. package/dist/agent.d.ts +108 -0
  6. package/dist/agent.d.ts.map +1 -0
  7. package/dist/agent.js +371 -0
  8. package/dist/agent.js.map +1 -0
  9. package/dist/definition.d.ts +81 -0
  10. package/dist/definition.d.ts.map +1 -0
  11. package/dist/definition.js +87 -0
  12. package/dist/definition.js.map +1 -0
  13. package/dist/history.d.ts +38 -0
  14. package/dist/history.d.ts.map +1 -0
  15. package/dist/history.js +226 -0
  16. package/dist/history.js.map +1 -0
  17. package/dist/identity.d.ts +43 -0
  18. package/dist/identity.d.ts.map +1 -0
  19. package/dist/identity.js +158 -0
  20. package/dist/identity.js.map +1 -0
  21. package/dist/images.d.ts +83 -0
  22. package/dist/images.d.ts.map +1 -0
  23. package/dist/images.js +181 -0
  24. package/dist/images.js.map +1 -0
  25. package/dist/index.d.ts +18 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +18 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/interactions.d.ts +61 -0
  30. package/dist/interactions.d.ts.map +1 -0
  31. package/dist/interactions.js +110 -0
  32. package/dist/interactions.js.map +1 -0
  33. package/dist/memory.d.ts +11 -0
  34. package/dist/memory.d.ts.map +1 -0
  35. package/dist/memory.js +55 -0
  36. package/dist/memory.js.map +1 -0
  37. package/dist/navigation.d.ts +50 -0
  38. package/dist/navigation.d.ts.map +1 -0
  39. package/dist/navigation.js +87 -0
  40. package/dist/navigation.js.map +1 -0
  41. package/dist/runtime.d.ts +83 -0
  42. package/dist/runtime.d.ts.map +1 -0
  43. package/dist/runtime.js +246 -0
  44. package/dist/runtime.js.map +1 -0
  45. package/dist/state.d.ts +24 -0
  46. package/dist/state.d.ts.map +1 -0
  47. package/dist/state.js +39 -0
  48. package/dist/state.js.map +1 -0
  49. package/dist/tools.d.ts +83 -0
  50. package/dist/tools.d.ts.map +1 -0
  51. package/dist/tools.js +162 -0
  52. package/dist/tools.js.map +1 -0
  53. package/package.json +67 -0
  54. package/src/agent.ts +334 -0
  55. package/src/definition.ts +136 -0
  56. package/src/history.ts +198 -0
  57. package/src/identity.ts +125 -0
  58. package/src/images.ts +184 -0
  59. package/src/index.ts +23 -0
  60. package/src/interactions.ts +121 -0
  61. package/src/memory.ts +42 -0
  62. package/src/navigation.ts +84 -0
  63. package/src/runtime.ts +243 -0
  64. package/src/state.ts +39 -0
  65. package/src/tools.ts +166 -0
package/dist/agent.js ADDED
@@ -0,0 +1,371 @@
1
+ import { generateText, streamText, stepCountIs } from 'ai';
2
+ import { ToolInteractions } from './interactions.js';
3
+ import { assertImageBudget, compactImagePart, decodeImagePart, imagePartDigest, ImageInputError, isImagePart, toLettaImage } from './images.js';
4
+ /** Most characters of text in one user turn. */
5
+ export const MAX_INPUT_CHARACTERS = 8000;
6
+ const usage = () => ({ inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined }, outputTokens: { total: undefined, text: undefined, reasoning: undefined } });
7
+ /**
8
+ * Canonical key of a semantic transcript (text, user images and completed tool
9
+ * calls), ignoring SDK metadata and step boundaries. Used to reject replayed or
10
+ * edited history: a new call must extend exactly what this process already
11
+ * sent. Images are compared by a SHA-256 of their bytes, so a transcript may
12
+ * carry either the image data or a compact reference to it.
13
+ */
14
+ export function historyKey(messages) {
15
+ const parts = [];
16
+ for (const message of messages) {
17
+ if (message.role === 'system')
18
+ throw new Error('System messages are not supported');
19
+ const content = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content;
20
+ for (const part of content) {
21
+ if (part.type === 'text') {
22
+ const last = parts.at(-1);
23
+ if (last?.role === message.role && typeof last.text === 'string')
24
+ last.text += part.text;
25
+ else
26
+ parts.push({ role: message.role, text: part.text });
27
+ }
28
+ else if (message.role === 'user' && isImagePart(part)) {
29
+ // A boundary like text: an image between two texts is not the same turn as the joined text.
30
+ parts.push({ role: message.role, text: null, image: imagePartDigest(part) });
31
+ }
32
+ else if (part.type === 'tool-call' && message.role === 'assistant') {
33
+ parts.push({ call: part.toolCallId, name: part.toolName, input: part.input });
34
+ }
35
+ else if (part.type === 'tool-result' && (message.role === 'assistant' || message.role === 'tool')) {
36
+ // UI error cards stringify provider error objects; conversion returns an
37
+ // error-json string whereas response.messages retains the original JSON.
38
+ // Normalize only error payloads, never successful text/JSON outputs.
39
+ let output = part.output;
40
+ if (output.type === 'error-json' && typeof output.value === 'string') {
41
+ try {
42
+ output = { ...output, value: JSON.parse(output.value) };
43
+ }
44
+ catch { /* plain error text */ }
45
+ }
46
+ parts.push({ result: part.toolCallId, name: part.toolName, output });
47
+ }
48
+ else
49
+ throw new Error('Only text, user image and completed application tool history are supported');
50
+ }
51
+ }
52
+ // Parallel calls arrive call/call/result/result, while UI cards convert as
53
+ // call/result/call/result. Canonicalize contiguous tool groups only; retain
54
+ // every ID, name, input and output and all text/turn boundaries.
55
+ const canonical = [];
56
+ let tools = [];
57
+ const flush = () => {
58
+ tools.sort((a, b) => {
59
+ const key = (value) => { const p = value; return `${p.call ?? p.result}\u0000${p.call ? '0' : '1'}`; };
60
+ return key(a).localeCompare(key(b));
61
+ });
62
+ canonical.push(...tools);
63
+ tools = [];
64
+ };
65
+ for (const part of parts) {
66
+ if ('text' in part) {
67
+ flush();
68
+ canonical.push(part);
69
+ }
70
+ else
71
+ tools.push(part);
72
+ }
73
+ flush();
74
+ return JSON.stringify(canonical);
75
+ }
76
+ /** Replace user image data with content-hash references so the retained transcript never duplicates image bytes. */
77
+ function compactTranscript(messages) {
78
+ return messages.map(message => message.role === 'user' && typeof message.content !== 'string'
79
+ ? { ...message, content: message.content.map(part => isImagePart(part) ? compactImagePart(part) : part) }
80
+ : message);
81
+ }
82
+ /**
83
+ * Validate the new user turn and build the single Letta message to send:
84
+ * a plain string for text-only turns, or text and `ImageContent` items in
85
+ * their original order.
86
+ * @throws {ImageInputError} for unsupported, invalid or oversized images
87
+ */
88
+ export function userTurnContent(content) {
89
+ const parts = typeof content === 'string' ? [{ type: 'text', text: content }] : content;
90
+ if (!Array.isArray(parts))
91
+ throw new Error('Expected a new user turn');
92
+ const items = [];
93
+ const images = [];
94
+ for (const part of parts) {
95
+ if (part.type === 'text') {
96
+ const last = items.at(-1);
97
+ if (last?.type === 'text')
98
+ last.text += part.text;
99
+ else
100
+ items.push({ type: 'text', text: part.text });
101
+ }
102
+ else if (isImagePart(part)) {
103
+ const image = decodeImagePart(part);
104
+ images.push(image);
105
+ assertImageBudget(images);
106
+ items.push(toLettaImage(image));
107
+ }
108
+ else if (part.type === 'file') {
109
+ throw new ImageInputError('image_unsupported_type', `Unsupported attachment type ${String(part.mediaType) || 'unknown'}; only PNG, JPEG, GIF and WebP images are supported`);
110
+ }
111
+ else
112
+ throw new Error('Only text and image input is supported');
113
+ }
114
+ const text = items.map(item => item.type === 'text' ? item.text : '').join('');
115
+ if (text.length > MAX_INPUT_CHARACTERS)
116
+ throw new Error(`Input text can be up to ${MAX_INPUT_CHARACTERS} characters`);
117
+ if (!text.trim() && !images.length)
118
+ throw new Error('Input must contain text or an image');
119
+ // Whitespace-only text next to images carries nothing; keep text-only turns byte-identical to before.
120
+ const message = images.length ? items.filter(item => item.type !== 'text' || item.text.trim()) : text;
121
+ return { message, text, images };
122
+ }
123
+ /**
124
+ * A persistent, Letta-backed Vercel AI SDK `Agent`.
125
+ *
126
+ * Letta owns the only reasoning and tool loop: each call sends exactly one new
127
+ * user message, and application tools run in this process through the Letta
128
+ * client-tool protocol (reported as `providerExecuted`). The AI SDK never
129
+ * dispatches tools itself. History you pass in must extend what this instance
130
+ * already sent; edits, regeneration and replay are rejected. After any failure
131
+ * or cancellation the instance refuses further turns, because delivery is
132
+ * uncertain; reopen it after inspecting the backend.
133
+ */
134
+ export class LettaAgent {
135
+ version = 'agent-v1';
136
+ id;
137
+ tools;
138
+ /** Letta-generated agent ID, when known. */
139
+ lettaAgentId;
140
+ /** Display-only restored state. */
141
+ presentation;
142
+ /** Broker for approvals and `ask_user` questions; connect a renderer to it. */
143
+ interactions;
144
+ open;
145
+ memoryTools;
146
+ delivery;
147
+ modelId;
148
+ history = [];
149
+ busy = false;
150
+ unusable = false;
151
+ active;
152
+ constructor(options) {
153
+ this.id = options.id;
154
+ this.tools = options.tools;
155
+ this.open = options.open;
156
+ this.memoryTools = options.memoryTools ?? [];
157
+ this.lettaAgentId = options.lettaAgentId;
158
+ this.presentation = options.presentation;
159
+ this.delivery = options.delivery;
160
+ this.interactions = options.interactions ?? new ToolInteractions();
161
+ this.modelId = options.modelId ?? 'letta';
162
+ }
163
+ /**
164
+ * A copy of the transcript this instance has sent and received (images as
165
+ * content-hash references, never bytes). To send a multimodal turn without
166
+ * keeping your own history, pass `messages: [...agent.transcript, newUserMessage]`.
167
+ */
168
+ get transcript() { return structuredClone(this.history); }
169
+ /** Abort any running turn, cancel pending prompts, and refuse further turns. */
170
+ close() { this.unusable = true; this.active?.abort(); this.interactions.close(); }
171
+ prepare(options) {
172
+ if (this.unusable)
173
+ throw new Error('Session closed or delivery uncertain; inspect backend history before reopening (no retries).');
174
+ if (this.busy)
175
+ throw new Error('A turn is already running');
176
+ for (const [key, value] of Object.entries(options)) {
177
+ if (!['prompt', 'messages', 'abortSignal'].includes(key) && value !== undefined)
178
+ throw new Error(`Unsupported agent option: ${key}`);
179
+ }
180
+ if (options.prompt !== undefined && options.messages !== undefined)
181
+ throw new Error('Use prompt or messages, not both');
182
+ const messages = typeof options.prompt === 'string' ? [...this.history, { role: 'user', content: options.prompt }] : options.messages ?? options.prompt;
183
+ if (!Array.isArray(messages) || !messages.length)
184
+ throw new Error('Expected a new user turn');
185
+ const last = messages.at(-1);
186
+ if (last.role !== 'user')
187
+ throw new Error('History edits, replay, and regeneration are not supported');
188
+ // Validate the new turn first, so an oversized or unsupported image is reported as such.
189
+ const turn = userTurnContent(last.content);
190
+ if (historyKey(messages.slice(0, -1)) !== historyKey(this.history))
191
+ throw new Error('History edits, replay, and regeneration are not supported');
192
+ options.abortSignal?.throwIfAborted();
193
+ this.busy = true;
194
+ const control = new AbortController();
195
+ this.active = control;
196
+ const signal = options.abortSignal ? AbortSignal.any([options.abortSignal, control.signal]) : control.signal;
197
+ // The retained transcript keeps images as hashes only; Letta already holds the bytes.
198
+ // (Compact before cloning: URL objects in image parts are not cloneable.)
199
+ return { messages: structuredClone(compactTranscript(messages)), message: turn.message, prompt: turn.text.trim() ? turn.text : '[Image]', signal };
200
+ }
201
+ model(message, signal) {
202
+ const run = async (emit) => {
203
+ let session;
204
+ let completed = false;
205
+ const abort = () => { void session?.abort().catch(() => { }); session?.close(); };
206
+ const calls = new Map();
207
+ const memoryCalls = new Set();
208
+ const tokens = usage();
209
+ let textId = 0;
210
+ let textOpen = false;
211
+ const endText = () => { if (textOpen) {
212
+ emit({ type: 'text-end', id: String(textId) });
213
+ textOpen = false;
214
+ } };
215
+ try {
216
+ signal.throwIfAborted();
217
+ session = this.open(signal);
218
+ signal.addEventListener('abort', abort, { once: true });
219
+ this.delivery?.begin();
220
+ await session.send(message);
221
+ signal.throwIfAborted();
222
+ for await (const event of session.stream()) {
223
+ signal.throwIfAborted();
224
+ if (event.type === 'assistant') {
225
+ if (!textOpen) {
226
+ textId++;
227
+ emit({ type: 'text-start', id: String(textId) });
228
+ textOpen = true;
229
+ }
230
+ emit({ type: 'text-delta', id: String(textId), delta: event.content });
231
+ }
232
+ else if (event.type === 'tool_call') {
233
+ endText();
234
+ if (calls.has(event.toolCallId) || memoryCalls.has(event.toolCallId))
235
+ throw new Error('Duplicate tool call');
236
+ // Harness memory operations are not application tool cards/history.
237
+ if (this.memoryTools.includes(event.toolName)) {
238
+ memoryCalls.add(event.toolCallId);
239
+ continue;
240
+ }
241
+ if (!Object.hasOwn(this.tools, event.toolName))
242
+ throw new Error('Unexpected tool call');
243
+ calls.set(event.toolCallId, event.toolName);
244
+ emit({ type: 'tool-call', toolCallId: event.toolCallId, toolName: event.toolName, input: JSON.stringify(event.toolInput), providerExecuted: true });
245
+ }
246
+ else if (event.type === 'tool_result') {
247
+ // The SDK can emit provisional Bash output as a tool_result before
248
+ // the authoritative result. Only known internal calls may use it.
249
+ if (memoryCalls.has(event.toolCallId) && event.uuid.startsWith('synthetic-tool-return-stream-'))
250
+ continue;
251
+ if (memoryCalls.delete(event.toolCallId))
252
+ continue;
253
+ const toolName = calls.get(event.toolCallId);
254
+ if (!toolName)
255
+ throw new Error('Unmatched tool result');
256
+ let result = event.content;
257
+ try {
258
+ result = JSON.parse(event.content);
259
+ }
260
+ catch { /* SDK text output */ }
261
+ emit({ type: 'tool-result', toolCallId: event.toolCallId, toolName, result: result ?? 'null', isError: event.isError });
262
+ calls.delete(event.toolCallId);
263
+ }
264
+ else if (event.type === 'stream_event' && event.event.message_type === 'usage_statistics') {
265
+ if (typeof event.event.prompt_tokens === 'number')
266
+ tokens.inputTokens.total = event.event.prompt_tokens;
267
+ if (typeof event.event.completion_tokens === 'number')
268
+ tokens.outputTokens.total = event.event.completion_tokens;
269
+ }
270
+ else if (event.type === 'result') {
271
+ if (!event.success || calls.size || memoryCalls.size)
272
+ throw new Error('Letta turn failed or left incomplete tools');
273
+ endText();
274
+ completed = true;
275
+ emit({ type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage: tokens });
276
+ return;
277
+ }
278
+ }
279
+ throw new Error('Letta stream closed before completion');
280
+ }
281
+ catch (error) {
282
+ this.unusable = true;
283
+ throw error;
284
+ }
285
+ finally {
286
+ signal.removeEventListener('abort', abort);
287
+ if (!completed)
288
+ void session?.abort().catch(() => { });
289
+ session?.close();
290
+ }
291
+ };
292
+ return {
293
+ specificationVersion: 'v4', provider: 'ai-sdk-letta', modelId: this.modelId, supportedUrls: {},
294
+ doGenerate: async () => {
295
+ const content = [];
296
+ let tokens = usage();
297
+ await run(part => {
298
+ if (part.type === 'text-delta') {
299
+ const last = content.at(-1);
300
+ if (last?.type === 'text')
301
+ last.text += part.delta;
302
+ else
303
+ content.push({ type: 'text', text: part.delta });
304
+ }
305
+ else if (part.type === 'tool-call' || part.type === 'tool-result')
306
+ content.push(part);
307
+ else if (part.type === 'finish')
308
+ tokens = part.usage;
309
+ });
310
+ return { content, usage: tokens, warnings: [], finishReason: { unified: 'stop', raw: 'stop' } };
311
+ },
312
+ doStream: async () => ({ stream: new ReadableStream({
313
+ start: controller => {
314
+ controller.enqueue({ type: 'stream-start', warnings: [] });
315
+ void run(part => controller.enqueue(part)).catch(error => {
316
+ try {
317
+ controller.enqueue({ type: 'error', error });
318
+ }
319
+ catch { /* reader closed */ }
320
+ }).finally(() => { try {
321
+ controller.close();
322
+ }
323
+ catch { /* reader closed */ } });
324
+ },
325
+ cancel: () => this.close(),
326
+ }) }),
327
+ };
328
+ }
329
+ /** Run one turn and wait for the full result. */
330
+ async generate(options) {
331
+ const turn = this.prepare(options);
332
+ try {
333
+ const result = await generateText({ model: this.model(turn.message, turn.signal), prompt: turn.prompt, tools: this.tools, maxRetries: 0, stopWhen: stepCountIs(1), abortSignal: turn.signal });
334
+ this.delivery?.complete();
335
+ this.history = [...turn.messages, ...result.response.messages];
336
+ return result;
337
+ }
338
+ catch (error) {
339
+ this.unusable = true;
340
+ throw error;
341
+ }
342
+ finally {
343
+ this.busy = false;
344
+ this.active = undefined;
345
+ }
346
+ }
347
+ /** Run one turn as a stream (text deltas, provider-executed tool calls and results). */
348
+ async stream(options) {
349
+ const turn = this.prepare(options);
350
+ return streamText({ model: this.model(turn.message, turn.signal), prompt: turn.prompt, tools: this.tools, maxRetries: 0, stopWhen: stepCountIs(1), abortSignal: turn.signal,
351
+ onError: () => { this.unusable = true; this.busy = false; },
352
+ onAbort: () => { this.close(); this.busy = false; },
353
+ onFinish: result => {
354
+ try {
355
+ if (!this.unusable && result.finishReason === 'stop')
356
+ this.delivery?.complete();
357
+ }
358
+ catch (error) {
359
+ this.unusable = true;
360
+ throw error;
361
+ }
362
+ finally {
363
+ this.busy = false;
364
+ this.active = undefined;
365
+ }
366
+ this.history = [...turn.messages, ...result.response.messages];
367
+ },
368
+ });
369
+ }
370
+ }
371
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,WAAW,EAAqH,MAAM,IAAI,CAAC;AAG9K,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAAE,WAAW,EAAE,YAAY,EAAqB,MAAM,aAAa,CAAC;AAEnK,gDAAgD;AAChD,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAuCzC,MAAM,KAAK,GAAG,GAAyB,EAAE,CAAC,CAAC,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;AAE9N;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,QAAwB;IACjD,MAAM,KAAK,GAAc,EAAE,CAAC;IAC5B,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACpF,MAAM,OAAO,GAAG,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,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IAAI,GAAG,KAAK,CAAC;oBAAC,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;gBAAC,CAAC;gBACvD,IAAI,CAAC,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;YACjE,CAAC;SACF,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,81 @@
1
+ import type { ToolSet } from 'ai';
2
+ import type { CreateAgentOptions } from '@letta-ai/letta-agent-sdk';
3
+ /** How a single application tool call is authorized. */
4
+ export type ToolPermission = 'allow' | 'ask' | 'deny';
5
+ /** When Letta runs background memory consolidation ("dreaming"). */
6
+ export type DreamingTrigger = 'off' | 'step-count' | 'compaction-event';
7
+ export interface DreamingSettings {
8
+ /** @default 'step-count' */
9
+ trigger: DreamingTrigger;
10
+ /** Steps between dreams when `trigger` is `'step-count'`. @default 25 */
11
+ stepCount: number;
12
+ }
13
+ /** Input accepted by {@link defineAgent}. */
14
+ export interface AgentDefinitionInput<TOOLS extends ToolSet = ToolSet> {
15
+ /**
16
+ * Stable, application-owned logical ID (lowercase letters, digits and `-`).
17
+ * It is mapped once to the Letta-generated agent ID and never re-created.
18
+ */
19
+ id: string;
20
+ /** Display name. Also stored on the Letta agent and checked on every start. */
21
+ name: string;
22
+ /**
23
+ * Letta model handle, e.g. `openai-codex/gpt-5.5` or `anthropic/claude-sonnet-4-5`.
24
+ * Only used when the agent is first created; must be connected on the local backend.
25
+ */
26
+ model: string;
27
+ /** System instructions, applied when the agent is first created. */
28
+ instructions: string;
29
+ /** AI SDK tools executed in this process when the agent calls them. */
30
+ tools: TOOLS;
31
+ /**
32
+ * Permission per tool. Fail-closed: every tool must be listed.
33
+ * `ask_user` defaults to `'allow'` (it is itself a human interaction).
34
+ */
35
+ permissions?: Partial<Record<Extract<keyof TOOLS, string>, ToolPermission>>;
36
+ /** Background memory consolidation. @default { trigger: 'step-count', stepCount: 25 } */
37
+ dreaming?: Partial<DreamingSettings>;
38
+ /** Per-call tool execution deadline in milliseconds (human waits excluded). @default 5000 */
39
+ toolTimeoutMs?: number;
40
+ }
41
+ /** A validated, immutable agent definition. */
42
+ export interface AgentDefinition<TOOLS extends ToolSet = ToolSet> {
43
+ readonly id: string;
44
+ readonly name: string;
45
+ readonly model: string;
46
+ readonly instructions: string;
47
+ readonly tools: TOOLS;
48
+ readonly permissions: Readonly<Record<string, ToolPermission>>;
49
+ readonly dreaming: Readonly<DreamingSettings>;
50
+ readonly toolTimeoutMs: number;
51
+ }
52
+ /** Tools the harness uses for MemFS. They are confined to the agent's own memory directory. */
53
+ export declare const INTERNAL_MEMORY_TOOLS: readonly ["Read", "Write", "Edit", "Bash"];
54
+ export declare const DEFAULT_DREAMING: Readonly<DreamingSettings>;
55
+ /**
56
+ * Validate and freeze an agent definition.
57
+ *
58
+ * @throws if the ID is invalid, a tool lacks a permission, or a permission names an unknown tool.
59
+ */
60
+ export declare function defineAgent<TOOLS extends ToolSet>(input: AgentDefinitionInput<TOOLS>): AgentDefinition<TOOLS>;
61
+ /**
62
+ * Appended to the definition's instructions at creation, so the model knows
63
+ * what the (enforced) memory policy allows.
64
+ */
65
+ export declare function memoryPolicyInstructions(dreaming: DreamingSettings): string;
66
+ /** Letta Agent SDK creation options for a definition. */
67
+ export declare function creationOptions(definition: AgentDefinition, cwd: string): CreateAgentOptions;
68
+ /** Protocol command that applies dreaming settings to this project scope only. */
69
+ export declare function dreamingCommand(definition: AgentDefinition, agentId: string, conversationId?: string): {
70
+ readonly type: "set_reflection_settings";
71
+ readonly runtime: {
72
+ readonly agent_id: string;
73
+ readonly conversation_id: string;
74
+ };
75
+ readonly scope: "local_project";
76
+ readonly settings: {
77
+ readonly trigger: DreamingTrigger;
78
+ readonly step_count: number;
79
+ };
80
+ };
81
+ //# sourceMappingURL=definition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definition.d.ts","sourceRoot":"","sources":["../src/definition.ts"],"names":[],"mappings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,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,WAAW,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;IAC/D,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IAC9C,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAChC;AAED,+FAA+F;AAC/F,eAAO,MAAM,qBAAqB,4CAA6C,CAAC;AAEhF,eAAO,MAAM,gBAAgB,EAAE,QAAQ,CAAC,gBAAgB,CAA2D,CAAC;AAIpH;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,SAAS,OAAO,EAAE,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,CAAC,CAkC7G;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,MAAM,CAM3E;AAED,yDAAyD;AACzD,wBAAgB,eAAe,CAAC,UAAU,EAAE,eAAe,EAAE,GAAG,EAAE,MAAM,GAAG,kBAAkB,CAQ5F;AAED,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,SAAY;;;;;;;;;;;EAKvG"}
@@ -0,0 +1,87 @@
1
+ import { ASK_USER_TOOL } from './tools.js';
2
+ /** Tools the harness uses for MemFS. They are confined to the agent's own memory directory. */
3
+ export const INTERNAL_MEMORY_TOOLS = ['Read', 'Write', 'Edit', 'Bash'];
4
+ export const DEFAULT_DREAMING = Object.freeze({ trigger: 'step-count', stepCount: 25 });
5
+ const permissionValues = ['allow', 'ask', 'deny'];
6
+ /**
7
+ * Validate and freeze an agent definition.
8
+ *
9
+ * @throws if the ID is invalid, a tool lacks a permission, or a permission names an unknown tool.
10
+ */
11
+ export function defineAgent(input) {
12
+ if (typeof input.id !== 'string' || !/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(input.id)) {
13
+ throw new Error('Agent id must be 1–64 lowercase letters, digits or "-", starting and ending with a letter or digit');
14
+ }
15
+ if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 120)
16
+ throw new Error('Agent name must contain 1–120 characters');
17
+ if (typeof input.model !== 'string' || !input.model.includes('/'))
18
+ throw new Error('Agent model must be a Letta model handle such as "provider/model"');
19
+ if (typeof input.instructions !== 'string' || !input.instructions.trim())
20
+ throw new Error('Agent instructions are required');
21
+ if (input.tools === null || typeof input.tools !== 'object' || Array.isArray(input.tools))
22
+ throw new Error('Agent tools must be an object of AI SDK tools; use {} for none');
23
+ const names = Object.keys(input.tools);
24
+ for (const name of names) {
25
+ if (INTERNAL_MEMORY_TOOLS.includes(name))
26
+ throw new Error(`Tool name "${name}" is reserved for memory operations`);
27
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name))
28
+ throw new Error(`Invalid tool name "${name}"`);
29
+ }
30
+ const permissions = {};
31
+ for (const [name, mode] of Object.entries(input.permissions ?? {})) {
32
+ if (!names.includes(name))
33
+ throw new Error(`Permission for unknown tool "${name}"`);
34
+ if (!permissionValues.includes(mode))
35
+ throw new Error(`Invalid permission for "${name}"`);
36
+ permissions[name] = mode;
37
+ }
38
+ if (names.includes(ASK_USER_TOOL)) {
39
+ permissions[ASK_USER_TOOL] ??= 'allow';
40
+ if (permissions[ASK_USER_TOOL] === 'ask')
41
+ throw new Error('ask_user is already interactive; use "allow" or "deny"');
42
+ }
43
+ const missing = names.filter(name => !Object.hasOwn(permissions, name));
44
+ if (missing.length)
45
+ throw new Error(`Missing permission for tool(s): ${missing.join(', ')}. Every tool needs "allow", "ask" or "deny".`);
46
+ const dreaming = { ...DEFAULT_DREAMING, ...input.dreaming };
47
+ if (!['off', 'step-count', 'compaction-event'].includes(dreaming.trigger))
48
+ throw new Error('Invalid dreaming trigger');
49
+ if (!Number.isInteger(dreaming.stepCount) || dreaming.stepCount < 1 || dreaming.stepCount > 10_000)
50
+ throw new Error('Dreaming stepCount must be a positive integer');
51
+ const toolTimeoutMs = input.toolTimeoutMs ?? 5000;
52
+ if (!Number.isInteger(toolTimeoutMs) || toolTimeoutMs < 1 || toolTimeoutMs > 300_000)
53
+ throw new Error('toolTimeoutMs must be 1–300000');
54
+ return Object.freeze({
55
+ id: input.id, name: input.name, model: input.model, instructions: input.instructions, tools: input.tools,
56
+ permissions: Object.freeze(permissions), dreaming: Object.freeze(dreaming), toolTimeoutMs,
57
+ });
58
+ }
59
+ /**
60
+ * Appended to the definition's instructions at creation, so the model knows
61
+ * what the (enforced) memory policy allows.
62
+ */
63
+ export function memoryPolicyInstructions(dreaming) {
64
+ return 'Maintain useful long-term memory in your own MemFS only. Read, Write and Edit are restricted to Markdown files in your memory directory. '
65
+ + 'Bash is restricted to the exact memory commit command supplied in tool permission feedback; no general shell or filesystem actions are available. '
66
+ + (dreaming.trigger === 'off'
67
+ ? 'Background dreaming is off.'
68
+ : `Background dreaming consolidates memory${dreaming.trigger === 'step-count' ? ` after ${dreaming.stepCount} steps` : ' after compaction'}; do not claim a dream ran without evidence.`);
69
+ }
70
+ /** Letta Agent SDK creation options for a definition. */
71
+ export function creationOptions(definition, cwd) {
72
+ return {
73
+ name: definition.name, model: definition.model, cwd, memfs: true,
74
+ baseTools: [], skillSources: [], systemPrompt: `${definition.instructions}\n\n${memoryPolicyInstructions(definition.dreaming)}`,
75
+ // Do not pass `dreaming` here: the SDK applies it with scope 'both', which
76
+ // mutates the user's global Letta defaults. The runtime installs the
77
+ // definition's settings with scope 'local_project' in the private state cwd.
78
+ };
79
+ }
80
+ /** Protocol command that applies dreaming settings to this project scope only. */
81
+ export function dreamingCommand(definition, agentId, conversationId = 'default') {
82
+ return {
83
+ type: 'set_reflection_settings', runtime: { agent_id: agentId, conversation_id: conversationId },
84
+ scope: 'local_project', settings: { trigger: definition.dreaming.trigger, step_count: definition.dreaming.stepCount },
85
+ };
86
+ }
87
+ //# sourceMappingURL=definition.js.map
@@ -0,0 +1 @@
1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'ai';
3
+ /** Maximum backend records loaded when restoring a conversation's display history. */
4
+ export declare const HISTORY_LIMIT = 10000;
5
+ /** Strip terminal escape sequences and control characters from untrusted text. */
6
+ export declare const sanitizeText: (text: string) => string;
7
+ /** The installed SDK drops agent_id for default history. Its supported command
8
+ * escape hatch forwards the backend's agent-scoped query, including real cursors.
9
+ * Named conversations use the ordinary SDK API. Neither path sends input.
10
+ */
11
+ export declare function historyPage(session: Pick<LettaCodeSession, 'listMessages' | 'sendCommand'>, agentId: string, conversationId: string, options: ListMessagesOptions, timeoutMs?: number): Promise<ListMessagesResult>;
12
+ /** Page backwards through history up to `maximum` records, validating cursors and IDs. */
13
+ export declare function loadHistory(page: (options: ListMessagesOptions) => Promise<ListMessagesResult>, maximum?: number): Promise<{
14
+ messages: ListMessagesResult['messages'];
15
+ truncated: boolean;
16
+ }>;
17
+ /** Text shown for a user image that cannot be displayed (unsupported, invalid, or over the display budget). */
18
+ export declare const IMAGE_PLACEHOLDER = "[Image]";
19
+ /** Most decoded image bytes restored for display from one conversation, newest first. Older images become placeholders. */
20
+ export declare const HISTORY_IMAGE_BUDGET: number;
21
+ /** Display projection only. Never reconstruct the model's context from this.
22
+ * Completed allowlisted app tools become inert output cards; everything else is
23
+ * omitted, including pending approvals, reasoning, system, memory and events.
24
+ * User images become `file` parts with a `data:` URL (newest first, within
25
+ * `imageBudget` bytes); the rest become an `[Image]` text placeholder.
26
+ */
27
+ export declare function projectHistory(messages: ListMessagesResult['messages'], appTools: readonly string[], imageBudget?: number): UIMessage[];
28
+ /** @throws when the conversation ends with an unanswered user turn or an unfinished tool call. */
29
+ export declare function assertHistorySettled(messages: ListMessagesResult['messages']): void;
30
+ /** List every conversation of one agent, failing closed on foreign or repeated rows. */
31
+ export declare function listConversations(list: (options: {
32
+ agentId: string;
33
+ after?: string;
34
+ limit: number;
35
+ order: 'asc';
36
+ orderBy: 'createdAt';
37
+ }) => Promise<LettaConversation[]>, agentId: string): Promise<LettaConversation[]>;
38
+ //# s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