Something went wrong. Try again.
Parametric learning in your code harness.
Something went wrong. Try again.
TypeScript
at letta-code
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218export type SessionMessageLike = { type: string; id?: string; timestamp?: string; message?: { role?: string; content?: unknown; toolCallId?: string; isError?: boolean; timestamp?: number; };};
export type TaggedExampleTag = "good" | "bad" | "observed";
export type TaggedTurn = { userId?: string; assistantId?: string; user: string; assistant: string;};
export type TrajectoryRecord = | { role: "user"; content: string; timestamp: string } | { role: "reasoning"; content: string; timestamp: string } | { role: "assistant"; content: string; timestamp: string } | { role: "assistant"; content: null; tool_calls: Array<{ id: string; name: string; args: string }>; timestamp: string } | { role: "tool"; tool_call_id: string; content: string; timestamp: string };
export function extractMessageText(content: unknown): string { if (typeof content === "string") return content.trim(); if (Array.isArray(content)) { return content .flatMap((part) => { if (!part || typeof part !== "object") return []; const block = part as { type?: string; text?: string }; return block.type === "text" && typeof block.text === "string" ? [block.text] : []; }) .join("\n") .trim(); } if (content && typeof content === "object") { const record = content as { text?: unknown; content?: unknown }; if (typeof record.text === "string") return record.text.trim(); if (record.content !== undefined) return extractMessageText(record.content); } return "";}
export function isoTimestamp(value: unknown, fallback?: string): string { if (typeof value === "string" && value) { const parsed = Date.parse(value); if (!Number.isNaN(parsed)) return new Date(parsed).toISOString(); } if (typeof value === "number" && Number.isFinite(value)) return new Date(value).toISOString(); return fallback ?? new Date().toISOString();}
/** Find the last user → assistant pair that both have visible text. */export function lastTaggedTurn(entries: SessionMessageLike[]): TaggedTurn | undefined { let assistant: { id?: string; text: string } | undefined; for (let i = entries.length - 1; i >= 0; i--) { const entry = entries[i]; if (entry.type !== "message" || !entry.message) continue; const text = extractMessageText(entry.message.content); if (!text) continue; if (!assistant && entry.message.role === "assistant") { assistant = { id: entry.id, text }; continue; } if (assistant && entry.message.role === "user") { return { userId: entry.id, assistantId: assistant.id, user: text, assistant: assistant.text }; } } return undefined;}
/** All message entries from the last user turn onward. */export function lastUserTurnEntries(entries: SessionMessageLike[]): SessionMessageLike[] { let userIndex = -1; for (let i = entries.length - 1; i >= 0; i--) { const entry = entries[i]; if (entry.type === "message" && entry.message?.role === "user" && extractMessageText(entry.message.content)) { userIndex = i; break; } } if (userIndex < 0) return []; return entries.slice(userIndex).filter((entry) => entry.type === "message" && entry.message);}
/** * Reconstruct a Letta-style record list * (https://www.letta.com/blog/trajectory/) from session entries: user / * reasoning / assistant / assistant+tool_calls / tool. */export function recordsFromSessionEntries(entries: SessionMessageLike[]): TrajectoryRecord[] { const records: TrajectoryRecord[] = []; for (const entry of entries) { const message = entry.message; if (!message) continue; const timestamp = isoTimestamp(entry.timestamp ?? message.timestamp); if (message.role === "user") { const content = extractMessageText(message.content); if (content) records.push({ role: "user", content, timestamp }); continue; } if (message.role === "assistant") { if (typeof message.content === "string") { if (message.content.trim()) records.push({ role: "assistant", content: message.content.trim(), timestamp }); continue; } for (const part of Array.isArray(message.content) ? message.content : []) { if (!part || typeof part !== "object") continue; const block = part as { type?: string; text?: string; thinking?: string; id?: string; name?: string; arguments?: unknown }; if (block.type === "thinking" && typeof block.thinking === "string" && block.thinking.trim()) { records.push({ role: "reasoning", content: block.thinking.trim(), timestamp }); } else if (block.type === "text" && typeof block.text === "string" && block.text.trim()) { records.push({ role: "assistant", content: block.text.trim(), timestamp }); } else if (block.type === "toolCall" && typeof block.name === "string" && block.name) { records.push({ role: "assistant", content: null, tool_calls: [{ id: typeof block.id === "string" && block.id ? block.id : `call_${records.length + 1}`, name: block.name, args: JSON.stringify(block.arguments && typeof block.arguments === "object" ? block.arguments : {}), }], timestamp, }); } } continue; } if (message.role === "toolResult" || message.role === "tool") { let content = extractMessageText(message.content); if (message.isError === true && content && !/^error/i.test(content)) content = `Error: ${content}`; records.push({ role: "tool", tool_call_id: typeof message.toolCallId === "string" && message.toolCallId ? message.toolCallId : `call_${records.length + 1}`, content, timestamp, }); } } return records;}
/** Replace the last assistant text record with the provided rewrite. */export function applyAssistantRewrite(records: TrajectoryRecord[], replacement: string): TrajectoryRecord[] { if (!replacement) return records; const rewritten = [...records]; for (let i = rewritten.length - 1; i >= 0; i--) { const record = rewritten[i]; if (record?.role === "assistant" && typeof record.content === "string") { rewritten[i] = { ...record, content: replacement }; return rewritten; } } return rewritten;}
/** * Convert records into Tinker chat JSONL messages. Reasoning is dropped, * tool-call records become OpenAI-style `tool_calls[].function`, and tool * records become `role: "tool"` messages so results stay in context. */export function trajectoryToMessages(records: TrajectoryRecord[]): Array<Record<string, unknown>> { return records.flatMap((record) => { if (record.role === "reasoning") return []; if (record.role === "assistant" && record.content === null) { return [{ role: "assistant", content: "", tool_calls: record.tool_calls.map((call) => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.args, }, })), }]; } if (record.role === "tool") { return [{ role: "tool", content: record.content, tool_call_id: record.tool_call_id }]; } return [{ role: record.role, content: record.content }]; });}
export function previewText(text: string, limit = 280): string { const compact = text.replace(/\s+/g, " ").trim(); return compact.length > limit ? `${compact.slice(0, limit - 1)}…` : compact;}
export function summarizeTrajectory(records: TrajectoryRecord[]): string { const counts = { user: records.filter((r) => r.role === "user").length, assistant: records.filter((r) => r.role === "assistant" && r.content !== null).length, toolCalls: records.filter((r) => r.role === "assistant" && r.content === null).length, tool: records.filter((r) => r.role === "tool").length, reasoning: records.filter((r) => r.role === "reasoning").length, }; const outline = records.slice(0, 16).map((record) => { if (record.role === "assistant" && record.content === null) { return `- assistant tool: ${record.tool_calls.map((call) => call.name).join(", ")}`; } if (record.role === "tool") return `- tool ${record.tool_call_id}: ${previewText(record.content, 80)}`; return `- ${record.role}: ${previewText(record.content, 80)}`; }); if (records.length > outline.length) outline.push(`- … ${records.length - outline.length} more`); return [ `${records.length} records (${counts.user} user, ${counts.assistant} assistant, ${counts.toolCalls} tool calls, ${counts.tool} tool results, ${counts.reasoning} reasoning)`, ...outline, ].join("\n");}