@librechat/agents 3.2.60 → 3.2.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +32 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
- package/dist/cjs/hooks/executeHooks.cjs +6 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
- package/dist/cjs/hooks/index.cjs +12 -0
- package/dist/cjs/hooks/index.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs.map +1 -1
- package/dist/cjs/langfuse.cjs +62 -1
- package/dist/cjs/langfuse.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +266 -43
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +274 -7
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/streamMetadata.cjs +69 -0
- package/dist/cjs/llm/openai/streamMetadata.cjs.map +1 -0
- package/dist/cjs/llm/openrouter/index.cjs +5 -6
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +6 -1
- package/dist/cjs/messages/format.cjs +61 -0
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +31 -19
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/stream.cjs +13 -3
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +75 -10
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/utils/tokens.cjs +111 -0
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +32 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
- package/dist/esm/hooks/executeHooks.mjs +6 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -1
- package/dist/esm/hooks/index.mjs +12 -1
- package/dist/esm/hooks/index.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs.map +1 -1
- package/dist/esm/langfuse.mjs +62 -1
- package/dist/esm/langfuse.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +266 -43
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +274 -7
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/streamMetadata.mjs +69 -0
- package/dist/esm/llm/openai/streamMetadata.mjs.map +1 -0
- package/dist/esm/llm/openrouter/index.mjs +5 -6
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -3
- package/dist/esm/messages/format.mjs +61 -0
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +31 -19
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/stream.mjs +13 -3
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +75 -10
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/utils/tokens.mjs +108 -1
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +3 -1
- package/dist/types/hooks/HookRegistry.d.ts +10 -0
- package/dist/types/hooks/index.d.ts +7 -0
- package/dist/types/hooks/types.d.ts +18 -1
- package/dist/types/llm/bedrock/index.d.ts +5 -0
- package/dist/types/llm/openai/index.d.ts +19 -0
- package/dist/types/llm/openai/streamMetadata.d.ts +16 -0
- package/dist/types/messages/prune.d.ts +4 -3
- package/dist/types/tools/ToolNode.d.ts +1 -0
- package/dist/types/types/llm.d.ts +12 -2
- package/dist/types/types/tools.d.ts +1 -1
- package/dist/types/utils/tokens.d.ts +30 -0
- package/package.json +9 -9
- package/src/__tests__/stream.eagerEventExecution.test.ts +100 -2
- package/src/common/enum.ts +2 -0
- package/src/hooks/HookRegistry.ts +45 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +48 -0
- package/src/hooks/__tests__/executeHooks.test.ts +85 -2
- package/src/hooks/executeHooks.ts +15 -0
- package/src/hooks/index.ts +7 -0
- package/src/hooks/types.ts +18 -1
- package/src/langfuse.ts +134 -1
- package/src/llm/bedrock/index.ts +434 -83
- package/src/llm/bedrock/streamSealDispatch.test.ts +97 -0
- package/src/llm/custom-chat-models.smoke.test.ts +7 -0
- package/src/llm/openai/index.ts +604 -6
- package/src/llm/openai/managedRequests.test.ts +182 -0
- package/src/llm/openai/streamMetadata.spec.ts +86 -0
- package/src/llm/openai/streamMetadata.ts +95 -0
- package/src/llm/openai/streamMetadataDedup.spec.ts +166 -0
- package/src/llm/openrouter/index.ts +9 -5
- package/src/messages/format.ts +96 -3
- package/src/messages/formatAgentMessages.steer.test.ts +326 -0
- package/src/messages/labelContentByAgent.test.ts +75 -0
- package/src/messages/prune.ts +56 -30
- package/src/specs/anthropic.simple.test.ts +4 -2
- package/src/specs/cache.simple.test.ts +17 -4
- package/src/specs/langfuse-callbacks.test.ts +61 -0
- package/src/specs/openai.simple.test.ts +4 -2
- package/src/specs/spec.utils.ts +12 -0
- package/src/specs/summarization.test.ts +9 -13
- package/src/specs/token-accounting-pipeline.test.ts +130 -4
- package/src/specs/tokens.test.ts +214 -0
- package/src/stream.ts +22 -3
- package/src/tools/ToolNode.ts +107 -12
- package/src/tools/__tests__/ToolNode.eagerEventExecution.test.ts +554 -0
- package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +49 -2
- package/src/tools/__tests__/hitl.test.ts +112 -0
- package/src/tools/subagent/SubagentExecutor.ts +2 -0
- package/src/types/llm.ts +12 -2
- package/src/types/tools.ts +1 -1
- package/src/utils/tokens.ts +181 -3
package/dist/cjs/common/enum.cjs
CHANGED
|
@@ -122,6 +122,8 @@ let ContentTypes = /* @__PURE__ */ function(ContentTypes) {
|
|
|
122
122
|
ContentTypes["SUMMARY"] = "summary";
|
|
123
123
|
/** Bedrock */
|
|
124
124
|
ContentTypes["REASONING_CONTENT"] = "reasoning_content";
|
|
125
|
+
/** Mid-run user steer persisted inline in an assistant message; replayed as a user turn */
|
|
126
|
+
ContentTypes["STEER"] = "steer";
|
|
125
127
|
return ContentTypes;
|
|
126
128
|
}({});
|
|
127
129
|
let ToolCallTypes = /* @__PURE__ */ function(ToolCallTypes) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.cjs","names":[],"sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n /** [Custom] Request to execute tools - dispatched by ToolNode, handled by host */\n ON_TOOL_EXECUTE = 'on_tool_execute',\n /** [Custom] Emitted when the summarize node begins generating a summary */\n ON_SUMMARIZE_START = 'on_summarize_start',\n /** [Custom] Delta event carrying the completed summary content */\n ON_SUMMARIZE_DELTA = 'on_summarize_delta',\n /** [Custom] Emitted when the summarize node completes with the final summary */\n ON_SUMMARIZE_COMPLETE = 'on_summarize_complete',\n /** [Custom] Progress update from a running subagent (wraps child-graph events so hosts can display activity separately from parent). */\n ON_SUBAGENT_UPDATE = 'on_subagent_update',\n /** [Custom] Diagnostic logging event for context management observability */\n ON_AGENT_LOG = 'on_agent_log',\n /** [Custom] Per-model-call context window usage snapshot (post-prune token budget) */\n ON_CONTEXT_USAGE = 'on_context_usage',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n MOONSHOT = 'moonshot',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n SUMMARIZE = 'summarize=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Framework-level conversation summary block */\n SUMMARY = 'summary',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH = 'tool_search',\n PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',\n WEB_SEARCH = 'web_search',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n /** Delimiter for MCP tools: toolName_mcp_serverName */\n MCP_DELIMITER = '_mcp_',\n /** Anthropic server tool ID prefix (web_search, code_execution, etc.) */\n ANTHROPIC_SERVER_TOOL_PREFIX = 'srvtoolu_',\n SKILL_TOOL = 'skill',\n /**\n * Callback-metadata keys stamped by `attemptInvoke` /\n * `tryFallbackProviders` carrying the provider (SDK `Providers` enum\n * value) and configured model that actually served a model invocation.\n * Unlike `ls_provider` — which derived providers inherit from their base\n * class (e.g. DeepSeek/OpenRouter report `'openai'`) — these reflect the\n * SDK's own routing, including fallback-provider calls. Consumed by the\n * subagent usage-capture handler to tag billing events.\n */\n INVOKED_PROVIDER = '__invoked_provider',\n INVOKED_MODEL = '__invoked_model',\n READ_FILE = 'read_file',\n BASH_TOOL = 'bash_tool',\n BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',\n SUBAGENT = 'subagent',\n /**\n * Local-engine coding tool names. Promoted to `Constants.*` (rather\n * than left as per-file `*ToolName` consts) so consumer UIs — most\n * importantly LibreChat's `getToolIconType` map — can match against\n * canonical strings instead of guessing. Existing matched names:\n * `bash_tool`, `read_file`, `execute_code`, `run_tools_with_code`.\n * The rest below are new and currently fall through to the generic\n * tool icon; once LibreChat adds icons keyed on the same names, the\n * wiring will work without an SDK change.\n */\n WRITE_FILE = 'write_file',\n EDIT_FILE = 'edit_file',\n GREP_SEARCH = 'grep_search',\n GLOB_SEARCH = 'glob_search',\n LIST_DIRECTORY = 'list_directory',\n COMPILE_CHECK = 'compile_check',\n}\n\n/** Tool names that use the code execution environment (shared session, file tracking). */\nexport const CODE_EXECUTION_TOOLS: ReadonlySet<string> = new Set([\n Constants.EXECUTE_CODE,\n Constants.BASH_TOOL,\n Constants.PROGRAMMATIC_TOOL_CALLING,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n]);\n\n/**\n * Canonical names of the local-engine-specific coding tools — the\n * file/edit/search/typecheck surface that doesn't exist in the\n * remote (sandbox-API) engine. Single source of truth; the per-tool\n * factories, registry definitions, and `createWorkspacePolicyHook`\n * default extractors all key off these.\n *\n * `read_file` is on this list (the existing ReadFile tool is\n * remote-specific; the local engine's `read_file` is a parallel\n * implementation that shares the canonical name so consumer UIs\n * — most importantly LibreChat's `getToolIconType` — render both\n * with the same icon).\n */\nexport const LOCAL_CODING_TOOL_NAMES: readonly string[] = [\n Constants.READ_FILE,\n Constants.WRITE_FILE,\n Constants.EDIT_FILE,\n Constants.GREP_SEARCH,\n Constants.GLOB_SEARCH,\n Constants.LIST_DIRECTORY,\n Constants.COMPILE_CHECK,\n];\n\n/**\n * Every tool name the local coding bundle (`createLocalCodingTools`)\n * exposes — the local-specific tools above plus the bash/code/PTC\n * pair that the local engine wraps around the existing factories.\n * Tests pin against this so any addition/removal in the bundle is\n * accompanied by a deliberate canonical-name update here.\n */\nexport const LOCAL_CODING_BUNDLE_NAMES: readonly string[] = [\n ...LOCAL_CODING_TOOL_NAMES,\n Constants.BASH_TOOL,\n Constants.EXECUTE_CODE,\n Constants.PROGRAMMATIC_TOOL_CALLING,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n];\n\nexport enum TitleMethod {\n STRUCTURED = 'structured',\n FUNCTIONS = 'functions',\n COMPLETION = 'completion',\n}\n\nexport enum EnvVar {\n CODE_BASEURL = 'LIBRECHAT_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IAAI;;;;;AAKjE,CAAC;;;;;;;;;;;;;;AAeD,MAAa,0BAA6C;;;;;;;;AAQ1D;;;;;;;;AASA,MAAa,4BAA+C;CAC1D,GAAG;;;;;AAKL;AAEA,IAAY,cAAL,yBAAA,aAAA;CACL,YAAA,gBAAA;CACA,YAAA,eAAA;CACA,YAAA,gBAAA;;AACF,EAAA,CAAA,CAAA;AAEA,IAAY,SAAL,yBAAA,QAAA;CACL,OAAA,kBAAA;CACA,OAAA,6BAAA;;AACF,EAAA,CAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"enum.cjs","names":[],"sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n /** [Custom] Request to execute tools - dispatched by ToolNode, handled by host */\n ON_TOOL_EXECUTE = 'on_tool_execute',\n /** [Custom] Emitted when the summarize node begins generating a summary */\n ON_SUMMARIZE_START = 'on_summarize_start',\n /** [Custom] Delta event carrying the completed summary content */\n ON_SUMMARIZE_DELTA = 'on_summarize_delta',\n /** [Custom] Emitted when the summarize node completes with the final summary */\n ON_SUMMARIZE_COMPLETE = 'on_summarize_complete',\n /** [Custom] Progress update from a running subagent (wraps child-graph events so hosts can display activity separately from parent). */\n ON_SUBAGENT_UPDATE = 'on_subagent_update',\n /** [Custom] Diagnostic logging event for context management observability */\n ON_AGENT_LOG = 'on_agent_log',\n /** [Custom] Per-model-call context window usage snapshot (post-prune token budget) */\n ON_CONTEXT_USAGE = 'on_context_usage',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n MOONSHOT = 'moonshot',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n SUMMARIZE = 'summarize=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Framework-level conversation summary block */\n SUMMARY = 'summary',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n /** Mid-run user steer persisted inline in an assistant message; replayed as a user turn */\n STEER = 'steer',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH = 'tool_search',\n PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',\n WEB_SEARCH = 'web_search',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n /** Delimiter for MCP tools: toolName_mcp_serverName */\n MCP_DELIMITER = '_mcp_',\n /** Anthropic server tool ID prefix (web_search, code_execution, etc.) */\n ANTHROPIC_SERVER_TOOL_PREFIX = 'srvtoolu_',\n SKILL_TOOL = 'skill',\n /**\n * Callback-metadata keys stamped by `attemptInvoke` /\n * `tryFallbackProviders` carrying the provider (SDK `Providers` enum\n * value) and configured model that actually served a model invocation.\n * Unlike `ls_provider` — which derived providers inherit from their base\n * class (e.g. DeepSeek/OpenRouter report `'openai'`) — these reflect the\n * SDK's own routing, including fallback-provider calls. Consumed by the\n * subagent usage-capture handler to tag billing events.\n */\n INVOKED_PROVIDER = '__invoked_provider',\n INVOKED_MODEL = '__invoked_model',\n READ_FILE = 'read_file',\n BASH_TOOL = 'bash_tool',\n BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',\n SUBAGENT = 'subagent',\n /**\n * Local-engine coding tool names. Promoted to `Constants.*` (rather\n * than left as per-file `*ToolName` consts) so consumer UIs — most\n * importantly LibreChat's `getToolIconType` map — can match against\n * canonical strings instead of guessing. Existing matched names:\n * `bash_tool`, `read_file`, `execute_code`, `run_tools_with_code`.\n * The rest below are new and currently fall through to the generic\n * tool icon; once LibreChat adds icons keyed on the same names, the\n * wiring will work without an SDK change.\n */\n WRITE_FILE = 'write_file',\n EDIT_FILE = 'edit_file',\n GREP_SEARCH = 'grep_search',\n GLOB_SEARCH = 'glob_search',\n LIST_DIRECTORY = 'list_directory',\n COMPILE_CHECK = 'compile_check',\n}\n\n/** Tool names that use the code execution environment (shared session, file tracking). */\nexport const CODE_EXECUTION_TOOLS: ReadonlySet<string> = new Set([\n Constants.EXECUTE_CODE,\n Constants.BASH_TOOL,\n Constants.PROGRAMMATIC_TOOL_CALLING,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n]);\n\n/**\n * Canonical names of the local-engine-specific coding tools — the\n * file/edit/search/typecheck surface that doesn't exist in the\n * remote (sandbox-API) engine. Single source of truth; the per-tool\n * factories, registry definitions, and `createWorkspacePolicyHook`\n * default extractors all key off these.\n *\n * `read_file` is on this list (the existing ReadFile tool is\n * remote-specific; the local engine's `read_file` is a parallel\n * implementation that shares the canonical name so consumer UIs\n * — most importantly LibreChat's `getToolIconType` — render both\n * with the same icon).\n */\nexport const LOCAL_CODING_TOOL_NAMES: readonly string[] = [\n Constants.READ_FILE,\n Constants.WRITE_FILE,\n Constants.EDIT_FILE,\n Constants.GREP_SEARCH,\n Constants.GLOB_SEARCH,\n Constants.LIST_DIRECTORY,\n Constants.COMPILE_CHECK,\n];\n\n/**\n * Every tool name the local coding bundle (`createLocalCodingTools`)\n * exposes — the local-specific tools above plus the bash/code/PTC\n * pair that the local engine wraps around the existing factories.\n * Tests pin against this so any addition/removal in the bundle is\n * accompanied by a deliberate canonical-name update here.\n */\nexport const LOCAL_CODING_BUNDLE_NAMES: readonly string[] = [\n ...LOCAL_CODING_TOOL_NAMES,\n Constants.BASH_TOOL,\n Constants.EXECUTE_CODE,\n Constants.PROGRAMMATIC_TOOL_CALLING,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n];\n\nexport enum TitleMethod {\n STRUCTURED = 'structured',\n FUNCTIONS = 'functions',\n COMPLETION = 'completion',\n}\n\nexport enum EnvVar {\n CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',\n CODE_API_RUN_TIMEOUT_MS = 'CODE_API_RUN_TIMEOUT_MS',\n}\n"],"mappings":";;;;;;;AAMA,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;;;;;;;AASA,MAAa,4BAA+C;CAC1D,GAAG;;;;;AAKL;AAEA,IAAY,cAAL,yBAAA,aAAA;CACL,YAAA,gBAAA;CACA,YAAA,eAAA;CACA,YAAA,gBAAA;;AACF,EAAA,CAAA,CAAA;AAEA,IAAY,SAAL,yBAAA,QAAA;CACL,OAAA,kBAAA;CACA,OAAA,6BAAA;;AACF,EAAA,CAAA,CAAA"}
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
//#region src/hooks/HookRegistry.ts
|
|
2
2
|
/**
|
|
3
|
+
* Events whose hooks can change a tool call's input or output. Presence of
|
|
4
|
+
* any of these disables eager tool execution and early completion emission;
|
|
5
|
+
* observation-only events (`PostToolBatch`, `Stop`, telemetry hooks) do not.
|
|
6
|
+
*/
|
|
7
|
+
const RESULT_ALTERING_HOOK_EVENTS = [
|
|
8
|
+
"PreToolUse",
|
|
9
|
+
"PostToolUse",
|
|
10
|
+
"PostToolUseFailure"
|
|
11
|
+
];
|
|
12
|
+
/**
|
|
3
13
|
* Run-scoped storage for hook matchers with an additional layer for
|
|
4
14
|
* session-scoped matchers that should be cleaned up between sessions.
|
|
5
15
|
*
|
|
@@ -134,6 +144,24 @@ var HookRegistry = class {
|
|
|
134
144
|
clearHaltSignal(sessionId) {
|
|
135
145
|
this.haltSignals.delete(sessionId);
|
|
136
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* True when any registered hook can alter a tool result before or after
|
|
149
|
+
* execution (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`). Eager
|
|
150
|
+
* tool execution and early completion emission gate on this instead of
|
|
151
|
+
* registry presence, so observation-only registries (e.g. a
|
|
152
|
+
* `PostToolBatch` steering drain) keep those fast paths. With
|
|
153
|
+
* `sessionId`, checks global + that session; without it, conservatively
|
|
154
|
+
* scans every session bucket.
|
|
155
|
+
*/
|
|
156
|
+
hasResultAlteringHooks(sessionId) {
|
|
157
|
+
if (hasResultAlteringInBucket(this.global)) return true;
|
|
158
|
+
if (sessionId !== void 0) {
|
|
159
|
+
const bucket = this.sessions.get(sessionId);
|
|
160
|
+
return bucket !== void 0 && hasResultAlteringInBucket(bucket);
|
|
161
|
+
}
|
|
162
|
+
for (const bucket of this.sessions.values()) if (hasResultAlteringInBucket(bucket)) return true;
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
137
165
|
/** True if at least one matcher exists for `event` (global + session). */
|
|
138
166
|
hasHookFor(event, sessionId) {
|
|
139
167
|
if (readList(this.global, event).length > 0) return true;
|
|
@@ -160,6 +188,10 @@ function ensureList(bucket, event) {
|
|
|
160
188
|
function readList(bucket, event) {
|
|
161
189
|
return bucket[event] ?? [];
|
|
162
190
|
}
|
|
191
|
+
function hasResultAlteringInBucket(bucket) {
|
|
192
|
+
for (const event of RESULT_ALTERING_HOOK_EVENTS) if (readList(bucket, event).length > 0) return true;
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
163
195
|
function removeFromList(list, matcher) {
|
|
164
196
|
const idx = list.indexOf(widen(matcher));
|
|
165
197
|
if (idx < 0) return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HookRegistry.cjs","names":[],"sources":["../../../src/hooks/HookRegistry.ts"],"sourcesContent":["// src/hooks/HookRegistry.ts\nimport type { HookEvent, HookMatcher } from './types';\n\n/**\n * Internal matcher storage type.\n *\n * Matchers registered via the public `register<E>` API are strictly typed\n * to a single `E`, but the storage needs one uniform slot type per event.\n * We store them as `HookMatcher<HookEvent>` and cast once at the variance\n * boundary — see `ensureList` and `snapshot` below. The invariant (every\n * matcher in `bucket[event]` was registered with that exact event) is\n * enforced by the public API; breaking it requires bypassing the types.\n */\ntype MatcherBucket = Partial<Record<HookEvent, HookMatcher<HookEvent>[]>>;\n\n/**\n * Snapshot of a halt request raised by a hook returning\n * `preventContinuation: true`. The SDK's run loop polls for this between\n * stream events and exits cleanly when set, skipping the `Stop` hook\n * (the run is being halted, not naturally completing). One per registry\n * instance — the first hook to halt wins; subsequent halts are ignored\n * so the original reason isn't clobbered.\n */\nexport interface HookHaltSignal {\n reason: string;\n /** Event of the hook that triggered the halt (for diagnostics). */\n source: HookEvent;\n}\n\n/**\n * Run-scoped storage for hook matchers with an additional layer for\n * session-scoped matchers that should be cleaned up between sessions.\n *\n * Hosts construct one registry per `Run` (mirroring how `HandlerRegistry` is\n * scoped) and register global matchers + per-session matchers against it.\n * Registration is strictly additive — nothing in this class mutates a\n * matcher's callbacks or flags after insertion.\n *\n * ## Why `Map<sessionId, MatcherBucket>` and not `Record`\n *\n * LibreChat runs thousands of parallel sessions in one Node process, and\n * hook registration happens inside hot paths (tool loading, agent spawning).\n * A `Record<sessionId, ...>` has to be spread on every insertion, which is\n * O(n) per call and O(n²) total for a batch of parallel registrations. A\n * Map mutates in place, keeping insertions O(1). This mirrors the reasoning\n * Claude Code documents at `utils/hooks/sessionHooks.ts:62`.\n */\nexport class HookRegistry {\n private readonly global: MatcherBucket = {};\n private readonly sessions: Map<string, MatcherBucket> = new Map();\n /**\n * Per-session halt signals. Scoped by `sessionId` (= the run id the\n * hook fired under) so a host that shares one registry across\n * concurrent runs cannot leak `preventContinuation` from one run\n * into another. Without scoping, a halt raised by run A's hook\n * would trip run B's stream-loop poll on the next iteration —\n * silently terminating an unrelated run.\n *\n * Map storage mirrors the reasoning above for session matchers:\n * O(1) insertion in hot paths, no spread-on-write.\n */\n private readonly haltSignals: Map<string, HookHaltSignal> = new Map();\n\n /**\n * Register a matcher for the lifetime of this registry (= one Run).\n * Returns an unregister function that removes the matcher by reference.\n */\n register<E extends HookEvent>(event: E, matcher: HookMatcher<E>): () => void {\n const list = ensureList(this.global, event);\n list.push(widen(matcher));\n return () => {\n removeFromList(list, matcher);\n };\n }\n\n /**\n * Register a matcher for a specific session. Cleared automatically when\n * `clearSession(sessionId)` is called, or can be removed directly via the\n * returned unregister function.\n */\n registerSession<E extends HookEvent>(\n sessionId: string,\n event: E,\n matcher: HookMatcher<E>\n ): () => void {\n const bucket = this.ensureSessionBucket(sessionId);\n const list = ensureList(bucket, event);\n list.push(widen(matcher));\n return () => {\n removeFromList(list, matcher);\n };\n }\n\n /**\n * Returns all matchers registered for `event`, concatenating global first\n * and then session-specific (when `sessionId` is supplied). The caller\n * receives a fresh array, so iterating it is safe even if a matcher is\n * removed mid-iteration (e.g. via `once: true`).\n */\n getMatchers<E extends HookEvent>(\n event: E,\n sessionId?: string\n ): HookMatcher<E>[] {\n const globalList = readList(this.global, event);\n if (sessionId === undefined) {\n return snapshot<E>(globalList);\n }\n const bucket = this.sessions.get(sessionId);\n if (bucket === undefined) {\n return snapshot<E>(globalList);\n }\n const sessionList = readList(bucket, event);\n if (globalList.length === 0) {\n return snapshot<E>(sessionList);\n }\n if (sessionList.length === 0) {\n return snapshot<E>(globalList);\n }\n return snapshot<E>([...globalList, ...sessionList]);\n }\n\n /**\n * Removes `matcher` by reference from global storage first, falling back\n * to the session bucket when `sessionId` is supplied. Used by\n * `executeHooks` to drop `once: true` matchers after they fire.\n */\n removeMatcher<E extends HookEvent>(\n event: E,\n matcher: HookMatcher<E>,\n sessionId?: string\n ): boolean {\n if (removeFromList(readList(this.global, event), matcher)) {\n return true;\n }\n if (sessionId === undefined) {\n return false;\n }\n const bucket = this.sessions.get(sessionId);\n if (bucket === undefined) {\n return false;\n }\n return removeFromList(readList(bucket, event), matcher);\n }\n\n /**\n * Drops every session-scoped matcher for `sessionId`. Call this in the\n * `finally` block around a Run so a `once: true` hook that never fired\n * cannot leak into the next session on the same registry.\n */\n clearSession(sessionId: string): void {\n this.sessions.delete(sessionId);\n }\n\n /**\n * Raise a halt signal scoped to `sessionId` (= the run id the hook\n * fired under). The SDK's run loop polls for this between stream\n * events with the run's own id. First-write-wins per session: a\n * halt already raised by an earlier hook in the same run is\n * preserved so the original `reason` / `source` aren't overwritten.\n *\n * Per-session scoping is critical when hosts share one registry\n * across concurrent runs (e.g. a global policy registered once and\n * reused). Without it, a `preventContinuation` from run A would\n * trip run B's stream-loop poll on the next iteration and silently\n * terminate an unrelated run.\n *\n * Called by the SDK after `executeHooks` returns an aggregate with\n * `preventContinuation: true`. Hosts can also call it directly from\n * inside a hook callback if they want to halt without going through\n * the aggregated return value, but `preventContinuation` is the\n * canonical path.\n */\n haltRun(sessionId: string, reason: string, source: HookEvent): void {\n if (this.haltSignals.has(sessionId)) {\n return;\n }\n this.haltSignals.set(sessionId, { reason, source });\n }\n\n /**\n * Returns the halt signal raised by hooks running under `sessionId`,\n * or `undefined` if no hook in that run has halted. Polled by\n * `Run.processStream` between stream events using the run's own id.\n */\n getHaltSignal(sessionId: string): HookHaltSignal | undefined {\n return this.haltSignals.get(sessionId);\n }\n\n /**\n * Clears the halt signal for `sessionId`. Called by\n * `Run.processStream` in its `finally` block so a subsequent\n * invocation of the same Run (e.g. resume) starts with a fresh\n * halt state. No-op when no signal exists for that session.\n */\n clearHaltSignal(sessionId: string): void {\n this.haltSignals.delete(sessionId);\n }\n\n /** True if at least one matcher exists for `event` (global + session). */\n hasHookFor(event: HookEvent, sessionId?: string): boolean {\n if (readList(this.global, event).length > 0) {\n return true;\n }\n if (sessionId === undefined) {\n return false;\n }\n const bucket = this.sessions.get(sessionId);\n if (bucket === undefined) {\n return false;\n }\n return readList(bucket, event).length > 0;\n }\n\n private ensureSessionBucket(sessionId: string): MatcherBucket {\n const existing = this.sessions.get(sessionId);\n if (existing !== undefined) {\n return existing;\n }\n const fresh: MatcherBucket = {};\n this.sessions.set(sessionId, fresh);\n return fresh;\n }\n}\n\nfunction ensureList(\n bucket: MatcherBucket,\n event: HookEvent\n): HookMatcher<HookEvent>[] {\n const existing = bucket[event];\n if (existing !== undefined) {\n return existing;\n }\n const fresh: HookMatcher<HookEvent>[] = [];\n bucket[event] = fresh;\n return fresh;\n}\n\nfunction readList(\n bucket: MatcherBucket,\n event: HookEvent\n): HookMatcher<HookEvent>[] {\n return bucket[event] ?? [];\n}\n\nfunction removeFromList<E extends HookEvent>(\n list: HookMatcher<HookEvent>[],\n matcher: HookMatcher<E>\n): boolean {\n const idx = list.indexOf(widen(matcher));\n if (idx < 0) {\n return false;\n }\n list.splice(idx, 1);\n return true;\n}\n\n/**\n * Widen a per-event matcher to the storage's uniform slot type. Unsound at\n * the type level (function parameters are contravariant) but safe by\n * construction: `HookRegistry.register<E>` only ever puts matchers into the\n * bucket slot for their own event, and reads go through `snapshot<E>`\n * which is only called with the same `E`.\n */\nfunction widen<E extends HookEvent>(\n matcher: HookMatcher<E>\n): HookMatcher<HookEvent> {\n return matcher as unknown as HookMatcher<HookEvent>;\n}\n\n/**\n * Narrow a storage list back to a per-event matcher list on the way out.\n * Sound counterpart to `widen`: the list only contains matchers that were\n * registered against `E`, because the public API enforces it on insert.\n */\nfunction snapshot<E extends HookEvent>(\n list: readonly HookMatcher<HookEvent>[]\n): HookMatcher<E>[] {\n return list.slice() as unknown as HookMatcher<E>[];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+CA,IAAa,eAAb,MAA0B;CACxB,SAAyC,CAAC;CAC1C,2BAAwD,IAAI,IAAI;;;;;;;;;;;;CAYhE,8BAA4D,IAAI,IAAI;;;;;CAMpE,SAA8B,OAAU,SAAqC;EAC3E,MAAM,OAAO,WAAW,KAAK,QAAQ,KAAK;EAC1C,KAAK,KAAK,MAAM,OAAO,CAAC;EACxB,aAAa;GACX,eAAe,MAAM,OAAO;EAC9B;CACF;;;;;;CAOA,gBACE,WACA,OACA,SACY;EAEZ,MAAM,OAAO,WADE,KAAK,oBAAoB,SACX,GAAG,KAAK;EACrC,KAAK,KAAK,MAAM,OAAO,CAAC;EACxB,aAAa;GACX,eAAe,MAAM,OAAO;EAC9B;CACF;;;;;;;CAQA,YACE,OACA,WACkB;EAClB,MAAM,aAAa,SAAS,KAAK,QAAQ,KAAK;EAC9C,IAAI,cAAc,KAAA,GAChB,OAAO,SAAY,UAAU;EAE/B,MAAM,SAAS,KAAK,SAAS,IAAI,SAAS;EAC1C,IAAI,WAAW,KAAA,GACb,OAAO,SAAY,UAAU;EAE/B,MAAM,cAAc,SAAS,QAAQ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ACF;AAEA,SAAS,WACP,QACA,OAC0B;CAC1B,MAAM,WAAW,OAAO;CACxB,IAAI,aAAa,KAAA,GACf,OAAO;CAET,MAAM,QAAkC,CAAC;CACzC,OAAO,SAAS;CAChB,OAAO;AACT;AAEA,SAAS,SACP,QACA,OAC0B;CAC1B,OAAO,OAAO,UAAU,CAAC;AAC3B;AAEA,SAAS,eACP,MACA,SACS;CACT,MAAM,MAAM,KAAK,QAAQ,MAAM,OAAO,CAAC;CACvC,IAAI,MAAM,GACR,OAAO;CAET,KAAK,OAAO,KAAK,CAAC;CAClB,OAAO;AACT;;;;;;;;AASA,SAAS,MACP,SACwB;CACxB,OAAO;AACT;;;;;;AAOA,SAAS,SACP,MACkB;CAClB,OAAO,KAAK,MAAM;AACpB"}
|
|
1
|
+
{"version":3,"file":"HookRegistry.cjs","names":[],"sources":["../../../src/hooks/HookRegistry.ts"],"sourcesContent":["// src/hooks/HookRegistry.ts\nimport type { HookEvent, HookMatcher } from './types';\n\n/**\n * Internal matcher storage type.\n *\n * Matchers registered via the public `register<E>` API are strictly typed\n * to a single `E`, but the storage needs one uniform slot type per event.\n * We store them as `HookMatcher<HookEvent>` and cast once at the variance\n * boundary — see `ensureList` and `snapshot` below. The invariant (every\n * matcher in `bucket[event]` was registered with that exact event) is\n * enforced by the public API; breaking it requires bypassing the types.\n */\ntype MatcherBucket = Partial<Record<HookEvent, HookMatcher<HookEvent>[]>>;\n\n/**\n * Events whose hooks can change a tool call's input or output. Presence of\n * any of these disables eager tool execution and early completion emission;\n * observation-only events (`PostToolBatch`, `Stop`, telemetry hooks) do not.\n */\nconst RESULT_ALTERING_HOOK_EVENTS = [\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n] as const satisfies readonly HookEvent[];\n\n/**\n * Snapshot of a halt request raised by a hook returning\n * `preventContinuation: true`. The SDK's run loop polls for this between\n * stream events and exits cleanly when set, skipping the `Stop` hook\n * (the run is being halted, not naturally completing). One per registry\n * instance — the first hook to halt wins; subsequent halts are ignored\n * so the original reason isn't clobbered.\n */\nexport interface HookHaltSignal {\n reason: string;\n /** Event of the hook that triggered the halt (for diagnostics). */\n source: HookEvent;\n}\n\n/**\n * Run-scoped storage for hook matchers with an additional layer for\n * session-scoped matchers that should be cleaned up between sessions.\n *\n * Hosts construct one registry per `Run` (mirroring how `HandlerRegistry` is\n * scoped) and register global matchers + per-session matchers against it.\n * Registration is strictly additive — nothing in this class mutates a\n * matcher's callbacks or flags after insertion.\n *\n * ## Why `Map<sessionId, MatcherBucket>` and not `Record`\n *\n * LibreChat runs thousands of parallel sessions in one Node process, and\n * hook registration happens inside hot paths (tool loading, agent spawning).\n * A `Record<sessionId, ...>` has to be spread on every insertion, which is\n * O(n) per call and O(n²) total for a batch of parallel registrations. A\n * Map mutates in place, keeping insertions O(1). This mirrors the reasoning\n * Claude Code documents at `utils/hooks/sessionHooks.ts:62`.\n */\nexport class HookRegistry {\n private readonly global: MatcherBucket = {};\n private readonly sessions: Map<string, MatcherBucket> = new Map();\n /**\n * Per-session halt signals. Scoped by `sessionId` (= the run id the\n * hook fired under) so a host that shares one registry across\n * concurrent runs cannot leak `preventContinuation` from one run\n * into another. Without scoping, a halt raised by run A's hook\n * would trip run B's stream-loop poll on the next iteration —\n * silently terminating an unrelated run.\n *\n * Map storage mirrors the reasoning above for session matchers:\n * O(1) insertion in hot paths, no spread-on-write.\n */\n private readonly haltSignals: Map<string, HookHaltSignal> = new Map();\n\n /**\n * Register a matcher for the lifetime of this registry (= one Run).\n * Returns an unregister function that removes the matcher by reference.\n */\n register<E extends HookEvent>(event: E, matcher: HookMatcher<E>): () => void {\n const list = ensureList(this.global, event);\n list.push(widen(matcher));\n return () => {\n removeFromList(list, matcher);\n };\n }\n\n /**\n * Register a matcher for a specific session. Cleared automatically when\n * `clearSession(sessionId)` is called, or can be removed directly via the\n * returned unregister function.\n */\n registerSession<E extends HookEvent>(\n sessionId: string,\n event: E,\n matcher: HookMatcher<E>\n ): () => void {\n const bucket = this.ensureSessionBucket(sessionId);\n const list = ensureList(bucket, event);\n list.push(widen(matcher));\n return () => {\n removeFromList(list, matcher);\n };\n }\n\n /**\n * Returns all matchers registered for `event`, concatenating global first\n * and then session-specific (when `sessionId` is supplied). The caller\n * receives a fresh array, so iterating it is safe even if a matcher is\n * removed mid-iteration (e.g. via `once: true`).\n */\n getMatchers<E extends HookEvent>(\n event: E,\n sessionId?: string\n ): HookMatcher<E>[] {\n const globalList = readList(this.global, event);\n if (sessionId === undefined) {\n return snapshot<E>(globalList);\n }\n const bucket = this.sessions.get(sessionId);\n if (bucket === undefined) {\n return snapshot<E>(globalList);\n }\n const sessionList = readList(bucket, event);\n if (globalList.length === 0) {\n return snapshot<E>(sessionList);\n }\n if (sessionList.length === 0) {\n return snapshot<E>(globalList);\n }\n return snapshot<E>([...globalList, ...sessionList]);\n }\n\n /**\n * Removes `matcher` by reference from global storage first, falling back\n * to the session bucket when `sessionId` is supplied. Used by\n * `executeHooks` to drop `once: true` matchers after they fire.\n */\n removeMatcher<E extends HookEvent>(\n event: E,\n matcher: HookMatcher<E>,\n sessionId?: string\n ): boolean {\n if (removeFromList(readList(this.global, event), matcher)) {\n return true;\n }\n if (sessionId === undefined) {\n return false;\n }\n const bucket = this.sessions.get(sessionId);\n if (bucket === undefined) {\n return false;\n }\n return removeFromList(readList(bucket, event), matcher);\n }\n\n /**\n * Drops every session-scoped matcher for `sessionId`. Call this in the\n * `finally` block around a Run so a `once: true` hook that never fired\n * cannot leak into the next session on the same registry.\n */\n clearSession(sessionId: string): void {\n this.sessions.delete(sessionId);\n }\n\n /**\n * Raise a halt signal scoped to `sessionId` (= the run id the hook\n * fired under). The SDK's run loop polls for this between stream\n * events with the run's own id. First-write-wins per session: a\n * halt already raised by an earlier hook in the same run is\n * preserved so the original `reason` / `source` aren't overwritten.\n *\n * Per-session scoping is critical when hosts share one registry\n * across concurrent runs (e.g. a global policy registered once and\n * reused). Without it, a `preventContinuation` from run A would\n * trip run B's stream-loop poll on the next iteration and silently\n * terminate an unrelated run.\n *\n * Called by the SDK after `executeHooks` returns an aggregate with\n * `preventContinuation: true`. Hosts can also call it directly from\n * inside a hook callback if they want to halt without going through\n * the aggregated return value, but `preventContinuation` is the\n * canonical path.\n */\n haltRun(sessionId: string, reason: string, source: HookEvent): void {\n if (this.haltSignals.has(sessionId)) {\n return;\n }\n this.haltSignals.set(sessionId, { reason, source });\n }\n\n /**\n * Returns the halt signal raised by hooks running under `sessionId`,\n * or `undefined` if no hook in that run has halted. Polled by\n * `Run.processStream` between stream events using the run's own id.\n */\n getHaltSignal(sessionId: string): HookHaltSignal | undefined {\n return this.haltSignals.get(sessionId);\n }\n\n /**\n * Clears the halt signal for `sessionId`. Called by\n * `Run.processStream` in its `finally` block so a subsequent\n * invocation of the same Run (e.g. resume) starts with a fresh\n * halt state. No-op when no signal exists for that session.\n */\n clearHaltSignal(sessionId: string): void {\n this.haltSignals.delete(sessionId);\n }\n\n /**\n * True when any registered hook can alter a tool result before or after\n * execution (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`). Eager\n * tool execution and early completion emission gate on this instead of\n * registry presence, so observation-only registries (e.g. a\n * `PostToolBatch` steering drain) keep those fast paths. With\n * `sessionId`, checks global + that session; without it, conservatively\n * scans every session bucket.\n */\n hasResultAlteringHooks(sessionId?: string): boolean {\n if (hasResultAlteringInBucket(this.global)) {\n return true;\n }\n if (sessionId !== undefined) {\n const bucket = this.sessions.get(sessionId);\n return bucket !== undefined && hasResultAlteringInBucket(bucket);\n }\n for (const bucket of this.sessions.values()) {\n if (hasResultAlteringInBucket(bucket)) {\n return true;\n }\n }\n return false;\n }\n\n /** True if at least one matcher exists for `event` (global + session). */\n hasHookFor(event: HookEvent, sessionId?: string): boolean {\n if (readList(this.global, event).length > 0) {\n return true;\n }\n if (sessionId === undefined) {\n return false;\n }\n const bucket = this.sessions.get(sessionId);\n if (bucket === undefined) {\n return false;\n }\n return readList(bucket, event).length > 0;\n }\n\n private ensureSessionBucket(sessionId: string): MatcherBucket {\n const existing = this.sessions.get(sessionId);\n if (existing !== undefined) {\n return existing;\n }\n const fresh: MatcherBucket = {};\n this.sessions.set(sessionId, fresh);\n return fresh;\n }\n}\n\nfunction ensureList(\n bucket: MatcherBucket,\n event: HookEvent\n): HookMatcher<HookEvent>[] {\n const existing = bucket[event];\n if (existing !== undefined) {\n return existing;\n }\n const fresh: HookMatcher<HookEvent>[] = [];\n bucket[event] = fresh;\n return fresh;\n}\n\nfunction readList(\n bucket: MatcherBucket,\n event: HookEvent\n): HookMatcher<HookEvent>[] {\n return bucket[event] ?? [];\n}\n\nfunction hasResultAlteringInBucket(bucket: MatcherBucket): boolean {\n for (const event of RESULT_ALTERING_HOOK_EVENTS) {\n if (readList(bucket, event).length > 0) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeFromList<E extends HookEvent>(\n list: HookMatcher<HookEvent>[],\n matcher: HookMatcher<E>\n): boolean {\n const idx = list.indexOf(widen(matcher));\n if (idx < 0) {\n return false;\n }\n list.splice(idx, 1);\n return true;\n}\n\n/**\n * Widen a per-event matcher to the storage's uniform slot type. Unsound at\n * the type level (function parameters are contravariant) but safe by\n * construction: `HookRegistry.register<E>` only ever puts matchers into the\n * bucket slot for their own event, and reads go through `snapshot<E>`\n * which is only called with the same `E`.\n */\nfunction widen<E extends HookEvent>(\n matcher: HookMatcher<E>\n): HookMatcher<HookEvent> {\n return matcher as unknown as HookMatcher<HookEvent>;\n}\n\n/**\n * Narrow a storage list back to a per-event matcher list on the way out.\n * Sound counterpart to `widen`: the list only contains matchers that were\n * registered against `E`, because the public API enforces it on insert.\n */\nfunction snapshot<E extends HookEvent>(\n list: readonly HookMatcher<HookEvent>[]\n): HookMatcher<E>[] {\n return list.slice() as unknown as HookMatcher<E>[];\n}\n"],"mappings":";;;;;;AAoBA,MAAM,8BAA8B;CAClC;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;AAkCA,IAAa,eAAb,MAA0B;CACxB,SAAyC,CAAC;CAC1C,2BAAwD,IAAI,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C,SAAS,GACnC,OAAO;CAGX,OAAO;AACT;AAEA,SAAS,eACP,MACA,SACS;CACT,MAAM,MAAM,KAAK,QAAQ,MAAM,OAAO,CAAC;CACvC,IAAI,MAAM,GACR,OAAO;CAET,KAAK,OAAO,KAAK,CAAC;CAClB,OAAO;AACT;;;;;;;;AASA,SAAS,MACP,SACwB;CACxB,OAAO;AACT;;;;;;AAOA,SAAS,SACP,MACkB;CAClB,OAAO,KAAK,MAAM;AACpB"}
|
|
@@ -5,6 +5,7 @@ const DEFAULT_HOOK_TIMEOUT_MS = 3e4;
|
|
|
5
5
|
function freshResult() {
|
|
6
6
|
return {
|
|
7
7
|
additionalContexts: [],
|
|
8
|
+
injectedMessages: [],
|
|
8
9
|
errors: []
|
|
9
10
|
};
|
|
10
11
|
}
|
|
@@ -126,6 +127,10 @@ function applyDecision(agg, output) {
|
|
|
126
127
|
function applyContext(agg, output) {
|
|
127
128
|
if (typeof output.additionalContext === "string" && output.additionalContext.length > 0) agg.additionalContexts.push(output.additionalContext);
|
|
128
129
|
}
|
|
130
|
+
function applyInjectedMessages(agg, output) {
|
|
131
|
+
if (output.injectedMessages === void 0 || output.injectedMessages.length === 0) return;
|
|
132
|
+
agg.injectedMessages.push(...output.injectedMessages);
|
|
133
|
+
}
|
|
129
134
|
function applyStopFlag(agg, output) {
|
|
130
135
|
if (output.preventContinuation !== true) return;
|
|
131
136
|
agg.preventContinuation = true;
|
|
@@ -160,6 +165,7 @@ function fold(outcomes) {
|
|
|
160
165
|
*/
|
|
161
166
|
if (output.async === true) continue;
|
|
162
167
|
applyContext(agg, output);
|
|
168
|
+
applyInjectedMessages(agg, output);
|
|
163
169
|
applyStopFlag(agg, output);
|
|
164
170
|
applyDecision(agg, output);
|
|
165
171
|
applyUpdatedInput(agg, output);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executeHooks.cjs","names":["matchesQuery"],"sources":["../../../src/hooks/executeHooks.ts"],"sourcesContent":["// src/hooks/executeHooks.ts\nimport type { Logger } from 'winston';\nimport type {\n HookInput,\n HookEvent,\n HookOutput,\n HookMatcher,\n ToolDecision,\n StopDecision,\n HookCallback,\n AggregatedHookResult,\n} from './types';\nimport type { HookRegistry } from './HookRegistry';\nimport { matchesQuery } from './matchers';\n\n/** Default per-hook timeout when a matcher doesn't set its own. */\nexport const DEFAULT_HOOK_TIMEOUT_MS = 30_000;\n\n/**\n * Options for a single `executeHooks` call. The `input` drives everything —\n * the event name is read from `input.hook_event_name`, matchers are looked\n * up against that event, and each hook receives `input` directly.\n */\nexport interface ExecuteHooksOptions {\n registry: HookRegistry;\n input: HookInput;\n /** Scope lookup to this session (in addition to global matchers). */\n sessionId?: string;\n /** Query string matched against each matcher's pattern (tool name, etc.). */\n matchQuery?: string;\n /** Parent AbortSignal — combined with per-hook timeout into the hook signal. */\n signal?: AbortSignal;\n /** Default per-hook timeout; overridden by `matcher.timeout` when present. */\n timeoutMs?: number;\n /** Optional winston logger for non-internal hook errors. */\n logger?: Logger;\n}\n\ntype WideMatcher = HookMatcher<HookEvent>;\ntype WideCallback = HookCallback<HookEvent>;\n\ninterface HookOutcome {\n matcher: WideMatcher;\n output: HookOutput | null;\n error: string | null;\n timedOut: boolean;\n}\n\ninterface AbortRace {\n promise: Promise<never>;\n cleanup: () => void;\n}\n\nfunction freshResult(): AggregatedHookResult {\n return {\n additionalContexts: [],\n errors: [],\n };\n}\n\nfunction combineSignals(\n parent: AbortSignal | undefined,\n timeoutMs: number\n): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (parent === undefined) {\n return timeoutSignal;\n }\n return AbortSignal.any([parent, timeoutSignal]);\n}\n\nfunction isTimeout(err: unknown): boolean {\n if (err instanceof Error) {\n return err.name === 'TimeoutError' || err.name === 'AbortError';\n }\n return false;\n}\n\nfunction describeError(err: unknown): string {\n if (err instanceof Error) {\n return err.message !== '' ? err.message : err.name;\n }\n return String(err);\n}\n\nfunction makeAbortPromise(signal: AbortSignal): {\n promise: Promise<never>;\n cleanup: () => void;\n} {\n let onAbort: (() => void) | undefined;\n const promise = new Promise<never>((_resolve, reject) => {\n if (signal.aborted) {\n reject(\n signal.reason instanceof Error ? signal.reason : new Error('aborted')\n );\n return;\n }\n onAbort = (): void => {\n reject(\n signal.reason instanceof Error ? signal.reason : new Error('aborted')\n );\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n const cleanup = (): void => {\n if (onAbort !== undefined) {\n signal.removeEventListener('abort', onAbort);\n onAbort = undefined;\n }\n };\n return { promise, cleanup };\n}\n\nasync function runHook(\n hook: WideCallback,\n input: HookInput,\n signal: AbortSignal,\n abortPromise: Promise<never>,\n matcher: WideMatcher\n): Promise<HookOutcome> {\n const hookPromise = Promise.resolve().then(() => hook(input, signal));\n try {\n const output = await Promise.race([hookPromise, abortPromise]);\n return { matcher, output, error: null, timedOut: false };\n } catch (err) {\n return {\n matcher,\n output: null,\n error: describeError(err),\n timedOut: isTimeout(err),\n };\n }\n}\n\nasync function runMatcherHooks(\n matcher: WideMatcher,\n input: HookInput,\n signal: AbortSignal\n): Promise<HookOutcome[]> {\n const abortRace: AbortRace = makeAbortPromise(signal);\n const tasks = matcher.hooks.map((hook) =>\n runHook(hook, input, signal, abortRace.promise, matcher)\n );\n try {\n return await Promise.all(tasks);\n } finally {\n abortRace.cleanup();\n }\n}\n\nfunction reportErrors(\n outcomes: readonly HookOutcome[],\n event: HookEvent,\n logger: Logger | undefined\n): void {\n for (const outcome of outcomes) {\n if (outcome.error === null) {\n continue;\n }\n if (outcome.matcher.internal === true) {\n continue;\n }\n const label = outcome.timedOut ? 'timed out' : 'threw an error';\n const message = `Hook for ${event} ${label}: ${outcome.error}`;\n if (logger !== undefined) {\n logger.warn(message);\n continue;\n }\n // eslint-disable-next-line no-console\n console.warn(message);\n }\n}\n\nfunction applyToolDecision(\n agg: AggregatedHookResult,\n decision: ToolDecision,\n reason: string | undefined\n): void {\n if (decision === 'deny') {\n if (agg.decision === 'deny') {\n return;\n }\n agg.decision = 'deny';\n agg.reason = reason;\n return;\n }\n if (decision === 'ask') {\n if (agg.decision === 'deny' || agg.decision === 'ask') {\n return;\n }\n agg.decision = 'ask';\n agg.reason = reason;\n return;\n }\n if (agg.decision === undefined) {\n agg.decision = 'allow';\n agg.reason = reason;\n }\n}\n\nfunction applyStopDecision(\n agg: AggregatedHookResult,\n decision: StopDecision,\n reason: string | undefined\n): void {\n if (decision === 'block') {\n if (agg.stopDecision === 'block') {\n return;\n }\n agg.stopDecision = 'block';\n agg.reason = reason;\n return;\n }\n if (agg.stopDecision === undefined) {\n agg.stopDecision = 'continue';\n if (agg.reason === undefined) {\n agg.reason = reason;\n }\n }\n}\n\nfunction applyDecision(agg: AggregatedHookResult, output: HookOutput): void {\n if (!('decision' in output) || output.decision === undefined) {\n return;\n }\n const decision = output.decision;\n const reason =\n 'reason' in output && typeof output.reason === 'string'\n ? output.reason\n : undefined;\n if (decision === 'deny' || decision === 'ask' || decision === 'allow') {\n applyToolDecision(agg, decision, reason);\n return;\n }\n applyStopDecision(agg, decision, reason);\n}\n\nfunction applyContext(agg: AggregatedHookResult, output: HookOutput): void {\n if (\n typeof output.additionalContext === 'string' &&\n output.additionalContext.length > 0\n ) {\n agg.additionalContexts.push(output.additionalContext);\n }\n}\n\nfunction applyStopFlag(agg: AggregatedHookResult, output: HookOutput): void {\n if (output.preventContinuation !== true) {\n return;\n }\n agg.preventContinuation = true;\n if (typeof output.stopReason === 'string' && agg.stopReason === undefined) {\n agg.stopReason = output.stopReason;\n }\n}\n\nfunction applyUpdatedInput(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (!('updatedInput' in output) || output.updatedInput === undefined) {\n return;\n }\n agg.updatedInput = output.updatedInput;\n}\n\nfunction applyUpdatedOutput(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (!('updatedOutput' in output) || output.updatedOutput === undefined) {\n return;\n }\n agg.updatedOutput = output.updatedOutput;\n}\n\nfunction applyAllowedDecisions(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (\n !('allowedDecisions' in output) ||\n output.allowedDecisions === undefined\n ) {\n return;\n }\n agg.allowedDecisions = output.allowedDecisions;\n}\n\nfunction fold(outcomes: readonly HookOutcome[]): AggregatedHookResult {\n const agg = freshResult();\n for (const outcome of outcomes) {\n if (outcome.error !== null) {\n if (outcome.matcher.internal !== true) {\n agg.errors.push(outcome.error);\n }\n continue;\n }\n const output = outcome.output;\n if (output === null) {\n continue;\n }\n /**\n * Skip fire-and-forget outputs entirely: the agent has already\n * moved on, so an async hook cannot influence the run. Background\n * work inside the hook body still runs (we don't cancel it), it\n * just doesn't fold into the aggregate result.\n */\n if (output.async === true) {\n continue;\n }\n applyContext(agg, output);\n applyStopFlag(agg, output);\n applyDecision(agg, output);\n applyUpdatedInput(agg, output);\n applyUpdatedOutput(agg, output);\n applyAllowedDecisions(agg, output);\n }\n return agg;\n}\n\n/**\n * Fires every matcher registered against `input.hook_event_name`, folding\n * their results per `deny > ask > allow` precedence and accumulating\n * context/errors.\n *\n * ## Parallelism and determinism\n *\n * All matching hooks fire simultaneously and are awaited via `Promise.all`,\n * which preserves input-array order in its returned results. The fold\n * therefore iterates outcomes in **registration order** — outer loop over\n * matchers as they sit in the registry (global first, then session), inner\n * loop over each matcher's `hooks` array. Last-writer-wins fields\n * (`updatedInput`, `updatedOutput`) are deterministic in that order, even\n * though hooks may complete in arbitrary wall-clock order.\n *\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput`/`updatedOutput` to one hook per matcher to avoid subtle\n * precedence bugs when matchers are added in a different order than\n * expected.\n *\n * ## Timeouts and cancellation\n *\n * Each matcher receives **one shared `AbortSignal`** derived from the\n * caller's parent signal combined with `matcher.timeout` (falling back to\n * `opts.timeoutMs`, default {@link DEFAULT_HOOK_TIMEOUT_MS}). Sharing the\n * signal across hooks in a matcher collapses N timer allocations into\n * one, which matters on the PreToolUse hot path where a matcher with\n * several hooks fires on every tool call. Each hook call is raced\n * against the shared signal, so even a hook that ignores the signal is\n * force-unblocked when the timeout fires. Timeout/abort errors are\n * swallowed into the aggregated result's `errors` array (non-fatal by\n * default).\n *\n * ## Internal matchers\n *\n * A matcher with `internal: true` is excluded from both the `errors` array\n * and the logger output. Use it for infrastructure hooks whose failures\n * should not pollute user-visible diagnostics.\n *\n * ## Once semantics — atomic at-most-once\n *\n * A matcher with `once: true` is removed from the registry **before any\n * hook runs**, inside the synchronous prefix of `executeHooks` (between\n * `getMatchers` and the first `await`). Because Node's event loop serialises\n * sync work, two concurrent `executeHooks` calls can never both observe\n * and dispatch the same `once` matcher — whichever call runs its sync\n * prefix first consumes it, and the loser sees an empty bucket.\n *\n * Trade-off: if every hook in a `once` matcher throws, the matcher is\n * still gone. \"Once\" here means \"at most one dispatch, ever\", not \"at\n * most one successful execution with retry on failure\". Hosts that need\n * retry semantics should register a normal matcher and self-unregister\n * via the `unregister` callback returned from `registry.register`.\n */\nexport async function executeHooks(\n opts: ExecuteHooksOptions\n): Promise<AggregatedHookResult> {\n const {\n registry,\n input,\n sessionId,\n matchQuery,\n signal,\n timeoutMs = DEFAULT_HOOK_TIMEOUT_MS,\n logger,\n } = opts;\n const event = input.hook_event_name;\n const matchers = registry.getMatchers(event, sessionId);\n if (matchers.length === 0) {\n return freshResult();\n }\n\n // --- SYNC CRITICAL SECTION: once-matcher removal must complete before any await ---\n const tasks: Promise<HookOutcome[]>[] = [];\n for (const matcher of matchers) {\n if (!matchesQuery(matcher.pattern, matchQuery)) {\n continue;\n }\n if (matcher.once === true) {\n registry.removeMatcher(event, matcher, sessionId);\n }\n if (matcher.hooks.length === 0) {\n continue;\n }\n const perHookTimeout = matcher.timeout ?? timeoutMs;\n const matcherSignal = combineSignals(signal, perHookTimeout);\n tasks.push(runMatcherHooks(matcher, input, matcherSignal));\n }\n // --- END SYNC CRITICAL SECTION ---\n if (tasks.length === 0) {\n return freshResult();\n }\n\n const outcomes = (await Promise.all(tasks)).flat();\n reportErrors(outcomes, event, logger);\n const aggregated = fold(outcomes);\n /**\n * Centralized `preventContinuation` propagation: when any hook (across\n * any callsite — RunStart, PreToolUse, PostToolBatch, SubagentStop,\n * etc.) returns `preventContinuation: true`, raise a halt signal on\n * the registry scoped to the run's `sessionId`. `Run.processStream`\n * polls the signal between stream events using its own id and exits\n * cleanly, skipping the `Stop` hook (since the run is being halted,\n * not naturally completing).\n *\n * First-write-wins per session inside the registry — a halt already\n * raised by an earlier hook in the same run is preserved so the\n * original `reason` / `source` are not clobbered. Hooks fired\n * without a `sessionId` cannot raise a halt (there's no run for the\n * loop to poll under), which is fine: every in-tree callsite passes\n * `sessionId: runId`. Pre-stream callsites in `Run.processStream`\n * still read `preventContinuation` directly off the result for an\n * early return because they have not yet entered the stream loop.\n */\n if (aggregated.preventContinuation === true && sessionId !== undefined) {\n registry.haltRun(\n sessionId,\n aggregated.stopReason ?? 'preventContinuation',\n event\n );\n }\n return aggregated;\n}\n"],"mappings":";;;AAgBA,MAAa,0BAA0B;AAqCvC,SAAS,cAAoC;CAC3C,OAAO;EACL,oBAAoB,CAAC;EACrB,QAAQ,CAAC;CACX;AACF;AAEA,SAAS,eACP,QACA,WACa;CACb,MAAM,gBAAgB,YAAY,QAAQ,SAAS;CACnD,IAAI,WAAW,KAAA,GACb,OAAO;CAET,OAAO,YAAY,IAAI,CAAC,QAAQ,aAAa,CAAC;AAChD;AAEA,SAAS,UAAU,KAAuB;CACxC,IAAI,eAAe,OACjB,OAAO,IAAI,SAAS,kBAAkB,IAAI,SAAS;CAErD,OAAO;AACT;AAEA,SAAS,cAAc,KAAsB;CAC3C,IAAI,eAAe,OACjB,OAAO,IAAI,YAAY,KAAK,IAAI,UAAU,IAAI;CAEhD,OAAO,OAAO,GAAG;AACnB;AAEA,SAAS,iBAAiB,QAGxB;CACA,IAAI;CACJ,MAAM,UAAU,IAAI,SAAgB,UAAU,WAAW;EACvD,IAAI,OAAO,SAAS;GAClB,OACE,OAAO,kBAAkB,QAAQ,OAAO,yBAAS,IAAI,MAAM,SAAS,CACtE;GACA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W,GAC3B;EAGF,MAAM,gBAAgB,eAAe,QADd,QAAQ,WAAW,SACiB;EAC3D,MAAM,KAAK,gBAAgB,SAAS,OAAO,aAAa,CAAC;CAC3D;CAEA,IAAI,MAAM,WAAW,GACnB,OAAO,YAAY;CAGrB,MAAM,YAAY,MAAM,QAAQ,IAAI,KAAK,EAAA,CAAG,KAAK;CACjD,aAAa,UAAU,OAAO,MAAM;CACpC,MAAM,aAAa,KAAK,QAAQ;;;;;;;;;;;;;;;;;;;CAmBhC,IAAI,WAAW,wBAAwB,QAAQ,cAAc,KAAA,GAC3D,SAAS,QACP,WACA,WAAW,cAAc,uBACzB,KACF;CAEF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"executeHooks.cjs","names":["matchesQuery"],"sources":["../../../src/hooks/executeHooks.ts"],"sourcesContent":["// src/hooks/executeHooks.ts\nimport type { Logger } from 'winston';\nimport type {\n HookInput,\n HookEvent,\n HookOutput,\n HookMatcher,\n ToolDecision,\n StopDecision,\n HookCallback,\n AggregatedHookResult,\n} from './types';\nimport type { HookRegistry } from './HookRegistry';\nimport { matchesQuery } from './matchers';\n\n/** Default per-hook timeout when a matcher doesn't set its own. */\nexport const DEFAULT_HOOK_TIMEOUT_MS = 30_000;\n\n/**\n * Options for a single `executeHooks` call. The `input` drives everything —\n * the event name is read from `input.hook_event_name`, matchers are looked\n * up against that event, and each hook receives `input` directly.\n */\nexport interface ExecuteHooksOptions {\n registry: HookRegistry;\n input: HookInput;\n /** Scope lookup to this session (in addition to global matchers). */\n sessionId?: string;\n /** Query string matched against each matcher's pattern (tool name, etc.). */\n matchQuery?: string;\n /** Parent AbortSignal — combined with per-hook timeout into the hook signal. */\n signal?: AbortSignal;\n /** Default per-hook timeout; overridden by `matcher.timeout` when present. */\n timeoutMs?: number;\n /** Optional winston logger for non-internal hook errors. */\n logger?: Logger;\n}\n\ntype WideMatcher = HookMatcher<HookEvent>;\ntype WideCallback = HookCallback<HookEvent>;\n\ninterface HookOutcome {\n matcher: WideMatcher;\n output: HookOutput | null;\n error: string | null;\n timedOut: boolean;\n}\n\ninterface AbortRace {\n promise: Promise<never>;\n cleanup: () => void;\n}\n\nfunction freshResult(): AggregatedHookResult {\n return {\n additionalContexts: [],\n injectedMessages: [],\n errors: [],\n };\n}\n\nfunction combineSignals(\n parent: AbortSignal | undefined,\n timeoutMs: number\n): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n if (parent === undefined) {\n return timeoutSignal;\n }\n return AbortSignal.any([parent, timeoutSignal]);\n}\n\nfunction isTimeout(err: unknown): boolean {\n if (err instanceof Error) {\n return err.name === 'TimeoutError' || err.name === 'AbortError';\n }\n return false;\n}\n\nfunction describeError(err: unknown): string {\n if (err instanceof Error) {\n return err.message !== '' ? err.message : err.name;\n }\n return String(err);\n}\n\nfunction makeAbortPromise(signal: AbortSignal): {\n promise: Promise<never>;\n cleanup: () => void;\n} {\n let onAbort: (() => void) | undefined;\n const promise = new Promise<never>((_resolve, reject) => {\n if (signal.aborted) {\n reject(\n signal.reason instanceof Error ? signal.reason : new Error('aborted')\n );\n return;\n }\n onAbort = (): void => {\n reject(\n signal.reason instanceof Error ? signal.reason : new Error('aborted')\n );\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n const cleanup = (): void => {\n if (onAbort !== undefined) {\n signal.removeEventListener('abort', onAbort);\n onAbort = undefined;\n }\n };\n return { promise, cleanup };\n}\n\nasync function runHook(\n hook: WideCallback,\n input: HookInput,\n signal: AbortSignal,\n abortPromise: Promise<never>,\n matcher: WideMatcher\n): Promise<HookOutcome> {\n const hookPromise = Promise.resolve().then(() => hook(input, signal));\n try {\n const output = await Promise.race([hookPromise, abortPromise]);\n return { matcher, output, error: null, timedOut: false };\n } catch (err) {\n return {\n matcher,\n output: null,\n error: describeError(err),\n timedOut: isTimeout(err),\n };\n }\n}\n\nasync function runMatcherHooks(\n matcher: WideMatcher,\n input: HookInput,\n signal: AbortSignal\n): Promise<HookOutcome[]> {\n const abortRace: AbortRace = makeAbortPromise(signal);\n const tasks = matcher.hooks.map((hook) =>\n runHook(hook, input, signal, abortRace.promise, matcher)\n );\n try {\n return await Promise.all(tasks);\n } finally {\n abortRace.cleanup();\n }\n}\n\nfunction reportErrors(\n outcomes: readonly HookOutcome[],\n event: HookEvent,\n logger: Logger | undefined\n): void {\n for (const outcome of outcomes) {\n if (outcome.error === null) {\n continue;\n }\n if (outcome.matcher.internal === true) {\n continue;\n }\n const label = outcome.timedOut ? 'timed out' : 'threw an error';\n const message = `Hook for ${event} ${label}: ${outcome.error}`;\n if (logger !== undefined) {\n logger.warn(message);\n continue;\n }\n // eslint-disable-next-line no-console\n console.warn(message);\n }\n}\n\nfunction applyToolDecision(\n agg: AggregatedHookResult,\n decision: ToolDecision,\n reason: string | undefined\n): void {\n if (decision === 'deny') {\n if (agg.decision === 'deny') {\n return;\n }\n agg.decision = 'deny';\n agg.reason = reason;\n return;\n }\n if (decision === 'ask') {\n if (agg.decision === 'deny' || agg.decision === 'ask') {\n return;\n }\n agg.decision = 'ask';\n agg.reason = reason;\n return;\n }\n if (agg.decision === undefined) {\n agg.decision = 'allow';\n agg.reason = reason;\n }\n}\n\nfunction applyStopDecision(\n agg: AggregatedHookResult,\n decision: StopDecision,\n reason: string | undefined\n): void {\n if (decision === 'block') {\n if (agg.stopDecision === 'block') {\n return;\n }\n agg.stopDecision = 'block';\n agg.reason = reason;\n return;\n }\n if (agg.stopDecision === undefined) {\n agg.stopDecision = 'continue';\n if (agg.reason === undefined) {\n agg.reason = reason;\n }\n }\n}\n\nfunction applyDecision(agg: AggregatedHookResult, output: HookOutput): void {\n if (!('decision' in output) || output.decision === undefined) {\n return;\n }\n const decision = output.decision;\n const reason =\n 'reason' in output && typeof output.reason === 'string'\n ? output.reason\n : undefined;\n if (decision === 'deny' || decision === 'ask' || decision === 'allow') {\n applyToolDecision(agg, decision, reason);\n return;\n }\n applyStopDecision(agg, decision, reason);\n}\n\nfunction applyContext(agg: AggregatedHookResult, output: HookOutput): void {\n if (\n typeof output.additionalContext === 'string' &&\n output.additionalContext.length > 0\n ) {\n agg.additionalContexts.push(output.additionalContext);\n }\n}\n\nfunction applyInjectedMessages(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (\n output.injectedMessages === undefined ||\n output.injectedMessages.length === 0\n ) {\n return;\n }\n agg.injectedMessages.push(...output.injectedMessages);\n}\n\nfunction applyStopFlag(agg: AggregatedHookResult, output: HookOutput): void {\n if (output.preventContinuation !== true) {\n return;\n }\n agg.preventContinuation = true;\n if (typeof output.stopReason === 'string' && agg.stopReason === undefined) {\n agg.stopReason = output.stopReason;\n }\n}\n\nfunction applyUpdatedInput(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (!('updatedInput' in output) || output.updatedInput === undefined) {\n return;\n }\n agg.updatedInput = output.updatedInput;\n}\n\nfunction applyUpdatedOutput(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (!('updatedOutput' in output) || output.updatedOutput === undefined) {\n return;\n }\n agg.updatedOutput = output.updatedOutput;\n}\n\nfunction applyAllowedDecisions(\n agg: AggregatedHookResult,\n output: HookOutput\n): void {\n if (\n !('allowedDecisions' in output) ||\n output.allowedDecisions === undefined\n ) {\n return;\n }\n agg.allowedDecisions = output.allowedDecisions;\n}\n\nfunction fold(outcomes: readonly HookOutcome[]): AggregatedHookResult {\n const agg = freshResult();\n for (const outcome of outcomes) {\n if (outcome.error !== null) {\n if (outcome.matcher.internal !== true) {\n agg.errors.push(outcome.error);\n }\n continue;\n }\n const output = outcome.output;\n if (output === null) {\n continue;\n }\n /**\n * Skip fire-and-forget outputs entirely: the agent has already\n * moved on, so an async hook cannot influence the run. Background\n * work inside the hook body still runs (we don't cancel it), it\n * just doesn't fold into the aggregate result.\n */\n if (output.async === true) {\n continue;\n }\n applyContext(agg, output);\n applyInjectedMessages(agg, output);\n applyStopFlag(agg, output);\n applyDecision(agg, output);\n applyUpdatedInput(agg, output);\n applyUpdatedOutput(agg, output);\n applyAllowedDecisions(agg, output);\n }\n return agg;\n}\n\n/**\n * Fires every matcher registered against `input.hook_event_name`, folding\n * their results per `deny > ask > allow` precedence and accumulating\n * context/errors.\n *\n * ## Parallelism and determinism\n *\n * All matching hooks fire simultaneously and are awaited via `Promise.all`,\n * which preserves input-array order in its returned results. The fold\n * therefore iterates outcomes in **registration order** — outer loop over\n * matchers as they sit in the registry (global first, then session), inner\n * loop over each matcher's `hooks` array. Last-writer-wins fields\n * (`updatedInput`, `updatedOutput`) are deterministic in that order, even\n * though hooks may complete in arbitrary wall-clock order.\n *\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput`/`updatedOutput` to one hook per matcher to avoid subtle\n * precedence bugs when matchers are added in a different order than\n * expected.\n *\n * ## Timeouts and cancellation\n *\n * Each matcher receives **one shared `AbortSignal`** derived from the\n * caller's parent signal combined with `matcher.timeout` (falling back to\n * `opts.timeoutMs`, default {@link DEFAULT_HOOK_TIMEOUT_MS}). Sharing the\n * signal across hooks in a matcher collapses N timer allocations into\n * one, which matters on the PreToolUse hot path where a matcher with\n * several hooks fires on every tool call. Each hook call is raced\n * against the shared signal, so even a hook that ignores the signal is\n * force-unblocked when the timeout fires. Timeout/abort errors are\n * swallowed into the aggregated result's `errors` array (non-fatal by\n * default).\n *\n * ## Internal matchers\n *\n * A matcher with `internal: true` is excluded from both the `errors` array\n * and the logger output. Use it for infrastructure hooks whose failures\n * should not pollute user-visible diagnostics.\n *\n * ## Once semantics — atomic at-most-once\n *\n * A matcher with `once: true` is removed from the registry **before any\n * hook runs**, inside the synchronous prefix of `executeHooks` (between\n * `getMatchers` and the first `await`). Because Node's event loop serialises\n * sync work, two concurrent `executeHooks` calls can never both observe\n * and dispatch the same `once` matcher — whichever call runs its sync\n * prefix first consumes it, and the loser sees an empty bucket.\n *\n * Trade-off: if every hook in a `once` matcher throws, the matcher is\n * still gone. \"Once\" here means \"at most one dispatch, ever\", not \"at\n * most one successful execution with retry on failure\". Hosts that need\n * retry semantics should register a normal matcher and self-unregister\n * via the `unregister` callback returned from `registry.register`.\n */\nexport async function executeHooks(\n opts: ExecuteHooksOptions\n): Promise<AggregatedHookResult> {\n const {\n registry,\n input,\n sessionId,\n matchQuery,\n signal,\n timeoutMs = DEFAULT_HOOK_TIMEOUT_MS,\n logger,\n } = opts;\n const event = input.hook_event_name;\n const matchers = registry.getMatchers(event, sessionId);\n if (matchers.length === 0) {\n return freshResult();\n }\n\n // --- SYNC CRITICAL SECTION: once-matcher removal must complete before any await ---\n const tasks: Promise<HookOutcome[]>[] = [];\n for (const matcher of matchers) {\n if (!matchesQuery(matcher.pattern, matchQuery)) {\n continue;\n }\n if (matcher.once === true) {\n registry.removeMatcher(event, matcher, sessionId);\n }\n if (matcher.hooks.length === 0) {\n continue;\n }\n const perHookTimeout = matcher.timeout ?? timeoutMs;\n const matcherSignal = combineSignals(signal, perHookTimeout);\n tasks.push(runMatcherHooks(matcher, input, matcherSignal));\n }\n // --- END SYNC CRITICAL SECTION ---\n if (tasks.length === 0) {\n return freshResult();\n }\n\n const outcomes = (await Promise.all(tasks)).flat();\n reportErrors(outcomes, event, logger);\n const aggregated = fold(outcomes);\n /**\n * Centralized `preventContinuation` propagation: when any hook (across\n * any callsite — RunStart, PreToolUse, PostToolBatch, SubagentStop,\n * etc.) returns `preventContinuation: true`, raise a halt signal on\n * the registry scoped to the run's `sessionId`. `Run.processStream`\n * polls the signal between stream events using its own id and exits\n * cleanly, skipping the `Stop` hook (since the run is being halted,\n * not naturally completing).\n *\n * First-write-wins per session inside the registry — a halt already\n * raised by an earlier hook in the same run is preserved so the\n * original `reason` / `source` are not clobbered. Hooks fired\n * without a `sessionId` cannot raise a halt (there's no run for the\n * loop to poll under), which is fine: every in-tree callsite passes\n * `sessionId: runId`. Pre-stream callsites in `Run.processStream`\n * still read `preventContinuation` directly off the result for an\n * early return because they have not yet entered the stream loop.\n */\n if (aggregated.preventContinuation === true && sessionId !== undefined) {\n registry.haltRun(\n sessionId,\n aggregated.stopReason ?? 'preventContinuation',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,QAAQ,cAAc,KAAA,GAC3D,SAAS,QACP,WACA,WAAW,cAAc,uBACzB,KACF;CAEF,OAAO;AACT"}
|
package/dist/cjs/hooks/index.cjs
CHANGED
|
@@ -4,3 +4,15 @@ require("./executeHooks.cjs");
|
|
|
4
4
|
require("./createToolPolicyHook.cjs");
|
|
5
5
|
require("./createWorkspacePolicyHook.cjs");
|
|
6
6
|
require("./types.cjs");
|
|
7
|
+
//#region src/hooks/index.ts
|
|
8
|
+
/**
|
|
9
|
+
* Feature probe for hosts: hook outputs support `injectedMessages`
|
|
10
|
+
* (per-message graph-state injection at the `PostToolBatch` boundary).
|
|
11
|
+
* Hosts must gate drain-style hooks on this so a queued message can never
|
|
12
|
+
* be consumed by an SDK version that would silently drop it.
|
|
13
|
+
*/
|
|
14
|
+
const HOOK_INJECTED_MESSAGES_CAPABLE = true;
|
|
15
|
+
//#endregion
|
|
16
|
+
exports.HOOK_INJECTED_MESSAGES_CAPABLE = HOOK_INJECTED_MESSAGES_CAPABLE;
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/hooks/index.ts"],"sourcesContent":["// src/hooks/index.ts\n//\n// Hook lifecycle system for `@librechat/agents`. Re-exported from\n// `src/index.ts` and consumed by `Run.processStream` (RunStart,\n// UserPromptSubmit, Stop, StopFailure), `ToolNode.dispatchToolEvents`\n// (PreToolUse, PostToolUse, PostToolUseFailure, PermissionDenied),\n// `createSummarizeNode` (PreCompact, PostCompact), and\n// `SubagentExecutor.execute` (SubagentStart, SubagentStop).\nexport { HookRegistry } from './HookRegistry';\nexport type { HookHaltSignal } from './HookRegistry';\nexport { executeHooks, DEFAULT_HOOK_TIMEOUT_MS } from './executeHooks';\n/**\n * Feature probe for hosts: hook outputs support `injectedMessages`\n * (per-message graph-state injection at the `PostToolBatch` boundary).\n * Hosts must gate drain-style hooks on this so a queued message can never\n * be consumed by an SDK version that would silently drop it.\n */\nexport const HOOK_INJECTED_MESSAGES_CAPABLE = true;\nexport {\n matchesQuery,\n hasNestedQuantifier,\n MAX_PATTERN_LENGTH,\n MAX_CACHE_SIZE,\n} from './matchers';\nexport { createToolPolicyHook } from './createToolPolicyHook';\nexport type { ToolPolicyMode, ToolPolicyConfig } from './createToolPolicyHook';\nexport { createWorkspacePolicyHook } from './createWorkspacePolicyHook';\nexport type {\n OutsideAccessPolicy,\n WorkspacePolicyConfig,\n PathExtractor,\n} from './createWorkspacePolicyHook';\nexport { HOOK_EVENTS } from './types';\nexport type {\n HookEvent,\n HookInput,\n HookOutput,\n HookCallback,\n HookMatcher,\n HooksByEvent,\n HookInputByEvent,\n HookOutputByEvent,\n BaseHookInput,\n BaseHookOutput,\n ToolDecision,\n StopDecision,\n AggregatedHookResult,\n RunStartHookInput,\n UserPromptSubmitHookInput,\n PreToolUseHookInput,\n PostToolUseHookInput,\n PostToolUseFailureHookInput,\n PostToolBatchHookInput,\n PostToolBatchEntry,\n PermissionDeniedHookInput,\n SubagentStartHookInput,\n SubagentStopHookInput,\n StopHookInput,\n StopFailureHookInput,\n PreCompactHookInput,\n PostCompactHookInput,\n RunStartHookOutput,\n UserPromptSubmitHookOutput,\n PreToolUseHookOutput,\n PostToolUseHookOutput,\n PostToolUseFailureHookOutput,\n PostToolBatchHookOutput,\n PermissionDeniedHookOutput,\n SubagentStartHookOutput,\n SubagentStopHookOutput,\n StopHookOutput,\n StopFailureHookOutput,\n PreCompactHookOutput,\n PostCompactHookOutput,\n} from './types';\nexport type { ExecuteHooksOptions } from './executeHooks';\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAa,iCAAiC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","names":[],"sources":["../../../src/hooks/types.ts"],"sourcesContent":["// src/hooks/types.ts\nimport type { BaseMessage } from '@langchain/core/messages';\n\n/**\n * Closed set of hook lifecycle events supported by the hooks system.\n *\n * These mirror the subset of Claude Code's event surface that makes sense\n * for a library context (no filesystem/CLI-specific events). See\n * `docs/hooks-design-report.md` §3.2 for the mapping to existing\n * `@librechat/agents` emission points.\n */\nexport const HOOK_EVENTS = [\n 'RunStart',\n 'UserPromptSubmit',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PostToolBatch',\n 'PermissionDenied',\n 'SubagentStart',\n 'SubagentStop',\n 'Stop',\n 'StopFailure',\n 'PreCompact',\n 'PostCompact',\n] as const;\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** Tool-gating decision; executeHooks folds with `deny > ask > allow` precedence. */\nexport type ToolDecision = 'allow' | 'deny' | 'ask';\n\n/** Stop-loop decision; `block` means \"do not stop, run another turn\". Any `block` wins. */\nexport type StopDecision = 'continue' | 'block';\n\n/**\n * Fields shared by every `HookInput`. Discriminated by `hook_event_name`.\n *\n * - `runId` identifies the current agent run and is always present.\n * - `threadId` identifies the conversation thread when the host has one.\n * - `agentId` is only set when the hook fires inside a subagent scope.\n * - `executingAgentId` identifies the agent that owns the node emitting the hook,\n * whenever the graph knows it — including top-level agents in a multi-agent\n * graph (where `agentId` is intentionally undefined). Use this to attribute a\n * hook to a specific agent regardless of subagent scope.\n */\nexport interface BaseHookInput {\n runId: string;\n threadId?: string;\n agentId?: string;\n executingAgentId?: string;\n}\n\nexport interface RunStartHookInput extends BaseHookInput {\n hook_event_name: 'RunStart';\n messages: BaseMessage[];\n}\n\nexport interface UserPromptSubmitHookInput extends BaseHookInput {\n hook_event_name: 'UserPromptSubmit';\n prompt: string;\n attachments?: BaseMessage[];\n}\n\n/**\n * Fires before a tool is invoked. Hook may return `deny`/`ask`/`allow` and/or\n * an `updatedInput` that replaces the tool arguments before invocation.\n *\n * `toolInput` is intentionally typed as `Record<string, unknown>` because the\n * SDK is tool-agnostic — concrete tool argument shapes are only known at the\n * call site and are narrowed by the host. This is the one escape hatch in\n * the hook type system.\n */\nexport interface PreToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PreToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n /**\n * Number of times this tool has been invoked in prior batches within the\n * current run. Within a single batch of parallel calls, all calls to the\n * same tool share the same turn value — per-call discrimination within a\n * batch is not supported in v1.\n */\n turn?: number;\n}\n\nexport interface PostToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PostToolUseFailureHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUseFailure';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n error: string;\n stepId?: string;\n turn?: number;\n}\n\n/**\n * Per-tool result snapshot included in a `PostToolBatch` event. Mirrors\n * the data PostToolUse / PostToolUseFailure get individually, but the\n * batch view lets a single hook see the whole set so it can inject one\n * consolidated convention/audit message rather than N per-tool ones.\n */\nexport interface PostToolBatchEntry {\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n /** Successful tool output, present only when `status === 'success'`. */\n toolOutput?: unknown;\n /** Error message, present only when `status === 'error'`. */\n error?: string;\n status: 'success' | 'error';\n}\n\n/**\n * Fires once after every tool call in a single batch finishes (including\n * any that were rejected via HITL). Lets a hook react to the batch as a\n * whole — useful for \"inject conventions once for the whole batch\", batch\n * audit logging, or coordinating cleanup that depends on knowing the full\n * result set rather than streaming each tool's result independently.\n *\n * Order: fires AFTER all per-tool PostToolUse / PostToolUseFailure hooks\n * for the same batch have completed, BEFORE the next model call. Pass an\n * `additionalContext` to inject context for that next model turn.\n */\nexport interface PostToolBatchHookInput extends BaseHookInput {\n hook_event_name: 'PostToolBatch';\n /** All tool calls (and their outcomes) from this batch, in batch order. */\n entries: PostToolBatchEntry[];\n}\n\nexport interface PermissionDeniedHookInput extends BaseHookInput {\n hook_event_name: 'PermissionDenied';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n reason: string;\n}\n\nexport interface SubagentStartHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStart';\n parentAgentId?: string;\n agentId: string;\n agentType: string;\n inputs: BaseMessage[];\n}\n\nexport interface SubagentStopHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStop';\n agentId: string;\n agentType: string;\n messages: BaseMessage[];\n}\n\nexport interface StopHookInput extends BaseHookInput {\n hook_event_name: 'Stop';\n messages: BaseMessage[];\n stopReason?: string;\n stopHookActive: boolean;\n}\n\nexport interface StopFailureHookInput extends BaseHookInput {\n hook_event_name: 'StopFailure';\n error: string;\n lastAssistantMessage?: BaseMessage;\n}\n\nexport interface PreCompactHookInput extends BaseHookInput {\n hook_event_name: 'PreCompact';\n messagesBeforeCount: number;\n /**\n * What triggered compaction. Matches `SummarizationTrigger.type` from the\n * agent's summarization config. `'default'` means no trigger was\n * configured and compaction fired because messages were pruned.\n */\n trigger:\n | 'token_ratio'\n | 'remaining_tokens'\n | 'messages_to_refine'\n | 'default'\n | (string & {});\n}\n\nexport interface PostCompactHookInput extends BaseHookInput {\n hook_event_name: 'PostCompact';\n summary: string;\n /**\n * Number of messages remaining after compaction. The summarize node\n * returns a `removeAll` signal that clears all messages from state;\n * the summary itself is injected into the system prompt, not as a\n * message. This is `0` at the point of hook dispatch.\n */\n messagesAfterCount: number;\n}\n\n/** Discriminated union of every hook input shape. */\nexport type HookInput =\n | RunStartHookInput\n | UserPromptSubmitHookInput\n | PreToolUseHookInput\n | PostToolUseHookInput\n | PostToolUseFailureHookInput\n | PostToolBatchHookInput\n | PermissionDeniedHookInput\n | SubagentStartHookInput\n | SubagentStopHookInput\n | StopHookInput\n | StopFailureHookInput\n | PreCompactHookInput\n | PostCompactHookInput;\n\n/** Compile-time map from event name to its input shape. */\nexport type HookInputByEvent = {\n RunStart: RunStartHookInput;\n UserPromptSubmit: UserPromptSubmitHookInput;\n PreToolUse: PreToolUseHookInput;\n PostToolUse: PostToolUseHookInput;\n PostToolUseFailure: PostToolUseFailureHookInput;\n PostToolBatch: PostToolBatchHookInput;\n PermissionDenied: PermissionDeniedHookInput;\n SubagentStart: SubagentStartHookInput;\n SubagentStop: SubagentStopHookInput;\n Stop: StopHookInput;\n StopFailure: StopFailureHookInput;\n PreCompact: PreCompactHookInput;\n PostCompact: PostCompactHookInput;\n};\n\n/**\n * Fields common to every hook output. Hooks that have nothing to say simply\n * return `{}` (or omit the fields below).\n */\nexport interface BaseHookOutput {\n /** Context string to inject into the conversation. Accumulated across hooks. */\n additionalContext?: string;\n /** True to prevent the next model turn. Any hook can set this. */\n preventContinuation?: boolean;\n /** Reason reported alongside `preventContinuation`. */\n stopReason?: string;\n /**\n * Marks this hook output as fire-and-forget for INFLUENCE only.\n * When `true`, the SDK skips every other field on this output —\n * `decision`, `additionalContext`, `updatedInput`,\n * `preventContinuation`, `allowedDecisions`, `updatedOutput` are\n * all ignored. The hook's return value cannot block, modify, or\n * inject context, so it's safe to use for pure side effects\n * (logging, metrics, webhooks).\n *\n * Important caveat: the hook's CALLBACK promise is still awaited\n * by `executeHooks` (subject to the matcher's timeout and the\n * default `DEFAULT_HOOK_TIMEOUT_MS`). The SDK does not\n * speculatively detach hooks based on output shape, because the\n * shape is only known after the promise resolves. For TRUE\n * fire-and-forget where the agent doesn't wait at all, the hook\n * body should detach its side effect itself and return\n * immediately:\n *\n * @example\n * ```ts\n * async (input) => {\n * // Detach the slow work — the SDK awaits this hook's\n * // returned promise, which resolves immediately because we\n * // don't `await` the side effect.\n * void sendToLoggingService(input).catch(console.error);\n * return { async: true };\n * };\n * ```\n *\n * @example WRONG — the agent will block on the webhook\n * ```ts\n * async (input) => {\n * await sendToLoggingService(input); // ← awaited, blocks\n * return { async: true }; // returning async:true doesn't undo the await\n * };\n * ```\n *\n * Mirrors Claude Code Agent SDK's `async` output, with the same\n * \"detach inside the hook body\" pattern.\n */\n async?: boolean;\n /**\n * Optional advisory timeout in milliseconds for the background work\n * a host has detached inside an `async: true` hook body. The SDK\n * does not enforce this (the hook's own AbortSignal handling does)\n * but the field is preserved on the wire so downstream\n * observability can surface long-running side effects. Ignored\n * unless `async` is true.\n */\n asyncTimeout?: number;\n}\n\nexport type RunStartHookOutput = BaseHookOutput;\n\nexport interface UserPromptSubmitHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport interface PreToolUseHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n /**\n * Replacement tool input. Merged into the pending tool call by the host.\n *\n * When multiple hooks set `updatedInput` within a single `executeHooks`\n * call, the last writer in registration order wins (outer loop: matcher\n * registration order; inner loop: hook position within the matcher). The\n * winner is deterministic — `Promise.all` preserves input-array order.\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput` to one hook per matcher to avoid confusing precedence.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Restricts which decisions the host UI is allowed to surface for this\n * tool call when the hook returns `decision: 'ask'`. Pass to lock a\n * tool down to a subset of `'approve' | 'reject' | 'edit' | 'respond'`\n * — for example, `['approve', 'reject']` to forbid the user from\n * editing the tool's args or substituting a custom response.\n *\n * The values flow into the resulting interrupt's\n * `review_configs[i].allowed_decisions`. Omitting the field keeps the\n * SDK default (all four decisions advertised). Last-writer-wins in\n * registration order, same precedence rules as `updatedInput`.\n */\n allowedDecisions?: ReadonlyArray<'approve' | 'reject' | 'edit' | 'respond'>;\n}\n\nexport interface PostToolUseHookOutput extends BaseHookOutput {\n /**\n * Replacement tool output. Flows through the aggregated result so the\n * host can substitute it before appending the tool result message.\n * Ordering semantics match `PreToolUseHookOutput.updatedInput`:\n * last-writer-wins in registration order.\n */\n updatedOutput?: unknown;\n}\n\nexport type PostToolUseFailureHookOutput = BaseHookOutput;\n\nexport type PostToolBatchHookOutput = BaseHookOutput;\n\nexport type PermissionDeniedHookOutput = BaseHookOutput;\n\nexport interface SubagentStartHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport type SubagentStopHookOutput = BaseHookOutput;\n\nexport interface StopHookOutput extends BaseHookOutput {\n decision?: StopDecision;\n reason?: string;\n}\n\nexport type StopFailureHookOutput = BaseHookOutput;\n\nexport type PreCompactHookOutput = BaseHookOutput;\n\nexport type PostCompactHookOutput = BaseHookOutput;\n\n/** Compile-time map from event name to its output shape. */\nexport type HookOutputByEvent = {\n RunStart: RunStartHookOutput;\n UserPromptSubmit: UserPromptSubmitHookOutput;\n PreToolUse: PreToolUseHookOutput;\n PostToolUse: PostToolUseHookOutput;\n PostToolUseFailure: PostToolUseFailureHookOutput;\n PostToolBatch: PostToolBatchHookOutput;\n PermissionDenied: PermissionDeniedHookOutput;\n SubagentStart: SubagentStartHookOutput;\n SubagentStop: SubagentStopHookOutput;\n Stop: StopHookOutput;\n StopFailure: StopFailureHookOutput;\n PreCompact: PreCompactHookOutput;\n PostCompact: PostCompactHookOutput;\n};\n\n/** Superset output shape used by the executor's fold loop. */\nexport type HookOutput =\n | RunStartHookOutput\n | UserPromptSubmitHookOutput\n | PreToolUseHookOutput\n | PostToolUseHookOutput\n | PostToolUseFailureHookOutput\n | PostToolBatchHookOutput\n | PermissionDeniedHookOutput\n | SubagentStartHookOutput\n | SubagentStopHookOutput\n | StopHookOutput\n | StopFailureHookOutput\n | PreCompactHookOutput\n | PostCompactHookOutput;\n\n/**\n * A hook callback is a plain async function registered against a specific\n * event. The `signal` is always supplied by `executeHooks` and combines the\n * batch's parent signal with the per-hook timeout — callbacks that perform\n * long-running work should observe it.\n */\nexport type HookCallback<E extends HookEvent = HookEvent> = (\n input: HookInputByEvent[E],\n signal: AbortSignal\n) => HookOutputByEvent[E] | Promise<HookOutputByEvent[E]>;\n\n/**\n * A matcher groups one or more callbacks under a shared regex filter and\n * shared timeout/once/internal flags. The generic `E` ties the callback\n * types to the event the matcher is registered against.\n */\nexport interface HookMatcher<E extends HookEvent = HookEvent> {\n /**\n * Regex pattern matched against the event's primary query string (e.g.\n * the tool name for `PreToolUse`, the agent type for `SubagentStart`).\n *\n * Omitted or empty means \"always match\". For events that do not supply a\n * query string (`RunStart`, `Stop`, etc.), only wildcard matchers fire —\n * a non-empty pattern on such events will never match.\n *\n * Patterns are treated as trusted input: `executeHooks` compiles them\n * with `new RegExp(pattern)` without any sandbox, and a pathological\n * pattern can block the event loop. Host registration code is expected\n * to validate or length-bound patterns that originate from user input.\n */\n pattern?: string;\n /** Callbacks that fire when the matcher hits. Executed in parallel. */\n hooks: HookCallback<E>[];\n /** Per-matcher timeout in ms. Defaults to the executor's batch timeout. */\n timeout?: number;\n /**\n * Atomically remove the matcher before its first dispatch.\n *\n * `executeHooks` claims `once: true` matchers synchronously — between\n * `getMatchers` and its first `await` — so two concurrent calls cannot\n * both dispatch the same matcher. Whichever call runs its sync prefix\n * first wins the matcher; the other sees an empty bucket.\n *\n * Semantics are \"at most one dispatch, ever\" — if every hook in the\n * matcher throws, the matcher is still gone. Use `once` for\n * fire-and-forget bootstrapping (registration, telemetry, setup). Hosts\n * that need retry semantics should register a normal matcher and\n * self-unregister via the callback returned from `registry.register`.\n */\n once?: boolean;\n /** Internal hooks are excluded from telemetry and non-fatal error logging. */\n internal?: boolean;\n}\n\n/**\n * Storage shape for matchers keyed by event. Each event's matcher list is\n * a generic array parameterized by that event type, so lookup via\n * `HooksByEvent[E]` preserves type-safe callback signatures.\n */\nexport type HooksByEvent = {\n [E in HookEvent]?: HookMatcher<E>[];\n};\n\n/**\n * Aggregated result of a single `executeHooks` call. Fields are populated\n * according to the fold rules in `executeHooks.ts`.\n */\nexport interface AggregatedHookResult {\n /** Folded tool-gating decision; `deny > ask > allow`. */\n decision?: ToolDecision;\n /** Folded stop decision; any `block` wins. */\n stopDecision?: StopDecision;\n /** Reason from the hook that set the winning decision. */\n reason?: string;\n /**\n * Replacement tool input from a `PreToolUse` hook.\n *\n * Last-writer-wins in **registration order**: `executeHooks` uses\n * `Promise.all`, which preserves input-array order, so the fold iterates\n * outcomes in the same order they were pushed — outer loop over matchers\n * as they sit in the registry, inner loop over each matcher's `hooks`\n * array. The winner is therefore deterministic but may not match the\n * order in which hooks actually completed. Consumers that want a single\n * authoritative rewrite should still register one `updatedInput`-setting\n * hook per matcher to avoid subtle precedence bugs.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Restricted decision set from a `PreToolUse` hook. Same last-writer-wins\n * semantics as `updatedInput`. Surfaces to the interrupt payload's\n * `review_configs[i].allowed_decisions`.\n */\n allowedDecisions?: ReadonlyArray<'approve' | 'reject' | 'edit' | 'respond'>;\n /**\n * Replacement tool output from a `PostToolUse` hook.\n *\n * Same last-writer-wins-in-registration-order semantics as\n * `updatedInput`. Present only when at least one hook set it; `undefined`\n * means \"use the original tool output\".\n */\n updatedOutput?: unknown;\n /** Accumulated `additionalContext` strings from every hook, in order. */\n additionalContexts: string[];\n /** True if any hook returned `preventContinuation`. */\n preventContinuation?: boolean;\n /**\n * Reason recorded alongside `preventContinuation`. First winner wins:\n * once a hook sets both flags, later hooks that also set\n * `preventContinuation` do not overwrite the reason.\n */\n stopReason?: string;\n /** Error messages from hooks that threw; always present (possibly empty). */\n errors: string[];\n}\n"],"mappings":";;;;;;;;;AAWA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"types.cjs","names":[],"sources":["../../../src/hooks/types.ts"],"sourcesContent":["// src/hooks/types.ts\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type { InjectedMessage } from '@/types/tools';\n\n/**\n * Closed set of hook lifecycle events supported by the hooks system.\n *\n * These mirror the subset of Claude Code's event surface that makes sense\n * for a library context (no filesystem/CLI-specific events). See\n * `docs/hooks-design-report.md` §3.2 for the mapping to existing\n * `@librechat/agents` emission points.\n */\nexport const HOOK_EVENTS = [\n 'RunStart',\n 'UserPromptSubmit',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PostToolBatch',\n 'PermissionDenied',\n 'SubagentStart',\n 'SubagentStop',\n 'Stop',\n 'StopFailure',\n 'PreCompact',\n 'PostCompact',\n] as const;\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** Tool-gating decision; executeHooks folds with `deny > ask > allow` precedence. */\nexport type ToolDecision = 'allow' | 'deny' | 'ask';\n\n/** Stop-loop decision; `block` means \"do not stop, run another turn\". Any `block` wins. */\nexport type StopDecision = 'continue' | 'block';\n\n/**\n * Fields shared by every `HookInput`. Discriminated by `hook_event_name`.\n *\n * - `runId` identifies the current agent run and is always present.\n * - `threadId` identifies the conversation thread when the host has one.\n * - `agentId` is only set when the hook fires inside a subagent scope.\n * - `executingAgentId` identifies the agent that owns the node emitting the hook,\n * whenever the graph knows it — including top-level agents in a multi-agent\n * graph (where `agentId` is intentionally undefined). Use this to attribute a\n * hook to a specific agent regardless of subagent scope.\n */\nexport interface BaseHookInput {\n runId: string;\n threadId?: string;\n agentId?: string;\n executingAgentId?: string;\n}\n\nexport interface RunStartHookInput extends BaseHookInput {\n hook_event_name: 'RunStart';\n messages: BaseMessage[];\n}\n\nexport interface UserPromptSubmitHookInput extends BaseHookInput {\n hook_event_name: 'UserPromptSubmit';\n prompt: string;\n attachments?: BaseMessage[];\n}\n\n/**\n * Fires before a tool is invoked. Hook may return `deny`/`ask`/`allow` and/or\n * an `updatedInput` that replaces the tool arguments before invocation.\n *\n * `toolInput` is intentionally typed as `Record<string, unknown>` because the\n * SDK is tool-agnostic — concrete tool argument shapes are only known at the\n * call site and are narrowed by the host. This is the one escape hatch in\n * the hook type system.\n */\nexport interface PreToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PreToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n /**\n * Number of times this tool has been invoked in prior batches within the\n * current run. Within a single batch of parallel calls, all calls to the\n * same tool share the same turn value — per-call discrimination within a\n * batch is not supported in v1.\n */\n turn?: number;\n}\n\nexport interface PostToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PostToolUseFailureHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUseFailure';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n error: string;\n stepId?: string;\n turn?: number;\n}\n\n/**\n * Per-tool result snapshot included in a `PostToolBatch` event. Mirrors\n * the data PostToolUse / PostToolUseFailure get individually, but the\n * batch view lets a single hook see the whole set so it can inject one\n * consolidated convention/audit message rather than N per-tool ones.\n */\nexport interface PostToolBatchEntry {\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n /** Successful tool output, present only when `status === 'success'`. */\n toolOutput?: unknown;\n /** Error message, present only when `status === 'error'`. */\n error?: string;\n status: 'success' | 'error';\n}\n\n/**\n * Fires once after every tool call in a single batch finishes (including\n * any that were rejected via HITL). Lets a hook react to the batch as a\n * whole — useful for \"inject conventions once for the whole batch\", batch\n * audit logging, or coordinating cleanup that depends on knowing the full\n * result set rather than streaming each tool's result independently.\n *\n * Order: fires AFTER all per-tool PostToolUse / PostToolUseFailure hooks\n * for the same batch have completed, BEFORE the next model call. Pass an\n * `additionalContext` to inject context for that next model turn, or\n * `injectedMessages` to inject standalone per-message user speech (e.g.\n * mid-run steering) that must not be consolidated with hook context.\n */\nexport interface PostToolBatchHookInput extends BaseHookInput {\n hook_event_name: 'PostToolBatch';\n /** All tool calls (and their outcomes) from this batch, in batch order. */\n entries: PostToolBatchEntry[];\n}\n\nexport interface PermissionDeniedHookInput extends BaseHookInput {\n hook_event_name: 'PermissionDenied';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n reason: string;\n}\n\nexport interface SubagentStartHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStart';\n parentAgentId?: string;\n agentId: string;\n agentType: string;\n inputs: BaseMessage[];\n}\n\nexport interface SubagentStopHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStop';\n agentId: string;\n agentType: string;\n messages: BaseMessage[];\n}\n\nexport interface StopHookInput extends BaseHookInput {\n hook_event_name: 'Stop';\n messages: BaseMessage[];\n stopReason?: string;\n stopHookActive: boolean;\n}\n\nexport interface StopFailureHookInput extends BaseHookInput {\n hook_event_name: 'StopFailure';\n error: string;\n lastAssistantMessage?: BaseMessage;\n}\n\nexport interface PreCompactHookInput extends BaseHookInput {\n hook_event_name: 'PreCompact';\n messagesBeforeCount: number;\n /**\n * What triggered compaction. Matches `SummarizationTrigger.type` from the\n * agent's summarization config. `'default'` means no trigger was\n * configured and compaction fired because messages were pruned.\n */\n trigger:\n | 'token_ratio'\n | 'remaining_tokens'\n | 'messages_to_refine'\n | 'default'\n | (string & {});\n}\n\nexport interface PostCompactHookInput extends BaseHookInput {\n hook_event_name: 'PostCompact';\n summary: string;\n /**\n * Number of messages remaining after compaction. The summarize node\n * returns a `removeAll` signal that clears all messages from state;\n * the summary itself is injected into the system prompt, not as a\n * message. This is `0` at the point of hook dispatch.\n */\n messagesAfterCount: number;\n}\n\n/** Discriminated union of every hook input shape. */\nexport type HookInput =\n | RunStartHookInput\n | UserPromptSubmitHookInput\n | PreToolUseHookInput\n | PostToolUseHookInput\n | PostToolUseFailureHookInput\n | PostToolBatchHookInput\n | PermissionDeniedHookInput\n | SubagentStartHookInput\n | SubagentStopHookInput\n | StopHookInput\n | StopFailureHookInput\n | PreCompactHookInput\n | PostCompactHookInput;\n\n/** Compile-time map from event name to its input shape. */\nexport type HookInputByEvent = {\n RunStart: RunStartHookInput;\n UserPromptSubmit: UserPromptSubmitHookInput;\n PreToolUse: PreToolUseHookInput;\n PostToolUse: PostToolUseHookInput;\n PostToolUseFailure: PostToolUseFailureHookInput;\n PostToolBatch: PostToolBatchHookInput;\n PermissionDenied: PermissionDeniedHookInput;\n SubagentStart: SubagentStartHookInput;\n SubagentStop: SubagentStopHookInput;\n Stop: StopHookInput;\n StopFailure: StopFailureHookInput;\n PreCompact: PreCompactHookInput;\n PostCompact: PostCompactHookInput;\n};\n\n/**\n * Fields common to every hook output. Hooks that have nothing to say simply\n * return `{}` (or omit the fields below).\n */\nexport interface BaseHookOutput {\n /** Context string to inject into the conversation. Accumulated across hooks. */\n additionalContext?: string;\n /**\n * Messages to inject into graph state, one `HumanMessage` per entry\n * (converted via `ToolNode.convertInjectedMessages`, which preserves\n * `role`/`source`/`isMeta` in `additional_kwargs`). Unlike\n * `additionalContext` — which is consolidated across hooks into a single\n * system-flavored message — each entry keeps its own identity and role,\n * making this the channel for injecting verbatim user speech (e.g. a\n * mid-run steering message). Accumulated across hooks in registration\n * order. Currently consumed only at the `PostToolBatch` dispatch site;\n * other events ignore the field.\n */\n injectedMessages?: InjectedMessage[];\n /** True to prevent the next model turn. Any hook can set this. */\n preventContinuation?: boolean;\n /** Reason reported alongside `preventContinuation`. */\n stopReason?: string;\n /**\n * Marks this hook output as fire-and-forget for INFLUENCE only.\n * When `true`, the SDK skips every other field on this output —\n * `decision`, `additionalContext`, `updatedInput`,\n * `preventContinuation`, `allowedDecisions`, `updatedOutput` are\n * all ignored. The hook's return value cannot block, modify, or\n * inject context, so it's safe to use for pure side effects\n * (logging, metrics, webhooks).\n *\n * Important caveat: the hook's CALLBACK promise is still awaited\n * by `executeHooks` (subject to the matcher's timeout and the\n * default `DEFAULT_HOOK_TIMEOUT_MS`). The SDK does not\n * speculatively detach hooks based on output shape, because the\n * shape is only known after the promise resolves. For TRUE\n * fire-and-forget where the agent doesn't wait at all, the hook\n * body should detach its side effect itself and return\n * immediately:\n *\n * @example\n * ```ts\n * async (input) => {\n * // Detach the slow work — the SDK awaits this hook's\n * // returned promise, which resolves immediately because we\n * // don't `await` the side effect.\n * void sendToLoggingService(input).catch(console.error);\n * return { async: true };\n * };\n * ```\n *\n * @example WRONG — the agent will block on the webhook\n * ```ts\n * async (input) => {\n * await sendToLoggingService(input); // ← awaited, blocks\n * return { async: true }; // returning async:true doesn't undo the await\n * };\n * ```\n *\n * Mirrors Claude Code Agent SDK's `async` output, with the same\n * \"detach inside the hook body\" pattern.\n */\n async?: boolean;\n /**\n * Optional advisory timeout in milliseconds for the background work\n * a host has detached inside an `async: true` hook body. The SDK\n * does not enforce this (the hook's own AbortSignal handling does)\n * but the field is preserved on the wire so downstream\n * observability can surface long-running side effects. Ignored\n * unless `async` is true.\n */\n asyncTimeout?: number;\n}\n\nexport type RunStartHookOutput = BaseHookOutput;\n\nexport interface UserPromptSubmitHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport interface PreToolUseHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n /**\n * Replacement tool input. Merged into the pending tool call by the host.\n *\n * When multiple hooks set `updatedInput` within a single `executeHooks`\n * call, the last writer in registration order wins (outer loop: matcher\n * registration order; inner loop: hook position within the matcher). The\n * winner is deterministic — `Promise.all` preserves input-array order.\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput` to one hook per matcher to avoid confusing precedence.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Restricts which decisions the host UI is allowed to surface for this\n * tool call when the hook returns `decision: 'ask'`. Pass to lock a\n * tool down to a subset of `'approve' | 'reject' | 'edit' | 'respond'`\n * — for example, `['approve', 'reject']` to forbid the user from\n * editing the tool's args or substituting a custom response.\n *\n * The values flow into the resulting interrupt's\n * `review_configs[i].allowed_decisions`. Omitting the field keeps the\n * SDK default (all four decisions advertised). Last-writer-wins in\n * registration order, same precedence rules as `updatedInput`.\n */\n allowedDecisions?: ReadonlyArray<'approve' | 'reject' | 'edit' | 'respond'>;\n}\n\nexport interface PostToolUseHookOutput extends BaseHookOutput {\n /**\n * Replacement tool output. Flows through the aggregated result so the\n * host can substitute it before appending the tool result message.\n * Ordering semantics match `PreToolUseHookOutput.updatedInput`:\n * last-writer-wins in registration order.\n */\n updatedOutput?: unknown;\n}\n\nexport type PostToolUseFailureHookOutput = BaseHookOutput;\n\nexport type PostToolBatchHookOutput = BaseHookOutput;\n\nexport type PermissionDeniedHookOutput = BaseHookOutput;\n\nexport interface SubagentStartHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport type SubagentStopHookOutput = BaseHookOutput;\n\nexport interface StopHookOutput extends BaseHookOutput {\n decision?: StopDecision;\n reason?: string;\n}\n\nexport type StopFailureHookOutput = BaseHookOutput;\n\nexport type PreCompactHookOutput = BaseHookOutput;\n\nexport type PostCompactHookOutput = BaseHookOutput;\n\n/** Compile-time map from event name to its output shape. */\nexport type HookOutputByEvent = {\n RunStart: RunStartHookOutput;\n UserPromptSubmit: UserPromptSubmitHookOutput;\n PreToolUse: PreToolUseHookOutput;\n PostToolUse: PostToolUseHookOutput;\n PostToolUseFailure: PostToolUseFailureHookOutput;\n PostToolBatch: PostToolBatchHookOutput;\n PermissionDenied: PermissionDeniedHookOutput;\n SubagentStart: SubagentStartHookOutput;\n SubagentStop: SubagentStopHookOutput;\n Stop: StopHookOutput;\n StopFailure: StopFailureHookOutput;\n PreCompact: PreCompactHookOutput;\n PostCompact: PostCompactHookOutput;\n};\n\n/** Superset output shape used by the executor's fold loop. */\nexport type HookOutput =\n | RunStartHookOutput\n | UserPromptSubmitHookOutput\n | PreToolUseHookOutput\n | PostToolUseHookOutput\n | PostToolUseFailureHookOutput\n | PostToolBatchHookOutput\n | PermissionDeniedHookOutput\n | SubagentStartHookOutput\n | SubagentStopHookOutput\n | StopHookOutput\n | StopFailureHookOutput\n | PreCompactHookOutput\n | PostCompactHookOutput;\n\n/**\n * A hook callback is a plain async function registered against a specific\n * event. The `signal` is always supplied by `executeHooks` and combines the\n * batch's parent signal with the per-hook timeout — callbacks that perform\n * long-running work should observe it.\n */\nexport type HookCallback<E extends HookEvent = HookEvent> = (\n input: HookInputByEvent[E],\n signal: AbortSignal\n) => HookOutputByEvent[E] | Promise<HookOutputByEvent[E]>;\n\n/**\n * A matcher groups one or more callbacks under a shared regex filter and\n * shared timeout/once/internal flags. The generic `E` ties the callback\n * types to the event the matcher is registered against.\n */\nexport interface HookMatcher<E extends HookEvent = HookEvent> {\n /**\n * Regex pattern matched against the event's primary query string (e.g.\n * the tool name for `PreToolUse`, the agent type for `SubagentStart`).\n *\n * Omitted or empty means \"always match\". For events that do not supply a\n * query string (`RunStart`, `Stop`, etc.), only wildcard matchers fire —\n * a non-empty pattern on such events will never match.\n *\n * Patterns are treated as trusted input: `executeHooks` compiles them\n * with `new RegExp(pattern)` without any sandbox, and a pathological\n * pattern can block the event loop. Host registration code is expected\n * to validate or length-bound patterns that originate from user input.\n */\n pattern?: string;\n /** Callbacks that fire when the matcher hits. Executed in parallel. */\n hooks: HookCallback<E>[];\n /** Per-matcher timeout in ms. Defaults to the executor's batch timeout. */\n timeout?: number;\n /**\n * Atomically remove the matcher before its first dispatch.\n *\n * `executeHooks` claims `once: true` matchers synchronously — between\n * `getMatchers` and its first `await` — so two concurrent calls cannot\n * both dispatch the same matcher. Whichever call runs its sync prefix\n * first wins the matcher; the other sees an empty bucket.\n *\n * Semantics are \"at most one dispatch, ever\" — if every hook in the\n * matcher throws, the matcher is still gone. Use `once` for\n * fire-and-forget bootstrapping (registration, telemetry, setup). Hosts\n * that need retry semantics should register a normal matcher and\n * self-unregister via the callback returned from `registry.register`.\n */\n once?: boolean;\n /** Internal hooks are excluded from telemetry and non-fatal error logging. */\n internal?: boolean;\n}\n\n/**\n * Storage shape for matchers keyed by event. Each event's matcher list is\n * a generic array parameterized by that event type, so lookup via\n * `HooksByEvent[E]` preserves type-safe callback signatures.\n */\nexport type HooksByEvent = {\n [E in HookEvent]?: HookMatcher<E>[];\n};\n\n/**\n * Aggregated result of a single `executeHooks` call. Fields are populated\n * according to the fold rules in `executeHooks.ts`.\n */\nexport interface AggregatedHookResult {\n /** Folded tool-gating decision; `deny > ask > allow`. */\n decision?: ToolDecision;\n /** Folded stop decision; any `block` wins. */\n stopDecision?: StopDecision;\n /** Reason from the hook that set the winning decision. */\n reason?: string;\n /**\n * Replacement tool input from a `PreToolUse` hook.\n *\n * Last-writer-wins in **registration order**: `executeHooks` uses\n * `Promise.all`, which preserves input-array order, so the fold iterates\n * outcomes in the same order they were pushed — outer loop over matchers\n * as they sit in the registry, inner loop over each matcher's `hooks`\n * array. The winner is therefore deterministic but may not match the\n * order in which hooks actually completed. Consumers that want a single\n * authoritative rewrite should still register one `updatedInput`-setting\n * hook per matcher to avoid subtle precedence bugs.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Restricted decision set from a `PreToolUse` hook. Same last-writer-wins\n * semantics as `updatedInput`. Surfaces to the interrupt payload's\n * `review_configs[i].allowed_decisions`.\n */\n allowedDecisions?: ReadonlyArray<'approve' | 'reject' | 'edit' | 'respond'>;\n /**\n * Replacement tool output from a `PostToolUse` hook.\n *\n * Same last-writer-wins-in-registration-order semantics as\n * `updatedInput`. Present only when at least one hook set it; `undefined`\n * means \"use the original tool output\".\n */\n updatedOutput?: unknown;\n /** Accumulated `additionalContext` strings from every hook, in order. */\n additionalContexts: string[];\n /** Accumulated `injectedMessages` from every hook, in registration order. */\n injectedMessages: InjectedMessage[];\n /** True if any hook returned `preventContinuation`. */\n preventContinuation?: boolean;\n /**\n * Reason recorded alongside `preventContinuation`. First winner wins:\n * once a hook sets both flags, later hooks that also set\n * `preventContinuation` do not overwrite the reason.\n */\n stopReason?: string;\n /** Error messages from hooks that threw; always present (possibly empty). */\n errors: string[];\n}\n"],"mappings":";;;;;;;;;AAYA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
package/dist/cjs/langfuse.cjs
CHANGED
|
@@ -1,11 +1,69 @@
|
|
|
1
1
|
const require_misc = require("./utils/misc.cjs");
|
|
2
2
|
const require_langfuseRuntimeScope = require("./langfuseRuntimeScope.cjs");
|
|
3
|
+
let _langchain_core_messages = require("@langchain/core/messages");
|
|
3
4
|
let _langfuse_langchain = require("@langfuse/langchain");
|
|
4
5
|
let _opentelemetry_api = require("@opentelemetry/api");
|
|
5
6
|
let _langfuse_tracing = require("@langfuse/tracing");
|
|
6
7
|
//#region src/langfuse.ts
|
|
7
8
|
const TRACE_METADATA_MAX_LENGTH = 200;
|
|
8
9
|
const LANGFUSE_FORCE_FLUSH_ON_DISPOSE = "LANGFUSE_FORCE_FLUSH_ON_DISPOSE";
|
|
10
|
+
function getLangfuseBedrockUsage(message) {
|
|
11
|
+
const usageMetadata = message.usage_metadata;
|
|
12
|
+
const bedrockUsage = message.response_metadata.metadata?.usage;
|
|
13
|
+
if (usageMetadata == null || bedrockUsage == null || usageMetadata.input_tokens !== bedrockUsage.inputTokens) return usageMetadata;
|
|
14
|
+
const cacheRead = bedrockUsage.cacheReadInputTokens ?? 0;
|
|
15
|
+
const cacheCreation = bedrockUsage.cacheWriteInputTokens ?? 0;
|
|
16
|
+
if (cacheRead === 0 && cacheCreation === 0) return usageMetadata;
|
|
17
|
+
return {
|
|
18
|
+
...usageMetadata,
|
|
19
|
+
input_tokens: usageMetadata.input_tokens + cacheRead + cacheCreation
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function cloneMessageWithUsage(message, usageMetadata) {
|
|
23
|
+
const fields = {
|
|
24
|
+
content: message.content,
|
|
25
|
+
additional_kwargs: message.additional_kwargs,
|
|
26
|
+
response_metadata: message.response_metadata,
|
|
27
|
+
id: message.id,
|
|
28
|
+
name: message.name,
|
|
29
|
+
tool_calls: message.tool_calls,
|
|
30
|
+
invalid_tool_calls: message.invalid_tool_calls,
|
|
31
|
+
usage_metadata: usageMetadata
|
|
32
|
+
};
|
|
33
|
+
if (message instanceof _langchain_core_messages.AIMessageChunk) return new _langchain_core_messages.AIMessageChunk({
|
|
34
|
+
...fields,
|
|
35
|
+
tool_call_chunks: message.tool_call_chunks
|
|
36
|
+
});
|
|
37
|
+
return new _langchain_core_messages.AIMessage(fields);
|
|
38
|
+
}
|
|
39
|
+
function normalizeGenerationForLangfuse(generation) {
|
|
40
|
+
if (!("message" in generation)) return generation;
|
|
41
|
+
const message = generation.message;
|
|
42
|
+
if (!(message instanceof _langchain_core_messages.AIMessage || message instanceof _langchain_core_messages.AIMessageChunk)) return generation;
|
|
43
|
+
const usageMetadata = getLangfuseBedrockUsage(message);
|
|
44
|
+
if (usageMetadata == null || usageMetadata === message.usage_metadata) return generation;
|
|
45
|
+
return {
|
|
46
|
+
...generation,
|
|
47
|
+
message: cloneMessageWithUsage(message, usageMetadata)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function normalizeBedrockUsageForLangfuse(output) {
|
|
51
|
+
if (output.generations.length === 0) return output;
|
|
52
|
+
const listIndex = output.generations.length - 1;
|
|
53
|
+
const generationList = output.generations[listIndex];
|
|
54
|
+
if (generationList.length === 0) return output;
|
|
55
|
+
const generationIndex = generationList.length - 1;
|
|
56
|
+
const generation = generationList[generationIndex];
|
|
57
|
+
const normalized = normalizeGenerationForLangfuse(generation);
|
|
58
|
+
if (normalized === generation) return output;
|
|
59
|
+
const generations = [...output.generations];
|
|
60
|
+
generations[listIndex] = [...generationList];
|
|
61
|
+
generations[listIndex][generationIndex] = normalized;
|
|
62
|
+
return {
|
|
63
|
+
...output,
|
|
64
|
+
generations
|
|
65
|
+
};
|
|
66
|
+
}
|
|
9
67
|
var ScopedLangfuseCallbackHandler = class extends _langfuse_langchain.CallbackHandler {
|
|
10
68
|
langfuse;
|
|
11
69
|
traceIdSeed;
|
|
@@ -42,6 +100,9 @@ var ScopedLangfuseCallbackHandler = class extends _langfuse_langchain.CallbackHa
|
|
|
42
100
|
handleLLMStart(...args) {
|
|
43
101
|
return this.withRuntimeContext(() => super.handleLLMStart(...args));
|
|
44
102
|
}
|
|
103
|
+
handleLLMEnd(output, runId, parentRunId) {
|
|
104
|
+
return super.handleLLMEnd(normalizeBedrockUsageForLangfuse(output), runId, parentRunId);
|
|
105
|
+
}
|
|
45
106
|
handleToolStart(...args) {
|
|
46
107
|
return this.withRuntimeContext(() => super.handleToolStart(...args));
|
|
47
108
|
}
|
|
@@ -139,7 +200,7 @@ function isLangfuseCallbackHandler(value) {
|
|
|
139
200
|
return value instanceof _langfuse_langchain.CallbackHandler;
|
|
140
201
|
}
|
|
141
202
|
async function disposeLangfuseHandler(value) {
|
|
142
|
-
if (value == null ||
|
|
203
|
+
if (value == null || require_misc.parseBooleanEnv(process.env[LANGFUSE_FORCE_FLUSH_ON_DISPOSE]) !== true) return;
|
|
143
204
|
await (0, _langfuse_tracing.getLangfuseTracerProvider)().forceFlush?.();
|
|
144
205
|
}
|
|
145
206
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"langfuse.cjs","names":["CallbackHandler","otelContext","resolveLangfuseConfigForSpan","withLangfuseRuntimeScope","resolveTraceIdSeedForSpan","isPresent","parseBooleanEnv"],"sources":["../../src/langfuse.ts"],"sourcesContent":["import { CallbackHandler } from '@langfuse/langchain';\nimport { context as otelContext } from '@opentelemetry/api';\nimport {\n getLangfuseTracerProvider,\n propagateAttributes,\n} from '@langfuse/tracing';\nimport type { PropagateAttributesParams } from '@langfuse/tracing';\nimport type * as t from '@/types';\nimport {\n resolveLangfuseConfigForSpan,\n resolveTraceIdSeedForSpan,\n withLangfuseRuntimeScope,\n} from '@/langfuseRuntimeScope';\nimport { isPresent, parseBooleanEnv } from '@/utils/misc';\n\nconst TRACE_METADATA_MAX_LENGTH = 200;\nconst LANGFUSE_FORCE_FLUSH_ON_DISPOSE = 'LANGFUSE_FORCE_FLUSH_ON_DISPOSE';\n\nexport type LangfuseTraceMetadata = Record<string, string>;\nexport type LangfuseTraceAttributes = Record<string, string | number | boolean>;\ntype LangfuseMetadata = NonNullable<t.LangfuseConfig['metadata']>;\ntype LangfuseConfigTraceAttributes = NonNullable<\n t.LangfuseConfig['librechatTraceAttributes']\n>;\n\ntype LangfuseHandlerParams = {\n userId?: string;\n sessionId?: string;\n traceMetadata?: LangfuseTraceMetadata;\n tags?: string[];\n traceIdSeed?: string;\n};\n\ntype AgentLangfuseHandlerParams = LangfuseHandlerParams & {\n langfuse?: t.LangfuseConfig;\n};\n\ntype LangfuseAttributeParams = AgentLangfuseHandlerParams & {\n traceName?: string;\n};\n\ntype FlushableTracerProvider = {\n forceFlush?: () => Promise<void> | void;\n};\n\nclass ScopedLangfuseCallbackHandler extends CallbackHandler {\n private readonly langfuse?: t.LangfuseConfig;\n private readonly traceIdSeed?: string;\n\n constructor(params?: AgentLangfuseHandlerParams) {\n const { langfuse, traceIdSeed, ...handlerParams } = params ?? {};\n super(handlerParams);\n this.langfuse = langfuse;\n this.traceIdSeed = traceIdSeed;\n }\n\n private getDeterministicTraceSeed(): string | undefined {\n return this.langfuse?.deterministicTraceId === true\n ? this.traceIdSeed\n : undefined;\n }\n\n private withRuntimeContext<T>(action: () => T): T {\n const activeContext = otelContext.active();\n const langfuse =\n resolveLangfuseConfigForSpan(activeContext) ?? this.langfuse;\n const seed = this.getDeterministicTraceSeed();\n return withLangfuseRuntimeScope(\n {\n langfuse,\n traceIdSeed: resolveTraceIdSeedForSpan(activeContext) ?? seed,\n },\n action\n );\n }\n\n // LangChain may invoke callback handlers outside the caller's OTEL context.\n // Re-enter tenant scope only for callbacks that start Langfuse observations;\n // end/error/token callbacks use spans already bound to a processor at start.\n override handleChainStart(\n ...args: Parameters<CallbackHandler['handleChainStart']>\n ): ReturnType<CallbackHandler['handleChainStart']> {\n return this.withRuntimeContext(() => super.handleChainStart(...args));\n }\n\n override handleAgentAction(\n ...args: Parameters<CallbackHandler['handleAgentAction']>\n ): ReturnType<CallbackHandler['handleAgentAction']> {\n return this.withRuntimeContext(() => super.handleAgentAction(...args));\n }\n\n override handleGenerationStart(\n ...args: Parameters<CallbackHandler['handleGenerationStart']>\n ): ReturnType<CallbackHandler['handleGenerationStart']> {\n return this.withRuntimeContext(() => super.handleGenerationStart(...args));\n }\n\n override handleChatModelStart(\n ...args: Parameters<CallbackHandler['handleChatModelStart']>\n ): ReturnType<CallbackHandler['handleChatModelStart']> {\n return this.withRuntimeContext(() => super.handleChatModelStart(...args));\n }\n\n override handleLLMStart(\n ...args: Parameters<CallbackHandler['handleLLMStart']>\n ): ReturnType<CallbackHandler['handleLLMStart']> {\n return this.withRuntimeContext(() => super.handleLLMStart(...args));\n }\n\n override handleToolStart(\n ...args: Parameters<CallbackHandler['handleToolStart']>\n ): ReturnType<CallbackHandler['handleToolStart']> {\n return this.withRuntimeContext(() => super.handleToolStart(...args));\n }\n\n override handleRetrieverStart(\n ...args: Parameters<CallbackHandler['handleRetrieverStart']>\n ): ReturnType<CallbackHandler['handleRetrieverStart']> {\n return this.withRuntimeContext(() => super.handleRetrieverStart(...args));\n }\n}\n\nfunction hasLangfuseTracingConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.toolNodeTracing != null || langfuse?.toolOutputTracing != null\n );\n}\n\nfunction hasLangfuseTraceAttributes(langfuse?: t.LangfuseConfig): boolean {\n return (\n Object.keys(createTraceMetadata(langfuse?.metadata ?? {})).length > 0 ||\n Object.keys(\n createLibreChatTraceAttributes(langfuse?.librechatTraceAttributes ?? {})\n ).length > 0 ||\n (mergeLangfuseTags(undefined, langfuse?.tags)?.length ?? 0) > 0\n );\n}\n\nexport function hasLangfuseConfigCredentials(\n langfuse?: t.LangfuseConfig\n): langfuse is t.LangfuseConfig & {\n publicKey: string;\n secretKey: string;\n} {\n return (\n langfuse != null &&\n isPresent(langfuse.publicKey) &&\n isPresent(langfuse.secretKey)\n );\n}\n\nfunction hasLangfuseConfigBaseUrl(langfuse?: t.LangfuseConfig): boolean {\n return isPresent(langfuse?.baseUrl);\n}\n\nexport function isExplicitLangfuseConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.enabled != null ||\n isPresent(langfuse?.publicKey) ||\n isPresent(langfuse?.secretKey) ||\n isPresent(langfuse?.baseUrl) ||\n hasLangfuseTraceAttributes(langfuse) ||\n hasLangfuseTracingConfig(langfuse)\n );\n}\n\nfunction createTraceMetadata(\n metadata: Record<string, unknown>\n): LangfuseTraceMetadata {\n const traceMetadata: LangfuseTraceMetadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (value == null) {\n continue;\n }\n const stringValue = typeof value === 'string' ? value : String(value);\n if (\n stringValue.trim() === '' ||\n stringValue.length > TRACE_METADATA_MAX_LENGTH\n ) {\n continue;\n }\n traceMetadata[key] = stringValue;\n }\n return traceMetadata;\n}\n\nexport function createLibreChatTraceAttributes(\n attributes: LangfuseConfigTraceAttributes\n): LangfuseTraceAttributes {\n const librechatTraceAttributes: LangfuseTraceAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value == null || key.trim() === '') {\n continue;\n }\n if (typeof value === 'string') {\n if (value.trim() === '' || value.length > TRACE_METADATA_MAX_LENGTH) {\n continue;\n }\n librechatTraceAttributes[key] = value;\n continue;\n }\n librechatTraceAttributes[key] = value;\n }\n return librechatTraceAttributes;\n}\n\nexport function createLangfuseTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n}: {\n messageId?: unknown;\n parentMessageId?: unknown;\n agentId?: unknown;\n agentName?: unknown;\n}): LangfuseTraceMetadata {\n return createTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n });\n}\n\nfunction mergeLangfuseTraceMetadata(\n traceMetadata?: LangfuseTraceMetadata,\n metadata?: LangfuseMetadata\n): LangfuseTraceMetadata | undefined {\n const merged = createTraceMetadata({\n ...(metadata ?? {}),\n ...(traceMetadata ?? {}),\n });\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nfunction mergeLangfuseTags(\n tags?: string[],\n configTags?: string[]\n): string[] | undefined {\n const merged = [...(tags ?? []), ...(configTags ?? [])].filter(\n (tag) => tag.trim() !== ''\n );\n return merged.length > 0 ? [...new Set(merged)] : undefined;\n}\n\nexport function getLangfuseTraceName(\n traceMetadata?: LangfuseTraceMetadata,\n fallback: string = 'LibreChat Agent'\n): string {\n const agentName = traceMetadata?.agentName;\n return isPresent(agentName) ? `${fallback}: ${agentName}` : fallback;\n}\n\nexport function hasLangfuseEnvConfig(): boolean {\n return hasLangfuseEnvCredentials();\n}\n\nexport function hasLangfuseEnvCredentials(): boolean {\n return (\n isPresent(process.env.LANGFUSE_SECRET_KEY) &&\n isPresent(process.env.LANGFUSE_PUBLIC_KEY)\n );\n}\n\nexport function shouldCreateLangfuseHandler(\n langfuse?: t.LangfuseConfig\n): boolean {\n if (langfuse?.enabled === false) {\n return false;\n }\n return (\n hasLangfuseEnvConfig() ||\n hasLangfuseConfigCredentials(langfuse) ||\n (hasLangfuseConfigBaseUrl(langfuse) && hasLangfuseEnvCredentials())\n );\n}\n\nexport function createLegacyLangfuseHandler(\n params: LangfuseHandlerParams\n): CallbackHandler {\n return new ScopedLangfuseCallbackHandler(params);\n}\n\nexport function createLangfuseHandler({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n tags,\n traceIdSeed,\n}: AgentLangfuseHandlerParams): CallbackHandler | undefined {\n if (!shouldCreateLangfuseHandler(langfuse)) {\n return undefined;\n }\n return new ScopedLangfuseCallbackHandler({\n userId,\n sessionId,\n traceMetadata: mergeLangfuseTraceMetadata(\n traceMetadata,\n langfuse?.metadata\n ),\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n langfuse,\n traceIdSeed,\n });\n}\n\nfunction createPropagateAttributeParams({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n traceName,\n tags,\n}: LangfuseAttributeParams): PropagateAttributesParams {\n return {\n userId,\n sessionId,\n traceName,\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n metadata: mergeLangfuseTraceMetadata(traceMetadata, langfuse?.metadata),\n };\n}\n\nexport function withLangfuseAttributes<T>(\n params: LangfuseAttributeParams,\n action: () => T\n): T {\n if (!shouldCreateLangfuseHandler(params.langfuse)) {\n return action();\n }\n return propagateAttributes(createPropagateAttributeParams(params), action);\n}\n\nexport function hasExplicitLangfuseConfig(\n contexts: Iterable<{ langfuse?: t.LangfuseConfig }>\n): boolean {\n for (const context of contexts) {\n if (isExplicitLangfuseConfig(context.langfuse)) {\n return true;\n }\n }\n return false;\n}\n\nexport function isLangfuseCallbackHandler(value: unknown): boolean {\n return value instanceof CallbackHandler;\n}\n\nexport async function disposeLangfuseHandler(value: unknown): Promise<void> {\n if (\n value == null ||\n !parseBooleanEnv(process.env[LANGFUSE_FORCE_FLUSH_ON_DISPOSE])\n ) {\n return;\n }\n const provider = getLangfuseTracerProvider() as FlushableTracerProvider;\n await provider.forceFlush?.();\n}\n"],"mappings":";;;;;;AAeA,MAAM,4BAA4B;AAClC,MAAM,kCAAkC;AA6BxC,IAAM,gCAAN,cAA4CA,oBAAAA,gBAAgB;CAC1D;CACA;CAEA,YAAY,QAAqC;EAC/C,MAAM,EAAE,UAAU,aAAa,GAAG,kBAAkB,UAAU,CAAC;EAC/D,MAAM,aAAa;EACnB,KAAK,WAAW;EAChB,KAAK,cAAc;CACrB;CAEA,4BAAwD;EACtD,OAAO,KAAK,UAAU,yBAAyB,OAC3C,KAAK,cACL,KAAA;CACN;CAEA,mBAA8B,QAAoB;EAChD,MAAM,gBAAgBC,mBAAAA,QAAY,OAAO;EACzC,MAAM,WACJC,6BAAAA,6BAA6B,aAAa,KAAK,KAAK;EACtD,MAAM,OAAO,KAAK,0BAA0B;EAC5C,OAAOC,6BAAAA,yBACL;GACE;GACA,aAAaC,6BAAAA,0BAA0B,aAAa,KAAK;EAC3D,GACA,MACF;CACF;CAKA,iBACE,GAAG,MAC8C;EACjD,OAAO,KAAK,yBAAyB,MAAM,iBAAiB,GAAG,IAAI,CAAC;CACtE;CAEA,kBACE,GAAG,MAC+C;EAClD,OAAO,KAAK,yBAAyB,MAAM,kBAAkB,GAAG,IAAI,CAAC;CACvE;CAEA,sBACE,GAAG,MACmD;EACtD,OAAO,KAAK,yBAAyB,MAAM,sBAAsB,GAAG,IAAI,CAAC;CAC3E;CAEA,qBACE,GAAG,MACkD;EACrD,OAAO,KAAK,yBAAyB,MAAM,qBAAqB,GAAG,IAAI,CAAC;CAC1E;CAEA,eACE,GAAG,MAC4C;EAC/C,OAAO,KAAK,yBAAyB,MAAM,eA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AO,OAAO;CAEhB,QAAA,GAAA,kBAAA,oBAAA,CAA2B,+BAA+B,MAAM,GAAG,MAAM;AAC3E;AAaA,SAAgB,0BAA0B,OAAyB;CACjE,OAAO,iBAAiBL,oBAAAA;AAC1B;AAEA,eAAsB,uBAAuB,OAA+B;CAC1E,IACE,SAAS,QACT,CAACM,aAAAA,gBAAgB,QAAQ,IAAI,gCAAgC,GAE7D;CAGF,OAAA,GAAA,kBAAA,0BAAA,CAAa,CAAC,CAAC,aAAa;AAC9B"}
|
|
1
|
+
{"version":3,"file":"langfuse.cjs","names":["AIMessageChunk","AIMessage","CallbackHandler","otelContext","resolveLangfuseConfigForSpan","withLangfuseRuntimeScope","resolveTraceIdSeedForSpan","isPresent","parseBooleanEnv"],"sources":["../../src/langfuse.ts"],"sourcesContent":["import { CallbackHandler } from '@langfuse/langchain';\nimport { context as otelContext } from '@opentelemetry/api';\nimport { AIMessage, AIMessageChunk } from '@langchain/core/messages';\nimport {\n getLangfuseTracerProvider,\n propagateAttributes,\n} from '@langfuse/tracing';\nimport type {\n AIMessageChunkFields,\n AIMessageFields,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ChatGeneration,\n Generation,\n LLMResult,\n} from '@langchain/core/outputs';\nimport type { PropagateAttributesParams } from '@langfuse/tracing';\nimport type * as t from '@/types';\nimport {\n resolveLangfuseConfigForSpan,\n resolveTraceIdSeedForSpan,\n withLangfuseRuntimeScope,\n} from '@/langfuseRuntimeScope';\nimport { isPresent, parseBooleanEnv } from '@/utils/misc';\n\nconst TRACE_METADATA_MAX_LENGTH = 200;\nconst LANGFUSE_FORCE_FLUSH_ON_DISPOSE = 'LANGFUSE_FORCE_FLUSH_ON_DISPOSE';\n\nexport type LangfuseTraceMetadata = Record<string, string>;\nexport type LangfuseTraceAttributes = Record<string, string | number | boolean>;\ntype LangfuseMetadata = NonNullable<t.LangfuseConfig['metadata']>;\ntype LangfuseConfigTraceAttributes = NonNullable<\n t.LangfuseConfig['librechatTraceAttributes']\n>;\n\ntype LangfuseHandlerParams = {\n userId?: string;\n sessionId?: string;\n traceMetadata?: LangfuseTraceMetadata;\n tags?: string[];\n traceIdSeed?: string;\n};\n\ntype AgentLangfuseHandlerParams = LangfuseHandlerParams & {\n langfuse?: t.LangfuseConfig;\n};\n\ntype LangfuseAttributeParams = AgentLangfuseHandlerParams & {\n traceName?: string;\n};\n\ntype FlushableTracerProvider = {\n forceFlush?: () => Promise<void> | void;\n};\n\ntype BedrockResponseUsage = {\n inputTokens?: number;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n};\n\ntype BedrockResponseMetadata = {\n metadata?: {\n usage?: BedrockResponseUsage;\n };\n};\n\nfunction getLangfuseBedrockUsage(\n message: AIMessage | AIMessageChunk\n): UsageMetadata | undefined {\n const usageMetadata = message.usage_metadata;\n const bedrockUsage = (message.response_metadata as BedrockResponseMetadata)\n .metadata?.usage;\n if (\n usageMetadata == null ||\n bedrockUsage == null ||\n usageMetadata.input_tokens !== bedrockUsage.inputTokens\n ) {\n return usageMetadata;\n }\n\n const cacheRead = bedrockUsage.cacheReadInputTokens ?? 0;\n const cacheCreation = bedrockUsage.cacheWriteInputTokens ?? 0;\n if (cacheRead === 0 && cacheCreation === 0) {\n return usageMetadata;\n }\n\n return {\n ...usageMetadata,\n input_tokens: usageMetadata.input_tokens + cacheRead + cacheCreation,\n };\n}\n\nfunction cloneMessageWithUsage(\n message: AIMessage | AIMessageChunk,\n usageMetadata: UsageMetadata\n): AIMessage | AIMessageChunk {\n const fields: AIMessageFields = {\n content: message.content,\n additional_kwargs: message.additional_kwargs,\n response_metadata: message.response_metadata,\n id: message.id,\n name: message.name,\n tool_calls: message.tool_calls,\n invalid_tool_calls: message.invalid_tool_calls,\n usage_metadata: usageMetadata,\n };\n\n if (message instanceof AIMessageChunk) {\n const chunkFields: AIMessageChunkFields = {\n ...fields,\n tool_call_chunks: message.tool_call_chunks,\n };\n return new AIMessageChunk(chunkFields);\n }\n\n return new AIMessage(fields);\n}\n\nfunction normalizeGenerationForLangfuse(generation: Generation): Generation {\n if (!('message' in generation)) {\n return generation;\n }\n\n const message = (generation as ChatGeneration).message;\n if (!(message instanceof AIMessage || message instanceof AIMessageChunk)) {\n return generation;\n }\n\n const usageMetadata = getLangfuseBedrockUsage(message);\n if (usageMetadata == null || usageMetadata === message.usage_metadata) {\n return generation;\n }\n\n const chatGeneration: ChatGeneration = {\n ...(generation as ChatGeneration),\n message: cloneMessageWithUsage(message, usageMetadata),\n };\n return chatGeneration;\n}\n\nfunction normalizeBedrockUsageForLangfuse(output: LLMResult): LLMResult {\n if (output.generations.length === 0) {\n return output;\n }\n\n const listIndex = output.generations.length - 1;\n const generationList = output.generations[listIndex];\n if (generationList.length === 0) {\n return output;\n }\n\n const generationIndex = generationList.length - 1;\n const generation = generationList[generationIndex];\n const normalized = normalizeGenerationForLangfuse(generation);\n if (normalized === generation) {\n return output;\n }\n\n const generations = [...output.generations];\n generations[listIndex] = [...generationList];\n generations[listIndex][generationIndex] = normalized;\n return { ...output, generations };\n}\n\nclass ScopedLangfuseCallbackHandler extends CallbackHandler {\n private readonly langfuse?: t.LangfuseConfig;\n private readonly traceIdSeed?: string;\n\n constructor(params?: AgentLangfuseHandlerParams) {\n const { langfuse, traceIdSeed, ...handlerParams } = params ?? {};\n super(handlerParams);\n this.langfuse = langfuse;\n this.traceIdSeed = traceIdSeed;\n }\n\n private getDeterministicTraceSeed(): string | undefined {\n return this.langfuse?.deterministicTraceId === true\n ? this.traceIdSeed\n : undefined;\n }\n\n private withRuntimeContext<T>(action: () => T): T {\n const activeContext = otelContext.active();\n const langfuse =\n resolveLangfuseConfigForSpan(activeContext) ?? this.langfuse;\n const seed = this.getDeterministicTraceSeed();\n return withLangfuseRuntimeScope(\n {\n langfuse,\n traceIdSeed: resolveTraceIdSeedForSpan(activeContext) ?? seed,\n },\n action\n );\n }\n\n // LangChain may invoke callback handlers outside the caller's OTEL context.\n // Re-enter tenant scope only for callbacks that start Langfuse observations;\n // end/error/token callbacks use spans already bound to a processor at start.\n override handleChainStart(\n ...args: Parameters<CallbackHandler['handleChainStart']>\n ): ReturnType<CallbackHandler['handleChainStart']> {\n return this.withRuntimeContext(() => super.handleChainStart(...args));\n }\n\n override handleAgentAction(\n ...args: Parameters<CallbackHandler['handleAgentAction']>\n ): ReturnType<CallbackHandler['handleAgentAction']> {\n return this.withRuntimeContext(() => super.handleAgentAction(...args));\n }\n\n override handleGenerationStart(\n ...args: Parameters<CallbackHandler['handleGenerationStart']>\n ): ReturnType<CallbackHandler['handleGenerationStart']> {\n return this.withRuntimeContext(() => super.handleGenerationStart(...args));\n }\n\n override handleChatModelStart(\n ...args: Parameters<CallbackHandler['handleChatModelStart']>\n ): ReturnType<CallbackHandler['handleChatModelStart']> {\n return this.withRuntimeContext(() => super.handleChatModelStart(...args));\n }\n\n override handleLLMStart(\n ...args: Parameters<CallbackHandler['handleLLMStart']>\n ): ReturnType<CallbackHandler['handleLLMStart']> {\n return this.withRuntimeContext(() => super.handleLLMStart(...args));\n }\n\n override handleLLMEnd(\n output: LLMResult,\n runId: string,\n parentRunId?: string\n ): Promise<void> {\n return super.handleLLMEnd(\n normalizeBedrockUsageForLangfuse(output),\n runId,\n parentRunId\n );\n }\n\n override handleToolStart(\n ...args: Parameters<CallbackHandler['handleToolStart']>\n ): ReturnType<CallbackHandler['handleToolStart']> {\n return this.withRuntimeContext(() => super.handleToolStart(...args));\n }\n\n override handleRetrieverStart(\n ...args: Parameters<CallbackHandler['handleRetrieverStart']>\n ): ReturnType<CallbackHandler['handleRetrieverStart']> {\n return this.withRuntimeContext(() => super.handleRetrieverStart(...args));\n }\n}\n\nfunction hasLangfuseTracingConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.toolNodeTracing != null || langfuse?.toolOutputTracing != null\n );\n}\n\nfunction hasLangfuseTraceAttributes(langfuse?: t.LangfuseConfig): boolean {\n return (\n Object.keys(createTraceMetadata(langfuse?.metadata ?? {})).length > 0 ||\n Object.keys(\n createLibreChatTraceAttributes(langfuse?.librechatTraceAttributes ?? {})\n ).length > 0 ||\n (mergeLangfuseTags(undefined, langfuse?.tags)?.length ?? 0) > 0\n );\n}\n\nexport function hasLangfuseConfigCredentials(\n langfuse?: t.LangfuseConfig\n): langfuse is t.LangfuseConfig & {\n publicKey: string;\n secretKey: string;\n} {\n return (\n langfuse != null &&\n isPresent(langfuse.publicKey) &&\n isPresent(langfuse.secretKey)\n );\n}\n\nfunction hasLangfuseConfigBaseUrl(langfuse?: t.LangfuseConfig): boolean {\n return isPresent(langfuse?.baseUrl);\n}\n\nexport function isExplicitLangfuseConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.enabled != null ||\n isPresent(langfuse?.publicKey) ||\n isPresent(langfuse?.secretKey) ||\n isPresent(langfuse?.baseUrl) ||\n hasLangfuseTraceAttributes(langfuse) ||\n hasLangfuseTracingConfig(langfuse)\n );\n}\n\nfunction createTraceMetadata(\n metadata: Record<string, unknown>\n): LangfuseTraceMetadata {\n const traceMetadata: LangfuseTraceMetadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (value == null) {\n continue;\n }\n const stringValue = typeof value === 'string' ? value : String(value);\n if (\n stringValue.trim() === '' ||\n stringValue.length > TRACE_METADATA_MAX_LENGTH\n ) {\n continue;\n }\n traceMetadata[key] = stringValue;\n }\n return traceMetadata;\n}\n\nexport function createLibreChatTraceAttributes(\n attributes: LangfuseConfigTraceAttributes\n): LangfuseTraceAttributes {\n const librechatTraceAttributes: LangfuseTraceAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value == null || key.trim() === '') {\n continue;\n }\n if (typeof value === 'string') {\n if (value.trim() === '' || value.length > TRACE_METADATA_MAX_LENGTH) {\n continue;\n }\n librechatTraceAttributes[key] = value;\n continue;\n }\n librechatTraceAttributes[key] = value;\n }\n return librechatTraceAttributes;\n}\n\nexport function createLangfuseTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n}: {\n messageId?: unknown;\n parentMessageId?: unknown;\n agentId?: unknown;\n agentName?: unknown;\n}): LangfuseTraceMetadata {\n return createTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n });\n}\n\nfunction mergeLangfuseTraceMetadata(\n traceMetadata?: LangfuseTraceMetadata,\n metadata?: LangfuseMetadata\n): LangfuseTraceMetadata | undefined {\n const merged = createTraceMetadata({\n ...(metadata ?? {}),\n ...(traceMetadata ?? {}),\n });\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nfunction mergeLangfuseTags(\n tags?: string[],\n configTags?: string[]\n): string[] | undefined {\n const merged = [...(tags ?? []), ...(configTags ?? [])].filter(\n (tag) => tag.trim() !== ''\n );\n return merged.length > 0 ? [...new Set(merged)] : undefined;\n}\n\nexport function getLangfuseTraceName(\n traceMetadata?: LangfuseTraceMetadata,\n fallback: string = 'LibreChat Agent'\n): string {\n const agentName = traceMetadata?.agentName;\n return isPresent(agentName) ? `${fallback}: ${agentName}` : fallback;\n}\n\nexport function hasLangfuseEnvConfig(): boolean {\n return hasLangfuseEnvCredentials();\n}\n\nexport function hasLangfuseEnvCredentials(): boolean {\n return (\n isPresent(process.env.LANGFUSE_SECRET_KEY) &&\n isPresent(process.env.LANGFUSE_PUBLIC_KEY)\n );\n}\n\nexport function shouldCreateLangfuseHandler(\n langfuse?: t.LangfuseConfig\n): boolean {\n if (langfuse?.enabled === false) {\n return false;\n }\n return (\n hasLangfuseEnvConfig() ||\n hasLangfuseConfigCredentials(langfuse) ||\n (hasLangfuseConfigBaseUrl(langfuse) && hasLangfuseEnvCredentials())\n );\n}\n\nexport function createLegacyLangfuseHandler(\n params: LangfuseHandlerParams\n): CallbackHandler {\n return new ScopedLangfuseCallbackHandler(params);\n}\n\nexport function createLangfuseHandler({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n tags,\n traceIdSeed,\n}: AgentLangfuseHandlerParams): CallbackHandler | undefined {\n if (!shouldCreateLangfuseHandler(langfuse)) {\n return undefined;\n }\n return new ScopedLangfuseCallbackHandler({\n userId,\n sessionId,\n traceMetadata: mergeLangfuseTraceMetadata(\n traceMetadata,\n langfuse?.metadata\n ),\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n langfuse,\n traceIdSeed,\n });\n}\n\nfunction createPropagateAttributeParams({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n traceName,\n tags,\n}: LangfuseAttributeParams): PropagateAttributesParams {\n return {\n userId,\n sessionId,\n traceName,\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n metadata: mergeLangfuseTraceMetadata(traceMetadata, langfuse?.metadata),\n };\n}\n\nexport function withLangfuseAttributes<T>(\n params: LangfuseAttributeParams,\n action: () => T\n): T {\n if (!shouldCreateLangfuseHandler(params.langfuse)) {\n return action();\n }\n return propagateAttributes(createPropagateAttributeParams(params), action);\n}\n\nexport function hasExplicitLangfuseConfig(\n contexts: Iterable<{ langfuse?: t.LangfuseConfig }>\n): boolean {\n for (const context of contexts) {\n if (isExplicitLangfuseConfig(context.langfuse)) {\n return true;\n }\n }\n return false;\n}\n\nexport function isLangfuseCallbackHandler(value: unknown): boolean {\n return value instanceof CallbackHandler;\n}\n\nexport async function disposeLangfuseHandler(value: unknown): Promise<void> {\n if (\n value == null ||\n parseBooleanEnv(process.env[LANGFUSE_FORCE_FLUSH_ON_DISPOSE]) !== true\n ) {\n return;\n }\n const provider = getLangfuseTracerProvider() as FlushableTracerProvider;\n await provider.forceFlush?.();\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,4BAA4B;AAClC,MAAM,kCAAkC;AAyCxC,SAAS,wBACP,SAC2B;CAC3B,MAAM,gBAAgB,QAAQ;CAC9B,MAAM,eAAgB,QAAQ,kBAC3B,UAAU;CACb,IACE,iBAAiB,QACjB,gBAAgB,QAChB,cAAc,iBAAiB,aAAa,aAE5C,OAAO;CAGT,MAAM,YAAY,aAAa,wBAAwB;CACvD,MAAM,gBAAgB,aAAa,yBAAyB;CAC5D,IAAI,cAAc,KAAK,kBAAkB,GACv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