@librechat/agents 3.1.80-dev.2 → 3.1.80

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 (42) hide show
  1. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +27 -7
  2. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  3. package/dist/cjs/llm/vertexai/index.cjs +52 -0
  4. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  5. package/dist/cjs/main.cjs +1 -2
  6. package/dist/cjs/main.cjs.map +1 -1
  7. package/dist/cjs/tools/BashExecutor.cjs +20 -78
  8. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  9. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +5 -1
  10. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  11. package/dist/cjs/tools/CodeExecutor.cjs +26 -106
  12. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  13. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +12 -31
  14. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  15. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +27 -8
  16. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  17. package/dist/esm/llm/vertexai/index.mjs +53 -2
  18. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  19. package/dist/esm/main.mjs +1 -1
  20. package/dist/esm/tools/BashExecutor.mjs +20 -78
  21. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  22. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +6 -2
  23. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  24. package/dist/esm/tools/CodeExecutor.mjs +26 -105
  25. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  26. package/dist/esm/tools/ProgrammaticToolCalling.mjs +12 -31
  27. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  28. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +15 -3
  29. package/dist/types/llm/vertexai/index.d.ts +29 -0
  30. package/dist/types/tools/CodeExecutor.d.ts +1 -7
  31. package/dist/types/tools/ProgrammaticToolCalling.d.ts +5 -0
  32. package/package.json +10 -5
  33. package/src/llm/anthropic/utils/message_inputs.ts +58 -7
  34. package/src/llm/anthropic/utils/tool-id-normalization.test.ts +178 -0
  35. package/src/llm/vertexai/index.ts +69 -2
  36. package/src/llm/vertexai/llm.spec.ts +18 -0
  37. package/src/llm/vertexai/repairUsageMetadata.test.ts +54 -0
  38. package/src/tools/BashExecutor.ts +24 -104
  39. package/src/tools/BashProgrammaticToolCalling.ts +7 -2
  40. package/src/tools/CodeExecutor.ts +30 -133
  41. package/src/tools/ProgrammaticToolCalling.ts +14 -49
  42. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +32 -131
@@ -1,7 +1,42 @@
1
1
  import { ChatGoogle } from '@langchain/google-gauth';
2
2
  import { ChatConnection } from '@langchain/google-common';
3
- import { isAIMessage } from '@langchain/core/messages';
3
+ import { AIMessageChunk, isAIMessage } from '@langchain/core/messages';
4
4
 
