@librechat/agents 3.2.41 → 3.2.42

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.
Files changed (37) hide show
  1. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  2. package/dist/cjs/graphs/Graph.cjs +4 -1
  3. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  4. package/dist/cjs/llm/bedrock/index.cjs +9 -1
  5. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  6. package/dist/cjs/main.cjs +4 -0
  7. package/dist/cjs/messages/cache.cjs +21 -0
  8. package/dist/cjs/messages/cache.cjs.map +1 -1
  9. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs +2 -2
  10. package/dist/cjs/tools/cloudflare/CloudflareProgrammaticToolCalling.cjs.map +1 -1
  11. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs +87 -7
  12. package/dist/cjs/tools/cloudflare/CloudflareSandboxExecutionEngine.cjs.map +1 -1
  13. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  14. package/dist/esm/graphs/Graph.mjs +5 -2
  15. package/dist/esm/graphs/Graph.mjs.map +1 -1
  16. package/dist/esm/llm/bedrock/index.mjs +10 -2
  17. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  18. package/dist/esm/main.mjs +3 -3
  19. package/dist/esm/messages/cache.mjs +21 -1
  20. package/dist/esm/messages/cache.mjs.map +1 -1
  21. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs +3 -3
  22. package/dist/esm/tools/cloudflare/CloudflareProgrammaticToolCalling.mjs.map +1 -1
  23. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs +85 -8
  24. package/dist/esm/tools/cloudflare/CloudflareSandboxExecutionEngine.mjs.map +1 -1
  25. package/dist/types/llm/bedrock/index.d.ts +7 -0
  26. package/dist/types/messages/cache.d.ts +17 -0
  27. package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +44 -0
  28. package/package.json +1 -1
  29. package/src/agents/AgentContext.ts +2 -0
  30. package/src/graphs/Graph.ts +17 -5
  31. package/src/llm/bedrock/index.ts +18 -2
  32. package/src/llm/bedrock/llm.spec.ts +97 -0
  33. package/src/messages/cache.test.ts +31 -0
  34. package/src/messages/cache.ts +25 -0
  35. package/src/tools/__tests__/CloudflareSandboxExecution.test.ts +131 -0
  36. package/src/tools/cloudflare/CloudflareProgrammaticToolCalling.ts +7 -2
  37. package/src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts +165 -9
