import type { MastraDBMessage } from '@mastra/core/agent';
import type { CoreMessage } from '@mastra/core/llm';
type ObserverFormatOptions = {
    maxPartLength?: number;
    maxToolResultTokens?: number;
};
/**
 * The core extraction instructions for the Observer.
 * This is exported so the Reflector can understand how observations were created.
 */
export declare const OBSERVER_EXTRACTION_INSTRUCTIONS = "CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS\n\nWhen the user TELLS you something about themselves, mark it as an assertion:\n- \"I have two kids\" \u2192 \uD83D\uDD34 (14:30) User stated has two kids\n- \"I work at Acme Corp\" \u2192 \uD83D\uDD34 (14:31) User stated works at Acme Corp\n- \"I graduated in 2019\" \u2192 \uD83D\uDD34 (14:32) User stated graduated in 2019\n\nWhen the user ASKS about something, mark it as a question/request:\n- \"Can you help me with X?\" \u2192 \uD83D\uDD34 (15:00) User asked help with X\n- \"What's the best way to do Y?\" \u2192 \uD83D\uDD34 (15:01) User asked best way to do Y\n\nDistinguish between QUESTIONS and STATEMENTS OF INTENT:\n- \"Can you recommend...\" \u2192 Question (extract as \"User asked...\")\n- \"I'm looking forward to [doing X]\" \u2192 Statement of intent (extract as \"User stated they will [do X] (include estimated/actual date if mentioned)\")\n- \"I need to [do X]\" \u2192 Statement of intent (extract as \"User stated they need to [do X] (again, add date if mentioned)\")\n\nSTATE CHANGES AND UPDATES:\nWhen a user indicates they are changing something, frame it as a state change that supersedes previous information:\n- \"I'm going to start doing X instead of Y\" \u2192 \"User will start doing X (changing from Y)\"\n- \"I'm switching from A to B\" \u2192 \"User is switching from A to B\"\n- \"I moved my stuff to the new place\" \u2192 \"User moved their stuff to the new place (no longer at previous location)\"\n\nIf the new state contradicts or updates previous information, make that explicit:\n- BAD: \"User plans to use the new method\"\n- GOOD: \"User will use the new method (replacing the old approach)\"\n\nThis helps distinguish current state from outdated information.\n\nUSER ASSERTIONS ARE AUTHORITATIVE. The user is the source of truth about their own life.\nIf a user previously stated something and later asks a question about the same topic,\nthe assertion is the answer - the question doesn't invalidate what they already told you.\n\nTEMPORAL ANCHORING:\nEach observation has TWO potential timestamps:\n\n1. BEGINNING: The time the statement was made (from the message timestamp) - ALWAYS include this\n2. END: The time being REFERENCED, if different from when it was said - ONLY when there's a relative time reference\n\nONLY add \"(meaning DATE)\" or \"(estimated DATE)\" at the END when you can provide an ACTUAL DATE:\n- Past: \"last week\", \"yesterday\", \"a few days ago\", \"last month\", \"in March\"\n- Future: \"this weekend\", \"tomorrow\", \"next week\"\n\nDO NOT add end dates for:\n- Present-moment statements with no time reference\n- Vague references like \"recently\", \"a while ago\", \"lately\", \"soon\" - these cannot be converted to actual dates\n\nFORMAT:\n- With time reference: (TIME) [observation]. (meaning/estimated DATE)\n- Without time reference: (TIME) [observation].\n\nGOOD: (09:15) User's friend had a birthday party in March. (meaning March 20XX)\n      ^ References a past event - add the referenced date at the end\n\nGOOD: (09:15) User will visit their parents this weekend. (meaning June 17-18, 20XX)\n      ^ References a future event - add the referenced date at the end\n\nGOOD: (09:15) User prefers hiking in the mountains.\n      ^ Present-moment preference, no time reference - NO end date needed\n\nGOOD: (09:15) User is considering adopting a dog.\n      ^ Present-moment thought, no time reference - NO end date needed\n\nBAD: (09:15) User prefers hiking in the mountains. (meaning June 15, 20XX - today)\n     ^ No time reference in the statement - don't repeat the message timestamp at the end\n\nIMPORTANT: If an observation contains MULTIPLE events, split them into SEPARATE observation lines.\nEACH split observation MUST have its own date at the end - even if they share the same time context.\n\nExamples (assume message is from June 15, 20XX):\n\nBAD: User will visit their parents this weekend (meaning June 17-18, 20XX) and go to the dentist tomorrow.\nGOOD (split into two observations, each with its date):\n  User will visit their parents this weekend. (meaning June 17-18, 20XX)\n  User will go to the dentist tomorrow. (meaning June 16, 20XX)\n\nBAD: User needs to clean the garage this weekend and is looking forward to setting up a new workbench.\nGOOD (split, BOTH get the same date since they're related):\n  User needs to clean the garage this weekend. (meaning June 17-18, 20XX)\n  User will set up a new workbench this weekend. (meaning June 17-18, 20XX)\n\nBAD: User was given a gift by their friend (estimated late May 20XX) last month.\nGOOD: (09:15) User was given a gift by their friend last month. (estimated late May 20XX)\n      ^ Message time at START, relative date reference at END - never in the middle\n\nBAD: User started a new job recently and will move to a new apartment next week.\nGOOD (split):\n  User started a new job recently.\n  User will move to a new apartment next week. (meaning June 21-27, 20XX)\n  ^ \"recently\" is too vague for a date - omit the end date. \"next week\" can be calculated.\n\nALWAYS put the date at the END in parentheses - this is critical for temporal reasoning.\nWhen splitting related events that share the same time context, EACH observation must have the date.\n\nPRESERVE UNUSUAL PHRASING:\nWhen the user uses unexpected or non-standard terminology, quote their exact words.\n\nBAD: User exercised.\nGOOD: User stated they did a \"movement session\" (their term for exercise).\n\nUSE PRECISE ACTION VERBS:\nReplace vague verbs like \"getting\", \"got\", \"have\" with specific action verbs that clarify the nature of the action.\nIf the assistant confirms or clarifies the user's action, use the assistant's more precise language.\n\nBAD: User is getting X.\nGOOD: User subscribed to X. (if context confirms recurring delivery)\nGOOD: User purchased X. (if context confirms one-time acquisition)\n\nBAD: User got something.\nGOOD: User purchased / received / was given something. (be specific)\n\nCommon clarifications:\n- \"getting\" something regularly \u2192 \"subscribed to\" or \"enrolled in\"\n- \"getting\" something once \u2192 \"purchased\" or \"acquired\"\n- \"got\" \u2192 \"purchased\", \"received as gift\", \"was given\", \"picked up\"\n- \"signed up\" \u2192 \"enrolled in\", \"registered for\", \"subscribed to\"\n- \"stopped getting\" \u2192 \"canceled\", \"unsubscribed from\", \"discontinued\"\n\nWhen the assistant interprets or confirms the user's vague language, prefer the assistant's precise terminology.\n\nPRESERVING DETAILS IN ASSISTANT-GENERATED CONTENT:\n\nWhen the assistant provides lists, recommendations, or creative content that the user explicitly requested,\npreserve the DISTINGUISHING DETAILS that make each item unique and queryable later.\n\n1. RECOMMENDATION LISTS - Preserve the key attribute that distinguishes each item:\n   BAD: Assistant recommended 5 hotels in the city.\n   GOOD: Assistant recommended hotels: Hotel A (near the train station), Hotel B (budget-friendly), \n         Hotel C (has rooftop pool), Hotel D (pet-friendly), Hotel E (historic building).\n   \n   BAD: Assistant listed 3 online stores for craft supplies.\n   GOOD: Assistant listed craft stores: Store A (based in Germany, ships worldwide), \n         Store B (specializes in vintage fabrics), Store C (offers bulk discounts).\n\n2. NAMES, HANDLES, AND IDENTIFIERS - Always preserve specific identifiers:\n   BAD: Assistant provided social media accounts for several photographers.\n   GOOD: Assistant provided photographer accounts: @photographer_one (portraits), \n         @photographer_two (landscapes), @photographer_three (nature).\n   \n   BAD: Assistant listed some authors to check out.\n   GOOD: Assistant recommended authors: Jane Smith (mystery novels), \n         Bob Johnson (science fiction), Maria Garcia (historical romance).\n\n3. CREATIVE CONTENT - Preserve structure and key sequences:\n   BAD: Assistant wrote a poem with multiple verses.\n   GOOD: Assistant wrote a 3-verse poem. Verse 1 theme: loss. Verse 2 theme: hope. \n         Verse 3 theme: renewal. Refrain: \"The light returns.\"\n   \n   BAD: User shared their lucky numbers from a fortune cookie.\n   GOOD: User's fortune cookie lucky numbers: 7, 14, 23, 38, 42, 49.\n\n4. TECHNICAL/NUMERICAL RESULTS - Preserve specific values:\n   BAD: Assistant explained the performance improvements from the optimization.\n   GOOD: Assistant explained the optimization achieved 43.7% faster load times \n         and reduced memory usage from 2.8GB to 940MB.\n   \n   BAD: Assistant provided statistics about the dataset.\n   GOOD: Assistant provided dataset stats: 7,342 samples, 89.6% accuracy, \n         23ms average inference time.\n\n5. QUANTITIES AND COUNTS - Always preserve how many of each item:\n   BAD: Assistant listed items with details but no quantities.\n   GOOD: Assistant listed items: Item A (4 units, size large), Item B (2 units, size small).\n   \n   When listing items with attributes, always include the COUNT first before other details.\n\n6. ROLE/PARTICIPATION STATEMENTS - When user mentions their role at an event:\n   BAD: User attended the company event.\n   GOOD: User was a presenter at the company event.\n   \n   BAD: User went to the fundraiser.\n   GOOD: User volunteered at the fundraiser (helped with registration).\n   \n   Always capture specific roles: presenter, organizer, volunteer, team lead, \n   coordinator, participant, contributor, helper, etc.\n\nCONVERSATION CONTEXT:\n- What the user is working on or asking about\n- Previous topics and their outcomes\n- What user understands or needs clarification on\n- Specific requirements or constraints mentioned\n- Contents of assistant learnings and summaries\n- Answers to users questions including full context to remember detailed summaries and explanations\n- Assistant explanations, especially complex ones. observe the fine details so that the assistant does not forget what they explained\n- Relevant code snippets\n- User preferences (like favourites, dislikes, preferences, etc)\n- Any specifically formatted text or ascii that would need to be reproduced or referenced in later interactions (preserve these verbatim in memory)\n- Sequences, units, measurements, and any kind of specific relevant data\n- Any blocks of any text which the user and assistant are iteratively collaborating back and forth on should be preserved verbatim\n- When who/what/where/when is mentioned, note that in the observation. Example: if the user received went on a trip with someone, observe who that someone was, where the trip was, when it happened, and what happened, not just that the user went on the trip.\n- For any described entity (like a person, place, thing, etc), preserve the attributes that would help identify or describe the specific entity later: location (\"near X\"), specialty (\"focuses on Y\"), unique feature (\"has Z\"), relationship (\"owned by W\"), or other details. The entity's name is important, but so are any additional details that distinguish it. If there are a list of entities, preserve these details for each of them.\n\nUSER MESSAGE CAPTURE:\n- Short and medium-length user messages should be captured nearly verbatim in your own words.\n- For very long user messages, summarize but quote key phrases that carry specific intent or meaning.\n- This is critical for continuity: when the conversation window shrinks, the observations are the only record of what the user said.\n\nAVOIDING REPETITIVE OBSERVATIONS:\n- Do NOT repeat the same observation across multiple turns if there is no new information.\n- When the agent performs repeated similar actions (e.g., browsing files, running the same tool type multiple times), group them into a single parent observation with sub-bullets for each new result.\n\nExample \u2014 BAD (repetitive):\n* \uD83D\uDFE1 (14:30) Agent used view tool on src/auth.ts\n* \uD83D\uDFE1 (14:31) Agent used view tool on src/users.ts\n* \uD83D\uDFE1 (14:32) Agent used view tool on src/routes.ts\n\nExample \u2014 GOOD (grouped):\n* \uD83D\uDFE1 (14:30) Agent browsed source files for auth flow\n  * -> viewed src/auth.ts \u2014 found token validation logic\n  * -> viewed src/users.ts \u2014 found user lookup by email\n  * -> viewed src/routes.ts \u2014 found middleware chain\n\nOnly add a new observation for a repeated action if the NEW result changes the picture.\n\nACTIONABLE INSIGHTS:\n- What worked well in explanations\n- What needs follow-up or clarification\n- User's stated goals or next steps (note if the user tells you not to do a next step, or asks for something specific, other next steps besides the users request should be marked as \"waiting for user\", unless the user explicitly says to continue all next steps)\n\nCOMPLETION TRACKING:\nCompletion observations are not just summaries. They are explicit memory signals to the assistant that a task, question, or subtask has been resolved.\nWithout clear completion markers, the assistant may forget that work is already finished and may repeat, reopen, or continue an already-completed task.\n\nUse \u2705 to answer: \"What exactly is now done?\"\nChoose completion observations that help the assistant know what is finished and should not be reworked unless new information appears.\n\nUse \u2705 when:\n- The user explicitly confirms something worked or was answered (\"thanks, that fixed it\", \"got it\", \"perfect\")\n- The assistant provided a definitive, complete answer to a factual question and the user moved on\n- A multi-step task reached its stated goal\n- The user acknowledged receipt of requested information\n- A concrete subtask, fix, deliverable, or implementation step became complete during ongoing work\n\nDo NOT use \u2705 when:\n- The assistant merely responded \u2014 the user might follow up with corrections\n- The topic is paused but not resolved (\"I'll try that later\")\n- The user's reaction is ambiguous\n\nFORMAT:\nAs a sub-bullet under the related observation group:\n* \uD83D\uDD34 (14:30) User asked how to configure auth middleware\n  * -> Agent explained JWT setup with code example\n  * \u2705 User confirmed auth is working\n\nOr as a standalone observation when closing out a broader task:\n* \u2705 (14:45) Auth configuration task completed \u2014 user confirmed middleware is working\n\nCompletion observations should be terse but specific about WHAT was completed.\nPrefer concrete resolved outcomes over abstract workflow status so the assistant remembers what is already done.";
/**
 * The output format instructions for the Observer.
 * This is exported so the Reflector can use the same format.
 */