5
+ /**
6
+ * `@langchain/google-common`'s `_streamResponseChunks` emits usage on TWO
7
+ * different paths within the same stream:
8
+ *
9
+ * - Streaming chunks set `chunk.generationInfo.usage_metadata` via
10
+ * `responseToUsageMetadata`, which correctly sums
11
+ * `candidatesTokenCount + thoughtsTokenCount` and includes
12
+ * `output_token_details.reasoning`.
13
+ * - The trailing fallback chunk (emitted after the API stream exhausts)
14
+ * attaches its own `chunk.message.usage_metadata` built inline as
15
+ * `output_tokens = candidatesTokenCount` only — dropping
16
+ * `thoughtsTokenCount` and `output_token_details` entirely.
17
+ *
18
+ * After `AIMessageChunk.concat`, only `message.usage_metadata` survives —
19
+ * which is the buggy fallback value. This breaks the documented
20
+ * `total_tokens === input_tokens + output_tokens` invariant and silently
21
+ * undercharges thinking models for reasoning tokens.
22
+ *
23
+ * The repair: track the last `generationInfo.usage_metadata` we see, and
24
+ * when the fallback chunk arrives with its buggy `message.usage_metadata`,
25
+ * replace it with the tracked good value. `CustomChatGoogleGenerativeAI`
26
+ * solves the same problem for the Google API path differently — by
27
+ * overriding `_convertToUsageMetadata`.
28
+ */
29
+ function repairStreamUsageMetadata(current, generationInfoUsage) {
30
+ if (!current)
31
+ return current;
32
+ if (!generationInfoUsage)
33
+ return current;
34
+ if (generationInfoUsage.total_tokens !== current.total_tokens)
35
+ return current;
36
+ if (generationInfoUsage.output_tokens <= current.output_tokens)
37
+ return current;
38
+ return generationInfoUsage;
39
+ }
5
40
  /**
6
41
  * Fixes thought signatures on functionCall parts in the formatted Gemini request.
7
42
  *
@@ -390,6 +425,22 @@ class ChatVertexAI extends ChatGoogle {
390
425
  }
391
426
  return params;
392
427
  }
428
+ async *_streamResponseChunks(messages, options, runManager) {
429
+ let lastGoodUsage;
430
+ for await (const chunk of super._streamResponseChunks(messages, options, runManager)) {
431
+ const genUsage = chunk.generationInfo?.usage_metadata;
432
+ if (genUsage) {
433
+ lastGoodUsage = genUsage;
434
+ }
435
+ if (chunk.message instanceof AIMessageChunk) {
436
+ const repaired = repairStreamUsageMetadata(chunk.message.usage_metadata, lastGoodUsage);
437
+ if (repaired !== chunk.message.usage_metadata) {
438
+ chunk.message.usage_metadata = repaired;
439
+ }
440
+ }
441
+ yield chunk;
442
+ }
443
+ }
393
444
  buildConnection(fields, client) {
394
445
  // Note: buildConnection is called from super() BEFORE this.thinkingConfig is set,
395
446
  // so we must read thinkingConfig from `fields` directly.
@@ -403,5 +454,5 @@ class ChatVertexAI extends ChatGoogle {
403
454
  }
404
455
  }
405
456
 
406
- export { ChatVertexAI };
457
+ export { ChatVertexAI, repairStreamUsageMetadata };
407
458
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../../src/llm/vertexai/index.ts"],"sourcesContent":["import { ChatGoogle } from '@langchain/google-gauth';\nimport { ChatConnection } from '@langchain/google-common';\nimport type {\n GeminiContent,\n GeminiRequest,\n GoogleAIModelRequestParams,\n GoogleAbstractedClient,\n} from '@langchain/google-common';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { isAIMessage } from '@langchain/core/messages';\nimport type { GoogleThinkingConfig, VertexAIClientOptions } from '@/types';\n\ntype AdditionalKwargs =\n | undefined\n | (BaseMessage['additional_kwargs'] & {\n signatures?: Array<string | undefined>;\n });\n\n/**\n * Fixes thought signatures on functionCall parts in the formatted Gemini request.\n *\n * `@langchain/google-common` stores signatures as a flat array in\n * `additional_kwargs.signatures` (one per response part) and re-attaches them\n * by index only when `signatures.length === parts.length`. This fails when:\n * - The API omits a signature (length mismatch)\n * - Streaming chunks merge with different part counts\n * - The signature for a functionCall part is an empty string\n *\n * This function correlates each \"model\" content block in the formatted request\n * back to its originating AI message, then re-attaches non-empty signatures\n * that the library failed to apply.\n */\nfunction fixThoughtSignatures(\n contents: GeminiContent[],\n input: BaseMessage[]\n): void {\n // Collect AI messages that have signatures, in order\n const aiMessages = input.filter(\n (msg) =>\n isAIMessage(msg) &&\n Array.isArray((msg.additional_kwargs as AdditionalKwargs)?.signatures) &&\n (msg.additional_kwargs.signatures as string[]).length > 0\n );\n\n // Collect \"model\" content blocks from the formatted request, in order\n const modelContents = contents.filter((c) => c.role === 'model');\n\n // They should correspond 1:1 in order (both derived from the same input sequence)\n const count = Math.min(aiMessages.length, modelContents.length);\n for (let i = 0; i < count; i++) {\n const msg = aiMessages[i];\n const content = modelContents[i];\n const signatures = (msg.additional_kwargs as AdditionalKwargs)?.signatures;\n\n // Collect non-empty signatures that aren't already attached to any part\n const attachedSignatures = new Set(\n content.parts\n .map((p) => p.thoughtSignature)\n .filter((s): s is string => s != null && s !== '')\n );\n const availableSignatures = signatures?.filter(\n (s) => s != null && s !== '' && !attachedSignatures.has(s)\n );\n\n // Assign available signatures to functionCall parts missing one, in order\n let sigIdx = 0;\n for (const part of content.parts) {\n if (\n 'functionCall' in part &&\n (part.thoughtSignature == null || part.thoughtSignature === '') &&\n sigIdx < (availableSignatures?.length ?? 0)\n ) {\n part.thoughtSignature = availableSignatures?.[sigIdx];\n sigIdx++;\n }\n }\n }\n}\n\nclass CustomChatConnection extends ChatConnection<VertexAIClientOptions> {\n thinkingConfig?: GoogleThinkingConfig;\n\n async formatData(\n input: BaseMessage[],\n parameters: GoogleAIModelRequestParams\n ): Promise<unknown> {\n const formattedData = (await super.formatData(\n input,\n parameters\n )) as GeminiRequest;\n if (formattedData.generationConfig?.thinkingConfig?.thinkingBudget === -1) {\n // -1 means \"let the model decide\" - delete the property so the API doesn't receive an invalid value\n if (\n formattedData.generationConfig.thinkingConfig.includeThoughts === false\n ) {\n formattedData.generationConfig.thinkingConfig.includeThoughts = true;\n }\n delete formattedData.generationConfig.thinkingConfig.thinkingBudget;\n }\n if (this.thinkingConfig?.thinkingLevel != null) {\n formattedData.generationConfig ??= {};\n // thinkingLevel and thinkingBudget cannot coexist — the API rejects the request.\n // Remove thinkingBudget when thinkingLevel is set.\n const { thinkingBudget: _, ...existingThinkingConfig } =\n (formattedData.generationConfig.thinkingConfig as\n | Record<string, unknown>\n | undefined) ?? {};\n (\n formattedData.generationConfig as Record<string, unknown>\n ).thinkingConfig = {\n ...existingThinkingConfig,\n thinkingLevel: this.thinkingConfig.thinkingLevel,\n ...(this.thinkingConfig.includeThoughts != null && {\n includeThoughts: this.thinkingConfig.includeThoughts,\n }),\n };\n }\n if (formattedData.contents) {\n fixThoughtSignatures(formattedData.contents, input);\n // gemini-3.1+ models reject role=\"function\"; convert to role=\"user\"\n for (const content of formattedData.contents) {\n if (content.role === 'function') {\n (content as { role: string }).role = 'user';\n }\n }\n }\n return formattedData;\n }\n}\n\n/**\n * Integration with Google Vertex AI chat models.\n *\n * Setup:\n * Install `@langchain/google-vertexai` and set your stringified\n * Vertex AI credentials as an environment variable named `GOOGLE_APPLICATION_CREDENTIALS`.\n *\n * ```bash\n * npm install @langchain/google-vertexai\n * export GOOGLE_APPLICATION_CREDENTIALS=\"path/to/credentials\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/_langchain_google_vertexai.index.ChatVertexAI.html#constructor.new_ChatVertexAI)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_common_types.GoogleAIBaseLanguageModelCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n * stop: [\"\\n\"],\n * tools: [...],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatVertexAI } from '@langchain/google-vertexai';\n *\n * const llm = new ChatVertexAI({\n * model: \"gemini-1.5-pro\",\n * temperature: 0,\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\\nHere's why this is the best translation:\\n\\n* **J'adore** means \\\"I love\\\" and conveys a strong passion.\\n* **Programmer** is the French verb for \\\"to program.\\\"\\n\\nThis translation is natural and idiomatic in French. \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 63,\n * \"total_tokens\": 72\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York City, NY' },\n * id: '33c1c1f47e2f492799c77d2800a43912',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: 'What do you call a cat that loves to bowl?',\n * punchline: 'An alley cat!'\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatVertexAI extends ChatGoogle {\n lc_namespace = ['langchain', 'chat_models', 'vertexai'];\n dynamicThinkingBudget = false;\n thinkingConfig?: GoogleThinkingConfig;\n\n static lc_name(): 'LibreChatVertexAI' {\n return 'LibreChatVertexAI';\n }\n\n constructor(model: string, fields?: Omit<VertexAIClientOptions, 'model'>);\n constructor(fields?: VertexAIClientOptions);\n constructor(\n modelOrFields?: string | VertexAIClientOptions,\n params?: Omit<VertexAIClientOptions, 'model'>\n ) {\n const fields =\n typeof modelOrFields === 'string'\n ? { ...(params ?? {}), model: modelOrFields }\n : modelOrFields;\n const dynamicThinkingBudget = fields?.thinkingBudget === -1;\n super({\n ...fields,\n platformType: 'gcp',\n });\n this.dynamicThinkingBudget = dynamicThinkingBudget;\n this.thinkingConfig = fields?.thinkingConfig;\n }\n invocationParams(\n options?: this['ParsedCallOptions'] | undefined\n ): GoogleAIModelRequestParams {\n const params = super.invocationParams(options);\n if (this.dynamicThinkingBudget) {\n params.maxReasoningTokens = -1;\n }\n return params;\n }\n buildConnection(\n fields: VertexAIClientOptions | undefined,\n client: GoogleAbstractedClient\n ): void {\n // Note: buildConnection is called from super() BEFORE this.thinkingConfig is set,\n // so we must read thinkingConfig from `fields` directly.\n const thinkingConfig = fields?.thinkingConfig ?? this.thinkingConfig;\n\n const connection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n connection.thinkingConfig = thinkingConfig;\n this.connection = connection;\n\n const streamedConnection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n streamedConnection.thinkingConfig = thinkingConfig;\n this.streamedConnection = streamedConnection;\n }\n}\n"],"names":[],"mappings":";;;;AAkBA;;;;;;;;;;;;;AAaG;AACH,SAAS,oBAAoB,CAC3B,QAAyB,EACzB,KAAoB,EAAA;;AAGpB,IAAA,MAAM,UAAU,GAAG,KAAK,CAAC,MAAM,CAC7B,CAAC,GAAG,KACF,WAAW,CAAC,GAAG,CAAC;QAChB,KAAK,CAAC,OAAO,CAAE,GAAG,CAAC,iBAAsC,EAAE,UAAU,CAAC;QACrE,GAAG,CAAC,iBAAiB,CAAC,UAAuB,CAAC,MAAM,GAAG,CAAC,CAC5D;;AAGD,IAAA,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC;;AAGhE,IAAA,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC;AAC/D,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;AAC9B,QAAA,MAAM,GAAG,GAAG,UAAU,CAAC,CAAC,CAAC;AACzB,QAAA,MAAM,OAAO,GAAG,aAAa,CAAC,CAAC,CAAC;AAChC,QAAA,MAAM,UAAU,GAAI,GAAG,CAAC,iBAAsC,EAAE,UAAU;;AAG1E,QAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAChC,OAAO,CAAC;aACL,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,gBAAgB;AAC7B,aAAA,MAAM,CAAC,CAAC,CAAC,KAAkB,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC,CACrD;QACD,MAAM,mBAAmB,GAAG,UAAU,EAAE,MAAM,CAC5C,CAAC,CA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,IAAI,MAAM,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,aAAa;cACzC,aAAa;QACnB,MAAM,qBAAqB,GAAG,MAAM,EAAE,cAAc,KAAK,EAAE;AAC3D,QAAA,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,YAAY,EAAE,KAAK;AACpB,SAAA,CAAC;AACF,QAAA,IAAI,CAAC,qBAAqB,GAAG,qBAAqB;AAClD,QAAA,IAAI,CAAC,cAAc,GAAG,MAAM,EAAE,cAAc;IAC9C;AACA,IAAA,gBAAgB,CACd,OAA+C,EAAA;QAE/C,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC;AAC9C,QAAA,IAAI,IAAI,CAAC,qBAAqB,EAAE;AAC9B,YAAA,MAAM,CAAC,kBAAkB,GAAG,EAAE;QAChC;AACA,QAAA,OAAO,MAAM;IACf;IACA,eAAe,CACb,MAAyC,EACzC,MAA8B,EAAA;;;QAI9B,MAAM,cAAc,GAAG,MAAM,EAAE,cAAc,IAAI,IAAI,CAAC,cAAc;QAEpE,MAAM,UAAU,GAAG,IAAI,oBAAoB,CACzC,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,KAAK,CACN;AACD,QAAA,UAAU,CAAC,cAAc,GAAG,cAAc;AAC1C,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;QAE5B,MAAM,kBAAkB,GAAG,IAAI,oBAAoB,CACjD,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,IAAI,CACL;AACD,QAAA,kBAAkB,CAAC,cAAc,GAAG,cAAc;AAClD,QAAA,IAAI,CAAC,kBAAkB,GAAG,kBAAkB;IAC9C;AACD;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../../src/llm/vertexai/index.ts"],"sourcesContent":["import { ChatGoogle } from '@langchain/google-gauth';\nimport { ChatConnection } from '@langchain/google-common';\nimport type {\n GeminiContent,\n GeminiRequest,\n GoogleAIModelRequestParams,\n GoogleAbstractedClient,\n} from '@langchain/google-common';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport { AIMessageChunk, isAIMessage } from '@langchain/core/messages';\nimport type { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { GoogleThinkingConfig, VertexAIClientOptions } from '@/types';\n\n/**\n * `@langchain/google-common`'s `_streamResponseChunks` emits usage on TWO\n * different paths within the same stream:\n *\n * - Streaming chunks set `chunk.generationInfo.usage_metadata` via\n * `responseToUsageMetadata`, which correctly sums\n * `candidatesTokenCount + thoughtsTokenCount` and includes\n * `output_token_details.reasoning`.\n * - The trailing fallback chunk (emitted after the API stream exhausts)\n * attaches its own `chunk.message.usage_metadata` built inline as\n * `output_tokens = candidatesTokenCount` only — dropping\n * `thoughtsTokenCount` and `output_token_details` entirely.\n *\n * After `AIMessageChunk.concat`, only `message.usage_metadata` survives —\n * which is the buggy fallback value. This breaks the documented\n * `total_tokens === input_tokens + output_tokens` invariant and silently\n * undercharges thinking models for reasoning tokens.\n *\n * The repair: track the last `generationInfo.usage_metadata` we see, and\n * when the fallback chunk arrives with its buggy `message.usage_metadata`,\n * replace it with the tracked good value. `CustomChatGoogleGenerativeAI`\n * solves the same problem for the Google API path differently — by\n * overriding `_convertToUsageMetadata`.\n */\nexport function repairStreamUsageMetadata(\n current: UsageMetadata | undefined,\n generationInfoUsage: UsageMetadata | undefined\n): UsageMetadata | undefined {\n if (!current) return current;\n if (!generationInfoUsage) return current;\n if (generationInfoUsage.total_tokens !== current.total_tokens) return current;\n if (generationInfoUsage.output_tokens <= current.output_tokens)\n return current;\n return generationInfoUsage;\n}\n\ntype AdditionalKwargs =\n | undefined\n | (BaseMessage['additional_kwargs'] & {\n signatures?: Array<string | undefined>;\n });\n\n/**\n * Fixes thought signatures on functionCall parts in the formatted Gemini request.\n *\n * `@langchain/google-common` stores signatures as a flat array in\n * `additional_kwargs.signatures` (one per response part) and re-attaches them\n * by index only when `signatures.length === parts.length`. This fails when:\n * - The API omits a signature (length mismatch)\n * - Streaming chunks merge with different part counts\n * - The signature for a functionCall part is an empty string\n *\n * This function correlates each \"model\" content block in the formatted request\n * back to its originating AI message, then re-attaches non-empty signatures\n * that the library failed to apply.\n */\nfunction fixThoughtSignatures(\n contents: GeminiContent[],\n input: BaseMessage[]\n): void {\n // Collect AI messages that have signatures, in order\n const aiMessages = input.filter(\n (msg) =>\n isAIMessage(msg) &&\n Array.isArray((msg.additional_kwargs as AdditionalKwargs)?.signatures) &&\n (msg.additional_kwargs.signatures as string[]).length > 0\n );\n\n // Collect \"model\" content blocks from the formatted request, in order\n const modelContents = contents.filter((c) => c.role === 'model');\n\n // They should correspond 1:1 in order (both derived from the same input sequence)\n const count = Math.min(aiMessages.length, modelContents.length);\n for (let i = 0; i < count; i++) {\n const msg = aiMessages[i];\n const content = modelContents[i];\n const signatures = (msg.additional_kwargs as AdditionalKwargs)?.signatures;\n\n // Collect non-empty signatures that aren't already attached to any part\n const attachedSignatures = new Set(\n content.parts\n .map((p) => p.thoughtSignature)\n .filter((s): s is string => s != null && s !== '')\n );\n const availableSignatures = signatures?.filter(\n (s) => s != null && s !== '' && !attachedSignatures.has(s)\n );\n\n // Assign available signatures to functionCall parts missing one, in order\n let sigIdx = 0;\n for (const part of content.parts) {\n if (\n 'functionCall' in part &&\n (part.thoughtSignature == null || part.thoughtSignature === '') &&\n sigIdx < (availableSignatures?.length ?? 0)\n ) {\n part.thoughtSignature = availableSignatures?.[sigIdx];\n sigIdx++;\n }\n }\n }\n}\n\nclass CustomChatConnection extends ChatConnection<VertexAIClientOptions> {\n thinkingConfig?: GoogleThinkingConfig;\n\n async formatData(\n input: BaseMessage[],\n parameters: GoogleAIModelRequestParams\n ): Promise<unknown> {\n const formattedData = (await super.formatData(\n input,\n parameters\n )) as GeminiRequest;\n if (formattedData.generationConfig?.thinkingConfig?.thinkingBudget === -1) {\n // -1 means \"let the model decide\" - delete the property so the API doesn't receive an invalid value\n if (\n formattedData.generationConfig.thinkingConfig.includeThoughts === false\n ) {\n formattedData.generationConfig.thinkingConfig.includeThoughts = true;\n }\n delete formattedData.generationConfig.thinkingConfig.thinkingBudget;\n }\n if (this.thinkingConfig?.thinkingLevel != null) {\n formattedData.generationConfig ??= {};\n // thinkingLevel and thinkingBudget cannot coexist — the API rejects the request.\n // Remove thinkingBudget when thinkingLevel is set.\n const { thinkingBudget: _, ...existingThinkingConfig } =\n (formattedData.generationConfig.thinkingConfig as\n | Record<string, unknown>\n | undefined) ?? {};\n (\n formattedData.generationConfig as Record<string, unknown>\n ).thinkingConfig = {\n ...existingThinkingConfig,\n thinkingLevel: this.thinkingConfig.thinkingLevel,\n ...(this.thinkingConfig.includeThoughts != null && {\n includeThoughts: this.thinkingConfig.includeThoughts,\n }),\n };\n }\n if (formattedData.contents) {\n fixThoughtSignatures(formattedData.contents, input);\n // gemini-3.1+ models reject role=\"function\"; convert to role=\"user\"\n for (const content of formattedData.contents) {\n if (content.role === 'function') {\n (content as { role: string }).role = 'user';\n }\n }\n }\n return formattedData;\n }\n}\n\n/**\n * Integration with Google Vertex AI chat models.\n *\n * Setup:\n * Install `@langchain/google-vertexai` and set your stringified\n * Vertex AI credentials as an environment variable named `GOOGLE_APPLICATION_CREDENTIALS`.\n *\n * ```bash\n * npm install @langchain/google-vertexai\n * export GOOGLE_APPLICATION_CREDENTIALS=\"path/to/credentials\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/_langchain_google_vertexai.index.ChatVertexAI.html#constructor.new_ChatVertexAI)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_common_types.GoogleAIBaseLanguageModelCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n * stop: [\"\\n\"],\n * tools: [...],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatVertexAI } from '@langchain/google-vertexai';\n *\n * const llm = new ChatVertexAI({\n * model: \"gemini-1.5-pro\",\n * temperature: 0,\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\\nHere's why this is the best translation:\\n\\n* **J'adore** means \\\"I love\\\" and conveys a strong passion.\\n* **Programmer** is the French verb for \\\"to program.\\\"\\n\\nThis translation is natural and idiomatic in French. \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 63,\n * \"total_tokens\": 72\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York City, NY' },\n * id: '33c1c1f47e2f492799c77d2800a43912',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: 'What do you call a cat that loves to bowl?',\n * punchline: 'An alley cat!'\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatVertexAI extends ChatGoogle {\n lc_namespace = ['langchain', 'chat_models', 'vertexai'];\n dynamicThinkingBudget = false;\n thinkingConfig?: GoogleThinkingConfig;\n\n static lc_name(): 'LibreChatVertexAI' {\n return 'LibreChatVertexAI';\n }\n\n constructor(model: string, fields?: Omit<VertexAIClientOptions, 'model'>);\n constructor(fields?: VertexAIClientOptions);\n constructor(\n modelOrFields?: string | VertexAIClientOptions,\n params?: Omit<VertexAIClientOptions, 'model'>\n ) {\n const fields =\n typeof modelOrFields === 'string'\n ? { ...(params ?? {}), model: modelOrFields }\n : modelOrFields;\n const dynamicThinkingBudget = fields?.thinkingBudget === -1;\n super({\n ...fields,\n platformType: 'gcp',\n });\n this.dynamicThinkingBudget = dynamicThinkingBudget;\n this.thinkingConfig = fields?.thinkingConfig;\n }\n invocationParams(\n options?: this['ParsedCallOptions'] | undefined\n ): GoogleAIModelRequestParams {\n const params = super.invocationParams(options);\n if (this.dynamicThinkingBudget) {\n params.maxReasoningTokens = -1;\n }\n return params;\n }\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n let lastGoodUsage: UsageMetadata | undefined;\n for await (const chunk of super._streamResponseChunks(\n messages,\n options,\n runManager\n )) {\n const genUsage = (\n chunk.generationInfo as { usage_metadata?: UsageMetadata } | undefined\n )?.usage_metadata;\n if (genUsage) {\n lastGoodUsage = genUsage;\n }\n if (chunk.message instanceof AIMessageChunk) {\n const repaired = repairStreamUsageMetadata(\n chunk.message.usage_metadata,\n lastGoodUsage\n );\n if (repaired !== chunk.message.usage_metadata) {\n chunk.message.usage_metadata = repaired;\n }\n }\n yield chunk;\n }\n }\n buildConnection(\n fields: VertexAIClientOptions | undefined,\n client: GoogleAbstractedClient\n ): void {\n // Note: buildConnection is called from super() BEFORE this.thinkingConfig is set,\n // so we must read thinkingConfig from `fields` directly.\n const thinkingConfig = fields?.thinkingConfig ?? this.thinkingConfig;\n\n const connection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n connection.thinkingConfig = thinkingConfig;\n this.connection = connection;\n\n const streamedConnection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n streamedConnection.thinkingConfig = thinkingConfig;\n this.streamedConnection = streamedConnection;\n }\n}\n"],"names":[],"mappings":";;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;AAuBG;AACG,SAAU,yBAAyB,CACvC,OAAkC,EAClC,mBAA8C,EAAA;AAE9C,IAAA,IAAI,CAAC,OAAO;AAAE,QAAA,OAAO,OAAO;AAC5B,IAAA,IAAI,CAAC,mBAAmB;AAAE,QAAA,OAAO,OAAO;AACxC,IAAA,IAAI,mBAAmB,CAAC,YAAY,KAAK,OAAO,CAAC,YAAY;AAAE,QAAA,OAAO,OAAO;AAC7E,IAAA,IAAI,mBAAmB,CAAC,aAAa,IAAI,OAAO,CAAC,aAAa;AAC5D,QAAA,OAAO,OAAO;AAChB,IAAA,OAAO,mBAAmB;AAC5B;AAQA;;;;;;;;;;;;;AAaG;AACH,SAAS,oBAAoB,CAC3B,QAAyB,EACzB,KAAoB,EAAA;;AAGpB,IAAA,MAAM,UAAU,GAAG,KAAK,CAAC,MAAM,CAC7B,CAAC,GAAG,KACF,WAAW,CAAC,GAAG,CAAC;QAChB,KAAK,CAAC,OAAO,CAAE,GAAG,CAAC,iBAAsC,EAAE,UAAU,CAAC;QACrE,GAAG,CAAC,iBAAiB,CAAC,UAAuB,CAAC,MAAM,GAAG,CAAC,CAC5D;;AAGD,IAAA,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC;;AAGhE,IAAA,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,EAAE,aAA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KAAK,IAAI,KAAK,CAAC,qBAAqB,CACnD,QAAQ,EACR,OAAO,EACP,UAAU,CACX,EAAE;AACD,YAAA,MAAM,QAAQ,GACZ,KAAK,CAAC,cACP,EAAE,cAAc;YACjB,IAAI,QAAQ,EAAE;gBACZ,aAAa,GAAG,QAAQ;YAC1B;AACA,YAAA,IAAI,KAAK,CAAC,OAAO,YAAY,cAAc,EAAE;AAC3C,gBAAA,MAAM,QAAQ,GAAG,yBAAyB,CACxC,KAAK,CAAC,OAAO,CAAC,cAAc,EAC5B,aAAa,CACd;gBACD,IAAI,QAAQ,KAAK,KAAK,CAAC,OAAO,CAAC,cAAc,EAAE;AAC7C,oBAAA,KAAK,CAAC,OAAO,CAAC,cAAc,GAAG,QAAQ;gBACzC;YACF;AACA,YAAA,MAAM,KAAK;QACb;IACF;IACA,eAAe,CACb,MAAyC,EACzC,MAA8B,EAAA;;;QAI9B,MAAM,cAAc,GAAG,MAAM,EAAE,cAAc,IAAI,IAAI,CAAC,cAAc;QAEpE,MAAM,UAAU,GAAG,IAAI,oBAAoB,CACzC,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,KAAK,CACN;AACD,QAAA,UAAU,CAAC,cAAc,GAAG,cAAc;AAC1C,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;QAE5B,MAAM,kBAAkB,GAAG,IAAI,oBAAoB,CACjD,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,IAAI,CACL;AACD,QAAA,kBAAkB,CAAC,cAAc,GAAG,cAAc;AAClD,QAAA,IAAI,CAAC,kBAAkB,GAAG,kBAAkB;IAC9C;AACD;;;;"}
package/dist/esm/main.mjs CHANGED
@@ -18,7 +18,7 @@ export { Graph, StandardGraph } from './graphs/Graph.mjs';
18
18
  export { MultiAgentGraph } from './graphs/MultiAgentGraph.mjs';
19
19
  export { _resetUnrecognizedTriggerWarnings, shouldTriggerSummarization } from './summarization/index.mjs';
20
20
  export { Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName } from './tools/Calculator.mjs';
21
- export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, createCodeExecutionTool, getCodeBaseURL, imageExtRegex, renderFileSection } from './tools/CodeExecutor.mjs';
21
+ export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, createCodeExecutionTool, emptyOutputMessage, getCodeBaseURL } from './tools/CodeExecutor.mjs';
22
22
  export { BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashToolOutputReferencesGuide, buildBashExecutionToolDescription, createBashExecutionTool } from './tools/BashExecutor.mjs';
