@librechat/agents 3.3.6 → 3.3.8
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/graphs/MultiAgentGraph.cjs +21 -4
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/main.cjs +2 -0
- package/dist/cjs/messages/format.cjs +124 -15
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/injected.cjs +10 -1
- package/dist/cjs/messages/injected.cjs.map +1 -1
- package/dist/cjs/prompts/activityLabel.cjs +29 -1
- package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
- package/dist/cjs/run.cjs +7 -2
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +55 -0
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/intentArg.cjs +78 -52
- package/dist/cjs/tools/intentArg.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +5 -5
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +21 -4
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -2
- package/dist/esm/messages/format.mjs +124 -15
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/injected.mjs +10 -1
- package/dist/esm/messages/injected.mjs.map +1 -1
- package/dist/esm/prompts/activityLabel.mjs +29 -1
- package/dist/esm/prompts/activityLabel.mjs.map +1 -1
- package/dist/esm/run.mjs +7 -2
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +55 -0
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/intentArg.mjs +77 -53
- package/dist/esm/tools/intentArg.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +5 -5
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/types/messages/format.d.ts +9 -8
- package/dist/types/prompts/activityLabel.d.ts +8 -1
- package/dist/types/run.d.ts +1 -1
- package/dist/types/tools/intentArg.d.ts +74 -12
- package/dist/types/tools/search/tool.d.ts +5 -5
- package/dist/types/types/activityLabel.d.ts +8 -0
- package/dist/types/types/stream.d.ts +27 -2
- package/package.json +1 -1
- package/src/graphs/MultiAgentGraph.ts +18 -4
- package/src/messages/format.ts +222 -50
- package/src/messages/formatAgentMessages.test.ts +308 -6
- package/src/messages/injected.test.ts +18 -1
- package/src/messages/injected.ts +8 -1
- package/src/prompts/activityLabel.ts +48 -0
- package/src/run.ts +10 -1
- package/src/specs/activity-label-prompt.test.ts +93 -0
- package/src/summarization/__tests__/node.test.ts +188 -0
- package/src/summarization/node.ts +67 -0
- package/src/tools/__tests__/intentArg.test.ts +101 -25
- package/src/tools/intentArg.ts +102 -68
- package/src/tools/search/outcome.test.ts +1 -1
- package/src/tools/search/tool.ts +5 -5
- package/src/types/activityLabel.ts +8 -0
- package/src/types/stream.ts +28 -2
|
@@ -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 cloneToolMessageWithContent,\n compactToolContent,\n isComputerCallOutputMessage,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\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 { calculateMaxToolResultChars } from '@/utils/truncation';\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 = serializeToolContentBounded(\n toolMsg.content,\n MAX_TOOL_FAILURE_CHARS * 4\n );\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 maxContextTokens?: number\n): BaseMessage[] {\n if (originalToolContent == null || originalToolContent.size === 0) {\n return messages;\n }\n\n const restorable: Array<{\n index: number;\n message: ToolMessage;\n content: string;\n }> = [];\n for (const [index, content] of originalToolContent) {\n const message = messages[index];\n if (\n message instanceof ToolMessage &&\n !isComputerCallOutputMessage(message)\n ) {\n restorable.push({ index, message, content });\n }\n }\n if (restorable.length === 0) {\n return messages;\n }\n\n /**\n * Restored originals improve checkpoint quality, but they still feed a\n * provider call. Share one tool-result budget across every restoration so\n * several previously masked results cannot overflow the summarizer.\n */\n let remainingChars = calculateMaxToolResultChars(maxContextTokens);\n const restored = [...messages];\n for (let i = 0; i < restorable.length; i++) {\n const { index, message, content } = restorable[i];\n const maxChars = Math.floor(remainingChars / (restorable.length - i));\n const compacted = compactToolContent(content, maxChars).content;\n restored[index] = cloneToolMessageWithContent(message, compacted);\n remainingChars -= serializeToolContentBounded(compacted, maxChars).length;\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 agentContext.maxContextTokens\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":";;;;;;;;;;;;;;;;AA2CA,MAAM,2BAA2B,IAAI,IAAI,CAAC,kBAAkB,CAAC;;;;;;;;;;;;;;;;;AAkB7D,MAAM,kCAAkC;;AAGxC,MAAa,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC5C,MAAa,sCAAsC;;;;;;;;;;;;;;AAenD,SAAS,mBAAmB,YAG1B;CACA,MAAM,YAAqC,CAAC;CAC5C,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,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 cloneToolMessageWithContent,\n compactToolContent,\n isComputerCallOutputMessage,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\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 { calculateMaxToolResultChars } from '@/utils/truncation';\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 = serializeToolContentBounded(\n toolMsg.content,\n MAX_TOOL_FAILURE_CHARS * 4\n );\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 maxContextTokens?: number\n): BaseMessage[] {\n if (originalToolContent == null || originalToolContent.size === 0) {\n return messages;\n }\n\n const restorable: Array<{\n index: number;\n message: ToolMessage;\n content: string;\n }> = [];\n for (const [index, content] of originalToolContent) {\n const message = messages[index];\n if (\n message instanceof ToolMessage &&\n !isComputerCallOutputMessage(message)\n ) {\n restorable.push({ index, message, content });\n }\n }\n if (restorable.length === 0) {\n return messages;\n }\n\n /**\n * Restored originals improve checkpoint quality, but they still feed a\n * provider call. Share one tool-result budget across every restoration so\n * several previously masked results cannot overflow the summarizer.\n */\n let remainingChars = calculateMaxToolResultChars(maxContextTokens);\n const restored = [...messages];\n for (let i = 0; i < restorable.length; i++) {\n const { index, message, content } = restorable[i];\n const maxChars = Math.floor(remainingChars / (restorable.length - i));\n const compacted = compactToolContent(content, maxChars).content;\n restored[index] = cloneToolMessageWithContent(message, compacted);\n remainingChars -= serializeToolContentBounded(compacted, maxChars).length;\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/**\n * Names the first retained message so the summary declares its own extent\n * rather than leaving the next run to infer coverage from where the block\n * happens to sit.\n *\n * Anchored to the retained side, not the covered side. One source message can\n * expand into several messages — a steer splits an assistant entry into\n * pre-steer, steer, and post-steer entries sharing its ID — and the recency\n * split lands on any human-type message, including the steer. Naming the last\n * *covered* message would then name a half-covered ID with no correct reading;\n * naming the first *retained* message makes that same message the anchor, so it\n * survives whole and everything before it is unambiguously covered.\n *\n * Synthetic entries are skipped, because they can sit *before* a resolvable\n * one. `formatAgentMessages` reconstructs skill bodies inside its payload loop\n * (see the `pendingSkillNames` block) and keeps processing payload entries\n * afterwards, so an unstamped skill body — which `messagesStateReducer` then\n * gives a UUID no payload entry carries — is followed by stamped messages.\n * Anchoring on the UUID would look resolvable at write time and degrade to\n * positional trimming on read, dropping the retained tail. Skipping it reaches\n * the stamped message behind it.\n *\n * `convertInjectedMessages` records `injected` on everything it builds, which is\n * what makes this decidable: `isMeta` and `source` are both optional on\n * `InjectedMessage`, so a bare entry carries no marker of its own, and an\n * injected `source: 'steer'` is otherwise indistinguishable from a replayed one.\n * The remaining `isMeta`/`source` checks cover the constructors that build\n * synthetic entries directly instead of going through that funnel — hook context\n * in `ToolNode` and `StandardGraph`, handoff cues, reconstructed skill bodies.\n *\n * `steer` is exempt from the `source` check because a replayed steer *is*\n * stamped from its payload entry; rejecting every marked `source` once dropped\n * exactly those retained steers. Injected steers are still caught, by `injected`.\n *\n * Known limitation: a payload entry that omits `messageId` is never stamped, so\n * the reducer's UUID is recorded and cannot resolve on the next run. There is no\n * write-time fix — such an entry has no stable ID to name in the next payload\n * either — and the reader's positional fallback is what `main` already does, so\n * the anchor degrades rather than misleads.\n */\nfunction isSyntheticContext(message: BaseMessage): boolean {\n const { additional_kwargs: kwargs } = message;\n if (kwargs.injected === true || kwargs.isMeta === true) {\n return true;\n }\n return kwargs.source != null && kwargs.source !== 'steer';\n}\n\nfunction resolveSummaryCoverage(\n messagesToRetain: BaseMessage[]\n): t.SummaryCoverage | undefined {\n for (let i = 0; i < messagesToRetain.length; i++) {\n const message = messagesToRetain[i];\n if (isSyntheticContext(message)) {\n continue;\n }\n const id = message.id?.trim();\n if (id != null && id !== '') {\n return { retainedFromMessageId: id };\n }\n }\n return undefined;\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 coverage?: t.SummaryCoverage;\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 ...(params.coverage != null ? { coverage: params.coverage } : {}),\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 agentContext.maxContextTokens\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 coverage: resolveSummaryCoverage(messagesToRetain),\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":";;;;;;;;;;;;;;;;AA2CA,MAAM,2BAA2B,IAAI,IAAI,CAAC,kBAAkB,CAAC;;;;;;;;;;;;;;;;;AAkB7D,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;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,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,8 +1,29 @@
|
|
|
1
1
|
//#region src/tools/intentArg.ts
|
|
2
2
|
/** Argument carrying the model-authored label for a tool call. */
|
|
3
3
|
const INTENT_ARG = "intent";
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Opening words of {@link INTENT_DESCRIPTION}, and the discriminator that
|
|
6
|
+
* tells the injected LABEL apart from a tool's own business parameter that
|
|
7
|
+
* merely shares the name `intent`.
|
|
8
|
+
*
|
|
9
|
+
* Exported because host applications reimplement the same strip/sanitize
|
|
10
|
+
* passes and would otherwise duplicate this as a string literal: if the two
|
|
11
|
+
* copies drift, the host silently stops recognizing SDK-native labels and
|
|
12
|
+
* fails OPEN (labels stay in schemas, opt-outs stop working) with no error.
|
|
13
|
+
* Any edit to the description must preserve this prefix verbatim.
|
|
14
|
+
*/
|
|
15
|
+
const INTENT_LABEL_MARKER = "ALWAYS write this field FIRST";
|
|
16
|
+
/**
|
|
17
|
+
* Model-facing instruction for the injected `intent` property.
|
|
18
|
+
*
|
|
19
|
+
* Deliberately terse — it is repeated on every opted-in tool schema, on every
|
|
20
|
+
* request, so each sentence is paid for many times over. What remains is
|
|
21
|
+
* load-bearing: first-position placement (the entire streaming mechanism),
|
|
22
|
+
* the one-sentence present-progressive form, who reads it, and the sibling
|
|
23
|
+
* rule, without which models emit identical labels for parallel calls to one
|
|
24
|
+
* tool and defeat the feature's headline case.
|
|
25
|
+
*/
|
|
26
|
+
const INTENT_DESCRIPTION = `${INTENT_LABEL_MARKER}, before any other argument. One present-progressive sentence saying what THIS call is about to do: "Searching for OAuth handling in the callback router". Shown to the user as this call's live status. Never name the tool. Sibling calls to one tool must differ.`;
|
|
6
27
|
/**
|
|
7
28
|
* Canonical (frozen) shape of the injected property. Always embed a COPY
|
|
8
29
|
* (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a
|
|
@@ -26,6 +47,38 @@ function isIntentLabelProperty(property) {
|
|
|
26
47
|
return record.type === "string" && typeof record.description === "string" && record.description.startsWith("ALWAYS write this field FIRST");
|
|
27
48
|
}
|
|
28
49
|
/**
|
|
50
|
+
* Returns a copy of `parameters` without the injected intent LABEL — the
|
|
51
|
+
* opt-out for consumers that render no status label and should not pay for
|
|
52
|
+
* the property.
|
|
53
|
+
*
|
|
54
|
+
* The SDK's native schemas carry the label unconditionally, so without this
|
|
55
|
+
* an embedder has no lever at all: `withIntent` is applied at module scope.
|
|
56
|
+
* Marker-guarded, so a tool's own business parameter named `intent` is never
|
|
57
|
+
* removed. Returns the input unchanged when there is nothing to strip.
|
|
58
|
+
*
|
|
59
|
+
* `required` is pruned alongside the property: a schema that lists `intent`
|
|
60
|
+
* as required (strict-mode normalization does exactly that, since OpenAI
|
|
61
|
+
* strict function schemas require every property to appear in `required`)
|
|
62
|
+
* would otherwise be left naming a property it no longer declares, which is
|
|
63
|
+
* invalid JSON Schema and gets rejected by the provider instead of quietly
|
|
64
|
+
* opting out.
|
|
65
|
+
*/
|
|
66
|
+
function withoutIntent(parameters) {
|
|
67
|
+
const props = parameters?.properties;
|
|
68
|
+
if (parameters == null || props == null || !isIntentLabelProperty(props["intent"])) return parameters;
|
|
69
|
+
const { [INTENT_ARG]: _omit, ...rest } = props;
|
|
70
|
+
const next = {
|
|
71
|
+
...parameters,
|
|
72
|
+
properties: rest
|
|
73
|
+
};
|
|
74
|
+
if (parameters.required != null) {
|
|
75
|
+
const required = parameters.required.filter((key) => key !== INTENT_ARG);
|
|
76
|
+
if (required.length > 0) next.required = required;
|
|
77
|
+
else delete next.required;
|
|
78
|
+
}
|
|
79
|
+
return next;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
29
82
|
* Returns a copy of the parameters schema with `intent` prepended as the
|
|
30
83
|
* FIRST property (object key order is insertion order and every provider
|
|
31
84
|
* serializer preserves it — first key in the schema means first key in the
|
|
@@ -79,54 +132,24 @@ function stripIntent(args) {
|
|
|
79
132
|
return rest;
|
|
80
133
|
}
|
|
81
134
|
/**
|
|
82
|
-
* Leading-verb map for the mechanical outcome transform, keyed by the
|
|
83
|
-
* lowercased first word of the intent. Deliberately small: an unknown leading
|
|
84
|
-
* word leaves the intent unchanged rather than mangling it.
|
|
85
|
-
*/
|
|
86
|
-
const OUTCOME_VERB_MAP = new Map([
|
|
87
|
-
["searching", "Searched"],
|
|
88
|
-
["reading", "Read"],
|
|
89
|
-
["writing", "Wrote"],
|
|
90
|
-
["editing", "Edited"],
|
|
91
|
-
["running", "Ran"],
|
|
92
|
-
["creating", "Created"],
|
|
93
|
-
["checking", "Checked"],
|
|
94
|
-
["fetching", "Fetched"],
|
|
95
|
-
["listing", "Listed"],
|
|
96
|
-
["looking", "Looked"],
|
|
97
|
-
["building", "Built"],
|
|
98
|
-
["deleting", "Deleted"],
|
|
99
|
-
["updating", "Updated"],
|
|
100
|
-
["adding", "Added"],
|
|
101
|
-
["removing", "Removed"],
|
|
102
|
-
["verifying", "Verified"],
|
|
103
|
-
["analyzing", "Analyzed"],
|
|
104
|
-
["generating", "Generated"],
|
|
105
|
-
["delegating", "Delegated"],
|
|
106
|
-
["spawning", "Spawned"],
|
|
107
|
-
["compiling", "Compiled"],
|
|
108
|
-
["grepping", "Grepped"]
|
|
109
|
-
]);
|
|
110
|
-
function matchLeadingCase(replacement, original) {
|
|
111
|
-
if (original.charAt(0) === original.charAt(0).toLowerCase()) return replacement.charAt(0).toLowerCase() + replacement.slice(1);
|
|
112
|
-
return replacement;
|
|
113
|
-
}
|
|
114
|
-
function transformLeadingVerb(intent) {
|
|
115
|
-
const spaceIdx = intent.search(/\s/);
|
|
116
|
-
const leading = spaceIdx === -1 ? intent : intent.slice(0, spaceIdx);
|
|
117
|
-
const mapped = OUTCOME_VERB_MAP.get(leading.toLowerCase());
|
|
118
|
-
if (mapped == null) return intent;
|
|
119
|
-
return matchLeadingCase(mapped, leading) + intent.slice(leading.length);
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
135
|
* Resolves the settled label for a call from its model-authored `intent` and
|
|
123
136
|
* the tool's result fields, in precedence order:
|
|
124
137
|
*
|
|
125
138
|
* 1. `outcome` — full replacement authored by the tool.
|
|
126
139
|
* 2. `outcome_patch` — first occurrence of `from` in the intent replaced
|
|
127
140
|
* with `to` (case-sensitive); no-op when `from` is absent or empty.
|
|
128
|
-
* 3.
|
|
129
|
-
*
|
|
141
|
+
* 3. Otherwise the intent is returned UNCHANGED.
|
|
142
|
+
*
|
|
143
|
+
* There is deliberately no mechanical present-progressive→past-tense rewrite.
|
|
144
|
+
* Such a transform can only be a closed list of English verbs, which makes it
|
|
145
|
+
* wrong in three ways at once: it never fires for the non-English labels this
|
|
146
|
+
* feature expects (the model answers in the user's language), it fires for
|
|
147
|
+
* some sibling calls and not others inside one group — "Searched…" beside
|
|
148
|
+
* "Recording…" — and it quietly enumerates a vocabulary in a feature whose
|
|
149
|
+
* premise is that the sentence is free-form. Completion is conveyed by UI
|
|
150
|
+
* state (the shimmer stopping, the icon settling), which is language-neutral
|
|
151
|
+
* and always consistent; a tool that wants past tense says so explicitly via
|
|
152
|
+
* `outcome` or `outcome_patch`.
|
|
130
153
|
*
|
|
131
154
|
* Returns undefined when there is neither an intent nor an outcome, so
|
|
132
155
|
* callers fall back to their default label. Pure and dependency-free — host
|
|
@@ -142,7 +165,7 @@ function applyOutcome(intent, result) {
|
|
|
142
165
|
* argument would interpret `$&`/`$'`-style tokens in tool-authored
|
|
143
166
|
* text (e.g. labels derived from shell syntax). */
|
|
144
167
|
return intent.replace(patch.from, () => patch.to);
|
|
145
|
-
return
|
|
168
|
+
return intent;
|
|
146
169
|
}
|
|
147
170
|
/**
|
|
148
171
|
* Hard cap on an emitted outcome label. The label is a single progress line
|
|
@@ -160,15 +183,16 @@ function boundOutcomeLabel(label) {
|
|
|
160
183
|
/**
|
|
161
184
|
* Resolves the settled label to emit on a completion event: only when the
|
|
162
185
|
* tool actually authored `outcome`/`outcome_patch` fields. Returns undefined
|
|
163
|
-
* otherwise
|
|
164
|
-
*
|
|
165
|
-
*
|
|
186
|
+
* otherwise, so the wire never carries a label the host already has — a bare
|
|
187
|
+
* intent needs no settled form, because it is displayed unchanged and the UI
|
|
188
|
+
* conveys completion through its own state. Hosts must NOT rewrite it (see
|
|
189
|
+
* {@link applyOutcome} for why a tense transform is deliberately absent). The
|
|
190
|
+
* result is collapsed to a bounded single line before emission.
|
|
166
191
|
*
|
|
167
192
|
* For failed calls (`isError`), only tool-AUTHORED text may label the call:
|
|
168
|
-
* an explicit `outcome`, or a patch whose `from` actually matches the
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* render a success-looking label for an error.
|
|
193
|
+
* an explicit `outcome`, or a patch whose `from` actually matches the intent.
|
|
194
|
+
* An unmatched patch resolves to undefined rather than silently reusing the
|
|
195
|
+
* in-flight intent, so a failure is never labelled as though it succeeded.
|
|
172
196
|
*/
|
|
173
197
|
function resolveToolOutcome(args, fields, options) {
|
|
174
198
|
if (fields == null || fields.outcome == null && fields.outcome_patch == null) return;
|
|
@@ -215,6 +239,6 @@ function readOutcomeFields(source) {
|
|
|
215
239
|
};
|
|
216
240
|
}
|
|
217
241
|
//#endregion
|
|
218
|
-
export { INTENT_ARG, INTENT_DESCRIPTION, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent };
|
|
242
|
+
export { INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent, withoutIntent };
|
|
219
243
|
|
|
220
244
|
//# sourceMappingURL=intentArg.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intentArg.mjs","names":[],"sources":["../../../src/tools/intentArg.ts"],"sourcesContent":["/**\n * @fileoverview Tool intent labels.\n *\n * Lets a tool declare, as the FIRST property of its input schema, an `intent`\n * string: one model-authored sentence stating what that specific call is about\n * to do (\"Searching for OAuth handling in the callback router\"). Because the\n * property is first, it is the first key providers stream in the tool-call\n * args, so a host UI can render it as the call's live status label before the\n * rest of the args exist. When the call settles, {@link applyOutcome} edits\n * the sentence in place into its outcome form — a tool-supplied replacement\n * (`outcome`), a tool-supplied span edit (`outcome_patch`), or a mechanical\n * present-progressive→past-tense transform of the leading verb.\n *\n * The arg is always optional (never listed in `required`): the same schemas\n * are callable from programmatic tool calling, where no UI renders a label\n * and forcing generated code to fabricate one would be pure cost. Tool bodies\n * must call {@link stripIntent} before using their args so no tool receives a\n * parameter it did not declare.\n */\n\nimport type { JsonSchemaType, OutcomePatch } from '@/types';\n\n/** Argument carrying the model-authored label for a tool call. */\nexport const INTENT_ARG = 'intent';\n\n/** Model-facing instruction for the injected `intent` property. */\nexport const INTENT_DESCRIPTION =\n 'ALWAYS write this field FIRST, before any other argument. One short sentence, ' +\n 'present progressive, stating what this specific call is about to do: ' +\n '\"Searching for OAuth handling in the callback router\". It is shown to the user ' +\n 'as the live status label for this call while it runs, so write it for a human ' +\n 'reading a progress line. Do not restate the tool name. Do not exceed one sentence. ' +\n 'When you make several calls to the same tool in one turn, each intent must ' +\n 'distinguish that call from its siblings.';\n\n/**\n * Canonical (frozen) shape of the injected property. Always embed a COPY\n * (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a\n * `__absolute_uri__` marker onto every subschema it dereferences, which\n * throws on a frozen object — and a single shared instance would be stamped\n * with one schema's URI while embedded in many.\n */\nexport const INTENT_PROPERTY: JsonSchemaType = Object.freeze<JsonSchemaType>({\n type: 'string',\n description: INTENT_DESCRIPTION,\n});\n\n/**\n * Discriminates the intent LABEL property from a tool's own business\n * parameter that merely shares the name: the label contract always opens\n * with the same instruction. Removal/sanitize passes must never strip a\n * parameter the tool actually needs.\n */\nexport function isIntentLabelProperty(property: unknown): boolean {\n if (property == null || typeof property !== 'object') {\n return false;\n }\n const record = property as { type?: unknown; description?: unknown };\n return (\n record.type === 'string' &&\n typeof record.description === 'string' &&\n record.description.startsWith('ALWAYS write this field FIRST')\n );\n}\n\n/**\n * Returns a copy of the parameters schema with `intent` prepended as the\n * FIRST property (object key order is insertion order and every provider\n * serializer preserves it — first key in the schema means first key in the\n * streamed input). Never mutates the input; no-op when the schema already\n * declares `intent`. The property is not added to `required`.\n */\nexport function withIntent(parameters?: JsonSchemaType): JsonSchemaType {\n const existingProps = parameters?.properties ?? {};\n if (INTENT_ARG in existingProps) {\n return parameters as JsonSchemaType;\n }\n return {\n ...parameters,\n type: 'object',\n properties: { [INTENT_ARG]: { ...INTENT_PROPERTY }, ...existingProps },\n };\n}\n\n/**\n * Coerces tool-call args to an object, parsing a stringified JSON object\n * (some providers deliver args as a string). Returns undefined otherwise.\n */\nfunction coerceArgsObject(args: unknown): Record<string, unknown> | undefined {\n if (typeof args === 'object' && args !== null && !Array.isArray(args)) {\n return args as Record<string, unknown>;\n }\n if (typeof args === 'string' && args.trim().startsWith('{')) {\n try {\n const parsed = JSON.parse(args) as unknown;\n if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Reads the model-authored intent from tool-call args (handles stringified\n * args). Returns undefined when absent, empty, or not a string.\n */\nexport function readIntent(args: unknown): string | undefined {\n const value = coerceArgsObject(args)?.[INTENT_ARG];\n if (typeof value !== 'string') {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\n/**\n * Returns the args without the `intent` key so downstream consumers that did\n * not declare it never receive it. Parses stringified JSON object args;\n * returns the value unchanged when the key is absent.\n */\nexport function stripIntent(args: unknown): unknown {\n const obj = coerceArgsObject(args);\n if (!obj || !(INTENT_ARG in obj)) {\n return args;\n }\n const { [INTENT_ARG]: _omit, ...rest } = obj;\n return rest;\n}\n\n/**\n * Leading-verb map for the mechanical outcome transform, keyed by the\n * lowercased first word of the intent. Deliberately small: an unknown leading\n * word leaves the intent unchanged rather than mangling it.\n */\nconst OUTCOME_VERB_MAP: ReadonlyMap<string, string> = new Map([\n ['searching', 'Searched'],\n ['reading', 'Read'],\n ['writing', 'Wrote'],\n ['editing', 'Edited'],\n ['running', 'Ran'],\n ['creating', 'Created'],\n ['checking', 'Checked'],\n ['fetching', 'Fetched'],\n ['listing', 'Listed'],\n ['looking', 'Looked'],\n ['building', 'Built'],\n ['deleting', 'Deleted'],\n ['updating', 'Updated'],\n ['adding', 'Added'],\n ['removing', 'Removed'],\n ['verifying', 'Verified'],\n ['analyzing', 'Analyzed'],\n ['generating', 'Generated'],\n ['delegating', 'Delegated'],\n ['spawning', 'Spawned'],\n ['compiling', 'Compiled'],\n ['grepping', 'Grepped'],\n]);\n\nfunction matchLeadingCase(replacement: string, original: string): string {\n if (original.charAt(0) === original.charAt(0).toLowerCase()) {\n return replacement.charAt(0).toLowerCase() + replacement.slice(1);\n }\n return replacement;\n}\n\nfunction transformLeadingVerb(intent: string): string {\n const spaceIdx = intent.search(/\\s/);\n const leading = spaceIdx === -1 ? intent : intent.slice(0, spaceIdx);\n const mapped = OUTCOME_VERB_MAP.get(leading.toLowerCase());\n if (mapped == null) {\n return intent;\n }\n return matchLeadingCase(mapped, leading) + intent.slice(leading.length);\n}\n\n/**\n * Resolves the settled label for a call from its model-authored `intent` and\n * the tool's result fields, in precedence order:\n *\n * 1. `outcome` — full replacement authored by the tool.\n * 2. `outcome_patch` — first occurrence of `from` in the intent replaced\n * with `to` (case-sensitive); no-op when `from` is absent or empty.\n * 3. Mechanical transform — the leading word mapped present-progressive →\n * past tense; an unknown leading word leaves the intent unchanged.\n *\n * Returns undefined when there is neither an intent nor an outcome, so\n * callers fall back to their default label. Pure and dependency-free — host\n * UIs needing identical logic can import or mirror it.\n */\nexport function applyOutcome(\n intent: string | undefined,\n result?: { outcome?: string; outcome_patch?: OutcomePatch },\n): string | undefined {\n const outcome = result?.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return outcome;\n }\n if (intent == null || intent === '') {\n return undefined;\n }\n const patch = result?.outcome_patch;\n if (patch != null && patch.from !== '' && intent.includes(patch.from)) {\n /** Replacement callback keeps `to` verbatim — a direct string second\n * argument would interpret `$&`/`$'`-style tokens in tool-authored\n * text (e.g. labels derived from shell syntax). */\n return intent.replace(patch.from, () => patch.to);\n }\n return transformLeadingVerb(intent);\n}\n\n/**\n * Hard cap on an emitted outcome label. The label is a single progress line\n * in UI chrome; a tool that derives it from data (or a malformed patch)\n * must not be able to inflate completion events or persisted parts.\n */\nconst MAX_OUTCOME_CHARS = 256;\n\nfunction boundOutcomeLabel(label: string | undefined): string | undefined {\n if (label == null) {\n return undefined;\n }\n const singleLine = label.replace(/\\s+/g, ' ').trim();\n if (singleLine === '') {\n return undefined;\n }\n if (singleLine.length <= MAX_OUTCOME_CHARS) {\n return singleLine;\n }\n return `${singleLine.slice(0, MAX_OUTCOME_CHARS - 1)}…`;\n}\n\n/**\n * Resolves the settled label to emit on a completion event: only when the\n * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined\n * otherwise — the mechanical transform of a bare intent is left to the host\n * so the wire never carries a label the host can derive itself. The result\n * is collapsed to a bounded single line before emission.\n *\n * For failed calls (`isError`), only tool-AUTHORED text may label the call:\n * an explicit `outcome`, or a patch whose `from` actually matches the\n * intent. An unmatched patch must not fall through to the mechanical\n * past-tense transform — wording drift in a failure patch would otherwise\n * render a success-looking label for an error.\n */\nexport function resolveToolOutcome(\n args: unknown,\n fields?: { outcome?: string; outcome_patch?: OutcomePatch } | null,\n options?: { isError?: boolean },\n): string | undefined {\n if (fields == null || (fields.outcome == null && fields.outcome_patch == null)) {\n return undefined;\n }\n if (options?.isError !== true) {\n return boundOutcomeLabel(applyOutcome(readIntent(args), fields));\n }\n const outcome = fields.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return boundOutcomeLabel(outcome);\n }\n const intent = readIntent(args);\n const patch = fields.outcome_patch;\n if (\n intent != null &&\n patch != null &&\n patch.from !== '' &&\n intent.includes(patch.from)\n ) {\n return boundOutcomeLabel(intent.replace(patch.from, () => patch.to));\n }\n return undefined;\n}\n\n/**\n * Reads the outcome fields off a tool-execution result: the typed\n * `outcome`/`outcome_patch` fields when present, else the artifact channel\n * (see {@link readOutcomeFields}) — so a `content_and_artifact` tool authors\n * its label the same way on the direct and event-driven paths.\n */\nexport function outcomeFieldsFromResult(result: {\n outcome?: string;\n outcome_patch?: OutcomePatch;\n artifact?: unknown;\n}): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (result.outcome != null || result.outcome_patch != null) {\n return result;\n }\n return readOutcomeFields(result.artifact);\n}\n\n/**\n * Extracts validated `outcome`/`outcome_patch` fields from an arbitrary\n * value — the artifact channel through which an in-process\n * `content_and_artifact` tool authors its settled label. Returns undefined\n * when neither field is usable.\n */\nexport function readOutcomeFields(\n source: unknown,\n): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (source == null || typeof source !== 'object' || Array.isArray(source)) {\n return undefined;\n }\n const record = source as Record<string, unknown>;\n const outcome =\n typeof record.outcome === 'string' && record.outcome.trim() !== ''\n ? record.outcome\n : undefined;\n let outcome_patch: OutcomePatch | undefined;\n const rawPatch = record.outcome_patch;\n if (rawPatch != null && typeof rawPatch === 'object' && !Array.isArray(rawPatch)) {\n const patch = rawPatch as Record<string, unknown>;\n if (typeof patch.from === 'string' && typeof patch.to === 'string') {\n outcome_patch = { from: patch.from, to: patch.to };\n }\n }\n if (outcome == null && outcome_patch == null) {\n return undefined;\n }\n return { outcome, outcome_patch };\n}\n"],"mappings":";;AAuBA,MAAa,aAAa;;AAG1B,MAAa,qBACX;;;;;;;;AAeF,MAAa,kBAAkC,OAAO,OAAuB;CAC3E,MAAM;CACN,aAAa;AACf,CAAC;;;;;;;AAQD,SAAgB,sBAAsB,UAA4B;CAChE,IAAI,YAAY,QAAQ,OAAO,aAAa,UAC1C,OAAO;CAET,MAAM,SAAS;CACf,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,gBAAgB,YAC9B,OAAO,YAAY,WAAW,+BAA+B;AAEjE;;;;;;;;AASA,SAAgB,WAAW,YAA6C;CACtE,MAAM,gBAAgB,YAAY,cAAc,CAAC;CACjD,IAAA,YAAkB,eAChB,OAAO;CAET,OAAO;EACL,GAAG;EACH,MAAM;EACN,YAAY;IAAG,aAAa,EAAE,GAAG,gBAAgB;GAAG,GAAG;EAAc;CACvE;AACF;;;;;AAMA,SAAS,iBAAiB,MAAoD;CAC5E,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,CAAC,MAAM,QAAQ,IAAI,GAClE,OAAO;CAET,IAAI,OAAO,SAAS,YAAY,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG,GACxD,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;EAC9B,IAAI,UAAU,QAAQ,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,GACvE,OAAO;CAEX,QAAQ;EACN;CACF;AAGJ;;;;;AAMA,SAAgB,WAAW,MAAmC;CAC5D,MAAM,QAA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,CAAC;AAGvE;;;;;;;AAQA,SAAgB,wBAAwB,QAI2B;CACjE,IAAI,OAAO,WAAW,QAAQ,OAAO,iBAAiB,MACpD,OAAO;CAET,OAAO,kBAAkB,OAAO,QAAQ;AAC1C;;;;;;;AAQA,SAAgB,kBACd,QACgE;CAChE,IAAI,UAAU,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACtE;CAEF,MAAM,SAAS;CACf,MAAM,UACJ,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,KAAK,MAAM,KAC5D,OAAO,UACP,KAAA;CACN,IAAI;CACJ,MAAM,WAAW,OAAO;CACxB,IAAI,YAAY,QAAQ,OAAO,aAAa,YAAY,CAAC,MAAM,QAAQ,QAAQ,GAAG;EAChF,MAAM,QAAQ;EACd,IAAI,OAAO,MAAM,SAAS,YAAY,OAAO,MAAM,OAAO,UACxD,gBAAgB;GAAE,MAAM,MAAM;GAAM,IAAI,MAAM;EAAG;CAErD;CACA,IAAI,WAAW,QAAQ,iBAAiB,MACtC;CAEF,OAAO;EAAE;EAAS;CAAc;AAClC"}
|
|
1
|
+
{"version":3,"file":"intentArg.mjs","names":[],"sources":["../../../src/tools/intentArg.ts"],"sourcesContent":["/**\n * @fileoverview Tool intent labels.\n *\n * Lets a tool declare, as the FIRST property of its input schema, an `intent`\n * string: one model-authored sentence stating what that specific call is about\n * to do (\"Searching for OAuth handling in the callback router\"). Because the\n * property is first, it is the first key providers stream in the tool-call\n * args, so a host UI can render it as the call's live status label before the\n * rest of the args exist. When the call settles, {@link applyOutcome} edits\n * the sentence in place into its outcome form — a tool-supplied replacement\n * (`outcome`) or a tool-supplied span edit (`outcome_patch`). Absent either,\n * the label is left exactly as the model wrote it: completion is a UI state\n * (the shimmer stopping, the icon settling), not a tense change.\n *\n * The arg is always optional (never listed in `required`): the same schemas\n * are callable from programmatic tool calling, where no UI renders a label\n * and forcing generated code to fabricate one would be pure cost. Tool bodies\n * must call {@link stripIntent} before using their args so no tool receives a\n * parameter it did not declare.\n */\n\nimport type { JsonSchemaType, OutcomePatch } from '@/types';\n\n/** Argument carrying the model-authored label for a tool call. */\nexport const INTENT_ARG = 'intent';\n\n/**\n * Opening words of {@link INTENT_DESCRIPTION}, and the discriminator that\n * tells the injected LABEL apart from a tool's own business parameter that\n * merely shares the name `intent`.\n *\n * Exported because host applications reimplement the same strip/sanitize\n * passes and would otherwise duplicate this as a string literal: if the two\n * copies drift, the host silently stops recognizing SDK-native labels and\n * fails OPEN (labels stay in schemas, opt-outs stop working) with no error.\n * Any edit to the description must preserve this prefix verbatim.\n */\nexport const INTENT_LABEL_MARKER = 'ALWAYS write this field FIRST';\n\n/**\n * Model-facing instruction for the injected `intent` property.\n *\n * Deliberately terse — it is repeated on every opted-in tool schema, on every\n * request, so each sentence is paid for many times over. What remains is\n * load-bearing: first-position placement (the entire streaming mechanism),\n * the one-sentence present-progressive form, who reads it, and the sibling\n * rule, without which models emit identical labels for parallel calls to one\n * tool and defeat the feature's headline case.\n */\nexport const INTENT_DESCRIPTION =\n `${INTENT_LABEL_MARKER}, before any other argument. One present-progressive ` +\n 'sentence saying what THIS call is about to do: \"Searching for OAuth handling ' +\n 'in the callback router\". Shown to the user as this call\\'s live status. ' +\n 'Never name the tool. Sibling calls to one tool must differ.';\n\n/**\n * Canonical (frozen) shape of the injected property. Always embed a COPY\n * (`{ ...INTENT_PROPERTY }`): LangChain's JSON-schema validator stamps a\n * `__absolute_uri__` marker onto every subschema it dereferences, which\n * throws on a frozen object — and a single shared instance would be stamped\n * with one schema's URI while embedded in many.\n */\nexport const INTENT_PROPERTY: JsonSchemaType = Object.freeze<JsonSchemaType>({\n type: 'string',\n description: INTENT_DESCRIPTION,\n});\n\n/**\n * Discriminates the intent LABEL property from a tool's own business\n * parameter that merely shares the name: the label contract always opens\n * with the same instruction. Removal/sanitize passes must never strip a\n * parameter the tool actually needs.\n */\nexport function isIntentLabelProperty(property: unknown): boolean {\n if (property == null || typeof property !== 'object') {\n return false;\n }\n const record = property as { type?: unknown; description?: unknown };\n return (\n record.type === 'string' &&\n typeof record.description === 'string' &&\n record.description.startsWith(INTENT_LABEL_MARKER)\n );\n}\n\n/**\n * Schema shape accepted by {@link withoutIntent}.\n *\n * `required` is widened to `readonly string[]` because the SDK's own native\n * schemas are declared `as const` — their `required` is a readonly tuple, and\n * a mutable `string[]` parameter would reject the very schemas this helper\n * exists for (TS2345), forcing embedders to cast to use the advertised API.\n */\nexport type IntentStrippableSchema = Omit<JsonSchemaType, 'required'> & {\n required?: readonly string[];\n};\n\n/**\n * Returns a copy of `parameters` without the injected intent LABEL — the\n * opt-out for consumers that render no status label and should not pay for\n * the property.\n *\n * The SDK's native schemas carry the label unconditionally, so without this\n * an embedder has no lever at all: `withIntent` is applied at module scope.\n * Marker-guarded, so a tool's own business parameter named `intent` is never\n * removed. Returns the input unchanged when there is nothing to strip.\n *\n * `required` is pruned alongside the property: a schema that lists `intent`\n * as required (strict-mode normalization does exactly that, since OpenAI\n * strict function schemas require every property to appear in `required`)\n * would otherwise be left naming a property it no longer declares, which is\n * invalid JSON Schema and gets rejected by the provider instead of quietly\n * opting out.\n */\nexport function withoutIntent(parameters?: IntentStrippableSchema): JsonSchemaType | undefined {\n const props = parameters?.properties;\n if (parameters == null || props == null || !isIntentLabelProperty(props[INTENT_ARG])) {\n return parameters as JsonSchemaType | undefined;\n }\n const { [INTENT_ARG]: _omit, ...rest } = props;\n const next: JsonSchemaType = {\n ...(parameters as JsonSchemaType),\n properties: rest,\n };\n if (parameters.required != null) {\n const required = parameters.required.filter((key) => key !== INTENT_ARG);\n if (required.length > 0) {\n next.required = required;\n } else {\n delete next.required;\n }\n }\n return next;\n}\n\n/**\n * Returns a copy of the parameters schema with `intent` prepended as the\n * FIRST property (object key order is insertion order and every provider\n * serializer preserves it — first key in the schema means first key in the\n * streamed input). Never mutates the input; no-op when the schema already\n * declares `intent`. The property is not added to `required`.\n */\nexport function withIntent(parameters?: JsonSchemaType): JsonSchemaType {\n const existingProps = parameters?.properties ?? {};\n if (INTENT_ARG in existingProps) {\n return parameters as JsonSchemaType;\n }\n return {\n ...parameters,\n type: 'object',\n properties: { [INTENT_ARG]: { ...INTENT_PROPERTY }, ...existingProps },\n };\n}\n\n/**\n * Coerces tool-call args to an object, parsing a stringified JSON object\n * (some providers deliver args as a string). Returns undefined otherwise.\n */\nfunction coerceArgsObject(args: unknown): Record<string, unknown> | undefined {\n if (typeof args === 'object' && args !== null && !Array.isArray(args)) {\n return args as Record<string, unknown>;\n }\n if (typeof args === 'string' && args.trim().startsWith('{')) {\n try {\n const parsed = JSON.parse(args) as unknown;\n if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Reads the model-authored intent from tool-call args (handles stringified\n * args). Returns undefined when absent, empty, or not a string.\n */\nexport function readIntent(args: unknown): string | undefined {\n const value = coerceArgsObject(args)?.[INTENT_ARG];\n if (typeof value !== 'string') {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\n/**\n * Returns the args without the `intent` key so downstream consumers that did\n * not declare it never receive it. Parses stringified JSON object args;\n * returns the value unchanged when the key is absent.\n */\nexport function stripIntent(args: unknown): unknown {\n const obj = coerceArgsObject(args);\n if (!obj || !(INTENT_ARG in obj)) {\n return args;\n }\n const { [INTENT_ARG]: _omit, ...rest } = obj;\n return rest;\n}\n\n/**\n * Resolves the settled label for a call from its model-authored `intent` and\n * the tool's result fields, in precedence order:\n *\n * 1. `outcome` — full replacement authored by the tool.\n * 2. `outcome_patch` — first occurrence of `from` in the intent replaced\n * with `to` (case-sensitive); no-op when `from` is absent or empty.\n * 3. Otherwise the intent is returned UNCHANGED.\n *\n * There is deliberately no mechanical present-progressive→past-tense rewrite.\n * Such a transform can only be a closed list of English verbs, which makes it\n * wrong in three ways at once: it never fires for the non-English labels this\n * feature expects (the model answers in the user's language), it fires for\n * some sibling calls and not others inside one group — \"Searched…\" beside\n * \"Recording…\" — and it quietly enumerates a vocabulary in a feature whose\n * premise is that the sentence is free-form. Completion is conveyed by UI\n * state (the shimmer stopping, the icon settling), which is language-neutral\n * and always consistent; a tool that wants past tense says so explicitly via\n * `outcome` or `outcome_patch`.\n *\n * Returns undefined when there is neither an intent nor an outcome, so\n * callers fall back to their default label. Pure and dependency-free — host\n * UIs needing identical logic can import or mirror it.\n */\nexport function applyOutcome(\n intent: string | undefined,\n result?: { outcome?: string; outcome_patch?: OutcomePatch },\n): string | undefined {\n const outcome = result?.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return outcome;\n }\n if (intent == null || intent === '') {\n return undefined;\n }\n const patch = result?.outcome_patch;\n if (patch != null && patch.from !== '' && intent.includes(patch.from)) {\n /** Replacement callback keeps `to` verbatim — a direct string second\n * argument would interpret `$&`/`$'`-style tokens in tool-authored\n * text (e.g. labels derived from shell syntax). */\n return intent.replace(patch.from, () => patch.to);\n }\n return intent;\n}\n\n/**\n * Hard cap on an emitted outcome label. The label is a single progress line\n * in UI chrome; a tool that derives it from data (or a malformed patch)\n * must not be able to inflate completion events or persisted parts.\n */\nconst MAX_OUTCOME_CHARS = 256;\n\nfunction boundOutcomeLabel(label: string | undefined): string | undefined {\n if (label == null) {\n return undefined;\n }\n const singleLine = label.replace(/\\s+/g, ' ').trim();\n if (singleLine === '') {\n return undefined;\n }\n if (singleLine.length <= MAX_OUTCOME_CHARS) {\n return singleLine;\n }\n return `${singleLine.slice(0, MAX_OUTCOME_CHARS - 1)}…`;\n}\n\n/**\n * Resolves the settled label to emit on a completion event: only when the\n * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined\n * otherwise, so the wire never carries a label the host already has — a bare\n * intent needs no settled form, because it is displayed unchanged and the UI\n * conveys completion through its own state. Hosts must NOT rewrite it (see\n * {@link applyOutcome} for why a tense transform is deliberately absent). The\n * result is collapsed to a bounded single line before emission.\n *\n * For failed calls (`isError`), only tool-AUTHORED text may label the call:\n * an explicit `outcome`, or a patch whose `from` actually matches the intent.\n * An unmatched patch resolves to undefined rather than silently reusing the\n * in-flight intent, so a failure is never labelled as though it succeeded.\n */\nexport function resolveToolOutcome(\n args: unknown,\n fields?: { outcome?: string; outcome_patch?: OutcomePatch } | null,\n options?: { isError?: boolean },\n): string | undefined {\n if (fields == null || (fields.outcome == null && fields.outcome_patch == null)) {\n return undefined;\n }\n if (options?.isError !== true) {\n return boundOutcomeLabel(applyOutcome(readIntent(args), fields));\n }\n const outcome = fields.outcome;\n if (typeof outcome === 'string' && outcome.trim() !== '') {\n return boundOutcomeLabel(outcome);\n }\n const intent = readIntent(args);\n const patch = fields.outcome_patch;\n if (\n intent != null &&\n patch != null &&\n patch.from !== '' &&\n intent.includes(patch.from)\n ) {\n return boundOutcomeLabel(intent.replace(patch.from, () => patch.to));\n }\n return undefined;\n}\n\n/**\n * Reads the outcome fields off a tool-execution result: the typed\n * `outcome`/`outcome_patch` fields when present, else the artifact channel\n * (see {@link readOutcomeFields}) — so a `content_and_artifact` tool authors\n * its label the same way on the direct and event-driven paths.\n */\nexport function outcomeFieldsFromResult(result: {\n outcome?: string;\n outcome_patch?: OutcomePatch;\n artifact?: unknown;\n}): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (result.outcome != null || result.outcome_patch != null) {\n return result;\n }\n return readOutcomeFields(result.artifact);\n}\n\n/**\n * Extracts validated `outcome`/`outcome_patch` fields from an arbitrary\n * value — the artifact channel through which an in-process\n * `content_and_artifact` tool authors its settled label. Returns undefined\n * when neither field is usable.\n */\nexport function readOutcomeFields(\n source: unknown,\n): { outcome?: string; outcome_patch?: OutcomePatch } | undefined {\n if (source == null || typeof source !== 'object' || Array.isArray(source)) {\n return undefined;\n }\n const record = source as Record<string, unknown>;\n const outcome =\n typeof record.outcome === 'string' && record.outcome.trim() !== ''\n ? record.outcome\n : undefined;\n let outcome_patch: OutcomePatch | undefined;\n const rawPatch = record.outcome_patch;\n if (rawPatch != null && typeof rawPatch === 'object' && !Array.isArray(rawPatch)) {\n const patch = rawPatch as Record<string, unknown>;\n if (typeof patch.from === 'string' && typeof patch.to === 'string') {\n outcome_patch = { from: patch.from, to: patch.to };\n }\n }\n if (outcome == null && outcome_patch == null) {\n return undefined;\n }\n return { outcome, outcome_patch };\n}\n"],"mappings":";;AAwBA,MAAa,aAAa;;;;;;;;;;;;AAa1B,MAAa,sBAAsB;;;;;;;;;;;AAYnC,MAAa,qBACX,GAAG,oBAAoB;;;;;;;;AAYzB,MAAa,kBAAkC,OAAO,OAAuB;CAC3E,MAAM;CACN,aAAa;AACf,CAAC;;;;;;;AAQD,SAAgB,sBAAsB,UAA4B;CAChE,IAAI,YAAY,QAAQ,OAAO,aAAa,UAC1C,OAAO;CAET,MAAM,SAAS;CACf,OACE,OAAO,SAAS,YAChB,OAAO,OAAO,gBAAgB,YAC9B,OAAO,YAAY,WAAA,+BAA8B;AAErD;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,cAAc,YAAiE;CAC7F,MAAM,QAAQ,YAAY;CAC1B,IAAI,cAAc,QAAQ,SAAS,QAAQ,CAAC,sBAAsB,MAAA,SAAiB,GACjF,OAAO;CAET,MAAM,GAAG,aAAa,OAAO,GAAG,SAAS;CACzC,MAAM,OAAuB;EAC3B,GAAI;EACJ,YAAY;CACd;CACA,IAAI,WAAW,YAAY,MAAM;EAC/B,MAAM,WAAW,WAAW,SAAS,QAAQ,QAAQ,QAAQ,UAAU;EACvE,IAAI,SAAS,SAAS,GACpB,KAAK,WAAW;OAEhB,OAAO,KAAK;CAEhB;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,WAAW,YAA6C;CACtE,MAAM,gBAAgB,YAAY,cAAc,CAAC;CACjD,IAAA,YAAkB,eAChB,OAAO;CAET,OAAO;EACL,GAAG;EACH,MAAM;EACN,YAAY;IAAG,aAAa,EAAE,GAAG,gBAAgB;GAAG,GAAG;EAAc;CACvE;AACF;;;;;AAMA,SAAS,iBAAiB,MAAoD;CAC5E,IAAI,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/tools";
|
|
|
24
24
|
*
|
|
25
25
|
* A caught provider or processing failure is reported through `data.error`
|
|
26
26
|
* while the tool still returns NORMALLY, so that case must author its own
|
|
27
|
-
* label: the `ToolMessage` carries success status,
|
|
28
|
-
*
|
|
29
|
-
* a failed search as
|
|
27
|
+
* label: the `ToolMessage` carries success status, so without an authored
|
|
28
|
+
* outcome the in-flight intent ("Searching…") would stand as the settled
|
|
29
|
+
* label and present a failed search as an ordinary one.
|
|
30
30
|
*
|
|
31
|
-
* Returns undefined for a genuine zero-result search, leaving the
|
|
32
|
-
*
|
|
31
|
+
* Returns undefined for a genuine zero-result search, leaving the
|
|
32
|
+
* model-authored intent to stand unchanged as the label.
|
|
33
33
|
*/
|
|
34
34
|
function resolveSearchOutcome(data, query) {
|
|
35
35
|
if (data.error != null && data.error !== "") return `Search failed for "${query}"`;
|