import * as path from "node:path"; import { APIUserAbortError } from "@letta-ai/letta-client/core/error"; import type { ApprovalReturn, TextContent, ToolReturn, } from "@letta-ai/letta-client/resources/agents/messages"; import type { ToolReturnMessage } from "@letta-ai/letta-client/resources/tools"; import type { ApprovalRequest } from "@/cli/helpers/stream"; import { INTERRUPTED_BY_USER } from "@/constants"; import { deliverDiskSpaceReminder, watchDiskSpaceDuring, } from "@/reminders/disk-space"; import { getCurrentWorkingDirectory } from "@/runtime-context"; import { executeTool, isModToolParallelSafeForContext, prepareCurrentToolExecutionContext, type ToolExecutionResult, type ToolReturnContent, } from "@/tools/manager"; export const ABORT_GRACE_MS = 500; export function isUserAbortError(error: unknown): boolean { return ( error instanceof APIUserAbortError || (error instanceof Error && (error.name === "AbortError" || error.message === INTERRUPTED_BY_USER || error.message === "The operation was aborted")) ); } export function overlayPartialResults( queued: ApprovalResult[] | null, partials: ApprovalResult[] | undefined, ): ApprovalResult[] { const realById = new Map((partials ?? []).map((r) => [r.tool_call_id, r])); const overlaid = (queued ?? []).map((r) => realById.get(r.tool_call_id) ?? r); const queuedIds = new Set((queued ?? []).map((r) => r.tool_call_id)); const extras = (partials ?? []).filter((r) => !queuedIds.has(r.tool_call_id)); return [...overlaid, ...extras]; } export function buildDeniedResults( autoDenied: Array<{ approval: ApprovalRequest; reason: string }>, ): ApprovalResult[] { return autoDenied.map((ad) => ({ type: "approval" as const, tool_call_id: ad.approval.toolCallId, approve: false, reason: ad.reason, })); } export function buildCompanionResults( autoHandled: Array<{ toolCallId: string; result: ToolExecutionResult; }>, autoDenied: Array<{ approval: ApprovalRequest; reason: string }>, ): ApprovalResult[] { return [ ...autoHandled.map((ar) => ({ type: "tool" as const, tool_call_id: ar.toolCallId, tool_return: ar.result.toolReturn, status: ar.result.status, stdout: ar.result.stdout, stderr: ar.result.stderr, })), ...buildDeniedResults(autoDenied), ]; } export function appendAbortPartials( error: unknown, extras: ApprovalResult[], ): void { if (extras.length === 0 || !isUserAbortError(error)) return; const abortError = error as Error & { partialResults?: ApprovalResult[] }; abortError.partialResults = [...(abortError.partialResults ?? []), ...extras]; } export function getDisplayableToolReturn(content: ToolReturnContent): string { if (typeof content === "string") { return content; } return content .filter((part): part is TextContent => part.type === "text") .map((part) => part.text) .join("\n"); } const PARALLEL_SAFE_TOOLS = new Set([ "Read", "ViewImage", "Grep", "Memory", "Glob", "conversation_search", "web_search", "fetch_webpage", "Task", "Agent", ]); function isParallelSafe(toolName: string, toolContextId?: string): boolean { return ( PARALLEL_SAFE_TOOLS.has(toolName) || isModToolParallelSafeForContext(toolName, toolContextId) ); } const FILE_PATH_TOOLS = new Set(["Edit", "Write"]); const GLOBAL_LOCK_TOOLS = new Set([ "Bash", "exec_command", "write_stdin", "ApplyPatch", ]); export function getResourceKey( toolName: string, toolArgs: Record, workingDirectory: string = getCurrentWorkingDirectory(), ): string { if (GLOBAL_LOCK_TOOLS.has(toolName)) { return "__global__"; } if (FILE_PATH_TOOLS.has(toolName)) { const filePath = toolArgs.file_path; if (typeof filePath === "string") { return path.isAbsolute(filePath) ? path.normalize(filePath) : path.resolve(workingDirectory, filePath); } } return "__global__"; } export type AutoAllowedResult = { toolCallId: string; result: ToolExecutionResult; }; export type ApprovalDecision = | { type: "approve"; approval: ApprovalRequest; reason?: string; precomputedResult?: ToolExecutionResult; } | { type: "deny"; approval: ApprovalRequest; reason: string }; export type ApprovalToolResult = ToolReturn & { reason?: string; }; export type ApprovalResult = ApprovalToolResult | ApprovalReturn; async function executeSingleDecision( decision: ApprovalDecision, onChunk?: (chunk: ToolReturnMessage) => void, options?: { abortSignal?: AbortSignal; onStreamingOutput?: ( toolCallId: string, chunk: string, isStderr?: boolean, ) => void; toolContextId?: string; parentScope?: { agentId: string; conversationId: string }; onFileWrite?: (filePath: string, content: string) => void; beforeToolExecution?: (toolCallId: string) => void | Promise; afterToolExecution?: ( toolCallId: string, result: ApprovalResult, ) => void | Promise; executeTool?: typeof executeTool; }, ): Promise { if (options?.abortSignal?.aborted) { if (onChunk) { onChunk({ message_type: "tool_return_message", id: "dummy", date: new Date().toISOString(), tool_call_id: decision.approval.toolCallId, tool_return: INTERRUPTED_BY_USER, status: "error", }); } return { type: "tool", tool_call_id: decision.approval.toolCallId, tool_return: INTERRUPTED_BY_USER, status: "error", }; } if (decision.type === "approve") { if (decision.precomputedResult) { return { type: "tool", tool_call_id: decision.approval.toolCallId, tool_return: decision.precomputedResult.toolReturn, status: decision.precomputedResult.status, stdout: decision.precomputedResult.stdout, stderr: decision.precomputedResult.stderr, reason: decision.reason, }; } await options?.beforeToolExecution?.(decision.approval.toolCallId); try { let parsedArgs: Record = {}; if (typeof decision.approval.toolArgs === "string") { try { parsedArgs = JSON.parse(decision.approval.toolArgs); } catch { parsedArgs = {}; } } else { parsedArgs = decision.approval.toolArgs || {}; } const toolResult = await (options?.executeTool ?? executeTool)( decision.approval.toolName, parsedArgs, { signal: options?.abortSignal, toolCallId: decision.approval.toolCallId, toolContextId: options?.toolContextId, parentScope: options?.parentScope, onOutput: options?.onStreamingOutput ? (chunk, stream) => options.onStreamingOutput?.( decision.approval.toolCallId, chunk, stream === "stderr", ) : undefined, onFileWrite: options?.onFileWrite, }, ); if (onChunk) { onChunk({ message_type: "tool_return_message", id: "dummy", date: new Date().toISOString(), tool_call_id: decision.approval.toolCallId, tool_return: getDisplayableToolReturn(toolResult.toolReturn), status: toolResult.status, stdout: toolResult.stdout, stderr: toolResult.stderr, }); } return { type: "tool", tool_call_id: decision.approval.toolCallId, tool_return: toolResult.toolReturn, status: toolResult.status, stdout: toolResult.stdout, stderr: toolResult.stderr, reason: decision.reason, }; } catch (e) { const isAbortError = e instanceof Error && (e.name === "AbortError" || e.message === "The operation was aborted"); const errorMessage = isAbortError ? INTERRUPTED_BY_USER : `Error executing tool: ${String(e)}`; if (onChunk) { onChunk({ message_type: "tool_return_message", id: "dummy", date: new Date().toISOString(), tool_call_id: decision.approval.toolCallId, tool_return: errorMessage, status: "error", }); } return { type: "tool", tool_call_id: decision.approval.toolCallId, tool_return: errorMessage, status: "error", reason: decision.reason, }; } } if (onChunk) { onChunk({ message_type: "tool_return_message", id: "dummy", date: new Date().toISOString(), tool_call_id: decision.approval.toolCallId, tool_return: `Error: request to call tool denied. User reason: ${decision.reason}`, status: "error", }); } return { type: "approval", tool_call_id: decision.approval.toolCallId, approve: false, reason: decision.reason, }; } export async function executeApprovalBatch( decisions: ApprovalDecision[], onChunk?: (chunk: ToolReturnMessage) => void, options?: { abortSignal?: AbortSignal; onStreamingOutput?: ( toolCallId: string, chunk: string, isStderr?: boolean, ) => void; toolContextId?: string; workingDirectory?: string; parentScope?: { agentId: string; conversationId: string }; onFileWrite?: (filePath: string, content: string) => void; beforeToolExecution?: (toolCallId: string) => void | Promise; afterToolExecution?: ( toolCallId: string, result: ApprovalResult, ) => void | Promise; executeTool?: typeof executeTool; }, ): Promise { return watchDiskSpaceDuring( options?.workingDirectory ?? getCurrentWorkingDirectory(), (text) => deliverDiskSpaceReminder(text, options?.parentScope), () => executeApprovalBatchUnwatched(decisions, onChunk, options), ); } export async function settleApprovalExecutionTasks( tasks: readonly Promise[], partialResults: () => ApprovalResult[] = () => [], options?: { abortSignal?: AbortSignal }, ): Promise { const signal = options?.abortSignal; if (!signal || signal.aborted) { throwFirstSettledRejection(await Promise.allSettled(tasks), partialResults); return; } const settled: PromiseSettledResult[] = new Array(tasks.length); let remaining = tasks.length; const tracked = tasks.map((task, index) => task .then( () => { settled[index] = { status: "fulfilled", value: undefined }; }, (reason) => { settled[index] = { status: "rejected", reason }; }, ) .finally(() => { remaining -= 1; }), ); let onAbort: () => void = () => {}; const aborted = new Promise((resolve) => { onAbort = resolve; signal.addEventListener("abort", onAbort, { once: true }); }); try { await Promise.race([Promise.all(tracked).then(() => undefined), aborted]); } finally { signal.removeEventListener("abort", onAbort); } if (remaining === 0) { throwFirstSettledRejection(settled, partialResults); return; } let graceTimer: ReturnType | undefined; const graceExpired = new Promise((resolve) => { graceTimer = setTimeout(resolve, ABORT_GRACE_MS); }); try { await Promise.race([ Promise.all(tracked).then(() => undefined), graceExpired, ]); } finally { clearTimeout(graceTimer); } if (remaining === 0) { throwFirstSettledRejection(settled, partialResults); return; } throwFirstSettledRejection( settled.filter((result) => result !== undefined), partialResults, ); const error = signal.reason instanceof Error ? signal.reason : new Error(INTERRUPTED_BY_USER); Object.assign(error, { partialResults: partialResults() }); throw error; } function throwFirstSettledRejection( settled: PromiseSettledResult[], partialResults: () => ApprovalResult[], ): void { for (const result of settled) { if (result.status !== "rejected") continue; const error = result.reason instanceof Error ? result.reason : new Error(String(result.reason)); Object.assign(error, { partialResults: partialResults() }); throw error; } } async function executeApprovalBatchUnwatched( decisions: ApprovalDecision[], onChunk: ((chunk: ToolReturnMessage) => void) | undefined, options: Parameters[2], ): Promise { const toolContextId = options?.toolContextId ?? (options?.workingDirectory ? ( await prepareCurrentToolExecutionContext({ workingDirectory: options.workingDirectory, }) ).contextId : undefined); const results: (ApprovalResult | null)[] = new Array(decisions.length).fill( null, ); let batchDiscarded = false; const guardedOnChunk = onChunk ? (chunk: ToolReturnMessage) => { if (!batchDiscarded) onChunk(chunk); } : undefined; const guardedOptions = options?.onStreamingOutput ? { ...options, onStreamingOutput: ( toolCallId: string, chunk: string, isStderr?: boolean, ) => { if (!batchDiscarded) { options.onStreamingOutput?.(toolCallId, chunk, isStderr); } }, } : options; const parallelIndices: number[] = []; const writeToolsByResource = new Map(); const denyIndices: number[] = []; for (let i = 0; i < decisions.length; i++) { const decision = decisions[i]; if (!decision) continue; if (decision.type === "deny") { denyIndices.push(i); continue; } const toolName = decision.approval.toolName; if (isParallelSafe(toolName, toolContextId)) { parallelIndices.push(i); } else { let args: Record = {}; if (typeof decision.approval.toolArgs === "string") { try { args = JSON.parse(decision.approval.toolArgs); } catch { args = {}; } } else { args = decision.approval.toolArgs || {}; } const resourceKey = getResourceKey( toolName, args, options?.workingDirectory, ); const indices = writeToolsByResource.get(resourceKey) || []; indices.push(i); writeToolsByResource.set(resourceKey, indices); } } const execute = async (i: number) => { const decision = decisions[i]; if (decision) { let crossedEffectBoundary = false; const result = await executeSingleDecision(decision, guardedOnChunk, { ...guardedOptions, toolContextId, beforeToolExecution: async (toolCallId) => { await guardedOptions?.beforeToolExecution?.(toolCallId); crossedEffectBoundary = true; }, }); results[i] = result; if (decision.type === "approve" && crossedEffectBoundary) { await options?.afterToolExecution?.( decision.approval.toolCallId, result, ); } } }; try { await settleApprovalExecutionTasks( [ ...parallelIndices.map(execute), ...denyIndices.map(execute), ...Array.from(writeToolsByResource.values()).map(async (indices) => { for (const i of indices) { await execute(i); } }), ], () => results.filter((result): result is ApprovalResult => result !== null), { abortSignal: options?.abortSignal }, ); } catch (error) { batchDiscarded = true; throw error; } return results.filter((r): r is ApprovalResult => r !== null); } export async function executeAutoAllowedTools( autoAllowed: Array<{ approval: ApprovalRequest }>, onChunk: (chunk: ToolReturnMessage) => void, options?: { abortSignal?: AbortSignal; onStreamingOutput?: ( toolCallId: string, chunk: string, isStderr?: boolean, ) => void; toolContextId?: string; workingDirectory?: string; onFileWrite?: (filePath: string, content: string) => void; }, ): Promise { const decisions: ApprovalDecision[] = autoAllowed.map((ac) => ({ type: "approve" as const, approval: ac.approval, })); const batchResults = await executeApprovalBatch(decisions, onChunk, options); return batchResults .filter((r): r is ApprovalResult & { type: "tool" } => r.type === "tool") .map((r) => ({ toolCallId: r.tool_call_id, result: { toolReturn: r.tool_return, status: r.status, stdout: r.stdout, stderr: r.stderr, } as ToolExecutionResult, })); }