23
23
  export { ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, executeTools, extractUsedToolNames, fetchSessionFiles, filterToolsByUsage, formatCompletedResponse, makeRequest, normalizeToPythonIdentifier, unwrapToolResponse } from './tools/ProgrammaticToolCalling.mjs';
24
24
  export { BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, extractUsedBashToolNames, filterBashToolsByUsage, normalizeToBashIdentifier } from './tools/BashProgrammaticToolCalling.mjs';
@@ -2,17 +2,10 @@ import { config } from 'dotenv';
2
2
  import fetch from 'node-fetch';
3
3
  import { HttpsProxyAgent } from 'https-proxy-agent';
4
4
  import { tool } from '@langchain/core/tools';
5
- import { getCodeBaseURL, renderFileSection } from './CodeExecutor.mjs';
5
+ import { getCodeBaseURL, emptyOutputMessage } from './CodeExecutor.mjs';
6
6
  import { Constants } from '../common/enum.mjs';
7
7
 
8
8
  config();
9
- const otherMessage = 'File is already downloaded by the user';
10
- const inheritedFileMessage = 'Available as an input — already known to the user';
11
- const accessMessage = 'Note: Files from previous executions are automatically available and can be modified.';
12
- const emptyOutputMessage = 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
13
- const inheritedFilesHeader = 'Available files (inputs, not generated by this execution):';
14
- const generatedFilesHeader = 'Generated files:';
15
- const inheritedNote = 'Note: Files in "Available files" are inputs the user (or a skill) already provided to the sandbox. They were not produced by this execution and you should not present them as new outputs in your response.';
16
9
  const baseEndpoint = getCodeBaseURL();
