@flutchai/flutch-sdk 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1908,13 +1908,13 @@ async function findAvailablePort(startPort) {
1908
1908
  throw new Error(`No available ports found in range ${startPort}-${startPort + 99}`);
1909
1909
  }
1910
1910
  __name(findAvailablePort, "findAvailablePort");
1911
- async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1911
+ async function registerWithServiceDiscovery(AppModule, port, logger3, app) {
1912
1912
  try {
1913
- logger2.debug("[SERVICE_DISCOVERY] Starting service discovery registration...");
1913
+ logger3.debug("[SERVICE_DISCOVERY] Starting service discovery registration...");
1914
1914
  const { FileBasedDiscovery: FileBasedDiscovery2 } = await Promise.resolve().then(() => (init_file_based_discovery(), file_based_discovery_exports));
1915
- logger2.debug("[SERVICE_DISCOVERY] FileBasedDiscovery imported successfully");
1915
+ logger3.debug("[SERVICE_DISCOVERY] FileBasedDiscovery imported successfully");
1916
1916
  const discovery = new FileBasedDiscovery2();
1917
- logger2.debug("[SERVICE_DISCOVERY] FileBasedDiscovery instance created");
1917
+ logger3.debug("[SERVICE_DISCOVERY] FileBasedDiscovery instance created");
1918
1918
  const serviceName = AppModule.name.replace("Module", "").toLowerCase();
1919
1919
  let graphTypes = [];
1920
1920
  try {
@@ -1923,26 +1923,26 @@ async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1923
1923
  const builderRegistry = app.get(BuilderRegistryService2, {
1924
1924
  strict: false
1925
1925
  });
1926
- logger2.debug(`BuilderRegistryService found in DI: ${!!builderRegistry}`);
1926
+ logger3.debug(`BuilderRegistryService found in DI: ${!!builderRegistry}`);
1927
1927
  if (builderRegistry) {
1928
1928
  const builders = builderRegistry.getBuilders();
1929
- logger2.debug(`Found ${builders.length} builders in registry`);
1929
+ logger3.debug(`Found ${builders.length} builders in registry`);
1930
1930
  const baseGraphTypes = builders.map((builder) => builder.graphType);
1931
- logger2.debug(`Base graph types: [${baseGraphTypes.join(", ")}]`);
1931
+ logger3.debug(`Base graph types: [${baseGraphTypes.join(", ")}]`);
1932
1932
  try {
1933
- logger2.debug("Attempting to import VersionedGraphService...");
1933
+ logger3.debug("Attempting to import VersionedGraphService...");
1934
1934
  const { VersionedGraphService: VersionedGraphService2 } = await Promise.resolve().then(() => (init_versioned_graph_service(), versioned_graph_service_exports));
1935
- logger2.debug("VersionedGraphService imported successfully");
1935
+ logger3.debug("VersionedGraphService imported successfully");
1936
1936
  const versionedService = app.get(VersionedGraphService2, {
1937
1937
  strict: false
1938
1938
  });
1939
- logger2.debug(`VersionedGraphService found in DI: ${!!versionedService}`);
1939
+ logger3.debug(`VersionedGraphService found in DI: ${!!versionedService}`);
1940
1940
  if (versionedService) {
1941
1941
  const allVersionedTypes = [];
1942
1942
  for (const baseType of baseGraphTypes) {
1943
- logger2.debug(`Getting versions for base type: ${baseType}`);
1943
+ logger3.debug(`Getting versions for base type: ${baseType}`);
1944
1944
  const versions = versionedService.getAvailableVersions(baseType);
1945
- logger2.debug(`Found ${versions.length} versions for ${baseType}: [${versions.join(", ")}]`);
1945
+ logger3.debug(`Found ${versions.length} versions for ${baseType}: [${versions.join(", ")}]`);
1946
1946
  if (versions.length > 0) {
1947
1947
  allVersionedTypes.push(baseType);
1948
1948
  versions.forEach((version) => {
@@ -1953,23 +1953,23 @@ async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1953
1953
  }
1954
1954
  }
1955
1955
  graphTypes = allVersionedTypes;
1956
- logger2.debug(`Found ${baseGraphTypes.length} base types with ${graphTypes.length} total versioned types: ${graphTypes.join(", ")}`);
1956
+ logger3.debug(`Found ${baseGraphTypes.length} base types with ${graphTypes.length} total versioned types: ${graphTypes.join(", ")}`);
1957
1957
  } else {
1958
1958
  graphTypes = baseGraphTypes;
1959
- logger2.debug(`VersionedGraphService not found in DI container, using base types: ${graphTypes.join(", ")}`);
1959
+ logger3.debug(`VersionedGraphService not found in DI container, using base types: ${graphTypes.join(", ")}`);
1960
1960
  }
1961
1961
  } catch (error) {
1962
1962
  graphTypes = baseGraphTypes;
1963
- logger2.debug(`Failed to get versioned types, using base types: ${error.message}`);
1964
- logger2.debug(`Stack trace: ${error.stack}`);
1963
+ logger3.debug(`Failed to get versioned types, using base types: ${error.message}`);
1964
+ logger3.debug(`Stack trace: ${error.stack}`);
1965
1965
  }
1966
1966
  }
1967
1967
  }
1968
1968
  } catch (error) {
1969
- logger2.debug(`Failed to get graph types from builders: ${error.message}`);
1969
+ logger3.debug(`Failed to get graph types from builders: ${error.message}`);
1970
1970
  }
1971
1971
  if (graphTypes.length === 0) {
1972
- logger2.debug("No builders found, using service name as graph type");
1972
+ logger3.debug("No builders found, using service name as graph type");
1973
1973
  graphTypes = [
1974
1974
  serviceName
1975
1975
  ];
@@ -1980,21 +1980,21 @@ async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1980
1980
  startTime: (/* @__PURE__ */ new Date()).toISOString(),
1981
1981
  version: process.env.npm_package_version || "1.0.0"
1982
1982
  }, graphTypes);
1983
- logger2.log(`\u{1F4E1} Service registered with discovery: ${serviceName} (types: ${graphTypes.join(", ")})`);
1983
+ logger3.log(`\u{1F4E1} Service registered with discovery: ${serviceName} (types: ${graphTypes.join(", ")})`);
1984
1984
  } catch (error) {
1985
- logger2.warn(`Failed to register with service discovery: ${error.message}`);
1985
+ logger3.warn(`Failed to register with service discovery: ${error.message}`);
1986
1986
  }
1987
1987
  }