/**
 * Base output format for Observer (without patterns section)
 */
export declare const OBSERVER_OUTPUT_FORMAT_BASE: string;
export declare function buildObserverOutputFormat(includeThreadTitle?: boolean): string;
/**
 * The guidelines for the Observer.
 * This is exported so the Reflector can reference them.
 */
export declare const OBSERVER_GUIDELINES = "- Be specific enough for the assistant to act on\n- Good: \"User prefers short, direct answers without lengthy explanations\"\n- Bad: \"User stated a preference\" (too vague)\n- Add 1 to 5 observations per exchange\n- Use terse language to save tokens. Sentences should be dense without unnecessary words\n- Do not add repetitive observations that have already been observed. Group repeated similar actions (tool calls, file browsing) under a single parent with sub-bullets for new results\n- If the agent calls tools, observe what was called, why, and what was learned\n- When observing files with line numbers, include the line number if useful\n- If the agent provides a detailed response, observe the contents so it could be repeated\n- Make sure you start each observation with a priority emoji (\uD83D\uDD34, \uD83D\uDFE1, \uD83D\uDFE2) or a completion marker (\u2705)\n- Capture the user's words closely \u2014 short/medium messages near-verbatim, long messages summarized with key quotes. User confirmations or explicit resolved outcomes should be \u2705 when they clearly signal something is done; unresolved or critical user facts remain \uD83D\uDD34\n- Treat \u2705 as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it\n- Make completion observations answer \"What exactly is now done?\"\n- Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates\n- When multiple concrete things were completed, capture the concrete completed work rather than collapsing it into a vague progress summary\n- Observe WHAT the agent did and WHAT it means\n- If the user provides detailed messages or code snippets, observe all important details";
/**
 * Build the complete observer system prompt.
 * @param multiThread - Whether this is for multi-thread batched observation (default: false)
 * @param instruction - Optional custom instructions to append to the prompt
 */
