@librechat/agents 3.1.68 → 3.1.71-dev.0
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/agents/AgentContext.cjs +23 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +16 -1
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +136 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +162 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
- package/dist/cjs/hooks/executeHooks.cjs +276 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
- package/dist/cjs/hooks/matchers.cjs +256 -0
- package/dist/cjs/hooks/matchers.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs +27 -0
- package/dist/cjs/hooks/types.cjs.map +1 -0
- package/dist/cjs/main.cjs +57 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +74 -12
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +9 -2
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/run.cjs +115 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +44 -0
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +208 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +287 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/CodeExecutor.cjs +0 -9
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +7 -23
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ReadFile.cjs +43 -0
- package/dist/cjs/tools/ReadFile.cjs.map +1 -0
- package/dist/cjs/tools/SkillTool.cjs +50 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -0
- package/dist/cjs/tools/SubagentTool.cjs +92 -0
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +746 -174
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +2 -13
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
- package/dist/cjs/tools/skillCatalog.cjs +84 -0
- package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +511 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
- package/dist/cjs/tools/toolOutputReferences.cjs +475 -0
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -0
- package/dist/cjs/utils/truncation.cjs +28 -0
- package/dist/cjs/utils/truncation.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +23 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +15 -2
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +136 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +160 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
- package/dist/esm/hooks/executeHooks.mjs +273 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -0
- package/dist/esm/hooks/matchers.mjs +251 -0
- package/dist/esm/hooks/matchers.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs +25 -0
- package/dist/esm/hooks/types.mjs.map +1 -0
- package/dist/esm/main.mjs +13 -2
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +66 -4
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +9 -2
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/run.mjs +115 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +44 -0
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +200 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +278 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/CodeExecutor.mjs +0 -9
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +8 -24
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ReadFile.mjs +38 -0
- package/dist/esm/tools/ReadFile.mjs.map +1 -0
- package/dist/esm/tools/SkillTool.mjs +45 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -0
- package/dist/esm/tools/SubagentTool.mjs +85 -0
- package/dist/esm/tools/SubagentTool.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +748 -176
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +3 -14
- package/dist/esm/tools/ToolSearch.mjs.map +1 -1
- package/dist/esm/tools/skillCatalog.mjs +82 -0
- package/dist/esm/tools/skillCatalog.mjs.map +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +505 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
- package/dist/esm/tools/toolOutputReferences.mjs +468 -0
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -0
- package/dist/esm/utils/truncation.mjs +27 -1
- package/dist/esm/utils/truncation.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +6 -0
- package/dist/types/common/enum.d.ts +10 -2
- package/dist/types/graphs/Graph.d.ts +23 -0
- package/dist/types/hooks/HookRegistry.d.ts +56 -0
- package/dist/types/hooks/executeHooks.d.ts +79 -0
- package/dist/types/hooks/index.d.ts +6 -0
- package/dist/types/hooks/matchers.d.ts +95 -0
- package/dist/types/hooks/types.d.ts +320 -0
- package/dist/types/index.d.ts +8 -0
- package/dist/types/messages/format.d.ts +2 -1
- package/dist/types/run.d.ts +2 -0
- package/dist/types/summarization/node.d.ts +2 -0
- package/dist/types/tools/BashExecutor.d.ts +76 -0
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +4 -9
- package/dist/types/tools/ReadFile.d.ts +28 -0
- package/dist/types/tools/SkillTool.d.ts +40 -0
- package/dist/types/tools/SubagentTool.d.ts +36 -0
- package/dist/types/tools/ToolNode.d.ts +109 -4
- package/dist/types/tools/ToolSearch.d.ts +2 -2
- package/dist/types/tools/skillCatalog.d.ts +19 -0
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
- package/dist/types/tools/subagent/index.d.ts +2 -0
- package/dist/types/tools/toolOutputReferences.d.ts +205 -0
- package/dist/types/types/graph.d.ts +61 -2
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/types/run.d.ts +28 -0
- package/dist/types/types/skill.d.ts +9 -0
- package/dist/types/types/tools.d.ts +108 -10
- package/dist/types/utils/truncation.d.ts +21 -0
- package/package.json +5 -1
- package/src/agents/AgentContext.ts +26 -2
- package/src/common/enum.ts +15 -1
- package/src/graphs/Graph.ts +161 -0
- package/src/hooks/HookRegistry.ts +208 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
- package/src/hooks/__tests__/compactHooks.test.ts +214 -0
- package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
- package/src/hooks/__tests__/integration.test.ts +337 -0
- package/src/hooks/__tests__/matchers.test.ts +238 -0
- package/src/hooks/__tests__/toolHooks.test.ts +669 -0
- package/src/hooks/executeHooks.ts +375 -0
- package/src/hooks/index.ts +57 -0
- package/src/hooks/matchers.ts +280 -0
- package/src/hooks/types.ts +404 -0
- package/src/index.ts +10 -0
- package/src/messages/format.ts +74 -4
- package/src/messages/formatAgentMessages.skills.test.ts +334 -0
- package/src/messages/prune.ts +9 -2
- package/src/run.ts +130 -0
- package/src/scripts/multi-agent-subagent.ts +246 -0
- package/src/scripts/programmatic_exec.ts +1 -10
- package/src/scripts/subagent-event-driven-debug.ts +190 -0
- package/src/scripts/subagent-tools-debug.ts +160 -0
- package/src/scripts/test_code_api.ts +0 -7
- package/src/scripts/tool_search.ts +1 -10
- package/src/specs/prune.test.ts +413 -0
- package/src/specs/subagent.test.ts +305 -0
- package/src/summarization/node.ts +53 -0
- package/src/tools/BashExecutor.ts +238 -0
- package/src/tools/BashProgrammaticToolCalling.ts +381 -0
- package/src/tools/CodeExecutor.ts +0 -11
- package/src/tools/ProgrammaticToolCalling.ts +4 -29
- package/src/tools/ReadFile.ts +39 -0
- package/src/tools/SkillTool.ts +46 -0
- package/src/tools/SubagentTool.ts +100 -0
- package/src/tools/ToolNode.ts +999 -214
- package/src/tools/ToolSearch.ts +3 -19
- package/src/tools/__tests__/BashExecutor.test.ts +36 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +7 -8
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -1
- package/src/tools/__tests__/ReadFile.test.ts +44 -0
- package/src/tools/__tests__/SkillTool.test.ts +442 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
- package/src/tools/__tests__/SubagentTool.test.ts +149 -0
- package/src/tools/__tests__/ToolNode.outputReferences.test.ts +1395 -0
- package/src/tools/__tests__/ToolNode.session.test.ts +12 -12
- package/src/tools/__tests__/ToolSearch.integration.test.ts +7 -8
- package/src/tools/__tests__/skillCatalog.test.ts +161 -0
- package/src/tools/__tests__/subagentHooks.test.ts +215 -0
- package/src/tools/__tests__/toolOutputReferences.test.ts +415 -0
- package/src/tools/skillCatalog.ts +126 -0
- package/src/tools/subagent/SubagentExecutor.ts +676 -0
- package/src/tools/subagent/index.ts +13 -0
- package/src/tools/toolOutputReferences.ts +590 -0
- package/src/types/graph.ts +80 -1
- package/src/types/index.ts +1 -0
- package/src/types/run.ts +28 -0
- package/src/types/skill.ts +11 -0
- package/src/types/tools.ts +112 -10
- package/src/utils/__tests__/truncation.test.ts +66 -0
- package/src/utils/truncation.ts +30 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.cjs","sources":["../../../src/summarization/node.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { UsageMetadata, BaseMessage } from '@langchain/core/messages';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { OnChunk } from '@/llm/invoke';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes, Providers } from '@/common';\nimport { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';\nimport { attemptInvoke, tryFallbackProviders } from '@/llm/invoke';\nimport { createRemoveAllMessage } from '@/messages/reducer';\nimport { getMaxOutputTokensKey } from '@/llm/request';\nimport { addCacheControl } from '@/messages/cache';\nimport { initializeModel } from '@/llm/init';\nimport { getChunkContent } from '@/stream';\n\nconst SUMMARIZATION_PARAM_KEYS = new Set(['maxSummaryTokens']);\n\n/**\n * Token overhead of the XML wrapper + instruction text added around the\n * summary at injection time in AgentContext.buildSystemRunnable:\n * `<summary>\\n${text}\\n</summary>\\n\\nYour context window was compacted...`\n * ~33 tokens on Anthropic, ~24-27 on OpenAI. Using 33 as a safe ceiling.\n */\nconst SUMMARY_WRAPPER_OVERHEAD_TOKENS = 33;\n\n/** Structured checkpoint prompt for fresh summarization (no prior summary). */\nexport const DEFAULT_SUMMARIZATION_PROMPT = `Hold on, before you continue I need you to write me a checkpoint of everything so far. Your context window is filling up and this checkpoint replaces the messages above, so capture everything you need to pick right back up.\n\nDon't second-guess or fact-check anything you did, your tool results reflect exactly what happened. If a tool result appears truncated, that's just a display artifact from context management: the tool executed fully. Just record what you did and what you observed. Only the checkpoint, don't respond to me or continue the conversation.\n\n## Checkpoint\n\n## Goal\nWhat I asked you to do and any sub-goals you identified.\n\n## Constraints & Preferences\nAny rules, preferences, or configuration I established.\n\n## Progress\n### Done\n- What you completed and the outcomes\n\n### In Progress\n- What you're currently working on\n\n## Key Decisions\nDecisions you made and why.\n\n## Next Steps\nConcrete task actions remaining, in priority order.\n\n## Critical Context\nExact identifiers, names, error messages, URLs, and details you need to preserve verbatim.\n\nRules:\n- Record what you did and observed, don't judge or re-evaluate it\n- For each tool call: the tool name, key inputs, and the outcome\n- Preserve exact identifiers, names, errors, and references verbatim\n- Short declarative sentences\n- Skip empty sections`;\n\n/** Prompt for re-compaction when a prior summary exists. */\nexport const DEFAULT_UPDATE_SUMMARIZATION_PROMPT = `Hold on again, update your checkpoint. Merge the new messages into your existing checkpoint and give me a single consolidated replacement.\n\nKeep it roughly the same length as your last checkpoint. Compress older details to make room for what's new, don't just append. Give recent actions more detail, compress older items to one-liners.\n\nDon't fact-check or second-guess anything, your tool results are ground truth. If a tool result appears truncated, that's just a display artifact: the tool executed fully. Only the checkpoint, don't respond to me or continue the conversation.\n\nRules:\n- Merge new progress into existing sections, don't duplicate headers\n- Compress older completed items into one-line entries\n- Move items from \"In Progress\" to \"Done\" when you completed them\n- Update \"Next Steps\" to reflect current task priorities.\n- For each new tool call: the tool name, key inputs, and the outcome\n- Preserve exact identifiers, names, errors, and references verbatim\n- Skip empty sections`;\n\nfunction separateParameters(parameters: Record<string, unknown>): {\n llmParams: Record<string, unknown>;\n maxSummaryTokens?: number;\n} {\n const llmParams: Record<string, unknown> = {};\n let maxSummaryTokens: number | undefined;\n\n for (const [key, value] of Object.entries(parameters)) {\n if (SUMMARIZATION_PARAM_KEYS.has(key)) {\n if (\n key === 'maxSummaryTokens' &&\n typeof value === 'number' &&\n value > 0\n ) {\n maxSummaryTokens = value;\n }\n } else {\n llmParams[key] = value;\n }\n }\n\n return { llmParams, maxSummaryTokens };\n}\n\n/**\n * Generates a structural metadata summary without making an LLM call.\n * Used as a last-resort fallback when all summarization attempts fail.\n * Preserves tool names and message counts so the agent retains basic context.\n */\nfunction generateMetadataStub(messages: BaseMessage[]): string {\n const counts: Record<string, number> = {};\n const toolNames = new Set<string>();\n\n for (const msg of messages) {\n const role = msg.getType();\n counts[role] = (counts[role] ?? 0) + 1;\n\n if (role === 'tool' && msg.name != null && msg.name !== '') {\n toolNames.add(msg.name);\n }\n\n if (\n role === 'ai' &&\n msg instanceof AIMessage &&\n msg.tool_calls &&\n msg.tool_calls.length > 0\n ) {\n for (const tc of msg.tool_calls) {\n toolNames.add(tc.name);\n }\n }\n }\n\n const countParts = Object.entries(counts)\n .map(([role, count]) => `${count} ${role}`)\n .join(', ');\n\n const lines = [\n `[Metadata summary: ${messages.length} messages (${countParts})]`,\n ];\n\n if (toolNames.size > 0) {\n lines.push(`[Tools used: ${Array.from(toolNames).join(', ')}]`);\n }\n\n return lines.join('\\n');\n}\n\n/** Maximum number of tool failures to include in the enrichment section. */\nconst MAX_TOOL_FAILURES = 8;\n/** Maximum chars per failure summary line. */\nconst MAX_TOOL_FAILURE_CHARS = 240;\n\n/**\n * Extracts failed tool results from messages and formats them as a structured\n * section. LLMs often omit specific failure details (exit codes, error messages)\n * from their summaries, this mechanical enrichment guarantees they survive.\n */\nfunction extractToolFailuresSection(messages: BaseMessage[]): string {\n const failures: Array<{ toolName: string; summary: string }> = [];\n const seen = new Set<string>();\n\n for (const msg of messages) {\n if (msg.getType() !== 'tool') {\n continue;\n }\n const toolMsg = msg as ToolMessage;\n if (toolMsg.status !== 'error') {\n continue;\n }\n // Deduplicate by tool_call_id\n const callId = toolMsg.tool_call_id;\n if (callId && seen.has(callId)) {\n continue;\n }\n if (callId) {\n seen.add(callId);\n }\n\n const toolName = toolMsg.name ?? 'tool';\n const content =\n typeof toolMsg.content === 'string'\n ? toolMsg.content\n : JSON.stringify(toolMsg.content);\n const normalized = content.replace(/\\s+/g, ' ').trim();\n const summary =\n normalized.length > MAX_TOOL_FAILURE_CHARS\n ? `${normalized.slice(0, MAX_TOOL_FAILURE_CHARS - 3)}...`\n : normalized;\n\n failures.push({ toolName, summary });\n }\n\n if (failures.length === 0) {\n return '';\n }\n\n const lines = failures\n .slice(0, MAX_TOOL_FAILURES)\n .map((f) => `- ${f.toolName}: ${f.summary}`);\n if (failures.length > MAX_TOOL_FAILURES) {\n lines.push(`- ...and ${failures.length - MAX_TOOL_FAILURES} more`);\n }\n\n return `\\n\\n## Tool Failures\\n${lines.join('\\n')}`;\n}\n\n/**\n * Appends mechanical enrichment sections to an LLM-generated summary.\n * Tool failures are appended verbatim because LLMs often omit specific\n * error details from their summaries.\n */\nfunction enrichSummary(summaryText: string, messages: BaseMessage[]): string {\n return summaryText + extractToolFailuresSection(messages);\n}\n\n/**\n * Restores pre-masking tool content onto the messages array using\n * `pendingOriginalToolContent` stored on AgentContext. Only allocates\n * a new array when there are entries to restore; otherwise returns the\n * input reference unchanged.\n */\nfunction restoreOriginalToolContent(\n messages: BaseMessage[],\n originalToolContent: Map<number, string> | undefined\n): BaseMessage[] {\n if (originalToolContent == null || originalToolContent.size === 0) {\n return messages;\n }\n const restored = [...messages];\n for (const [idx, content] of originalToolContent) {\n const msg = restored[idx];\n if (msg instanceof ToolMessage) {\n restored[idx] = new ToolMessage({\n content,\n tool_call_id: msg.tool_call_id,\n name: msg.name,\n id: msg.id,\n additional_kwargs: msg.additional_kwargs,\n response_metadata: msg.response_metadata,\n });\n }\n }\n return restored;\n}\n\n// ---------------------------------------------------------------------------\n// Extracted helpers for createSummarizeNode\n// ---------------------------------------------------------------------------\n\ninterface SummarizationClientConfig {\n provider: string;\n modelName?: string;\n clientOptions: Record<string, unknown>;\n effectiveMaxSummaryTokens?: number;\n promptText: string;\n updatePromptText: string;\n}\n\n/** Assembles the summarization model's client options from agent and config. */\nfunction buildSummarizationClientConfig(\n agentContext: AgentContext,\n summarizationConfig?: t.SummarizationConfig\n): SummarizationClientConfig {\n const provider = (summarizationConfig?.provider ??\n agentContext.provider) as string;\n const modelName = summarizationConfig?.model;\n const parameters = summarizationConfig?.parameters ?? {};\n const promptText =\n summarizationConfig?.prompt ?? DEFAULT_SUMMARIZATION_PROMPT;\n const updatePromptText =\n summarizationConfig?.updatePrompt ?? DEFAULT_UPDATE_SUMMARIZATION_PROMPT;\n\n const { llmParams, maxSummaryTokens: paramMaxSummaryTokens } =\n separateParameters(parameters);\n\n const isSelfSummarize = provider === (agentContext.provider as string);\n const baseOptions =\n isSelfSummarize && agentContext.clientOptions\n ? { ...agentContext.clientOptions }\n : {};\n\n const clientOptions: Record<string, unknown> = {\n ...baseOptions,\n ...llmParams,\n };\n\n if (modelName != null && modelName !== '') {\n clientOptions.model = modelName;\n clientOptions.modelName = modelName;\n }\n\n const effectiveMaxSummaryTokens =\n paramMaxSummaryTokens ?? summarizationConfig?.maxSummaryTokens;\n\n if (effectiveMaxSummaryTokens != null) {\n clientOptions[getMaxOutputTokensKey(provider)] = effectiveMaxSummaryTokens;\n }\n\n return {\n provider,\n modelName,\n clientOptions,\n effectiveMaxSummaryTokens,\n promptText,\n updatePromptText,\n };\n}\n\n/** Computes the token count for a summary, preferring provider output tokens when available. */\nfunction computeSummaryTokenCount(\n summaryText: string,\n summaryUsage: Partial<UsageMetadata> | undefined,\n tokenCounter?: (message: BaseMessage) => number\n): number {\n const providerOutputTokens = Number(summaryUsage?.output_tokens) || 0;\n if (providerOutputTokens > 0) {\n return providerOutputTokens + SUMMARY_WRAPPER_OVERHEAD_TOKENS;\n }\n if (tokenCounter) {\n return (\n tokenCounter(new SystemMessage(summaryText)) +\n SUMMARY_WRAPPER_OVERHEAD_TOKENS\n );\n }\n return 0;\n}\n\n/** Constructs the SummaryContentBlock persisted in the run step and dispatched to events. */\nfunction buildSummaryBlock(params: {\n summaryText: string;\n tokenCount: number;\n stepId: string;\n stepIndex: number;\n modelName?: string;\n provider: string;\n summaryVersion: number;\n}): t.SummaryContentBlock {\n return {\n type: ContentTypes.SUMMARY,\n content: [\n {\n type: ContentTypes.TEXT,\n text: params.summaryText,\n } as t.MessageContentComplex,\n ],\n tokenCount: params.tokenCount,\n summaryVersion: params.summaryVersion,\n boundary: {\n messageId: params.stepId,\n contentIndex: params.stepIndex,\n },\n model: params.modelName,\n provider: params.provider,\n createdAt: new Date().toISOString(),\n };\n}\n\ntype LogFn = (\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n data?: Record<string, unknown>\n) => void;\n\n/**\n * Extracts an HTTP status code from a thrown LLM-provider error. Returns\n * `undefined` for non-object values (including `null` or `undefined`, both\n * valid `throw` targets in JS) so callers never dereference a nullish\n * value.\n */\nfunction extractHttpStatus(err: unknown): number | undefined {\n if (err == null || typeof err !== 'object') {\n return undefined;\n }\n const errRecord = err as Record<string, unknown>;\n const direct = errRecord.status;\n if (typeof direct === 'number') {\n return direct;\n }\n const statusCode = errRecord.statusCode;\n if (typeof statusCode === 'number') {\n return statusCode;\n }\n const response = errRecord.response;\n if (response != null && typeof response === 'object') {\n const nested = (response as Record<string, unknown>).status;\n if (typeof nested === 'number') {\n return nested;\n }\n }\n return undefined;\n}\n\n/**\n * Formats a provider-level error for logging. Returns both a human-readable\n * suffix (safe to include in the message string so it survives any host-side\n * formatter) and a structured metadata bag for rich log backends.\n */\nfunction describeProviderError(\n err: unknown,\n provider: string,\n modelName?: string\n): { suffix: string; data: Record<string, unknown> } {\n const providerLabel = `${provider}/${modelName ?? '(no-model)'}`;\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const data: Record<string, unknown> = {\n provider,\n model: modelName,\n };\n if (err instanceof Error) {\n data.errorName = err.name;\n data.errorStack = err.stack;\n }\n\n const status = extractHttpStatus(err);\n const statusSuffix = status != null ? ` (HTTP ${status})` : '';\n if (status != null) {\n data.status = status;\n }\n\n return {\n suffix: `[${providerLabel}]${statusSuffix}: ${errMsg}`,\n data,\n };\n}\n\n/**\n * Formats an exhausted-fallback error. `tryFallbackProviders` throws the\n * last fallback provider's error, which may be from any of the configured\n * fallbacks — not the primary — so we label the log with the list of\n * fallback providers attempted rather than mis-attributing to the primary.\n *\n * Entries in `fallbacks` are normally strongly typed, but we defend against\n * malformed runtime config (null/undefined entries, missing `provider`\n * field) so a recoverable summarization failure is never promoted to an\n * uncaught exception from inside the logging path.\n */\nfunction describeFallbackError(\n err: unknown,\n fallbacks: unknown\n): { suffix: string; data: Record<string, unknown> } {\n const errMsg = err instanceof Error ? err.message : String(err);\n const list: ReadonlyArray<unknown> = Array.isArray(fallbacks)\n ? fallbacks\n : [];\n const providerNames = list\n .map((f) => {\n if (f == null || typeof f !== 'object') {\n return undefined;\n }\n const raw = (f as { provider?: unknown }).provider;\n return raw != null ? String(raw) : undefined;\n })\n .filter((p): p is string => typeof p === 'string');\n const label =\n providerNames.length > 0\n ? `fallbacks=[${providerNames.join(',')}]`\n : 'no-fallbacks';\n\n const data: Record<string, unknown> = {\n fallbackProviders: providerNames,\n fallbackCount: list.length,\n };\n if (err instanceof Error) {\n data.errorName = err.name;\n data.errorStack = err.stack;\n }\n const status = extractHttpStatus(err);\n const statusSuffix = status != null ? ` (HTTP ${status})` : '';\n if (status != null) {\n data.status = status;\n }\n\n return {\n suffix: `[${label}]${statusSuffix}: ${errMsg}`,\n data,\n };\n}\n\n/**\n * Runs the summarization LLM call with primary + fallback providers,\n * falling back to a metadata stub when all calls fail.\n */\nasync function executeSummarizationWithFallback(params: {\n agentContext: AgentContext;\n messages: BaseMessage[];\n clientConfig: SummarizationClientConfig;\n summarizeConfig?: RunnableConfig;\n stepId: string;\n usePromptCache: boolean;\n log: LogFn;\n}): Promise<{ text: string; usage?: Partial<UsageMetadata> }> {\n const {\n agentContext,\n messages,\n clientConfig,\n summarizeConfig,\n stepId,\n usePromptCache,\n log,\n } = params;\n\n const priorSummaryText = agentContext.getSummaryText()?.trim() ?? '';\n\n let summaryText = '';\n let summaryUsage: Partial<UsageMetadata> | undefined;\n\n try {\n /**\n * Initialize inside the try so that a misconfigured provider\n * (e.g. an unrecognized summarization.provider) surfaces through the\n * `log('error', ...)` path below rather than bubbling up silently.\n */\n const summarizationModel = initializeModel({\n provider: clientConfig.provider as Providers,\n clientOptions: clientConfig.clientOptions as t.ClientOptions,\n tools: agentContext.getToolsForBinding(),\n }) as t.ChatModel;\n\n const result = await summarizeWithCacheHit({\n model: summarizationModel,\n messages,\n promptText: clientConfig.promptText,\n updatePromptText: clientConfig.updatePromptText,\n priorSummaryText,\n config: summarizeConfig,\n stepId,\n provider: clientConfig.provider as Providers,\n reasoningKey: agentContext.reasoningKey,\n usePromptCache,\n log,\n });\n summaryText = result.text;\n summaryUsage = result.usage;\n } catch (primaryError) {\n const primaryDescribed = describeProviderError(\n primaryError,\n clientConfig.provider,\n clientConfig.modelName\n );\n log('error', `Summarization LLM call failed ${primaryDescribed.suffix}`, {\n ...primaryDescribed.data,\n messagesToRefineCount: messages.length,\n });\n\n const rawFallbacks = (\n clientConfig.clientOptions as unknown as t.LLMConfig | undefined\n )?.fallbacks;\n const fallbacks = Array.isArray(rawFallbacks) ? rawFallbacks : [];\n if (fallbacks.length > 0) {\n try {\n const onChunk = createSummarizationChunkHandler({\n stepId,\n config: traceConfig(summarizeConfig, 'cache_hit_compaction'),\n provider: clientConfig.provider as Providers,\n reasoningKey: agentContext.reasoningKey,\n });\n const fbResult = await tryFallbackProviders({\n fallbacks,\n tools: agentContext.getToolsForBinding(),\n messages: [\n ...messages,\n new HumanMessage(\n buildSummarizationInstruction(\n clientConfig.promptText,\n clientConfig.updatePromptText,\n priorSummaryText\n )\n ),\n ],\n config: traceConfig(summarizeConfig, 'cache_hit_compaction'),\n primaryError,\n onChunk,\n });\n const fbMsg = fbResult?.messages?.[0];\n if (fbMsg) {\n summaryText = extractResponseText(\n fbMsg as { content: string | object }\n );\n }\n } catch (fbErr) {\n const fbDescribed = describeFallbackError(fbErr, fallbacks);\n log('warn', `Fallback providers also failed ${fbDescribed.suffix}`, {\n ...fbDescribed.data,\n });\n }\n }\n if (!summaryText) {\n log(\n 'warn',\n `Summarization failed, falling back to metadata stub ${primaryDescribed.suffix}`,\n {\n ...primaryDescribed.data,\n messagesToRefineCount: messages.length,\n }\n );\n summaryText = generateMetadataStub(messages);\n }\n }\n\n return { text: summaryText, usage: summaryUsage };\n}\n\n/** Dispatches run step completion, ON_SUMMARIZE_COMPLETE, and rebuilds token map. */\nasync function dispatchCompletionEvents(params: {\n graph: CreateSummarizeNodeParams['graph'];\n runnableConfig?: RunnableConfig;\n stepId: string;\n summaryBlock: t.SummaryContentBlock;\n agentContext: AgentContext;\n runStep: t.RunStep;\n summaryUsage?: Partial<UsageMetadata>;\n agentId: string;\n}): Promise<void> {\n const {\n graph,\n runnableConfig,\n stepId,\n summaryBlock,\n agentContext,\n runStep,\n summaryUsage,\n agentId,\n } = params;\n\n runStep.summary = summaryBlock;\n if (summaryUsage) {\n runStep.usage = {\n prompt_tokens: Number(summaryUsage.input_tokens) || 0,\n completion_tokens: Number(summaryUsage.output_tokens) || 0,\n total_tokens:\n (Number(summaryUsage.input_tokens) || 0) +\n (Number(summaryUsage.output_tokens) || 0),\n };\n }\n\n await graph.dispatchRunStepCompleted(\n stepId,\n { type: 'summary', summary: summaryBlock } satisfies t.SummaryCompleted,\n runnableConfig\n );\n\n if (runnableConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_COMPLETE,\n {\n id: stepId,\n agentId,\n summary: summaryBlock,\n } satisfies t.SummarizeCompleteEvent,\n runnableConfig\n );\n }\n\n agentContext.rebuildTokenMapAfterSummarization({});\n}\n\n// ---------------------------------------------------------------------------\n// createSummarizeNode\n// ---------------------------------------------------------------------------\n\ninterface CreateSummarizeNodeParams {\n agentContext: AgentContext;\n graph: {\n contentData: t.RunStep[];\n contentIndexMap: Map<string, number>;\n config?: RunnableConfig;\n runId?: string;\n isMultiAgent: boolean;\n dispatchRunStep: (\n runStep: t.RunStep,\n config?: RunnableConfig\n ) => Promise<void>;\n dispatchRunStepCompleted: (\n stepId: string,\n result: t.StepCompleted,\n config?: RunnableConfig\n ) => Promise<void>;\n };\n generateStepId: (stepKey: string) => [string, number];\n}\n\nexport function createSummarizeNode({\n agentContext,\n graph,\n generateStepId,\n}: CreateSummarizeNodeParams) {\n return async (\n state: {\n messages: BaseMessage[];\n summarizationRequest?: t.SummarizationNodeInput;\n },\n config?: RunnableConfig\n ): Promise<{ summarizationRequest: undefined; messages?: BaseMessage[] }> => {\n const request = state.summarizationRequest;\n if (request == null) {\n return { summarizationRequest: undefined };\n }\n\n const maxCtx = agentContext.maxContextTokens ?? 0;\n if (maxCtx > 0 && agentContext.instructionTokens >= maxCtx) {\n emitAgentLog(\n config,\n 'warn',\n 'summarize',\n 'Summarization skipped, instructions exceed context budget. Reduce the number of tools or increase maxContextTokens.',\n {\n instructionTokens: agentContext.instructionTokens,\n maxContextTokens: maxCtx,\n breakdown: agentContext.formatTokenBudgetBreakdown(),\n },\n { runId: graph.runId, agentId: request.agentId }\n );\n return { summarizationRequest: undefined };\n }\n\n const messagesToRefine = restoreOriginalToolContent(\n state.messages,\n agentContext.pendingOriginalToolContent\n );\n agentContext.pendingOriginalToolContent = undefined;\n\n const clientConfig = buildSummarizationClientConfig(\n agentContext,\n agentContext.summarizationConfig\n );\n\n const runnableConfig = config ?? graph.config;\n\n const stepKey = `summarize-${request.agentId}`;\n const [stepId, stepIndex] = generateStepId(stepKey);\n\n const placeholderSummary: t.SummaryContentBlock = {\n type: ContentTypes.SUMMARY,\n model: clientConfig.modelName,\n provider: clientConfig.provider,\n };\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: StepTypes.MESSAGE_CREATION,\n index: graph.contentData.length,\n stepDetails: {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: { message_id: stepId },\n },\n summary: placeholderSummary,\n usage: null,\n };\n\n if (graph.runId != null && graph.runId !== '') {\n runStep.runId = graph.runId;\n }\n if (graph.isMultiAgent && agentContext.agentId) {\n runStep.agentId = agentContext.agentId;\n }\n\n await graph.dispatchRunStep(runStep, runnableConfig);\n\n if (runnableConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_START,\n {\n agentId: request.agentId,\n provider: clientConfig.provider,\n model: clientConfig.modelName,\n messagesToRefineCount: messagesToRefine.length,\n summaryVersion: agentContext.summaryVersion + 1,\n } satisfies t.SummarizeStartEvent,\n runnableConfig\n );\n }\n\n const isSelfSummarizeModel =\n clientConfig.provider === (agentContext.provider as string);\n const hasPromptCache =\n isSelfSummarizeModel &&\n (agentContext.clientOptions as Record<string, unknown> | undefined)\n ?.promptCache === true;\n\n const log: LogFn = (level, message, data) => {\n emitAgentLog(runnableConfig, level, 'summarize', message, data, {\n runId: graph.runId,\n agentId: request.agentId,\n });\n };\n\n log('debug', 'Summarization starting', {\n messagesToRefineCount: messagesToRefine.length,\n hasPriorSummary: (agentContext.getSummaryText()?.trim() ?? '') !== '',\n summaryVersion: agentContext.summaryVersion + 1,\n isSelfSummarize: isSelfSummarizeModel,\n hasPromptCache,\n provider: clientConfig.provider,\n });\n\n const summarizeConfig: RunnableConfig | undefined = config\n ? {\n ...config,\n metadata: {\n ...config.metadata,\n agent_id: request.agentId,\n summarization_provider: clientConfig.provider,\n summarization_model: clientConfig.modelName,\n },\n }\n : undefined;\n\n const { text: rawText, usage: summaryUsage } =\n await executeSummarizationWithFallback({\n agentContext,\n messages: messagesToRefine,\n clientConfig,\n summarizeConfig,\n stepId,\n usePromptCache: isSelfSummarizeModel && hasPromptCache,\n log,\n });\n\n if (!rawText) {\n agentContext.markSummarizationTriggered(0);\n if (runnableConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_COMPLETE,\n {\n id: stepId,\n agentId: request.agentId,\n error: 'Summarization produced empty output',\n } satisfies t.SummarizeCompleteEvent,\n runnableConfig\n );\n }\n return { summarizationRequest: undefined };\n }\n\n const summaryText = enrichSummary(rawText, messagesToRefine);\n\n const tokenCount = computeSummaryTokenCount(\n summaryText,\n summaryUsage,\n agentContext.tokenCounter\n );\n\n agentContext.setSummary(summaryText, tokenCount);\n\n log('info', 'Summary persisted');\n log('debug', 'Summary details', {\n summaryTokens: tokenCount,\n textLength: summaryText.length,\n messagesCompacted: messagesToRefine.length,\n summaryVersion: agentContext.summaryVersion,\n ...(summaryUsage != null\n ? {\n input_tokens: summaryUsage.input_tokens,\n output_tokens: summaryUsage.output_tokens,\n cache_read: summaryUsage.input_token_details?.cache_read,\n cache_creation: summaryUsage.input_token_details?.cache_creation,\n }\n : {}),\n });\n\n const summaryBlock = buildSummaryBlock({\n summaryText,\n tokenCount,\n stepId,\n stepIndex: runStep.index,\n modelName: clientConfig.modelName,\n provider: clientConfig.provider,\n summaryVersion: agentContext.summaryVersion,\n });\n\n await dispatchCompletionEvents({\n graph,\n runnableConfig,\n stepId,\n summaryBlock,\n agentContext,\n runStep,\n summaryUsage,\n agentId: request.agentId,\n });\n\n return {\n summarizationRequest: undefined,\n messages: [createRemoveAllMessage()],\n };\n };\n}\n\n/** Extracts text from an LLM response, skipping reasoning/thinking blocks. */\nfunction extractResponseText(response: { content: string | object }): string {\n const { content } = response;\n if (typeof content === 'string') {\n return content.trim();\n }\n if (!Array.isArray(content)) {\n return '';\n }\n const parts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n parts.push(block);\n continue;\n }\n if (block == null || typeof block !== 'object') {\n continue;\n }\n const rec = block as Record<string, unknown>;\n if (\n rec.type === ContentTypes.THINKING ||\n rec.type === ContentTypes.REASONING_CONTENT ||\n rec.type === 'redacted_thinking'\n ) {\n continue;\n }\n if (rec.type === 'text' && typeof rec.text === 'string') {\n parts.push(rec.text);\n }\n }\n return parts.join('').trim();\n}\n\nfunction buildSummarizationInstruction(\n promptText: string,\n updatePromptText: string | undefined,\n priorSummaryText: string\n): string {\n const effectivePrompt = priorSummaryText\n ? (updatePromptText ?? promptText)\n : promptText;\n const parts = [effectivePrompt];\n if (priorSummaryText) {\n parts.push(\n `\\n\\n<previous-summary>\\n${priorSummaryText}\\n</previous-summary>`\n );\n }\n return parts.join('');\n}\n\n/** Creates an `onChunk` callback that dispatches `ON_SUMMARIZE_DELTA` events for streaming. */\nfunction createSummarizationChunkHandler({\n stepId,\n config,\n provider,\n reasoningKey = 'reasoning_content',\n}: {\n stepId?: string;\n config?: RunnableConfig;\n provider?: Providers;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n}): OnChunk | undefined {\n if (stepId == null || stepId === '' || !config) {\n return undefined;\n }\n return (chunk) => {\n const chunkAny = chunk as Parameters<typeof getChunkContent>[0]['chunk'];\n const raw = getChunkContent({ chunk: chunkAny, provider, reasoningKey });\n if (raw == null || (typeof raw === 'string' && !raw)) {\n return;\n }\n const contentBlocks: t.MessageContentComplex[] =\n typeof raw === 'string'\n ? [{ type: ContentTypes.TEXT, text: raw } as t.MessageContentComplex]\n : raw;\n\n safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_DELTA,\n {\n id: stepId,\n delta: {\n summary: {\n type: ContentTypes.SUMMARY,\n content: contentBlocks,\n provider: String(config.metadata?.summarization_provider ?? ''),\n model: String(config.metadata?.summarization_model ?? ''),\n },\n },\n } satisfies t.SummarizeDeltaEvent,\n config\n );\n };\n}\n\nfunction traceConfig(\n config: RunnableConfig | undefined,\n stage: string\n): RunnableConfig | undefined {\n if (!config) {\n return undefined;\n }\n return {\n ...config,\n runName: `summarization:${stage}`,\n metadata: { ...config.metadata, summarization: true, stage },\n };\n}\n\n/**\n * Cache-friendly compaction: sends raw conversation messages with the\n * summarization instruction appended as the final HumanMessage.\n * Providers with prompt caching get a cache hit on the system prompt +\n * tool definitions prefix.\n */\nasync function summarizeWithCacheHit({\n model,\n messages,\n promptText,\n updatePromptText,\n priorSummaryText,\n config,\n stepId,\n provider,\n reasoningKey,\n usePromptCache,\n log,\n}: {\n model: t.ChatModel;\n messages: BaseMessage[];\n promptText: string;\n updatePromptText?: string;\n priorSummaryText: string;\n config?: RunnableConfig;\n stepId?: string;\n provider: Providers;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n usePromptCache?: boolean;\n log?: LogFn;\n}): Promise<{ text: string; usage?: Partial<UsageMetadata> }> {\n const instruction = buildSummarizationInstruction(\n promptText,\n updatePromptText,\n priorSummaryText\n );\n\n const fullMessages = [...messages, new HumanMessage(instruction)];\n const invokeMessages =\n usePromptCache === true ? addCacheControl(fullMessages) : fullMessages;\n\n const result = await attemptInvoke(\n {\n model,\n messages: invokeMessages,\n provider,\n onChunk: createSummarizationChunkHandler({\n stepId,\n config: traceConfig(config, 'cache_hit_compaction'),\n provider,\n reasoningKey,\n }),\n },\n traceConfig(config, 'cache_hit_compaction')\n );\n\n const responseMsg = result.messages?.[0];\n const text = responseMsg\n ? extractResponseText(responseMsg as { content: string | object })\n : '';\n let usage: Partial<UsageMetadata> | undefined;\n let usageSource = 'none';\n if (\n responseMsg != null &&\n 'usage_metadata' in responseMsg &&\n responseMsg.usage_metadata != null\n ) {\n usage = responseMsg.usage_metadata as Partial<UsageMetadata>;\n usageSource = 'usage_metadata';\n } else if (responseMsg != null) {\n const respMeta = responseMsg.response_metadata as\n | Record<string, unknown>\n | undefined;\n const raw = (respMeta?.metadata as Record<string, unknown> | undefined)\n ?.usage as Record<string, unknown> | undefined;\n if (raw != null) {\n usage = {\n input_tokens: Number(raw.inputTokens) || undefined,\n output_tokens: Number(raw.outputTokens) || undefined,\n } as Partial<UsageMetadata>;\n usageSource = 'response_metadata';\n }\n }\n const cacheDetails = (\n usage as\n | {\n input_token_details?: {\n cache_read?: number;\n cache_creation?: number;\n };\n }\n | undefined\n )?.input_token_details;\n log?.('debug', 'Summarization LLM usage', {\n source: usageSource,\n input_tokens: usage?.input_tokens,\n output_tokens: usage?.output_tokens,\n ...(cacheDetails?.cache_read != null || cacheDetails?.cache_creation != null\n ? {\n 'input_token_details.cache_read': cacheDetails.cache_read,\n 'input_token_details.cache_creation': cacheDetails.cache_creation,\n }\n : {}),\n });\n return { text, usage };\n}\n"],"names":["messages","AIMessage","ToolMessage","getMaxOutputTokensKey","SystemMessage","ContentTypes","initializeModel","tryFallbackProviders","HumanMessage","safeDispatchCustomEvent","GraphEvents","emitAgentLog","StepTypes","createRemoveAllMessage","getChunkContent","addCacheControl","attemptInvoke"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC,CAAC,kBAAkB,CAAC,CAAC;AAE9D;;;;;AAKG;AACH,MAAM,+BAA+B,GAAG,EAAE;AAE1C;AACO,MAAM,4BAA4B,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmC5C;AACO,MAAM,mCAAmC,GAAG,CAAA;;;;;;;;;;;;;;AAenD,SAAS,kBAAkB,CAAC,UAAmC,EAAA;IAI7D,MAAM,SAAS,GAA4B,EAAE;AAC7C,IAAA,IAAI,gBAAoC;AAExC,IAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE;AACrD,QAAA,IAAI,wBAAwB,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACrC,IACE,GAAG,KAAK,kBAAkB;gBAC1B,OAAO,KAAK,KAAK,QAAQ;gBACzB,KAAK,GAAG,CAAC,EACT;gBACA,gBAAgB,GAAG,KAAK;YAC1B;QACF;aAAO;AACL,YAAA,SAAS,CAAC,GAAG,CAAC,GAAG,KAAK;QACxB;IACF;AAEA,IAAA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE;AACxC;AAEA;;;;AAIG;AACH,SAAS,oBAAoB,CAACA,UAAuB,EAAA;IACnD,MAAM,MAAM,GAA2B,EAAE;AACzC,IAAA,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU;AAEnC,IAAA,KAAK,MAAM,GAAG,IAAIA,UAAQ,EAAE;AAC1B,QAAA,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,EAAE;AAC1B,QAAA,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AA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QACnB,YAAY,EAAE,KAAK,EAAE,YAAY;QACjC,aAAa,EAAE,KAAK,EAAE,aAAa;QACnC,IAAI,YAAY,EAAE,UAAU,IAAI,IAAI,IAAI,YAAY,EAAE,cAAc,IAAI;AACtE,cAAE;gBACA,gCAAgC,EAAE,YAAY,CAAC,UAAU;gBACzD,oCAAoC,EAAE,YAAY,CAAC,cAAc;AAClE;cACC,EAAE,CAAC;AACR,KAAA,CAAC;AACF,IAAA,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE;AACxB;;;;;;"}
|
|
1
|
+
{"version":3,"file":"node.cjs","sources":["../../../src/summarization/node.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { UsageMetadata, BaseMessage } from '@langchain/core/messages';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { HookRegistry } from '@/hooks';\nimport type { OnChunk } from '@/llm/invoke';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes, Providers } from '@/common';\nimport { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';\nimport { attemptInvoke, tryFallbackProviders } from '@/llm/invoke';\nimport { createRemoveAllMessage } from '@/messages/reducer';\nimport { getMaxOutputTokensKey } from '@/llm/request';\nimport { addCacheControl } from '@/messages/cache';\nimport { initializeModel } from '@/llm/init';\nimport { getChunkContent } from '@/stream';\nimport { executeHooks } from '@/hooks';\n\nconst SUMMARIZATION_PARAM_KEYS = new Set(['maxSummaryTokens']);\n\n/**\n * Token overhead of the XML wrapper + instruction text added around the\n * summary at injection time in AgentContext.buildSystemRunnable:\n * `<summary>\\n${text}\\n</summary>\\n\\nYour context window was compacted...`\n * ~33 tokens on Anthropic, ~24-27 on OpenAI. Using 33 as a safe ceiling.\n */\nconst SUMMARY_WRAPPER_OVERHEAD_TOKENS = 33;\n\n/** Structured checkpoint prompt for fresh summarization (no prior summary). */\nexport const DEFAULT_SUMMARIZATION_PROMPT = `Hold on, before you continue I need you to write me a checkpoint of everything so far. Your context window is filling up and this checkpoint replaces the messages above, so capture everything you need to pick right back up.\n\nDon't second-guess or fact-check anything you did, your tool results reflect exactly what happened. If a tool result appears truncated, that's just a display artifact from context management: the tool executed fully. Just record what you did and what you observed. Only the checkpoint, don't respond to me or continue the conversation.\n\n## Checkpoint\n\n## Goal\nWhat I asked you to do and any sub-goals you identified.\n\n## Constraints & Preferences\nAny rules, preferences, or configuration I established.\n\n## Progress\n### Done\n- What you completed and the outcomes\n\n### In Progress\n- What you're currently working on\n\n## Key Decisions\nDecisions you made and why.\n\n## Next Steps\nConcrete task actions remaining, in priority order.\n\n## Critical Context\nExact identifiers, names, error messages, URLs, and details you need to preserve verbatim.\n\nRules:\n- Record what you did and observed, don't judge or re-evaluate it\n- For each tool call: the tool name, key inputs, and the outcome\n- Preserve exact identifiers, names, errors, and references verbatim\n- Short declarative sentences\n- Skip empty sections`;\n\n/** Prompt for re-compaction when a prior summary exists. */\nexport const DEFAULT_UPDATE_SUMMARIZATION_PROMPT = `Hold on again, update your checkpoint. Merge the new messages into your existing checkpoint and give me a single consolidated replacement.\n\nKeep it roughly the same length as your last checkpoint. Compress older details to make room for what's new, don't just append. Give recent actions more detail, compress older items to one-liners.\n\nDon't fact-check or second-guess anything, your tool results are ground truth. If a tool result appears truncated, that's just a display artifact: the tool executed fully. Only the checkpoint, don't respond to me or continue the conversation.\n\nRules:\n- Merge new progress into existing sections, don't duplicate headers\n- Compress older completed items into one-line entries\n- Move items from \"In Progress\" to \"Done\" when you completed them\n- Update \"Next Steps\" to reflect current task priorities.\n- For each new tool call: the tool name, key inputs, and the outcome\n- Preserve exact identifiers, names, errors, and references verbatim\n- Skip empty sections`;\n\nfunction separateParameters(parameters: Record<string, unknown>): {\n llmParams: Record<string, unknown>;\n maxSummaryTokens?: number;\n} {\n const llmParams: Record<string, unknown> = {};\n let maxSummaryTokens: number | undefined;\n\n for (const [key, value] of Object.entries(parameters)) {\n if (SUMMARIZATION_PARAM_KEYS.has(key)) {\n if (\n key === 'maxSummaryTokens' &&\n typeof value === 'number' &&\n value > 0\n ) {\n maxSummaryTokens = value;\n }\n } else {\n llmParams[key] = value;\n }\n }\n\n return { llmParams, maxSummaryTokens };\n}\n\n/**\n * Generates a structural metadata summary without making an LLM call.\n * Used as a last-resort fallback when all summarization attempts fail.\n * Preserves tool names and message counts so the agent retains basic context.\n */\nfunction generateMetadataStub(messages: BaseMessage[]): string {\n const counts: Record<string, number> = {};\n const toolNames = new Set<string>();\n\n for (const msg of messages) {\n const role = msg.getType();\n counts[role] = (counts[role] ?? 0) + 1;\n\n if (role === 'tool' && msg.name != null && msg.name !== '') {\n toolNames.add(msg.name);\n }\n\n if (\n role === 'ai' &&\n msg instanceof AIMessage &&\n msg.tool_calls &&\n msg.tool_calls.length > 0\n ) {\n for (const tc of msg.tool_calls) {\n toolNames.add(tc.name);\n }\n }\n }\n\n const countParts = Object.entries(counts)\n .map(([role, count]) => `${count} ${role}`)\n .join(', ');\n\n const lines = [\n `[Metadata summary: ${messages.length} messages (${countParts})]`,\n ];\n\n if (toolNames.size > 0) {\n lines.push(`[Tools used: ${Array.from(toolNames).join(', ')}]`);\n }\n\n return lines.join('\\n');\n}\n\n/** Maximum number of tool failures to include in the enrichment section. */\nconst MAX_TOOL_FAILURES = 8;\n/** Maximum chars per failure summary line. */\nconst MAX_TOOL_FAILURE_CHARS = 240;\n\n/**\n * Extracts failed tool results from messages and formats them as a structured\n * section. LLMs often omit specific failure details (exit codes, error messages)\n * from their summaries, this mechanical enrichment guarantees they survive.\n */\nfunction extractToolFailuresSection(messages: BaseMessage[]): string {\n const failures: Array<{ toolName: string; summary: string }> = [];\n const seen = new Set<string>();\n\n for (const msg of messages) {\n if (msg.getType() !== 'tool') {\n continue;\n }\n const toolMsg = msg as ToolMessage;\n if (toolMsg.status !== 'error') {\n continue;\n }\n // Deduplicate by tool_call_id\n const callId = toolMsg.tool_call_id;\n if (callId && seen.has(callId)) {\n continue;\n }\n if (callId) {\n seen.add(callId);\n }\n\n const toolName = toolMsg.name ?? 'tool';\n const content =\n typeof toolMsg.content === 'string'\n ? toolMsg.content\n : JSON.stringify(toolMsg.content);\n const normalized = content.replace(/\\s+/g, ' ').trim();\n const summary =\n normalized.length > MAX_TOOL_FAILURE_CHARS\n ? `${normalized.slice(0, MAX_TOOL_FAILURE_CHARS - 3)}...`\n : normalized;\n\n failures.push({ toolName, summary });\n }\n\n if (failures.length === 0) {\n return '';\n }\n\n const lines = failures\n .slice(0, MAX_TOOL_FAILURES)\n .map((f) => `- ${f.toolName}: ${f.summary}`);\n if (failures.length > MAX_TOOL_FAILURES) {\n lines.push(`- ...and ${failures.length - MAX_TOOL_FAILURES} more`);\n }\n\n return `\\n\\n## Tool Failures\\n${lines.join('\\n')}`;\n}\n\n/**\n * Appends mechanical enrichment sections to an LLM-generated summary.\n * Tool failures are appended verbatim because LLMs often omit specific\n * error details from their summaries.\n */\nfunction enrichSummary(summaryText: string, messages: BaseMessage[]): string {\n return summaryText + extractToolFailuresSection(messages);\n}\n\n/**\n * Restores pre-masking tool content onto the messages array using\n * `pendingOriginalToolContent` stored on AgentContext. Only allocates\n * a new array when there are entries to restore; otherwise returns the\n * input reference unchanged.\n */\nfunction restoreOriginalToolContent(\n messages: BaseMessage[],\n originalToolContent: Map<number, string> | undefined\n): BaseMessage[] {\n if (originalToolContent == null || originalToolContent.size === 0) {\n return messages;\n }\n const restored = [...messages];\n for (const [idx, content] of originalToolContent) {\n const msg = restored[idx];\n if (msg instanceof ToolMessage) {\n restored[idx] = new ToolMessage({\n content,\n tool_call_id: msg.tool_call_id,\n name: msg.name,\n id: msg.id,\n additional_kwargs: msg.additional_kwargs,\n response_metadata: msg.response_metadata,\n });\n }\n }\n return restored;\n}\n\n// ---------------------------------------------------------------------------\n// Extracted helpers for createSummarizeNode\n// ---------------------------------------------------------------------------\n\ninterface SummarizationClientConfig {\n provider: string;\n modelName?: string;\n clientOptions: Record<string, unknown>;\n effectiveMaxSummaryTokens?: number;\n promptText: string;\n updatePromptText: string;\n}\n\n/** Assembles the summarization model's client options from agent and config. */\nfunction buildSummarizationClientConfig(\n agentContext: AgentContext,\n summarizationConfig?: t.SummarizationConfig\n): SummarizationClientConfig {\n const provider = (summarizationConfig?.provider ??\n agentContext.provider) as string;\n const modelName = summarizationConfig?.model;\n const parameters = summarizationConfig?.parameters ?? {};\n const promptText =\n summarizationConfig?.prompt ?? DEFAULT_SUMMARIZATION_PROMPT;\n const updatePromptText =\n summarizationConfig?.updatePrompt ?? DEFAULT_UPDATE_SUMMARIZATION_PROMPT;\n\n const { llmParams, maxSummaryTokens: paramMaxSummaryTokens } =\n separateParameters(parameters);\n\n const isSelfSummarize = provider === (agentContext.provider as string);\n const baseOptions =\n isSelfSummarize && agentContext.clientOptions\n ? { ...agentContext.clientOptions }\n : {};\n\n const clientOptions: Record<string, unknown> = {\n ...baseOptions,\n ...llmParams,\n };\n\n if (modelName != null && modelName !== '') {\n clientOptions.model = modelName;\n clientOptions.modelName = modelName;\n }\n\n const effectiveMaxSummaryTokens =\n paramMaxSummaryTokens ?? summarizationConfig?.maxSummaryTokens;\n\n if (effectiveMaxSummaryTokens != null) {\n clientOptions[getMaxOutputTokensKey(provider)] = effectiveMaxSummaryTokens;\n }\n\n return {\n provider,\n modelName,\n clientOptions,\n effectiveMaxSummaryTokens,\n promptText,\n updatePromptText,\n };\n}\n\n/** Computes the token count for a summary, preferring provider output tokens when available. */\nfunction computeSummaryTokenCount(\n summaryText: string,\n summaryUsage: Partial<UsageMetadata> | undefined,\n tokenCounter?: (message: BaseMessage) => number\n): number {\n const providerOutputTokens = Number(summaryUsage?.output_tokens) || 0;\n if (providerOutputTokens > 0) {\n return providerOutputTokens + SUMMARY_WRAPPER_OVERHEAD_TOKENS;\n }\n if (tokenCounter) {\n return (\n tokenCounter(new SystemMessage(summaryText)) +\n SUMMARY_WRAPPER_OVERHEAD_TOKENS\n );\n }\n return 0;\n}\n\n/** Constructs the SummaryContentBlock persisted in the run step and dispatched to events. */\nfunction buildSummaryBlock(params: {\n summaryText: string;\n tokenCount: number;\n stepId: string;\n stepIndex: number;\n modelName?: string;\n provider: string;\n summaryVersion: number;\n}): t.SummaryContentBlock {\n return {\n type: ContentTypes.SUMMARY,\n content: [\n {\n type: ContentTypes.TEXT,\n text: params.summaryText,\n } as t.MessageContentComplex,\n ],\n tokenCount: params.tokenCount,\n summaryVersion: params.summaryVersion,\n boundary: {\n messageId: params.stepId,\n contentIndex: params.stepIndex,\n },\n model: params.modelName,\n provider: params.provider,\n createdAt: new Date().toISOString(),\n };\n}\n\ntype LogFn = (\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n data?: Record<string, unknown>\n) => void;\n\n/**\n * Extracts an HTTP status code from a thrown LLM-provider error. Returns\n * `undefined` for non-object values (including `null` or `undefined`, both\n * valid `throw` targets in JS) so callers never dereference a nullish\n * value.\n */\nfunction extractHttpStatus(err: unknown): number | undefined {\n if (err == null || typeof err !== 'object') {\n return undefined;\n }\n const errRecord = err as Record<string, unknown>;\n const direct = errRecord.status;\n if (typeof direct === 'number') {\n return direct;\n }\n const statusCode = errRecord.statusCode;\n if (typeof statusCode === 'number') {\n return statusCode;\n }\n const response = errRecord.response;\n if (response != null && typeof response === 'object') {\n const nested = (response as Record<string, unknown>).status;\n if (typeof nested === 'number') {\n return nested;\n }\n }\n return undefined;\n}\n\n/**\n * Formats a provider-level error for logging. Returns both a human-readable\n * suffix (safe to include in the message string so it survives any host-side\n * formatter) and a structured metadata bag for rich log backends.\n */\nfunction describeProviderError(\n err: unknown,\n provider: string,\n modelName?: string\n): { suffix: string; data: Record<string, unknown> } {\n const providerLabel = `${provider}/${modelName ?? '(no-model)'}`;\n const errMsg = err instanceof Error ? err.message : String(err);\n\n const data: Record<string, unknown> = {\n provider,\n model: modelName,\n };\n if (err instanceof Error) {\n data.errorName = err.name;\n data.errorStack = err.stack;\n }\n\n const status = extractHttpStatus(err);\n const statusSuffix = status != null ? ` (HTTP ${status})` : '';\n if (status != null) {\n data.status = status;\n }\n\n return {\n suffix: `[${providerLabel}]${statusSuffix}: ${errMsg}`,\n data,\n };\n}\n\n/**\n * Formats an exhausted-fallback error. `tryFallbackProviders` throws the\n * last fallback provider's error, which may be from any of the configured\n * fallbacks — not the primary — so we label the log with the list of\n * fallback providers attempted rather than mis-attributing to the primary.\n *\n * Entries in `fallbacks` are normally strongly typed, but we defend against\n * malformed runtime config (null/undefined entries, missing `provider`\n * field) so a recoverable summarization failure is never promoted to an\n * uncaught exception from inside the logging path.\n */\nfunction describeFallbackError(\n err: unknown,\n fallbacks: unknown\n): { suffix: string; data: Record<string, unknown> } {\n const errMsg = err instanceof Error ? err.message : String(err);\n const list: ReadonlyArray<unknown> = Array.isArray(fallbacks)\n ? fallbacks\n : [];\n const providerNames = list\n .map((f) => {\n if (f == null || typeof f !== 'object') {\n return undefined;\n }\n const raw = (f as { provider?: unknown }).provider;\n return raw != null ? String(raw) : undefined;\n })\n .filter((p): p is string => typeof p === 'string');\n const label =\n providerNames.length > 0\n ? `fallbacks=[${providerNames.join(',')}]`\n : 'no-fallbacks';\n\n const data: Record<string, unknown> = {\n fallbackProviders: providerNames,\n fallbackCount: list.length,\n };\n if (err instanceof Error) {\n data.errorName = err.name;\n data.errorStack = err.stack;\n }\n const status = extractHttpStatus(err);\n const statusSuffix = status != null ? ` (HTTP ${status})` : '';\n if (status != null) {\n data.status = status;\n }\n\n return {\n suffix: `[${label}]${statusSuffix}: ${errMsg}`,\n data,\n };\n}\n\n/**\n * Runs the summarization LLM call with primary + fallback providers,\n * falling back to a metadata stub when all calls fail.\n */\nasync function executeSummarizationWithFallback(params: {\n agentContext: AgentContext;\n messages: BaseMessage[];\n clientConfig: SummarizationClientConfig;\n summarizeConfig?: RunnableConfig;\n stepId: string;\n usePromptCache: boolean;\n log: LogFn;\n}): Promise<{ text: string; usage?: Partial<UsageMetadata> }> {\n const {\n agentContext,\n messages,\n clientConfig,\n summarizeConfig,\n stepId,\n usePromptCache,\n log,\n } = params;\n\n const priorSummaryText = agentContext.getSummaryText()?.trim() ?? '';\n\n let summaryText = '';\n let summaryUsage: Partial<UsageMetadata> | undefined;\n\n try {\n /**\n * Initialize inside the try so that a misconfigured provider\n * (e.g. an unrecognized summarization.provider) surfaces through the\n * `log('error', ...)` path below rather than bubbling up silently.\n */\n const summarizationModel = initializeModel({\n provider: clientConfig.provider as Providers,\n clientOptions: clientConfig.clientOptions as t.ClientOptions,\n tools: agentContext.getToolsForBinding(),\n }) as t.ChatModel;\n\n const result = await summarizeWithCacheHit({\n model: summarizationModel,\n messages,\n promptText: clientConfig.promptText,\n updatePromptText: clientConfig.updatePromptText,\n priorSummaryText,\n config: summarizeConfig,\n stepId,\n provider: clientConfig.provider as Providers,\n reasoningKey: agentContext.reasoningKey,\n usePromptCache,\n log,\n });\n summaryText = result.text;\n summaryUsage = result.usage;\n } catch (primaryError) {\n const primaryDescribed = describeProviderError(\n primaryError,\n clientConfig.provider,\n clientConfig.modelName\n );\n log('error', `Summarization LLM call failed ${primaryDescribed.suffix}`, {\n ...primaryDescribed.data,\n messagesToRefineCount: messages.length,\n });\n\n const rawFallbacks = (\n clientConfig.clientOptions as unknown as t.LLMConfig | undefined\n )?.fallbacks;\n const fallbacks = Array.isArray(rawFallbacks) ? rawFallbacks : [];\n if (fallbacks.length > 0) {\n try {\n const onChunk = createSummarizationChunkHandler({\n stepId,\n config: traceConfig(summarizeConfig, 'cache_hit_compaction'),\n provider: clientConfig.provider as Providers,\n reasoningKey: agentContext.reasoningKey,\n });\n const fbResult = await tryFallbackProviders({\n fallbacks,\n tools: agentContext.getToolsForBinding(),\n messages: [\n ...messages,\n new HumanMessage(\n buildSummarizationInstruction(\n clientConfig.promptText,\n clientConfig.updatePromptText,\n priorSummaryText\n )\n ),\n ],\n config: traceConfig(summarizeConfig, 'cache_hit_compaction'),\n primaryError,\n onChunk,\n });\n const fbMsg = fbResult?.messages?.[0];\n if (fbMsg) {\n summaryText = extractResponseText(\n fbMsg as { content: string | object }\n );\n }\n } catch (fbErr) {\n const fbDescribed = describeFallbackError(fbErr, fallbacks);\n log('warn', `Fallback providers also failed ${fbDescribed.suffix}`, {\n ...fbDescribed.data,\n });\n }\n }\n if (!summaryText) {\n log(\n 'warn',\n `Summarization failed, falling back to metadata stub ${primaryDescribed.suffix}`,\n {\n ...primaryDescribed.data,\n messagesToRefineCount: messages.length,\n }\n );\n summaryText = generateMetadataStub(messages);\n }\n }\n\n return { text: summaryText, usage: summaryUsage };\n}\n\n/** Dispatches run step completion, ON_SUMMARIZE_COMPLETE, and rebuilds token map. */\nasync function dispatchCompletionEvents(params: {\n graph: CreateSummarizeNodeParams['graph'];\n runnableConfig?: RunnableConfig;\n stepId: string;\n summaryBlock: t.SummaryContentBlock;\n agentContext: AgentContext;\n runStep: t.RunStep;\n summaryUsage?: Partial<UsageMetadata>;\n agentId: string;\n}): Promise<void> {\n const {\n graph,\n runnableConfig,\n stepId,\n summaryBlock,\n agentContext,\n runStep,\n summaryUsage,\n agentId,\n } = params;\n\n runStep.summary = summaryBlock;\n if (summaryUsage) {\n runStep.usage = {\n prompt_tokens: Number(summaryUsage.input_tokens) || 0,\n completion_tokens: Number(summaryUsage.output_tokens) || 0,\n total_tokens:\n (Number(summaryUsage.input_tokens) || 0) +\n (Number(summaryUsage.output_tokens) || 0),\n };\n }\n\n await graph.dispatchRunStepCompleted(\n stepId,\n { type: 'summary', summary: summaryBlock } satisfies t.SummaryCompleted,\n runnableConfig\n );\n\n if (runnableConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_COMPLETE,\n {\n id: stepId,\n agentId,\n summary: summaryBlock,\n } satisfies t.SummarizeCompleteEvent,\n runnableConfig\n );\n }\n\n const sessionId = graph.runId ?? '';\n if (graph.hookRegistry?.hasHookFor('PostCompact', sessionId) === true) {\n const threadId = (\n runnableConfig?.configurable as Record<string, unknown> | undefined\n )?.thread_id as string | undefined;\n const firstBlock = summaryBlock.content?.[0];\n const summaryText =\n firstBlock != null &&\n typeof firstBlock === 'object' &&\n 'text' in firstBlock &&\n typeof firstBlock.text === 'string'\n ? firstBlock.text\n : '';\n await executeHooks({\n registry: graph.hookRegistry,\n input: {\n hook_event_name: 'PostCompact',\n runId: sessionId,\n threadId,\n agentId,\n summary: summaryText,\n messagesAfterCount: 0,\n },\n sessionId,\n }).catch(() => {\n /* PostCompact is observational — swallow errors */\n });\n }\n\n agentContext.rebuildTokenMapAfterSummarization({});\n}\n\n// ---------------------------------------------------------------------------\n// createSummarizeNode\n// ---------------------------------------------------------------------------\n\ninterface CreateSummarizeNodeParams {\n agentContext: AgentContext;\n graph: {\n contentData: t.RunStep[];\n contentIndexMap: Map<string, number>;\n config?: RunnableConfig;\n runId?: string;\n isMultiAgent: boolean;\n hookRegistry?: HookRegistry;\n dispatchRunStep: (\n runStep: t.RunStep,\n config?: RunnableConfig\n ) => Promise<void>;\n dispatchRunStepCompleted: (\n stepId: string,\n result: t.StepCompleted,\n config?: RunnableConfig\n ) => Promise<void>;\n };\n generateStepId: (stepKey: string) => [string, number];\n}\n\nexport function createSummarizeNode({\n agentContext,\n graph,\n generateStepId,\n}: CreateSummarizeNodeParams) {\n return async (\n state: {\n messages: BaseMessage[];\n summarizationRequest?: t.SummarizationNodeInput;\n },\n config?: RunnableConfig\n ): Promise<{ summarizationRequest: undefined; messages?: BaseMessage[] }> => {\n const request = state.summarizationRequest;\n if (request == null) {\n return { summarizationRequest: undefined };\n }\n\n const maxCtx = agentContext.maxContextTokens ?? 0;\n if (maxCtx > 0 && agentContext.instructionTokens >= maxCtx) {\n emitAgentLog(\n config,\n 'warn',\n 'summarize',\n 'Summarization skipped, instructions exceed context budget. Reduce the number of tools or increase maxContextTokens.',\n {\n instructionTokens: agentContext.instructionTokens,\n maxContextTokens: maxCtx,\n breakdown: agentContext.formatTokenBudgetBreakdown(),\n },\n { runId: graph.runId, agentId: request.agentId }\n );\n return { summarizationRequest: undefined };\n }\n\n const messagesToRefine = restoreOriginalToolContent(\n state.messages,\n agentContext.pendingOriginalToolContent\n );\n agentContext.pendingOriginalToolContent = undefined;\n\n const clientConfig = buildSummarizationClientConfig(\n agentContext,\n agentContext.summarizationConfig\n );\n\n const runnableConfig = config ?? graph.config;\n\n const stepKey = `summarize-${request.agentId}`;\n const [stepId, stepIndex] = generateStepId(stepKey);\n\n const placeholderSummary: t.SummaryContentBlock = {\n type: ContentTypes.SUMMARY,\n model: clientConfig.modelName,\n provider: clientConfig.provider,\n };\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: StepTypes.MESSAGE_CREATION,\n index: graph.contentData.length,\n stepDetails: {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: { message_id: stepId },\n },\n summary: placeholderSummary,\n usage: null,\n };\n\n if (graph.runId != null && graph.runId !== '') {\n runStep.runId = graph.runId;\n }\n if (graph.isMultiAgent && agentContext.agentId) {\n runStep.agentId = agentContext.agentId;\n }\n\n await graph.dispatchRunStep(runStep, runnableConfig);\n\n if (runnableConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_START,\n {\n agentId: request.agentId,\n provider: clientConfig.provider,\n model: clientConfig.modelName,\n messagesToRefineCount: messagesToRefine.length,\n summaryVersion: agentContext.summaryVersion + 1,\n } satisfies t.SummarizeStartEvent,\n runnableConfig\n );\n }\n\n const sessionId = graph.runId ?? '';\n if (graph.hookRegistry?.hasHookFor('PreCompact', sessionId) === true) {\n const threadId = (\n runnableConfig?.configurable as Record<string, unknown> | undefined\n )?.thread_id as string | undefined;\n await executeHooks({\n registry: graph.hookRegistry,\n input: {\n hook_event_name: 'PreCompact',\n runId: sessionId,\n threadId,\n agentId: request.agentId,\n messagesBeforeCount: messagesToRefine.length,\n trigger: agentContext.summarizationConfig?.trigger?.type ?? 'default',\n },\n sessionId,\n }).catch(() => {\n /* PreCompact is observational — swallow errors */\n });\n }\n\n const isSelfSummarizeModel =\n clientConfig.provider === (agentContext.provider as string);\n const hasPromptCache =\n isSelfSummarizeModel &&\n (agentContext.clientOptions as Record<string, unknown> | undefined)\n ?.promptCache === true;\n\n const log: LogFn = (level, message, data) => {\n emitAgentLog(runnableConfig, level, 'summarize', message, data, {\n runId: graph.runId,\n agentId: request.agentId,\n });\n };\n\n log('debug', 'Summarization starting', {\n messagesToRefineCount: messagesToRefine.length,\n hasPriorSummary: (agentContext.getSummaryText()?.trim() ?? '') !== '',\n summaryVersion: agentContext.summaryVersion + 1,\n isSelfSummarize: isSelfSummarizeModel,\n hasPromptCache,\n provider: clientConfig.provider,\n });\n\n const summarizeConfig: RunnableConfig | undefined = config\n ? {\n ...config,\n metadata: {\n ...config.metadata,\n agent_id: request.agentId,\n summarization_provider: clientConfig.provider,\n summarization_model: clientConfig.modelName,\n },\n }\n : undefined;\n\n const { text: rawText, usage: summaryUsage } =\n await executeSummarizationWithFallback({\n agentContext,\n messages: messagesToRefine,\n clientConfig,\n summarizeConfig,\n stepId,\n usePromptCache: isSelfSummarizeModel && hasPromptCache,\n log,\n });\n\n if (!rawText) {\n agentContext.markSummarizationTriggered(0);\n if (runnableConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_COMPLETE,\n {\n id: stepId,\n agentId: request.agentId,\n error: 'Summarization produced empty output',\n } satisfies t.SummarizeCompleteEvent,\n runnableConfig\n );\n }\n return { summarizationRequest: undefined };\n }\n\n const summaryText = enrichSummary(rawText, messagesToRefine);\n\n const tokenCount = computeSummaryTokenCount(\n summaryText,\n summaryUsage,\n agentContext.tokenCounter\n );\n\n agentContext.setSummary(summaryText, tokenCount);\n\n log('info', 'Summary persisted');\n log('debug', 'Summary details', {\n summaryTokens: tokenCount,\n textLength: summaryText.length,\n messagesCompacted: messagesToRefine.length,\n summaryVersion: agentContext.summaryVersion,\n ...(summaryUsage != null\n ? {\n input_tokens: summaryUsage.input_tokens,\n output_tokens: summaryUsage.output_tokens,\n cache_read: summaryUsage.input_token_details?.cache_read,\n cache_creation: summaryUsage.input_token_details?.cache_creation,\n }\n : {}),\n });\n\n const summaryBlock = buildSummaryBlock({\n summaryText,\n tokenCount,\n stepId,\n stepIndex: runStep.index,\n modelName: clientConfig.modelName,\n provider: clientConfig.provider,\n summaryVersion: agentContext.summaryVersion,\n });\n\n await dispatchCompletionEvents({\n graph,\n runnableConfig,\n stepId,\n summaryBlock,\n agentContext,\n runStep,\n summaryUsage,\n agentId: request.agentId,\n });\n\n return {\n summarizationRequest: undefined,\n messages: [createRemoveAllMessage()],\n };\n };\n}\n\n/** Extracts text from an LLM response, skipping reasoning/thinking blocks. */\nfunction extractResponseText(response: { content: string | object }): string {\n const { content } = response;\n if (typeof content === 'string') {\n return content.trim();\n }\n if (!Array.isArray(content)) {\n return '';\n }\n const parts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n parts.push(block);\n continue;\n }\n if (block == null || typeof block !== 'object') {\n continue;\n }\n const rec = block as Record<string, unknown>;\n if (\n rec.type === ContentTypes.THINKING ||\n rec.type === ContentTypes.REASONING_CONTENT ||\n rec.type === 'redacted_thinking'\n ) {\n continue;\n }\n if (rec.type === 'text' && typeof rec.text === 'string') {\n parts.push(rec.text);\n }\n }\n return parts.join('').trim();\n}\n\nfunction buildSummarizationInstruction(\n promptText: string,\n updatePromptText: string | undefined,\n priorSummaryText: string\n): string {\n const effectivePrompt = priorSummaryText\n ? (updatePromptText ?? promptText)\n : promptText;\n const parts = [effectivePrompt];\n if (priorSummaryText) {\n parts.push(\n `\\n\\n<previous-summary>\\n${priorSummaryText}\\n</previous-summary>`\n );\n }\n return parts.join('');\n}\n\n/** Creates an `onChunk` callback that dispatches `ON_SUMMARIZE_DELTA` events for streaming. */\nfunction createSummarizationChunkHandler({\n stepId,\n config,\n provider,\n reasoningKey = 'reasoning_content',\n}: {\n stepId?: string;\n config?: RunnableConfig;\n provider?: Providers;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n}): OnChunk | undefined {\n if (stepId == null || stepId === '' || !config) {\n return undefined;\n }\n return (chunk) => {\n const chunkAny = chunk as Parameters<typeof getChunkContent>[0]['chunk'];\n const raw = getChunkContent({ chunk: chunkAny, provider, reasoningKey });\n if (raw == null || (typeof raw === 'string' && !raw)) {\n return;\n }\n const contentBlocks: t.MessageContentComplex[] =\n typeof raw === 'string'\n ? [{ type: ContentTypes.TEXT, text: raw } as t.MessageContentComplex]\n : raw;\n\n safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_DELTA,\n {\n id: stepId,\n delta: {\n summary: {\n type: ContentTypes.SUMMARY,\n content: contentBlocks,\n provider: String(config.metadata?.summarization_provider ?? ''),\n model: String(config.metadata?.summarization_model ?? ''),\n },\n },\n } satisfies t.SummarizeDeltaEvent,\n config\n );\n };\n}\n\nfunction traceConfig(\n config: RunnableConfig | undefined,\n stage: string\n): RunnableConfig | undefined {\n if (!config) {\n return undefined;\n }\n return {\n ...config,\n runName: `summarization:${stage}`,\n metadata: { ...config.metadata, summarization: true, stage },\n };\n}\n\n/**\n * Cache-friendly compaction: sends raw conversation messages with the\n * summarization instruction appended as the final HumanMessage.\n * Providers with prompt caching get a cache hit on the system prompt +\n * tool definitions prefix.\n */\nasync function summarizeWithCacheHit({\n model,\n messages,\n promptText,\n updatePromptText,\n priorSummaryText,\n config,\n stepId,\n provider,\n reasoningKey,\n usePromptCache,\n log,\n}: {\n model: t.ChatModel;\n messages: BaseMessage[];\n promptText: string;\n updatePromptText?: string;\n priorSummaryText: string;\n config?: RunnableConfig;\n stepId?: string;\n provider: Providers;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n usePromptCache?: boolean;\n log?: LogFn;\n}): Promise<{ text: string; usage?: Partial<UsageMetadata> }> {\n const instruction = buildSummarizationInstruction(\n promptText,\n updatePromptText,\n priorSummaryText\n );\n\n const fullMessages = [...messages, new HumanMessage(instruction)];\n const invokeMessages =\n usePromptCache === true ? addCacheControl(fullMessages) : fullMessages;\n\n const result = await attemptInvoke(\n {\n model,\n messages: invokeMessages,\n provider,\n onChunk: createSummarizationChunkHandler({\n stepId,\n config: traceConfig(config, 'cache_hit_compaction'),\n provider,\n reasoningKey,\n }),\n },\n traceConfig(config, 'cache_hit_compaction')\n );\n\n const responseMsg = result.messages?.[0];\n const text = responseMsg\n ? extractResponseText(responseMsg as { content: string | object })\n : '';\n let usage: Partial<UsageMetadata> | undefined;\n let usageSource = 'none';\n if (\n responseMsg != null &&\n 'usage_metadata' in responseMsg &&\n responseMsg.usage_metadata != null\n ) {\n usage = responseMsg.usage_metadata as Partial<UsageMetadata>;\n usageSource = 'usage_metadata';\n } else if (responseMsg != null) {\n const respMeta = responseMsg.response_metadata as\n | Record<string, unknown>\n | undefined;\n const raw = (respMeta?.metadata as Record<string, unknown> | undefined)\n ?.usage as Record<string, unknown> | undefined;\n if (raw != null) {\n usage = {\n input_tokens: Number(raw.inputTokens) || undefined,\n output_tokens: Number(raw.outputTokens) || undefined,\n } as Partial<UsageMetadata>;\n usageSource = 'response_metadata';\n }\n }\n const cacheDetails = (\n usage as\n | {\n input_token_details?: {\n cache_read?: number;\n cache_creation?: number;\n };\n }\n | undefined\n )?.input_token_details;\n log?.('debug', 'Summarization LLM usage', {\n source: usageSource,\n input_tokens: usage?.input_tokens,\n output_tokens: usage?.output_tokens,\n ...(cacheDetails?.cache_read != null || cacheDetails?.cache_creation != null\n ? {\n 'input_token_details.cache_read': cacheDetails.cache_read,\n 'input_token_details.cache_creation': cacheDetails.cache_creation,\n }\n : {}),\n });\n return { text, usage };\n}\n"],"names":["messages","AIMessage","ToolMessage","getMaxOutputTokensKey","SystemMessage","ContentTypes","initializeModel","tryFallbackProviders","HumanMessage","safeDispatchCustomEvent","GraphEvents","executeHooks","emitAgentLog","StepTypes","createRemoveAllMessage","getChunkContent","addCacheControl","attemptInvoke"],"mappings":";;;;;;;;;;;;;AAsBA,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAAC,CAAC,kBAAkB,CAAC,CAAC;AAE9D;;;;;AAKG;AACH,MAAM,+BAA+B,GAAG,EAAE;AAE1C;AACO,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YAAY;QACjC,aAAa,EAAE,KAAK,EAAE,aAAa;QACnC,IAAI,YAAY,EAAE,UAAU,IAAI,IAAI,IAAI,YAAY,EAAE,cAAc,IAAI;AACtE,cAAE;gBACA,gCAAgC,EAAE,YAAY,CAAC,UAAU;gBACzD,oCAAoC,EAAE,YAAY,CAAC,cAAc;AAClE;cACC,EAAE,CAAC;AACR,KAAA,CAAC;AACF,IAAA,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE;AACxB;;;;;;"}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var dotenv = require('dotenv');
|
|
4
|
+
var fetch = require('node-fetch');
|
|
5
|
+
var httpsProxyAgent = require('https-proxy-agent');
|
|
6
|
+
var tools = require('@langchain/core/tools');
|
|
7
|
+
var CodeExecutor = require('./CodeExecutor.cjs');
|
|
8
|
+
var _enum = require('../common/enum.cjs');
|
|
9
|
+
|
|
10
|
+
dotenv.config();
|
|
11
|
+
const imageMessage = 'Image is already displayed to the user';
|
|
12
|
+
const otherMessage = 'File is already downloaded by the user';
|
|
13
|
+
const accessMessage = 'Note: Files from previous executions are automatically available and can be modified.';
|
|
14
|
+
const emptyOutputMessage = 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
|
|
15
|
+
const baseEndpoint = CodeExecutor.getCodeBaseURL();
|
|
16
|
+
const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
|
|
17
|
+
const BashExecutionToolSchema = {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
command: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
description: `The bash command or script to execute.
|
|
23
|
+
- The environment is stateless; variables and state don't persist between executions.
|
|
24
|
+
- Generated files from previous executions are automatically available in "/mnt/data/".
|
|
25
|
+
- Files from previous executions are automatically available and can be modified in place.
|
|
26
|
+
- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
|
|
27
|
+
- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
|
|
28
|
+
- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
|
|
29
|
+
- Use \`echo\`, \`printf\`, or \`cat\` for all outputs.`,
|
|
30
|
+
},
|
|
31
|
+
args: {
|
|
32
|
+
type: 'array',
|
|
33
|
+
items: { type: 'string' },
|
|
34
|
+
description: 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
required: ['command'],
|
|
38
|
+
};
|
|
39
|
+
const BashExecutionToolDescription = `
|
|
40
|
+
Runs bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.
|
|
41
|
+
|
|
42
|
+
Usage:
|
|
43
|
+
- No network access available.
|
|
44
|
+
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
45
|
+
- NEVER use this tool to execute malicious commands.
|
|
46
|
+
`.trim();
|
|
47
|
+
/**
|
|
48
|
+
* Supplemental prompt documenting the tool-output reference feature.
|
|
49
|
+
*
|
|
50
|
+
* Hosts should append this (separated by a blank line) to the base
|
|
51
|
+
* {@link BashExecutionToolDescription} only when
|
|
52
|
+
* `RunConfig.toolOutputReferences.enabled` is `true`. When the feature
|
|
53
|
+
* is disabled, including this text would tell the LLM to emit
|
|
54
|
+
* `{{tool0turn0}}` placeholders that pass through unsubstituted and
|
|
55
|
+
* leak into the shell.
|
|
56
|
+
*/
|
|
57
|
+
const BashToolOutputReferencesGuide = `
|
|
58
|
+
Referencing previous tool outputs:
|
|
59
|
+
- Every successful tool result is tagged with a reference key of the form \`tool<idx>turn<turn>\` (e.g., \`tool0turn0\`). The key appears either as a \`[ref: tool0turn0]\` prefix line or, when the output is a JSON object, as a \`_ref\` field on the object.
|
|
60
|
+
- To pipe a previous tool output into this tool, embed the placeholder \`{{tool<idx>turn<turn>}}\` literally anywhere in the \`command\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.
|
|
61
|
+
- The substituted value is the original output string (no \`[ref: …]\` prefix, no \`_ref\` key), so it is safe to pipe directly into \`jq\`, \`grep\`, \`awk\`, etc.
|
|
62
|
+
- Example: \`echo '{{tool0turn0}}' | jq '.foo'\` takes the full output of the first tool from the first turn and pipes it into jq.
|
|
63
|
+
- Unknown reference keys are left in place and surfaced as \`[unresolved refs: …]\` after the output.
|
|
64
|
+
`.trim();
|
|
65
|
+
/**
|
|
66
|
+
* Composes the bash tool description, optionally appending the
|
|
67
|
+
* tool-output references guide. Hosts that enable
|
|
68
|
+
* `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`
|
|
69
|
+
* when registering the tool so the LLM learns the `{{…}}` syntax it
|
|
70
|
+
* will actually be able to use.
|
|
71
|
+
*/
|
|
72
|
+
function buildBashExecutionToolDescription(options) {
|
|
73
|
+
if (options?.enableToolOutputReferences === true) {
|
|
74
|
+
return `${BashExecutionToolDescription}\n\n${BashToolOutputReferencesGuide}`;
|
|
75
|
+
}
|
|
76
|
+
return BashExecutionToolDescription;
|
|
77
|
+
}
|
|
78
|
+
const BashExecutionToolName = _enum.Constants.BASH_TOOL;
|
|
79
|
+
/**
|
|
80
|
+
* Default bash tool definition using the base description.
|
|
81
|
+
*
|
|
82
|
+
* When `RunConfig.toolOutputReferences.enabled` is `true`, build a
|
|
83
|
+
* reference-aware description with
|
|
84
|
+
* {@link buildBashExecutionToolDescription}
|
|
85
|
+
* (`{ enableToolOutputReferences: true }`) and construct a custom
|
|
86
|
+
* definition using it — using this constant as-is leaves the LLM
|
|
87
|
+
* unaware of the `{{tool<i>turn<n>}}` syntax.
|
|
88
|
+
*/
|
|
89
|
+
const BashExecutionToolDefinition = {
|
|
90
|
+
name: BashExecutionToolName,
|
|
91
|
+
description: BashExecutionToolDescription,
|
|
92
|
+
schema: BashExecutionToolSchema,
|
|
93
|
+
};
|
|
94
|
+
function createBashExecutionTool(params = {}) {
|
|
95
|
+
return tools.tool(async (rawInput, config) => {
|
|
96
|
+
const { command, ...rest } = rawInput;
|
|
97
|
+
const { session_id, _injected_files } = (config.toolCall ?? {});
|
|
98
|
+
const postData = {
|
|
99
|
+
lang: 'bash',
|
|
100
|
+
code: command,
|
|
101
|
+
...rest,
|
|
102
|
+
...params,
|
|
103
|
+
};
|
|
104
|
+
if (_injected_files && _injected_files.length > 0) {
|
|
105
|
+
postData.files = _injected_files;
|
|
106
|
+
}
|
|
107
|
+
else if (session_id != null && session_id.length > 0) {
|
|
108
|
+
try {
|
|
109
|
+
const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
|
|
110
|
+
const fetchOptions = {
|
|
111
|
+
method: 'GET',
|
|
112
|
+
headers: {
|
|
113
|
+
'User-Agent': 'LibreChat/1.0',
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
117
|
+
fetchOptions.agent = new httpsProxyAgent.HttpsProxyAgent(process.env.PROXY);
|
|
118
|
+
}
|
|
119
|
+
const response = await fetch(filesEndpoint, fetchOptions);
|
|
120
|
+
if (!response.ok) {
|
|
121
|
+
throw new Error(`Failed to fetch files for session: ${response.status}`);
|
|
122
|
+
}
|
|
123
|
+
const files = await response.json();
|
|
124
|
+
if (Array.isArray(files) && files.length > 0) {
|
|
125
|
+
const fileReferences = files.map((file) => {
|
|
126
|
+
const nameParts = file.name.split('/');
|
|
127
|
+
const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
|
|
128
|
+
return {
|
|
129
|
+
session_id,
|
|
130
|
+
id,
|
|
131
|
+
name: file.metadata['original-filename'],
|
|
132
|
+
};
|
|
133
|
+
});
|
|
134
|
+
postData.files = fileReferences;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// eslint-disable-next-line no-console
|
|
139
|
+
console.warn(`Failed to fetch files for session: ${session_id}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const fetchOptions = {
|
|
144
|
+
method: 'POST',
|
|
145
|
+
headers: {
|
|
146
|
+
'Content-Type': 'application/json',
|
|
147
|
+
'User-Agent': 'LibreChat/1.0',
|
|
148
|
+
},
|
|
149
|
+
body: JSON.stringify(postData),
|
|
150
|
+
};
|
|
151
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
152
|
+
fetchOptions.agent = new httpsProxyAgent.HttpsProxyAgent(process.env.PROXY);
|
|
153
|
+
}
|
|
154
|
+
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
155
|
+
if (!response.ok) {
|
|
156
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
157
|
+
}
|
|
158
|
+
const result = await response.json();
|
|
159
|
+
let formattedOutput = '';
|
|
160
|
+
if (result.stdout) {
|
|
161
|
+
formattedOutput += `stdout:\n${result.stdout}\n`;
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
formattedOutput += emptyOutputMessage;
|
|
165
|
+
}
|
|
166
|
+
if (result.stderr)
|
|
167
|
+
formattedOutput += `stderr:\n${result.stderr}\n`;
|
|
168
|
+
if (result.files && result.files.length > 0) {
|
|
169
|
+
formattedOutput += 'Generated files:\n';
|
|
170
|
+
const fileCount = result.files.length;
|
|
171
|
+
for (let i = 0; i < fileCount; i++) {
|
|
172
|
+
const file = result.files[i];
|
|
173
|
+
const isImage = CodeExecutor.imageExtRegex.test(file.name);
|
|
174
|
+
formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
|
|
175
|
+
if (i < fileCount - 1) {
|
|
176
|
+
formattedOutput += fileCount <= 3 ? ', ' : ',\n';
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
formattedOutput += `\n\n${accessMessage}`;
|
|
180
|
+
return [
|
|
181
|
+
formattedOutput.trim(),
|
|
182
|
+
{
|
|
183
|
+
session_id: result.session_id,
|
|
184
|
+
files: result.files,
|
|
185
|
+
},
|
|
186
|
+
];
|
|
187
|
+
}
|
|
188
|
+
return [formattedOutput.trim(), { session_id: result.session_id }];
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
throw new Error(`Execution error:\n\n${error?.message}`);
|
|
192
|
+
}
|
|
193
|
+
}, {
|
|
194
|
+
name: BashExecutionToolName,
|
|
195
|
+
description: BashExecutionToolDescription,
|
|
196
|
+
schema: BashExecutionToolSchema,
|
|
197
|
+
responseFormat: _enum.Constants.CONTENT_AND_ARTIFACT,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
exports.BashExecutionToolDefinition = BashExecutionToolDefinition;
|
|
202
|
+
exports.BashExecutionToolDescription = BashExecutionToolDescription;
|
|
203
|
+
exports.BashExecutionToolName = BashExecutionToolName;
|
|
204
|
+
exports.BashExecutionToolSchema = BashExecutionToolSchema;
|
|
205
|
+
exports.BashToolOutputReferencesGuide = BashToolOutputReferencesGuide;
|
|
206
|
+
exports.buildBashExecutionToolDescription = buildBashExecutionToolDescription;
|
|
207
|
+
exports.createBashExecutionTool = createBashExecutionTool;
|
|
208
|
+
//# sourceMappingURL=BashExecutor.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BashExecutor.cjs","sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example: \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n}): string {\n if (options?.enableToolOutputReferences === true) {\n return `${BashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return BashExecutionToolDescription;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...params,\n };\n\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"names":["config","getCodeBaseURL","Constants","tool","HttpsProxyAgent","imageExtRegex"],"mappings":";;;;;;;;;AAQAA,aAAM,EAAE;AAER,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D,MAAM,YAAY,GAAGC,2BAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAErC,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;AAOqC,uDAAA,CAAA;AACnD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,YAAA,WAAW,EACT,uIAAuI;AAC1I,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,SAAS,CAAC;;AAGhB,MAAM,4BAA4B,GAAG;;;;;;;CAO3C,CAAC,IAAI;AAEN;;;;;;;;;AASG;AACI,MAAM,6BAA6B,GAAG;;;;;;;CAO5C,CAAC,IAAI;AAEN;;;;;;AAMG;AACG,SAAU,iCAAiC,CAAC,OAEjD,EAAA;AACC,IAAA,IAAI,OAAO,EAAE,0BAA0B,KAAK,IAAI,EAAE;AAChD,QAAA,OAAO,CAAA,EAAG,4BAA4B,CAAA,IAAA,EAAO,6BAA6B,EAAE;IAC9E;AACA,IAAA,OAAO,4BAA4B;AACrC;AAEO,MAAM,qBAAqB,GAAG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