{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n  UsageMetadata,\n  BaseMessage,\n  BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { ContentTypes, Providers } from '@/common';\nimport { toJsonSchema } from '@/utils/schema';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n  /**\n   * Create an AgentContext from configuration with token accounting initialization\n   */\n  static fromConfig(\n    agentConfig: t.AgentInputs,\n    tokenCounter?: t.TokenCounter,\n    indexTokenCountMap?: Record<string, number>\n  ): AgentContext {\n    const {\n      agentId,\n      name,\n      description,\n      provider,\n      clientOptions,\n      tools,\n      toolMap,\n      toolEnd,\n      toolRegistry,\n      toolDefinitions,\n      instructions,\n      additional_instructions,\n      streamBuffer,\n      maxContextTokens,\n      reasoningKey,\n      useLegacyContent,\n      dynamicContext,\n      structuredOutput: structuredOutputCamel,\n\n      structured_output: structuredOutputSnake,\n      discoveredTools,\n      summarizeCallback,\n      persistedSummary,\n      summarizationConfig,\n      fileManifest,\n      system_cache_blocks,\n      instructions_cache_ttl,\n    } = agentConfig;\n\n    // Normalize structured output: support both camelCase and snake_case inputs\n    // Priority: structuredOutput (camelCase) > structured_output (snake_case with enabled check)\n    let structuredOutput: t.StructuredOutputConfig | undefined;\n    if (structuredOutputCamel) {\n      structuredOutput = structuredOutputCamel;\n    } else if (\n      structuredOutputSnake?.enabled === true &&\n      structuredOutputSnake.schema != null\n    ) {\n      // Convert snake_case input to StructuredOutputConfig\n      structuredOutput = {\n        schema: structuredOutputSnake.schema,\n        name: structuredOutputSnake.name,\n        description: structuredOutputSnake.description,\n        mode: structuredOutputSnake.mode,\n        strict: structuredOutputSnake.strict,\n      };\n    }\n\n    const agentContext = new AgentContext({\n      agentId,\n      name: name ?? agentId,\n      description,\n      provider,\n      clientOptions,\n      maxContextTokens,\n      streamBuffer,\n      tools,\n      toolMap,\n      toolRegistry,\n      toolDefinitions,\n      instructions,\n      additionalInstructions: additional_instructions,\n      reasoningKey,\n      toolEnd,\n      instructionTokens: 0,\n      tokenCounter,\n      useLegacyContent,\n      dynamicContext,\n      structuredOutput,\n      discoveredTools,\n      summarizeCallback,\n      persistedSummary,\n      summarizationConfig,\n      fileManifest,\n      systemCacheBlocks: system_cache_blocks,\n      instructionsCacheTtl: instructions_cache_ttl,\n    });\n\n    /**\n     * Track upstream-aligned subagent inputs on the context. `_sourceInputs`\n     * preserves the original AgentInputs so SubagentExecutor can self-spawn\n     * (`SubagentConfig.self === true`) without separate config; the other\n     * two flow straight from agentConfig.\n     */\n    agentContext._sourceInputs = agentConfig;\n    agentContext.subagentConfigs = agentConfig.subagentConfigs;\n    agentContext.maxSubagentDepth = agentConfig.maxSubagentDepth;\n\n    if (tokenCounter) {\n      // Initialize system runnable BEFORE async tool token calculation\n      // This ensures system message tokens are in instructionTokens before\n      // updateTokenMapWithInstructions is called\n      agentContext.initializeSystemRunnable();\n\n      const tokenMap = indexTokenCountMap || {};\n      agentContext.baseIndexTokenCountMap = { ...tokenMap };\n      agentContext.indexTokenCountMap = tokenMap;\n      agentContext.tokenCalculationPromise = agentContext\n        .calculateInstructionTokens(tokenCounter)\n        .then(() => {\n          // Update token map with instruction tokens (includes system + tool tokens)\n          agentContext.updateTokenMapWithInstructions(tokenMap);\n        })\n        .catch((err) => {\n          console.error('Error calculating instruction tokens:', err);\n        });\n    } else if (indexTokenCountMap) {\n      agentContext.baseIndexTokenCountMap = { ...indexTokenCountMap };\n      agentContext.indexTokenCountMap = indexTokenCountMap;\n    }\n\n    return agentContext;\n  }\n\n  /** Agent identifier */\n  agentId!: string;\n  /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */\n  name?: string;\n  /** Description of what this agent does (used to enrich handoff tool descriptions). */\n  description?: string;\n  /** Provider for this specific agent */\n  provider!: Providers;\n  /** Client options for this agent */\n  clientOptions?: t.ClientOptions;\n  /** Token count map indexed by message position */\n  indexTokenCountMap: Record<string, number | undefined> = {};\n  /** Canonical pre-run token map used to restore token accounting on reset */\n  baseIndexTokenCountMap: Record<string, number> = {};\n  /** Maximum context tokens for this agent */\n  maxContextTokens?: number;\n  /** Current usage metadata for this agent */\n  currentUsage?: Partial<UsageMetadata>;\n  /** Prune messages function configured for this agent */\n  pruneMessages?: ReturnType<typeof createPruneMessages>;\n  /** Token counter function for this agent */\n  tokenCounter?: t.TokenCounter;\n  /** Instructions/system message token count */\n  instructionTokens: number = 0;\n  /** The amount of time that should pass before another consecutive API call */\n  streamBuffer?: number;\n  /** Last stream call timestamp for rate limiting */\n  lastStreamCall?: number;\n  /** Tools available to this agent */\n  tools?: t.GraphTools;\n  /** Graph-managed tools (e.g., handoff tools created by MultiAgentGraph) that bypass event-driven dispatch */\n  graphTools?: t.GraphTools;\n  /** Tool map for this agent */\n  toolMap?: t.ToolMap;\n  /**\n   * Tool definitions registry (includes deferred and programmatic tool metadata).\n   * Used for tool search and programmatic tool calling.\n   */\n  toolRegistry?: t.LCToolRegistry;\n  /**\n   * Serializable tool definitions for event-driven execution.\n   * When provided, ToolNode operates in event-driven mode.\n   */\n  toolDefinitions?: t.LCTool[];\n  /** Set of tool names discovered via tool search (to be loaded) */\n  discoveredToolNames: Set<string> = new Set();\n  /** Instructions for this agent */\n  instructions?: string;\n  /** Additional instructions for this agent */\n  additionalInstructions?: string;\n  /**\n   * Dynamic context that changes per-request (e.g., current time, user info).\n   * This is NOT included in the system message to preserve cache.\n   * Instead, it's injected as a user message at the start of the conversation.\n   */\n  dynamicContext?: string;\n  /** Reasoning key for this agent */\n  reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n  /** Last token for reasoning detection */\n  lastToken?: string;\n  /** Token type switch state */\n  tokenTypeSwitch?: 'reasoning' | 'content';\n  /** Tracks how many reasoning→text transitions have occurred (ensures unique post-reasoning step keys) */\n  reasoningTransitionCount = 0;\n  /** Current token type being processed */\n  currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n    ContentTypes.TEXT;\n  /** Whether tools should end the workflow */\n  toolEnd: boolean = false;\n  /** Cached system runnable (created lazily) */\n  private cachedSystemRunnable?: Runnable<\n    BaseMessage[],\n    (BaseMessage | SystemMessage)[],\n    RunnableConfig<Record<string, unknown>>\n  >;\n  /** Whether system runnable needs rebuild (set when discovered tools change) */\n  private systemRunnableStale: boolean = true;\n  /** Cached system message token count (separate from tool tokens) */\n  private systemMessageTokens: number = 0;\n  /** Promise for token calculation initialization */\n  tokenCalculationPromise?: Promise<void>;\n  /** Format content blocks as strings (for legacy compatibility) */\n  useLegacyContent: boolean = false;\n  /** Detailed per-tool token breakdown for admin tracking */\n  private toolsDetail: Array<{ name: string; tokens: number }> = [];\n  /** Total tool tokens (sum of all toolsDetail) */\n  private toolTokensTotal: number = 0;\n  /** Per-prompt token breakdown for detailed admin reporting */\n  private promptBreakdown: {\n    branding: number;\n    toolRouting: number;\n    agentInstructions: number;\n    mcpInstructions: number;\n    artifacts: number;\n    memory: number;\n  } = {\n    branding: 0,\n    toolRouting: 0,\n    agentInstructions: 0,\n    mcpInstructions: 0,\n    artifacts: 0,\n    memory: 0,\n  };\n  /**\n   * Handoff context when this agent receives control via handoff.\n   * Contains source and parallel execution info for system message context.\n   */\n  handoffContext?: {\n    /** Source agent that transferred control */\n    sourceAgentName: string;\n    /** Names of sibling agents executing in parallel (empty if sequential) */\n    parallelSiblings: string[];\n  };\n  /**\n   * Structured output configuration.\n   * When set, the agent will return a validated JSON response\n   * instead of streaming text.\n   */\n  structuredOutput?: t.StructuredOutputConfig;\n  /** Optional callback to summarize discarded messages during context pruning */\n  summarizeCallback?: (messages: BaseMessage[]) => Promise<string | undefined>;\n  /** Pre-existing summary loaded from persistent storage, injected into context on new turns */\n  persistedSummary?: string;\n  /** Summarization configuration controlling trigger strategy, reserve ratio, and EMA calibration */\n  summarizationConfig?: t.SummarizationConfig;\n  /** Lightweight file manifest for file-aware compaction (IDs and names only, no content) */\n  fileManifest?: t.FileManifestEntry[];\n  /**\n   * Workspace-shared system-message tiers. When set, each entry becomes a\n   * separate text block in the SystemMessage with its own cachePoint /\n   * cache_control marker, BEFORE the per-agent `instructions` block.\n   * See {@link t.AgentInputs.system_cache_blocks} for full semantics.\n   */\n  systemCacheBlocks?: Array<{ text: string; ttl?: '5m' | '1h' }>;\n  /** TTL hint for the per-agent instructions cache marker. Defaults to '5m'. */\n  instructionsCacheTtl?: '5m' | '1h';\n  /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */\n  _sourceInputs?: t.AgentInputs;\n  /** Subagent configurations for hierarchical delegation. */\n  subagentConfigs?: t.SubagentConfig[];\n  /** Maximum subagent nesting depth. */\n  maxSubagentDepth?: number;\n\n  constructor({\n    agentId,\n    name,\n    description,\n    provider,\n    clientOptions,\n    maxContextTokens,\n    streamBuffer,\n    tokenCounter,\n    tools,\n    toolMap,\n    toolRegistry,\n    toolDefinitions,\n    instructions,\n    additionalInstructions,\n    dynamicContext,\n    reasoningKey,\n    toolEnd,\n    instructionTokens,\n    useLegacyContent,\n    structuredOutput,\n    discoveredTools,\n    summarizeCallback,\n    persistedSummary,\n    summarizationConfig,\n    fileManifest,\n    systemCacheBlocks,\n    instructionsCacheTtl,\n  }: {\n    agentId: string;\n    name?: string;\n    description?: string;\n    provider: Providers;\n    clientOptions?: t.ClientOptions;\n    maxContextTokens?: number;\n    streamBuffer?: number;\n    tokenCounter?: t.TokenCounter;\n    tools?: t.GraphTools;\n    toolMap?: t.ToolMap;\n    toolRegistry?: t.LCToolRegistry;\n    toolDefinitions?: t.LCTool[];\n    instructions?: string;\n    additionalInstructions?: string;\n    dynamicContext?: string;\n    reasoningKey?: 'reasoning_content' | 'reasoning';\n    toolEnd?: boolean;\n    instructionTokens?: number;\n    useLegacyContent?: boolean;\n    structuredOutput?: t.StructuredOutputConfig;\n    discoveredTools?: string[];\n    summarizeCallback?: (\n      messages: BaseMessage[]\n    ) => Promise<string | undefined>;\n    persistedSummary?: string;\n    summarizationConfig?: t.SummarizationConfig;\n    fileManifest?: t.FileManifestEntry[];\n    systemCacheBlocks?: Array<{ text: string; ttl?: '5m' | '1h' }>;\n    instructionsCacheTtl?: '5m' | '1h';\n  }) {\n    this.agentId = agentId;\n    this.name = name;\n    this.description = description;\n    this.provider = provider;\n    this.clientOptions = clientOptions;\n    this.maxContextTokens = maxContextTokens;\n    this.streamBuffer = streamBuffer;\n    this.tokenCounter = tokenCounter;\n    this.tools = tools;\n    this.toolMap = toolMap;\n    this.toolRegistry = toolRegistry;\n    this.toolDefinitions = toolDefinitions;\n    this.instructions = instructions;\n    this.additionalInstructions = additionalInstructions;\n    this.dynamicContext = dynamicContext;\n    this.structuredOutput = structuredOutput;\n    this.summarizeCallback = summarizeCallback;\n    this.persistedSummary = persistedSummary;\n    this.summarizationConfig = summarizationConfig;\n    this.fileManifest = fileManifest;\n    if (systemCacheBlocks && systemCacheBlocks.length > 0) {\n      this.systemCacheBlocks = systemCacheBlocks;\n    }\n    if (instructionsCacheTtl) {\n      this.instructionsCacheTtl = instructionsCacheTtl;\n    }\n    if (reasoningKey) {\n      this.reasoningKey = reasoningKey;\n    }\n    if (toolEnd !== undefined) {\n      this.toolEnd = toolEnd;\n    }\n    if (instructionTokens !== undefined) {\n      this.instructionTokens = instructionTokens;\n    }\n\n    this.useLegacyContent = useLegacyContent ?? false;\n\n    if (discoveredTools && discoveredTools.length > 0) {\n      for (const toolName of discoveredTools) {\n        this.discoveredToolNames.add(toolName);\n      }\n    }\n  }\n\n  /**\n   * Checks if structured output mode is enabled for this agent.\n   * When enabled, the agent will use model.invoke() instead of streaming\n   * and return a validated JSON response.\n   */\n  get isStructuredOutputMode(): boolean {\n    // Runtime safety: schema can be null/undefined via API despite type saying required\n    return (\n      this.structuredOutput != null &&\n      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n      this.structuredOutput.schema != null\n    );\n  }\n\n  /**\n   * Gets the structured output schema with normalized defaults.\n   * Returns undefined if structured output is not configured.\n   */\n  getStructuredOutputSchema(): Record<string, unknown> | undefined {\n    if (!this.structuredOutput?.schema) {\n      return undefined;\n    }\n\n    const schema = { ...this.structuredOutput.schema };\n\n    // Ensure type is set\n    if (schema.type == null && schema.properties != null) {\n      schema.type = 'object';\n    }\n\n    // Add title from config name\n    if (\n      this.structuredOutput.name != null &&\n      this.structuredOutput.name !== '' &&\n      schema.title == null\n    ) {\n      schema.title = this.structuredOutput.name;\n    }\n\n    // Add description from config\n    if (\n      this.structuredOutput.description != null &&\n      this.structuredOutput.description !== '' &&\n      schema.description == null\n    ) {\n      schema.description = this.structuredOutput.description;\n    }\n\n    // Enable strict mode by default\n    if (this.structuredOutput.strict !== false && schema.type === 'object') {\n      schema.additionalProperties = schema.additionalProperties ?? false;\n    }\n\n    return schema;\n  }\n\n  /**\n   * Resolves the structured output mode to a concrete method based on provider capabilities.\n   *\n   * Resolution logic:\n   * - 'native' or 'auto' + supported provider → native constrained decoding\n   * - 'native' + unsupported provider → fallback to 'functionCalling' with warning\n   * - 'provider' → LangChain's jsonMode (existing behavior)\n   * - 'tool' → function calling trick (existing behavior)\n   * - 'auto' + unsupported provider → 'functionCalling'\n   *\n   * @returns The resolved method for withStructuredOutput, or 'native' for direct API usage\n   */\n  resolveStructuredOutputMode(): {\n    method: t.ResolvedStructuredOutputMethod;\n    warnings: string[];\n  } {\n    const mode = this.structuredOutput?.mode ?? 'auto';\n    const warnings: string[] = [];\n\n    // Providers that support native constrained decoding via LangChain\n    const nativeProviders = new Set([\n      Providers.ANTHROPIC,\n      Providers.OPENAI,\n      Providers.AZURE,\n    ]);\n\n    // Providers where LangChain supports jsonMode\n    const jsonModeProviders = new Set([\n      Providers.ANTHROPIC,\n      Providers.OPENAI,\n      Providers.AZURE,\n    ]);\n\n    switch (mode) {\n      case 'native': {\n        if (nativeProviders.has(this.provider)) {\n          if (this.provider === Providers.ANTHROPIC) {\n            return { method: 'jsonSchema', warnings };\n          }\n          // OpenAI/Azure\n          return { method: 'jsonSchema', warnings };\n        }\n        // Fallback for unsupported providers\n        warnings.push(\n          `Native structured output is not supported for provider '${this.provider}'. Falling back to function calling.`\n        );\n        return { method: 'functionCalling', warnings };\n      }\n\n      case 'auto': {\n        if (nativeProviders.has(this.provider)) {\n          if (this.provider === Providers.ANTHROPIC) {\n            return { method: 'jsonSchema', warnings };\n          }\n          // OpenAI/Azure\n          return { method: 'jsonSchema', warnings };\n        }\n        // Default to function calling for all other providers\n        return { method: undefined, warnings };\n      }\n\n      case 'provider': {\n        if (this.provider === Providers.BEDROCK) {\n          // Bedrock doesn't support jsonMode, fall back to functionCalling\n          return { method: 'functionCalling', warnings };\n        }\n        if (jsonModeProviders.has(this.provider)) {\n          return { method: 'jsonMode', warnings };\n        }\n        return { method: 'jsonMode', warnings };\n      }\n\n      case 'tool': {\n        return { method: 'functionCalling', warnings };\n      }\n\n      default: {\n        return { method: undefined, warnings };\n      }\n    }\n  }\n\n  /**\n   * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n   * These tools cannot be called directly by the LLM but are available through the\n   * run_tools_with_code tool.\n   *\n   * Includes:\n   * - Code_execution-only tools that are NOT deferred\n   * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n   */\n  private buildProgrammaticOnlyToolsInstructions(): string {\n    if (!this.toolRegistry) return '';\n\n    const programmaticOnlyTools: t.LCTool[] = [];\n    for (const [name, toolDef] of this.toolRegistry) {\n      const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n      const isCodeExecutionOnly =\n        allowedCallers.includes('code_execution') &&\n        !allowedCallers.includes('direct');\n\n      if (!isCodeExecutionOnly) continue;\n\n      // Include if: not deferred OR deferred but discovered\n      const isDeferred = toolDef.defer_loading === true;\n      const isDiscovered = this.discoveredToolNames.has(name);\n      if (!isDeferred || isDiscovered) {\n        programmaticOnlyTools.push(toolDef);\n      }\n    }\n\n    if (programmaticOnlyTools.length === 0) return '';\n\n    const toolDescriptions = programmaticOnlyTools\n      .map((tool) => {\n        let desc = `- **${tool.name}**`;\n        if (tool.description != null && tool.description !== '') {\n          desc += `: ${tool.description}`;\n        }\n        if (tool.parameters) {\n          desc += `\\n  Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n  ')}`;\n        }\n        return desc;\n      })\n      .join('\\n\\n');\n\n    return (\n      '\\n\\n## Programmatic-Only Tools\\n\\n' +\n      'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n      'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n      toolDescriptions\n    );\n  }\n\n  /**\n   * Gets the system runnable, creating it lazily if needed.\n   * Includes instructions, additional instructions, and programmatic-only tools documentation.\n   * Only rebuilds when marked stale (via markToolsAsDiscovered).\n   */\n  get systemRunnable():\n    | Runnable<\n        BaseMessage[],\n        (BaseMessage | SystemMessage)[],\n        RunnableConfig<Record<string, unknown>>\n      >\n    | undefined {\n    // Return cached if not stale\n    if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n      return this.cachedSystemRunnable;\n    }\n\n    // Stale or first access - rebuild\n    const instructionsString = this.buildInstructionsString();\n    this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n    this.systemRunnableStale = false;\n    return this.cachedSystemRunnable;\n  }\n\n  /**\n   * Explicitly initializes the system runnable.\n   * Call this before async token calculation to ensure system message tokens are counted first.\n   */\n  initializeSystemRunnable(): void {\n    if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n      const instructionsString = this.buildInstructionsString();\n      this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n      this.systemRunnableStale = false;\n    }\n  }\n\n  /**\n   * Builds the raw instructions string (without creating SystemMessage).\n   * Includes agent identity preamble and handoff context when available.\n   */\n  private buildInstructionsString(): string {\n    const parts: string[] = [];\n\n    /** Build agent identity and handoff context preamble */\n    const identityPreamble = this.buildIdentityPreamble();\n    if (identityPreamble) {\n      parts.push(identityPreamble);\n    }\n\n    /** Add main instructions */\n    if (this.instructions != null && this.instructions !== '') {\n      parts.push(this.instructions);\n    }\n\n    /** Add additional instructions */\n    if (\n      this.additionalInstructions != null &&\n      this.additionalInstructions !== ''\n    ) {\n      parts.push(this.additionalInstructions);\n    }\n\n    /** Add programmatic tools documentation */\n    const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n    if (programmaticToolsDoc) {\n      parts.push(programmaticToolsDoc);\n    }\n\n    return parts.join('\\n\\n');\n  }\n\n  /**\n   * Builds the agent identity preamble including handoff context if present.\n   * This helps the agent understand its role in the multi-agent workflow.\n   */\n  private buildIdentityPreamble(): string {\n    if (!this.handoffContext) return '';\n\n    const displayName = this.name ?? this.agentId;\n    const { sourceAgentName, parallelSiblings } = this.handoffContext;\n    const isParallel = parallelSiblings.length > 0;\n\n    const lines: string[] = [];\n    lines.push('## Subagent Context');\n    lines.push('');\n    lines.push(\n      `You are \"${displayName}\", a subagent spawned by \"${sourceAgentName}\" for a specific task.`\n    );\n\n    if (isParallel) {\n      lines.push(`Running in parallel with: ${parallelSiblings.join(', ')}.`);\n    }\n\n    lines.push('');\n    lines.push('### Your Role');\n    lines.push('- Complete your assigned task. That is your entire purpose.');\n    lines.push(`- You are NOT \"${sourceAgentName}\". Do not try to be.`);\n    lines.push('');\n    lines.push('### Rules');\n    lines.push('1. **Stay focused** — Do your assigned task, nothing else.');\n    lines.push(\n      '2. **Complete the task** — Your final message will be automatically reported back.'\n    );\n    lines.push(\n      '3. **Be autonomous** — Execute directly without asking for user confirmation. Use your tools and best judgment.'\n    );\n    lines.push(\n      '4. **No placeholders** — Never generate fake or placeholder data. If you cannot retrieve real data, say so.'\n    );\n    lines.push(\n      '5. **No side effects** — Do not send messages, emails, or notifications unless explicitly tasked to do so.'\n    );\n    lines.push('');\n    lines.push('### Output');\n    lines.push('When complete, your final response should include:');\n    lines.push('- What you accomplished or found');\n    lines.push('- Any relevant details the orchestrator should know');\n    lines.push('- Keep it concise but informative');\n\n    return lines.join('\\n');\n  }\n\n  /**\n   * Build system runnable from pre-built instructions string.\n   * Only called when content has actually changed.\n   */\n  private buildSystemRunnable(\n    instructionsString: string\n  ):\n    | Runnable<\n        BaseMessage[],\n        (BaseMessage | SystemMessage)[],\n        RunnableConfig<Record<string, unknown>>\n      >\n    | undefined {\n    if (!instructionsString) {\n      // Remove previous tokens if we had a system message before\n      this.instructionTokens -= this.systemMessageTokens;\n      this.systemMessageTokens = 0;\n      return undefined;\n    }\n\n    let finalInstructions: string | BaseMessageFields = instructionsString;\n\n    /**\n     * Tiered system-message assembly. When `systemCacheBlocks` is set, build\n     * a multi-block SystemMessage so each tier has its own cache breakpoint:\n     *\n     *   [tier1_block_1][tier1_cachePoint]...[tier1_block_N][tier1_cachePoint]\n     *   [instructions][instructions_cachePoint]\n     *\n     * Forward-prefix-hash means agents in the same workspace whose tier-1\n     * bytes are identical share the platform cache entry; only the per-agent\n     * `instructions` block invalidates per-agent.\n     *\n     * - Bedrock: emit `cachePoint: { type: 'default' }` blocks (handled by\n     *   `convertSystemMessageToConverseMessage`).\n     * - Anthropic: emit `cache_control: { type: 'ephemeral' }` on each text\n     *   block. (TTL hints are dropped for Anthropic — the SDK currently\n     *   only supports `'ephemeral'`. Bedrock cachePoint has no TTL knob.)\n     */\n    const hasTieredCache =\n      Array.isArray(this.systemCacheBlocks) &&\n      this.systemCacheBlocks.length > 0;\n    const isBedrock = this.provider === Providers.BEDROCK;\n    const isAnthropic = this.provider === Providers.ANTHROPIC;\n    const anthropicCacheEnabled =\n      isAnthropic &&\n      (this.clientOptions as t.AnthropicClientOptions | undefined)\n        ?.promptCache === true;\n    /**\n     * Bedrock cachePoint is Claude-only — Nova/Llama/Titan reject it.\n     * Mirrors the model check in `IllumaBedrockConverse.invocationParams`\n     * (src/llm/bedrock/index.ts:186-189).\n     */\n    const bedrockCacheEnabled =\n      isBedrock &&\n      (() => {\n        const opts = this.clientOptions as\n          | (t.BedrockAnthropicClientOptions & { model?: string })\n          | undefined;\n        const modelId = (opts?.model ?? '').toLowerCase();\n        const isClaudeModel =\n          modelId.includes('claude') || modelId.includes('anthropic');\n        return opts?.promptCache === true && isClaudeModel;\n      })();\n\n    if (hasTieredCache && (bedrockCacheEnabled || anthropicCacheEnabled)) {\n      /**\n       * Anthropic / Bedrock cap cache breakpoints at 4 per request. The\n       * lib already emits one for tools and up to two for messages, so we\n       * have at most 1 left for the system block. We spend it on Tier 1\n       * (the workspace-shared bytes) — per-agent Tier 2 caching is still\n       * achieved implicitly via the tools breakpoint that follows, since\n       * cache lookups are forward-prefix-hash.\n       *\n       * Tier 1 may itself be emitted as multiple text blocks (one per\n       * `systemCacheBlocks` entry); only the LAST gets the cache marker,\n       * the rest are plain text inside the same cached prefix.\n       */\n      const contentBlocks: Array<Record<string, unknown>> = [];\n      const tier1Blocks = this.systemCacheBlocks!.filter((b) => b?.text);\n      tier1Blocks.forEach((block, idx) => {\n        const isLast = idx === tier1Blocks.length - 1;\n        if (bedrockCacheEnabled) {\n          contentBlocks.push({ type: 'text', text: block.text });\n          if (isLast) {\n            contentBlocks.push({ cachePoint: { type: 'default' } });\n          }\n        } else if (isLast) {\n          contentBlocks.push({\n            type: 'text',\n            text: block.text,\n            cache_control: { type: 'ephemeral' },\n          });\n        } else {\n          contentBlocks.push({ type: 'text', text: block.text });\n        }\n      });\n      if (instructionsString) {\n        // No cache marker on the trailing per-agent block — tools'\n        // breakpoint covers it.\n        contentBlocks.push({ type: 'text', text: instructionsString });\n      }\n      finalInstructions = {\n        content: contentBlocks as unknown as BaseMessageFields['content'],\n      };\n    } else if (anthropicCacheEnabled) {\n      // Legacy single-block Anthropic caching (preserved for back-compat).\n      finalInstructions = {\n        content: [\n          {\n            type: 'text',\n            text: instructionsString,\n            cache_control: { type: 'ephemeral' },\n          },\n        ],\n      };\n    }\n\n    const systemMessage = new SystemMessage(finalInstructions);\n\n    // Update token counts (subtract old, add new)\n    if (this.tokenCounter) {\n      this.instructionTokens -= this.systemMessageTokens;\n      this.systemMessageTokens = this.tokenCounter(systemMessage);\n      this.instructionTokens += this.systemMessageTokens;\n    }\n\n    return RunnableLambda.from((messages: BaseMessage[]) => {\n      return [systemMessage, ...messages];\n    }).withConfig({ runName: 'prompt' });\n  }\n\n  /**\n   * Reset context for a new run\n   */\n  reset(): void {\n    this.instructionTokens = 0;\n    this.systemMessageTokens = 0;\n    this.toolsDetail = [];\n    this.toolTokensTotal = 0;\n    this.cachedSystemRunnable = undefined;\n    this.systemRunnableStale = true;\n    this.lastToken = undefined;\n    this.indexTokenCountMap = { ...this.baseIndexTokenCountMap };\n    this.currentUsage = undefined;\n    this.pruneMessages = undefined;\n    this.lastStreamCall = undefined;\n    this.tokenTypeSwitch = undefined;\n    this.reasoningTransitionCount = 0;\n    this.currentTokenType = ContentTypes.TEXT;\n    this.discoveredToolNames.clear();\n    this.handoffContext = undefined;\n\n    if (this.tokenCounter) {\n      this.initializeSystemRunnable();\n      const baseTokenMap = { ...this.baseIndexTokenCountMap };\n      this.indexTokenCountMap = baseTokenMap;\n      this.tokenCalculationPromise = this.calculateInstructionTokens(\n        this.tokenCounter\n      )\n        .then(() => {\n          this.updateTokenMapWithInstructions(baseTokenMap);\n        })\n        .catch((err) => {\n          console.error('Error calculating instruction tokens:', err);\n        });\n    } else {\n      this.tokenCalculationPromise = undefined;\n    }\n  }\n\n  /**\n   * Update the token count map with instruction tokens\n   */\n  updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n    if (this.instructionTokens > 0) {\n      // Shift all indices by the instruction token count\n      const shiftedMap: Record<string, number> = {};\n      for (const [key, value] of Object.entries(baseTokenMap)) {\n        const index = parseInt(key, 10);\n        if (!isNaN(index)) {\n          shiftedMap[String(index)] =\n            value + (index === 0 ? this.instructionTokens : 0);\n        }\n      }\n      this.indexTokenCountMap = shiftedMap;\n    } else {\n      this.indexTokenCountMap = { ...baseTokenMap };\n    }\n  }\n\n  /**\n   * Calculate tool tokens and add to instruction tokens\n   * Note: System message tokens are calculated during systemRunnable creation\n   * Also tracks per-tool token breakdown for admin reporting\n   */\n  async calculateInstructionTokens(\n    tokenCounter: t.TokenCounter\n  ): Promise<void> {\n    let toolTokens = 0;\n    // Track names to avoid double-counting when a tool appears in both\n    // this.tools (bound StructuredTool instances) and this.toolDefinitions\n    // (MCP / event-driven schemas).\n    const countedToolNames = new Set<string>();\n\n    // Reset per-tool breakdown\n    this.toolsDetail = [];\n\n    // Count tokens for bound tools (StructuredTool instances with .schema)\n    if (this.tools && this.tools.length > 0) {\n      for (const tool of this.tools) {\n        const genericTool = tool as Record<string, unknown>;\n        if (\n          genericTool.schema != null &&\n          typeof genericTool.schema === 'object'\n        ) {\n          const toolName = (genericTool.name as string | undefined) ?? '';\n          const jsonSchema = toJsonSchema(\n            genericTool.schema,\n            toolName,\n            (genericTool.description as string | undefined) ?? ''\n          );\n          const tokens = tokenCounter(\n            new SystemMessage(JSON.stringify(jsonSchema))\n          );\n          if (toolName) {\n            countedToolNames.add(toolName);\n          }\n\n          // Track per-tool breakdown\n          this.toolsDetail.push({ name: toolName || 'unknown', tokens });\n          toolTokens += tokens;\n        }\n      }\n    }\n\n    // Count tokens for tool definitions (MCP / event-driven tools).\n    // These are sent to the provider API as tool schemas alongside bound tools.\n    // Both can be populated simultaneously (graph tools + MCP tools).\n    if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n      for (const def of this.toolDefinitions) {\n        if (countedToolNames.has(def.name)) {\n          continue; // Already counted via this.tools\n        }\n        const schema = {\n          name: def.name,\n          description: def.description ?? '',\n          parameters: def.parameters ?? {},\n        };\n        const defTokens = tokenCounter(\n          new SystemMessage(JSON.stringify(schema))\n        );\n        this.toolsDetail.push({\n          name: def.name || 'unknown',\n          tokens: defTokens,\n        });\n        toolTokens += defTokens;\n      }\n    }\n\n    // Store total tool tokens for breakdown reporting\n    this.toolTokensTotal = toolTokens;\n\n    // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n    this.instructionTokens += toolTokens;\n  }\n\n  /**\n   * Set the per-prompt token breakdown for detailed admin tracking.\n   * Called by the client after assembling all prompt components.\n   * @param breakdown - Object with token counts per prompt component\n   */\n  setPromptBreakdown(breakdown: {\n    branding?: number;\n    toolRouting?: number;\n    agentInstructions?: number;\n    mcpInstructions?: number;\n    artifacts?: number;\n    memory?: number;\n  }): void {\n    if (breakdown.branding !== undefined)\n      this.promptBreakdown.branding = breakdown.branding;\n    if (breakdown.toolRouting !== undefined)\n      this.promptBreakdown.toolRouting = breakdown.toolRouting;\n    if (breakdown.agentInstructions !== undefined)\n      this.promptBreakdown.agentInstructions = breakdown.agentInstructions;\n    if (breakdown.mcpInstructions !== undefined)\n      this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;\n    if (breakdown.artifacts !== undefined)\n      this.promptBreakdown.artifacts = breakdown.artifacts;\n    if (breakdown.memory !== undefined)\n      this.promptBreakdown.memory = breakdown.memory;\n  }\n\n  /**\n   * Get a detailed breakdown of context tokens for admin reporting.\n   * This provides visibility into what's consuming the input token budget.\n   * @returns ContextBreakdown object with per-component token counts\n   */\n  getContextBreakdown(): {\n    instructions: number;\n    artifacts: number;\n    tools: number;\n    toolCount: number;\n    toolContext: number;\n    total: number;\n    toolsDetail: Array<{ name: string; tokens: number }>;\n    toolContextDetail: Array<{ name: string; tokens: number }>;\n    prompts?: {\n      branding: number;\n      toolRouting: number;\n      agentInstructions: number;\n      mcpInstructions: number;\n      artifacts: number;\n      memory: number;\n    };\n  } {\n    // Calculate sum of prompt components\n    const promptsTotal =\n      this.promptBreakdown.branding +\n      this.promptBreakdown.toolRouting +\n      this.promptBreakdown.agentInstructions +\n      this.promptBreakdown.mcpInstructions +\n      this.promptBreakdown.artifacts +\n      this.promptBreakdown.memory;\n\n    return {\n      // System message tokens (instructions + additional_instructions)\n      instructions: this.systemMessageTokens,\n      // Artifacts prompt tokens\n      artifacts: this.promptBreakdown.artifacts,\n      // Total tool definition tokens\n      tools: this.toolTokensTotal,\n      // Number of tools\n      toolCount: this.toolsDetail.length,\n      // Tool context/usage instructions (currently embedded in system message)\n      toolContext: 0,\n      // Total tracked context tokens\n      total: this.instructionTokens,\n      // Per-tool token breakdown\n      toolsDetail: [...this.toolsDetail],\n      // Tool context detail (currently not tracked separately)\n      toolContextDetail: [],\n      // Per-prompt breakdown (only include if any prompts were tracked)\n      prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,\n    };\n  }\n\n  /**\n   * Gets the tool registry for deferred tools (for tool search).\n   * @param onlyDeferred If true, only returns tools with defer_loading=true\n   * @returns LCToolRegistry with tool definitions\n   */\n  getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n    const registry: t.LCToolRegistry = new Map();\n\n    if (!this.toolRegistry) {\n      return registry;\n    }\n\n    for (const [name, toolDef] of this.toolRegistry) {\n      if (!onlyDeferred || toolDef.defer_loading === true) {\n        registry.set(name, toolDef);\n      }\n    }\n\n    return registry;\n  }\n\n  /**\n   * Sets the handoff context for this agent.\n   * Call this when the agent receives control via handoff from another agent.\n   * Marks system runnable as stale to include handoff context in system message.\n   * @param sourceAgentName - Name of the agent that transferred control\n   * @param parallelSiblings - Names of other agents executing in parallel with this one\n   */\n  setHandoffContext(sourceAgentName: string, parallelSiblings: string[]): void {\n    this.handoffContext = { sourceAgentName, parallelSiblings };\n    this.systemRunnableStale = true;\n  }\n\n  /**\n   * Clears any handoff context.\n   * Call this when resetting the agent or when handoff context is no longer relevant.\n   */\n  clearHandoffContext(): void {\n    if (this.handoffContext) {\n      this.handoffContext = undefined;\n      this.systemRunnableStale = true;\n    }\n  }\n\n  /**\n   * Marks tools as discovered via tool search.\n   * Discovered tools will be included in the next model binding.\n   * Only marks system runnable stale if NEW tools were actually added.\n   * @param toolNames - Array of discovered tool names\n   * @returns true if any new tools were discovered\n   */\n  markToolsAsDiscovered(toolNames: string[]): boolean {\n    let hasNewDiscoveries = false;\n    for (const name of toolNames) {\n      if (!this.discoveredToolNames.has(name)) {\n        this.discoveredToolNames.add(name);\n        hasNewDiscoveries = true;\n      }\n    }\n    if (hasNewDiscoveries) {\n      this.systemRunnableStale = true;\n    }\n    return hasNewDiscoveries;\n  }\n\n  /**\n   * Gets tools that should be bound to the LLM.\n   * In event-driven mode (toolDefinitions present, tools empty), creates schema-only tools.\n   * Otherwise filters tool instances based on:\n   * 1. Non-deferred tools with allowed_callers: ['direct']\n   * 2. Discovered tools (from tool search)\n   * @returns Array of tools to bind to model\n   */\n  getToolsForBinding(): t.GraphTools | undefined {\n    /** Event-driven mode: create schema-only tools from definitions */\n    if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n      return this.getEventDrivenToolsForBinding();\n    }\n\n    /** Traditional mode: filter actual tool instances */\n    const filtered =\n      !this.tools || !this.toolRegistry\n        ? this.tools\n        : this.filterToolsForBinding(this.tools);\n\n    if (this.graphTools && this.graphTools.length > 0) {\n      return [...(filtered ?? []), ...this.graphTools];\n    }\n\n    return filtered;\n  }\n\n  /** Creates schema-only tools from toolDefinitions for event-driven mode, merged with native tools */\n  private getEventDrivenToolsForBinding(): t.GraphTools {\n    if (!this.toolDefinitions) {\n      return this.graphTools ?? [];\n    }\n\n    const defsToInclude = this.toolDefinitions.filter((def) => {\n      const allowedCallers = def.allowed_callers ?? ['direct'];\n      if (!allowedCallers.includes('direct')) {\n        return false;\n      }\n      if (\n        def.defer_loading === true &&\n        !this.discoveredToolNames.has(def.name)\n      ) {\n        return false;\n      }\n      return true;\n    });\n\n    const schemaTools = createSchemaOnlyTools(defsToInclude) as t.GraphTools;\n\n    const allTools = [...schemaTools];\n\n    if (this.graphTools && this.graphTools.length > 0) {\n      allTools.push(...this.graphTools);\n    }\n\n    if (this.tools && this.tools.length > 0) {\n      allTools.push(...this.tools);\n    }\n\n    return allTools;\n  }\n\n  /** Filters tool instances for binding based on registry config */\n  private filterToolsForBinding(tools: t.GraphTools): t.GraphTools {\n    return tools.filter((tool) => {\n      if (!('name' in tool)) {\n        return true;\n      }\n\n      const toolDef = this.toolRegistry?.get(tool.name);\n      if (!toolDef) {\n        return true;\n      }\n\n      if (this.discoveredToolNames.has(tool.name)) {\n        const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n        return allowedCallers.includes('direct');\n      }\n\n      const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n      return (\n        allowedCallers.includes('direct') && toolDef.defer_loading !== true\n      );\n    });\n  }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;AACA;AAeA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;QAE3C,MAAM,EACJ,OAAO,EACP,IAAI,EACJ,WAAW,EACX,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAAE,qBAAqB,EAEvC,iBAAiB,EAAE,qBAAqB,EACxC,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,YAAY,EACZ,mBAAmB,EACnB,sBAAsB,GACvB,GAAG,WAAW;;;AAIf,QAAA,IAAI,gBAAsD;QAC1D,IAAI,qBAAqB,EAAE;YACzB,gBAAgB,GAAG,qBAAqB;QAC1C;AAAO,aAAA,IACL,qBAAqB,EAAE,OAAO,KAAK,IAAI;AACvC,YAAA,qBAAqB,CAAC,MAAM,IAAI,IAAI,EACpC;;AAEA,YAAA,gBAAgB,GAAG;gBACjB,MAAM,EAAE,qBAAqB,CAAC,MAAM;gBACpC,IAAI,EAAE,qBAAqB,CAAC,IAAI;gBAChC,WAAW,EAAE,qBAAqB,CAAC,WAAW;gBAC9C,IAAI,EAAE,qBAAqB,CAAC,IAAI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