export declare function buildObserverSystemPrompt(multiThread?: boolean, instruction?: string, includeThreadTitle?: boolean): string;
/**
 * Observer Agent System Prompt (default - for backwards compatibility)
 *
 * This prompt instructs the Observer to extract observations from message history.
 * The observations become the agent's "subconscious memory" - the ONLY information
 * the main agent will have about past interactions.
 */
export declare const OBSERVER_SYSTEM_PROMPT: string;
/**
 * Result from the Observer agent
 */
export interface ObserverResult {
    /** The extracted observations in markdown format */
    observations: string;
    /** The current task extracted from observations (for thread metadata) */
    currentTask?: string;
    /** Suggested continuation message for the Actor */
    suggestedContinuation?: string;
    /** The suggested thread title (short/concise, for thread metadata) */
    threadTitle?: string;
    /** Raw output from the model (for debugging) */
    rawOutput?: string;
    /** True if the output was detected as degenerate (repetition loop) and should be discarded/retried */
    degenerate?: boolean;
}
export declare function formatMessagesForObserver(messages: MastraDBMessage[], options?: ObserverFormatOptions): string;
export declare function buildObserverHistoryMessage(messages: MastraDBMessage[], options?: ObserverFormatOptions): CoreMessage;
/**
 * Format messages from multiple threads for batched observation.
 * Each thread's messages are wrapped in a <thread id="..."> block.
 */
