illuma-agents 1.0.17 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +3 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +18 -9
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +5 -3
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +10 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs +7 -8
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +17 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +11 -6
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +2 -2
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +2 -1
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +2 -2
- package/dist/cjs/messages/tools.cjs.map +1 -1
- package/dist/cjs/stream.cjs +29 -16
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/BrowserTools.cjs +473 -0
- package/dist/cjs/tools/BrowserTools.cjs.map +1 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +209 -47
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +1 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/search/search.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +3 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/utils/contextAnalytics.cjs +7 -5
- package/dist/cjs/utils/contextAnalytics.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/cjs/utils/toonFormat.cjs +42 -12
- package/dist/cjs/utils/toonFormat.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +3 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +18 -9
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +5 -3
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +10 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs +7 -8
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +11 -6
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +2 -2
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +2 -1
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +2 -2
- package/dist/esm/messages/tools.mjs.map +1 -1
- package/dist/esm/stream.mjs +29 -16
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/BrowserTools.mjs +458 -0
- package/dist/esm/tools/BrowserTools.mjs.map +1 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +208 -48
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +1 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/search/search.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +3 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/utils/contextAnalytics.mjs +7 -5
- package/dist/esm/utils/contextAnalytics.mjs.map +1 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/esm/utils/toonFormat.mjs +42 -12
- package/dist/esm/utils/toonFormat.mjs.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/tools/BrowserTools.d.ts +244 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +19 -0
- package/dist/types/types/tools.d.ts +3 -1
- package/package.json +6 -2
- package/src/agents/AgentContext.ts +28 -20
- package/src/graphs/Graph.ts +76 -37
- package/src/index.ts +1 -0
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +495 -473
- package/src/llm/bedrock/index.ts +47 -35
- package/src/llm/openrouter/index.ts +11 -1
- package/src/llm/vertexai/index.ts +9 -10
- package/src/messages/cache.ts +104 -55
- package/src/messages/core.ts +5 -3
- package/src/messages/format.ts +6 -2
- package/src/messages/tools.ts +2 -2
- package/src/scripts/simple.ts +1 -1
- package/src/specs/emergency-prune.test.ts +407 -355
- package/src/stream.ts +28 -20
- package/src/tools/BrowserTools.test.ts +528 -0
- package/src/tools/BrowserTools.ts +582 -0
- package/src/tools/ProgrammaticToolCalling.ts +246 -52
- package/src/tools/ToolNode.ts +4 -4
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +155 -0
- package/src/tools/search/jina-reranker.test.ts +32 -28
- package/src/tools/search/search.ts +3 -1
- package/src/tools/search/tool.ts +16 -7
- package/src/types/tools.ts +3 -1
- package/src/utils/contextAnalytics.ts +103 -95
- package/src/utils/llmConfig.ts +8 -1
- package/src/utils/run.ts +5 -4
- package/src/utils/toonFormat.ts +475 -437
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toonFormat.cjs","sources":["../../../src/utils/toonFormat.ts"],"sourcesContent":["/**\r\n * TOON Format Utility\r\n * \r\n * Provides JSON to TOON conversion for token-efficient encoding.\r\n * TOON format can reduce token count by 30-60% for JSON data.\r\n * \r\n * Uses the official @toon-format/toon library when available.\r\n */\r\n\r\n// Dynamic import holder for the TOON library (ESM)\r\nlet toonEncode: ((data: unknown) => string) | null = null;\r\nlet toonLoadAttempted = false;\r\nlet toonLoadPromise: Promise<boolean> | null = null;\r\n\r\n/**\r\n * Lazily loads the TOON library\r\n * Tries both ESM dynamic import and CommonJS require for compatibility\r\n */\r\nasync function loadToonLibrary(): Promise<boolean> {\r\n if (toonLoadAttempted) return toonEncode !== null;\r\n toonLoadAttempted = true;\r\n\r\n // Try ESM dynamic import first\r\n try {\r\n const mod = await import('@toon-format/toon');\r\n toonEncode = mod.encode;\r\n return true;\r\n } catch {\r\n // ESM import failed, try CommonJS require\r\n try {\r\n // eslint-disable-next-line @typescript-eslint/no-require-imports\r\n const mod = require('@toon-format/toon');\r\n toonEncode = mod.encode;\r\n return true;\r\n } catch {\r\n // Library not available - that's OK, we'll return original content\r\n return false;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Ensures the TOON library is loaded. Call this before using jsonToToon in tests.\r\n */\r\nexport async function ensureToonLoaded(): Promise<boolean> {\r\n if (!toonLoadPromise) {\r\n toonLoadPromise = loadToonLibrary();\r\n }\r\n return toonLoadPromise;\r\n}\r\n\r\n// Start loading immediately\r\nensureToonLoaded();\r\n\r\n/**\r\n * Check if a string appears to be in TOON format.\r\n * TOON format characteristics:\r\n * - Uses key: value syntax (like YAML)\r\n * - Uses array notation like [3] or {fields}\r\n * - Does NOT start with { or [\r\n * - Often has patterns like \"name[N]:\" or \"name{fields}:\"\r\n * \r\n * @param str - String to check\r\n * @returns true if string appears to be TOON format\r\n */\r\nexport function isToonFormat(str: string): boolean {\r\n if (typeof str !== 'string' || str.length === 0) return false;\r\n \r\n const trimmed = str.trim();\r\n \r\n // TOON doesn't start with JSON brackets\r\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) return false;\r\n \r\n // Check for TOON-specific patterns:\r\n // 1. Key-value with colon (but not URL-like patterns)\r\n // 2. Array notation like \"items[3]:\" or \"data[10]:\"\r\n // 3. Object schema notation like \"items{id,name}:\"\r\n const toonPatterns = [\r\n /^\\w+:$/m, // Simple key: at start of line\r\n /^\\w+\\[\\d+\\]:/m, // Array notation: items[3]:\r\n /^\\w+\\{[^}]+\\}:/m, // Schema notation: items{id,name}:\r\n /^\\w+\\[\\d+\\]\\{[^}]+\\}:/m, // Combined: items[3]{id,name}:\r\n ];\r\n \r\n // Must match at least one TOON pattern\r\n const hasToonPattern = toonPatterns.some(pattern => pattern.test(trimmed));\r\n \r\n // Additional check: TOON typically has multiple lines with consistent indentation\r\n const lines = trimmed.split('\\n').filter(l => l.trim());\r\n const hasMultipleKeyValueLines = lines.filter(l => /^\\s*\\w+.*:/.test(l)).length >= 2;\r\n \r\n return hasToonPattern || hasMultipleKeyValueLines;\r\n}\r\n\r\n/**\r\n * Extract the first valid JSON object or array from a string.\r\n * Handles pure JSON or JSON embedded in text (e.g., tool responses).\r\n * \r\n * @param str - The string to extract JSON from\r\n * @returns Object with found status, parsed JSON, and indices\r\n */\r\nexport function extractFirstJson(str: string): {\r\n found: boolean;\r\n parsed: unknown;\r\n startIndex: number;\r\n endIndex: number;\r\n} {\r\n if (typeof str !== 'string' || str.length === 0) {\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n }\r\n\r\n // Find the first { or [ character\r\n const objStart = str.indexOf('{');\r\n const arrStart = str.indexOf('[');\r\n\r\n if (objStart === -1 && arrStart === -1) {\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n }\r\n\r\n let startIndex: number;\r\n if (objStart === -1) {\r\n startIndex = arrStart;\r\n } else if (arrStart === -1) {\r\n startIndex = objStart;\r\n } else {\r\n startIndex = Math.min(objStart, arrStart);\r\n }\r\n\r\n // Find the matching closing bracket using a stack-based approach\r\n // Properly handle strings to avoid counting brackets inside strings\r\n let depth = 0;\r\n let inString = false;\r\n let escapeNext = false;\r\n\r\n for (let i = startIndex; i < str.length; i++) {\r\n const char = str[i];\r\n\r\n if (escapeNext) {\r\n escapeNext = false;\r\n continue;\r\n }\r\n\r\n if (char === '\\\\' && inString) {\r\n escapeNext = true;\r\n continue;\r\n }\r\n\r\n if (char === '\"') {\r\n inString = !inString;\r\n continue;\r\n }\r\n\r\n if (inString) continue;\r\n\r\n if (char === '{' || char === '[') depth++;\r\n if (char === '}' || char === ']') depth--;\r\n\r\n if (depth === 0) {\r\n // Found matching bracket, try to parse\r\n const jsonStr = str.substring(startIndex, i + 1);\r\n try {\r\n const parsed = JSON.parse(jsonStr);\r\n return { found: true, parsed, startIndex, endIndex: i };\r\n } catch {\r\n // Not valid JSON at this bracket level, continue searching\r\n // Reset and look for the next JSON start after this position\r\n const nextResult = extractFirstJson(str.substring(i + 1));\r\n if (nextResult.found) {\r\n return {\r\n found: true,\r\n parsed: nextResult.parsed,\r\n startIndex: i + 1 + nextResult.startIndex,\r\n endIndex: i + 1 + nextResult.endIndex,\r\n };\r\n }\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n }\r\n }\r\n }\r\n\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n}\r\n\r\n/**\r\n * Convert JSON content to TOON format for token efficiency.\r\n * Extracts JSON from string if embedded, converts to TOON.\r\n * Returns original string if:\r\n * - Already in TOON format\r\n * - Not JSON\r\n * - TOON conversion fails or is larger\r\n * \r\n * @param str - The string containing JSON to convert\r\n * @returns Object with conversion status, result, and reduction percentage\r\n */\r\nexport function jsonToToon(str: string): {\r\n converted: boolean;\r\n result: string;\r\n reduction: number;\r\n alreadyToon?: boolean;\r\n error?: string;\r\n} {\r\n if (!toonEncode || typeof str !== 'string') {\r\n return { converted: false, result: str, reduction: 0, error: !toonEncode ? 'TOON library not loaded' : undefined };\r\n }\r\n\r\n // Check if already in TOON format - skip conversion\r\n if (isToonFormat(str)) {\r\n return { converted: false, result: str, reduction: 0, alreadyToon: true };\r\n }\r\n\r\n try {\r\n const { found, parsed, startIndex, endIndex } = extractFirstJson(str);\r\n\r\n if (!found || !parsed) {\r\n return { converted: false, result: str, reduction: 0, error: 'No JSON found in content' };\r\n }\r\n\r\n // Check if this JSON structure would benefit from TOON\r\n // Text-heavy content (emails, documents) won't compress well\r\n if (!isToonBeneficial(parsed)) {\r\n return { converted: false, result: str, reduction: 0, error: 'Content is text-heavy (>70% string values), TOON not beneficial' };\r\n }\r\n\r\n const toonResult = toonEncode(parsed);\r\n \r\n // Preserve text before and after the JSON block\r\n const textBefore = str.substring(0, startIndex);\r\n const textAfter = str.substring(endIndex + 1);\r\n \r\n // Build the full result: textBefore + TOON + textAfter\r\n const fullResult = textBefore + toonResult + textAfter;\r\n\r\n if (fullResult.length < str.length) {\r\n const reduction = Math.round(((str.length - fullResult.length) / str.length) * 100);\r\n return { converted: true, result: fullResult, reduction };\r\n } else {\r\n // TOON output was larger or same size - not beneficial\r\n return { converted: false, result: str, reduction: 0, error: `TOON output not smaller (${fullResult.length} >= ${str.length})` };\r\n }\r\n } catch (err) {\r\n // TOON encoding or extraction failed - log error for debugging\r\n const errorMsg = err instanceof Error ? err.message : String(err);\r\n return { converted: false, result: str, reduction: 0, error: `TOON conversion error: ${errorMsg}` };\r\n }\r\n}\r\n\r\n/**\r\n * Check if TOON library is loaded and available\r\n */\r\nexport function isToonAvailable(): boolean {\r\n return toonEncode !== null;\r\n}\r\n\r\n/**\r\n * Result of processing tool output\r\n */\r\nexport interface ProcessToolOutputResult {\r\n /** The processed content string */\r\n content: string;\r\n /** Whether TOON conversion was applied */\r\n toonConverted: boolean;\r\n /** Whether content was truncated */\r\n truncated: boolean;\r\n /** Percentage reduction from TOON (0 if not converted) */\r\n reduction: number;\r\n /** Whether input was already in TOON format */\r\n alreadyToon: boolean;\r\n /** Original content length */\r\n originalLength: number;\r\n /** Estimated original tokens (~4 chars per token) */\r\n originalTokens: number;\r\n /** Final content length */\r\n finalLength: number;\r\n /** Estimated final tokens */\r\n finalTokens: number;\r\n /** Error message if TOON conversion failed (for debugging) */\r\n toonError?: string;\r\n}\r\n\r\n/**\r\n * Options for processing tool output\r\n */\r\nexport interface ProcessToolOutputOptions {\r\n /** Maximum output length in characters (default: 100000) */\r\n maxLength?: number;\r\n /** Whether to apply TOON conversion (default: true) */\r\n enableToon?: boolean;\r\n /** Minimum content size to attempt TOON conversion (default: 1000) */\r\n minSizeForToon?: number;\r\n /** Minimum reduction % to accept TOON result (default: 10) */\r\n minReductionPercent?: number;\r\n}\r\n\r\n/**\r\n * Analyze JSON structure to determine if TOON conversion would be beneficial.\r\n * Text-heavy content (emails, documents) doesn't compress well with TOON.\r\n * Structured data (API responses, metadata) compresses much better.\r\n * \r\n * @param parsed - Parsed JSON object\r\n * @returns true if TOON conversion is likely beneficial\r\n */\r\nfunction isToonBeneficial(parsed: unknown): boolean {\r\n if (!parsed || typeof parsed !== 'object') return false;\r\n \r\n const jsonStr = JSON.stringify(parsed);\r\n const totalLength = jsonStr.length;\r\n \r\n // Count characters in string values (text content)\r\n let textContentLength = 0;\r\n \r\n function countTextContent(obj: unknown): void {\r\n if (typeof obj === 'string') {\r\n // Count string length (this is text content that TOON can't compress)\r\n textContentLength += obj.length;\r\n } else if (Array.isArray(obj)) {\r\n obj.forEach(countTextContent);\r\n } else if (obj && typeof obj === 'object') {\r\n Object.values(obj).forEach(countTextContent);\r\n }\r\n }\r\n \r\n countTextContent(parsed);\r\n \r\n // Calculate ratio of text content to total JSON\r\n const textRatio = textContentLength / totalLength;\r\n \r\n // If more than 70% is text content, TOON won't help much\r\n // TOON compresses structure (field names, brackets), not text\r\n return textRatio < 0.7;\r\n}\r\n\r\n/**\r\n * Process tool output: apply TOON conversion if beneficial, then truncate if needed.\r\n * This is the main entry point for processing any tool output (regular or MCP).\r\n * \r\n * Flow:\r\n * 1. Check if already TOON format → skip conversion\r\n * 2. Try TOON conversion if content is JSON and large enough\r\n * 3. Truncate if still exceeds maxLength (with smart break points)\r\n * \r\n * @param content - The tool output content\r\n * @param options - Processing options\r\n * @returns Processed content and metadata\r\n */\r\nexport function processToolOutput(\r\n content: string,\r\n options: ProcessToolOutputOptions = {}\r\n): ProcessToolOutputResult {\r\n const { \r\n maxLength = 100000, \r\n enableToon = true,\r\n minSizeForToon = 1000,\r\n minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial\r\n } = options;\r\n\r\n const originalLength = content.length;\r\n const originalTokens = Math.ceil(originalLength / 4);\r\n \r\n let result = content;\r\n let toonConverted = false;\r\n let alreadyToon = false;\r\n let reduction = 0;\r\n let truncated = false;\r\n let toonError: string | undefined;\r\n\r\n // Step 1: Check if already TOON format\r\n if (isToonFormat(content)) {\r\n alreadyToon = true;\r\n }\r\n // Step 2: Apply TOON conversion if enabled and content is large enough\r\n else if (enableToon && content.length > minSizeForToon) {\r\n const toonResult = jsonToToon(content);\r\n if (toonResult.alreadyToon) {\r\n alreadyToon = true;\r\n } else if (toonResult.converted && toonResult.reduction >= minReductionPercent) {\r\n result = toonResult.result;\r\n toonConverted = true;\r\n reduction = toonResult.reduction;\r\n } else if (toonResult.error) {\r\n // Track error for debugging\r\n toonError = toonResult.error;\r\n } else if (toonResult.converted && toonResult.reduction < minReductionPercent) {\r\n // TOON converted but reduction was too small to be worth it\r\n toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;\r\n } else if (!toonResult.converted) {\r\n // Conversion failed without explicit error - investigate\r\n toonError = toonResult.error || 'TOON conversion returned false with no error';\r\n }\r\n }\r\n\r\n // Step 3: Truncate if still too long (with smart break points)\r\n if (result.length > maxLength) {\r\n let truncatedStr = result.substring(0, maxLength);\r\n \r\n // Try to find a clean break point\r\n if (toonConverted || alreadyToon) {\r\n // For TOON format, break at newline for cleaner output\r\n const lastNewline = truncatedStr.lastIndexOf('\\n');\r\n if (lastNewline > maxLength * 0.7) {\r\n truncatedStr = truncatedStr.substring(0, lastNewline);\r\n }\r\n } else {\r\n // For JSON, try to find a clean JSON break point\r\n const lastCompleteItem = truncatedStr.lastIndexOf('},');\r\n const lastArrayItem = truncatedStr.lastIndexOf('],');\r\n const breakPoint = Math.max(lastCompleteItem, lastArrayItem);\r\n if (breakPoint > maxLength * 0.5) {\r\n truncatedStr = truncatedStr.substring(0, breakPoint + 1);\r\n }\r\n }\r\n \r\n // Build truncation message\r\n const truncationInfo = toonConverted\r\n ? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +\r\n `Still exceeds ${maxLength.toLocaleString()} char limit.`\r\n : `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;\r\n \r\n result = truncatedStr + `\\n\\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;\r\n truncated = true;\r\n }\r\n\r\n const finalLength = result.length;\r\n const finalTokens = Math.ceil(finalLength / 4);\r\n\r\n return { \r\n content: result, \r\n toonConverted, \r\n truncated, \r\n reduction, \r\n alreadyToon,\r\n originalLength,\r\n originalTokens,\r\n finalLength,\r\n finalTokens,\r\n toonError,\r\n };\r\n}\r\n"],"names":[],"mappings":";;AAAA;;;;;;;AAOG;AAEH;AACA,IAAI,UAAU,GAAuC,IAAI;AACzD,IAAI,iBAAiB,GAAG,KAAK;AAC7B,IAAI,eAAe,GAA4B,IAAI;AAEnD;;;AAGG;AACH,eAAe,eAAe,GAAA;AAC5B,IAAA,IAAI,iBAAiB;QAAE,OAAO,UAAU,KAAK,IAAI;IACjD,iBAAiB,GAAG,IAAI;;AAGxB,IAAA,IAAI;AACF,QAAA,MAAM,GAAG,GAAG,MAAM,OAAO,mBAAmB,CAAC;AAC7C,QAAA,UAAU,GAAG,GAAG,CAAC,MAAM;AACvB,QAAA,OAAO,IAAI;;AACX,IAAA,MAAM;;AAEN,QAAA,IAAI;;AAEF,YAAA,MAAM,GAAG,GAAG,OAAO,CAAC,mBAAmB,CAAC;AACxC,YAAA,UAAU,GAAG,GAAG,CAAC,MAAM;AACvB,YAAA,OAAO,IAAI;;AACX,QAAA,MAAM;;AAEN,YAAA,OAAO,KAAK;;;AAGlB;AAEA;;AAEG;AACI,eAAe,gBAAgB,GAAA;IACpC,IAAI,CAAC,eAAe,EAAE;QACpB,eAAe,GAAG,eAAe,EAAE;;AAErC,IAAA,OAAO,eAAe;AACxB;AAEA;AACA,gBAAgB,EA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AI;;AAGlB,IAAA,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM;IACjC,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC;IAE9C,OAAO;AACL,QAAA,OAAO,EAAE,MAAM;QACf,aAAa;QACb,SAAS;QACT,SAAS;QACT,WAAW;QACX,cAAc;QACd,cAAc;QACd,WAAW;QACX,WAAW;QACX,SAAS;KACV;AACH;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"toonFormat.cjs","sources":["../../../src/utils/toonFormat.ts"],"sourcesContent":["/**\n * TOON Format Utility\n *\n * Provides JSON to TOON conversion for token-efficient encoding.\n * TOON format can reduce token count by 30-60% for JSON data.\n *\n * Uses the official @toon-format/toon library when available.\n */\n\n// Dynamic import holder for the TOON library (ESM)\nlet toonEncode: ((data: unknown) => string) | null = null;\nlet toonLoadAttempted = false;\nlet toonLoadPromise: Promise<boolean> | null = null;\n\n/**\n * Lazily loads the TOON library\n * Tries both ESM dynamic import and CommonJS require for compatibility\n */\nasync function loadToonLibrary(): Promise<boolean> {\n if (toonLoadAttempted) return toonEncode !== null;\n toonLoadAttempted = true;\n\n // Try ESM dynamic import first\n try {\n const mod = await import('@toon-format/toon');\n toonEncode = mod.encode;\n return true;\n } catch {\n // ESM import failed, try CommonJS require\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require('@toon-format/toon');\n toonEncode = mod.encode;\n return true;\n } catch {\n // Library not available - that's OK, we'll return original content\n return false;\n }\n }\n}\n\n/**\n * Ensures the TOON library is loaded. Call this before using jsonToToon in tests.\n */\nexport async function ensureToonLoaded(): Promise<boolean> {\n if (!toonLoadPromise) {\n toonLoadPromise = loadToonLibrary();\n }\n return toonLoadPromise;\n}\n\n// Start loading immediately\nensureToonLoaded();\n\n/**\n * Check if a string appears to be in TOON format.\n * TOON format characteristics:\n * - Uses key: value syntax (like YAML)\n * - Uses array notation like [3] or {fields}\n * - Does NOT start with { or [\n * - Often has patterns like \"name[N]:\" or \"name{fields}:\"\n *\n * @param str - String to check\n * @returns true if string appears to be TOON format\n */\nexport function isToonFormat(str: string): boolean {\n if (typeof str !== 'string' || str.length === 0) return false;\n\n const trimmed = str.trim();\n\n // TOON doesn't start with JSON brackets\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) return false;\n\n // Check for TOON-specific patterns:\n // 1. Key-value with colon (but not URL-like patterns)\n // 2. Array notation like \"items[3]:\" or \"data[10]:\"\n // 3. Object schema notation like \"items{id,name}:\"\n const toonPatterns = [\n /^\\w+:$/m, // Simple key: at start of line\n /^\\w+\\[\\d+\\]:/m, // Array notation: items[3]:\n /^\\w+\\{[^}]+\\}:/m, // Schema notation: items{id,name}:\n /^\\w+\\[\\d+\\]\\{[^}]+\\}:/m, // Combined: items[3]{id,name}:\n ];\n\n // Must match at least one TOON pattern\n const hasToonPattern = toonPatterns.some((pattern) => pattern.test(trimmed));\n\n // Additional check: TOON typically has multiple lines with consistent indentation\n const lines = trimmed.split('\\n').filter((l) => l.trim());\n const hasMultipleKeyValueLines =\n lines.filter((l) => /^\\s*\\w+.*:/.test(l)).length >= 2;\n\n return hasToonPattern || hasMultipleKeyValueLines;\n}\n\n/**\n * Extract the first valid JSON object or array from a string.\n * Handles pure JSON or JSON embedded in text (e.g., tool responses).\n *\n * @param str - The string to extract JSON from\n * @returns Object with found status, parsed JSON, and indices\n */\nexport function extractFirstJson(str: string): {\n found: boolean;\n parsed: unknown;\n startIndex: number;\n endIndex: number;\n} {\n if (typeof str !== 'string' || str.length === 0) {\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\n }\n\n // Find the first { or [ character\n const objStart = str.indexOf('{');\n const arrStart = str.indexOf('[');\n\n if (objStart === -1 && arrStart === -1) {\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\n }\n\n let startIndex: number;\n if (objStart === -1) {\n startIndex = arrStart;\n } else if (arrStart === -1) {\n startIndex = objStart;\n } else {\n startIndex = Math.min(objStart, arrStart);\n }\n\n // Find the matching closing bracket using a stack-based approach\n // Properly handle strings to avoid counting brackets inside strings\n let depth = 0;\n let inString = false;\n let escapeNext = false;\n\n for (let i = startIndex; i < str.length; i++) {\n const char = str[i];\n\n if (escapeNext) {\n escapeNext = false;\n continue;\n }\n\n if (char === '\\\\' && inString) {\n escapeNext = true;\n continue;\n }\n\n if (char === '\"') {\n inString = !inString;\n continue;\n }\n\n if (inString) continue;\n\n if (char === '{' || char === '[') depth++;\n if (char === '}' || char === ']') depth--;\n\n if (depth === 0) {\n // Found matching bracket, try to parse\n const jsonStr = str.substring(startIndex, i + 1);\n try {\n const parsed = JSON.parse(jsonStr);\n return { found: true, parsed, startIndex, endIndex: i };\n } catch {\n // Not valid JSON at this bracket level, continue searching\n // Reset and look for the next JSON start after this position\n const nextResult = extractFirstJson(str.substring(i + 1));\n if (nextResult.found) {\n return {\n found: true,\n parsed: nextResult.parsed,\n startIndex: i + 1 + nextResult.startIndex,\n endIndex: i + 1 + nextResult.endIndex,\n };\n }\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\n }\n }\n }\n\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\n}\n\n/**\n * Convert JSON content to TOON format for token efficiency.\n * Extracts JSON from string if embedded, converts to TOON.\n * Returns original string if:\n * - Already in TOON format\n * - Not JSON\n * - TOON conversion fails or is larger\n *\n * @param str - The string containing JSON to convert\n * @returns Object with conversion status, result, and reduction percentage\n */\nexport function jsonToToon(str: string): {\n converted: boolean;\n result: string;\n reduction: number;\n alreadyToon?: boolean;\n error?: string;\n} {\n if (!toonEncode || typeof str !== 'string') {\n return {\n converted: false,\n result: str,\n reduction: 0,\n error: !toonEncode ? 'TOON library not loaded' : undefined,\n };\n }\n\n // Check if already in TOON format - skip conversion\n if (isToonFormat(str)) {\n return { converted: false, result: str, reduction: 0, alreadyToon: true };\n }\n\n try {\n const { found, parsed, startIndex, endIndex } = extractFirstJson(str);\n\n if (!found || !parsed) {\n return {\n converted: false,\n result: str,\n reduction: 0,\n error: 'No JSON found in content',\n };\n }\n\n // Check if this JSON structure would benefit from TOON\n // Text-heavy content (emails, documents) won't compress well\n if (!isToonBeneficial(parsed)) {\n return {\n converted: false,\n result: str,\n reduction: 0,\n error:\n 'Content is text-heavy (>70% string values), TOON not beneficial',\n };\n }\n\n const toonResult = toonEncode(parsed);\n\n // Preserve text before and after the JSON block\n const textBefore = str.substring(0, startIndex);\n const textAfter = str.substring(endIndex + 1);\n\n // Build the full result: textBefore + TOON + textAfter\n const fullResult = textBefore + toonResult + textAfter;\n\n if (fullResult.length < str.length) {\n const reduction = Math.round(\n ((str.length - fullResult.length) / str.length) * 100\n );\n return { converted: true, result: fullResult, reduction };\n } else {\n // TOON output was larger or same size - not beneficial\n return {\n converted: false,\n result: str,\n reduction: 0,\n error: `TOON output not smaller (${fullResult.length} >= ${str.length})`,\n };\n }\n } catch (err) {\n // TOON encoding or extraction failed - log error for debugging\n const errorMsg = err instanceof Error ? err.message : String(err);\n return {\n converted: false,\n result: str,\n reduction: 0,\n error: `TOON conversion error: ${errorMsg}`,\n };\n }\n}\n\n/**\n * Check if TOON library is loaded and available\n */\nexport function isToonAvailable(): boolean {\n return toonEncode !== null;\n}\n\n/**\n * Result of processing tool output\n */\nexport interface ProcessToolOutputResult {\n /** The processed content string */\n content: string;\n /** Whether TOON conversion was applied */\n toonConverted: boolean;\n /** Whether content was truncated */\n truncated: boolean;\n /** Percentage reduction from TOON (0 if not converted) */\n reduction: number;\n /** Whether input was already in TOON format */\n alreadyToon: boolean;\n /** Original content length */\n originalLength: number;\n /** Estimated original tokens (~4 chars per token) */\n originalTokens: number;\n /** Final content length */\n finalLength: number;\n /** Estimated final tokens */\n finalTokens: number;\n /** Error message if TOON conversion failed (for debugging) */\n toonError?: string;\n}\n\n/**\n * Options for processing tool output\n */\nexport interface ProcessToolOutputOptions {\n /** Maximum output length in characters (default: 100000) */\n maxLength?: number;\n /** Whether to apply TOON conversion (default: true) */\n enableToon?: boolean;\n /** Minimum content size to attempt TOON conversion (default: 1000) */\n minSizeForToon?: number;\n /** Minimum reduction % to accept TOON result (default: 10) */\n minReductionPercent?: number;\n}\n\n/**\n * Analyze JSON structure to determine if TOON conversion would be beneficial.\n * Text-heavy content (emails, documents) doesn't compress well with TOON.\n * Structured data (API responses, metadata) compresses much better.\n *\n * @param parsed - Parsed JSON object\n * @returns true if TOON conversion is likely beneficial\n */\nfunction isToonBeneficial(parsed: unknown): boolean {\n if (!parsed || typeof parsed !== 'object') return false;\n\n const jsonStr = JSON.stringify(parsed);\n const totalLength = jsonStr.length;\n\n // Count characters in string values (text content)\n let textContentLength = 0;\n\n function countTextContent(obj: unknown): void {\n if (typeof obj === 'string') {\n // Count string length (this is text content that TOON can't compress)\n textContentLength += obj.length;\n } else if (Array.isArray(obj)) {\n obj.forEach(countTextContent);\n } else if (obj && typeof obj === 'object') {\n Object.values(obj).forEach(countTextContent);\n }\n }\n\n countTextContent(parsed);\n\n // Calculate ratio of text content to total JSON\n const textRatio = textContentLength / totalLength;\n\n // If more than 70% is text content, TOON won't help much\n // TOON compresses structure (field names, brackets), not text\n return textRatio < 0.7;\n}\n\n/**\n * Process tool output: apply TOON conversion if beneficial, then truncate if needed.\n * This is the main entry point for processing any tool output (regular or MCP).\n *\n * Flow:\n * 1. Check if already TOON format → skip conversion\n * 2. Try TOON conversion if content is JSON and large enough\n * 3. Truncate if still exceeds maxLength (with smart break points)\n *\n * @param content - The tool output content\n * @param options - Processing options\n * @returns Processed content and metadata\n */\nexport function processToolOutput(\n content: string,\n options: ProcessToolOutputOptions = {}\n): ProcessToolOutputResult {\n const {\n maxLength = 100000,\n enableToon = true,\n minSizeForToon = 1000,\n minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial\n } = options;\n\n const originalLength = content.length;\n const originalTokens = Math.ceil(originalLength / 4);\n\n let result = content;\n let toonConverted = false;\n let alreadyToon = false;\n let reduction = 0;\n let truncated = false;\n let toonError: string | undefined;\n\n // Step 1: Check if already TOON format\n if (isToonFormat(content)) {\n alreadyToon = true;\n }\n // Step 2: Apply TOON conversion if enabled and content is large enough\n else if (enableToon && content.length > minSizeForToon) {\n const toonResult = jsonToToon(content);\n if (toonResult.alreadyToon) {\n alreadyToon = true;\n } else if (\n toonResult.converted &&\n toonResult.reduction >= minReductionPercent\n ) {\n result = toonResult.result;\n toonConverted = true;\n reduction = toonResult.reduction;\n } else if (toonResult.error) {\n // Track error for debugging\n toonError = toonResult.error;\n } else if (\n toonResult.converted &&\n toonResult.reduction < minReductionPercent\n ) {\n // TOON converted but reduction was too small to be worth it\n toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;\n } else if (!toonResult.converted) {\n // Conversion failed without explicit error - investigate\n toonError =\n toonResult.error || 'TOON conversion returned false with no error';\n }\n }\n\n // Step 3: Truncate if still too long (with smart break points)\n if (result.length > maxLength) {\n let truncatedStr = result.substring(0, maxLength);\n\n // Try to find a clean break point\n if (toonConverted || alreadyToon) {\n // For TOON format, break at newline for cleaner output\n const lastNewline = truncatedStr.lastIndexOf('\\n');\n if (lastNewline > maxLength * 0.7) {\n truncatedStr = truncatedStr.substring(0, lastNewline);\n }\n } else {\n // For JSON, try to find a clean JSON break point\n const lastCompleteItem = truncatedStr.lastIndexOf('},');\n const lastArrayItem = truncatedStr.lastIndexOf('],');\n const breakPoint = Math.max(lastCompleteItem, lastArrayItem);\n if (breakPoint > maxLength * 0.5) {\n truncatedStr = truncatedStr.substring(0, breakPoint + 1);\n }\n }\n\n // Build truncation message\n const truncationInfo = toonConverted\n ? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +\n `Still exceeds ${maxLength.toLocaleString()} char limit.`\n : `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;\n\n result =\n truncatedStr +\n `\\n\\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;\n truncated = true;\n }\n\n const finalLength = result.length;\n const finalTokens = Math.ceil(finalLength / 4);\n\n return {\n content: result,\n toonConverted,\n truncated,\n reduction,\n alreadyToon,\n originalLength,\n originalTokens,\n finalLength,\n finalTokens,\n toonError,\n };\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;AAOG;AAEH;AACA,IAAI,UAAU,GAAuC,IAAI;AACzD,IAAI,iBAAiB,GAAG,KAAK;AAC7B,IAAI,eAAe,GAA4B,IAAI;AAEnD;;;AAGG;AACH,eAAe,eAAe,GAAA;AAC5B,IAAA,IAAI,iBAAiB;QAAE,OAAO,UAAU,KAAK,IAAI;IACjD,iBAAiB,GAAG,IAAI;;AAGxB,IAAA,IAAI;AACF,QAAA,MAAM,GAAG,GAAG,MAAM,OAAO,mBAAmB,CAAC;AAC7C,QAAA,UAAU,GAAG,GAAG,CAAC,MAAM;AACvB,QAAA,OAAO,IAAI;;AACX,IAAA,MAAM;;AAEN,QAAA,IAAI;;AAEF,YAAA,MAAM,GAAG,GAAG,OAAO,CAAC,mBAAmB,CAAC;AACxC,YAAA,UAAU,GAAG,GAAG,CAAC,MAAM;AACvB,YAAA,OAAO,IAAI;;AACX,QAAA,MAAM;;AAEN,YAAA,OAAO,KAAK;;;AAGlB;AAEA;;AAEG;AACI,eAAe,gBAAgB,GAAA;IACpC,IAAI,CAAC,eAAe,EAAE;QACpB,eAAe,GAAG,eAAe,EAAE;;AAErC,IAAA,OAAO,eAAe;AACxB;AAEA;AACA,gBAAgB,EAAE;AAElB;;;;;;;;;;AAUG;AACG,SAAU,YAAY,CAAC,GAAW,EAAA;IACtC,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,KAAK;AAE7D,IAAA,MAAM,OAAO,GAAG,GAAG,CAAC,IAAI,EAAE;;AAG1B,IAAA,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;AAAE,QAAA,OAAO,KAAK;;;;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d,WAAW;QACX,WAAW;QACX,SAAS;KACV;AACH;;;;;;;;;"}
|
|
@@ -282,7 +282,9 @@ class AgentContext {
|
|
|
282
282
|
if (this.provider === Providers.BEDROCK) {
|
|
283
283
|
const bedrockOptions = this.clientOptions;
|
|
284
284
|
const modelId = bedrockOptions?.model?.toLowerCase() ?? '';
|
|
285
|
-
const supportsCaching = modelId.includes('claude') ||
|
|
285
|
+
const supportsCaching = modelId.includes('claude') ||
|
|
286
|
+
modelId.includes('anthropic') ||
|
|
287
|
+
modelId.includes('nova');
|
|
286
288
|
if (bedrockOptions?.promptCache === true && supportsCaching) {
|
|
287
289
|
finalInstructions = {
|
|
288
290
|
content: [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n dynamicContext,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n dynamicContext,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is NOT included in the system message to preserve cache.\n * Instead, it's injected as a user message at the start of the conversation.\n */\n dynamicContext?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Detailed per-tool token breakdown for admin tracking */\n private toolsDetail: Array<{ name: string; tokens: number }> = [];\n /** Total tool tokens (sum of all toolsDetail) */\n private toolTokensTotal: number = 0;\n /** Per-prompt token breakdown for detailed admin reporting */\n private promptBreakdown: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n } = {\n branding: 0,\n toolRouting: 0,\n agentInstructions: 0,\n mcpInstructions: 0,\n artifacts: 0,\n memory: 0,\n };\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n dynamicContext,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n dynamicContext?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n this.dynamicContext = dynamicContext;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n */\n private buildInstructionsString(): string {\n let result = this.instructions ?? '';\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n result = result\n ? `${result}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n result = result\n ? `${result}${programmaticToolsDoc}`\n : programmaticToolsDoc;\n }\n\n return result;\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching (Direct API)\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n // Handle Bedrock prompt caching (Converse API)\n // Adds cachePoint block after text content for system message caching\n // NOTE: Both Claude and Nova models support cachePoint in system and messages\n // (Nova does NOT support cachePoint in tools - that check is in bedrock/index.ts)\n if (this.provider === Providers.BEDROCK) {\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicInput\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching = modelId.includes('claude') || modelId.includes('anthropic') || modelId.includes('nova');\n\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n \n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n },\n {\n cachePoint: { type: 'default' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.toolsDetail = [];\n this.toolTokensTotal = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n * Also tracks per-tool token breakdown for admin reporting\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n this.toolsDetail = []; // Reset per-tool breakdown\n \n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n const toolName = (genericTool.name as string) || 'unknown';\n const tokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n \n // Track per-tool breakdown\n this.toolsDetail.push({ name: toolName, tokens });\n toolTokens += tokens;\n }\n }\n }\n\n // Store total tool tokens for breakdown reporting\n this.toolTokensTotal = toolTokens;\n \n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Set the per-prompt token breakdown for detailed admin tracking.\n * Called by the client after assembling all prompt components.\n * @param breakdown - Object with token counts per prompt component\n */\n setPromptBreakdown(breakdown: {\n branding?: number;\n toolRouting?: number;\n agentInstructions?: number;\n mcpInstructions?: number;\n artifacts?: number;\n memory?: number;\n }): void {\n if (breakdown.branding !== undefined) this.promptBreakdown.branding = breakdown.branding;\n if (breakdown.toolRouting !== undefined) this.promptBreakdown.toolRouting = breakdown.toolRouting;\n if (breakdown.agentInstructions !== undefined) this.promptBreakdown.agentInstructions = breakdown.agentInstructions;\n if (breakdown.mcpInstructions !== undefined) this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;\n if (breakdown.artifacts !== undefined) this.promptBreakdown.artifacts = breakdown.artifacts;\n if (breakdown.memory !== undefined) this.promptBreakdown.memory = breakdown.memory;\n }\n\n /**\n * Get a detailed breakdown of context tokens for admin reporting.\n * This provides visibility into what's consuming the input token budget.\n * @returns ContextBreakdown object with per-component token counts\n */\n getContextBreakdown(): {\n instructions: number;\n artifacts: number;\n tools: number;\n toolCount: number;\n toolContext: number;\n total: number;\n toolsDetail: Array<{ name: string; tokens: number }>;\n toolContextDetail: Array<{ name: string; tokens: number }>;\n prompts?: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n };\n } {\n // Calculate sum of prompt components\n const promptsTotal = \n this.promptBreakdown.branding +\n this.promptBreakdown.toolRouting +\n this.promptBreakdown.agentInstructions +\n this.promptBreakdown.mcpInstructions +\n this.promptBreakdown.artifacts +\n this.promptBreakdown.memory;\n\n return {\n // System message tokens (instructions + additional_instructions)\n instructions: this.systemMessageTokens,\n // Artifacts prompt tokens\n artifacts: this.promptBreakdown.artifacts,\n // Total tool definition tokens\n tools: this.toolTokensTotal,\n // Number of tools\n toolCount: this.toolsDetail.length,\n // Tool context/usage instructions (currently embedded in system message)\n toolContext: 0,\n // Total tracked context tokens\n total: this.instructionTokens,\n // Per-tool token breakdown\n toolsDetail: [...this.toolsDetail],\n // Tool context detail (currently not tracked separately)\n toolContextDetail: [],\n // Per-prompt breakdown (only include if any prompts were tracked)\n prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,\n };\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAChB,cAAc,GACf,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,YAAY;YACZ,OAAO;AACP,YAAA,iBAAiB,EAAE,CAAC;YACpB,YAAY;YACZ,gBAAgB;YAChB,cAAc;AACf,SAAA,CAAC;QAEF,IAAI,YAAY,EAAE;;;;YAIhB,YAAY,CAAC,wBAAwB,EAAE;AAEvC,YAAA,MAAM,QAAQ,GAAG,kBAAkB,IAAI,EAAE;AACzC,YAAA,YAAY,CAAC,kBAAkB,GAAG,QAAQ;YAC1C,YAAY,CAAC,uBAAuB,GAAG;iBACpC,0BAA0B,CAAC,YAAY;iBACvC,IAAI,CAAC,MAAK;;AAET,gBAAA,YAAY,CAAC,8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AEvE,SAAC,CAAC;AAEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
|
|
1
|
+
{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n dynamicContext,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n dynamicContext,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is NOT included in the system message to preserve cache.\n * Instead, it's injected as a user message at the start of the conversation.\n */\n dynamicContext?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Detailed per-tool token breakdown for admin tracking */\n private toolsDetail: Array<{ name: string; tokens: number }> = [];\n /** Total tool tokens (sum of all toolsDetail) */\n private toolTokensTotal: number = 0;\n /** Per-prompt token breakdown for detailed admin reporting */\n private promptBreakdown: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n } = {\n branding: 0,\n toolRouting: 0,\n agentInstructions: 0,\n mcpInstructions: 0,\n artifacts: 0,\n memory: 0,\n };\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n dynamicContext,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n dynamicContext?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n this.dynamicContext = dynamicContext;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n */\n private buildInstructionsString(): string {\n let result = this.instructions ?? '';\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n result = result\n ? `${result}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n result = result\n ? `${result}${programmaticToolsDoc}`\n : programmaticToolsDoc;\n }\n\n return result;\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching (Direct API)\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n // Handle Bedrock prompt caching (Converse API)\n // Adds cachePoint block after text content for system message caching\n // NOTE: Both Claude and Nova models support cachePoint in system and messages\n // (Nova does NOT support cachePoint in tools - that check is in bedrock/index.ts)\n if (this.provider === Providers.BEDROCK) {\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicInput\n | undefined;\n const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n const supportsCaching =\n modelId.includes('claude') ||\n modelId.includes('anthropic') ||\n modelId.includes('nova');\n\n if (bedrockOptions?.promptCache === true && supportsCaching) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n },\n {\n cachePoint: { type: 'default' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.toolsDetail = [];\n this.toolTokensTotal = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n * Also tracks per-tool token breakdown for admin reporting\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n this.toolsDetail = []; // Reset per-tool breakdown\n\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n const toolName = (genericTool.name as string) || 'unknown';\n const tokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n\n // Track per-tool breakdown\n this.toolsDetail.push({ name: toolName, tokens });\n toolTokens += tokens;\n }\n }\n }\n\n // Store total tool tokens for breakdown reporting\n this.toolTokensTotal = toolTokens;\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Set the per-prompt token breakdown for detailed admin tracking.\n * Called by the client after assembling all prompt components.\n * @param breakdown - Object with token counts per prompt component\n */\n setPromptBreakdown(breakdown: {\n branding?: number;\n toolRouting?: number;\n agentInstructions?: number;\n mcpInstructions?: number;\n artifacts?: number;\n memory?: number;\n }): void {\n if (breakdown.branding !== undefined)\n this.promptBreakdown.branding = breakdown.branding;\n if (breakdown.toolRouting !== undefined)\n this.promptBreakdown.toolRouting = breakdown.toolRouting;\n if (breakdown.agentInstructions !== undefined)\n this.promptBreakdown.agentInstructions = breakdown.agentInstructions;\n if (breakdown.mcpInstructions !== undefined)\n this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;\n if (breakdown.artifacts !== undefined)\n this.promptBreakdown.artifacts = breakdown.artifacts;\n if (breakdown.memory !== undefined)\n this.promptBreakdown.memory = breakdown.memory;\n }\n\n /**\n * Get a detailed breakdown of context tokens for admin reporting.\n * This provides visibility into what's consuming the input token budget.\n * @returns ContextBreakdown object with per-component token counts\n */\n getContextBreakdown(): {\n instructions: number;\n artifacts: number;\n tools: number;\n toolCount: number;\n toolContext: number;\n total: number;\n toolsDetail: Array<{ name: string; tokens: number }>;\n toolContextDetail: Array<{ name: string; tokens: number }>;\n prompts?: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n };\n } {\n // Calculate sum of prompt components\n const promptsTotal =\n this.promptBreakdown.branding +\n this.promptBreakdown.toolRouting +\n this.promptBreakdown.agentInstructions +\n this.promptBreakdown.mcpInstructions +\n this.promptBreakdown.artifacts +\n this.promptBreakdown.memory;\n\n return {\n // System message tokens (instructions + additional_instructions)\n instructions: this.systemMessageTokens,\n // Artifacts prompt tokens\n artifacts: this.promptBreakdown.artifacts,\n // Total tool definition tokens\n tools: this.toolTokensTotal,\n // Number of tools\n toolCount: this.toolsDetail.length,\n // Tool context/usage instructions (currently embedded in system message)\n toolContext: 0,\n // Total tracked context tokens\n total: this.instructionTokens,\n // Per-tool token breakdown\n toolsDetail: [...this.toolsDetail],\n // Tool context detail (currently not tracked separately)\n toolContextDetail: [],\n // Per-prompt breakdown (only include if any prompts were tracked)\n prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,\n };\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CA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AAA,IAAI,CAAC,mBAAmB,GAAG,IAAI;;AAEjC,QAAA,OAAO,iBAAiB;;AAG1B;;;;;;AAMG;IACH,kBAAkB,GAAA;QAChB,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;YACrC,OAAO,IAAI,CAAC,KAAK;;QAGnB,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAI;AAChD,YAAA,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,EAAE;gBACrB,OAAO,IAAI,CAAC;;AAGd,YAAA,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;YACjD,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,IAAI,CAAC;;;YAId,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;;gBAE3C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,gBAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;;;YAI1C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,YAAA,QACE,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI;AAEvE,SAAC,CAAC;AAEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
|
|
@@ -574,7 +574,9 @@ class StandardGraph extends Graph {
|
|
|
574
574
|
// Both Claude and Nova models support cachePoint in system and messages
|
|
575
575
|
// (Llama, Titan, and other models do NOT support cachePoint)
|
|
576
576
|
const modelId = bedrockOptions?.model?.toLowerCase() ?? '';
|
|
577
|
-
const supportsCaching = modelId.includes('claude') ||
|
|
577
|
+
const supportsCaching = modelId.includes('claude') ||
|
|
578
|
+
modelId.includes('anthropic') ||
|
|
579
|
+
modelId.includes('nova');
|
|
578
580
|
if (bedrockOptions?.promptCache === true && supportsCaching) {
|
|
579
581
|
finalMessages = addBedrockCacheControl(finalMessages);
|
|
580
582
|
}
|
|
@@ -600,9 +602,12 @@ class StandardGraph extends Graph {
|
|
|
600
602
|
}
|
|
601
603
|
// Get model info for analytics
|
|
602
604
|
const bedrockOpts = agentContext.clientOptions;
|
|
603
|
-
const modelId = bedrockOpts?.model ||
|
|
605
|
+
const modelId = bedrockOpts?.model ||
|
|
606
|
+
agentContext.clientOptions
|
|
607
|
+
?.modelName;
|
|
604
608
|
const thinkingConfig = bedrockOpts?.additionalModelRequestFields?.['thinking'] ||
|
|
605
|
-
agentContext.clientOptions
|
|
609
|
+
agentContext.clientOptions
|
|
610
|
+
?.thinking;
|
|
606
611
|
// Build and emit context analytics for traces
|
|
607
612
|
const contextAnalytics = buildContextAnalytics(finalMessages, {
|
|
608
613
|
tokenCounter: agentContext.tokenCounter,
|
|
@@ -629,7 +634,7 @@ class StandardGraph extends Graph {
|
|
|
629
634
|
}
|
|
630
635
|
catch (primaryError) {
|
|
631
636
|
// Check if this is a "input too long" error from Bedrock/Anthropic
|
|
632
|
-
const errorMessage = primaryError
|
|
637
|
+
const errorMessage = primaryError.message.toLowerCase() ?? '';
|
|
633
638
|
const isInputTooLongError = errorMessage.includes('too long') ||
|
|
634
639
|
errorMessage.includes('input is too long') ||
|
|
635
640
|
errorMessage.includes('context length') ||
|
|
@@ -643,7 +648,8 @@ class StandardGraph extends Graph {
|
|
|
643
648
|
hasPruneMessages: !!agentContext.pruneMessages,
|
|
644
649
|
hasTokenCounter: !!agentContext.tokenCounter,
|
|
645
650
|
maxContextTokens: agentContext.maxContextTokens,
|
|
646
|
-
indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)
|
|
651
|
+
indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)
|
|
652
|
+
.length,
|
|
647
653
|
});
|
|
648
654
|
}
|
|
649
655
|
// If input too long and we have pruning capability OR tokenCounter, retry with progressively more aggressive pruning
|
|
@@ -717,9 +723,12 @@ If I seem to be missing something we discussed earlier, just give me a quick rem
|
|
|
717
723
|
if (agentContext.provider === Providers.BEDROCK) {
|
|
718
724
|
const bedrockOptions = agentContext.clientOptions;
|
|
719
725
|
const modelId = bedrockOptions?.model?.toLowerCase() ?? '';
|
|
720
|
-
const supportsCaching = modelId.includes('claude') ||
|
|
726
|
+
const supportsCaching = modelId.includes('claude') ||
|
|
727
|
+
modelId.includes('anthropic') ||
|
|
728
|
+
modelId.includes('nova');
|
|
721
729
|
if (bedrockOptions?.promptCache === true && supportsCaching) {
|
|
722
|
-
retryMessages =
|
|
730
|
+
retryMessages =
|
|
731
|
+
addBedrockCacheControl(retryMessages);
|
|
723
732
|
}
|
|
724
733
|
}
|
|
725
734
|
try {
|
|
@@ -733,7 +742,7 @@ If I seem to be missing something we discussed earlier, just give me a quick rem
|
|
|
733
742
|
console.info(`[Graph] ✅ Retry successful at ${reductionFactor * 100}% with ${reducedMessages.length} messages (reduced from ${finalMessages.length})`);
|
|
734
743
|
}
|
|
735
744
|
catch (retryError) {
|
|
736
|
-
const retryErrorMsg = retryError
|
|
745
|
+
const retryErrorMsg = retryError.message.toLowerCase() ?? '';
|
|
737
746
|
const stillTooLong = retryErrorMsg.includes('too long') ||
|
|
738
747
|
retryErrorMsg.includes('context length') ||
|
|
739
748
|
retryErrorMsg.includes('validationexception');
|
|
@@ -741,7 +750,7 @@ If I seem to be missing something we discussed earlier, just give me a quick rem
|
|
|
741
750
|
console.warn(`[Graph] Still too long at ${reductionFactor * 100}%, trying more aggressive pruning...`);
|
|
742
751
|
}
|
|
743
752
|
else {
|
|
744
|
-
console.error(`[Graph] Retry at ${reductionFactor * 100}% failed:`, retryError
|
|
753
|
+
console.error(`[Graph] Retry at ${reductionFactor * 100}% failed:`, retryError.message);
|
|
745
754
|
}
|
|
746
755
|
}
|
|
747
756
|
}
|