@@ -1 +1 @@
1
- {"version":3,"file":"CloudflareSandboxExecutionEngine.cjs","names":["stream","PassThrough","EventEmitter","LOCAL_SPAWN_TIMEOUT_MS","validateBashCommand"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts"],"sourcesContent":["import { PassThrough } from 'stream';\nimport { posix as path } from 'path';\nimport { EventEmitter } from 'events';\nimport type { WriteFileOptions, MakeDirectoryOptions, Stats } from 'fs';\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\nimport type { FileHandle } from 'fs/promises';\nimport type { WorkspaceFS, ReaddirEntry } from '@/tools/local/workspaceFS';\nimport type * as t from '@/types';\nimport {\n LOCAL_SPAWN_TIMEOUT_MS,\n validateBashCommand,\n} from '@/tools/local/LocalExecutionEngine';\n\nconst DEFAULT_WORKSPACE_ROOT = '/workspace';\nconst DEFAULT_TIMEOUT_MS = 60000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE =\n /\\b(?:rm\\s+-[^\\s]*[rf]|chmod\\s+-R|chown\\s+-R)\\b/;\n\ntype SpawnResult = {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n};\n\ntype RuntimeCommand = {\n fileName: string;\n source?: string;\n command: string;\n};\n\ntype SandboxRuntimeContext = {\n sandbox: t.CloudflareSandboxRuntime;\n workspaceRoot: string;\n env?: Record<string, string | undefined>;\n timeoutMs: number;\n maxOutputChars: number;\n shell: string;\n};\n\nconst sandboxFactoryCache = new WeakMap<\n t.CloudflareSandboxExecutionConfig,\n Promise<t.CloudflareSandboxRuntime>\n>();\n\nfunction normalizeWorkspaceRoot(workspaceRoot: string): string {\n const normalized = path.normalize(workspaceRoot);\n return normalized === '/' ? normalized : normalized.replace(/\\/+$/, '');\n}\n\nexport function getCloudflareWorkspaceRoot(\n config?: t.CloudflareSandboxExecutionConfig\n): string {\n return normalizeWorkspaceRoot(\n config?.workspaceRoot ?? DEFAULT_WORKSPACE_ROOT\n );\n}\n\nexport async function resolveCloudflareSandbox(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<t.CloudflareSandboxRuntime> {\n const sandbox = config.sandbox;\n if (typeof sandbox !== 'function') {\n return sandbox;\n }\n let cached = sandboxFactoryCache.get(config);\n if (cached == null) {\n cached = Promise.resolve()\n .then(() => sandbox())\n .catch((error: unknown) => {\n sandboxFactoryCache.delete(config);\n throw error;\n });\n sandboxFactoryCache.set(config, cached);\n }\n return cached;\n}\n\nasync function getRuntimeContext(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SandboxRuntimeContext> {\n return {\n sandbox: await resolveCloudflareSandbox(config),\n workspaceRoot: getCloudflareWorkspaceRoot(config),\n env: config.env,\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxOutputChars: config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS,\n shell: config.shell ?? 'bash',\n };\n}\n\nfunction toSandboxPath(filePath: string, workspaceRoot: string): string {\n const raw = filePath === '' ? '.' : filePath;\n const root = normalizeWorkspaceRoot(workspaceRoot);\n const resolved = raw.startsWith('/')\n ? path.normalize(raw)\n : path.resolve(root, raw);\n if (root === '/') {\n return resolved;\n }\n if (resolved === root || resolved.startsWith(`${root}/`)) {\n return resolved;\n }\n throw new Error(\n `Path is outside the Cloudflare sandbox workspace: ${filePath}`\n );\n}\n\nfunction quote(value: string): string {\n if (value === '') {\n return '\\'\\'';\n }\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n return `'${value.replace(/'/g, '\\'\\\\\\'\\'')}'`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\nfunction truncateOutput(value: string, maxChars: number): string {\n if (maxChars <= 0 || value.length <= maxChars) {\n return value;\n }\n const head = Math.max(Math.floor(maxChars / 2), 0);\n const tail = Math.max(maxChars - head, 0);\n return `${value.slice(0, head)}\\n...[truncated ${value.length - maxChars} chars]...\\n${value.slice(value.length - tail)}`;\n}\n\nasync function readStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nasync function normalizeReadFileContent(\n result: t.CloudflareSandboxReadFileResult\n): Promise<Buffer> {\n if (typeof result === 'string') {\n return Buffer.from(result, 'utf8');\n }\n if (Buffer.isBuffer(result)) {\n return result;\n }\n if (result instanceof Uint8Array) {\n return Buffer.from(result);\n }\n const content = result.content;\n if (typeof content === 'string') {\n if (result.encoding === 'base64') {\n return Buffer.from(content, 'base64');\n }\n return Buffer.from(content, 'utf8');\n }\n if (Buffer.isBuffer(content)) {\n return content;\n }\n if (content instanceof Uint8Array) {\n return Buffer.from(content);\n }\n return readStream(content);\n}\n\nfunction bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller): void {\n controller.enqueue(bytes);\n controller.close();\n },\n });\n}\n\nfunction normalizeWriteFileContent(content: string | Buffer | Uint8Array): {\n content: string | ReadableStream<Uint8Array>;\n options?: { encoding?: string };\n} {\n if (typeof content === 'string') {\n return { content, options: { encoding: 'utf8' } };\n }\n return { content: bytesToStream(content) };\n}\n\nfunction createStats(info: {\n size?: number;\n type?: t.CloudflareSandboxFileInfo['type'];\n}): Stats {\n const type = info.type ?? 'file';\n const now = new Date();\n return {\n size: info.size ?? 0,\n isFile: () => type === 'file',\n isDirectory: () => type === 'directory',\n isSymbolicLink: () => type === 'symlink',\n isBlockDevice: () => false,\n isCharacterDevice: () => false,\n isFIFO: () => false,\n isSocket: () => false,\n dev: 0,\n ino: 0,\n mode: 0,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 0,\n blocks: 0,\n atimeMs: now.getTime(),\n mtimeMs: now.getTime(),\n ctimeMs: now.getTime(),\n birthtimeMs: now.getTime(),\n atime: now,\n mtime: now,\n ctime: now,\n birthtime: now,\n } as Stats;\n}\n\nfunction normalizeFileList(\n result: t.CloudflareSandboxListFilesResult\n): t.CloudflareSandboxFileInfo[] {\n return Array.isArray(result) ? result : result.files;\n}\n\nfunction entryNameFor(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.name !== '') {\n return info.name.includes('/') ? path.basename(info.name) : info.name;\n }\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.basename(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.basename(info.relativePath);\n }\n return path.basename(parentPath);\n}\n\nfunction entryAbsolutePath(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.normalize(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.resolve(parentPath, info.relativePath);\n }\n return path.resolve(parentPath, info.name);\n}\n\nfunction createDirent(info: t.CloudflareSandboxFileInfo): ReaddirEntry {\n return {\n name: entryNameFor(info, ''),\n isFile: () => (info.type ?? 'file') === 'file',\n isDirectory: () => info.type === 'directory',\n isSymbolicLink: () => info.type === 'symlink',\n };\n}\n\nasync function findChildInfo(\n sandbox: t.CloudflareSandboxRuntime,\n filePath: string\n): Promise<t.CloudflareSandboxFileInfo | undefined> {\n const parent = path.dirname(filePath);\n const basename = path.basename(filePath);\n const entries = normalizeFileList(\n await sandbox.listFiles(parent, { includeHidden: true })\n );\n return entries.find((entry) => {\n const absolute = entryAbsolutePath(entry, parent);\n return absolute === filePath || entryNameFor(entry, parent) === basename;\n });\n}\n\nexport function createCloudflareWorkspaceFS(\n config: t.CloudflareSandboxExecutionConfig\n): WorkspaceFS {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n\n const fs: WorkspaceFS = {\n readFile: (async (filePath: string, encoding?: 'utf8') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved, encoding ? { encoding } : undefined)\n );\n return encoding != null ? buffer.toString(encoding) : buffer;\n }) as WorkspaceFS['readFile'],\n writeFile: async (\n filePath: string,\n content: string | Buffer,\n _options?: WriteFileOptions\n ) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const normalized = normalizeWriteFileContent(content);\n await sandbox.writeFile(resolved, normalized.content, normalized.options);\n },\n stat: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n if (resolved === workspaceRoot) {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n }\n const info = await findChildInfo(sandbox, resolved);\n if (info != null) {\n return createStats({ size: info.size, type: info.type });\n }\n try {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n } catch {\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return createStats({ size: buffer.length, type: 'file' });\n }\n },\n readdir: (async (filePath: string, options?: { withFileTypes: true }) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n if (options?.withFileTypes === true) {\n return entries.map(createDirent);\n }\n return entries.map((entry) => entryNameFor(entry, resolved));\n }) as WorkspaceFS['readdir'],\n mkdir: async (filePath: string, options?: MakeDirectoryOptions) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.mkdir(toSandboxPath(filePath, workspaceRoot), {\n recursive: options?.recursive,\n });\n },\n realpath: async (filePath: string) =>\n toSandboxPath(filePath, workspaceRoot),\n unlink: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.deleteFile(toSandboxPath(filePath, workspaceRoot));\n },\n open: async (filePath: string, _flags: 'r') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return {\n read: async (\n target: Buffer,\n offset: number,\n length: number,\n position: number\n ) => {\n const start = Math.max(position, 0);\n const slice = buffer.subarray(start, start + length);\n slice.copy(target, offset);\n return { bytesRead: slice.length, buffer: target };\n },\n close: async () => undefined,\n } as unknown as FileHandle;\n },\n };\n\n return fs;\n}\n\nfunction createCloudflareSpawn(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalSpawn {\n return (command, args, options) => {\n const stdout = new PassThrough();\n const stderr = new PassThrough();\n const child = new EventEmitter() as ChildProcessWithoutNullStreams;\n const abortController = new AbortController();\n const state = { closed: false };\n /** Read through a function so concurrent `closeOnce` mutation (via\n * `kill()`/abort during an `await`) isn't statically narrowed away. */\n const isClosed = (): boolean => state.closed;\n const closeOnce = (\n exitCode: number | null,\n signal: NodeJS.Signals | null\n ): void => {\n if (state.closed) {\n return;\n }\n state.closed = true;\n stdout.end();\n stderr.end();\n Object.assign(child, {\n exitCode,\n signalCode: signal,\n });\n child.emit('close', exitCode, signal);\n };\n Object.assign(child, {\n stdout,\n stderr,\n stdin: new PassThrough(),\n stdio: [null, stdout, stderr],\n killed: false,\n exitCode: null,\n signalCode: null,\n pid: undefined,\n kill: (signal: NodeJS.Signals = 'SIGTERM') => {\n Object.assign(child, { killed: true, signalCode: signal });\n abortController.abort();\n closeOnce(null, signal);\n return true;\n },\n });\n\n void (async (): Promise<void> => {\n const ctx = await getRuntimeContext(config);\n const rendered = [command, ...args].map(quote).join(' ');\n const spawnTimeoutMs = (\n options as {\n [LOCAL_SPAWN_TIMEOUT_MS]?: number;\n }\n )[LOCAL_SPAWN_TIMEOUT_MS];\n const timeoutMs =\n typeof spawnTimeoutMs === 'number' && Number.isFinite(spawnTimeoutMs)\n ? spawnTimeoutMs\n : ctx.timeoutMs;\n const timedCommand = withInSandboxTimeout(rendered, timeoutMs);\n const cwd =\n options.cwd == null ? ctx.workspaceRoot : options.cwd.toString();\n if (isClosed()) {\n return;\n }\n const execOptions: t.CloudflareSandboxExecOptions = {\n cwd,\n env: ctx.env,\n timeout: outerTimeoutMs(timeoutMs),\n };\n if (ctx.sandbox.supportsExecSignal === true) {\n execOptions.signal = abortController.signal;\n }\n try {\n const result = await ctx.sandbox.exec(timedCommand, execOptions);\n if (isClosed()) {\n return;\n }\n if (result.stdout) stdout.write(result.stdout);\n if (result.stderr) stderr.write(result.stderr);\n closeOnce(result.exitCode, null);\n } catch (error) {\n if (isClosed()) {\n return;\n }\n stderr.write((error as Error).message);\n closeOnce(1, null);\n }\n })();\n\n return child;\n };\n}\n\nexport function createCloudflareLocalExecutionConfig(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalExecutionConfig {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n return {\n cwd: workspaceRoot,\n workspace: { root: workspaceRoot },\n exec: {\n spawn: createCloudflareSpawn(config),\n fs: createCloudflareWorkspaceFS(config),\n sandboxed: true,\n },\n shell: config.shell ?? 'bash',\n timeoutMs: config.timeoutMs,\n maxOutputChars: config.maxOutputChars,\n env: config.env,\n includeCodingTools: config.includeCodingTools,\n compileCheck: config.compileCheck,\n readOnly: config.readOnly,\n allowDangerousCommands: config.allowDangerousCommands,\n bashAst: config.bashAst,\n fileCheckpointing: config.fileCheckpointing,\n maxReadBytes: config.maxReadBytes,\n attachReadAttachments: config.attachReadAttachments,\n maxAttachmentBytes: config.maxAttachmentBytes,\n postEditSyntaxCheck: config.postEditSyntaxCheck,\n };\n}\n\nexport async function validateCloudflareBashCommand(\n command: string,\n args: readonly string[],\n config: t.CloudflareSandboxExecutionConfig\n): Promise<void> {\n const localConfig = createCloudflareLocalExecutionConfig(config);\n const validation = await validateBashCommand(command, localConfig);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n\n if (\n args.length > 0 &&\n config.allowDangerousCommands !== true &&\n DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)\n ) {\n const offending = args.find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n throw new Error(\n `Command matches a destructive command pattern (protected target \"${offending}\" passed via positional arg).`\n );\n }\n }\n}\n\nexport async function executeCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig,\n args: readonly string[] = []\n): Promise<SpawnResult> {\n await validateCloudflareBashCommand(command, args, config);\n const ctx = await getRuntimeContext(config);\n const shellCommand =\n args.length > 0\n ? `${ctx.shell} -lc ${quote(command)} -- ${args.map(quote).join(' ')}`\n : `${ctx.shell} -lc ${quote(command)}`;\n const result = await ctx.sandbox.exec(\n withInSandboxTimeout(shellCommand, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n }\n );\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction runtimeForCode(\n lang: string,\n tempDir: string,\n code: string,\n args: string[] = [],\n shell = 'bash'\n): RuntimeCommand {\n const fileFor = (name: string): string => path.join(tempDir, name);\n const argText = args.map(quote).join(' ');\n switch (lang) {\n case 'py':\n case 'python':\n return {\n fileName: 'main.py',\n source: code,\n command: `python3 ${quote(fileFor('main.py'))} ${argText}`,\n };\n case 'js':\n case 'javascript':\n return {\n fileName: 'main.js',\n source: code,\n command: `node ${quote(fileFor('main.js'))} ${argText}`,\n };\n case 'ts':\n case 'typescript':\n return {\n fileName: 'main.ts',\n source: code,\n command: `npx --no-install tsx ${quote(fileFor('main.ts'))} ${argText}`,\n };\n case 'php':\n return {\n fileName: 'main.php',\n source: code,\n command: `php ${quote(fileFor('main.php'))} ${argText}`,\n };\n case 'go':\n return {\n fileName: 'main.go',\n source: code,\n command: `go run ${quote(fileFor('main.go'))} ${argText}`,\n };\n case 'rs':\n return {\n fileName: 'main.rs',\n source: code,\n command: `${shell} -lc ${quote(\n `rustc ${quote(fileFor('main.rs'))} -o ${quote(fileFor('main-rs'))} && ${quote(fileFor('main-rs'))} ${argText}`\n )}`,\n };\n case 'c':\n return {\n fileName: 'main.c',\n source: code,\n command: `${shell} -lc ${quote(\n `cc ${quote(fileFor('main.c'))} -o ${quote(fileFor('main-c'))} && ${quote(fileFor('main-c'))} ${argText}`\n )}`,\n };\n case 'cpp':\n return {\n fileName: 'main.cpp',\n source: code,\n command: `${shell} -lc ${quote(\n `c++ ${quote(fileFor('main.cpp'))} -o ${quote(fileFor('main-cpp'))} && ${quote(fileFor('main-cpp'))} ${argText}`\n )}`,\n };\n case 'java':\n return {\n fileName: 'Main.java',\n source: code,\n command: `${shell} -lc ${quote(\n `javac ${quote(fileFor('Main.java'))} && java -cp ${quote(tempDir)} Main ${argText}`\n )}`,\n };\n case 'r':\n return {\n fileName: 'main.R',\n source: code,\n command: `Rscript ${quote(fileFor('main.R'))} ${argText}`,\n };\n case 'd':\n return {\n fileName: 'main.d',\n source: code,\n command: `${shell} -lc ${quote(\n `dmd ${quote(fileFor('main.d'))} -of=${quote(fileFor('main-d'))} && ${quote(fileFor('main-d'))} ${argText}`\n )}`,\n };\n case 'f90':\n return {\n fileName: 'main.f90',\n source: code,\n command: `${shell} -lc ${quote(\n `gfortran ${quote(fileFor('main.f90'))} -o ${quote(fileFor('main-f90'))} && ${quote(fileFor('main-f90'))} ${argText}`\n )}`,\n };\n case 'bash':\n case 'sh':\n return {\n fileName: 'main.sh',\n source: code,\n command: `${shell} -lc ${quote(code)} -- ${argText}`,\n };\n default:\n throw new Error(`Unsupported Cloudflare sandbox runtime: ${lang}`);\n }\n}\n\nexport async function executeCloudflareCode(\n input: { lang: string; code: string; args?: string[] },\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SpawnResult> {\n if (input.lang === 'bash' || input.lang === 'sh') {\n return executeCloudflareBash(input.code, config, input.args ?? []);\n }\n const ctx = await getRuntimeContext(config);\n const id = globalThis.crypto.randomUUID();\n const tempDir = path.join(ctx.workspaceRoot, '.lc-exec', id);\n const runtime = runtimeForCode(\n input.lang,\n tempDir,\n input.code,\n input.args,\n ctx.shell\n );\n await ctx.sandbox.mkdir(tempDir, { recursive: true });\n if (runtime.source != null) {\n await ctx.sandbox.writeFile(\n path.join(tempDir, runtime.fileName),\n runtime.source,\n {\n encoding: 'utf8',\n }\n );\n }\n try {\n const result = await ctx.sandbox.exec(\n withInSandboxTimeout(runtime.command, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n }\n );\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n } finally {\n await ctx.sandbox\n .exec(`rm -rf ${quote(tempDir)}`, {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: 10000,\n })\n .catch(() => undefined);\n }\n}\n\nexport function formatCloudflareOutput(\n result: SpawnResult,\n cwd: string\n): string {\n let formatted = '';\n if (result.stdout !== '') {\n formatted += `stdout:\\n${result.stdout}\\n`;\n } else {\n formatted += 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n }\n if (result.stderr !== '') {\n formatted += `stderr:\\n${result.stderr}\\n`;\n }\n if (result.exitCode != null && result.exitCode !== 0) {\n formatted += `exit_code: ${result.exitCode}\\n`;\n }\n if (result.timedOut) {\n formatted += 'timed_out: true\\n';\n }\n formatted += `working_directory: ${cwd}`;\n return formatted.trim();\n}\n"],"mappings":";;;;;AAaA,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;AAChC,MAAM,+BACJ;AAwBF,MAAM,sCAAsB,IAAI,QAG9B;AAEF,SAAS,uBAAuB,eAA+B;CAC7D,MAAM,aAAa,KAAA,MAAK,UAAU,aAAa;CAC/C,OAAO,eAAe,MAAM,aAAa,WAAW,QAAQ,QAAQ,EAAE;AACxE;AAEA,SAAgB,2BACd,QACQ;CACR,OAAO,uBACL,QAAQ,iBAAiB,sBAC3B;AACF;AAEA,eAAsB,yBACpB,QACqC;CACrC,MAAM,UAAU,OAAO;CACvB,IAAI,OAAO,YAAY,YACrB,OAAO;CAET,IAAI,SAAS,oBAAoB,IAAI,MAAM;CAC3C,IAAI,UAAU,MAAM;EAClB,SAAS,QAAQ,QAAQ,CAAC,CACvB,WAAW,QAAQ,CAAC,CAAC,CACrB,OAAO,UAAmB;GACzB,oBAAoB,OAAO,MAAM;GACjC,MAAM;EACR,CAAC;EACH,oBAAoB,IAAI,QAAQ,MAAM;CACxC;CACA,OAAO;AACT;AAEA,eAAe,kBACb,QACgC;CAChC,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,OAAO,QAAQ,IAAI,cAAc;GACxD,QAAQ,eAAe,OAAO,QAAQ,IAAI,cAAc;GACxD,UAAU,OAAO;GACjB,UAAU,uBAAuB,OAAO,QAAQ;EAClD;CACF,UAAU;EACR,MAAM,IAAI,QACP,KAAK,UAAU,MAAM,OAAO,KAAK;GAChC,KAAK,IAAI;GACT,KAAK,IAAI;GACT,SAAS;EACX,CAAC,CAAC,CACD,YAAY,KAAA,CAAS;CAC1B;AACF;AAEA,SAAgB,uBACd,QACA,KACQ;CACR,IAAI,YAAY;CAChB,IAAI,OAAO,WAAW,IACpB,aAAa,YAAY,OAAO,OAAO;MAEvC,aAAa;CAEf,IAAI,OAAO,WAAW,IACpB,aAAa,YAAY,OAAO,OAAO;CAEzC,IAAI,OAAO,YAAY,QAAQ,OAAO,aAAa,GACjD,aAAa,cAAc,OAAO,SAAS;CAE7C,IAAI,OAAO,UACT,aAAa;CAEf,aAAa,sBAAsB;CACnC,OAAO,UAAU,KAAK;AACxB"}
1
+ {"version":3,"file":"CloudflareSandboxExecutionEngine.cjs","names":["stream","PassThrough","EventEmitter","LOCAL_SPAWN_TIMEOUT_MS","validateBashCommand"],"sources":["../../../../src/tools/cloudflare/CloudflareSandboxExecutionEngine.ts"],"sourcesContent":["import { PassThrough } from 'stream';\nimport { posix as path } from 'path';\nimport { EventEmitter } from 'events';\nimport type { WriteFileOptions, MakeDirectoryOptions, Stats } from 'fs';\nimport type { ChildProcessWithoutNullStreams } from 'child_process';\nimport type { FileHandle } from 'fs/promises';\nimport type { WorkspaceFS, ReaddirEntry } from '@/tools/local/workspaceFS';\nimport type * as t from '@/types';\nimport {\n LOCAL_SPAWN_TIMEOUT_MS,\n validateBashCommand,\n} from '@/tools/local/LocalExecutionEngine';\n\nconst DEFAULT_WORKSPACE_ROOT = '/workspace';\nconst DEFAULT_TIMEOUT_MS = 60000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 200000;\nconst PROTECTED_TARGET_ARG_RE = /^(?:\\/|~|\\$\\{?HOME\\}?|\\.)(?:\\/?\\.?\\*|\\/)?$/;\nconst DESTRUCTIVE_OP_IN_COMMAND_RE =\n /\\b(?:rm\\s+-[^\\s]*[rf]|chmod\\s+-R|chown\\s+-R)\\b/;\n\ntype SpawnResult = {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n};\n\ntype RuntimeCommand = {\n fileName: string;\n source?: string;\n command: string;\n};\n\ntype SandboxRuntimeContext = {\n sandbox: t.CloudflareSandboxRuntime;\n workspaceRoot: string;\n env?: Record<string, string | undefined>;\n timeoutMs: number;\n maxOutputChars: number;\n shell: string;\n};\n\nconst sandboxFactoryCache = new WeakMap<\n t.CloudflareSandboxExecutionConfig,\n Promise<t.CloudflareSandboxRuntime>\n>();\n\nfunction normalizeWorkspaceRoot(workspaceRoot: string): string {\n const normalized = path.normalize(workspaceRoot);\n return normalized === '/' ? normalized : normalized.replace(/\\/+$/, '');\n}\n\nexport function getCloudflareWorkspaceRoot(\n config?: t.CloudflareSandboxExecutionConfig\n): string {\n return normalizeWorkspaceRoot(\n config?.workspaceRoot ?? DEFAULT_WORKSPACE_ROOT\n );\n}\n\nexport async function resolveCloudflareSandbox(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<t.CloudflareSandboxRuntime> {\n const sandbox = config.sandbox;\n if (typeof sandbox !== 'function') {\n return sandbox;\n }\n let cached = sandboxFactoryCache.get(config);\n if (cached == null) {\n cached = Promise.resolve()\n .then(() => sandbox())\n .catch((error: unknown) => {\n sandboxFactoryCache.delete(config);\n throw error;\n });\n sandboxFactoryCache.set(config, cached);\n }\n return cached;\n}\n\nasync function getRuntimeContext(\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SandboxRuntimeContext> {\n return {\n sandbox: await resolveCloudflareSandbox(config),\n workspaceRoot: getCloudflareWorkspaceRoot(config),\n env: config.env,\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxOutputChars: config.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS,\n shell: config.shell ?? 'bash',\n };\n}\n\nfunction toSandboxPath(filePath: string, workspaceRoot: string): string {\n const raw = filePath === '' ? '.' : filePath;\n const root = normalizeWorkspaceRoot(workspaceRoot);\n const resolved = raw.startsWith('/')\n ? path.normalize(raw)\n : path.resolve(root, raw);\n if (root === '/') {\n return resolved;\n }\n if (resolved === root || resolved.startsWith(`${root}/`)) {\n return resolved;\n }\n throw new Error(\n `Path is outside the Cloudflare sandbox workspace: ${filePath}`\n );\n}\n\nfunction quote(value: string): string {\n if (value === '') {\n return '\\'\\'';\n }\n if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {\n return value;\n }\n return `'${value.replace(/'/g, '\\'\\\\\\'\\'')}'`;\n}\n\nfunction withInSandboxTimeout(command: string, timeoutMs: number): string {\n const timeoutSeconds = Math.max(1, Math.ceil(timeoutMs / 1000));\n return `timeout -k 2s ${timeoutSeconds}s ${command}`;\n}\n\nfunction outerTimeoutMs(timeoutMs: number): number {\n return timeoutMs + 5000;\n}\n\nfunction isInSandboxTimeoutExit(exitCode: number | null): boolean {\n return exitCode === 124 || exitCode === 137;\n}\n\n/**\n * Client-side backstop timeout for a `sandbox.exec()` await: a few seconds beyond\n * the exec's own `timeout` option, so a stalled exec that never honors `timeout`\n * still can't outlast this.\n */\nexport function clientExecTimeoutMs(timeoutMs: number): number {\n return outerTimeoutMs(timeoutMs) + 5000;\n}\n\n/**\n * Bound a `sandbox.exec()` await with a CLIENT-SIDE timeout.\n *\n * The native Cloudflare Sandbox Durable Object `exec()` is effectively\n * uncancellable from the host: `ExecOptions` has no `signal` (so\n * `supportsExecSignal` is false for the native transport), and its `timeout`\n * option is not reliably enforced when the container/RPC itself stalls — while\n * the in-sandbox `timeout(1)` wrapper only bounds a command that is actually\n * running. So a stalled exec (an unresponsive/cold container) otherwise hangs\n * until the host's run-level abort, burning the whole run budget on one tool\n * call. This race guarantees the host await settles within `timeoutMs`\n * regardless of the transport.\n *\n * On timeout the underlying `exec` promise may keep running in the DO (a\n * native-DO exec cannot be truly cancelled), so its late settlement is swallowed\n * to avoid an unhandled rejection.\n */\nexport async function withClientTimeout<T>(\n exec: Promise<T>,\n timeoutMs: number,\n label: string,\n options: {\n /**\n * Detach the backstop timer from the event loop. Use ONLY when something else\n * already settles the caller (e.g. the spawn path, where spawnLocalProcess's\n * own timer resolves the child). The awaited direct-exec paths must leave it\n * REF'd so the timeout is guaranteed to fire even if nothing else is pending.\n */\n unref?: boolean;\n /** Invoked when the client timeout fires — e.g. abort a signal-aware exec. */\n onTimeout?: () => void;\n } = {}\n): Promise<T> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return exec;\n }\n // Swallow a late rejection from the losing promise after the race settles.\n exec.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n exec,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n // Reject FIRST so this client-timeout message reliably wins the race;\n // only then abort a signal-aware exec, whose resulting AbortError must\n // not surface to the caller instead of the timeout.\n reject(\n new Error(\n `${label} exceeded ${timeoutMs}ms client-side timeout (sandbox exec did not return)`\n )\n );\n options.onTimeout?.();\n }, timeoutMs);\n if (options.unref === true) {\n (timer as { unref?: () => void } | undefined)?.unref?.();\n }\n }),\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n}\n\n/**\n * Run `sandbox.exec()` bounded by a client-side timeout, and — for signal-aware\n * transports (e.g. the HTTP bridge, `supportsExecSignal === true`) — abort the\n * underlying exec when the timeout fires instead of merely abandoning it. The\n * native DO transport ignores `signal`, so it only gets the timeout. Leaves the\n * backstop timer ref'd (this is an awaited direct-exec path).\n */\nexport async function execWithClientTimeout(\n sandbox: t.CloudflareSandboxRuntime,\n command: string,\n options: t.CloudflareSandboxExecOptions,\n timeoutMs: number,\n label: string,\n runOptions: { unref?: boolean } = {}\n): Promise<t.CloudflareSandboxExecResult> {\n const controller = new AbortController();\n const execOptions: t.CloudflareSandboxExecOptions = { ...options };\n const callerSignal = options.signal;\n let onCallerAbort: (() => void) | undefined;\n if (sandbox.supportsExecSignal === true) {\n // Compose the caller's signal (e.g. run/user cancellation) with our timeout\n // controller so EITHER source cancels the exec — don't clobber the caller's.\n if (callerSignal != null) {\n if (callerSignal.aborted) {\n controller.abort();\n } else {\n onCallerAbort = (): void => controller.abort();\n callerSignal.addEventListener('abort', onCallerAbort, { once: true });\n }\n }\n execOptions.signal = controller.signal;\n } else if ('signal' in execOptions) {\n // Native DO RPC cannot consume an AbortSignal (and would fail to clone it).\n // Strip any caller-provided one so the spread above can't reintroduce it.\n delete execOptions.signal;\n }\n try {\n return await withClientTimeout(\n sandbox.exec(command, execOptions),\n timeoutMs,\n label,\n {\n unref: runOptions.unref,\n onTimeout: () => controller.abort(),\n }\n );\n } finally {\n // Don't leave a listener attached to a long-lived/shared caller signal.\n if (onCallerAbort != null && callerSignal != null) {\n callerSignal.removeEventListener('abort', onCallerAbort);\n }\n }\n}\n\nfunction truncateOutput(value: string, maxChars: number): string {\n if (maxChars <= 0 || value.length <= maxChars) {\n return value;\n }\n const head = Math.max(Math.floor(maxChars / 2), 0);\n const tail = Math.max(maxChars - head, 0);\n return `${value.slice(0, head)}\\n...[truncated ${value.length - maxChars} chars]...\\n${value.slice(value.length - tail)}`;\n}\n\nasync function readStream(stream: ReadableStream<Uint8Array>): Promise<Buffer> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nasync function normalizeReadFileContent(\n result: t.CloudflareSandboxReadFileResult\n): Promise<Buffer> {\n if (typeof result === 'string') {\n return Buffer.from(result, 'utf8');\n }\n if (Buffer.isBuffer(result)) {\n return result;\n }\n if (result instanceof Uint8Array) {\n return Buffer.from(result);\n }\n const content = result.content;\n if (typeof content === 'string') {\n if (result.encoding === 'base64') {\n return Buffer.from(content, 'base64');\n }\n return Buffer.from(content, 'utf8');\n }\n if (Buffer.isBuffer(content)) {\n return content;\n }\n if (content instanceof Uint8Array) {\n return Buffer.from(content);\n }\n return readStream(content);\n}\n\nfunction bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller): void {\n controller.enqueue(bytes);\n controller.close();\n },\n });\n}\n\nfunction normalizeWriteFileContent(content: string | Buffer | Uint8Array): {\n content: string | ReadableStream<Uint8Array>;\n options?: { encoding?: string };\n} {\n if (typeof content === 'string') {\n return { content, options: { encoding: 'utf8' } };\n }\n return { content: bytesToStream(content) };\n}\n\nfunction createStats(info: {\n size?: number;\n type?: t.CloudflareSandboxFileInfo['type'];\n}): Stats {\n const type = info.type ?? 'file';\n const now = new Date();\n return {\n size: info.size ?? 0,\n isFile: () => type === 'file',\n isDirectory: () => type === 'directory',\n isSymbolicLink: () => type === 'symlink',\n isBlockDevice: () => false,\n isCharacterDevice: () => false,\n isFIFO: () => false,\n isSocket: () => false,\n dev: 0,\n ino: 0,\n mode: 0,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 0,\n blocks: 0,\n atimeMs: now.getTime(),\n mtimeMs: now.getTime(),\n ctimeMs: now.getTime(),\n birthtimeMs: now.getTime(),\n atime: now,\n mtime: now,\n ctime: now,\n birthtime: now,\n } as Stats;\n}\n\nfunction normalizeFileList(\n result: t.CloudflareSandboxListFilesResult\n): t.CloudflareSandboxFileInfo[] {\n return Array.isArray(result) ? result : result.files;\n}\n\nfunction entryNameFor(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.name !== '') {\n return info.name.includes('/') ? path.basename(info.name) : info.name;\n }\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.basename(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.basename(info.relativePath);\n }\n return path.basename(parentPath);\n}\n\nfunction entryAbsolutePath(\n info: t.CloudflareSandboxFileInfo,\n parentPath: string\n): string {\n if (info.absolutePath != null && info.absolutePath !== '') {\n return path.normalize(info.absolutePath);\n }\n if (info.relativePath != null && info.relativePath !== '') {\n return path.resolve(parentPath, info.relativePath);\n }\n return path.resolve(parentPath, info.name);\n}\n\nfunction createDirent(info: t.CloudflareSandboxFileInfo): ReaddirEntry {\n return {\n name: entryNameFor(info, ''),\n isFile: () => (info.type ?? 'file') === 'file',\n isDirectory: () => info.type === 'directory',\n isSymbolicLink: () => info.type === 'symlink',\n };\n}\n\nasync function findChildInfo(\n sandbox: t.CloudflareSandboxRuntime,\n filePath: string\n): Promise<t.CloudflareSandboxFileInfo | undefined> {\n const parent = path.dirname(filePath);\n const basename = path.basename(filePath);\n const entries = normalizeFileList(\n await sandbox.listFiles(parent, { includeHidden: true })\n );\n return entries.find((entry) => {\n const absolute = entryAbsolutePath(entry, parent);\n return absolute === filePath || entryNameFor(entry, parent) === basename;\n });\n}\n\nexport function createCloudflareWorkspaceFS(\n config: t.CloudflareSandboxExecutionConfig\n): WorkspaceFS {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n\n const fs: WorkspaceFS = {\n readFile: (async (filePath: string, encoding?: 'utf8') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved, encoding ? { encoding } : undefined)\n );\n return encoding != null ? buffer.toString(encoding) : buffer;\n }) as WorkspaceFS['readFile'],\n writeFile: async (\n filePath: string,\n content: string | Buffer,\n _options?: WriteFileOptions\n ) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const normalized = normalizeWriteFileContent(content);\n await sandbox.writeFile(resolved, normalized.content, normalized.options);\n },\n stat: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n if (resolved === workspaceRoot) {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n }\n const info = await findChildInfo(sandbox, resolved);\n if (info != null) {\n return createStats({ size: info.size, type: info.type });\n }\n try {\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n return createStats({ size: entries.length, type: 'directory' });\n } catch {\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return createStats({ size: buffer.length, type: 'file' });\n }\n },\n readdir: (async (filePath: string, options?: { withFileTypes: true }) => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const entries = normalizeFileList(\n await sandbox.listFiles(resolved, { includeHidden: true })\n );\n if (options?.withFileTypes === true) {\n return entries.map(createDirent);\n }\n return entries.map((entry) => entryNameFor(entry, resolved));\n }) as WorkspaceFS['readdir'],\n mkdir: async (filePath: string, options?: MakeDirectoryOptions) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.mkdir(toSandboxPath(filePath, workspaceRoot), {\n recursive: options?.recursive,\n });\n },\n realpath: async (filePath: string) =>\n toSandboxPath(filePath, workspaceRoot),\n unlink: async (filePath: string) => {\n const sandbox = await resolveCloudflareSandbox(config);\n await sandbox.deleteFile(toSandboxPath(filePath, workspaceRoot));\n },\n open: async (filePath: string, _flags: 'r') => {\n const sandbox = await resolveCloudflareSandbox(config);\n const resolved = toSandboxPath(filePath, workspaceRoot);\n const buffer = await normalizeReadFileContent(\n await sandbox.readFile(resolved)\n );\n return {\n read: async (\n target: Buffer,\n offset: number,\n length: number,\n position: number\n ) => {\n const start = Math.max(position, 0);\n const slice = buffer.subarray(start, start + length);\n slice.copy(target, offset);\n return { bytesRead: slice.length, buffer: target };\n },\n close: async () => undefined,\n } as unknown as FileHandle;\n },\n };\n\n return fs;\n}\n\nfunction createCloudflareSpawn(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalSpawn {\n return (command, args, options) => {\n const stdout = new PassThrough();\n const stderr = new PassThrough();\n const child = new EventEmitter() as ChildProcessWithoutNullStreams;\n const abortController = new AbortController();\n const state = { closed: false };\n /** Read through a function so concurrent `closeOnce` mutation (via\n * `kill()`/abort during an `await`) isn't statically narrowed away. */\n const isClosed = (): boolean => state.closed;\n const closeOnce = (\n exitCode: number | null,\n signal: NodeJS.Signals | null\n ): void => {\n if (state.closed) {\n return;\n }\n state.closed = true;\n stdout.end();\n stderr.end();\n Object.assign(child, {\n exitCode,\n signalCode: signal,\n });\n child.emit('close', exitCode, signal);\n };\n Object.assign(child, {\n stdout,\n stderr,\n stdin: new PassThrough(),\n stdio: [null, stdout, stderr],\n killed: false,\n exitCode: null,\n signalCode: null,\n pid: undefined,\n kill: (signal: NodeJS.Signals = 'SIGTERM') => {\n Object.assign(child, { killed: true, signalCode: signal });\n abortController.abort();\n closeOnce(null, signal);\n return true;\n },\n });\n\n void (async (): Promise<void> => {\n const ctx = await getRuntimeContext(config);\n const rendered = [command, ...args].map(quote).join(' ');\n const spawnTimeoutMs = (\n options as {\n [LOCAL_SPAWN_TIMEOUT_MS]?: number;\n }\n )[LOCAL_SPAWN_TIMEOUT_MS];\n const timeoutMs =\n typeof spawnTimeoutMs === 'number' && Number.isFinite(spawnTimeoutMs)\n ? spawnTimeoutMs\n : ctx.timeoutMs;\n const timedCommand = withInSandboxTimeout(rendered, timeoutMs);\n const cwd =\n options.cwd == null ? ctx.workspaceRoot : options.cwd.toString();\n if (isClosed()) {\n return;\n }\n const execOptions: t.CloudflareSandboxExecOptions = {\n cwd,\n env: ctx.env,\n timeout: outerTimeoutMs(timeoutMs),\n };\n if (ctx.sandbox.supportsExecSignal === true) {\n execOptions.signal = abortController.signal;\n }\n try {\n const result = await withClientTimeout(\n ctx.sandbox.exec(timedCommand, execOptions),\n clientExecTimeoutMs(timeoutMs),\n 'cloudflare sandbox exec',\n // spawnLocalProcess's own timer already resolves the child, so this\n // backstop may safely detach; abort the (signal-aware) exec on timeout.\n { unref: true, onTimeout: () => abortController.abort() }\n );\n if (isClosed()) {\n return;\n }\n if (result.stdout) stdout.write(result.stdout);\n if (result.stderr) stderr.write(result.stderr);\n closeOnce(result.exitCode, null);\n } catch (error) {\n if (isClosed()) {\n return;\n }\n stderr.write((error as Error).message);\n closeOnce(1, null);\n }\n })();\n\n return child;\n };\n}\n\nexport function createCloudflareLocalExecutionConfig(\n config: t.CloudflareSandboxExecutionConfig\n): t.LocalExecutionConfig {\n const workspaceRoot = getCloudflareWorkspaceRoot(config);\n return {\n cwd: workspaceRoot,\n workspace: { root: workspaceRoot },\n exec: {\n spawn: createCloudflareSpawn(config),\n fs: createCloudflareWorkspaceFS(config),\n sandboxed: true,\n },\n shell: config.shell ?? 'bash',\n timeoutMs: config.timeoutMs,\n maxOutputChars: config.maxOutputChars,\n env: config.env,\n includeCodingTools: config.includeCodingTools,\n compileCheck: config.compileCheck,\n readOnly: config.readOnly,\n allowDangerousCommands: config.allowDangerousCommands,\n bashAst: config.bashAst,\n fileCheckpointing: config.fileCheckpointing,\n maxReadBytes: config.maxReadBytes,\n attachReadAttachments: config.attachReadAttachments,\n maxAttachmentBytes: config.maxAttachmentBytes,\n postEditSyntaxCheck: config.postEditSyntaxCheck,\n };\n}\n\nexport async function validateCloudflareBashCommand(\n command: string,\n args: readonly string[],\n config: t.CloudflareSandboxExecutionConfig\n): Promise<void> {\n const localConfig = createCloudflareLocalExecutionConfig(config);\n const validation = await validateBashCommand(command, localConfig);\n if (!validation.valid) {\n throw new Error(validation.errors.join('\\n'));\n }\n\n if (\n args.length > 0 &&\n config.allowDangerousCommands !== true &&\n DESTRUCTIVE_OP_IN_COMMAND_RE.test(command)\n ) {\n const offending = args.find((arg) => PROTECTED_TARGET_ARG_RE.test(arg));\n if (offending !== undefined) {\n throw new Error(\n `Command matches a destructive command pattern (protected target \"${offending}\" passed via positional arg).`\n );\n }\n }\n}\n\nexport async function executeCloudflareBash(\n command: string,\n config: t.CloudflareSandboxExecutionConfig,\n args: readonly string[] = []\n): Promise<SpawnResult> {\n await validateCloudflareBashCommand(command, args, config);\n const ctx = await getRuntimeContext(config);\n const shellCommand =\n args.length > 0\n ? `${ctx.shell} -lc ${quote(command)} -- ${args.map(quote).join(' ')}`\n : `${ctx.shell} -lc ${quote(command)}`;\n const result = await execWithClientTimeout(\n ctx.sandbox,\n withInSandboxTimeout(shellCommand, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n },\n clientExecTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox bash exec'\n );\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n}\n\nfunction runtimeForCode(\n lang: string,\n tempDir: string,\n code: string,\n args: string[] = [],\n shell = 'bash'\n): RuntimeCommand {\n const fileFor = (name: string): string => path.join(tempDir, name);\n const argText = args.map(quote).join(' ');\n switch (lang) {\n case 'py':\n case 'python':\n return {\n fileName: 'main.py',\n source: code,\n command: `python3 ${quote(fileFor('main.py'))} ${argText}`,\n };\n case 'js':\n case 'javascript':\n return {\n fileName: 'main.js',\n source: code,\n command: `node ${quote(fileFor('main.js'))} ${argText}`,\n };\n case 'ts':\n case 'typescript':\n return {\n fileName: 'main.ts',\n source: code,\n command: `npx --no-install tsx ${quote(fileFor('main.ts'))} ${argText}`,\n };\n case 'php':\n return {\n fileName: 'main.php',\n source: code,\n command: `php ${quote(fileFor('main.php'))} ${argText}`,\n };\n case 'go':\n return {\n fileName: 'main.go',\n source: code,\n command: `go run ${quote(fileFor('main.go'))} ${argText}`,\n };\n case 'rs':\n return {\n fileName: 'main.rs',\n source: code,\n command: `${shell} -lc ${quote(\n `rustc ${quote(fileFor('main.rs'))} -o ${quote(fileFor('main-rs'))} && ${quote(fileFor('main-rs'))} ${argText}`\n )}`,\n };\n case 'c':\n return {\n fileName: 'main.c',\n source: code,\n command: `${shell} -lc ${quote(\n `cc ${quote(fileFor('main.c'))} -o ${quote(fileFor('main-c'))} && ${quote(fileFor('main-c'))} ${argText}`\n )}`,\n };\n case 'cpp':\n return {\n fileName: 'main.cpp',\n source: code,\n command: `${shell} -lc ${quote(\n `c++ ${quote(fileFor('main.cpp'))} -o ${quote(fileFor('main-cpp'))} && ${quote(fileFor('main-cpp'))} ${argText}`\n )}`,\n };\n case 'java':\n return {\n fileName: 'Main.java',\n source: code,\n command: `${shell} -lc ${quote(\n `javac ${quote(fileFor('Main.java'))} && java -cp ${quote(tempDir)} Main ${argText}`\n )}`,\n };\n case 'r':\n return {\n fileName: 'main.R',\n source: code,\n command: `Rscript ${quote(fileFor('main.R'))} ${argText}`,\n };\n case 'd':\n return {\n fileName: 'main.d',\n source: code,\n command: `${shell} -lc ${quote(\n `dmd ${quote(fileFor('main.d'))} -of=${quote(fileFor('main-d'))} && ${quote(fileFor('main-d'))} ${argText}`\n )}`,\n };\n case 'f90':\n return {\n fileName: 'main.f90',\n source: code,\n command: `${shell} -lc ${quote(\n `gfortran ${quote(fileFor('main.f90'))} -o ${quote(fileFor('main-f90'))} && ${quote(fileFor('main-f90'))} ${argText}`\n )}`,\n };\n case 'bash':\n case 'sh':\n return {\n fileName: 'main.sh',\n source: code,\n command: `${shell} -lc ${quote(code)} -- ${argText}`,\n };\n default:\n throw new Error(`Unsupported Cloudflare sandbox runtime: ${lang}`);\n }\n}\n\nexport async function executeCloudflareCode(\n input: { lang: string; code: string; args?: string[] },\n config: t.CloudflareSandboxExecutionConfig\n): Promise<SpawnResult> {\n if (input.lang === 'bash' || input.lang === 'sh') {\n return executeCloudflareBash(input.code, config, input.args ?? []);\n }\n const ctx = await getRuntimeContext(config);\n const id = globalThis.crypto.randomUUID();\n const tempDir = path.join(ctx.workspaceRoot, '.lc-exec', id);\n const runtime = runtimeForCode(\n input.lang,\n tempDir,\n input.code,\n input.args,\n ctx.shell\n );\n await ctx.sandbox.mkdir(tempDir, { recursive: true });\n if (runtime.source != null) {\n await ctx.sandbox.writeFile(\n path.join(tempDir, runtime.fileName),\n runtime.source,\n {\n encoding: 'utf8',\n }\n );\n }\n let execSucceeded = false;\n try {\n const result = await execWithClientTimeout(\n ctx.sandbox,\n withInSandboxTimeout(runtime.command, ctx.timeoutMs),\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: outerTimeoutMs(ctx.timeoutMs),\n },\n clientExecTimeoutMs(ctx.timeoutMs),\n 'cloudflare sandbox code-exec'\n );\n execSucceeded = true;\n return {\n stdout: truncateOutput(result.stdout, ctx.maxOutputChars),\n stderr: truncateOutput(result.stderr, ctx.maxOutputChars),\n exitCode: result.exitCode,\n timedOut: isInSandboxTimeoutExit(result.exitCode),\n };\n } finally {\n // After a normal run, AWAIT cleanup so the temp dir is gone before returning.\n // After a stalled/failed run, detach it (unref'd) so we don't pile a second\n // client timeout onto the caller's latency; cleanup still runs best-effort.\n const detach = !execSucceeded;\n const cleanup = execWithClientTimeout(\n ctx.sandbox,\n `rm -rf ${quote(tempDir)}`,\n {\n cwd: ctx.workspaceRoot,\n env: ctx.env,\n timeout: 10000,\n },\n clientExecTimeoutMs(10000),\n 'cloudflare sandbox cleanup',\n { unref: detach }\n ).catch(() => undefined);\n if (!detach) {\n await cleanup;\n }\n }\n}\n\nexport function formatCloudflareOutput(\n result: SpawnResult,\n cwd: string\n): string {\n let formatted = '';\n if (result.stdout !== '') {\n formatted += `stdout:\\n${result.stdout}\\n`;\n } else {\n formatted += 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n }\n if (result.stderr !== '') {\n formatted += `stderr:\\n${result.stderr}\\n`;\n }\n if (result.exitCode != null && result.exitCode !== 0) {\n formatted += `exit_code: ${result.exitCode}\\n`;\n }\n if (result.timedOut) {\n formatted += 'timed_out: true\\n';\n }\n formatted += `working_directory: ${cwd}`;\n return formatted.trim();\n}\n"],"mappings":";;;;;AAaA,MAAM,yBAAyB;AAC/B,MAAM,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B,IAAI,CAAC,QACH,MAAM;CAEV;AACF;AAEA,SAAgB,uBACd,QACA,KACQ;CACR,IAAI,YAAY;CAChB,IAAI,OAAO,WAAW,IACpB,aAAa,YAAY,OAAO,OAAO;MAEvC,aAAa;CAEf,IAAI,OAAO,WAAW,IACpB,aAAa,YAAY,OAAO,OAAO;CAEzC,IAAI,OAAO,YAAY,QAAQ,OAAO,aAAa,GACjD,aAAa,cAAc,OAAO,SAAS;CAE7C,IAAI,OAAO,UACT,aAAa;CAEf,aAAa,sBAAsB;CACnC,OAAO,UAAU,KAAK;AACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"AgentContext.mjs","names":[],"sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport { HumanMessage, SystemMessage } from '@langchain/core/messages';\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 {\n addTailCacheControl,\n addCacheControlToStablePrefixMessages,\n buildAnthropicCacheControl,\n buildBedrockCachePoint,\n resolvePromptCacheTtl,\n cloneMessage,\n type PromptCacheTtl,\n} from '@/messages/cache';\nimport {\n ANTHROPIC_TOOL_TOKEN_MULTIPLIER,\n DEFAULT_TOOL_TOKEN_MULTIPLIER,\n ContentTypes,\n Constants,\n Providers,\n} from '@/common';\nimport {\n DEFAULT_RESERVE_RATIO,\n createPruneMessages,\n syncBudgetDerivedFields,\n} from '@/messages';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { apportionTokenCounts } from '@/utils/tokens';\nimport { isThinkingEnabled } from '@/llm/request';\nimport { toJsonSchema } from '@/utils/schema';\n\ntype AgentSystemTextBlock = {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral'; ttl?: '1h' };\n};\n\ntype AgentSystemContentBlock =\n | AgentSystemTextBlock\n | { cachePoint: { type: 'default'; ttl?: '1h' } };\n\ntype PromptCacheProvider = Providers.ANTHROPIC | Providers.OPENROUTER;\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 name,\n provider,\n clientOptions,\n langfuse,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n toolDefinitions,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n initialSummary,\n contextPruningConfig,\n maxToolResultChars,\n toolSchemaTokens,\n subagentConfigs,\n maxSubagentDepth,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n name: name ?? agentId,\n provider,\n clientOptions,\n langfuse,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n });\n\n agentContext._sourceInputs = agentConfig;\n agentContext.subagentConfigs = subagentConfigs;\n agentContext.maxSubagentDepth = maxSubagentDepth;\n\n if (initialSummary?.text != null && initialSummary.text !== '') {\n agentContext.setInitialSummary(\n initialSummary.text,\n initialSummary.tokenCount\n );\n }\n\n if (tokenCounter) {\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.baseIndexTokenCountMap = { ...tokenMap };\n agentContext.indexTokenCountMap = tokenMap;\n\n if (toolSchemaTokens != null && toolSchemaTokens > 0) {\n /** Use pre-computed (cached) tool schema tokens — skip calculateInstructionTokens */\n agentContext.toolSchemaTokens = toolSchemaTokens;\n agentContext.tokenCalculationPromise = Promise.resolve();\n agentContext.updateTokenMapWithInstructions(tokenMap);\n } else {\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n }\n } else if (indexTokenCountMap) {\n agentContext.baseIndexTokenCountMap = { ...indexTokenCountMap };\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */\n name?: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Per-agent Langfuse tracing configuration. */\n langfuse?: t.LangfuseConfig;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Canonical pre-run token map used to restore token accounting on reset */\n baseIndexTokenCountMap: Record<string, number> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /**\n * Usage from the most recent LLM call only (not accumulated).\n * Used for accurate provider calibration in pruning.\n */\n lastCallUsage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheRead?: number;\n cacheCreation?: number;\n };\n /**\n * Whether totalTokens data is fresh (set true when provider usage arrives,\n * false at the start of each turn before the LLM responds).\n * Prevents stale token data from driving pruning/trigger decisions.\n */\n totalTokensFresh: boolean = false;\n /** Context pruning configuration. */\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\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 /** Token count for the system message (instructions text). */\n systemMessageTokens: number = 0;\n /** Token count for instruction text emitted outside the system message. */\n dynamicInstructionTokens: number = 0;\n /** Token count for tool schemas only. */\n toolSchemaTokens: number = 0;\n /** Per-tool schema token counts (post-multiplier), keyed by tool name.\n * `undefined` when not calculated (e.g. cached aggregate schema tokens). */\n toolTokenCounts?: Record<string, number>;\n /** Names of counted tools that are deferred (`defer_loading`) and discovered. */\n deferredToolNames: string[] = [];\n /** Running calibration ratio from the pruner — persisted across runs via contextMeta. */\n calibrationRatio: number = 1;\n /** Provider-observed instruction overhead from the pruner's best-variance turn. */\n resolvedInstructionOverhead?: number;\n /** Pre-masking tool content keyed by message index, consumed by the summarize node. */\n pendingOriginalToolContent?: Map<number, string>;\n\n /** Total instruction overhead: system message + tool schemas + pending summary. */\n get instructionTokens(): number {\n const summaryOverhead =\n this._summaryLocation === 'user_message' ? this.summaryTokenCount : 0;\n return (\n this.systemMessageTokens +\n this.dynamicInstructionTokens +\n this.toolSchemaTokens +\n summaryOverhead\n );\n }\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 /** Graph-managed tools (e.g., handoff tools created by MultiAgentGraph) that bypass event-driven dispatch */\n graphTools?: 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 /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode.\n */\n toolDefinitions?: t.LCTool[];\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */\n _sourceInputs?: t.AgentInputs;\n /** Subagent configurations for hierarchical delegation. */\n subagentConfigs?: t.SubagentConfig[];\n /** Maximum subagent nesting depth. */\n maxSubagentDepth?: number;\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: 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 /** Tracks how many reasoning→text transitions have occurred (ensures unique post-reasoning step keys) */\n reasoningTransitionCount = 0;\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 /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Enables graph-level summarization for this agent */\n summarizationEnabled?: boolean;\n /** Summarization runtime settings used by graph pruning hooks */\n summarizationConfig?: t.SummarizationConfig;\n /** Current summary text produced by the summarize node, integrated into system message */\n private summaryText?: string;\n /** Token count of the current summary (tracked for token accounting) */\n private summaryTokenCount: number = 0;\n /**\n * Where the summary should be injected:\n * - `'system_prompt'`: cross-run summary, included in the dynamic system tail\n * - `'user_message'`: mid-run compaction, injected as HumanMessage on clean slate\n * - `'none'`: no summary present\n */\n private _summaryLocation: 'system_prompt' | 'user_message' | 'none' = 'none';\n /**\n * Durable summary that survives reset() calls. Set from initialSummary\n * during fromConfig() and updated by setSummary() so that the latest\n * summary (whether cross-run or intra-run) is always restored after\n * processStream's resetValues() cycle.\n */\n private _durableSummaryText?: string;\n private _durableSummaryTokenCount: number = 0;\n /** Number of summarization cycles that have occurred for this agent context */\n private _summaryVersion: number = 0;\n /**\n * Message count at the time summarization was last triggered.\n * Used to prevent re-summarizing the same unchanged message set.\n * Summarization is allowed to fire again only when new messages appear.\n */\n private _lastSummarizationMsgCount: number = 0;\n /**\n * Handoff context when this agent receives control via handoff.\n * Contains source and parallel execution info for system message context.\n */\n handoffContext?: {\n /** Source agent that transferred control */\n sourceAgentName: string;\n /** Names of sibling agents executing in parallel (empty if sequential) */\n parallelSiblings: string[];\n };\n\n constructor({\n agentId,\n name,\n provider,\n clientOptions,\n langfuse,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n }: {\n agentId: string;\n name?: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n langfuse?: t.LangfuseConfig;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n toolDefinitions?: t.LCTool[];\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n discoveredTools?: string[];\n summarizationEnabled?: boolean;\n summarizationConfig?: t.SummarizationConfig;\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\n }) {\n this.agentId = agentId;\n this.name = name;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.langfuse = langfuse;\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.toolDefinitions = toolDefinitions;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.systemMessageTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n this.summarizationEnabled = summarizationEnabled;\n this.summarizationConfig = summarizationConfig;\n this.contextPruningConfig = contextPruningConfig;\n this.maxToolResultChars = maxToolResultChars;\n\n if (discoveredTools && discoveredTools.length > 0) {\n for (const toolName of discoveredTools) {\n this.discoveredToolNames.add(toolName);\n }\n }\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 * configured programmatic 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 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 programmaticTool = this.getProgrammaticToolInstructionTarget();\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 \\`${programmaticTool.name}\\` tool. ` +\n `You cannot call these tools directly; instead, use \\`${programmaticTool.name}\\` with ${programmaticTool.language} code that invokes them.\\n\\n` +\n toolDescriptions\n );\n }\n\n private getProgrammaticToolInstructionTarget(): {\n name: string;\n language: 'bash' | 'Python';\n } {\n if (this.hasAvailableTool(Constants.BASH_PROGRAMMATIC_TOOL_CALLING)) {\n return {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n language: 'bash',\n };\n }\n\n if (this.hasAvailableTool(Constants.PROGRAMMATIC_TOOL_CALLING)) {\n return { name: Constants.PROGRAMMATIC_TOOL_CALLING, language: 'Python' };\n }\n\n return { name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING, language: 'bash' };\n }\n\n private hasAvailableTool(name: string): boolean {\n if (this.toolDefinitions?.some((tool) => tool.name === name) === true)\n return true;\n if (\n this.tools?.some((tool) => 'name' in tool && tool.name === name) === true\n ) {\n return true;\n }\n if (this.toolMap?.has(name) === true) return true;\n return this.toolRegistry?.has(name) === true;\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes stable instructions, dynamic additional instructions, and\n * 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 if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n this.cachedSystemRunnable = this.buildSystemRunnable({\n stableInstructions: this.buildStableInstructionsString(),\n dynamicInstructions: this.buildDynamicInstructionsString(),\n });\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 this.cachedSystemRunnable = this.buildSystemRunnable({\n stableInstructions: this.buildStableInstructionsString(),\n dynamicInstructions: this.buildDynamicInstructionsString(),\n });\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the cacheable instructions string (without creating SystemMessage).\n * Includes agent identity preamble and handoff context when available.\n */\n private buildStableInstructionsString(): string {\n const parts: string[] = [];\n\n const identityPreamble = this.buildIdentityPreamble();\n if (identityPreamble) {\n parts.push(identityPreamble);\n }\n\n if (this.instructions != null && this.instructions !== '') {\n parts.push(this.instructions);\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n parts.push(programmaticToolsDoc);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the dynamic system-tail string (without creating SystemMessage).\n * Keep this out of prompt-cache-marked content so volatile context does not\n * invalidate the stable prefix.\n */\n private buildDynamicInstructionsString(): string {\n const parts: string[] = [];\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n parts.push(this.additionalInstructions);\n }\n\n // Cross-run summary: include in the system tail so the model has context\n // from the prior run without invalidating the cacheable prefix. Mid-run\n // summaries are injected as a HumanMessage on the post-compaction clean\n // slate instead (see buildSystemRunnable).\n if (\n this._summaryLocation === 'system_prompt' &&\n this.summaryText != null &&\n this.summaryText !== ''\n ) {\n parts.push('## Conversation Summary\\n\\n' + this.summaryText);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the agent identity preamble including handoff context if present.\n * This helps the agent understand its role in the multi-agent workflow.\n */\n private buildIdentityPreamble(): string {\n if (!this.handoffContext) return '';\n\n const displayName = this.name ?? this.agentId;\n const { sourceAgentName, parallelSiblings } = this.handoffContext;\n const isParallel = parallelSiblings.length > 0;\n\n const lines: string[] = [];\n lines.push('## Multi-Agent Workflow');\n lines.push(\n `You are \"${displayName}\", transferred from \"${sourceAgentName}\".`\n );\n\n if (isParallel) {\n lines.push(`Running in parallel with: ${parallelSiblings.join(', ')}.`);\n }\n\n lines.push(\n 'Execute only tasks relevant to your role. Routing is already handled if requested, unless you can route further.'\n );\n\n return lines.join('\\n');\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 stableInstructions,\n dynamicInstructions,\n }: {\n stableInstructions: string;\n dynamicInstructions: string;\n }):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n const hasMidRunSummary =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n if (!stableInstructions && !dynamicInstructions && !hasMidRunSummary) {\n this.systemMessageTokens = 0;\n this.dynamicInstructionTokens = 0;\n return undefined;\n }\n\n const promptCacheProvider = this.getPromptCacheProvider();\n const shouldMoveDynamicInstructions =\n promptCacheProvider != null &&\n stableInstructions !== '' &&\n dynamicInstructions !== '';\n const systemMessage = this.buildSystemMessage({\n stableInstructions,\n dynamicInstructions,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n });\n\n if (this.tokenCounter) {\n this.systemMessageTokens = systemMessage\n ? this.tokenCounter(systemMessage)\n : 0;\n this.dynamicInstructionTokens = shouldMoveDynamicInstructions\n ? this.tokenCounter(new HumanMessage(dynamicInstructions))\n : 0;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n const prefix: BaseMessage[] = systemMessage ? [systemMessage] : [];\n\n // Build the non-system portion (summary + conversation), then apply\n // cache markers separately so addCacheControl doesn't strip the\n // SystemMessage's own cache_control breakpoint set above.\n const hasSummaryBody =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n const bodyWithSummary =\n hasSummaryBody && promptCacheProvider == null\n ? [this.buildSummaryHumanMessage(promptCacheProvider), ...messages]\n : messages;\n const dynamicTail = this.buildPromptCacheDynamicTail({\n dynamicInstructions,\n hasSummaryBody,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n });\n let body = this.buildBodyWithPromptCacheDynamicTail(\n bodyWithSummary,\n dynamicTail,\n promptCacheProvider\n );\n\n if (\n promptCacheProvider != null &&\n dynamicTail.length === 0 &&\n body.length >= 2\n ) {\n body = addTailCacheControl(\n body,\n this.getPromptCacheTtl(promptCacheProvider)\n );\n }\n return [...prefix, ...body];\n }).withConfig({ runName: 'prompt' });\n }\n\n private buildSummaryHumanMessage(\n promptCacheProvider: PromptCacheProvider | undefined\n ): HumanMessage {\n const wrappedSummary =\n '<summary>\\n' +\n (this.summaryText as string) +\n '\\n</summary>\\n\\n' +\n 'This is your own checkpoint: you wrote it to preserve context after compaction. Pick up where you left off based on the summary above. Do not repeat prior tasks, information or acknowledge this checkpoint message directly.';\n\n if (promptCacheProvider !== Providers.ANTHROPIC) {\n return new HumanMessage(wrappedSummary);\n }\n\n return new HumanMessage({\n content: [\n {\n type: 'text',\n text: wrappedSummary,\n cache_control: buildAnthropicCacheControl(\n this.getPromptCacheTtl(Providers.ANTHROPIC)\n ),\n },\n ],\n });\n }\n\n private buildPromptCacheDynamicTail({\n dynamicInstructions,\n hasSummaryBody,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n }: {\n dynamicInstructions: string;\n hasSummaryBody: boolean;\n promptCacheProvider: PromptCacheProvider | undefined;\n shouldMoveDynamicInstructions: boolean;\n }): BaseMessage[] {\n if (promptCacheProvider == null) {\n return [];\n }\n\n const dynamicTail = shouldMoveDynamicInstructions\n ? [new HumanMessage(dynamicInstructions)]\n : [];\n\n if (!hasSummaryBody) {\n return dynamicTail;\n }\n\n return [...dynamicTail, this.buildSummaryHumanMessage(undefined)];\n }\n\n private buildBodyWithPromptCacheDynamicTail(\n messages: BaseMessage[],\n tail: BaseMessage[],\n promptCacheProvider: PromptCacheProvider | undefined\n ): BaseMessage[] {\n if (tail.length === 0) {\n return messages;\n }\n\n const tailIndex = this.getPromptCacheDynamicTailIndex(\n messages,\n promptCacheProvider\n );\n const stablePrefix = messages.slice(0, tailIndex);\n const trailingMessages = messages.slice(tailIndex);\n const cacheablePrefix = this.addStablePromptCacheMarkers(\n stablePrefix,\n this.getPromptCacheTtl(promptCacheProvider)\n );\n\n return [...cacheablePrefix, ...tail, ...trailingMessages];\n }\n\n private getPromptCacheDynamicTailIndex(\n messages: BaseMessage[],\n promptCacheProvider: PromptCacheProvider | undefined\n ): number {\n const lastIndex = messages.length - 1;\n\n if (lastIndex < 0) {\n return 0;\n }\n\n if (promptCacheProvider === Providers.OPENROUTER && messages.length === 1) {\n return messages.length;\n }\n\n for (let index = lastIndex; index >= 0; index--) {\n if (messages[index].getType() === 'human') {\n if (promptCacheProvider === Providers.OPENROUTER && index === 0) {\n return 1;\n }\n return index;\n }\n }\n\n return messages.length;\n }\n\n private addStablePromptCacheMarkers(\n messages: BaseMessage[],\n ttl?: PromptCacheTtl\n ): BaseMessage[] {\n if (messages.length <= 1) {\n return messages;\n }\n\n return [\n messages[0],\n ...addCacheControlToStablePrefixMessages(messages.slice(1), 2, ttl),\n ];\n }\n\n private getPromptCacheProvider(): PromptCacheProvider | undefined {\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n return anthropicOptions?.promptCache === true\n ? Providers.ANTHROPIC\n : undefined;\n }\n\n if (this.provider === Providers.OPENROUTER) {\n const openRouterOptions = this.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined;\n return openRouterOptions?.promptCache === true\n ? Providers.OPENROUTER\n : undefined;\n }\n\n return undefined;\n }\n\n private hasBedrockPromptCache(): boolean {\n if (this.provider !== Providers.BEDROCK) {\n return false;\n }\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n return bedrockOptions?.promptCache === true;\n }\n\n /**\n * Resolved TTL for the active prompt-cache provider (Anthropic or OpenRouter).\n * Both expose `promptCacheTtl` and use the Anthropic `cache_control` format, so\n * the configured value resolves the same way (default `'1h'` extended cache).\n */\n private getPromptCacheTtl(\n provider: PromptCacheProvider | undefined\n ): PromptCacheTtl | undefined {\n if (provider == null) {\n return undefined;\n }\n return resolvePromptCacheTtl(\n (this.clientOptions as { promptCacheTtl?: PromptCacheTtl } | undefined)\n ?.promptCacheTtl\n );\n }\n\n /**\n * Resolved TTL for Bedrock prompt-cache checkpoints (default `'1h'`).\n * Models that don't support the 1-hour TTL downgrade to 5m server-side.\n */\n private getBedrockPromptCacheTtl(): PromptCacheTtl {\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n return resolvePromptCacheTtl(bedrockOptions?.promptCacheTtl);\n }\n\n private buildSystemMessage({\n stableInstructions,\n dynamicInstructions,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n }: {\n stableInstructions: string;\n dynamicInstructions: string;\n promptCacheProvider: PromptCacheProvider | undefined;\n shouldMoveDynamicInstructions: boolean;\n }): SystemMessage | undefined {\n if (!stableInstructions && !dynamicInstructions) {\n return undefined;\n }\n\n if (promptCacheProvider === Providers.ANTHROPIC) {\n const content: AgentSystemContentBlock[] = [];\n if (stableInstructions) {\n content.push({\n type: 'text',\n text: stableInstructions,\n cache_control: buildAnthropicCacheControl(\n this.getPromptCacheTtl(promptCacheProvider)\n ),\n });\n }\n if (dynamicInstructions && !shouldMoveDynamicInstructions) {\n content.push({ type: 'text', text: dynamicInstructions });\n }\n return new SystemMessage({ content } as BaseMessageFields);\n }\n\n if (promptCacheProvider === Providers.OPENROUTER && !stableInstructions) {\n return new SystemMessage(dynamicInstructions);\n }\n\n if (promptCacheProvider === Providers.OPENROUTER) {\n return new SystemMessage({\n content: [\n {\n type: 'text',\n text: stableInstructions,\n cache_control: buildAnthropicCacheControl(\n this.getPromptCacheTtl(promptCacheProvider)\n ),\n },\n ],\n } as BaseMessageFields);\n }\n\n if (this.hasBedrockPromptCache() && stableInstructions) {\n const content: AgentSystemContentBlock[] = [\n { type: 'text', text: stableInstructions },\n { cachePoint: buildBedrockCachePoint(this.getBedrockPromptCacheTtl()) },\n ];\n if (dynamicInstructions) {\n content.push({ type: 'text', text: dynamicInstructions });\n }\n return new SystemMessage({ content } as BaseMessageFields);\n }\n\n return new SystemMessage(\n [stableInstructions, dynamicInstructions]\n .filter((part) => part !== '')\n .join('\\n\\n')\n );\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.systemMessageTokens = 0;\n this.dynamicInstructionTokens = 0;\n this.toolSchemaTokens = 0;\n this.toolTokenCounts = undefined;\n this.deferredToolNames = [];\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = { ...this.baseIndexTokenCountMap };\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.reasoningTransitionCount = 0;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n this.handoffContext = undefined;\n\n this.summaryText = this._durableSummaryText;\n this.summaryTokenCount = this._durableSummaryTokenCount;\n this._lastSummarizationMsgCount = 0;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n\n if (this.tokenCounter) {\n this.initializeSystemRunnable();\n const baseTokenMap = { ...this.baseIndexTokenCountMap };\n this.indexTokenCountMap = baseTokenMap;\n this.tokenCalculationPromise = this.calculateInstructionTokens(\n this.tokenCounter\n )\n .then(() => {\n this.updateTokenMapWithInstructions(baseTokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else {\n this.tokenCalculationPromise = undefined;\n }\n }\n\n /**\n * Update the token count map from a base map.\n *\n * Previously this inflated index 0 with instructionTokens to indirectly\n * reserve budget for the system prompt. That approach was imprecise: with\n * large tool-schema overhead (e.g. 26 MCP tools ~5 000 tokens) the first\n * conversation message appeared enormous and was always pruned, while the\n * real available budget was never explicitly computed.\n *\n * Now instruction tokens are passed to getMessagesWithinTokenLimit via\n * the `getInstructionTokens` factory param so the pruner subtracts them\n * from the budget directly. The token map contains only real per-message\n * token counts.\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n\n /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */\n private getActiveToolDefinitions(): t.LCTool[] {\n if (!this.toolDefinitions) {\n return [];\n }\n /**\n * Mirror `getEventDrivenToolsForBinding`'s gate: a definition is only\n * bound to the model when its `allowed_callers` include `'direct'` and\n * (if deferred) it has been discovered. Filtering by `defer_loading`\n * alone left programmatic-only definitions counted in\n * `toolSchemaTokens` even though they were never bound.\n */\n return this.toolDefinitions.filter((def) => {\n const allowedCallers = def.allowed_callers ?? ['direct'];\n if (!allowedCallers.includes('direct')) {\n return false;\n }\n return (\n def.defer_loading !== true || this.discoveredToolNames.has(def.name)\n );\n });\n }\n\n /**\n * Single source of truth for \"which entries of `this.tools` should be\n * treated as actually bound\". Callers:\n * - `getToolsForBinding` (non-event-driven branch)\n * - `getEventDrivenToolsForBinding` (appends instance tools alongside\n * schema-only definitions)\n * - `calculateInstructionTokens` (counts schema bytes for accounting)\n *\n * In event-driven mode (`toolDefinitions` present) instance tools are\n * appended unfiltered; outside event-driven mode they pass through\n * `filterToolsForBinding`. Centralizing the decision here prevents the\n * accounting/binding paths from drifting apart, which was the root\n * cause of the original miscount.\n */\n private getEffectiveInstanceTools(): t.GraphTools | undefined {\n if (!this.tools) {\n return undefined;\n }\n const isEventDriven = (this.toolDefinitions?.length ?? 0) > 0;\n if (isEventDriven || !this.toolRegistry) {\n return this.tools;\n }\n return this.filterToolsForBinding(this.tools);\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n const countedToolNames = new Set<string>();\n /** Prototype-free: external tool names like `toString` must not hit\n * inherited properties during accumulation */\n const rawToolTokenCounts: Record<string, number> = Object.create(null);\n const deferredCountedNames = new Set<string>();\n\n /**\n * Iterate both `tools` (user-provided instance tools) and `graphTools`\n * (graph-managed tools like handoff + subagent). `graphTools` is often\n * populated after `fromConfig()` kicks off the initial calculation, so\n * callers that mutate `graphTools` must re-trigger this method to\n * refresh `toolSchemaTokens`.\n *\n * Use `getEffectiveInstanceTools()` so accounting reflects exactly the\n * subset that `getToolsForBinding` would emit — preventing the\n * worst-case-ceiling miscount that triggered spurious `empty_messages`\n * preflight rejections at low `maxContextTokens`. Deferred and\n * non-`'direct'` `toolDefinitions` are excluded by\n * `getActiveToolDefinitions()` below.\n */\n const instanceTools: t.GraphTools = [\n ...((this.getEffectiveInstanceTools() as t.GenericTool[] | undefined) ??\n []),\n ...((this.graphTools as t.GenericTool[] | undefined) ?? []),\n ];\n\n if (instanceTools.length > 0) {\n for (const tool of instanceTools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const toolName = (genericTool.name as string | undefined) ?? '';\n const jsonSchema = toJsonSchema(\n genericTool.schema,\n toolName,\n (genericTool.description as string | undefined) ?? ''\n );\n const schemaTokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n toolTokens += schemaTokens;\n if (toolName) {\n countedToolNames.add(toolName);\n rawToolTokenCounts[toolName] =\n (rawToolTokenCounts[toolName] ?? 0) + schemaTokens;\n }\n }\n }\n }\n\n for (const def of this.getActiveToolDefinitions()) {\n if (countedToolNames.has(def.name)) {\n continue;\n }\n const schema = {\n type: 'function',\n function: {\n name: def.name,\n description: def.description ?? '',\n parameters: def.parameters ?? {},\n },\n };\n const schemaTokens = tokenCounter(\n new SystemMessage(JSON.stringify(schema))\n );\n toolTokens += schemaTokens;\n countedToolNames.add(def.name);\n rawToolTokenCounts[def.name] =\n (rawToolTokenCounts[def.name] ?? 0) + schemaTokens;\n if (def.defer_loading === true) {\n deferredCountedNames.add(def.name);\n }\n }\n\n const isAnthropic =\n this.provider !== Providers.BEDROCK &&\n (this.provider === Providers.ANTHROPIC ||\n /anthropic|claude/i.test(\n String(\n (this.clientOptions as { model?: string } | undefined)?.model ?? ''\n )\n ));\n const toolTokenMultiplier = isAnthropic\n ? ANTHROPIC_TOOL_TOKEN_MULTIPLIER\n : DEFAULT_TOOL_TOKEN_MULTIPLIER;\n this.toolSchemaTokens = Math.ceil(toolTokens * toolTokenMultiplier);\n\n /** Largest-remainder apportionment keeps the per-tool counts summing\n * exactly to the aggregate despite per-entry rounding */\n const toolTokenCounts = apportionTokenCounts(\n rawToolTokenCounts,\n toolTokenMultiplier,\n this.toolSchemaTokens\n );\n const deferredToolNames: string[] = [];\n for (const name of Object.keys(rawToolTokenCounts)) {\n if (\n deferredCountedNames.has(name) ||\n this.toolRegistry?.get(name)?.defer_loading === true\n ) {\n deferredToolNames.push(name);\n }\n }\n this.toolTokenCounts = toolTokenCounts;\n this.deferredToolNames = deferredToolNames;\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 * Sets the handoff context for this agent.\n * Call this when the agent receives control via handoff from another agent.\n * Marks system runnable as stale to include handoff context in system message.\n * @param sourceAgentName - Name of the agent that transferred control\n * @param parallelSiblings - Names of other agents executing in parallel with this one\n */\n setHandoffContext(sourceAgentName: string, parallelSiblings: string[]): void {\n this.handoffContext = { sourceAgentName, parallelSiblings };\n this.systemRunnableStale = true;\n }\n\n /**\n * Clears any handoff context.\n * Call this when resetting the agent or when handoff context is no longer relevant.\n */\n clearHandoffContext(): void {\n if (this.handoffContext) {\n this.handoffContext = undefined;\n this.systemRunnableStale = true;\n }\n }\n\n setSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'user_message';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n this.pruneMessages = undefined;\n }\n\n /** Sets a cross-run summary that is injected into the system prompt. */\n setInitialSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'system_prompt';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n }\n\n /**\n * Replaces the indexTokenCountMap with a fresh map keyed to the surviving\n * context messages after summarization. Called by the summarize node after\n * it emits RemoveMessage operations that shift message indices.\n */\n rebuildTokenMapAfterSummarization(newTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = newTokenMap;\n this.baseIndexTokenCountMap = { ...newTokenMap };\n this._lastSummarizationMsgCount = Object.keys(newTokenMap).length;\n this.currentUsage = undefined;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n }\n\n hasSummary(): boolean {\n return this.summaryText != null && this.summaryText !== '';\n }\n\n /** True when a mid-run compaction summary is ready to be injected as a HumanMessage. */\n hasPendingCompactionSummary(): boolean {\n return this._summaryLocation === 'user_message' && this.hasSummary();\n }\n\n getSummaryText(): string | undefined {\n return this.summaryText;\n }\n\n get summaryVersion(): number {\n return this._summaryVersion;\n }\n\n /**\n * Returns true when the message count hasn't changed since the last\n * summarization — re-summarizing would produce an identical result.\n * Oversized individual messages are handled by fit-to-budget truncation\n * in the pruner, which keeps them in context without triggering overflow.\n */\n shouldSkipSummarization(currentMsgCount: number): boolean {\n return (\n this._lastSummarizationMsgCount > 0 &&\n currentMsgCount <= this._lastSummarizationMsgCount\n );\n }\n\n /**\n * Records the message count at which summarization was triggered,\n * so subsequent calls with the same count are suppressed.\n */\n markSummarizationTriggered(msgCount: number): void {\n this._lastSummarizationMsgCount = msgCount;\n }\n\n clearSummary(): void {\n if (this.summaryText != null) {\n this.summaryText = undefined;\n this.summaryTokenCount = 0;\n this._durableSummaryText = undefined;\n this._durableSummaryTokenCount = 0;\n this._summaryLocation = 'none';\n this.systemRunnableStale = true;\n }\n }\n\n /**\n * Returns a structured breakdown of how the context token budget is consumed.\n * Useful for diagnostics when context overflow or pruning issues occur.\n *\n * Note: `markToolsAsDiscovered` re-triggers `calculateInstructionTokens`,\n * so `toolSchemaTokens`/`toolTokenCounts` refresh before the next call.\n */\n getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown {\n const maxContextTokens = this.maxContextTokens ?? 0;\n /**\n * Derive `toolCount` from `getToolsForBinding()` so the diagnostic stays\n * aligned with what is actually bound to the model — and with what\n * `calculateInstructionTokens` counts into `toolSchemaTokens`. Using raw\n * `this.tools.length` would inflate the count whenever the registry\n * marks instance tools as deferred-undiscovered or non-`'direct'`,\n * producing the same misleading \"N tools\" diagnostic this fix is meant\n * to eliminate.\n */\n const toolCount = this.getToolsForBinding()?.length ?? 0;\n const messageCount = messages?.length ?? 0;\n\n let messageTokens = 0;\n if (messages != null) {\n for (let i = 0; i < messages.length; i++) {\n messageTokens +=\n (this.indexTokenCountMap[i] as number | undefined) ?? 0;\n }\n }\n\n /** Mirror the pruner's reserve math so availableForMessages agrees\n * with the contextBudget computed during pruning */\n const reserveRatio =\n this.summarizationConfig?.reserveRatio ?? DEFAULT_RESERVE_RATIO;\n const reserveTokens =\n reserveRatio > 0 && reserveRatio < 1\n ? Math.round(maxContextTokens * reserveRatio)\n : 0;\n const availableForMessages = Math.max(\n 0,\n maxContextTokens - reserveTokens - this.instructionTokens\n );\n\n return {\n maxContextTokens,\n instructionTokens: this.instructionTokens,\n systemMessageTokens: this.systemMessageTokens,\n dynamicInstructionTokens: this.dynamicInstructionTokens,\n toolSchemaTokens: this.toolSchemaTokens,\n summaryTokens: this.summaryTokenCount,\n toolCount,\n messageCount,\n messageTokens,\n availableForMessages,\n toolTokenCounts:\n this.toolTokenCounts != null ? { ...this.toolTokenCounts } : undefined,\n deferredToolNames:\n this.deferredToolNames.length > 0\n ? [...this.deferredToolNames]\n : undefined,\n };\n }\n\n /**\n * Returns a human-readable string of the token budget breakdown\n * for inclusion in error messages and diagnostics.\n */\n formatTokenBudgetBreakdown(messages?: BaseMessage[]): string {\n const b = this.getTokenBudgetBreakdown(messages);\n const lines = [\n 'Token budget breakdown:',\n ` maxContextTokens: ${b.maxContextTokens}`,\n ` instructionTokens: ${b.instructionTokens} (system: ${b.systemMessageTokens}, dynamic: ${b.dynamicInstructionTokens}, tools: ${b.toolSchemaTokens} [${b.toolCount} tools])`,\n ` summaryTokens: ${b.summaryTokens}`,\n ` messageTokens: ${b.messageTokens} (${b.messageCount} messages)`,\n ` availableForMessages: ${b.availableForMessages}`,\n ];\n return lines.join('\\n');\n }\n\n /**\n * Projects the context-usage snapshot for an arbitrary message set WITHOUT\n * invoking the model — the pre-send / page-load / window-switch counterpart to\n * the live `ON_CONTEXT_USAGE` snapshot. Runs the same pruner + budget math the\n * graph uses (`createPruneMessages` → `getTokenBudgetBreakdown` →\n * `syncBudgetDerivedFields`) so projected numbers match a real call. Returns\n * null when the context lacks the tokenizer or window needed to prune. Omits\n * the live post-format reconciliation (provider-specific, invoke-time) — a\n * small, acceptable delta for a pre-send estimate.\n *\n * Safe to call off the hot path: the supplied `messages` are never mutated\n * (each is passed as a clone — the pruner both replaces tool-result slots and\n * unshifts reasoning blocks into AI content arrays in place), and this\n * context's own state is untouched apart from refreshing stale instruction\n * counts (idempotent, exactly what a real call does). Token counts are\n * recounted for the supplied messages (the context's `indexTokenCountMap` is\n * keyed to the live run's branch and would missum an arbitrary branch) unless\n * the caller passes a map it guarantees matches. Calibration is NOT re-derived\n * from this context's live usage (a fresh pruner would compare the prior\n * call's provider input against the whole projected branch); the learned\n * `calibrationRatio` is applied as a static seed, and callers may override it\n * with a persisted ratio via `opts.calibrationRatio`.\n */\n projectContextUsage(\n messages: BaseMessage[],\n opts?: {\n runId?: string;\n agentId?: string;\n calibrationRatio?: number;\n indexTokenCountMap?: Record<string, number | undefined>;\n }\n ): t.ContextUsageEvent | null {\n const tokenCounter = this.tokenCounter;\n if (tokenCounter == null || this.maxContextTokens == null) {\n return null;\n }\n /** Refresh stale system overhead (handoff/summary changes) so instruction\n * tokens match the prompt a real call would send. */\n this.initializeSystemRunnable();\n /** Clone array-content messages: the pruner unshifts reasoning blocks into\n * AI content arrays in place, which would otherwise corrupt the caller's\n * history. (Slot replacements land on the mapped array, not the caller's.) */\n const projected = messages.map((message) =>\n Array.isArray(message.content)\n ? cloneMessage(message, [...message.content])\n : message\n );\n let indexTokenCountMap = opts?.indexTokenCountMap;\n if (indexTokenCountMap == null) {\n indexTokenCountMap = {};\n for (let i = 0; i < messages.length; i++) {\n indexTokenCountMap[String(i)] = tokenCounter(messages[i]);\n }\n }\n const prune = createPruneMessages({\n startIndex: 0,\n provider: this.provider,\n tokenCounter,\n maxTokens: this.maxContextTokens,\n thinkingEnabled: isThinkingEnabled(this.provider, this.clientOptions),\n indexTokenCountMap,\n contextPruningConfig: this.contextPruningConfig,\n summarizationEnabled: this.summarizationEnabled,\n reserveRatio: this.summarizationConfig?.reserveRatio,\n calibrationRatio: opts?.calibrationRatio ?? this.calibrationRatio,\n getInstructionTokens: () => this.instructionTokens,\n });\n const {\n context,\n prePruneContextTokens,\n remainingContextTokens,\n contextBudget,\n effectiveInstructionTokens,\n calibrationRatio,\n } = prune({\n messages: projected,\n usageMetadata: undefined,\n lastCallUsage: undefined,\n totalTokensFresh: false,\n });\n const breakdown = this.getTokenBudgetBreakdown(messages);\n breakdown.messageCount = context.length;\n const usage: t.ContextUsageEvent = {\n runId: opts?.runId,\n agentId: opts?.agentId,\n breakdown,\n contextBudget,\n effectiveInstructionTokens,\n prePruneContextTokens,\n remainingContextTokens,\n calibrationRatio,\n };\n syncBudgetDerivedFields(usage);\n return usage;\n }\n\n /**\n * Updates the last-call usage with data from the most recent LLM response.\n * Unlike `currentUsage` which accumulates, this captures only the single call.\n */\n updateLastCallUsage(usage: Partial<UsageMetadata>): void {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation =\n Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const outputTokens = Number(usage.output_tokens) || 0;\n const cacheSum = cacheCreation + cacheRead;\n const cacheIsAdditive = cacheSum > 0 && cacheSum > baseInputTokens;\n const totalInputTokens = cacheIsAdditive\n ? baseInputTokens + cacheSum\n : baseInputTokens;\n\n this.lastCallUsage = {\n inputTokens: totalInputTokens,\n outputTokens,\n totalTokens: totalInputTokens + outputTokens,\n cacheRead: cacheRead || undefined,\n cacheCreation: cacheCreation || undefined,\n };\n this.totalTokensFresh = true;\n }\n\n /** Marks token data as stale before a new LLM call. */\n markTokensStale(): void {\n this.totalTokensFresh = false;\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 /** Refresh schema token accounting so the next call's budget and\n * per-tool breakdown include the newly discovered tools; awaited\n * via tokenCalculationPromise before the next model call */\n if (this.tokenCounter) {\n this.tokenCalculationPromise = this.calculateInstructionTokens(\n this.tokenCounter\n );\n }\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * In event-driven mode (toolDefinitions present, tools empty), creates schema-only tools.\n * Otherwise filters tool instances based on:\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.toolDefinitions && this.toolDefinitions.length > 0) {\n return this.getEventDrivenToolsForBinding();\n }\n\n const filtered = this.getEffectiveInstanceTools();\n\n if (this.graphTools && this.graphTools.length > 0) {\n return [...(filtered ?? []), ...this.graphTools];\n }\n\n return filtered;\n }\n\n /** Creates schema-only tools from toolDefinitions for event-driven mode, merged with native tools */\n private getEventDrivenToolsForBinding(): t.GraphTools {\n if (!this.toolDefinitions) {\n return this.graphTools ?? [];\n }\n\n const schemaTools = createSchemaOnlyTools(\n this.getActiveToolDefinitions()\n ) as t.GraphTools;\n\n const allTools = [...schemaTools];\n\n if (this.graphTools && this.graphTools.length > 0) {\n allTools.push(...this.graphTools);\n }\n\n const instanceTools = this.getEffectiveInstanceTools();\n if (instanceTools && instanceTools.length > 0) {\n allTools.push(...instanceTools);\n }\n\n return allTools;\n }\n\n /** Filters tool instances for binding based on registry config */\n private filterToolsForBinding(tools: t.GraphTools): t.GraphTools {\n return tools.filter((tool) => {\n if (!('name' in tool)) {\n return true;\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true;\n }\n\n if (this.discoveredToolNames.has(tool.name)) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmDA,IAAa,eAAb,MAAa,aAAa;;;;CAIxB,OAAO,WACL,aACA,cACA,oBACc;EACd,MAAM,EACJ,SACA,MACA,UACA,eACA,UACA,OACA,SACA,SACA,cACA,iBACA,cACA,yBACA,cACA,kBACA,cACA,kBACA,iBACA,sBACA,qBACA,gBACA,sBACA,oBACA,kBACA,iBACA,qBACE;EAEJ,MAAM,eAAe,IAAI,aAAa;GACpC;GACA,MAAM,QAAQ;GACd;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,wBAAwB;GACxB;GACA;GACA,mBAAmB;GACnB;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;EAED,aAAa,gBAAgB;EAC7B,aAAa,kBAAkB;EAC/B,aAAa,mBAAmB;EAEhC,IAAI,gBAAgB,QAAQ,QAAQ,eAAe,SAAS,IAC1D,aAAa,kBACX,eAAe,MACf,eAAe,UACjB;EAGF,IAAI,cAAc;GAChB,aAAa,yBAAyB;GAEtC,MAAM,WAAW,sBAAsB,CAAC;GACx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GACjC,oBAAoB;EACtB;EAEF,IAAI,mBAAmB;GACrB,KAAK,sBAAsB;;;;GAI3B,IAAI,KAAK,cACP,KAAK,0BAA0B,KAAK,2BAClC,KAAK,YACP;EAEJ;EACA,OAAO;CACT;;;;;;;;;CAUA,qBAA+C;EAC7C,IAAI,KAAK,mBAAmB,KAAK,gBAAgB,SAAS,GACxD,OAAO,KAAK,8BAA8B;EAG5C,MAAM,WAAW,KAAK,0BAA0B;EAEhD,IAAI,KAAK,cAAc,KAAK,WAAW,SAAS,GAC9C,OAAO,CAAC,GAAI,YAAY,CAAC,GAAI,GAAG,KAAK,UAAU;EAGjD,OAAO;CACT;;CAGA,gCAAsD;EACpD,IAAI,CAAC,KAAK,iBACR,OAAO,KAAK,cAAc,CAAC;EAO7B,MAAM,WAAW,CAAC,GAJE,sBAClB,KAAK,yBAAyB,CAGD,CAAC;EAEhC,IAAI,KAAK,cAAc,KAAK,WAAW,SAAS,GAC9C,SAAS,KAAK,GAAG,KAAK,UAAU;EAGlC,MAAM,gBAAgB,KAAK,0BAA0B;EACrD,IAAI,iBAAiB,cAAc,SAAS,GAC1C,SAAS,KAAK,GAAG,aAAa;EAGhC,OAAO;CACT;;CAGA,sBAA8B,OAAmC;EAC/D,OAAO,MAAM,QAAQ,SAAS;GAC5B,IAAI,EAAE,UAAU,OACd,OAAO;GAGT,MAAM,UAAU,KAAK,cAAc,IAAI,KAAK,IAAI;GAChD,IAAI,CAAC,SACH,OAAO;GAGT,IAAI,KAAK,oBAAoB,IAAI,KAAK,IAAI,GAExC,QADuB,QAAQ,mBAAmB,CAAC,QAAQ,EAAA,CACrC,SAAS,QAAQ;GAIzC,QADuB,QAAQ,mBAAmB,CAAC,QAAQ,EAAA,CAE1C,SAAS,QAAQ,KAAK,QAAQ,kBAAkB;EAEnE,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"AgentContext.mjs","names":[],"sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport { HumanMessage, SystemMessage } from '@langchain/core/messages';\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 {\n addTailCacheControl,\n addCacheControlToStablePrefixMessages,\n buildAnthropicCacheControl,\n buildBedrockCachePoint,\n resolvePromptCacheTtl,\n cloneMessage,\n type PromptCacheTtl,\n} from '@/messages/cache';\nimport {\n ANTHROPIC_TOOL_TOKEN_MULTIPLIER,\n DEFAULT_TOOL_TOKEN_MULTIPLIER,\n ContentTypes,\n Constants,\n Providers,\n} from '@/common';\nimport {\n DEFAULT_RESERVE_RATIO,\n createPruneMessages,\n syncBudgetDerivedFields,\n} from '@/messages';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { apportionTokenCounts } from '@/utils/tokens';\nimport { isThinkingEnabled } from '@/llm/request';\nimport { toJsonSchema } from '@/utils/schema';\n\ntype AgentSystemTextBlock = {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral'; ttl?: '1h' };\n};\n\ntype AgentSystemContentBlock =\n | AgentSystemTextBlock\n | { cachePoint: { type: 'default'; ttl?: '1h' } };\n\ntype PromptCacheProvider = Providers.ANTHROPIC | Providers.OPENROUTER;\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 name,\n provider,\n clientOptions,\n langfuse,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n toolDefinitions,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n initialSummary,\n contextPruningConfig,\n maxToolResultChars,\n toolSchemaTokens,\n subagentConfigs,\n maxSubagentDepth,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n name: name ?? agentId,\n provider,\n clientOptions,\n langfuse,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n });\n\n agentContext._sourceInputs = agentConfig;\n agentContext.subagentConfigs = subagentConfigs;\n agentContext.maxSubagentDepth = maxSubagentDepth;\n\n if (initialSummary?.text != null && initialSummary.text !== '') {\n agentContext.setInitialSummary(\n initialSummary.text,\n initialSummary.tokenCount\n );\n }\n\n if (tokenCounter) {\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.baseIndexTokenCountMap = { ...tokenMap };\n agentContext.indexTokenCountMap = tokenMap;\n\n if (toolSchemaTokens != null && toolSchemaTokens > 0) {\n /** Use pre-computed (cached) tool schema tokens — skip calculateInstructionTokens */\n agentContext.toolSchemaTokens = toolSchemaTokens;\n agentContext.tokenCalculationPromise = Promise.resolve();\n agentContext.updateTokenMapWithInstructions(tokenMap);\n } else {\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n }\n } else if (indexTokenCountMap) {\n agentContext.baseIndexTokenCountMap = { ...indexTokenCountMap };\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */\n name?: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Per-agent Langfuse tracing configuration. */\n langfuse?: t.LangfuseConfig;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Canonical pre-run token map used to restore token accounting on reset */\n baseIndexTokenCountMap: Record<string, number> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /**\n * Usage from the most recent LLM call only (not accumulated).\n * Used for accurate provider calibration in pruning.\n */\n lastCallUsage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheRead?: number;\n cacheCreation?: number;\n };\n /**\n * Whether totalTokens data is fresh (set true when provider usage arrives,\n * false at the start of each turn before the LLM responds).\n * Prevents stale token data from driving pruning/trigger decisions.\n */\n totalTokensFresh: boolean = false;\n /** Context pruning configuration. */\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\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 /** Token count for the system message (instructions text). */\n systemMessageTokens: number = 0;\n /** Token count for instruction text emitted outside the system message. */\n dynamicInstructionTokens: number = 0;\n /** Token count for tool schemas only. */\n toolSchemaTokens: number = 0;\n /** Per-tool schema token counts (post-multiplier), keyed by tool name.\n * `undefined` when not calculated (e.g. cached aggregate schema tokens). */\n toolTokenCounts?: Record<string, number>;\n /** Names of counted tools that are deferred (`defer_loading`) and discovered. */\n deferredToolNames: string[] = [];\n /** Running calibration ratio from the pruner — persisted across runs via contextMeta. */\n calibrationRatio: number = 1;\n /** Provider-observed instruction overhead from the pruner's best-variance turn. */\n resolvedInstructionOverhead?: number;\n /** Pre-masking tool content keyed by message index, consumed by the summarize node. */\n pendingOriginalToolContent?: Map<number, string>;\n\n /** Total instruction overhead: system message + tool schemas + pending summary. */\n get instructionTokens(): number {\n const summaryOverhead =\n this._summaryLocation === 'user_message' ? this.summaryTokenCount : 0;\n return (\n this.systemMessageTokens +\n this.dynamicInstructionTokens +\n this.toolSchemaTokens +\n summaryOverhead\n );\n }\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 /** Graph-managed tools (e.g., handoff tools created by MultiAgentGraph) that bypass event-driven dispatch */\n graphTools?: 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 /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode.\n */\n toolDefinitions?: t.LCTool[];\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */\n _sourceInputs?: t.AgentInputs;\n /** Subagent configurations for hierarchical delegation. */\n subagentConfigs?: t.SubagentConfig[];\n /** Maximum subagent nesting depth. */\n maxSubagentDepth?: number;\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: 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 /** Tracks how many reasoning→text transitions have occurred (ensures unique post-reasoning step keys) */\n reasoningTransitionCount = 0;\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 /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Enables graph-level summarization for this agent */\n summarizationEnabled?: boolean;\n /** Summarization runtime settings used by graph pruning hooks */\n summarizationConfig?: t.SummarizationConfig;\n /** Current summary text produced by the summarize node, integrated into system message */\n private summaryText?: string;\n /** Token count of the current summary (tracked for token accounting) */\n private summaryTokenCount: number = 0;\n /**\n * Where the summary should be injected:\n * - `'system_prompt'`: cross-run summary, included in the dynamic system tail\n * - `'user_message'`: mid-run compaction, injected as HumanMessage on clean slate\n * - `'none'`: no summary present\n */\n private _summaryLocation: 'system_prompt' | 'user_message' | 'none' = 'none';\n /**\n * Durable summary that survives reset() calls. Set from initialSummary\n * during fromConfig() and updated by setSummary() so that the latest\n * summary (whether cross-run or intra-run) is always restored after\n * processStream's resetValues() cycle.\n */\n private _durableSummaryText?: string;\n private _durableSummaryTokenCount: number = 0;\n /** Number of summarization cycles that have occurred for this agent context */\n private _summaryVersion: number = 0;\n /**\n * Message count at the time summarization was last triggered.\n * Used to prevent re-summarizing the same unchanged message set.\n * Summarization is allowed to fire again only when new messages appear.\n */\n private _lastSummarizationMsgCount: number = 0;\n /**\n * Handoff context when this agent receives control via handoff.\n * Contains source and parallel execution info for system message context.\n */\n handoffContext?: {\n /** Source agent that transferred control */\n sourceAgentName: string;\n /** Names of sibling agents executing in parallel (empty if sequential) */\n parallelSiblings: string[];\n };\n\n constructor({\n agentId,\n name,\n provider,\n clientOptions,\n langfuse,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n }: {\n agentId: string;\n name?: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n langfuse?: t.LangfuseConfig;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n toolDefinitions?: t.LCTool[];\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n discoveredTools?: string[];\n summarizationEnabled?: boolean;\n summarizationConfig?: t.SummarizationConfig;\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\n }) {\n this.agentId = agentId;\n this.name = name;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.langfuse = langfuse;\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.toolDefinitions = toolDefinitions;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.systemMessageTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n this.summarizationEnabled = summarizationEnabled;\n this.summarizationConfig = summarizationConfig;\n this.contextPruningConfig = contextPruningConfig;\n this.maxToolResultChars = maxToolResultChars;\n\n if (discoveredTools && discoveredTools.length > 0) {\n for (const toolName of discoveredTools) {\n this.discoveredToolNames.add(toolName);\n }\n }\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 * configured programmatic 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 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 programmaticTool = this.getProgrammaticToolInstructionTarget();\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 \\`${programmaticTool.name}\\` tool. ` +\n `You cannot call these tools directly; instead, use \\`${programmaticTool.name}\\` with ${programmaticTool.language} code that invokes them.\\n\\n` +\n toolDescriptions\n );\n }\n\n private getProgrammaticToolInstructionTarget(): {\n name: string;\n language: 'bash' | 'Python';\n } {\n if (this.hasAvailableTool(Constants.BASH_PROGRAMMATIC_TOOL_CALLING)) {\n return {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n language: 'bash',\n };\n }\n\n if (this.hasAvailableTool(Constants.PROGRAMMATIC_TOOL_CALLING)) {\n return { name: Constants.PROGRAMMATIC_TOOL_CALLING, language: 'Python' };\n }\n\n return { name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING, language: 'bash' };\n }\n\n private hasAvailableTool(name: string): boolean {\n if (this.toolDefinitions?.some((tool) => tool.name === name) === true)\n return true;\n if (\n this.tools?.some((tool) => 'name' in tool && tool.name === name) === true\n ) {\n return true;\n }\n if (this.toolMap?.has(name) === true) return true;\n return this.toolRegistry?.has(name) === true;\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes stable instructions, dynamic additional instructions, and\n * 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 if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n this.cachedSystemRunnable = this.buildSystemRunnable({\n stableInstructions: this.buildStableInstructionsString(),\n dynamicInstructions: this.buildDynamicInstructionsString(),\n });\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 this.cachedSystemRunnable = this.buildSystemRunnable({\n stableInstructions: this.buildStableInstructionsString(),\n dynamicInstructions: this.buildDynamicInstructionsString(),\n });\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the cacheable instructions string (without creating SystemMessage).\n * Includes agent identity preamble and handoff context when available.\n */\n private buildStableInstructionsString(): string {\n const parts: string[] = [];\n\n const identityPreamble = this.buildIdentityPreamble();\n if (identityPreamble) {\n parts.push(identityPreamble);\n }\n\n if (this.instructions != null && this.instructions !== '') {\n parts.push(this.instructions);\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n parts.push(programmaticToolsDoc);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the dynamic system-tail string (without creating SystemMessage).\n * Keep this out of prompt-cache-marked content so volatile context does not\n * invalidate the stable prefix.\n */\n private buildDynamicInstructionsString(): string {\n const parts: string[] = [];\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n parts.push(this.additionalInstructions);\n }\n\n // Cross-run summary: include in the system tail so the model has context\n // from the prior run without invalidating the cacheable prefix. Mid-run\n // summaries are injected as a HumanMessage on the post-compaction clean\n // slate instead (see buildSystemRunnable).\n if (\n this._summaryLocation === 'system_prompt' &&\n this.summaryText != null &&\n this.summaryText !== ''\n ) {\n parts.push('## Conversation Summary\\n\\n' + this.summaryText);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the agent identity preamble including handoff context if present.\n * This helps the agent understand its role in the multi-agent workflow.\n */\n private buildIdentityPreamble(): string {\n if (!this.handoffContext) return '';\n\n const displayName = this.name ?? this.agentId;\n const { sourceAgentName, parallelSiblings } = this.handoffContext;\n const isParallel = parallelSiblings.length > 0;\n\n const lines: string[] = [];\n lines.push('## Multi-Agent Workflow');\n lines.push(\n `You are \"${displayName}\", transferred from \"${sourceAgentName}\".`\n );\n\n if (isParallel) {\n lines.push(`Running in parallel with: ${parallelSiblings.join(', ')}.`);\n }\n\n lines.push(\n 'Execute only tasks relevant to your role. Routing is already handled if requested, unless you can route further.'\n );\n\n return lines.join('\\n');\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 stableInstructions,\n dynamicInstructions,\n }: {\n stableInstructions: string;\n dynamicInstructions: string;\n }):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n const hasMidRunSummary =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n if (!stableInstructions && !dynamicInstructions && !hasMidRunSummary) {\n this.systemMessageTokens = 0;\n this.dynamicInstructionTokens = 0;\n return undefined;\n }\n\n const promptCacheProvider = this.getPromptCacheProvider();\n const shouldMoveDynamicInstructions =\n promptCacheProvider != null &&\n stableInstructions !== '' &&\n dynamicInstructions !== '';\n const systemMessage = this.buildSystemMessage({\n stableInstructions,\n dynamicInstructions,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n });\n\n if (this.tokenCounter) {\n this.systemMessageTokens = systemMessage\n ? this.tokenCounter(systemMessage)\n : 0;\n this.dynamicInstructionTokens = shouldMoveDynamicInstructions\n ? this.tokenCounter(new HumanMessage(dynamicInstructions))\n : 0;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n const prefix: BaseMessage[] = systemMessage ? [systemMessage] : [];\n\n // Build the non-system portion (summary + conversation), then apply\n // cache markers separately so addCacheControl doesn't strip the\n // SystemMessage's own cache_control breakpoint set above.\n const hasSummaryBody =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n const bodyWithSummary =\n hasSummaryBody && promptCacheProvider == null\n ? [this.buildSummaryHumanMessage(promptCacheProvider), ...messages]\n : messages;\n const dynamicTail = this.buildPromptCacheDynamicTail({\n dynamicInstructions,\n hasSummaryBody,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n });\n let body = this.buildBodyWithPromptCacheDynamicTail(\n bodyWithSummary,\n dynamicTail,\n promptCacheProvider\n );\n\n if (\n promptCacheProvider != null &&\n dynamicTail.length === 0 &&\n body.length >= 2\n ) {\n body = addTailCacheControl(\n body,\n this.getPromptCacheTtl(promptCacheProvider)\n );\n }\n return [...prefix, ...body];\n }).withConfig({ runName: 'prompt' });\n }\n\n private buildSummaryHumanMessage(\n promptCacheProvider: PromptCacheProvider | undefined\n ): HumanMessage {\n const wrappedSummary =\n '<summary>\\n' +\n (this.summaryText as string) +\n '\\n</summary>\\n\\n' +\n 'This is your own checkpoint: you wrote it to preserve context after compaction. Pick up where you left off based on the summary above. Do not repeat prior tasks, information or acknowledge this checkpoint message directly.';\n\n if (promptCacheProvider !== Providers.ANTHROPIC) {\n return new HumanMessage(wrappedSummary);\n }\n\n return new HumanMessage({\n content: [\n {\n type: 'text',\n text: wrappedSummary,\n cache_control: buildAnthropicCacheControl(\n this.getPromptCacheTtl(Providers.ANTHROPIC)\n ),\n },\n ],\n });\n }\n\n private buildPromptCacheDynamicTail({\n dynamicInstructions,\n hasSummaryBody,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n }: {\n dynamicInstructions: string;\n hasSummaryBody: boolean;\n promptCacheProvider: PromptCacheProvider | undefined;\n shouldMoveDynamicInstructions: boolean;\n }): BaseMessage[] {\n if (promptCacheProvider == null) {\n return [];\n }\n\n const dynamicTail = shouldMoveDynamicInstructions\n ? [new HumanMessage(dynamicInstructions)]\n : [];\n\n if (!hasSummaryBody) {\n return dynamicTail;\n }\n\n return [...dynamicTail, this.buildSummaryHumanMessage(undefined)];\n }\n\n private buildBodyWithPromptCacheDynamicTail(\n messages: BaseMessage[],\n tail: BaseMessage[],\n promptCacheProvider: PromptCacheProvider | undefined\n ): BaseMessage[] {\n if (tail.length === 0) {\n return messages;\n }\n\n const tailIndex = this.getPromptCacheDynamicTailIndex(\n messages,\n promptCacheProvider\n );\n const stablePrefix = messages.slice(0, tailIndex);\n const trailingMessages = messages.slice(tailIndex);\n const cacheablePrefix = this.addStablePromptCacheMarkers(\n stablePrefix,\n this.getPromptCacheTtl(promptCacheProvider)\n );\n\n return [...cacheablePrefix, ...tail, ...trailingMessages];\n }\n\n private getPromptCacheDynamicTailIndex(\n messages: BaseMessage[],\n promptCacheProvider: PromptCacheProvider | undefined\n ): number {\n const lastIndex = messages.length - 1;\n\n if (lastIndex < 0) {\n return 0;\n }\n\n if (promptCacheProvider === Providers.OPENROUTER && messages.length === 1) {\n return messages.length;\n }\n\n for (let index = lastIndex; index >= 0; index--) {\n if (messages[index].getType() === 'human') {\n if (promptCacheProvider === Providers.OPENROUTER && index === 0) {\n return 1;\n }\n return index;\n }\n }\n\n return messages.length;\n }\n\n private addStablePromptCacheMarkers(\n messages: BaseMessage[],\n ttl?: PromptCacheTtl\n ): BaseMessage[] {\n if (messages.length <= 1) {\n return messages;\n }\n\n return [\n messages[0],\n ...addCacheControlToStablePrefixMessages(messages.slice(1), 2, ttl),\n ];\n }\n\n private getPromptCacheProvider(): PromptCacheProvider | undefined {\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n return anthropicOptions?.promptCache === true\n ? Providers.ANTHROPIC\n : undefined;\n }\n\n if (this.provider === Providers.OPENROUTER) {\n const openRouterOptions = this.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined;\n return openRouterOptions?.promptCache === true\n ? Providers.OPENROUTER\n : undefined;\n }\n\n return undefined;\n }\n\n private hasBedrockPromptCache(): boolean {\n if (this.provider !== Providers.BEDROCK) {\n return false;\n }\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n // Nova accepts system/message cachePoints (only the tool checkpoint is\n // Claude-only), so this is gated on promptCache alone.\n return bedrockOptions?.promptCache === true;\n }\n\n /**\n * Resolved TTL for the active prompt-cache provider (Anthropic or OpenRouter).\n * Both expose `promptCacheTtl` and use the Anthropic `cache_control` format, so\n * the configured value resolves the same way (default `'1h'` extended cache).\n */\n private getPromptCacheTtl(\n provider: PromptCacheProvider | undefined\n ): PromptCacheTtl | undefined {\n if (provider == null) {\n return undefined;\n }\n return resolvePromptCacheTtl(\n (this.clientOptions as { promptCacheTtl?: PromptCacheTtl } | undefined)\n ?.promptCacheTtl\n );\n }\n\n /**\n * Resolved TTL for Bedrock prompt-cache checkpoints (default `'1h'`).\n * Models that don't support the 1-hour TTL downgrade to 5m server-side.\n */\n private getBedrockPromptCacheTtl(): PromptCacheTtl {\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n return resolvePromptCacheTtl(bedrockOptions?.promptCacheTtl);\n }\n\n private buildSystemMessage({\n stableInstructions,\n dynamicInstructions,\n promptCacheProvider,\n shouldMoveDynamicInstructions,\n }: {\n stableInstructions: string;\n dynamicInstructions: string;\n promptCacheProvider: PromptCacheProvider | undefined;\n shouldMoveDynamicInstructions: boolean;\n }): SystemMessage | undefined {\n if (!stableInstructions && !dynamicInstructions) {\n return undefined;\n }\n\n if (promptCacheProvider === Providers.ANTHROPIC) {\n const content: AgentSystemContentBlock[] = [];\n if (stableInstructions) {\n content.push({\n type: 'text',\n text: stableInstructions,\n cache_control: buildAnthropicCacheControl(\n this.getPromptCacheTtl(promptCacheProvider)\n ),\n });\n }\n if (dynamicInstructions && !shouldMoveDynamicInstructions) {\n content.push({ type: 'text', text: dynamicInstructions });\n }\n return new SystemMessage({ content } as BaseMessageFields);\n }\n\n if (promptCacheProvider === Providers.OPENROUTER && !stableInstructions) {\n return new SystemMessage(dynamicInstructions);\n }\n\n if (promptCacheProvider === Providers.OPENROUTER) {\n return new SystemMessage({\n content: [\n {\n type: 'text',\n text: stableInstructions,\n cache_control: buildAnthropicCacheControl(\n this.getPromptCacheTtl(promptCacheProvider)\n ),\n },\n ],\n } as BaseMessageFields);\n }\n\n if (this.hasBedrockPromptCache() && stableInstructions) {\n const content: AgentSystemContentBlock[] = [\n { type: 'text', text: stableInstructions },\n { cachePoint: buildBedrockCachePoint(this.getBedrockPromptCacheTtl()) },\n ];\n if (dynamicInstructions) {\n content.push({ type: 'text', text: dynamicInstructions });\n }\n return new SystemMessage({ content } as BaseMessageFields);\n }\n\n return new SystemMessage(\n [stableInstructions, dynamicInstructions]\n .filter((part) => part !== '')\n .join('\\n\\n')\n );\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.systemMessageTokens = 0;\n this.dynamicInstructionTokens = 0;\n this.toolSchemaTokens = 0;\n this.toolTokenCounts = undefined;\n this.deferredToolNames = [];\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = { ...this.baseIndexTokenCountMap };\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.reasoningTransitionCount = 0;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n this.handoffContext = undefined;\n\n this.summaryText = this._durableSummaryText;\n this.summaryTokenCount = this._durableSummaryTokenCount;\n this._lastSummarizationMsgCount = 0;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n\n if (this.tokenCounter) {\n this.initializeSystemRunnable();\n const baseTokenMap = { ...this.baseIndexTokenCountMap };\n this.indexTokenCountMap = baseTokenMap;\n this.tokenCalculationPromise = this.calculateInstructionTokens(\n this.tokenCounter\n )\n .then(() => {\n this.updateTokenMapWithInstructions(baseTokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else {\n this.tokenCalculationPromise = undefined;\n }\n }\n\n /**\n * Update the token count map from a base map.\n *\n * Previously this inflated index 0 with instructionTokens to indirectly\n * reserve budget for the system prompt. That approach was imprecise: with\n * large tool-schema overhead (e.g. 26 MCP tools ~5 000 tokens) the first\n * conversation message appeared enormous and was always pruned, while the\n * real available budget was never explicitly computed.\n *\n * Now instruction tokens are passed to getMessagesWithinTokenLimit via\n * the `getInstructionTokens` factory param so the pruner subtracts them\n * from the budget directly. The token map contains only real per-message\n * token counts.\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n\n /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */\n private getActiveToolDefinitions(): t.LCTool[] {\n if (!this.toolDefinitions) {\n return [];\n }\n /**\n * Mirror `getEventDrivenToolsForBinding`'s gate: a definition is only\n * bound to the model when its `allowed_callers` include `'direct'` and\n * (if deferred) it has been discovered. Filtering by `defer_loading`\n * alone left programmatic-only definitions counted in\n * `toolSchemaTokens` even though they were never bound.\n */\n return this.toolDefinitions.filter((def) => {\n const allowedCallers = def.allowed_callers ?? ['direct'];\n if (!allowedCallers.includes('direct')) {\n return false;\n }\n return (\n def.defer_loading !== true || this.discoveredToolNames.has(def.name)\n );\n });\n }\n\n /**\n * Single source of truth for \"which entries of `this.tools` should be\n * treated as actually bound\". Callers:\n * - `getToolsForBinding` (non-event-driven branch)\n * - `getEventDrivenToolsForBinding` (appends instance tools alongside\n * schema-only definitions)\n * - `calculateInstructionTokens` (counts schema bytes for accounting)\n *\n * In event-driven mode (`toolDefinitions` present) instance tools are\n * appended unfiltered; outside event-driven mode they pass through\n * `filterToolsForBinding`. Centralizing the decision here prevents the\n * accounting/binding paths from drifting apart, which was the root\n * cause of the original miscount.\n */\n private getEffectiveInstanceTools(): t.GraphTools | undefined {\n if (!this.tools) {\n return undefined;\n }\n const isEventDriven = (this.toolDefinitions?.length ?? 0) > 0;\n if (isEventDriven || !this.toolRegistry) {\n return this.tools;\n }\n return this.filterToolsForBinding(this.tools);\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n const countedToolNames = new Set<string>();\n /** Prototype-free: external tool names like `toString` must not hit\n * inherited properties during accumulation */\n const rawToolTokenCounts: Record<string, number> = Object.create(null);\n const deferredCountedNames = new Set<string>();\n\n /**\n * Iterate both `tools` (user-provided instance tools) and `graphTools`\n * (graph-managed tools like handoff + subagent). `graphTools` is often\n * populated after `fromConfig()` kicks off the initial calculation, so\n * callers that mutate `graphTools` must re-trigger this method to\n * refresh `toolSchemaTokens`.\n *\n * Use `getEffectiveInstanceTools()` so accounting reflects exactly the\n * subset that `getToolsForBinding` would emit — preventing the\n * worst-case-ceiling miscount that triggered spurious `empty_messages`\n * preflight rejections at low `maxContextTokens`. Deferred and\n * non-`'direct'` `toolDefinitions` are excluded by\n * `getActiveToolDefinitions()` below.\n */\n const instanceTools: t.GraphTools = [\n ...((this.getEffectiveInstanceTools() as t.GenericTool[] | undefined) ??\n []),\n ...((this.graphTools as t.GenericTool[] | undefined) ?? []),\n ];\n\n if (instanceTools.length > 0) {\n for (const tool of instanceTools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const toolName = (genericTool.name as string | undefined) ?? '';\n const jsonSchema = toJsonSchema(\n genericTool.schema,\n toolName,\n (genericTool.description as string | undefined) ?? ''\n );\n const schemaTokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n toolTokens += schemaTokens;\n if (toolName) {\n countedToolNames.add(toolName);\n rawToolTokenCounts[toolName] =\n (rawToolTokenCounts[toolName] ?? 0) + schemaTokens;\n }\n }\n }\n }\n\n for (const def of this.getActiveToolDefinitions()) {\n if (countedToolNames.has(def.name)) {\n continue;\n }\n const schema = {\n type: 'function',\n function: {\n name: def.name,\n description: def.description ?? '',\n parameters: def.parameters ?? {},\n },\n };\n const schemaTokens = tokenCounter(\n new SystemMessage(JSON.stringify(schema))\n );\n toolTokens += schemaTokens;\n countedToolNames.add(def.name);\n rawToolTokenCounts[def.name] =\n (rawToolTokenCounts[def.name] ?? 0) + schemaTokens;\n if (def.defer_loading === true) {\n deferredCountedNames.add(def.name);\n }\n }\n\n const isAnthropic =\n this.provider !== Providers.BEDROCK &&\n (this.provider === Providers.ANTHROPIC ||\n /anthropic|claude/i.test(\n String(\n (this.clientOptions as { model?: string } | undefined)?.model ?? ''\n )\n ));\n const toolTokenMultiplier = isAnthropic\n ? ANTHROPIC_TOOL_TOKEN_MULTIPLIER\n : DEFAULT_TOOL_TOKEN_MULTIPLIER;\n this.toolSchemaTokens = Math.ceil(toolTokens * toolTokenMultiplier);\n\n /** Largest-remainder apportionment keeps the per-tool counts summing\n * exactly to the aggregate despite per-entry rounding */\n const toolTokenCounts = apportionTokenCounts(\n rawToolTokenCounts,\n toolTokenMultiplier,\n this.toolSchemaTokens\n );\n const deferredToolNames: string[] = [];\n for (const name of Object.keys(rawToolTokenCounts)) {\n if (\n deferredCountedNames.has(name) ||\n this.toolRegistry?.get(name)?.defer_loading === true\n ) {\n deferredToolNames.push(name);\n }\n }\n this.toolTokenCounts = toolTokenCounts;\n this.deferredToolNames = deferredToolNames;\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 * Sets the handoff context for this agent.\n * Call this when the agent receives control via handoff from another agent.\n * Marks system runnable as stale to include handoff context in system message.\n * @param sourceAgentName - Name of the agent that transferred control\n * @param parallelSiblings - Names of other agents executing in parallel with this one\n */\n setHandoffContext(sourceAgentName: string, parallelSiblings: string[]): void {\n this.handoffContext = { sourceAgentName, parallelSiblings };\n this.systemRunnableStale = true;\n }\n\n /**\n * Clears any handoff context.\n * Call this when resetting the agent or when handoff context is no longer relevant.\n */\n clearHandoffContext(): void {\n if (this.handoffContext) {\n this.handoffContext = undefined;\n this.systemRunnableStale = true;\n }\n }\n\n setSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'user_message';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n this.pruneMessages = undefined;\n }\n\n /** Sets a cross-run summary that is injected into the system prompt. */\n setInitialSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'system_prompt';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n }\n\n /**\n * Replaces the indexTokenCountMap with a fresh map keyed to the surviving\n * context messages after summarization. Called by the summarize node after\n * it emits RemoveMessage operations that shift message indices.\n */\n rebuildTokenMapAfterSummarization(newTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = newTokenMap;\n this.baseIndexTokenCountMap = { ...newTokenMap };\n this._lastSummarizationMsgCount = Object.keys(newTokenMap).length;\n this.currentUsage = undefined;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n }\n\n hasSummary(): boolean {\n return this.summaryText != null && this.summaryText !== '';\n }\n\n /** True when a mid-run compaction summary is ready to be injected as a HumanMessage. */\n hasPendingCompactionSummary(): boolean {\n return this._summaryLocation === 'user_message' && this.hasSummary();\n }\n\n getSummaryText(): string | undefined {\n return this.summaryText;\n }\n\n get summaryVersion(): number {\n return this._summaryVersion;\n }\n\n /**\n * Returns true when the message count hasn't changed since the last\n * summarization — re-summarizing would produce an identical result.\n * Oversized individual messages are handled by fit-to-budget truncation\n * in the pruner, which keeps them in context without triggering overflow.\n */\n shouldSkipSummarization(currentMsgCount: number): boolean {\n return (\n this._lastSummarizationMsgCount > 0 &&\n currentMsgCount <= this._lastSummarizationMsgCount\n );\n }\n\n /**\n * Records the message count at which summarization was triggered,\n * so subsequent calls with the same count are suppressed.\n */\n markSummarizationTriggered(msgCount: number): void {\n this._lastSummarizationMsgCount = msgCount;\n }\n\n clearSummary(): void {\n if (this.summaryText != null) {\n this.summaryText = undefined;\n this.summaryTokenCount = 0;\n this._durableSummaryText = undefined;\n this._durableSummaryTokenCount = 0;\n this._summaryLocation = 'none';\n this.systemRunnableStale = true;\n }\n }\n\n /**\n * Returns a structured breakdown of how the context token budget is consumed.\n * Useful for diagnostics when context overflow or pruning issues occur.\n *\n * Note: `markToolsAsDiscovered` re-triggers `calculateInstructionTokens`,\n * so `toolSchemaTokens`/`toolTokenCounts` refresh before the next call.\n */\n getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown {\n const maxContextTokens = this.maxContextTokens ?? 0;\n /**\n * Derive `toolCount` from `getToolsForBinding()` so the diagnostic stays\n * aligned with what is actually bound to the model — and with what\n * `calculateInstructionTokens` counts into `toolSchemaTokens`. Using raw\n * `this.tools.length` would inflate the count whenever the registry\n * marks instance tools as deferred-undiscovered or non-`'direct'`,\n * producing the same misleading \"N tools\" diagnostic this fix is meant\n * to eliminate.\n */\n const toolCount = this.getToolsForBinding()?.length ?? 0;\n const messageCount = messages?.length ?? 0;\n\n let messageTokens = 0;\n if (messages != null) {\n for (let i = 0; i < messages.length; i++) {\n messageTokens +=\n (this.indexTokenCountMap[i] as number | undefined) ?? 0;\n }\n }\n\n /** Mirror the pruner's reserve math so availableForMessages agrees\n * with the contextBudget computed during pruning */\n const reserveRatio =\n this.summarizationConfig?.reserveRatio ?? DEFAULT_RESERVE_RATIO;\n const reserveTokens =\n reserveRatio > 0 && reserveRatio < 1\n ? Math.round(maxContextTokens * reserveRatio)\n : 0;\n const availableForMessages = Math.max(\n 0,\n maxContextTokens - reserveTokens - this.instructionTokens\n );\n\n return {\n maxContextTokens,\n instructionTokens: this.instructionTokens,\n systemMessageTokens: this.systemMessageTokens,\n dynamicInstructionTokens: this.dynamicInstructionTokens,\n toolSchemaTokens: this.toolSchemaTokens,\n summaryTokens: this.summaryTokenCount,\n toolCount,\n messageCount,\n messageTokens,\n availableForMessages,\n toolTokenCounts:\n this.toolTokenCounts != null ? { ...this.toolTokenCounts } : undefined,\n deferredToolNames:\n this.deferredToolNames.length > 0\n ? [...this.deferredToolNames]\n : undefined,\n };\n }\n\n /**\n * Returns a human-readable string of the token budget breakdown\n * for inclusion in error messages and diagnostics.\n */\n formatTokenBudgetBreakdown(messages?: BaseMessage[]): string {\n const b = this.getTokenBudgetBreakdown(messages);\n const lines = [\n 'Token budget breakdown:',\n ` maxContextTokens: ${b.maxContextTokens}`,\n ` instructionTokens: ${b.instructionTokens} (system: ${b.systemMessageTokens}, dynamic: ${b.dynamicInstructionTokens}, tools: ${b.toolSchemaTokens} [${b.toolCount} tools])`,\n ` summaryTokens: ${b.summaryTokens}`,\n ` messageTokens: ${b.messageTokens} (${b.messageCount} messages)`,\n ` availableForMessages: ${b.availableForMessages}`,\n ];\n return lines.join('\\n');\n }\n\n /**\n * Projects the context-usage snapshot for an arbitrary message set WITHOUT\n * invoking the model — the pre-send / page-load / window-switch counterpart to\n * the live `ON_CONTEXT_USAGE` snapshot. Runs the same pruner + budget math the\n * graph uses (`createPruneMessages` → `getTokenBudgetBreakdown` →\n * `syncBudgetDerivedFields`) so projected numbers match a real call. Returns\n * null when the context lacks the tokenizer or window needed to prune. Omits\n * the live post-format reconciliation (provider-specific, invoke-time) — a\n * small, acceptable delta for a pre-send estimate.\n *\n * Safe to call off the hot path: the supplied `messages` are never mutated\n * (each is passed as a clone — the pruner both replaces tool-result slots and\n * unshifts reasoning blocks into AI content arrays in place), and this\n * context's own state is untouched apart from refreshing stale instruction\n * counts (idempotent, exactly what a real call does). Token counts are\n * recounted for the supplied messages (the context's `indexTokenCountMap` is\n * keyed to the live run's branch and would missum an arbitrary branch) unless\n * the caller passes a map it guarantees matches. Calibration is NOT re-derived\n * from this context's live usage (a fresh pruner would compare the prior\n * call's provider input against the whole projected branch); the learned\n * `calibrationRatio` is applied as a static seed, and callers may override it\n * with a persisted ratio via `opts.calibrationRatio`.\n */\n projectContextUsage(\n messages: BaseMessage[],\n opts?: {\n runId?: string;\n agentId?: string;\n calibrationRatio?: number;\n indexTokenCountMap?: Record<string, number | undefined>;\n }\n ): t.ContextUsageEvent | null {\n const tokenCounter = this.tokenCounter;\n if (tokenCounter == null || this.maxContextTokens == null) {\n return null;\n }\n /** Refresh stale system overhead (handoff/summary changes) so instruction\n * tokens match the prompt a real call would send. */\n this.initializeSystemRunnable();\n /** Clone array-content messages: the pruner unshifts reasoning blocks into\n * AI content arrays in place, which would otherwise corrupt the caller's\n * history. (Slot replacements land on the mapped array, not the caller's.) */\n const projected = messages.map((message) =>\n Array.isArray(message.content)\n ? cloneMessage(message, [...message.content])\n : message\n );\n let indexTokenCountMap = opts?.indexTokenCountMap;\n if (indexTokenCountMap == null) {\n indexTokenCountMap = {};\n for (let i = 0; i < messages.length; i++) {\n indexTokenCountMap[String(i)] = tokenCounter(messages[i]);\n }\n }\n const prune = createPruneMessages({\n startIndex: 0,\n provider: this.provider,\n tokenCounter,\n maxTokens: this.maxContextTokens,\n thinkingEnabled: isThinkingEnabled(this.provider, this.clientOptions),\n indexTokenCountMap,\n contextPruningConfig: this.contextPruningConfig,\n summarizationEnabled: this.summarizationEnabled,\n reserveRatio: this.summarizationConfig?.reserveRatio,\n calibrationRatio: opts?.calibrationRatio ?? this.calibrationRatio,\n getInstructionTokens: () => this.instructionTokens,\n });\n const {\n context,\n prePruneContextTokens,\n remainingContextTokens,\n contextBudget,\n effectiveInstructionTokens,\n calibrationRatio,\n } = prune({\n messages: projected,\n usageMetadata: undefined,\n lastCallUsage: undefined,\n totalTokensFresh: false,\n });\n const breakdown = this.getTokenBudgetBreakdown(messages);\n breakdown.messageCount = context.length;\n const usage: t.ContextUsageEvent = {\n runId: opts?.runId,\n agentId: opts?.agentId,\n breakdown,\n contextBudget,\n effectiveInstructionTokens,\n prePruneContextTokens,\n remainingContextTokens,\n calibrationRatio,\n };\n syncBudgetDerivedFields(usage);\n return usage;\n }\n\n /**\n * Updates the last-call usage with data from the most recent LLM response.\n * Unlike `currentUsage` which accumulates, this captures only the single call.\n */\n updateLastCallUsage(usage: Partial<UsageMetadata>): void {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation =\n Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const outputTokens = Number(usage.output_tokens) || 0;\n const cacheSum = cacheCreation + cacheRead;\n const cacheIsAdditive = cacheSum > 0 && cacheSum > baseInputTokens;\n const totalInputTokens = cacheIsAdditive\n ? baseInputTokens + cacheSum\n : baseInputTokens;\n\n this.lastCallUsage = {\n inputTokens: totalInputTokens,\n outputTokens,\n totalTokens: totalInputTokens + outputTokens,\n cacheRead: cacheRead || undefined,\n cacheCreation: cacheCreation || undefined,\n };\n this.totalTokensFresh = true;\n }\n\n /** Marks token data as stale before a new LLM call. */\n markTokensStale(): void {\n this.totalTokensFresh = false;\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 /** Refresh schema token accounting so the next call's budget and\n * per-tool breakdown include the newly discovered tools; awaited\n * via tokenCalculationPromise before the next model call */\n if (this.tokenCounter) {\n this.tokenCalculationPromise = this.calculateInstructionTokens(\n this.tokenCounter\n );\n }\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * In event-driven mode (toolDefinitions present, tools empty), creates schema-only tools.\n * Otherwise filters tool instances based on:\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.toolDefinitions && this.toolDefinitions.length > 0) {\n return this.getEventDrivenToolsForBinding();\n }\n\n const filtered = this.getEffectiveInstanceTools();\n\n if (this.graphTools && this.graphTools.length > 0) {\n return [...(filtered ?? []), ...this.graphTools];\n }\n\n return filtered;\n }\n\n /** Creates schema-only tools from toolDefinitions for event-driven mode, merged with native tools */\n private getEventDrivenToolsForBinding(): t.GraphTools {\n if (!this.toolDefinitions) {\n return this.graphTools ?? [];\n }\n\n const schemaTools = createSchemaOnlyTools(\n this.getActiveToolDefinitions()\n ) as t.GraphTools;\n\n const allTools = [...schemaTools];\n\n if (this.graphTools && this.graphTools.length > 0) {\n allTools.push(...this.graphTools);\n }\n\n const instanceTools = this.getEffectiveInstanceTools();\n if (instanceTools && instanceTools.length > 0) {\n allTools.push(...instanceTools);\n }\n\n return allTools;\n }\n\n /** Filters tool instances for binding based on registry config */\n private filterToolsForBinding(tools: t.GraphTools): t.GraphTools {\n return tools.filter((tool) => {\n if (!('name' in tool)) {\n return true;\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true;\n }\n\n if (this.discoveredToolNames.has(tool.name)) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmDA,IAAa,eAAb,MAAa,aAAa;;;;CAIxB,OAAO,WACL,aACA,cACA,oBACc;EACd,MAAM,EACJ,SACA,MACA,UACA,eACA,UACA,OACA,SACA,SACA,cACA,iBACA,cACA,yBACA,cACA,kBACA,cACA,kBACA,iBACA,sBACA,qBACA,gBACA,sBACA,oBACA,kBACA,iBACA,qBACE;EAEJ,MAAM,eAAe,IAAI,aAAa;GACpC;GACA,MAAM,QAAQ;GACd;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,wBAAwB;GACxB;GACA;GACA,mBAAmB;GACnB;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;EAED,aAAa,gBAAgB;EAC7B,aAAa,kBAAkB;EAC/B,aAAa,mBAAmB;EAEhC,IAAI,gBAAgB,QAAQ,QAAQ,eAAe,SAAS,IAC1D,aAAa,kBACX,eAAe,MACf,eAAe,UACjB;EAGF,IAAI,cAAc;GAChB,aAAa,yBAAyB;GAEtC,MAAM,WAAW,sBAAsB,CAAC;GACxC,aAAa,yBAAyB,EAAE,GAAG,SAAS;GACpD,aAAa,qBAAqB;GAElC,IAAI,oBAAoB,QAAQ,mBAAmB,GAAG;;IAEpD,aAAa,mBAAmB;IAChC,aAAa,0BAA0B,QAAQ,QAAQ;IACvD,aAAa,+BAA+B,QAAQ;GACtD,OACE,aAAa,0BAA0B,aACpC,2BAA2B,YAAY,CAAC,CACxC,WAAW;IACV,aAAa,+BAA+B,QAAQ;GACtD,CAAC,CAAC,CACD,OAAO,QAAQ;IACd,QAAQ,MAAM,yCAAyC,GAAG;GAC5D,CAAC;EAEP,OAAO,IAAI,oBAAoB;GAC7B,aAAa,yBAAyB,EAAE,GAAG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AAsD;EACpD,IAAI,CAAC,KAAK,iBACR,OAAO,KAAK,cAAc,CAAC;EAO7B,MAAM,WAAW,CAAC,GAJE,sBAClB,KAAK,yBAAyB,CAGD,CAAC;EAEhC,IAAI,KAAK,cAAc,KAAK,WAAW,SAAS,GAC9C,SAAS,KAAK,GAAG,KAAK,UAAU;EAGlC,MAAM,gBAAgB,KAAK,0BAA0B;EACrD,IAAI,iBAAiB,cAAc,SAAS,GAC1C,SAAS,KAAK,GAAG,aAAa;EAGhC,OAAO;CACT;;CAGA,sBAA8B,OAAmC;EAC/D,OAAO,MAAM,QAAQ,SAAS;GAC5B,IAAI,EAAE,UAAU,OACd,OAAO;GAGT,MAAM,UAAU,KAAK,cAAc,IAAI,KAAK,IAAI;GAChD,IAAI,CAAC,SACH,OAAO;GAGT,IAAI,KAAK,oBAAoB,IAAI,KAAK,IAAI,GAExC,QADuB,QAAQ,mBAAmB,CAAC,QAAQ,EAAA,CACrC,SAAS,QAAQ;GAIzC,QADuB,QAAQ,mBAAmB,CAAC,QAAQ,EAAA,CAE1C,SAAS,QAAQ,KAAK,QAAQ,kBAAkB;EAEnE,CAAC;CACH;AACF"}
@@ -11,7 +11,7 @@ import { createPruneMessages, enforceOriginalContentCap, sanitizeOrphanToolBlock
11
11
  import { syncBudgetDerivedFields } from "../messages/budget.mjs";
12
12
  import { emitAgentLog, safeDispatchCustomEvent } from "../utils/events.mjs";
13
13
  import { ensureThinkingBlockInMessages } from "../messages/format.mjs";
14
- import { addBedrockTailCacheControl, addTailCacheControl, resolvePromptCacheTtl } from "../messages/cache.mjs";
14
+ import { addBedrockTailCacheControl, addTailCacheControl, resolvePromptCacheTtl, supportsBedrockToolCache } from "../messages/cache.mjs";
15
15
  import { makeIsDeferred, partitionAndMarkAnthropicToolCache } from "../messages/anthropicToolCache.mjs";
16
16
  import { formatContentStrings, isLegacyConvertible } from "../messages/content.mjs";
17
17
  import { extractToolDiscoveries } from "../messages/tools.mjs";
@@ -760,7 +760,10 @@ var StandardGraph = class StandardGraph extends Graph {
760
760
  let toolsForBinding = rawToolsForBinding;
761
761
  if (agentContext.provider === "anthropic" && agentContext.clientOptions?.promptCache === true) toolsForBinding = partitionAndMarkAnthropicToolCache(rawToolsForBinding, makeIsDeferred(agentContext.toolDefinitions), resolvePromptCacheTtl(agentContext.clientOptions?.promptCacheTtl)) ?? rawToolsForBinding;
762
762
  else if (agentContext.provider === "openrouter" && agentContext.clientOptions?.promptCache === true) toolsForBinding = partitionAndMarkOpenRouterToolCache(rawToolsForBinding, makeIsDeferred(agentContext.toolDefinitions), resolvePromptCacheTtl(agentContext.clientOptions?.promptCacheTtl)) ?? rawToolsForBinding;
763
- else if (agentContext.provider === "bedrock" && agentContext.clientOptions?.promptCache === true) toolsForBinding = partitionAndMarkBedrockToolCache(rawToolsForBinding, makeIsDeferred(agentContext.toolDefinitions)) ?? rawToolsForBinding;
763
+ else if (agentContext.provider === "bedrock" && agentContext.clientOptions?.promptCache === true) {
764
+ const bedrockModel = agentContext.clientOptions?.model;
765
+ if (bedrockModel == null || supportsBedrockToolCache(bedrockModel)) toolsForBinding = partitionAndMarkBedrockToolCache(rawToolsForBinding, makeIsDeferred(agentContext.toolDefinitions)) ?? rawToolsForBinding;
766
+ }
764
767
  let model = this.overrideModel ?? initializeModel({
765
768
  tools: toolsForBinding,
766
769
  provider: agentContext.provider,