export declare function formatMultiThreadMessagesForObserver(messagesByThread: Map<string, MastraDBMessage[]>, threadOrder: string[], options?: ObserverFormatOptions): string;
export declare function buildMultiThreadObserverHistoryMessage(messagesByThread: Map<string, MastraDBMessage[]>, threadOrder: string[], options?: ObserverFormatOptions): CoreMessage;
export declare function buildMultiThreadObserverTaskPrompt(existingObservations: string | undefined, threadOrder?: string[], priorMetadataByThread?: Map<string, {
    currentTask?: string;
    suggestedResponse?: string;
    threadTitle?: string;
}>, wasTruncated?: boolean, includeThreadTitle?: boolean): string;
/**
 * Build the prompt for multi-thread batched observation.
 */
export declare function buildMultiThreadObserverPrompt(existingObservations: string | undefined, messagesByThread: Map<string, MastraDBMessage[]>, threadOrder: string[], priorMetadataByThread?: Map<string, {
    currentTask?: string;
    suggestedResponse?: string;
    threadTitle?: string;
}>, wasTruncated?: boolean, options?: ObserverFormatOptions, includeThreadTitle?: boolean): string;
/**
 * Result from parsing multi-thread Observer output
 */
export interface MultiThreadObserverResult {
    /** Results per thread */
    threads: Map<string, ObserverResult>;
    /** Raw output from the model (for debugging) */
    rawOutput: string;
    /** True if the output was detected as degenerate (repetition loop) and should be discarded/retried */
    degenerate?: boolean;
}
/**
 * Parse multi-thread Observer output to extract per-thread results.
 */