17
10
  const EXEC_ENDPOINT = `${baseEndpoint}/exec`;
18
11
  const BashExecutionToolSchema = {
@@ -104,49 +97,17 @@ function createBashExecutionTool(params = {}) {
104
97
  ...rest,
105
98
  ...params,
106
99
  };
100
+ /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`
101
+ * HTTP fallback was removed because codeapi's sessionAuth requires
102
+ * kind/id query params unavailable at this point. */
107
103
  if (_injected_files && _injected_files.length > 0) {
108
104
  postData.files = _injected_files;
109
105
  }
110
- else if (session_id != null && session_id.length > 0) {
111
- try {
112
- const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
113
- const fetchOptions = {
114
- method: 'GET',
115
- headers: {
116
- 'User-Agent': 'LibreChat/1.0',
117
- },
118
- };
119
- if (process.env.PROXY != null && process.env.PROXY !== '') {
120
- fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
121
- }
122
- const response = await fetch(filesEndpoint, fetchOptions);
123
- if (!response.ok) {
124
- throw new Error(`Failed to fetch files for session: ${response.status}`);
125
- }
126
- const files = await response.json();
127
- if (Array.isArray(files) && files.length > 0) {
128
- const fileReferences = files.map((file) => {
129
- const nameParts = file.name.split('/');
130
- const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
131
- return {
132
- storage_session_id: session_id,
133
- /* `/files` fallback returns code-output files belonging
134
- * to the user; tag them user-private. */
135
- kind: 'user',
136
- id,
137
- /* `resource_id` informational for `kind: 'user'` —
138
- * codeapi derives sessionKey from auth context. */
139
- resource_id: id,
140
- name: file.metadata['original-filename'],
141
- };
142
- });
143
- postData.files = fileReferences;
144
- }
145
- }
146
- catch {
147
- // eslint-disable-next-line no-console
148
- console.warn(`Failed to fetch files for session: ${session_id}`);
149
- }
106
+ else if (session_id != null &&
107
+ session_id.length > 0 &&
108
+ !Array.isArray(postData.files)) {
109
+ // eslint-disable-next-line no-console
110
+ console.debug(`[BashExecutor] No injected files for session_id=${session_id} — exec will run without input files`);
150
111
  }
151
112
  try {
152
113
  const fetchOptions = {
@@ -165,6 +126,11 @@ function createBashExecutionTool(params = {}) {
165
126
  throw new Error(`HTTP error! status: ${response.status}`);
166
127
  }
167
128
  const result = await response.json();
129
+ /* See `CodeExecutor.ts` — file listings were removed from the
130
+ * LLM-facing tool result. Bash especially benefits: models
131
+ * naturally `ls /mnt/data/` to discover what's available
132
+ * rather than relying on a prescriptive summary that
133
+ * misleads as often as it helps. */
168
134
  let formattedOutput = '';
169
135
  if (result.stdout) {
170
136
  formattedOutput += `stdout:\n${result.stdout}\n`;
@@ -174,38 +140,14 @@ function createBashExecutionTool(params = {}) {
174
140
  }
175
141
  if (result.stderr)
176
142
  formattedOutput += `stderr:\n${result.stderr}\n`;
177
- if (result.files && result.files.length > 0) {
178
- /* Split inherited (read-only / unchanged-input passthroughs from
179
- * codeapi) from genuine generated outputs. The LLM was previously
180
- * shown skill files under "Generated files:" with the message
181
- * "File is already downloaded by the user", which led it to
182
- * (a) believe it had just produced files it merely referenced
183
- * and (b) sometimes invent paths like /mnt/user-data/uploads/
184
- * trying to find the "originals". Labeling them as inputs makes
185
- * the mental model accurate. */
186
- const inheritedFiles = result.files.filter((f) => f.inherited === true);
187
- const generatedFiles = result.files.filter((f) => f.inherited !== true);
188
- formattedOutput += renderFileSection(generatedFilesHeader, generatedFiles, otherMessage);
189
- formattedOutput += renderFileSection(inheritedFilesHeader, inheritedFiles, inheritedFileMessage);
190
- if (generatedFiles.length > 0) {
191
- formattedOutput += `\n\n${accessMessage}`;
192
- }
193
- if (inheritedFiles.length > 0) {
194
- formattedOutput += `\n\n${inheritedNote}`;
195
- }
196
- return [
197
- formattedOutput.trim(),
198
- {
199
- session_id: result.session_id,
200
- files: result.files,
201
- },
202
- ];
203
- }
143
+ const hasFiles = result.files != null && result.files.length > 0;
204
144
  return [
205
145
  formattedOutput.trim(),
206
- {
207
- session_id: result.session_id,
208
- },
146
+ (hasFiles
147
+ ? { session_id: result.session_id, files: result.files }
148
+ : {
149
+ session_id: result.session_id,
150
+ }),
209
151
  ];
210
152
  }
211
153
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"BashExecutor.mjs","sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { getCodeBaseURL, renderFileSection } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst otherMessage = 'File is already downloaded by the user';\nconst inheritedFileMessage =\n 'Available as an input — already known to the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\nconst inheritedFilesHeader =\n 'Available files (inputs, not generated by this execution):';\nconst generatedFilesHeader = 'Generated files:';\nconst inheritedNote =\n 'Note: Files in \"Available files\" are inputs the user (or a skill) already provided to the sandbox. They were not produced by this execution and you should not present them as new outputs in your response.';\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n}): string {\n if (options?.enableToolOutputReferences === true) {\n return `${BashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return BashExecutionToolDescription;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...params,\n };\n\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n },\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n storage_session_id: session_id,\n /* `/files` fallback returns code-output files belonging\n * to the user; tag them user-private. */\n kind: 'user' as const,\n id,\n /* `resource_id` informational for `kind: 'user'` —\n * codeapi derives sessionKey from auth context. */\n resource_id: id,\n name: file.metadata['original-filename'],\n };\n });\n\n postData.files = fileReferences;\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n /* Split inherited (read-only / unchanged-input passthroughs from\n * codeapi) from genuine generated outputs. The LLM was previously\n * shown skill files under \"Generated files:\" with the message\n * \"File is already downloaded by the user\", which led it to\n * (a) believe it had just produced files it merely referenced\n * and (b) sometimes invent paths like /mnt/user-data/uploads/\n * trying to find the \"originals\". Labeling them as inputs makes\n * the mental model accurate. */\n const inheritedFiles = result.files.filter(\n (f) => f.inherited === true\n );\n const generatedFiles = result.files.filter(\n (f) => f.inherited !== true\n );\n\n formattedOutput += renderFileSection(\n generatedFilesHeader,\n generatedFiles,\n otherMessage\n );\n formattedOutput += renderFileSection(\n inheritedFilesHeader,\n inheritedFiles,\n inheritedFileMessage\n );\n\n if (generatedFiles.length > 0) {\n formattedOutput += `\\n\\n${accessMessage}`;\n }\n if (inheritedFiles.length > 0) {\n formattedOutput += `\\n\\n${inheritedNote}`;\n }\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n } satisfies t.CodeExecutionArtifact,\n ];\n }\n\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n } satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"names":[],"mappings":";;;;;;;AAQA,MAAM,EAAE;AAER,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,oBAAoB,GACxB,mDAAmD;AACrD,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAC9D,MAAM,oBAAoB,GACxB,4DAA4D;AAC9D,MAAM,oBAAoB,GAAG,kBAAkB;AAC/C,MAAM,aAAa,GACjB,8MAA8M;AAEhN,MAAM,YAAY,GAAG,cAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAErC,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;AAOqC,uDAAA,CAAA;AACnD,S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AA,EAAwB,KAA2B,EAAE,OAAO,CAAA,CAAE,CAC/D;QACH;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,WAAW,EAAE,4BAA4B;AACzC,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
1
+ {"version":3,"file":"BashExecutor.mjs","sources":["../../../src/tools/BashExecutor.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { emptyOutputMessage, getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nexport const BashExecutionToolSchema = {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: `The bash command or script to execute.\n- The environment is stateless; variables and state don't persist between executions.\n- Generated files from previous executions are automatically available in \"/mnt/data/\".\n- Files from previous executions are automatically available and can be modified in place.\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- Use \\`echo\\`, \\`printf\\`, or \\`cat\\` for all outputs.`,\n },\n args: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Additional arguments to execute the command with. This should only be used if the input command requires additional arguments to run.',\n },\n },\n required: ['command'],\n} as const;\n\nexport const BashExecutionToolDescription = `\nRuns bash commands and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious commands.\n`.trim();\n\n/**\n * Supplemental prompt documenting the tool-output reference feature.\n *\n * Hosts should append this (separated by a blank line) to the base\n * {@link BashExecutionToolDescription} only when\n * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature\n * is disabled, including this text would tell the LLM to emit\n * `{{tool0turn0}}` placeholders that pass through unsubstituted and\n * leak into the shell.\n */\nexport const BashToolOutputReferencesGuide = `\nReferencing previous tool outputs:\n- Every successful tool result is tagged with a reference key of the form \\`tool<idx>turn<turn>\\` (e.g., \\`tool0turn0\\`). The key appears either as a \\`[ref: tool0turn0]\\` prefix line or, when the output is a JSON object, as a \\`_ref\\` field on the object.\n- To pipe a previous tool output into this tool, embed the placeholder \\`{{tool<idx>turn<turn>}}\\` literally anywhere in the \\`command\\` string (or any string arg). It will be substituted with the stored output verbatim before the command runs.\n- The substituted value is the original output string (no \\`[ref: …]\\` prefix, no \\`_ref\\` key), so it is safe to pipe directly into \\`jq\\`, \\`grep\\`, \\`awk\\`, etc.\n- Example (simple ASCII output): \\`echo '{{tool0turn0}}' | jq '.foo'\\` takes the full output of the first tool from the first turn and pipes it into jq.\n- For payloads that may contain quotes, parentheses, backticks, or arbitrary bytes (random/binary data, JSON with embedded quotes, multi-line strings), prefer a quoted-delimiter heredoc over \\`echo '…'\\`. The heredoc body is not interpreted by the shell, so substituted payloads pass through unchanged.\n- Heredoc example: \\`wc -c << 'EOF'\\\\n{{tool0turn0}}\\\\nEOF\\` (the quotes around \\`'EOF'\\` disable interpolation inside the body).\n- Unknown reference keys are left in place and surfaced as \\`[unresolved refs: …]\\` after the output.\n`.trim();\n\n/**\n * Composes the bash tool description, optionally appending the\n * tool-output references guide. Hosts that enable\n * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`\n * when registering the tool so the LLM learns the `{{…}}` syntax it\n * will actually be able to use.\n */\nexport function buildBashExecutionToolDescription(options?: {\n enableToolOutputReferences?: boolean;\n}): string {\n if (options?.enableToolOutputReferences === true) {\n return `${BashExecutionToolDescription}\\n\\n${BashToolOutputReferencesGuide}`;\n }\n return BashExecutionToolDescription;\n}\n\nexport const BashExecutionToolName = Constants.BASH_TOOL;\n\n/**\n * Default bash tool definition using the base description.\n *\n * When `RunConfig.toolOutputReferences.enabled` is `true`, build a\n * reference-aware description with\n * {@link buildBashExecutionToolDescription}\n * (`{ enableToolOutputReferences: true }`) and construct a custom\n * definition using it — using this constant as-is leaves the LLM\n * unaware of the `{{tool<i>turn<n>}}` syntax.\n */\nexport const BashExecutionToolDefinition = {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n} as const;\n\nfunction createBashExecutionTool(\n params: t.BashExecutionToolParams = {}\n): DynamicStructuredTool {\n return tool(\n async (rawInput, config) => {\n const { command, ...rest } = rawInput as {\n command: string;\n args?: string[];\n };\n const { session_id, _injected_files } = (config.toolCall ?? {}) as {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n const postData: Record<string, unknown> = {\n lang: 'bash',\n code: command,\n ...rest,\n ...params,\n };\n\n /* See `CodeExecutor.ts` for the rationale — `/files/<session_id>`\n * HTTP fallback was removed because codeapi's sessionAuth requires\n * kind/id query params unavailable at this point. */\n if (_injected_files && _injected_files.length > 0) {\n postData.files = _injected_files;\n } else if (\n session_id != null &&\n session_id.length > 0 &&\n !Array.isArray(postData.files)\n ) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashExecutor] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n },\n body: JSON.stringify(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n /* See `CodeExecutor.ts` — file listings were removed from the\n * LLM-facing tool result. Bash especially benefits: models\n * naturally `ls /mnt/data/` to discover what's available\n * rather than relying on a prescriptive summary that\n * misleads as often as it helps. */\n let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n\n const hasFiles = result.files != null && result.files.length > 0;\n return [\n formattedOutput.trim(),\n (hasFiles\n ? { session_id: result.session_id, files: result.files }\n : {\n session_id: result.session_id,\n }) satisfies t.CodeExecutionArtifact,\n ];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: BashExecutionToolName,\n description: BashExecutionToolDescription,\n schema: BashExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createBashExecutionTool };\n"],"names":[],"mappings":";;;;;;;AAQA,MAAM,EAAE;AAER,MAAM,YAAY,GAAG,cAAc,EAAE;AACrC,MAAM,aAAa,GAAG,CAAA,EAAG,YAAY,OAAO;AAErC,MAAM,uBAAuB,GAAG;AACrC,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,WAAW,EAAE,CAAA;;;;;;;AAOqC,uDAAA,CAAA;AACnD,SAAA;AACD,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,OAAO;AACb,YAAA,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;AACzB,YAAA,WAAW,EACT,uIAAuI;AAC1I,SAAA;AACF,KAAA;IACD,QAAQ,EAAE,CAAC,SAAS,CAAC;;AAGhB,MAAM,4BAA4B,GAAG;;;;;;;CAO3C,CAAC,IAAI;AAEN;;;;;;;;;AASG;AACI,MAAM,6BAA6B,GAAG;;;;;;;;;CAS5C,CAAC,IAAI;AAEN;;;;;;AAMG;AACG,SAAU,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ACJ;QACH;QAAE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAA,CAAE,CAC/D;QACH;AACF,IAAA,CAAC,EACD;AACE,QAAA,IAAI,EAAE,qBAAqB;AAC3B,QAAA,WAAW,EAAE,4BAA4B;AACzC,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
@@ -1,6 +1,6 @@
1
1
  import { config } from 'dotenv';
2
2
  import { tool } from '@langchain/core/tools';
3
- import { fetchSessionFiles, makeRequest, executeTools, formatCompletedResponse } from './ProgrammaticToolCalling.mjs';
3
+ import { makeRequest, executeTools, formatCompletedResponse } from './ProgrammaticToolCalling.mjs';
4
4
  import { getCodeBaseURL } from './CodeExecutor.mjs';
5
5
  import { Constants } from '../common/enum.mjs';
6
6
 
@@ -215,12 +215,16 @@ function createBashProgrammaticToolCallingTool(initParams = {}) {
215
215
  console.log(`[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +
216
216
  `(filtered from ${toolDefs.length})`);
217
217
  }
218
+ /* `/files/<session_id>` HTTP fallback removed — codeapi's
219
+ * sessionAuth requires kind/id query params unavailable at
220
+ * this point. See `CodeExecutor.ts` for full rationale. */
218
221
  let files;
219
222
  if (_injected_files && _injected_files.length > 0) {
220
223
  files = _injected_files;
221
224
  }
222
225
  else if (session_id != null && session_id.length > 0) {
223
- files = await fetchSessionFiles(baseUrl, session_id, proxy);
226
+ // eslint-disable-next-line no-console
227
+ console.debug(`[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`);
224
228
  }
225
229
  let response = await makeRequest(EXEC_ENDPOINT, {
226
230
  lang: 'bash',
@@ -1 +1 @@
1
- {"version":3,"file":"BashProgrammaticToolCalling.mjs","sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n makeRequest,\n executeTools,\n fetchSessionFiles,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_TIMEOUT = 60000;\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport const BashProgrammaticToolCallingSchema = {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: {\n type: 'integer',\n minimum: 1000,\n maximum: 300000,\n default: DEFAULT_TIMEOUT,\n description:\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',\n },\n },\n required: ['code'],\n} as const;\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code, timeout = DEFAULT_TIMEOUT } = params;\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n const { toolMap, toolDefs, session_id, _injected_files } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Bash programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings":";;;;;;AAaA,MAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,uBAAuB,GAAG,EAAE;AAClC,MAAM,eAAe,GAAG,KAAK;AAE7B;AACA,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,IAAI;IACJ,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;IACN,MAAM;IACN,KAAK;IACL,OAAO;IACP,OAAO;IACP,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,UAAU;IACV,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;IACT,SAAS;IACT,OAAO;IACP,UAAU;IACV,QAAQ;IACR,OAAO;AACR,CAAA,CAAC;AAEF;AACA;AACA;AAEA,MAAM,iBAAiB,GAAG,CAAA;;;sEAG4C;AAEtE,MAAM,UAAU,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AE,CAClE;QACH;AACF,IAAA,CAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,8BAA8B;AAC9C,QAAA,WAAW,EAAE,sCAAsC;AACnD,QAAA,MAAM,EAAE,iCAAiC;QACzC,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
1
+ {"version":3,"file":"BashProgrammaticToolCalling.mjs","sources":["../../../src/tools/BashProgrammaticToolCalling.ts"],"sourcesContent":["import { config } from 'dotenv';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n makeRequest,\n executeTools,\n formatCompletedResponse,\n} from './ProgrammaticToolCalling';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\nconst DEFAULT_TIMEOUT = 60000;\n\n/** Bash reserved words that get `_tool` suffix when used as function names */\nconst BASH_RESERVED = new Set([\n 'if',\n 'then',\n 'else',\n 'elif',\n 'fi',\n 'case',\n 'esac',\n 'for',\n 'while',\n 'until',\n 'do',\n 'done',\n 'in',\n 'function',\n 'select',\n 'time',\n 'coproc',\n 'declare',\n 'typeset',\n 'local',\n 'readonly',\n 'export',\n 'unset',\n]);\n\n// ============================================================================\n// Description Components\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh bash shell. Variables and state do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- EVERYTHING in one call—no state persists between executions\n- Tools are pre-defined as bash functions—DO NOT redefine them\n- Each tool function accepts a JSON string argument\n- Only echo/printf output returns to the model\n- Generated files are automatically available in /mnt/data/ for subsequent executions`;\n\nconst ADDITIONAL_RULES =\n '- Tool names normalized: hyphens→underscores, reserved words get `_tool` suffix';\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data and process\n data=$(query_database '{\"sql\": \"SELECT * FROM users\"}')\n echo \"$data\" | jq '.[] | .name'\n\nExample (Parallel calls):\n web_search '{\"query\": \"SF weather\"}' > /tmp/sf.txt &\n web_search '{\"query\": \"NY weather\"}' > /tmp/ny.txt &\n wait\n echo \"SF: $(cat /tmp/sf.txt)\"\n echo \"NY: $(cat /tmp/ny.txt)\"`;\n\nconst CODE_PARAM_DESCRIPTION = `Bash code that calls tools programmatically. Tools are available as bash functions.\n\n${STATELESS_WARNING}\n\nEach tool function accepts a JSON string as its argument.\nExample: tool_name '{\"key\": \"value\"}'\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport const BashProgrammaticToolCallingSchema = {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: {\n type: 'integer',\n minimum: 1000,\n maximum: 300000,\n default: DEFAULT_TIMEOUT,\n description:\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',\n },\n },\n required: ['code'],\n} as const;\n\nexport const BashProgrammaticToolCallingName =\n Constants.BASH_PROGRAMMATIC_TOOL_CALLING;\n\nexport const BashProgrammaticToolCallingDescription = `\nRun tools via bash code. Tools are available as bash functions that accept JSON string arguments.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: shell pipelines, parallel execution (& and wait), file processing, text manipulation.\n\n${EXAMPLES}\n`.trim();\n\nexport const BashProgrammaticToolCallingDefinition = {\n name: BashProgrammaticToolCallingName,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Normalizes a tool name to a valid bash function identifier.\n * 1. Replace hyphens, spaces, dots with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a bash reserved word\n */\nexport function normalizeToBashIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s.]/g, '_');\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (BASH_RESERVED.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the bash code.\n * Bash functions are invoked as commands (no parentheses), so we match\n * the normalized name as a word boundary.\n */\nexport function extractUsedBashToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [bashName, originalName] of toolNameMap) {\n const escapedName = bashName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\b`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the bash code.\n */\nexport function filterBashToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const def of toolDefs) {\n const bashName = normalizeToBashIdentifier(def.name);\n toolNameMap.set(bashName, def.name);\n }\n\n const usedToolNames = extractUsedBashToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[BashPTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((def) => usedToolNames.has(def.name));\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Bash Programmatic Tool Calling tool for multi-tool orchestration.\n *\n * This tool enables AI agents to write bash scripts that orchestrate multiple\n * tool calls programmatically via the remote Code API, reducing LLM round-trips.\n *\n * The tool map must be provided at runtime via config.toolCall (injected by ToolNode).\n */\nexport function createBashProgrammaticToolCallingTool(\n initParams: t.BashProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.BASH_PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code, timeout = DEFAULT_TIMEOUT } = params;\n\n const toolCall = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n const { toolMap, toolDefs, session_id, _injected_files } = toolCall;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterBashToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /* `/files/<session_id>` HTTP fallback removed — codeapi's\n * sessionAuth requires kind/id query params unavailable at\n * this point. See `CodeExecutor.ts` for full rationale. */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n // eslint-disable-next-line no-console\n console.debug(\n `[BashProgrammaticToolCalling] No injected files for session_id=${session_id} — exec will run without input files`\n );\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n {\n lang: 'bash',\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[BashPTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Bash programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,\n description: BashProgrammaticToolCallingDescription,\n schema: BashProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":[],"mappings":";;;;;;AAYA,MAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,uBAAu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