{"version":3,"file":"graph.cjs","sources":["../../../src/types/graph.ts"],"sourcesContent":["// src/types/graph.ts\nimport type {\n  START,\n  StateType,\n  UpdateType,\n  StateGraph,\n  StateGraphArgs,\n  StateDefinition,\n  CompiledStateGraph,\n  BinaryOperatorAggregate,\n} from '@langchain/langgraph';\nimport type { BindToolsInput } from '@langchain/core/language_models/chat_models';\nimport type {\n  BaseMessage,\n  AIMessageChunk,\n  SystemMessage,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { GoogleAIToolType } from '@langchain/google-common';\nimport type {\n  ToolMap,\n  ToolEndEvent,\n  GenericTool,\n  LCTool,\n  ToolApprovalConfig,\n  ToolExecuteBatchRequest,\n} from '@/types/tools';\nimport type { Providers, Callback, GraphNodeKeys } from '@/common';\nimport type { StandardGraph, MultiAgentGraph } from '@/graphs';\nimport type { ClientOptions } from '@/types/llm';\nimport type {\n  RunStep,\n  RunStepDeltaEvent,\n  MessageDeltaEvent,\n  ReasoningDeltaEvent,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\n\n/** Interface for bound model with stream and invoke methods */\nexport interface ChatModel {\n  stream?: (\n    messages: BaseMessage[],\n    config?: RunnableConfig\n  ) => Promise<AsyncIterable<AIMessageChunk>>;\n  invoke: (\n    messages: BaseMessage[],\n    config?: RunnableConfig\n  ) => Promise<AIMessageChunk>;\n}\n\n/** Payload for ON_AGENT_TRANSITION events */\nexport type AgentTransitionEvent = {\n  sourceAgentId?: string;\n  sourceAgentName?: string;\n  destinationAgentId: string;\n  destinationAgentName: string;\n  edgeType: string; // 'handoff' | 'transfer' | 'sequence'\n  timestamp: number;\n  /** When true, this event signals handoff completion (child → parent return) */\n  isCompletion?: boolean;\n  /** Duration of child agent execution in milliseconds (only on completion events) */\n  durationMs?: number;\n  /** Length of child agent result text in characters (only on completion events) */\n  resultLength?: number;\n};\n\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (\n  graph: StandardGraph,\n  ...args: T\n) => void;\n\nexport type ClientCallbacks = {\n  [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n  [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n  [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n};\n\nexport type SystemCallbacks = {\n  [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<\n    infer Args\n  >\n    ? (...args: Args) => void\n    : never;\n};\n\nexport type BaseGraphState = {\n  messages: BaseMessage[];\n  /**\n   * Structured response when using structured output mode.\n   * Contains the validated JSON response conforming to the configured schema.\n   */\n  structuredResponse?: Record<string, unknown>;\n};\n\nexport type MultiAgentGraphState = BaseGraphState & {\n  agentMessages?: BaseMessage[];\n};\n\nexport type IState = BaseGraphState;\n\nexport interface EventHandler {\n  handle(\n    event: string,\n    data:\n      | StreamEventData\n      | ModelEndData\n      | RunStep\n      | RunStepDeltaEvent\n      | MessageDeltaEvent\n      | ReasoningDeltaEvent\n      | SubagentUpdateEvent\n      | ToolExecuteBatchRequest\n      | { result: ToolEndEvent },\n    metadata?: Record<string, unknown>,\n    graph?: StandardGraph | MultiAgentGraph\n  ): void | Promise<void>;\n}\n\nexport type GraphStateChannels<T extends BaseGraphState> =\n  StateGraphArgs<T>['channels'];\n\nexport type Workflow<\n  T extends BaseGraphState = BaseGraphState,\n  U extends Partial<T> = Partial<T>,\n  N extends string = string,\n> = StateGraph<T, U, N>;\n\nexport type CompiledWorkflow<\n  T extends BaseGraphState = BaseGraphState,\n  U extends Partial<T> = Partial<T>,\n  N extends string = string,\n> = CompiledStateGraph<T, U, N>;\n\nexport type CompiledStateWorkflow = CompiledStateGraph<\n  StateType<{\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  }>,\n  UpdateType<{\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  }>,\n  string,\n  {\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  },\n  {\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  },\n  StateDefinition\n>;\n\nexport type CompiledMultiAgentWorkflow = CompiledStateGraph<\n  StateType<{\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n    agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  }>,\n  UpdateType<{\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n    agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  }>,\n  string,\n  {\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n    agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  },\n  {\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n    agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  },\n  StateDefinition\n>;\n\nexport type CompiledAgentWorfklow = CompiledStateGraph<\n  {\n    messages: BaseMessage[];\n  },\n  {\n    messages?: BaseMessage[] | undefined;\n  },\n  '__start__' | `agent=${string}` | `tools=${string}`,\n  {\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  },\n  {\n    messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n  },\n  StateDefinition,\n  {\n    [x: `agent=${string}`]: Partial<BaseGraphState>;\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    [x: `tools=${string}`]: any;\n  }\n>;\n\nexport type SystemRunnable =\n  | Runnable<\n      BaseMessage[],\n      (BaseMessage | SystemMessage)[],\n      RunnableConfig<Record<string, unknown>>\n    >\n  | undefined;\n\n/**\n * Optional compile options passed to workflow.compile().\n * These are intentionally untyped to avoid coupling to library internals.\n */\nexport type CompileOptions = {\n  // A checkpointer instance (e.g., MemorySaver, SQL saver)\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  checkpointer?: any;\n  interruptBefore?: string[];\n  interruptAfter?: string[];\n  /**\n   * Human-in-the-loop tool approval configuration.\n   * When set, tools matching the policy will trigger an interrupt()\n   * before execution, pausing the graph for human approval.\n   * Requires a checkpointer to be set for interrupt/resume to work.\n   */\n  toolApprovalConfig?: ToolApprovalConfig;\n};\n\nexport type EventStreamCallbackHandlerInput =\n  Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<\n    infer T,\n    'autoClose'\n  >\n    ? T\n    : never;\n\nexport type StreamChunk =\n  | (ChatGenerationChunk & {\n      message: AIMessageChunk;\n    })\n  | AIMessageChunk;\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n  /**\n   * The input passed to the runnable that generated the event.\n   * Inputs will sometimes be available at the *START* of the runnable, and\n   * sometimes at the *END* of the runnable.\n   * If a runnable is able to stream its inputs, then its input by definition\n   * won't be known until the *END* of the runnable when it has finished streaming\n   * its inputs.\n   */\n  input?: unknown;\n  /**\n   * The output of the runnable that generated the event.\n   * Outputs will only be available at the *END* of the runnable.\n   * For most runnables, this field can be inferred from the `chunk` field,\n   * though there might be some exceptions for special cased runnables (e.g., like\n   * chat models), which may return more information.\n   */\n  output?: unknown;\n  /**\n   * A streaming chunk from the output that generated the event.\n   * chunks support addition in general, and adding them up should result\n   * in the output of the runnable that generated the event.\n   */\n  chunk?: StreamChunk;\n  /**\n   * Runnable config for invoking other runnables within handlers.\n   */\n  config?: RunnableConfig;\n  /**\n   * Custom result from the runnable that generated the event.\n   */\n  result?: unknown;\n  /**\n   * Custom field to indicate the event was manually emitted, and may have been handled already\n   */\n  emitted?: boolean;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n  /**\n   * Event names are of the format: on_[runnable_type]_(start|stream|end).\n   *\n   * Runnable types are one of:\n   * - llm - used by non chat models\n   * - chat_model - used by chat models\n   * - prompt --  e.g., ChatPromptTemplate\n   * - tool -- LangChain tools\n   * - chain - most Runnables are of this type\n   *\n   * Further, the events are categorized as one of:\n   * - start - when the runnable starts\n   * - stream - when the runnable is streaming\n   * - end - when the runnable ends\n   *\n   * start, stream and end are associated with slightly different `data` payload.\n   *\n   * Please see the documentation for `EventData` for more details.\n   */\n  event: string;\n  /** The name of the runnable that generated the event. */\n  name: string;\n  /**\n   * An randomly generated ID to keep track of the execution of the given runnable.\n   *\n   * Each child runnable that gets invoked as part of the execution of a parent runnable\n   * is assigned its own unique ID.\n   */\n  run_id: string;\n  /**\n   * Tags associated with the runnable that generated this event.\n   * Tags are always inherited from parent runnables.\n   */\n  tags?: string[];\n  /** Metadata associated with the runnable that generated this event. */\n  metadata: Record<string, unknown>;\n  /**\n   * Event data.\n   *\n   * The contents of the event data depend on the event type.\n   */\n  data: StreamEventData;\n};\n\nexport type GraphConfig = {\n  provider: string;\n  thread_id?: string;\n  run_id?: string;\n};\n\nexport type PartMetadata = {\n  progress?: number;\n  asset_pointer?: string;\n  status?: string;\n  action?: boolean;\n  output?: string;\n};\n\nexport type ModelEndData =\n  | (StreamEventData & { output: AIMessageChunk | undefined })\n  | undefined;\nexport type GraphTools = GenericTool[] | BindToolsInput[] | GoogleAIToolType[];\nexport type StandardGraphInput = {\n  runId?: string;\n  signal?: AbortSignal;\n  agents: AgentInputs[];\n  tokenCounter?: TokenCounter;\n  indexTokenCountMap?: Record<string, number>;\n};\n\n/**\n * Configuration for an approval gate placed on a sequence edge.\n * When present, the graph inserts an approval gate node between the source\n * and destination agents. The gate ALWAYS fires (regardless of ExecutionContext)\n * and calls interrupt() to pause the graph for human approval.\n */\nexport type ApprovalGateConfig = {\n  /** Unique identifier for this gate (used as node ID suffix) */\n  gateId: string;\n  /**\n   * Approval channel — where the approval UI is rendered.\n   * - 'chat': SSE-based chat UI (default)\n   * - 'outlook': MS Graph Actionable Messages\n   * - 'telegram': Telegram Bot inline keyboard\n   */\n  channel?: 'chat' | 'outlook' | 'telegram';\n  /** Optional human-readable prompt shown to the approver */\n  prompt?: string;\n  /** Optional approver identifier (e.g., email, user ID) */\n  approver?: string;\n  /** Timeout in ms before the gate auto-expires (default: 5 minutes) */\n  timeoutMs?: number;\n  /** What to do on denial: 'stop' ends the graph, 'skip' skips the destination agent */\n  onDeny?: 'stop' | 'skip';\n};\n\nexport type GraphEdge = {\n  /** Agent ID, use a list for multiple sources */\n  from: string | string[];\n  /** Agent ID, use a list for multiple destinations */\n  to: string | string[];\n  description?: string;\n  /** Can return boolean or specific destination(s) */\n  condition?: (state: BaseGraphState) => boolean | string | string[];\n  /**\n   * EdgeType.HANDOFF — one-way routing: parent emits an `lc_transfer_to_*`\n   *   tool call and exits, child takes over and responds directly to the\n   *   user. Aligns with upstream's handoff semantics.\n   * EdgeType.DIRECT — fixed graph edges for automatic sequential / parallel\n   *   transitions. Ranger preserves its enriched wiring (fan-in with prompt,\n   *   parallel groups, ApprovalGateNode, excludeResults / agentMessages).\n   */\n  edgeType?: import('@/common').EdgeType;\n  /**\n   * For sequence edges: Optional prompt to add when transitioning through this edge.\n   * String prompts can include variables like {results} which will be replaced with\n   * messages from startIndex onwards. When {results} is used, excludeResults defaults to true.\n   *\n   * For transfer edges: Description for the input parameter that the transfer tool accepts,\n   * allowing the supervisor to pass specific instructions/context to the transferred agent.\n   */\n  prompt?:\n    | string\n    | ((\n        messages: BaseMessage[],\n        runStartIndex: number\n      ) => string | Promise<string> | undefined);\n  /**\n   * When true, excludes messages from startIndex when adding prompt.\n   * Automatically set to true when {results} variable is used in prompt.\n   */\n  excludeResults?: boolean;\n  /**\n   * For transfer edges: Customizes the parameter name for the transfer input.\n   * Defaults to \"instructions\" if not specified.\n   * Only applies when prompt is provided for transfer edges.\n   *\n   * For handoff edges: Customizes the parameter name for the handoff instruction input.\n   */\n  promptKey?: string;\n  /**\n   * Approval gate configuration for sequence edges.\n   * When set, inserts an approval gate node between source and destination.\n   * The gate ALWAYS fires regardless of ExecutionContext (unlike tool approval).\n   */\n  approvalGate?: ApprovalGateConfig;\n};\n\nexport type MultiAgentGraphInput = StandardGraphInput & {\n  edges: GraphEdge[];\n  /**\n   * When set, the graph routes START to this agent instead of the default\n   * starting nodes. Used for multi-turn resumption: the caller reads the\n   * last active agent id from the previous turn (e.g. via\n   * `Run.getLastActiveAgentId()`, which derives it from the run's content\n   * data trail) and passes it here so follow-up messages route to the\n   * agent that last handled the conversation.\n   *\n   * If the agent ID is invalid (not in the graph), falls back to default\n   * starting nodes.\n   */\n  resumeFromAgentId?: string;\n};\n\n/**\n * Structured output mode determines how the agent returns structured data.\n * - 'tool': Uses tool calling to return structured output (works with all tool-calling models)\n * - 'provider': Uses provider-native structured output via LangChain's jsonMode (OpenAI, Anthropic, etc.)\n * - 'native': Uses provider's constrained decoding API directly for guaranteed schema compliance\n *   (Anthropic output_config.format, OpenAI response_format.json_schema). Falls back to 'tool' for unsupported providers.\n * - 'auto': Automatically selects the best strategy — 'native' for supported providers, 'tool' for others\n */\nexport type StructuredOutputMode = 'tool' | 'provider' | 'native' | 'auto';\n\n/**\n * Resolved method used internally after mode resolution.\n * Maps to LangChain's withStructuredOutput method parameter plus our native path.\n */\nexport type ResolvedStructuredOutputMethod =\n  | 'functionCalling'\n  | 'jsonMode'\n  | 'jsonSchema'\n  | 'native'\n  | undefined;\n\n/**\n * Error thrown when the model refuses to produce structured output due to safety policies.\n */\nexport class StructuredOutputRefusalError extends Error {\n  constructor(public refusalText: string) {\n    super(`Model refused to produce structured output: ${refusalText}`);\n    this.name = 'StructuredOutputRefusalError';\n  }\n}\n\n/**\n * Error thrown when the structured output response was truncated due to max_tokens.\n */\nexport class StructuredOutputTruncatedError extends Error {\n  constructor(public stopReason: string) {\n    super(\n      `Structured output was truncated (stop_reason: ${stopReason}). ` +\n        'Increase max_tokens to allow the full JSON response to be generated.'\n    );\n    this.name = 'StructuredOutputTruncatedError';\n  }\n}\n\n/**\n * Configuration for structured JSON output from agents.\n * When configured, the agent will return a validated JSON response\n * instead of streaming text.\n */\nexport interface StructuredOutputConfig {\n  /**\n   * JSON Schema defining the output structure.\n   * The model will be forced to return data conforming to this schema.\n   */\n  schema: Record<string, unknown>;\n  /**\n   * Name for the structured output format (used in tool mode).\n   * @default 'StructuredResponse'\n   */\n  name?: string;\n  /**\n   * Description of what the structured output represents.\n   * Helps the model understand the expected format.\n   */\n  description?: string;\n  /**\n   * Output mode strategy.\n   * @default 'auto'\n   */\n  mode?: StructuredOutputMode;\n  /**\n   * Enable strict schema validation.\n   * When true, the response must exactly match the schema.\n   * @default true\n   */\n  strict?: boolean;\n  /**\n   * Error handling configuration.\n   * - true: Auto-retry on validation errors (default)\n   * - false: Throw error on validation failure\n   * - string: Custom error message for retry\n   */\n  handleErrors?: boolean | string;\n  /**\n   * Maximum number of retry attempts on validation failure.\n   * @default 2\n   */\n  maxRetries?: number;\n  /**\n   * Include the raw AI message along with structured response.\n   * Useful for debugging.\n   * @default false\n   */\n  includeRaw?: boolean;\n}\n\n/**\n * Database/API structured output format (snake_case with enabled flag).\n * This matches the format stored in MongoDB and sent from frontends.\n */\nexport interface StructuredOutputInput {\n  /** Whether structured output is enabled */\n  enabled?: boolean;\n  /** JSON Schema defining the expected response structure */\n  schema?: Record<string, unknown>;\n  /** Name identifier for the structured output */\n  name?: string;\n  /** Description of what the structured output represents */\n  description?: string;\n  /** Mode for structured output: 'tool' | 'provider' | 'native' | 'auto' */\n  mode?: StructuredOutputMode;\n  /** Whether to enforce strict schema validation */\n  strict?: boolean;\n}\n\n/**\n * Trigger strategy for when summarization should activate.\n * - 'contextPercentage': Trigger when context utilization exceeds a threshold percentage\n * - 'messageCount': Trigger when pruned message count exceeds a threshold\n * - 'tokenThreshold': Trigger when total token count exceeds a raw threshold\n */\nexport type SummarizationTriggerType =\n  | 'contextPercentage'\n  | 'messageCount'\n  | 'tokenThreshold';\n\n/**\n * Configuration for summarization behavior within the agent pipeline.\n * All fields are optional — sensible defaults are provided via constants.\n *\n * @see SUMMARIZATION_CONTEXT_THRESHOLD, SUMMARIZATION_RESERVE_RATIO, PRUNING_EMA_ALPHA\n */\nexport interface SummarizationConfig {\n  /**\n   * Strategy for when summarization triggers.\n   * @default 'contextPercentage'\n   */\n  triggerType?: SummarizationTriggerType;\n\n  /**\n   * Threshold value interpreted based on triggerType:\n   * - contextPercentage: 0-100 (percentage of context window)\n   * - messageCount: absolute count of messages pruned\n   * - tokenThreshold: absolute token count\n   * @default 80 (for contextPercentage)\n   */\n  triggerThreshold?: number;\n\n  /**\n   * Fraction of context window (0-1) reserved for recent messages.\n   * Prevents over-pruning by ensuring at least this fraction of the\n   * context budget is preserved as recent conversation history.\n   * @default 0.3\n   */\n  reserveRatio?: number;\n\n  /**\n   * Whether context pruning is enabled (can be disabled for debugging).\n   * @default true\n   */\n  contextPruning?: boolean;\n\n  /**\n   * Initial summary text to seed across runs.\n   * Different from persistedSummary: this is provided by the caller as a\n   * cross-conversation seed (e.g., agent personality or recurring context),\n   * while persistedSummary is loaded from the conversation's own history.\n   */\n  initialSummary?: string;\n\n  /**\n   * Upstream-aligned optional fields. When the host wants the summarization\n   * pass to run on a different LLM than the agent's own (e.g. a cheaper\n   * model for compaction), these provider/model overrides flow through to\n   * the summarize callback.\n   */\n  provider?: Providers;\n  model?: string;\n  parameters?: Record<string, unknown>;\n  prompt?: string;\n  updatePrompt?: string;\n  trigger?: { type: string; value: number };\n  maxSummaryTokens?: number;\n}\n\n/**\n * Runtime state for EMA-based pruning calibration.\n * Maintained across iterations within a single run to smooth pruning decisions.\n */\nexport interface PruneCalibrationState {\n  /** Current EMA calibration ratio */\n  ratio: number;\n  /** Number of calibration updates applied */\n  iterations: number;\n}\n\n/**\n * Lightweight file metadata entry for conversation-level file awareness.\n * Contains only IDs and names — NOT full content — so the agent always knows\n * what files exist in the conversation even after compaction pushes old messages\n * behind the summary window. The agent can retrieve full content on-demand\n * via file_search (RAG) or content_tool read (by contentId).\n */\nexport interface FileManifestEntry {\n  /** Unique file identifier (e.g., MongoDB ObjectId or UUID) */\n  fileId: string;\n  /** Original filename (e.g., \"quarterly-report.pdf\") */\n  filename: string;\n  /** Content identifier for on-demand retrieval via content_tool read */\n  contentId?: string;\n  /** File source (e.g., \"local\", \"sharepoint\", \"onedrive\") */\n  source?: string;\n  /** Index of the message that introduced this file (0-based in the original message array) */\n  messageIndex?: number;\n}\n\n/** Configuration for a subagent type that can be spawned by a parent agent. */\nexport type SubagentConfig = {\n  /** Identifier used in the tool's `subagent_type` enum (e.g. 'researcher', 'coder'). */\n  type: string;\n  /** Human-readable display name. */\n  name: string;\n  /** What this subagent specializes in — shown to the LLM. */\n  description: string;\n  /** Full agent config for the child graph. Omit when `self` is true. */\n  agentInputs?: AgentInputs;\n  /** When true, reuse the parent's AgentInputs (context isolation without separate config). */\n  self?: boolean;\n  /** Max AGENT→TOOLS cycles before forced stop (default: 25). */\n  maxTurns?: number;\n  /** Allow this subagent to spawn its own subagents (default: false). */\n  allowNested?: boolean;\n};\n\n/** SubagentConfig with agentInputs guaranteed present (self-spawn resolved). */\nexport type ResolvedSubagentConfig = SubagentConfig & {\n  agentInputs: AgentInputs;\n};\n\n/** Lifecycle phase carried on {@link SubagentUpdateEvent}. */\nexport type SubagentUpdatePhase =\n  | 'start'\n  | 'run_step'\n  | 'run_step_delta'\n  | 'run_step_completed'\n  | 'message_delta'\n  | 'reasoning_delta'\n  | 'stop'\n  | 'error';\n\n/**\n * Wrapper event emitted when a subagent's child graph dispatches activity.\n * Lets hosts show subagent progress in a UI surface separate from the parent\n * conversation without having to untangle events by agent ID.\n */\nexport interface SubagentUpdateEvent {\n  /** Parent run ID. */\n  runId: string;\n  /** Child run ID (unique per subagent execution). */\n  subagentRunId: string;\n  /**\n   * Parent-side `tool_call_id` for the `subagent` tool invocation that\n   * triggered this run. Stable for the duration of the child; lets hosts\n   * correlate updates deterministically instead of inferring by ordering.\n   * Omitted when the executor was invoked outside of a tool-call context.\n   */\n  parentToolCallId?: string;\n  /** Subagent `type` identifier from the SubagentConfig. */\n  subagentType: string;\n  /** Child agent ID assigned to this subagent execution. */\n  subagentAgentId: string;\n  /** Parent agent ID that spawned this subagent. */\n  parentAgentId?: string;\n  /** Lifecycle phase carried by this update. */\n  phase: SubagentUpdatePhase;\n  /** Underlying event payload (shape depends on phase). */\n  data?: unknown;\n  /** Short human-readable description. Hosts can render this directly. */\n  label?: string;\n  /** ISO timestamp for ordering / display. */\n  timestamp: string;\n}\n\nexport interface AgentInputs {\n  agentId: string;\n  /** Human-readable name for the agent (used in handoff context). Defaults 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  toolEnd?: boolean;\n  toolMap?: ToolMap;\n  tools?: GraphTools;\n  provider: Providers;\n  instructions?: string;\n  streamBuffer?: number;\n  maxContextTokens?: number;\n  clientOptions?: ClientOptions;\n  additional_instructions?: string;\n  reasoningKey?: 'reasoning_content' | 'reasoning';\n  /**\n   * Subagent types this agent may spawn. When non-empty, Graph injects the\n   * `subagent` tool into the agent's toolset with the per-config enum and\n   * description populated.\n   */\n  subagentConfigs?: SubagentConfig[];\n  /**\n   * Maximum subagent depth allowed below this agent. Used by SubagentExecutor\n   * to abort runaway nesting. Defaults to a small constant.\n   */\n  maxSubagentDepth?: number;\n  /**\n   * Pre-existing summary injected into the system message via\n   * AgentContext.buildInstructionsString. Populated by SubagentExecutor when\n   * spawning a self-config subagent that should inherit the parent's prior\n   * compaction summary; otherwise host-supplied at run time.\n   */\n  initialSummary?: { text: string; tokenCount: number };\n  /**\n   * Upstream-aligned opt-in for summarization. When false, the agent never\n   * invokes the summarize callback regardless of context utilization.\n   * Defaults to undefined (treated as enabled in Ranger to preserve prior\n   * behaviour); hosts that want strict opt-in semantics should set it\n   * explicitly.\n   */\n  summarizationEnabled?: boolean;\n  /** Format content blocks as strings (for legacy compatibility i.e. Ollama/Azure Serverless) */\n  useLegacyContent?: boolean;\n  /**\n   * Tool definitions for all tools, including deferred and programmatic.\n   * Used for tool search and programmatic tool calling.\n   * Maps tool name to LCTool definition.\n   */\n  toolRegistry?: Map<string, LCTool>;\n  /**\n   * Dynamic context that changes per-request (e.g., current time, user info).\n   * This is injected as a user message rather than system prompt to preserve cache.\n   * Keeping this separate from instructions ensures the system message stays static\n   * and can be cached by Bedrock/Anthropic prompt caching.\n   */\n  dynamicContext?: string;\n  /**\n   * Structured output configuration (camelCase).\n   * When set, disables streaming and returns a validated JSON response\n   * conforming to the specified schema.\n   */\n  structuredOutput?: StructuredOutputConfig;\n  /**\n   * Structured output configuration (snake_case - database/API format).\n   * Alternative to structuredOutput for compatibility with MongoDB/frontend.\n   * Uses an `enabled` flag to control activation.\n   * @deprecated Use structuredOutput instead when possible\n   */\n  structured_output?: StructuredOutputInput;\n  /**\n   * Serializable tool definitions for event-driven execution.\n   * When provided, ToolNode operates in event-driven mode, dispatching\n   * ON_TOOL_EXECUTE events instead of invoking tools directly.\n   */\n  toolDefinitions?: LCTool[];\n  /**\n   * Tool names discovered from previous conversation history.\n   * These tools will be pre-marked as discovered so they're included\n   * in tool binding without requiring tool_search.\n   */\n  discoveredTools?: string[];\n  /**\n   * Optional callback for summarizing messages that were pruned from context.\n   * When provided, discarded messages are summarized by the host caller\n   * using a cheap LLM call, and the summary is prepended to the context.\n   */\n  summarizeCallback?: (\n    messagesToRefine: import('@langchain/core/messages').BaseMessage[]\n  ) => Promise<string | undefined>;\n  /**\n   * Pre-existing summary text loaded from persistent storage (MongoDB/Redis).\n   * When provided, this summary is injected into the initial message context\n   * so the agent has prior conversation history even on new turns.\n   * Set by the host's summary store when resuming a conversation.\n   */\n  persistedSummary?: string;\n  /**\n   * Summarization configuration controlling trigger strategy, reserve ratio,\n   * and EMA calibration for pruning. When omitted, sensible defaults apply.\n   * @see SummarizationConfig\n   */\n  summarizationConfig?: SummarizationConfig;\n  /**\n   * Workspace-shared system-message tiers. Each entry becomes a separate\n   * text block in the SystemMessage with its own cachePoint / cache_control\n   * marker, allowing the platform-tier bytes (e.g. shared branding, tool\n   * routing rules, code-executor instructions) to be hashed independently\n   * from the per-agent `instructions` block. Hosts that don't use tiered\n   * caching can leave this undefined; behavior falls back to the legacy\n   * single SystemMessage.\n   *\n   * Anthropic / Bedrock prompt-cache lookups are forward-prefix-hash, so\n   * blocks are emitted in array order BEFORE `instructions`. Up to 4 blocks\n   * are supported (the LLM cap on cache breakpoints).\n   */\n  system_cache_blocks?: Array<{ text: string; ttl?: '5m' | '1h' }>;\n  /**\n   * TTL hint for the per-agent `instructions` block's cache marker.\n   * Defaults to '5m' (matching addCacheControl message-level behavior).\n   * Only consulted when `system_cache_blocks` is set; otherwise the\n   * legacy SystemMessage path is unchanged.\n   */\n  instructions_cache_ttl?: '5m' | '1h';\n  /**\n   * Lightweight file manifest for the conversation.\n   * Contains file IDs, names, and metadata — NOT full content.\n   *\n   * Used by the compaction engine to inject a [Conversation Files] block\n   * into the windowed view, ensuring the LLM always knows what files exist\n   * even when old messages (with full file content) are behind the summary.\n   *\n   * The agent can retrieve full content on-demand via:\n   *   - file_search (RAG semantic search over embedded files)\n   *   - content_tool read (by contentId for exact file retrieval)\n   *\n   * Built by the host orchestrator from message_file_map\n   * and metadata.context_files across all conversation messages.\n   */\n  fileManifest?: FileManifestEntry[];\n}\n\n/**\n * Tunable knobs for position-based content degradation.\n * See `messages/contextPruning.ts` and `messages/contextPruningSettings.ts`.\n */\nexport interface ContextPruningConfig {\n  enabled?: boolean;\n  keepLastAssistants?: number;\n  softTrimRatio?: number;\n  hardClearRatio?: number;\n  minPrunableToolChars?: number;\n  softTrim?: {\n    maxChars?: number;\n    headChars?: number;\n    tailChars?: number;\n  };\n  hardClear?: {\n    enabled?: boolean;\n    placeholder?: string;\n  };\n}\n"],"names":[],"mappings":";;AAodA;;AAEG;AACG,MAAO,4BAA6B,SAAQ,KAAK,CAAA;AAClC,IAAA,WAAA;AAAnB,IAAA,WAAA,CAAmB,WAAmB,EAAA;AACpC,QAAA,KAAK,CAAC,CAAA,4CAAA,EAA+C,WAAW,CAAA,CAAE,CAAC;QADlD,IAAA,CAAA,WAAW,GAAX,WAAW;AAE5B,QAAA,IAAI,CAAC,IAAI,GAAG,8BAA8B;IAC5C;AACD;AAED;;AAEG;AACG,MAAO,8BAA+B,SAAQ,KAAK,CAAA;AACpC,IAAA,UAAA;AAAnB,IAAA,WAAA,CAAmB,UAAkB,EAAA;QACnC,KAAK,CACH,CAAA,8CAAA,EAAiD,UAAU,CAAA,GAAA,CAAK;AAC9D,YAAA,sEAAsE,CACzE;QAJgB,IAAA,CAAA,UAAU,GAAV,UAAU;AAK3B,QAAA,IAAI,CAAC,IAAI,GAAG,gCAAgC;IAC9C;AACD;;;;;"}