@librechat/agents 3.3.0 → 3.3.2
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 +116 -2
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +229 -48
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +102 -27
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +11 -2
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/contextOverflowRecovery.cjs +132 -0
- package/dist/cjs/llm/contextOverflowRecovery.cjs.map +1 -0
- package/dist/cjs/llm/google/index.cjs +1 -1
- package/dist/cjs/llm/invoke.cjs +60 -3
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/main.cjs +20 -7
- package/dist/cjs/messages/prune.cjs +16 -5
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/messages/recency.cjs +2 -0
- package/dist/cjs/messages/recency.cjs.map +1 -1
- package/dist/cjs/run.cjs +15 -2
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +205 -49
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +55 -7
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +2 -2
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -2
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +69 -8
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +19 -15
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +32 -3
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/utils/errors.cjs +317 -52
- package/dist/cjs/utils/errors.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +117 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +227 -46
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +102 -27
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +11 -2
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/contextOverflowRecovery.mjs +130 -0
- package/dist/esm/llm/contextOverflowRecovery.mjs.map +1 -0
- package/dist/esm/llm/google/index.mjs +1 -1
- package/dist/esm/llm/invoke.mjs +59 -4
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/main.mjs +9 -9
- package/dist/esm/messages/prune.mjs +14 -6
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/messages/recency.mjs +2 -1
- package/dist/esm/messages/recency.mjs.map +1 -1
- package/dist/esm/run.mjs +15 -2
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +205 -49
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +55 -7
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +3 -3
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +3 -3
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +62 -9
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +20 -16
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +32 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/utils/errors.mjs +317 -53
- package/dist/esm/utils/errors.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +62 -3
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +16 -2
- package/dist/types/graphs/MultiAgentGraph.d.ts +1 -0
- package/dist/types/llm/contextOverflowRecovery.d.ts +85 -0
- package/dist/types/llm/invoke.d.ts +35 -6
- package/dist/types/messages/prune.d.ts +10 -2
- package/dist/types/messages/recency.d.ts +1 -0
- package/dist/types/run.d.ts +2 -0
- package/dist/types/tools/CodeExecutor.d.ts +14 -1
- package/dist/types/types/llm.d.ts +7 -4
- package/dist/types/types/stream.d.ts +5 -4
- package/dist/types/types/summarize.d.ts +22 -0
- package/dist/types/utils/__tests__/fixtures/contextOverflowSignatures.d.ts +40 -0
- package/dist/types/utils/errors.d.ts +65 -16
- package/dist/types/utils/redactSecrets.d.ts +3 -0
- package/package.json +10 -11
- package/src/agents/AgentContext.ts +188 -7
- package/src/agents/__tests__/AgentContext.overflow.test.ts +205 -0
- package/src/common/enum.ts +2 -0
- package/src/graphs/Graph.ts +389 -58
- package/src/graphs/MultiAgentGraph.ts +184 -46
- package/src/graphs/__tests__/Graph.contextOverflow.test.ts +631 -0
- package/src/llm/__tests__/contextOverflowRecovery.test.ts +401 -0
- package/src/llm/__tests__/fallbackOverflow.test.ts +287 -0
- package/src/llm/anthropic/llm.spec.ts +8 -0
- package/src/llm/bedrock/index.ts +25 -12
- package/src/llm/contextOverflowRecovery.ts +292 -0
- package/src/llm/invoke.ts +119 -4
- package/src/messages/prune.ts +24 -11
- package/src/messages/recency.ts +3 -1
- package/src/run.ts +24 -1
- package/src/scripts/context-overflow-probe.ts +997 -0
- package/src/specs/agent-handoffs.test.ts +903 -1
- package/src/specs/context-overflow-recovery.live.test.ts +213 -0
- package/src/splitStream.test.ts +882 -0
- package/src/stream.ts +315 -51
- package/src/summarization/__tests__/aggregator.test.ts +83 -0
- package/src/summarization/__tests__/node.test.ts +139 -0
- package/src/summarization/node.ts +99 -14
- package/src/tools/BashExecutor.ts +4 -2
- package/src/tools/BashProgrammaticToolCalling.ts +4 -7
- package/src/tools/CodeExecutor.ts +119 -8
- package/src/tools/ProgrammaticToolCalling.ts +29 -27
- package/src/tools/ToolNode.ts +50 -8
- package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +297 -3
- package/src/types/llm.ts +8 -1
- package/src/types/stream.ts +5 -4
- package/src/types/summarize.ts +22 -0
- package/src/utils/__tests__/errors.test.ts +270 -0
- package/src/utils/__tests__/fixtures/contextOverflowSignatures.ts +336 -0
- package/src/utils/__tests__/redactSecrets.test.ts +56 -0
- package/src/utils/errors.ts +484 -66
- package/src/utils/redactSecrets.ts +61 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.mjs","names":["chunkAny"],"sources":["../../../src/summarization/node.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { UsageMetadata, BaseMessage } from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { HookRegistry } from '@/hooks';\nimport type { OnChunk } from '@/llm/invoke';\nimport type * as t from '@/types';\nimport {\n addTailCacheControl,\n resolvePromptCacheTtl,\n type PromptCacheTtl,\n} from '@/messages/cache';\nimport {\n Constants,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';\nimport { attemptInvoke, tryFallbackProviders } from '@/llm/invoke';\nimport { createRemoveAllMessage } from '@/messages/reducer';\nimport { splitAtRecencyBoundary } from '@/messages/recency';\nimport { getMaxOutputTokensKey } from '@/llm/request';\nimport { initializeModel } from '@/llm/init';\nimport { getChunkContent } from '@/stream';\nimport { executeHooks } from '@/hooks';\n\nconst SUMMARIZATION_PARAM_KEYS = new Set(['maxSummaryTokens']);\n\n/**\n * Default number of recent user-led turns preserved verbatim during\n * compaction. A turn begins at a HumanMessage and includes every\n * following AIMessage and ToolMessage up to the next HumanMessage.\n * The most recent turn is always retained regardless of this value;\n * the default of `2` additionally keeps the prior exchange so the\n * model has fresh context on what just happened. Setting\n * `retainRecent.turns` to `0` reverts to the legacy \"summarize every\n * message\" behavior.\n */\nconst DEFAULT_RETAIN_RECENT_TURNS = 2;\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 promptCacheTtl:\n (clientConfig.provider as Providers) === Providers.ANTHROPIC ||\n (clientConfig.provider as Providers) === Providers.OPENROUTER\n ? resolvePromptCacheTtl(\n (\n clientConfig.clientOptions as {\n promptCacheTtl?: PromptCacheTtl;\n }\n ).promptCacheTtl\n )\n : undefined,\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 /**\n * Number of messages preserved verbatim by the recency window after\n * compaction. Reported via the PostCompact hook payload so observers\n * (metrics, cleanup) see the true post-compaction message count\n * instead of always-zero.\n */\n messagesAfterCount: number;\n}): Promise<void> {\n const {\n graph,\n runnableConfig,\n stepId,\n summaryBlock,\n agentContext,\n runStep,\n summaryUsage,\n agentId,\n messagesAfterCount,\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,\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 /**\n * Capture the original-tool-content map locally before doing the\n * split. We need it in three places: to restore the head for\n * summarizer quality, to leave intact on the skip path (state is\n * unchanged), and — critically — to carry forward the tail-relevant\n * entries on the summarize-fired path. Clearing it eagerly here\n * would lose the originals for masked tool messages that the\n * recency window keeps in the tail; a future summarization could\n * then only summarize the masked stub instead of the full payload.\n */\n const originalPending = agentContext.pendingOriginalToolContent;\n\n const restoredMessages = restoreOriginalToolContent(\n state.messages,\n originalPending\n );\n\n const runnableConfig = config ?? graph.config;\n\n const retainRecent = agentContext.summarizationConfig?.retainRecent;\n const { head: messagesToRefine, tailStartIndex } = splitAtRecencyBoundary(\n restoredMessages,\n {\n turns: retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS,\n tokens: retainRecent?.tokens,\n tokenCounter: agentContext.tokenCounter,\n }\n );\n /**\n * Use the *masked* messages for the retained tail so that any\n * truncation prune applied to oversized ToolMessage content stays\n * truncated in live state. The summarizer above reads the restored\n * (full-content) head for summary quality, but reinjecting restored\n * tool payloads into state would defeat masking and bloat the\n * checkpoint, forcing more expensive re-pruning on later turns.\n * `restoreOriginalToolContent` returns an array with identical\n * length and structure to `state.messages` (replacements only at\n * specific indices), so the same tailStartIndex slices both arrays\n * at the same turn boundary.\n */\n const messagesToRetain = state.messages.slice(tailStartIndex);\n\n if (messagesToRefine.length === 0) {\n /**\n * Recency window covers the entire conversation — there is no\n * older content to summarize. Skipping prevents the model from\n * destroying the user's most recent message (e.g. a large pasted\n * payload on the first turn) by replacing it with a generic\n * checkpoint summary. Mark the trigger so the same unchanged\n * state is not re-evaluated on the next prune cycle.\n */\n emitAgentLog(\n config,\n 'debug',\n 'summarize',\n 'Summarization skipped — recency window retains all messages',\n {\n messagesRetained: messagesToRetain.length,\n retainTurns: retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS,\n },\n { runId: graph.runId, agentId: request.agentId }\n );\n agentContext.markSummarizationTriggered(state.messages.length);\n return { summarizationRequest: undefined };\n }\n\n const clientConfig = buildSummarizationClientConfig(\n agentContext,\n agentContext.summarizationConfig\n );\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 * Per-call model attribution for usage consumers (the subagent\n * usage-capture handler): the summarizer's model can differ from\n * the agent's primary, and providers that emit no `ls_model_name`\n * would otherwise be billed against the primary config's model.\n * Omitted for self-summarize (no explicit model — the primary\n * config fallback is then correct). `tryFallbackProviders`\n * overrides this per fallback attempt; `INVOKED_PROVIDER` is\n * stamped by `attemptInvoke` itself.\n */\n ...(clientConfig.modelName != null && clientConfig.modelName !== ''\n ? { [Constants.INVOKED_MODEL]: clientConfig.modelName }\n : {}),\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 messagesAfterCount: messagesToRetain.length,\n });\n\n /**\n * `dispatchCompletionEvents` calls `rebuildTokenMapAfterSummarization({})`\n * which resets the dedupe baseline to 0 — correct under the legacy\n * \"remove-all only\" shape where no messages survived, but stale once\n * the recency window keeps a tail. Realign the baseline to the\n * surviving tail length so a subsequent prune cycle on the unchanged\n * tail short-circuits via `shouldSkipSummarization` instead of\n * looping back into another summarize call.\n */\n agentContext.markSummarizationTriggered(messagesToRetain.length);\n\n /**\n * Carry forward the original-content entries that correspond to the\n * retained tail, reindexed for the post-removeAll state where tail\n * messages start at index 0. Without this, a future summarization\n * that pulls these tail messages into its head would only see the\n * masked stubs (since `setSummary` clears `pruneMessages`, and the\n * fresh pruner at the next turn has no record of prior masks).\n * Entries for indices < `tailStartIndex` belong to messages we just\n * summarized — they are no longer reachable so they are dropped.\n */\n if (originalPending != null && originalPending.size > 0) {\n const tailPending = new Map<number, string>();\n for (const [idx, content] of originalPending) {\n if (idx >= tailStartIndex) {\n tailPending.set(idx - tailStartIndex, content);\n }\n }\n agentContext.pendingOriginalToolContent =\n tailPending.size > 0 ? tailPending : undefined;\n } else {\n agentContext.pendingOriginalToolContent = undefined;\n }\n\n return {\n summarizationRequest: undefined,\n messages:\n messagesToRetain.length > 0\n ? [createRemoveAllMessage(), ...messagesToRetain]\n : [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 void 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 promptCacheTtl,\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 promptCacheTtl?: PromptCacheTtl;\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\n ? addTailCacheControl(fullMessages, promptCacheTtl)\n : 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"],"mappings":";;;;;;;;;;;;;;AAiCA,MAAM,2BAA2B,IAAI,IAAI,CAAC,kBAAkB,CAAC;;;;;;;;;;;AAY7D,MAAM,8BAA8B;;;;;;;AAQpC,MAAM,kCAAkC;;AAGxC,MAAa,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC5C,MAAa,sCAAsC;;;;;;;;;;;;;;AAenD,SAAS,mBAAmB,YAG1B;CACA,MAAM,YAAqC,CAAC;CAC5C,IAAI;CAEJ,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,yBAAyB,IAAI,GAAG;MAEhC,QAAQ,sBACR,OAAO,UAAU,YACjB,QAAQ,GAER,mBAAmB;CAAA,OAGrB,UAAU,OAAO;CAIrB,OAAO;EAAE;EAAW;CAAiB;AACvC;;;;;;AAOA,SAAS,qBAAqB,UAAiC;CAC7D,MAAM,SAAiC,CAAC;CACxC,MAAM,4BAAY,IAAI,IAAY;CAElC,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,OAAO,IAAI,QAAQ;EACzB,OAAO,SAAS,OAAO,SAAS,KAAK;EAErC,IAAI,SAAS,UAAU,IAAI,QAAQ,QAAQ,IAAI,SAAS,IACtD,UAAU,IAAI,IAAI,IAAI;EAG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AG;EACH,SAAS,iBAAiB;EAC1B,UAAU;GAAE,GAAG,OAAO;GAAU,eAAe;GAAM;EAAM;CAC7D;AACF;;;;;;;AAQA,eAAe,sBAAsB,EACnC,OACA,UACA,YACA,kBACA,kBACA,QACA,QACA,UACA,cACA,gBACA,gBACA,OAc4D;CAC5D,MAAM,cAAc,8BAClB,YACA,kBACA,gBACF;CAEA,MAAM,eAAe,CAAC,GAAG,UAAU,IAAI,aAAa,WAAW,CAAC;CAqBhE,MAAM,eAAc,MAfC,cACnB;EACE;EACA,UAPF,mBAAmB,OACf,oBAAoB,cAAc,cAAc,IAChD;EAMF;EACA,SAAS,gCAAgC;GACvC;GACA,QAAQ,YAAY,QAAQ,sBAAsB;GAClD;GACA;EACF,CAAC;CACH,GACA,YAAY,QAAQ,sBAAsB,CAC5C,EAAA,CAE2B,WAAW;CACtC,MAAM,OAAO,cACT,oBAAoB,WAA2C,IAC/D;CACJ,IAAI;CACJ,IAAI,cAAc;CAClB,IACE,eAAe,QACf,oBAAoB,eACpB,YAAY,kBAAkB,MAC9B;EACA,QAAQ,YAAY;EACpB,cAAc;CAChB,OAAO,IAAI,eAAe,MAAM;EAI9B,MAAM,OAHW,YAAY,mBAGN,SAAA,EACnB;EACJ,IAAI,OAAO,MAAM;GACf,QAAQ;IACN,cAAc,OAAO,IAAI,WAAW,KAAK,KAAA;IACzC,eAAe,OAAO,IAAI,YAAY,KAAK,KAAA;GAC7C;GACA,cAAc;EAChB;CACF;CACA,MAAM,eACJ,OAQC;CACH,MAAM,SAAS,2BAA2B;EACxC,QAAQ;EACR,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,GAAI,cAAc,cAAc,QAAQ,cAAc,kBAAkB,OACpE;GACA,kCAAkC,aAAa;GAC/C,sCAAsC,aAAa;EACrD,IACE,CAAC;CACP,CAAC;CACD,OAAO;EAAE;EAAM;CAAM;AACvB"}
|
|
1
|
+
{"version":3,"file":"node.mjs","names":["chunkAny"],"sources":["../../../src/summarization/node.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { UsageMetadata, BaseMessage } from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { HookRegistry } from '@/hooks';\nimport type { OnChunk } from '@/llm/invoke';\nimport type * as t from '@/types';\nimport {\n addTailCacheControl,\n resolvePromptCacheTtl,\n type PromptCacheTtl,\n} from '@/messages/cache';\nimport {\n DEFAULT_RETAIN_RECENT_TURNS,\n splitAtRecencyBoundary,\n} from '@/messages/recency';\nimport {\n Constants,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} 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 { initializeModel } from '@/llm/init';\nimport { getChunkContent } from '@/stream';\nimport { executeHooks } from '@/hooks';\n\nconst SUMMARIZATION_PARAM_KEYS = new Set(['maxSummaryTokens']);\n\n/**\n * Default number of recent user-led turns preserved verbatim during\n * compaction. A turn begins at a HumanMessage and includes every\n * following AIMessage and ToolMessage up to the next HumanMessage.\n * The most recent turn is always retained regardless of this value;\n * the default of `2` additionally keeps the prior exchange so the\n * model has fresh context on what just happened. Setting\n * `retainRecent.turns` to `0` reverts to the legacy \"summarize every\n * message\" behavior.\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<{\n text: string;\n usage?: Partial<UsageMetadata>;\n /**\n * True when every model call failed and `text` is the generated metadata\n * stub rather than a real summary. Callers that would replace history with\n * this need to know it carries none of the original content.\n */\n usedMetadataStub?: boolean;\n}> {\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 let usedMetadataStub = false;\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 promptCacheTtl:\n (clientConfig.provider as Providers) === Providers.ANTHROPIC ||\n (clientConfig.provider as Providers) === Providers.OPENROUTER\n ? resolvePromptCacheTtl(\n (\n clientConfig.clientOptions as {\n promptCacheTtl?: PromptCacheTtl;\n }\n ).promptCacheTtl\n )\n : undefined,\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 usedMetadataStub = true;\n }\n }\n\n return { text: summaryText, usage: summaryUsage, usedMetadataStub };\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 /**\n * Number of messages preserved verbatim by the recency window after\n * compaction. Reported via the PostCompact hook payload so observers\n * (metrics, cleanup) see the true post-compaction message count\n * instead of always-zero.\n */\n messagesAfterCount: number;\n}): Promise<void> {\n const {\n graph,\n runnableConfig,\n stepId,\n summaryBlock,\n agentContext,\n runStep,\n summaryUsage,\n agentId,\n messagesAfterCount,\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,\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 /**\n * Overflow recovery routes through this node purely to get back to the\n * agent node with a corrected budget, and deliberately spends no model\n * call on its first attempt: re-pruning under the raised context pressure\n * drives the pruner's tool-output compression and masking, which is\n * cheaper than a summary and cannot lose message content. Summarization\n * is also skipped outright when the caller never enabled it.\n */\n if (\n request.reason === 'overflow' &&\n (request.allowSummarization !== true ||\n agentContext.summarizationEnabled !== true)\n ) {\n emitAgentLog(\n config,\n 'debug',\n 'summarize',\n 'Overflow recovery re-prune — compressing tool output without a summarization call',\n {\n maxContextTokens: agentContext.maxContextTokens,\n summarizationEnabled: agentContext.summarizationEnabled === true,\n allowSummarization: request.allowSummarization === true,\n },\n { runId: graph.runId, agentId: request.agentId }\n );\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 /**\n * Capture the original-tool-content map locally before doing the\n * split. We need it in three places: to restore the head for\n * summarizer quality, to leave intact on the skip path (state is\n * unchanged), and — critically — to carry forward the tail-relevant\n * entries on the summarize-fired path. Clearing it eagerly here\n * would lose the originals for masked tool messages that the\n * recency window keeps in the tail; a future summarization could\n * then only summarize the masked stub instead of the full payload.\n */\n const originalPending = agentContext.pendingOriginalToolContent;\n\n const restoredMessages = restoreOriginalToolContent(\n state.messages,\n originalPending\n );\n\n const runnableConfig = config ?? graph.config;\n\n const retainRecent = agentContext.summarizationConfig?.retainRecent;\n const { head: messagesToRefine, tailStartIndex } = splitAtRecencyBoundary(\n restoredMessages,\n {\n turns: retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS,\n tokens: retainRecent?.tokens,\n tokenCounter: agentContext.tokenCounter,\n }\n );\n /**\n * Use the *masked* messages for the retained tail so that any\n * truncation prune applied to oversized ToolMessage content stays\n * truncated in live state. The summarizer above reads the restored\n * (full-content) head for summary quality, but reinjecting restored\n * tool payloads into state would defeat masking and bloat the\n * checkpoint, forcing more expensive re-pruning on later turns.\n * `restoreOriginalToolContent` returns an array with identical\n * length and structure to `state.messages` (replacements only at\n * specific indices), so the same tailStartIndex slices both arrays\n * at the same turn boundary.\n */\n const messagesToRetain = state.messages.slice(tailStartIndex);\n\n if (messagesToRefine.length === 0) {\n /**\n * Recency window covers the entire conversation — there is no\n * older content to summarize. Skipping prevents the model from\n * destroying the user's most recent message (e.g. a large pasted\n * payload on the first turn) by replacing it with a generic\n * checkpoint summary. Mark the trigger so the same unchanged\n * state is not re-evaluated on the next prune cycle.\n */\n emitAgentLog(\n config,\n 'debug',\n 'summarize',\n 'Summarization skipped — recency window retains all messages',\n {\n messagesRetained: messagesToRetain.length,\n retainTurns: retainRecent?.turns ?? DEFAULT_RETAIN_RECENT_TURNS,\n },\n { runId: graph.runId, agentId: request.agentId }\n );\n agentContext.markSummarizationTriggered(state.messages.length);\n return { summarizationRequest: undefined };\n }\n\n const clientConfig = buildSummarizationClientConfig(\n agentContext,\n agentContext.summarizationConfig\n );\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 * Per-call model attribution for usage consumers (the subagent\n * usage-capture handler): the summarizer's model can differ from\n * the agent's primary, and providers that emit no `ls_model_name`\n * would otherwise be billed against the primary config's model.\n * Omitted for self-summarize (no explicit model — the primary\n * config fallback is then correct). `tryFallbackProviders`\n * overrides this per fallback attempt; `INVOKED_PROVIDER` is\n * stamped by `attemptInvoke` itself.\n */\n ...(clientConfig.modelName != null && clientConfig.modelName !== ''\n ? { [Constants.INVOKED_MODEL]: clientConfig.modelName }\n : {}),\n },\n }\n : undefined;\n\n const {\n text: rawText,\n usage: summaryUsage,\n usedMetadataStub,\n } = await executeSummarizationWithFallback({\n agentContext,\n messages: messagesToRefine,\n clientConfig,\n summarizeConfig,\n stepId,\n usePromptCache: isSelfSummarizeModel && hasPromptCache,\n log,\n });\n\n /**\n * The metadata stub describes the history rather than summarizing it, so\n * committing it means removing the head and keeping nothing of what it\n * said. That trade is never worth making to paper over an overflow: the\n * recovery would \"succeed\" only by destroying the conversation it was\n * supposed to preserve. Leave state untouched and let the provider error\n * surface instead.\n */\n if (usedMetadataStub === true && request.reason === 'overflow') {\n log(\n 'warn',\n 'Overflow summarization failed; keeping history rather than replacing it with a metadata stub'\n );\n agentContext.markSummarizationTriggered(state.messages.length);\n /**\n * The run step was already dispatched, so it has to be resolved here or\n * consumers tracking step lifecycle keep an unfinished placeholder for\n * the rest of the run.\n */\n await graph.dispatchRunStepCompleted(\n stepId,\n {\n type: 'summary',\n summary: placeholderSummary,\n } satisfies t.SummaryCompleted,\n runnableConfig\n );\n if (runnableConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_SUMMARIZE_COMPLETE,\n {\n id: stepId,\n agentId: request.agentId,\n error:\n 'Summarization failed during overflow recovery; conversation history was preserved',\n } satisfies t.SummarizeCompleteEvent,\n runnableConfig\n );\n }\n return { summarizationRequest: undefined };\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 messagesAfterCount: messagesToRetain.length,\n });\n\n /**\n * `dispatchCompletionEvents` calls `rebuildTokenMapAfterSummarization({})`\n * which resets the dedupe baseline to 0 — correct under the legacy\n * \"remove-all only\" shape where no messages survived, but stale once\n * the recency window keeps a tail. Realign the baseline to the\n * surviving tail length so a subsequent prune cycle on the unchanged\n * tail short-circuits via `shouldSkipSummarization` instead of\n * looping back into another summarize call.\n */\n agentContext.markSummarizationTriggered(messagesToRetain.length);\n\n /**\n * Carry forward the original-content entries that correspond to the\n * retained tail, reindexed for the post-removeAll state where tail\n * messages start at index 0. Without this, a future summarization\n * that pulls these tail messages into its head would only see the\n * masked stubs (since `setSummary` clears `pruneMessages`, and the\n * fresh pruner at the next turn has no record of prior masks).\n * Entries for indices < `tailStartIndex` belong to messages we just\n * summarized — they are no longer reachable so they are dropped.\n */\n if (originalPending != null && originalPending.size > 0) {\n const tailPending = new Map<number, string>();\n for (const [idx, content] of originalPending) {\n if (idx >= tailStartIndex) {\n tailPending.set(idx - tailStartIndex, content);\n }\n }\n agentContext.pendingOriginalToolContent =\n tailPending.size > 0 ? tailPending : undefined;\n } else {\n agentContext.pendingOriginalToolContent = undefined;\n }\n\n return {\n summarizationRequest: undefined,\n messages:\n messagesToRetain.length > 0\n ? [createRemoveAllMessage(), ...messagesToRetain]\n : [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 void 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 promptCacheTtl,\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 promptCacheTtl?: PromptCacheTtl;\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\n ? addTailCacheControl(fullMessages, promptCacheTtl)\n : 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"],"mappings":";;;;;;;;;;;;;;AAoCA,MAAM,2BAA2B,IAAI,IAAI,CAAC,kBAAkB,CAAC;;;;;;;;;;;;;;;;;AAkB7D,MAAM,kCAAkC;;AAGxC,MAAa,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC5C,MAAa,sCAAsC;;;;;;;;;;;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import "../common/index.mjs";
|
|
3
3
|
import { appendCodeSessionFileSummary } from "./CodeSessionFileSummary.mjs";
|
|
4
|
-
import { BASH_SHELL_GUIDANCE, CODE_ARTIFACT_PATH_GUIDANCE, appendFailedExecutionFileReminder, appendTmpScratchReminder, buildCodeApiHttpErrorMessage, emptyOutputMessage, getCodeBaseURL, resolveCodeApiAuthHeaders } from "./CodeExecutor.mjs";
|
|
4
|
+
import { BASH_SHELL_GUIDANCE, CODE_ARTIFACT_PATH_GUIDANCE, CodeApiRequestError, appendFailedExecutionFileReminder, appendTmpScratchReminder, buildCodeApiHttpErrorMessage, emptyOutputMessage, getCodeBaseURL, normalizeCodeApiRequestError, resolveCodeApiAuthHeaders } from "./CodeExecutor.mjs";
|
|
5
5
|
import { tool } from "@langchain/core/tools";
|
|
6
6
|
import { config } from "dotenv";
|
|
7
7
|
import fetch from "node-fetch";
|
|
@@ -153,7 +153,7 @@ function createBashExecutionTool(params = {}) {
|
|
|
153
153
|
};
|
|
154
154
|
if (process.env.PROXY != null && process.env.PROXY !== "") fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
|
|
155
155
|
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
156
|
-
if (!response.ok) throw new
|
|
156
|
+
if (!response.ok) throw new CodeApiRequestError(await buildCodeApiHttpErrorMessage("POST", EXEC_ENDPOINT, response));
|
|
157
157
|
const result = await response.json();
|
|
158
158
|
let formattedOutput = "";
|
|
159
159
|
if (result.stdout) formattedOutput += `stdout:\n${result.stdout}\n`;
|
|
@@ -174,7 +174,7 @@ function createBashExecutionTool(params = {}) {
|
|
|
174
174
|
...runtimeEcho
|
|
175
175
|
}];
|
|
176
176
|
} catch (error) {
|
|
177
|
-
const messageWithReminder = appendFailedExecutionFileReminder(error
|
|
177
|
+
const messageWithReminder = appendFailedExecutionFileReminder(normalizeCodeApiRequestError(error).message, command);
|
|
178
178
|
throw new Error(`Execution error:\n\n${messageWithReminder}`);
|
|
179
179
|
}
|
|
180
180
|
}, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BashExecutor.mjs","names":[],"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 {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n appendTmpScratchReminder,\n appendCodeSessionFileSummary,\n emptyOutputMessage,\n buildCodeApiHttpErrorMessage,\n getCodeBaseURL,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\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- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\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- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Bash statefulness is filesystem-tier and scoped to `/mnt/data`. The machine\n * is warm across calls, but each call runs in a fresh sandbox (new process\n * tree + private /tmp), so background processes are reaped when the call ends\n * and anything written outside /mnt/data is discarded. The note must not\n * promise otherwise: a model told background processes survive will start a\n * server in one call and assume it is listening in the next.\n */\nexport const STATEFUL_BASH_NOTE =\n 'Session state: commands in this conversation run on the same warm machine, so files written to /mnt/data persist between calls. Each call runs in a fresh, isolated sandbox: shell variables, the working directory, /tmp, and background processes do NOT survive after the call returns — a process started in one call is terminated when that call ends. Only /mnt/data is durable (the machine itself may also be reset at any time).';\n\nexport const StatefulBashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output. Commands in this conversation share one warm machine with a persistent /mnt/data, but each command runs in its own isolated sandbox (not a persistent shell session).\n\n${STATEFUL_BASH_NOTE}\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\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 (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\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 statefulSessions?: boolean;\n}): string {\n const base =\n options?.statefulSessions === true\n ? StatefulBashExecutionToolDescription\n : BashExecutionToolDescription;\n if (options?.enableToolOutputReferences === true) {\n return `${base}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return base;\n}\n\nconst STATELESS_BASH_PARAM_NOTE =\n 'The environment is stateless; variables and state don\\'t persist between executions.';\nconst STATEFUL_BASH_PARAM_NOTE =\n 'Files written to /mnt/data persist between calls on the same warm machine. Each call runs in a fresh sandbox: shell variables, cwd, /tmp, and background processes do NOT survive the call. Only /mnt/data is durable.';\n\nexport function buildBashExecutionToolSchema(opts?: {\n statefulSessions?: boolean;\n}): typeof BashExecutionToolSchema {\n const note =\n opts?.statefulSessions === true\n ? STATEFUL_BASH_PARAM_NOTE\n : STATELESS_BASH_PARAM_NOTE;\n const commandDescription =\n BashExecutionToolSchema.properties.command.description.replace(\n STATELESS_BASH_PARAM_NOTE,\n note\n );\n return {\n ...BashExecutionToolSchema,\n properties: {\n ...BashExecutionToolSchema.properties,\n command: {\n ...BashExecutionToolSchema.properties.command,\n description: commandDescription,\n },\n },\n } as typeof BashExecutionToolSchema;\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 | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n /* `statefulSessions` is prompt-only — keep it out of the wire body. */\n const {\n authHeaders,\n statefulSessions: _statefulSessions,\n ...executionParams\n } = params ?? {};\n void _statefulSessions;\n /* Drop any model-supplied `runtime_session_hint` from the raw args: the\n * hint must only come from ToolNode's injected `_runtime_session_hint`\n * (below), never from the tool call itself. */\n const {\n command,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n command: string;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\n const { session_id, _injected_files, _runtime_session_hint } =\n (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...executionParams,\n };\n\n if (\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ) {\n postData.runtime_session_hint = _runtime_session_hint;\n }\n\n /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`\n * HTTP fallback was removed because codeapi's sessionAuth requires\n * kind/id query params unavailable at this point. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\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(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\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\n const outputWithReminder = appendTmpScratchReminder(\n formattedOutput,\n command\n );\n const hasFiles = result.files != null && result.files.length > 0;\n const runtimeEcho =\n result.runtime_session_id != null\n ? {\n runtime_session_id: result.runtime_session_id,\n runtime_status: result.runtime_status,\n }\n : {};\n return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? {\n session_id: result.session_id,\n files: result.files,\n ...runtimeEcho,\n }\n : {\n session_id: result.session_id,\n ...runtimeEcho,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error | undefined)?.message ?? '',\n command\n );\n throw new Error(`Execution error:\\n\\n${messageWithReminder}`);\n }\n },\n {\n name: BashExecutionToolName,\n description: buildBashExecutionToolDescription({\n statefulSessions: params?.statefulSessions,\n }),\n schema: buildBashExecutionToolSchema(params ?? undefined),\n responseFormat: Constants.CONTENT_AND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O,KAAK,GAC5D,WACG;IACA,YAAY,OAAO;IACnB,OAAO,OAAO;IACd,GAAG;GACL,IACE;IACA,YAAY,OAAO;IACnB,GAAG;GACL,CACJ;EACF,SAAS,OAAO;GACd,MAAM,sBAAsB,kCACzB,OAA6B,WAAW,IACzC,OACF;GACA,MAAM,IAAI,MAAM,uBAAuB,qBAAqB;EAC9D;CACF,GACA;EACE,MAAM;EACN,aAAa,kCAAkC,EAC7C,kBAAkB,QAAQ,iBAC5B,CAAC;EACD,QAAQ,6BAA6B,UAAU,KAAA,CAAS;EACxD,gBAAA;CACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"BashExecutor.mjs","names":[],"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 {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n appendTmpScratchReminder,\n appendCodeSessionFileSummary,\n emptyOutputMessage,\n buildCodeApiHttpErrorMessage,\n CodeApiRequestError,\n getCodeBaseURL,\n normalizeCodeApiRequestError,\n resolveCodeApiAuthHeaders,\n} from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\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- Prior /mnt/data files are available and can be modified in place.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\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- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Bash statefulness is filesystem-tier and scoped to `/mnt/data`. The machine\n * is warm across calls, but each call runs in a fresh sandbox (new process\n * tree + private /tmp), so background processes are reaped when the call ends\n * and anything written outside /mnt/data is discarded. The note must not\n * promise otherwise: a model told background processes survive will start a\n * server in one call and assume it is listening in the next.\n */\nexport const STATEFUL_BASH_NOTE =\n 'Session state: commands in this conversation run on the same warm machine, so files written to /mnt/data persist between calls. Each call runs in a fresh, isolated sandbox: shell variables, the working directory, /tmp, and background processes do NOT survive after the call returns — a process started in one call is terminated when that call ends. Only /mnt/data is durable (the machine itself may also be reset at any time).';\n\nexport const StatefulBashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output. Commands in this conversation share one warm machine with a persistent /mnt/data, but each command runs in its own isolated sandbox (not a persistent shell session).\n\n${STATEFUL_BASH_NOTE}\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\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 (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\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 statefulSessions?: boolean;\n}): string {\n const base =\n options?.statefulSessions === true\n ? StatefulBashExecutionToolDescription\n : BashExecutionToolDescription;\n if (options?.enableToolOutputReferences === true) {\n return `${base}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return base;\n}\n\nconst STATELESS_BASH_PARAM_NOTE =\n 'The environment is stateless; variables and state don\\'t persist between executions.';\nconst STATEFUL_BASH_PARAM_NOTE =\n 'Files written to /mnt/data persist between calls on the same warm machine. Each call runs in a fresh sandbox: shell variables, cwd, /tmp, and background processes do NOT survive the call. Only /mnt/data is durable.';\n\nexport function buildBashExecutionToolSchema(opts?: {\n statefulSessions?: boolean;\n}): typeof BashExecutionToolSchema {\n const note =\n opts?.statefulSessions === true\n ? STATEFUL_BASH_PARAM_NOTE\n : STATELESS_BASH_PARAM_NOTE;\n const commandDescription =\n BashExecutionToolSchema.properties.command.description.replace(\n STATELESS_BASH_PARAM_NOTE,\n note\n );\n return {\n ...BashExecutionToolSchema,\n properties: {\n ...BashExecutionToolSchema.properties,\n command: {\n ...BashExecutionToolSchema.properties.command,\n description: commandDescription,\n },\n },\n } as typeof BashExecutionToolSchema;\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 | null = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n /* `statefulSessions` is prompt-only — keep it out of the wire body. */\n const {\n authHeaders,\n statefulSessions: _statefulSessions,\n ...executionParams\n } = params ?? {};\n void _statefulSessions;\n /* Drop any model-supplied `runtime_session_hint` from the raw args: the\n * hint must only come from ToolNode's injected `_runtime_session_hint`\n * (below), never from the tool call itself. */\n const {\n command,\n runtime_session_hint: _ignoredModelHint,\n ...rest\n } = rawInput as {\n command: string;\n runtime_session_hint?: unknown;\n args?: string[];\n };\n void _ignoredModelHint;\n const { session_id, _injected_files, _runtime_session_hint } =\n (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...executionParams,\n };\n\n if (\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ) {\n postData.runtime_session_hint = _runtime_session_hint;\n }\n\n /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`\n * HTTP fallback was removed because codeapi's sessionAuth requires\n * kind/id query params unavailable at this point. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const resolvedAuthHeaders =\n await resolveCodeApiAuthHeaders(authHeaders);\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n ...resolvedAuthHeaders,\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 CodeApiRequestError(\n await buildCodeApiHttpErrorMessage('POST', EXEC_ENDPOINT, response)\n );\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\n const outputWithReminder = appendTmpScratchReminder(\n formattedOutput,\n command\n );\n const hasFiles = result.files != null && result.files.length > 0;\n const runtimeEcho =\n result.runtime_session_id != null\n ? {\n runtime_session_id: result.runtime_session_id,\n runtime_status: result.runtime_status,\n }\n : {};\n return [\n appendCodeSessionFileSummary(outputWithReminder, result.files),\n (hasFiles\n ? {\n session_id: result.session_id,\n files: result.files,\n ...runtimeEcho,\n }\n : {\n session_id: result.session_id,\n ...runtimeEcho,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n normalizeCodeApiRequestError(error).message,\n command\n );\n throw new Error(`Execution error:\\n\\n${messageWithReminder}`);\n }\n },\n {\n name: BashExecutionToolName,\n description: buildBashExecutionToolDescription({\n statefulSessions: params?.statefulSessions,\n }),\n schema: buildBashExecutionToolSchema(params ?? undefined),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"mappings":";;;;;;;;;AAoBA,OAAO;AAGP,MAAM,gBAAgB,GADD,eACe,EAAE;AAEtC,MAAa,0BAA0B;CACrC,MAAM;CACN,YAAY;EACV,SAAS;GACP,MAAM;GACN,aAAa;;;IAGf,4BAA4B;IAC5B,oBAAoB;;;;;EAKpB;EACA,MAAM;GACJ,MAAM;GACN,OAAO,EAAE,MAAM,SAAS;GACxB,aACE;EACJ;CACF;CACA,UAAU,CAAC,SAAS;AACtB;AAEA,MAAa,+BAA+B;;;;;;IAMxC,4BAA4B;IAC5B,oBAAoB;;EAEtB,KAAK;;;;;;;;;AAUP,MAAa,qBACX;AAEF,MAAa,uCAAuC;;;EAGlD,mBAAmB;;;;;IAKjB,4BAA4B;IAC5B,oBAAoB;;EAEtB,KAAK;;;;;;;;;;;AAYP,MAAa,gCAAgC;;;;;;;;;EAS3C,KAAK;;;;;;;;AASP,SAAgB,kCAAkC,SAGvC;CACT,MAAM,OACJ,SAAS,qBAAqB,OAC1B,uCACA;CACN,IAAI,SAAS,+BAA+B,MAC1C,OAAO,GAAG,KAAK,MAAM;CAEvB,OAAO;AACT;AAEA,MAAM,4BACJ;AACF,MAAM,2BACJ;AAEF,SAAgB,6BAA6B,MAEV;CACjC,MAAM,OACJ,MAAM,qBAAqB,OACvB,2BAC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SAA0B,MAAM,SAAS,KAAK;GACpD,IAAI,kBAAkB;GACtB,IAAI,OAAO,QACT,mBAAmB,YAAY,OAAO,OAAO;QAE7C,mBAAmB;GAErB,IAAI,OAAO,QAAQ,mBAAmB,YAAY,OAAO,OAAO;GAEhE,MAAM,qBAAqB,yBACzB,iBACA,OACF;GACA,MAAM,WAAW,OAAO,SAAS,QAAQ,OAAO,MAAM,SAAS;GAC/D,MAAM,cACJ,OAAO,sBAAsB,OACzB;IACA,oBAAoB,OAAO;IAC3B,gBAAgB,OAAO;GACzB,IACE,CAAC;GACP,OAAO,CACL,6BAA6B,oBAAoB,OAAO,KAAK,GAC5D,WACG;IACA,YAAY,OAAO;IACnB,OAAO,OAAO;IACd,GAAG;GACL,IACE;IACA,YAAY,OAAO;IACnB,GAAG;GACL,CACJ;EACF,SAAS,OAAO;GACd,MAAM,sBAAsB,kCAC1B,6BAA6B,KAAK,CAAC,CAAC,SACpC,OACF;GACA,MAAM,IAAI,MAAM,uBAAuB,qBAAqB;EAC9D;CACF,GACA;EACE,MAAM;EACN,aAAa,kCAAkC,EAC7C,kBAAkB,QAAQ,iBAC5B,CAAC;EACD,QAAQ,6BAA6B,UAAU,KAAA,CAAS;EACxD,gBAAA;CACF,CACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../common/enum.mjs";
|
|
2
2
|
import "../common/index.mjs";
|
|
3
|
-
import { BASH_SHELL_GUIDANCE, CODE_ARTIFACT_PATH_GUIDANCE, appendFailedExecutionFileReminder, getCodeBaseURL } from "./CodeExecutor.mjs";
|
|
3
|
+
import { BASH_SHELL_GUIDANCE, CODE_ARTIFACT_PATH_GUIDANCE, CodeApiRequestError, appendFailedExecutionFileReminder, buildCodeApiExecutionErrorMessage, getCodeBaseURL } from "./CodeExecutor.mjs";
|
|
4
4
|
import { clampCodeApiRunTimeoutMs, createCodeApiRunTimeoutSchema, resolveCodeApiRunTimeoutMs } from "./ptcTimeout.mjs";
|
|
5
5
|
import { executeTools, formatCompletedResponse, makeRequest } from "./ProgrammaticToolCalling.mjs";
|
|
6
6
|
import { tool } from "@langchain/core/tools";
|
|
@@ -220,8 +220,8 @@ function createBashProgrammaticToolCallingTool(initParams = {}) {
|
|
|
220
220
|
}, proxy, initParams.authHeaders);
|
|
221
221
|
}
|
|
222
222
|
if (response.status === "completed") return formatCompletedResponse(response, code);
|
|
223
|
-
if (response.status === "error") throw new Error(
|
|
224
|
-
throw new
|
|
223
|
+
if (response.status === "error") throw new Error(buildCodeApiExecutionErrorMessage(response));
|
|
224
|
+
throw new CodeApiRequestError();
|
|
225
225
|
} catch (error) {
|
|
226
226
|
const messageWithReminder = appendFailedExecutionFileReminder(error.message, code);
|
|
227
227
|
throw new Error(`Bash programmatic execution failed: ${messageWithReminder}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BashProgrammaticToolCalling.mjs","names":[],"sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n getCodeBaseURL,\n} from './CodeExecutor';\nimport {\n clampCodeApiRunTimeoutMs,\n createCodeApiRunTimeoutSchema,\n resolveCodeApiRunTimeoutMs,\n} from './ptcTimeout';\nimport {\n makeRequest,\n executeTools,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- One call: state does not persist\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Save tool output with raw=$(tool '{}'); printf '%s\\n' \"$raw\" > /mnt/data/file.json; direct tool > file may be empty\n- Tool stdout is normalized to one compact JSON value when possible; parse saved stdout once, then use fromjson? // . only for JSON-string fields\n- Only echo/printf output returns to the model\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n { sf=$(web_search '{\"query\": \"SF weather\"}'); printf '%s\\n' \"$sf\" > /mnt/data/sf.json; } &\n { ny=$(web_search '{\"query\": \"NY weather\"}'); printf '%s\\n' \"$ny\" > /mnt/data/ny.json; } &\n wait\n echo \"SF: $(jq -r . /mnt/data/sf.json)\"\n echo \"NY: $(jq -r . /mnt/data/ny.json)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport function createBashProgrammaticToolCallingSchema(\n maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS\n): ProgrammaticToolCallingJsonSchema {\n return {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),\n },\n required: ['code'],\n } as const;\n}\n\nexport const BashProgrammaticToolCallingSchema =\n createBashProgrammaticToolCallingSchema();\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\nfunction maybeParseJsonResultString(result: unknown): unknown {\n if (typeof result !== 'string') {\n return result;\n }\n\n const trimmed = result.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return result;\n }\n\n try {\n return JSON.parse(trimmed) as unknown;\n } catch {\n return result;\n }\n}\n\nexport function normalizeBashToolResultsForReplay(\n toolResults: t.PTCToolResult[]\n): t.PTCToolResult[] {\n return toolResults.map((toolResult) => {\n if (toolResult.is_error) {\n return toolResult;\n }\n\n return {\n ...toolResult,\n result: maybeParseJsonResultString(toolResult.result),\n };\n });\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code } = params;\n const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n const {\n toolMap,\n toolDefs,\n session_id,\n _injected_files,\n _runtime_session_hint,\n } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /* `/files/<session_id>` HTTP fallback removed — codeapi's\n * sessionAuth requires kind/id query params unavailable at\n * this point. See `CodeExecutor.ts` for full rationale. */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n /* Stateful sessions: hint on the INITIAL request only (continuations\n * bind via continuation_token). Wire-only in v1 — BashPTC keeps its\n * stateless prompt. */\n const runtimeSessionHint =\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ? _runtime_session_hint\n : undefined;\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n ...(runtimeSessionHint != null\n ? { runtime_session_hint: runtimeSessionHint }\n : {}),\n },\n proxy,\n initParams.authHeaders\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = normalizeBashToolResultsForReplay(\n await executeTools(\n response.tool_calls ?? [],\n toolMap,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n )\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy,\n initParams.authHeaders\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response, code);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error).message,\n code\n );\n throw new Error(\n `Bash programmatic execution failed: ${messageWithReminder}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: createBashProgrammaticToolCallingSchema(maxRunTimeoutMs),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;;AAuBA,OAAO;AAMP,MAAM,0BAA0B;AAChC,MAAM,yBAAyB,2BAA2B;;AAG1D,MAAM,gBAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAMD,MAAM,oBAAoB;;;;AAK1B,MAAM,aAAa;;;;;;;IAOf,4BAA4B;IAC5B,oBAAoB;;AAGxB,MAAM,mBACJ;AAEF,MAAM,WAAW;;;;;;;;;;;AAYjB,MAAM,yBAAyB;;EAE7B,kBAAkB;;;;;EAKlB,SAAS;;EAET;AAMF,SAAgB,wCACd,kBAAkB,wBACiB;CACnC,OAAO;EACL,MAAM;EACN,YAAY;GACV,MAAM;IACJ,MAAM;IACN,WAAW;IACX,aAAa;GACf;GACA,SAAS,8BAA8B,eAAe;EACxD;EACA,UAAU,CAAC,MAAM;CACnB;AACF;AAEA,MAAa,oCACX,wCAAwC;AAE1C,MAAa,kCAAA;AAGb,MAAa,yCAAyC;;;EAGpD,kBAAkB;;EAElB,WAAW;EACX,iBAAiB;;;;EAIjB,SAAS;EACT,KAAK;AAEP,MAAa,wCAAwC;CACnD,MAAM;CACN,aAAa;CAC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AA0B,YACjC,0BAA0B,KACtB,wBACA,KAAA;GAEN,IAAI,WAAW,MAAM,YACnB,eACA;IACE,MAAM;IACN;IACA,OAAO;IACP;IACA;IACA,GAAI,SAAS,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;IAC7C,GAAI,sBAAsB,OACtB,EAAE,sBAAsB,mBAAmB,IAC3C,CAAC;GACP,GACA,OACA,WAAW,WACb;GAMA,OAAO,SAAS,WAAW,sBAAsB;IAC/C;IAEA,IAAI,YAAY,eACd,MAAM,IAAI,MACR,iCAAiC,cAAc,4FAGjD;IAGF,IAAI,OAEF,QAAQ,IACN,8BAA8B,UAAU,IAAI,SAAS,YAAY,UAAU,EAAE,oBAC/E;IAGF,MAAM,cAAc,kCAClB,MAAM,aACJ,SAAS,cAAc,CAAC,GACxB,SAAA,qBAEF,CACF;IAEA,WAAW,MAAM,YACf,eACA;KACE,oBAAoB,SAAS;KAC7B,cAAc;IAChB,GACA,OACA,WAAW,WACb;GACF;GAMA,IAAI,SAAS,WAAW,aACtB,OAAO,wBAAwB,UAAU,IAAI;GAG/C,IAAI,SAAS,WAAW,SACtB,MAAM,IAAI,MACR,oBAAoB,SAAS,WAC1B,SAAS,UAAU,QAAQ,SAAS,WAAW,KAC5C,gBAAgB,SAAS,WACzB,GACR;GAGF,MAAM,IAAI,MAAM,+BAA+B,SAAS,QAAQ;EAClE,SAAS,OAAO;GACd,MAAM,sBAAsB,kCACzB,MAAgB,SACjB,IACF;GACA,MAAM,IAAI,MACR,uCAAuC,qBACzC;EACF;CACF,GACA;EACE,MAAA;EACA,aAAa;EACb,QAAQ,wCAAwC,eAAe;EAC/D,gBAAA;CACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"BashProgrammaticToolCalling.mjs","names":[],"sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ProgrammaticToolCallingJsonSchema } from './ptcTimeout';\nimport type * as t from '@/types';\nimport {\n BASH_SHELL_GUIDANCE,\n CODE_ARTIFACT_PATH_GUIDANCE,\n appendFailedExecutionFileReminder,\n buildCodeApiExecutionErrorMessage,\n CodeApiRequestError,\n getCodeBaseURL,\n} from './CodeExecutor';\nimport {\n clampCodeApiRunTimeoutMs,\n createCodeApiRunTimeoutSchema,\n resolveCodeApiRunTimeoutMs,\n} from './ptcTimeout';\nimport {\n makeRequest,\n executeTools,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_RUN_TIMEOUT_MS = resolveCodeApiRunTimeoutMs();\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- One call: state does not persist\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Save tool output with raw=$(tool '{}'); printf '%s\\n' \"$raw\" > /mnt/data/file.json; direct tool > file may be empty\n- Tool stdout is normalized to one compact JSON value when possible; parse saved stdout once, then use fromjson? // . only for JSON-string fields\n- Only echo/printf output returns to the model\n- ${CODE_ARTIFACT_PATH_GUIDANCE}\n- ${BASH_SHELL_GUIDANCE}\n- timeout caps one sandbox run/replay iteration, not the total multi-round-trip workflow`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n { sf=$(web_search '{\"query\": \"SF weather\"}'); printf '%s\\n' \"$sf\" > /mnt/data/sf.json; } &\n { ny=$(web_search '{\"query\": \"NY weather\"}'); printf '%s\\n' \"$ny\" > /mnt/data/ny.json; } &\n wait\n echo \"SF: $(jq -r . /mnt/data/sf.json)\"\n echo \"NY: $(jq -r . /mnt/data/ny.json)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport function createBashProgrammaticToolCallingSchema(\n maxRunTimeoutMs = DEFAULT_RUN_TIMEOUT_MS\n): ProgrammaticToolCallingJsonSchema {\n return {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: createCodeApiRunTimeoutSchema(maxRunTimeoutMs),\n },\n required: ['code'],\n } as const;\n}\n\nexport const BashProgrammaticToolCallingSchema =\n createBashProgrammaticToolCallingSchema();\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\nfunction maybeParseJsonResultString(result: unknown): unknown {\n if (typeof result !== 'string') {\n return result;\n }\n\n const trimmed = result.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return result;\n }\n\n try {\n return JSON.parse(trimmed) as unknown;\n } catch {\n return result;\n }\n}\n\nexport function normalizeBashToolResultsForReplay(\n toolResults: t.PTCToolResult[]\n): t.PTCToolResult[] {\n return toolResults.map((toolResult) => {\n if (toolResult.is_error) {\n return toolResult;\n }\n\n return {\n ...toolResult,\n result: maybeParseJsonResultString(toolResult.result),\n };\n });\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const maxRunTimeoutMs = resolveCodeApiRunTimeoutMs(initParams.runTimeoutMs);\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code } = params;\n const timeout = clampCodeApiRunTimeoutMs(params.timeout, maxRunTimeoutMs);\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n _runtime_session_hint?: string;\n };\n const {\n toolMap,\n toolDefs,\n session_id,\n _injected_files,\n _runtime_session_hint,\n } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /* `/files/<session_id>` HTTP fallback removed — codeapi's\n * sessionAuth requires kind/id query params unavailable at\n * this point. See `CodeExecutor.ts` for full rationale. */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n /* Stateful sessions: hint on the INITIAL request only (continuations\n * bind via continuation_token). Wire-only in v1 — BashPTC keeps its\n * stateless prompt. */\n const runtimeSessionHint =\n typeof _runtime_session_hint === 'string' &&\n _runtime_session_hint !== ''\n ? _runtime_session_hint\n : undefined;\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n ...(runtimeSessionHint != null\n ? { runtime_session_hint: runtimeSessionHint }\n : {}),\n },\n proxy,\n initParams.authHeaders\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = normalizeBashToolResultsForReplay(\n await executeTools(\n response.tool_calls ?? [],\n toolMap,\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING\n )\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy,\n initParams.authHeaders\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response, code);\n }\n\n if (response.status === 'error') {\n throw new Error(buildCodeApiExecutionErrorMessage(response));\n }\n\n throw new CodeApiRequestError();\n } catch (error) {\n const messageWithReminder = appendFailedExecutionFileReminder(\n (error as Error).message,\n code\n );\n throw new Error(\n `Bash programmatic execution failed: ${messageWithReminder}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: createBashProgrammaticToolCallingSchema(maxRunTimeoutMs),\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"mappings":";;;;;;;;AAyBA,OAAO;AAMP,MAAM,0BAA0B;AAChC,MAAM,yBAAyB,2BAA2B;;AAG1D,MAAM,gBAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAMD,MAAM,oBAAoB;;;;AAK1B,MAAM,aAAa;;;;;;;IAOf,4BAA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