1988
1988
  __name(registerWithServiceDiscovery, "registerWithServiceDiscovery");
1989
1989
  async function bootstrap(AppModule, options = {}) {
1990
1990
  setupRedisMock();
1991
1991
  const app = await core.NestFactory.create(AppModule);
1992
- const logger2 = new common.Logger("Bootstrap");
1992
+ const logger3 = new common.Logger("Bootstrap");
1993
1993
  const requestedPort = options.port || parseInt(process.env.PORT || "3100", 10);
1994
1994
  const port = await findAvailablePort(requestedPort);
1995
1995
  const globalPrefix = options.globalPrefix;
1996
1996
  if (port !== requestedPort) {
1997
- logger2.warn(`Port ${requestedPort} is busy, using port ${port} instead`);
1997
+ logger3.warn(`Port ${requestedPort} is busy, using port ${port} instead`);
1998
1998
  }
1999
1999
  if (globalPrefix) {
2000
2000
  app.setGlobalPrefix(globalPrefix);
@@ -2013,13 +2013,13 @@ async function bootstrap(AppModule, options = {}) {
2013
2013
  swagger.SwaggerModule.setup("api/docs", app, document);
2014
2014
  await app.listen(port);
2015
2015
  const baseUrl = globalPrefix ? `http://localhost:${port}/${globalPrefix}` : `http://localhost:${port}`;
2016
- logger2.log(`\u{1F680} Graph service is running on: ${baseUrl}`);
2017
- logger2.log(`\u{1F4DA} API Documentation: http://localhost:${port}/api/docs`);
2016
+ logger3.log(`\u{1F680} Graph service is running on: ${baseUrl}`);
2017
+ logger3.log(`\u{1F4DA} API Documentation: http://localhost:${port}/api/docs`);
2018
2018
  if (process.env.NODE_ENV !== "production") {
2019
- logger2.debug(`Attempting service discovery registration (NODE_ENV: ${process.env.NODE_ENV || "undefined"})`);
2020
- await registerWithServiceDiscovery(AppModule, port, logger2, app);
2019
+ logger3.debug(`Attempting service discovery registration (NODE_ENV: ${process.env.NODE_ENV || "undefined"})`);
2020
+ await registerWithServiceDiscovery(AppModule, port, logger3, app);
2021
2021
  } else {
2022
- logger2.debug(`Skipping service discovery registration (NODE_ENV: ${process.env.NODE_ENV})`);
2022
+ logger3.debug(`Skipping service discovery registration (NODE_ENV: ${process.env.NODE_ENV})`);
2023
2023
  }
2024
2024
  return app;
2025
2025
  }
@@ -4872,7 +4872,7 @@ function clearAttachmentDataStore(threadId) {
4872
4872
  }
4873
4873
  __name(clearAttachmentDataStore, "clearAttachmentDataStore");
4874
4874
  async function executeToolWithAttachments(params) {
4875
- const { toolCall, mcpClient, enrichedArgs, executionContext, config, attachments, logger: logger2, threshold = DEFAULT_ATTACHMENT_THRESHOLD, injectIntoArg = "data", sourceAttachmentId, threadId, toolSchema, mcpServers } = params;
4875
+ const { toolCall, mcpClient, enrichedArgs, executionContext, config, attachments, logger: logger3, threshold = DEFAULT_ATTACHMENT_THRESHOLD, injectIntoArg = "data", sourceAttachmentId, threadId, toolSchema, mcpServers } = params;
4876
4876
  const argsWithInjection = {
4877
4877
  ...enrichedArgs
4878
4878
  };
@@ -4885,12 +4885,12 @@ async function executeToolWithAttachments(params) {
4885
4885
  const data = storedData !== void 0 ? storedData : attachment.data;
4886
4886
  if (data != null) {
4887
4887
  argsWithInjection[injectIntoArg] = typeof data === "string" ? data : JSON.stringify(data);
4888
- logger2?.debug(`[Attachment] Auto-injected data from attachment "${attachment.toolCallId}" into ${toolCall.name}.${injectIntoArg} (source: ${storedData !== void 0 ? "memory" : "state"})`);
4888
+ logger3?.debug(`[Attachment] Auto-injected data from attachment "${attachment.toolCallId}" into ${toolCall.name}.${injectIntoArg} (source: ${storedData !== void 0 ? "memory" : "state"})`);
4889
4889
  }
4890
4890
  }
4891
4891
  }
4892
4892
  } catch (e) {
4893
- logger2?.warn(`[Attachment] Auto-injection failed: ${e}`);
4893
+ logger3?.warn(`[Attachment] Auto-injection failed: ${e}`);
4894
4894
  }
4895
4895
  const { content, success, rawResult } = await mcpClient.executeToolWithEvents(toolCall.id, toolCall.name, argsWithInjection, executionContext, config, mcpServers);
4896
4896
  try {
@@ -4901,7 +4901,7 @@ async function executeToolWithAttachments(params) {
4901
4901
  ...attachment,
4902
4902
  data: null
4903
4903
  };
4904
- logger2?.debug(`[Attachment] Stored large result (${content.length} chars) as attachment "${toolCall.id}" (data in memory, metadata in state)`);
4904
+ logger3?.debug(`[Attachment] Stored large result (${content.length} chars) as attachment "${toolCall.id}" (data in memory, metadata in state)`);
4905
4905
  const toolMessage2 = new messages.ToolMessage({
4906
4906
  content: attachment.summary,
4907
4907
  tool_call_id: toolCall.id,
@@ -4916,7 +4916,7 @@ async function executeToolWithAttachments(params) {
4916
4916
  };
4917
4917
  }
4918
4918
  } catch (e) {
4919
- logger2?.warn(`[Attachment] Failed to create attachment, using full content: ${e}`);
4919
+ logger3?.warn(`[Attachment] Failed to create attachment, using full content: ${e}`);
4920
4920
  }
4921
4921
  const toolMessage = new messages.ToolMessage({
4922
4922
  content,
@@ -6230,7 +6230,7 @@ function createMetaBuilder(config, versionedGraphService, moduleRef) {
6230
6230
  }
6231
6231
  __name(createMetaBuilder, "createMetaBuilder");
6232
6232
  function buildCheckpointerProviders(options) {
6233
- const logger2 = new common.Logger("UniversalGraphModule");
6233
+ const logger3 = new common.Logger("UniversalGraphModule");
6234
6234
  if (options.postgres !== void 0) {
6235
6235
  return [
6236
6236
  {
@@ -6244,7 +6244,7 @@ function buildCheckpointerProviders(options) {
6244
6244
  if (!connString) {
6245
6245
  throw new Error("[UniversalGraphModule] Postgres checkpointer: provide postgres.connectionString or set the DATABASE_URL environment variable.");
6246
6246
  }
6247
- logger2.log(`Checkpointer: PostgreSQL (${connString.replace(/:[^:@]+@/, ":***@")})`);
6247
+ logger3.log(`Checkpointer: PostgreSQL (${connString.replace(/:[^:@]+@/, ":***@")})`);
6248
6248
  const saver = PostgresSaver.fromConnString(connString, {
6249
6249
  ...options.postgres.schema ? {
6250
6250
  schema: options.postgres.schema
@@ -6266,7 +6266,7 @@ function buildCheckpointerProviders(options) {
6266
6266
  if (!mongoUri) {
6267
6267
  throw new Error("[UniversalGraphModule] MongoDB checkpointer: provide mongodb.uri or set the MONGODB_URI environment variable.");
6268
6268
  }
6269
- logger2.log(`Checkpointer: MongoDB (${mongoUri.substring(0, 50)}...)`);
6269
+ logger3.log(`Checkpointer: MongoDB (${mongoUri.substring(0, 50)}...)`);
6270
6270
  await mongoose__default.default.connect(mongoUri, {
6271
6271
  dbName
6272
6272
  });
@@ -6300,7 +6300,7 @@ function buildCheckpointerProviders(options) {
6300
6300
  provide: "CHECKPOINTER",
6301
6301
  useFactory: /* @__PURE__ */ __name(async () => {
6302
6302
  const { MemorySaver } = await import('@langchain/langgraph');
6303
- logger2.warn("Checkpointer: MemorySaver (in-process, no persistence). Configure postgres or mongodb in UniversalGraphModule.forRoot() for production.");
6303
+ logger3.warn("Checkpointer: MemorySaver (in-process, no persistence). Configure postgres or mongodb in UniversalGraphModule.forRoot() for production.");
6304
6304
  return new MemorySaver();
6305
6305
  }, "useFactory")
6306
6306
  }
@@ -6339,8 +6339,8 @@ exports.UniversalGraphModule = class _UniversalGraphModule {
6339
6339
  const redisUrl = options.redis?.url ?? process.env.REDIS_URL;
6340
6340
  if (redisUrl) {
6341
6341
  const Redis2 = __require("ioredis");
6342
- const logger2 = new common.Logger("UniversalGraphModule");
6343
- logger2.log(`Callbacks: Redis (${redisUrl.replace(/:[^:@]+@/, ":***@")})`);
6342
+ const logger3 = new common.Logger("UniversalGraphModule");
6343
+ logger3.log(`Callbacks: Redis (${redisUrl.replace(/:[^:@]+@/, ":***@")})`);
6344
6344
  return new Redis2(redisUrl);
6345
6345
  }
6346
6346
  const IORedisMock = __require("ioredis-mock");
@@ -6624,7 +6624,7 @@ var McpConverter = class _McpConverter {
6624
6624
  * Convert a single MCP tool to LangChain DynamicStructuredTool
6625
6625
  */
6626
6626
  convertTool(mcpTool) {
6627
- const logger2 = this.logger;
6627
+ const logger3 = this.logger;
6628
6628
  const mcpRuntimeUrl = this.mcpRuntimeUrl;
6629
6629
  let enhancedDescription = mcpTool.description;
6630
6630
  if (mcpTool.inputSchema?.properties) {
@@ -6644,12 +6644,12 @@ ${paramDescriptions.join("\n")}`;
6644
6644
  }
6645
6645
  }
6646
6646
  const schema = this.jsonSchemaToZod(mcpTool.inputSchema);
6647
- logger2.debug(`\u{1F527} [${mcpTool.name}] Original schema:`, JSON.stringify(mcpTool.inputSchema, null, 2));
6648
- logger2.debug(`\u{1F527} [${mcpTool.name}] Using schema type: ${schema?._def?.typeName ?? "unknown"}`);
6647
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Original schema:`, JSON.stringify(mcpTool.inputSchema, null, 2));
6648
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Using schema type: ${schema?._def?.typeName ?? "unknown"}`);
6649
6649
  if (schema?._def?.shape && typeof schema._def.shape === "function") {
6650
6650
  try {
6651
6651
  const shape = schema._def.shape();
6652
- logger2.debug(`\u{1F527} [${mcpTool.name}] Converted Zod schema shape:`, JSON.stringify(Object.entries(shape).reduce((acc, [key, val]) => {
6652
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Converted Zod schema shape:`, JSON.stringify(Object.entries(shape).reduce((acc, [key, val]) => {
6653
6653
  acc[key] = {
6654
6654
  type: val?._def?.typeName,
6655
6655
  description: val?._def?.description,
@@ -6658,50 +6658,50 @@ ${paramDescriptions.join("\n")}`;
6658
6658
  return acc;
6659
6659
  }, {}), null, 2));
6660
6660
  } catch (error) {
6661
- logger2.debug(`\u{1F527} [${mcpTool.name}] Could not extract Zod schema shape: ${error}`);
6661
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Could not extract Zod schema shape: ${error}`);
6662
6662
  }
6663
6663
  }
6664
6664
  try {
6665
6665
  const convertedJsonSchema = zodToJsonSchema.zodToJsonSchema(schema);
6666
- logger2.warn(`\u{1F527} [${mcpTool.name}] JSON Schema that LangChain will use:`, JSON.stringify(convertedJsonSchema, null, 2));
6666
+ logger3.warn(`\u{1F527} [${mcpTool.name}] JSON Schema that LangChain will use:`, JSON.stringify(convertedJsonSchema, null, 2));
6667
6667
  } catch (error) {
6668
- logger2.warn(`\u{1F527} [${mcpTool.name}] Could not convert Zod to JSON Schema: ${error}`);
6668
+ logger3.warn(`\u{1F527} [${mcpTool.name}] Could not convert Zod to JSON Schema: ${error}`);
6669
6669
  }
6670
6670
  return new tools.DynamicStructuredTool({
6671
6671
  name: mcpTool.name,
6672
6672
  description: enhancedDescription,
6673
6673
  schema,
6674
6674
  func: /* @__PURE__ */ __name(async (input, _runManager, config) => {
6675
- logger2.log(`\u{1F527} [${mcpTool.name}] LLM INPUT: ${JSON.stringify(input)}`);
6675
+ logger3.log(`\u{1F527} [${mcpTool.name}] LLM INPUT: ${JSON.stringify(input)}`);
6676
6676
  const configurable = config?.configurable;
6677
6677
  const context = {
6678
6678
  agentId: configurable?.agentId,
6679
6679
  userId: configurable?.userId,
6680
6680
  threadId: configurable?.thread_id
6681
6681
  };
6682
- logger2.debug(`\u{1F527} [${mcpTool.name}] Execution context: ${JSON.stringify(context)}`);
6682
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Execution context: ${JSON.stringify(context)}`);
6683
6683
  try {
6684
6684
  const request = {
6685
6685
  name: mcpTool.name,
6686
6686
  arguments: input ?? {},
6687
6687
  context
6688
6688
  };
6689
- logger2.log(`\u{1F527} [${mcpTool.name}] Calling MCP Runtime...`);
6689
+ logger3.log(`\u{1F527} [${mcpTool.name}] Calling MCP Runtime...`);
6690
6690
  const response = await axios2__default.default.post(`${mcpRuntimeUrl}/tools/execute`, request, {
6691
6691
  timeout: 3e4
6692
6692
  });
6693
6693
  const result = response.data;
6694
- logger2.log(`\u{1F527} [${mcpTool.name}] MCP Runtime response: success=${result.success}`);
6694
+ logger3.log(`\u{1F527} [${mcpTool.name}] MCP Runtime response: success=${result.success}`);
6695
6695
  if (!result.success) {
6696
6696
  const errorMessage = result.error || "Tool execution failed";
6697
- logger2.error(`\u{1F527} [${mcpTool.name}] MCP Runtime error: ${errorMessage}`);
6697
+ logger3.error(`\u{1F527} [${mcpTool.name}] MCP Runtime error: ${errorMessage}`);
6698
6698
  throw new Error(errorMessage);
6699
6699
  }
6700
6700
  const output = typeof result.result === "string" ? result.result : JSON.stringify(result.result, null, 2);
6701
- logger2.log(`\u{1F527} [${mcpTool.name}] TOOL OUTPUT: ${output.length > 200 ? output.substring(0, 200) + "..." : output}`);
6701
+ logger3.log(`\u{1F527} [${mcpTool.name}] TOOL OUTPUT: ${output.length > 200 ? output.substring(0, 200) + "..." : output}`);
6702
6702
  return output;
6703
6703
  } catch (error) {
6704
- logger2.error(`\u{1F527} [${mcpTool.name}] Exception during execution`, error);
6704
+ logger3.error(`\u{1F527} [${mcpTool.name}] Exception during execution`, error);
6705
6705
  if (axios2__default.default.isAxiosError(error)) {
6706
6706
  throw new Error(`MCP Runtime error: ${error.message}`);
6707
6707
  }
@@ -7076,6 +7076,68 @@ function isReasoningModel(modelName) {
7076
7076
  return modelName.includes("gpt-5") || modelName.includes("gpt-o1") || modelName.includes("gpt-o2") || modelName.includes("gpt-o3") || modelName.includes("gpt-o4") || /^gpt-(5|6|7|8|9)/.test(modelName) || /^gpt-o[1-4]/.test(modelName);
7077
7077
  }
7078
7078
  __name(isReasoningModel, "isReasoningModel");
7079
+ function toOptionalNumber(value) {
7080
+ if (value === void 0 || value === null || value === "") return void 0;
7081
+ const n = Number(value);
7082
+ return Number.isFinite(n) ? n : void 0;
7083
+ }
7084
+ __name(toOptionalNumber, "toOptionalNumber");
7085
+ var SAMPLING_PARAM_FREE_THRESHOLDS = {
7086
+ opus: {
7087
+ major: 4,
7088
+ minor: 7
7089
+ },
7090
+ sonnet: {
7091
+ major: 5,
7092
+ minor: 0
7093
+ },
7094
+ haiku: {
7095
+ major: 5,
7096
+ minor: 0
7097
+ }
7098
+ };
7099
+ var SAMPLING_PARAM_FREE_FAMILIES = /claude-(fable|mythos)\b/;
7100
+ var CLAUDE_FAMILY_VERSION = /claude-(opus|sonnet|haiku)-(\d{1,2})(?:-(\d{1,2}))?(?![\d.])/;
7101
+ function modelAcceptsSamplingParams(modelIdentifier) {
7102
+ if (!modelIdentifier) return true;
7103
+ const id = modelIdentifier.toLowerCase();
7104
+ if (SAMPLING_PARAM_FREE_FAMILIES.test(id)) return false;
7105
+ const match = CLAUDE_FAMILY_VERSION.exec(id);
7106
+ if (!match) return true;
7107
+ const [, family, majorRaw, minorRaw] = match;
7108
+ const threshold = SAMPLING_PARAM_FREE_THRESHOLDS[family];
7109
+ if (!threshold) return true;
7110
+ const major = Number(majorRaw);
7111
+ const minor = minorRaw === void 0 ? 0 : Number(minorRaw);
7112
+ const atOrAboveThreshold = major > threshold.major || major === threshold.major && minor >= threshold.minor;
7113
+ return !atOrAboveThreshold;
7114
+ }
7115
+ __name(modelAcceptsSamplingParams, "modelAcceptsSamplingParams");
7116
+ function resolveSamplingParams(modelIdentifiers, requested, supportsSamplingParams) {
7117
+ const accepted = supportsSamplingParams ?? modelIdentifiers.every((id) => modelAcceptsSamplingParams(id));
7118
+ if (accepted) {
7119
+ const params = {};
7120
+ if (requested.temperature !== void 0) params.temperature = requested.temperature;
7121
+ if (requested.topP !== void 0) params.topP = requested.topP;
7122
+ if (requested.topK !== void 0) params.topK = requested.topK;
7123
+ return {
7124
+ params,
7125
+ dropped: [],
7126
+ accepted: true
7127
+ };
7128
+ }
7129
+ const dropped = [
7130
+ "temperature",
7131
+ "topP",
7132
+ "topK"
7133
+ ].filter((key) => requested[key] !== void 0);
7134
+ return {
7135
+ params: {},
7136
+ dropped,
7137
+ accepted: false
7138
+ };
7139
+ }
7140
+ __name(resolveSamplingParams, "resolveSamplingParams");
7079
7141
  function hashToolsConfig(toolsConfig) {
7080
7142
  const sorted = toolsConfig.map((t) => `${t.toolName}:${t.enabled}:${JSON.stringify(t.config || {})}`).sort().join("|");
7081
7143
  return crypto.createHash("md5").update(sorted).digest("hex").slice(0, 16);
@@ -7128,13 +7190,122 @@ function buildOpenAIModelConfig(modelName, temperature, maxTokens, apiToken) {
7128
7190
  }
7129
7191
  return {
7130
7192
  modelName,
7131
- temperature,
7193
+ // Omit the key entirely when absent — an explicit `undefined` would still
7194
+ // be enumerable and can be forwarded as a null-ish value downstream.
7195
+ ...temperature !== void 0 && {
7196
+ temperature
7197
+ },
7132
7198
  maxTokens,
7133
7199
  streaming: true,
7134
7200
  openAIApiKey: apiToken
7135
7201
  };
7136
7202
  }
7137
7203
  __name(buildOpenAIModelConfig, "buildOpenAIModelConfig");
7204
+
7205
+ // src/models/reasoning-content.logic.ts
7206
+ function isReasoningBlock(block) {
7207
+ return typeof block === "object" && block !== null && block.type === "reasoning_content";
7208
+ }
7209
+ __name(isReasoningBlock, "isReasoningBlock");
7210
+ function isSendableReasoningBlock(block) {
7211
+ if (typeof block.redactedContent === "string" && block.redactedContent !== "") return true;
7212
+ const text = block.reasoningText?.text;
7213
+ return typeof text === "string" && text !== "";
7214
+ }
7215
+ __name(isSendableReasoningBlock, "isSendableReasoningBlock");
7216
+ function normalizeUnsendableBlock(block) {
7217
+ const signature = block.reasoningText?.signature;
7218
+ if (typeof signature !== "string" || signature === "") return null;
7219
+ return {
7220
+ type: "reasoning_content",
7221
+ reasoningText: {
7222
+ text: "",
7223
+ signature
7224
+ }
7225
+ };
7226
+ }
7227
+ __name(normalizeUnsendableBlock, "normalizeUnsendableBlock");
7228
+ function hasToolCalls(message) {
7229
+ const toolCalls = message.tool_calls;
7230
+ return Array.isArray(toolCalls) && toolCalls.length > 0;
7231
+ }
7232
+ __name(hasToolCalls, "hasToolCalls");
7233
+ function withContent(message, content) {
7234
+ const clone = Object.assign(Object.create(Object.getPrototypeOf(message)), message, {
7235
+ content
7236
+ });
7237
+ if (clone.lc_kwargs) clone.lc_kwargs = {
7238
+ ...clone.lc_kwargs,
7239
+ content
7240
+ };
7241
+ return clone;
7242
+ }
7243
+ __name(withContent, "withContent");
7244
+ function sanitizeMessageReasoning(message) {
7245
+ if (message.getType() !== "ai") return message;
7246
+ const content = message.content;
7247
+ if (!Array.isArray(content)) return message;
7248
+ const unsendable = content.filter((block) => isReasoningBlock(block) && !isSendableReasoningBlock(block));
7249
+ if (unsendable.length === 0) return message;
7250
+ const kept = content.filter((block) => !unsendable.includes(block));
7251
+ if (kept.length === 0 && !hasToolCalls(message)) {
7252
+ for (let i = unsendable.length - 1; i >= 0; i--) {
7253
+ const normalized = normalizeUnsendableBlock(unsendable[i]);
7254
+ if (normalized) return withContent(message, [
7255
+ normalized
7256
+ ]);
7257
+ }
7258
+ }
7259
+ return withContent(message, kept);
7260
+ }
7261
+ __name(sanitizeMessageReasoning, "sanitizeMessageReasoning");
7262
+ function sanitizeReasoningForBedrock(messages) {
7263
+ let sanitized = 0;
7264
+ let next;
7265
+ for (let i = 0; i < messages.length; i++) {
7266
+ const cleaned = sanitizeMessageReasoning(messages[i]);
7267
+ if (cleaned === messages[i]) continue;
7268
+ if (!next) next = [
7269
+ ...messages
7270
+ ];
7271
+ next[i] = cleaned;
7272
+ const before = messages[i].content.length;
7273
+ const after = cleaned.content.length;
7274
+ sanitized += Math.max(1, before - after);
7275
+ }
7276
+ return {
7277
+ messages: next ?? messages,
7278
+ sanitized
7279
+ };
7280
+ }
7281
+ __name(sanitizeReasoningForBedrock, "sanitizeReasoningForBedrock");
7282
+
7283
+ // src/models/bedrock-chat-model.ts
7284
+ var logger2 = new common.Logger("FlutchChatBedrockConverse");
7285
+ var FlutchChatBedrockConverse = class extends aws.ChatBedrockConverse {
7286
+ static {
7287
+ __name(this, "FlutchChatBedrockConverse");
7288
+ }
7289
+ static lc_name() {
7290
+ return "FlutchChatBedrockConverse";
7291
+ }
7292
+ sanitize(messages) {
7293
+ const { messages: cleaned, sanitized } = sanitizeReasoningForBedrock(messages);
7294
+ if (sanitized > 0) {
7295
+ logger2.debug(`Dropped ${sanitized} unsendable reasoning block(s) from outgoing history (model=${this.model})`);
7296
+ }
7297
+ return cleaned;
7298
+ }
7299
+ /** `.invoke()` / `.generate()` path. */
7300
+ async _generate(messages, options, runManager) {
7301
+ return super._generate(this.sanitize(messages), options, runManager);
7302
+ }
7303
+ /** `.stream()` / `streamEvents()` path (also used by `_generate` when the
7304
+ * model is constructed with `streaming: true` — sanitizing is idempotent). */
7305
+ async *_streamResponseChunks(messages, options, runManager) {
7306
+ yield* super._streamResponseChunks(this.sanitize(messages), options, runManager);
7307
+ }
7308
+ };
7138
7309
  var VoyageAIRerank = class extends document_compressors.BaseDocumentCompressor {
7139
7310
  static {
7140
7311
  __name(this, "VoyageAIRerank");
@@ -7206,10 +7377,10 @@ var ModelInitializer = class _ModelInitializer {
7206
7377
  [ModelProvider.COHERE]: "COHERE_API_KEY",
7207
7378
  [ModelProvider.VOYAGEAI]: "VOYAGEAI_API_KEY"
7208
7379
  };
7209
- constructor(configFetcher, logger2, apiKeyResolver) {
7380
+ constructor(configFetcher, logger3, apiKeyResolver) {
7210
7381
  this.configFetcher = configFetcher;
7211
7382
  this.apiKeyResolver = apiKeyResolver;
7212
- this.logger = logger2 || new common.Logger(_ModelInitializer.name);
7383
+ this.logger = logger3 || new common.Logger(_ModelInitializer.name);
7213
7384
  }
7214
7385
  /**
7215
7386
  * Resolve API key for a provider.
@@ -7232,6 +7403,32 @@ var ModelInitializer = class _ModelInitializer {
7232
7403
  return process.env.BEDROCK_AWS_REGION || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || "us-east-1";
7233
7404
  }
7234
7405
  /**
7406
+ * Resolve sampling parameters for a model, dropping them when the model
7407
+ * does not accept them (Claude Opus 4.7+, Claude 5 and newer).
7408
+ *
7409
+ * An explicitly requested value on such a model is **ignored with a warning**
7410
+ * rather than raising: the request must keep working, and the model runs at
7411
+ * its own default sampling behaviour. Pass `supportsSamplingParams: true` in
7412
+ * the config to force the params through anyway.
7413
+ *
7414
+ * @param modelIdentifiers every name the model is known by (catalog model
7415
+ * name, Bedrock model id, …) — a match on any of them drops the params
7416
+ * @param wasExplicit whether the caller explicitly asked for these values
7417
+ * (as opposed to inheriting a catalog/SDK default) — controls log level
7418
+ */
7419
+ resolveSampling(modelIdentifiers, requested, supportsSamplingParams, wasExplicit = false) {
7420
+ const resolved = resolveSamplingParams(modelIdentifiers, requested, supportsSamplingParams);
7421
+ if (!resolved.accepted && resolved.dropped.length > 0) {
7422
+ const message = `Model ${modelIdentifiers.filter(Boolean).join(" / ")} does not accept sampling parameters \u2014 ignoring ${resolved.dropped.join(", ")}. Set supportsSamplingParams: true to override.`;
7423
+ if (wasExplicit) {
7424
+ this.logger.warn(message);
7425
+ } else {
7426
+ this.logger.debug(message);
7427
+ }
7428
+ }
7429
+ return resolved.params;
7430
+ }
7431
+ /**
7235
7432
  * Generate hash from toolsConfig for cache key
7236
7433
  * Uses MD5 hash to create short, unique identifier
7237
7434
  */
@@ -7245,10 +7442,8 @@ var ModelInitializer = class _ModelInitializer {
7245
7442
  */
7246
7443
  generateModelCacheKey(config) {
7247
7444
  const base = generateModelCacheKey(config.modelId, config.temperature, config.maxTokens, config.toolsConfig, config.baseURL);
7248
- if (config.mcpServers && config.mcpServers.length > 0) {
7249
- return `${base}:mcp:${JSON.stringify(config.mcpServers)}`;
7250
- }
7251
- return base;
7445
+ const withMcp = config.mcpServers && config.mcpServers.length > 0 ? `${base}:mcp:${JSON.stringify(config.mcpServers)}` : base;
7446
+ return config.supportsSamplingParams === void 0 ? withMcp : `${withMcp}:sp:${config.supportsSamplingParams}`;
7252
7447
  }
7253
7448
  // Chat model creators
7254
7449
  chatModelCreators = {
@@ -7267,7 +7462,11 @@ var ModelInitializer = class _ModelInitializer {
7267
7462
  const routerURL = resolveRouterURL(baseURL);
7268
7463
  return new anthropic.ChatAnthropic({
7269
7464
  modelName,
7270
- temperature: defaultTemperature,
7465
+ // Claude Opus 4.7+ / Claude 5 reject `temperature` outright — the key
7466
+ // must be absent, not `undefined`.
7467
+ ...defaultTemperature !== void 0 && {
7468
+ temperature: defaultTemperature
7469
+ },
7271
7470
  maxTokens: defaultMaxTokens,
7272
7471
  anthropicApiKey: apiToken || this.resolveApiKey(ModelProvider.ANTHROPIC),
7273
7472
  ...routerURL && {
@@ -7283,7 +7482,9 @@ var ModelInitializer = class _ModelInitializer {
7283
7482
  const token = apiToken || this.resolveApiKey(ModelProvider.COHERE);
7284
7483
  return routerURL ? new cohere.ChatCohere({
7285
7484
  model: modelName,
7286
- temperature: defaultTemperature,
7485
+ ...defaultTemperature !== void 0 && {
7486
+ temperature: defaultTemperature
7487
+ },
7287
7488
  client: new cohereAi.CohereClient({
7288
7489
  token,
7289
7490
  baseUrl: routerURL,
@@ -7293,7 +7494,9 @@ var ModelInitializer = class _ModelInitializer {
7293
7494
  })
7294
7495
  }) : new cohere.ChatCohere({
7295
7496
  model: modelName,
7296
- temperature: defaultTemperature,
7497
+ ...defaultTemperature !== void 0 && {
7498
+ temperature: defaultTemperature
7499
+ },
7297
7500
  apiKey: token
7298
7501
  });
7299
7502
  },
@@ -7301,7 +7504,9 @@ var ModelInitializer = class _ModelInitializer {
7301
7504
  const routerURL = resolveRouterURL(baseURL);
7302
7505
  return new mistralai.ChatMistralAI({
7303
7506
  model: modelName,
7304
- temperature: defaultTemperature,
7507
+ ...defaultTemperature !== void 0 && {
7508
+ temperature: defaultTemperature
7509
+ },
7305
7510
  maxTokens: defaultMaxTokens,
7306
7511
  apiKey: apiToken || this.resolveApiKey(ModelProvider.MISTRAL),
7307
7512
  ...routerURL && {
@@ -7391,7 +7596,8 @@ var ModelInitializer = class _ModelInitializer {
7391
7596
  async initializeChatModelDirect(config, customTools) {
7392
7597
  const toolsConfig = normalizeToolConfigs(config.tools);
7393
7598
  const modelIdentifier = `${config.provider}:${config.modelName}`;
7394
- const cacheKey = generateModelCacheKey(modelIdentifier, config.temperature, config.maxTokens, toolsConfig, config.baseURL);
7599
+ const baseCacheKey = generateModelCacheKey(modelIdentifier, config.temperature, config.maxTokens, toolsConfig, config.baseURL);
7600
+ const cacheKey = config.supportsSamplingParams === void 0 ? baseCacheKey : `${baseCacheKey}:sp:${config.supportsSamplingParams}`;
7395
7601
  const cached = this.modelInstanceCache.get(cacheKey);
7396
7602
  if (cached) {
7397
7603
  this.logger.debug(`Using cached chat model instance: ${cacheKey}`);
@@ -7402,18 +7608,23 @@ var ModelInitializer = class _ModelInitializer {
7402
7608
  throw new Error(`Unknown provider "${provider}". Valid: ${Object.values(ModelProvider).join(", ")}`);
7403
7609
  }
7404
7610
  const apiToken = this.resolveApiKey(provider);
7405
- const temperature = config.temperature ?? 0.7;
7406
- const maxTokens = config.maxTokens ?? 4096;
7611
+ const maxTokens = toOptionalNumber(config.maxTokens) ?? 4096;
7612
+ const sampling = this.resolveSampling([
7613
+ config.modelName
7614
+ ], {
7615
+ temperature: toOptionalNumber(config.temperature) ?? 0.7
7616
+ }, config.supportsSamplingParams, config.temperature !== void 0);
7407
7617
  const modelConfig = {
7408
7618
  modelId: modelIdentifier,
7409
7619
  modelName: config.modelName,
7410
7620
  provider,
7411
7621
  modelType: ModelType.CHAT,
7412
- defaultTemperature: Number(temperature),
7413
- defaultMaxTokens: Number(maxTokens),
7622
+ defaultTemperature: sampling.temperature,
7623
+ defaultMaxTokens: maxTokens,
7414
7624
  apiToken,
7415
7625
  requiresApiKey: true,
7416
- baseURL: config.baseURL
7626
+ baseURL: config.baseURL,
7627
+ supportsSamplingParams: config.supportsSamplingParams
7417
7628
  };
7418
7629
  this.logger.debug(`Creating chat model: ${modelIdentifier} (apiKeyResolved=${!!apiToken})`);
7419
7630
  const creator = this.chatModelCreators[provider];
@@ -7448,19 +7659,29 @@ var ModelInitializer = class _ModelInitializer {
7448
7659
  if (modelConfig.modelType !== ModelType.CHAT) {
7449
7660
  throw new Error(`Model ${config.modelId} is not a chat model (type: ${modelConfig.modelType})`);
7450
7661
  }
7662
+ const requestedTemperature = toOptionalNumber(config.temperature) ?? toOptionalNumber(modelConfig.defaultTemperature);
7663
+ const sampling = this.resolveSampling([
7664
+ modelConfig.modelName,
7665
+ modelConfig.bedrockModelId
7666
+ ], {
7667
+ temperature: requestedTemperature
7668
+ }, config.supportsSamplingParams ?? modelConfig.supportsSamplingParams, config.temperature !== void 0);
7451
7669
  const finalConfig = {
7452
7670
  ...modelConfig,
7453
- defaultTemperature: Number(config.temperature ?? modelConfig.defaultTemperature),
7454
- defaultMaxTokens: Number(config.maxTokens ?? modelConfig.defaultMaxTokens),
7671
+ defaultTemperature: sampling.temperature,
7672
+ defaultMaxTokens: toOptionalNumber(config.maxTokens) ?? toOptionalNumber(modelConfig.defaultMaxTokens),
7455
7673
  baseURL: config.baseURL ?? modelConfig.baseURL
7456
7674
  };
7457
7675
  this.logger.debug(`Creating new chat model instance: ${cacheKey}`);
7458
7676
  let model;
7459
7677
  if (finalConfig.useBedrock && finalConfig.bedrockModelId) {
7460
- model = new aws.ChatBedrockConverse({
7678
+ model = new FlutchChatBedrockConverse({
7461
7679
  model: finalConfig.bedrockModelId,
7462
7680
  region: this.resolveBedrockRegion(),
7463
- temperature: finalConfig.defaultTemperature,
7681
+ // Key omitted (not `undefined`) for models that reject sampling params.
7682
+ ...finalConfig.defaultTemperature !== void 0 && {
7683
+ temperature: finalConfig.defaultTemperature
7684
+ },
7464
7685
  maxTokens: finalConfig.defaultMaxTokens,
7465
7686
  streaming: true
7466
7687
  });
@@ -8319,6 +8540,7 @@ exports.DEFAULT_ROUTER_URL = DEFAULT_ROUTER_URL;
8319
8540
  exports.DEFAULT_TRACER_OPTIONS = DEFAULT_TRACER_OPTIONS;
8320
8541
  exports.Endpoint = Endpoint;
8321
8542
  exports.FileTokenStore = FileTokenStore;
8543
+ exports.FlutchChatBedrockConverse = FlutchChatBedrockConverse;
8322
8544
  exports.GraphEngineType = GraphEngineType;
8323
8545
  exports.GraphManifestSchema = GraphManifestSchema;
8324
8546
  exports.GraphManifestValidator = GraphManifestValidator;
@@ -8332,6 +8554,7 @@ exports.ModelType = ModelType;
8332
8554
  exports.MongoTokenStore = MongoTokenStore;
8333
8555
  exports.OAuthTokenManager = OAuthTokenManager;
8334
8556
  exports.RetrieverSearchType = RetrieverSearchType;
8557
+ exports.SAMPLING_PARAM_FREE_THRESHOLDS = SAMPLING_PARAM_FREE_THRESHOLDS;
8335
8558
  exports.StreamChannel = StreamChannel;
8336
8559
  exports.UIEndpoint = UIEndpoint;
8337
8560
  exports.UniversalCallbackService = UniversalCallbackService;
@@ -8371,15 +8594,22 @@ exports.hasCallbacks = hasCallbacks;
8371
8594
  exports.hasUIEndpoints = hasUIEndpoints;
8372
8595
  exports.hashToolsConfig = hashToolsConfig;
8373
8596
  exports.isInternalMode = isInternalMode;
8597
+ exports.isReasoningBlock = isReasoningBlock;
8374
8598
  exports.isReasoningModel = isReasoningModel;
8599
+ exports.isSendableReasoningBlock = isSendableReasoningBlock;
8375
8600
  exports.loadOAuthProviders = loadOAuthProviders;
8601
+ exports.modelAcceptsSamplingParams = modelAcceptsSamplingParams;
8376
8602
  exports.normalizeToolConfigs = normalizeToolConfigs;
8377
8603
  exports.registerFinanceExampleCallback = registerFinanceExampleCallback;
8378
8604
  exports.registerUIEndpointsFromClass = registerUIEndpointsFromClass;
8379
8605
  exports.resolveOAuthProviderConfig = resolveOAuthProviderConfig;
8380
8606
  exports.resolveRouterURL = resolveRouterURL;
8607
+ exports.resolveSamplingParams = resolveSamplingParams;
8608
+ exports.sanitizeMessageReasoning = sanitizeMessageReasoning;
8609
+ exports.sanitizeReasoningForBedrock = sanitizeReasoningForBedrock;
8381
8610
  exports.sanitizeTraceData = sanitizeTraceData;
8382
8611
  exports.storeAttachmentData = storeAttachmentData;
8612
+ exports.toOptionalNumber = toOptionalNumber;
8383
8613
  exports.traceApiCall = traceApiCall;
8384
8614
  exports.withFlutchContext = withFlutchContext;
8385
8615
  exports.wrapCohereFetcher = wrapCohereFetcher;