/** * Memory Management Module * * Handles agent memory operations, LLM call management, and chat title generation. * Provides functions for saving messages, continuing LLM after tool execution, and text response handling. * * Features: * - Save incoming messages to agent memory with auto-save * - Continue LLM execution after tool results (auto-execution flow) * - Handle text responses with auto-mention logic * - Reset LLM call count for human/world messages * - Generate chat titles from message content using LLM * * Dependencies (Layer 4): * - types.ts (Layer 1) * - mention-logic.ts (Layer 2) * - publishers.ts (Layer 3) * - utils.ts, logger.ts * - llm-manager.ts (runtime) * - storage (runtime) * * Changes: * - 2026-03-13: Phase 1 — weak fallback no-commit: `pickFallbackTitle` returns '' instead of 'Chat Session' so low-signal LLM results keep the chat in 'New Chat' state. * - 2026-03-13: Phase 2 — bounded context window: `buildTitlePromptMessages` collects up to TITLE_CONTEXT_WINDOW_TURNS*2 recent user+assistant messages for richer prompt context. * - 2026-03-13: Improved title-gen prompt: explicit @mention semantics, no-verbatim-copy rule, noun-phrase Title Case format constraint. * - 2026-03-13: Title-generation LLM calls now strip world `reasoning_effort` so background title requests omit provider reasoning params by default. * - 2026-03-06: Required explicit chat scope in memory-save/continuation/assistant-response paths; removed `world.currentChatId` fallback from agent event routing. * - 2026-03-06: Normalized shell continuation parse/validation/policy failures through explicit canonical shell failure reasons and updated continuation comments to reflect bounded-preview tool persistence. * - 2026-03-06: Collapsed shell continuation result-mode selection to one bounded-preview mode and normalized persisted shell tool failures through the canonical shell-result formatter. * - 2026-02-28: Added canonical `message.publish` logs for assistant publish events in direct and continuation response paths. * - 2026-02-27: Passed explicit chat scope to continuation system events (`publishEvent`) to prevent fallback routing to `world.currentChatId` during chat switches. * - 2026-02-27: Suppress repeated identical `load_skill` tool calls within the same continuation run once a prior same-run load succeeded. * - 2026-02-27: Added per-chat/agent continuation run lock in `continueLLMAfterToolExecution` to skip concurrent duplicate continuation runs while tools are pending/executing (prevents duplicate HITL approval prompts). * - 2026-03-01: Expanded script-like shell command detection to treat path-based interpreter executables (for example `.venv/bin/python`) as script hosts so continuation prefers smart shell result mode after skill-driven script calls. * - 2026-03-01: Generalized script-host detection for smart shell continuation mode to include additional interpreter families (`bash`, `node`, `deno`, `bun`, `ruby`, `perl`, `php`, `pwsh`) and `env script` invocation patterns. * - 2026-03-01: Updated duplicate `shell_cmd` matching to ignore `output_format`/`output_detail` differences and redact those fields from continuation tool telemetry payloads. * - 2026-02-26: Replaced `resumePendingToolCallsForChat` console traces with categorized structured logger events (`chat.restore.resume.tools`) for env-controlled restore diagnostics. * - 2026-02-24: Commented out hardcoded Infinite-Etude handoff safeguard to respect separation of concerns (logic moved to agent prompt). * - 2026-02-25: Added detailed resume tracing in `resumePendingToolCallsForChat` (start/skip/execute/error/continue) for cross-layer restore diagnostics. * - 2026-02-25: Added duplicate messageId guard in `saveIncomingMessageToMemory` so chat-restore replay can re-emit pending user messages without duplicating persisted agent memory. * - 2026-02-25: Added `resumePendingToolCallsForChat` to restore unresolved persisted tool calls (e.g. `load_skill`) on chat load/switch and continue the LLM loop. * - 2026-02-21: Shell tool continuation context now requests minimal LLM result mode (`status`/`exit_code`) and passes agent name for assistant-stream shell SSE attribution. * - 2026-02-20: Added Infinite-Etude handoff safeguard to enforce Pedagogue -> Engraver final mention when missing. * - 2026-02-16: Added plain-text tool-intent fallback parser in continuation to synthesize executable `tool_calls` when providers return `Calling tool: ...` text. * - 2026-02-16: Max tool-hop guardrail now emits UI/tool errors and injects transient LLM context, then continues loop instead of returning. * - 2026-02-16: Removed plain-text tool-intent reminder/retry path; continuation now relies only on tool-call loop + hop guardrail. * - 2026-02-16: Empty/invalid continuation tool_calls now write a synthetic tool-error result back to memory before continuing the LLM loop. * - 2026-02-16: Added bounded retry when continuation returns empty/invalid `tool_calls` so agent loops do not stop silently. * - 2026-02-16: Added bounded retry when post-tool continuation returns empty text so tool loops (e.g., load_skill) do not stop silently. * - 2026-02-16: Added multi-hop tool continuation support when post-tool LLM responses contain additional tool_calls. * - 2026-02-15: Sanitized agent self-mentions in `handleTextResponse` before auto-mentioning to prevent `@self` prefixes. * - 2026-02-13: Added per-agent `autoReply` gate; disables sender auto-mention when set to false. * - 2026-02-13: Hardened title output normalization with markdown/prefix stripping and low-quality fallback hierarchy. * - 2026-02-13: Canceled title-generation calls now exit without fallback renaming. * - 2026-02-13: Added deterministic chat-title prompt shaping (role filtering, de-duplication, bounded window). * - 2026-02-13: Made chat-title generation explicitly chat-scoped by requiring target `chatId`. * - 2026-02-13: Title generation LLM calls now use chat-scoped queue context for cancellation alignment. * - 2026-02-13: Added abort-signal guards so stop requests prevent post-tool LLM continuation and suppress cancellation noise. * - 2026-02-13: Passed explicit `chatId` through LLM calls for chat-scoped stop cancellation support. * - 2026-02-08: Removed stale manual tool-intervention terminology from comments and transient types * - 2026-02-06: Renamed resumeLLMAfterManualDecision to continueLLMAfterToolExecution * - 2025-01-09: Extracted from events.ts for modular architecture */ import type { World, Agent, WorldMessageEvent } from '../types.js'; export declare function resumePendingToolCallsForChat(world: World, chatId: string, targetAssistantMessageId?: string): Promise; /** * Save incoming message to agent memory with auto-save * Uses explicit chatId from the message event for concurrency-safe saving */ export declare function saveIncomingMessageToMemory(world: World, agent: Agent, messageEvent: WorldMessageEvent): Promise; /** * Continue LLM execution after tool execution * Calls the LLM with the updated memory (including tool result) to continue the execution loop * Used for auto-execution flow where tools are executed automatically */ export declare function continueLLMAfterToolExecution(world: World, agent: Agent, chatId?: string | null, options?: { abortSignal?: AbortSignal; hopCount?: number; emptyTextRetryCount?: number; emptyToolCallRetryCount?: number; continuationRunId?: string; transientContinuationInstruction?: string; preloadedSkillIds?: string[]; }): Promise; /** * Handle text response from LLM (extracted for clarity) * @param chatId - Explicit chat ID for concurrency-safe processing. When omitted, `messageEvent.chatId` is used. */ export declare function handleTextResponse(world: World, agent: Agent, responseText: string, messageId: string, messageEvent: WorldMessageEvent, chatId?: string | null): Promise; /** * Reset LLM call count for human/world messages with persistence */ export declare function resetLLMCallCountIfNeeded(world: World, agent: Agent, messageEvent: WorldMessageEvent): Promise; /** * Generate chat title from message content with LLM support and fallback */ export declare function generateChatTitleFromMessages(world: World, content: string, targetChatId: string | null): Promise;