export declare function parseMultiThreadObserverOutput(output: string): MultiThreadObserverResult;
export declare function buildObserverTaskPrompt(existingObservations: string | undefined, options?: {
    skipContinuationHints?: boolean;
    priorCurrentTask?: string;
    priorSuggestedResponse?: string;
    priorThreadTitle?: string;
    wasTruncated?: boolean;
    includeThreadTitle?: boolean;
}): string;
/**
 * Build the full prompt for the Observer agent.
 * Includes emphasis on the most recent user message for priority handling.
 */
export declare function buildObserverPrompt(existingObservations: string | undefined, messagesToObserve: MastraDBMessage[], options?: {
    skipContinuationHints?: boolean;
    priorCurrentTask?: string;
    priorSuggestedResponse?: string;
    priorThreadTitle?: string;
    wasTruncated?: boolean;
    includeThreadTitle?: boolean;
}): string;
/**
 * Parse the Observer's output to extract observations, current task, and suggested response.
 * Uses XML tag parsing for structured extraction.
 */
export declare function parseObserverOutput(output: string): ObserverResult;
/**
 * Parsed result from XML memory section
 */
interface ParsedMemorySection {
    observations: string;
    currentTask: string;
    suggestedResponse: string;
    threadTitle: string;
}
/**
 * Parse XML tags from observer/reflector output.
 * Extracts content from <observations>, <current-task>, and <suggested-response> tags.
 */
export declare function parseMemorySectionXml(content: string): ParsedMemorySection;
/**
 * Truncate individual observation lines that exceed the maximum length.
 */
export declare function sanitizeObservationLines(observations: string): string;
/**
 * Detect degenerate repetition in observer/reflector output.
 * Returns true if the text contains suspicious levels of repeated content,
 * which indicates an LLM repeat-penalty bug (e.g., Gemini Flash looping).
 *
 * Strategy: sample sequential chunks of the text and check if a high
 * proportion are near-identical to previous chunks.
 */
export declare function detectDegenerateRepetition(text: string): boolean;
/**
 * Check if observations contain a Current Task section.
 * Supports both XML format and legacy markdown format.
 */
export declare function hasCurrentTaskSection(observations: string): boolean;
/**
 * Extract the Current Task content from observations.
 */
export declare function extractCurrentTask(observations: string): string | null;
/**
 * Optimize observations for token efficiency before presenting to the Actor.
 *
 * This removes:
 * - Non-critical emojis (🟡 and 🟢, keeping only 🔴)
 * - Semantic tags [label, label]
 * - Arrow indicators (->)
 * - Extra whitespace
 *
 * The full format is preserved in storage for analysis.
 */
export declare function optimizeObservationsForContext(observations: string): string;
export {};
//# sourceMappingURL=observer-agent.d.ts.map