@flutchai/flutch-sdk 0.6.2 → 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.js CHANGED
@@ -1878,13 +1878,13 @@ async function findAvailablePort(startPort) {
1878
1878
  throw new Error(`No available ports found in range ${startPort}-${startPort + 99}`);
1879
1879
  }
1880
1880
  __name(findAvailablePort, "findAvailablePort");
1881
- async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1881
+ async function registerWithServiceDiscovery(AppModule, port, logger3, app) {
1882
1882
  try {
1883
- logger2.debug("[SERVICE_DISCOVERY] Starting service discovery registration...");
1883
+ logger3.debug("[SERVICE_DISCOVERY] Starting service discovery registration...");
1884
1884
  const { FileBasedDiscovery: FileBasedDiscovery2 } = await Promise.resolve().then(() => (init_file_based_discovery(), file_based_discovery_exports));
1885
- logger2.debug("[SERVICE_DISCOVERY] FileBasedDiscovery imported successfully");
1885
+ logger3.debug("[SERVICE_DISCOVERY] FileBasedDiscovery imported successfully");
1886
1886
  const discovery = new FileBasedDiscovery2();
1887
- logger2.debug("[SERVICE_DISCOVERY] FileBasedDiscovery instance created");
1887
+ logger3.debug("[SERVICE_DISCOVERY] FileBasedDiscovery instance created");
1888
1888
  const serviceName = AppModule.name.replace("Module", "").toLowerCase();
1889
1889
  let graphTypes = [];
1890
1890
  try {
@@ -1893,26 +1893,26 @@ async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1893
1893
  const builderRegistry = app.get(BuilderRegistryService2, {
1894
1894
  strict: false
1895
1895
  });
1896
- logger2.debug(`BuilderRegistryService found in DI: ${!!builderRegistry}`);
1896
+ logger3.debug(`BuilderRegistryService found in DI: ${!!builderRegistry}`);
1897
1897
  if (builderRegistry) {
1898
1898
  const builders = builderRegistry.getBuilders();
1899
- logger2.debug(`Found ${builders.length} builders in registry`);
1899
+ logger3.debug(`Found ${builders.length} builders in registry`);
1900
1900
  const baseGraphTypes = builders.map((builder) => builder.graphType);
1901
- logger2.debug(`Base graph types: [${baseGraphTypes.join(", ")}]`);
1901
+ logger3.debug(`Base graph types: [${baseGraphTypes.join(", ")}]`);
1902
1902
  try {
1903
- logger2.debug("Attempting to import VersionedGraphService...");
1903
+ logger3.debug("Attempting to import VersionedGraphService...");
1904
1904
  const { VersionedGraphService: VersionedGraphService2 } = await Promise.resolve().then(() => (init_versioned_graph_service(), versioned_graph_service_exports));
1905
- logger2.debug("VersionedGraphService imported successfully");
1905
+ logger3.debug("VersionedGraphService imported successfully");
1906
1906
  const versionedService = app.get(VersionedGraphService2, {
1907
1907
  strict: false
1908
1908
  });
1909
- logger2.debug(`VersionedGraphService found in DI: ${!!versionedService}`);
1909
+ logger3.debug(`VersionedGraphService found in DI: ${!!versionedService}`);
1910
1910
  if (versionedService) {
1911
1911
  const allVersionedTypes = [];
1912
1912
  for (const baseType of baseGraphTypes) {
1913
- logger2.debug(`Getting versions for base type: ${baseType}`);
1913
+ logger3.debug(`Getting versions for base type: ${baseType}`);
1914
1914
  const versions = versionedService.getAvailableVersions(baseType);
1915
- logger2.debug(`Found ${versions.length} versions for ${baseType}: [${versions.join(", ")}]`);
1915
+ logger3.debug(`Found ${versions.length} versions for ${baseType}: [${versions.join(", ")}]`);
1916
1916
  if (versions.length > 0) {
1917
1917
  allVersionedTypes.push(baseType);
1918
1918
  versions.forEach((version) => {
@@ -1923,23 +1923,23 @@ async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1923
1923
  }
1924
1924
  }
1925
1925
  graphTypes = allVersionedTypes;
1926
- logger2.debug(`Found ${baseGraphTypes.length} base types with ${graphTypes.length} total versioned types: ${graphTypes.join(", ")}`);
1926
+ logger3.debug(`Found ${baseGraphTypes.length} base types with ${graphTypes.length} total versioned types: ${graphTypes.join(", ")}`);
1927
1927
  } else {
1928
1928
  graphTypes = baseGraphTypes;
1929
- logger2.debug(`VersionedGraphService not found in DI container, using base types: ${graphTypes.join(", ")}`);
1929
+ logger3.debug(`VersionedGraphService not found in DI container, using base types: ${graphTypes.join(", ")}`);
1930
1930
  }
1931
1931
  } catch (error) {
1932
1932
  graphTypes = baseGraphTypes;
1933
- logger2.debug(`Failed to get versioned types, using base types: ${error.message}`);
1934
- logger2.debug(`Stack trace: ${error.stack}`);
1933
+ logger3.debug(`Failed to get versioned types, using base types: ${error.message}`);
1934
+ logger3.debug(`Stack trace: ${error.stack}`);
1935
1935
  }
1936
1936
  }
1937
1937
  }
1938
1938
  } catch (error) {
1939
- logger2.debug(`Failed to get graph types from builders: ${error.message}`);
1939
+ logger3.debug(`Failed to get graph types from builders: ${error.message}`);
1940
1940
  }
1941
1941
  if (graphTypes.length === 0) {
1942
- logger2.debug("No builders found, using service name as graph type");
1942
+ logger3.debug("No builders found, using service name as graph type");
1943
1943
  graphTypes = [
1944
1944
  serviceName
1945
1945
  ];
@@ -1950,21 +1950,21 @@ async function registerWithServiceDiscovery(AppModule, port, logger2, app) {
1950
1950
  startTime: (/* @__PURE__ */ new Date()).toISOString(),
1951
1951
  version: process.env.npm_package_version || "1.0.0"
1952
1952
  }, graphTypes);
1953
- logger2.log(`\u{1F4E1} Service registered with discovery: ${serviceName} (types: ${graphTypes.join(", ")})`);
1953
+ logger3.log(`\u{1F4E1} Service registered with discovery: ${serviceName} (types: ${graphTypes.join(", ")})`);
1954
1954
  } catch (error) {
1955
- logger2.warn(`Failed to register with service discovery: ${error.message}`);
1955
+ logger3.warn(`Failed to register with service discovery: ${error.message}`);
1956
1956
  }
1957
1957
  }
1958
1958
  __name(registerWithServiceDiscovery, "registerWithServiceDiscovery");
1959
1959
  async function bootstrap(AppModule, options = {}) {
1960
1960
  setupRedisMock();
1961
1961
  const app = await NestFactory.create(AppModule);
1962
- const logger2 = new Logger("Bootstrap");
1962
+ const logger3 = new Logger("Bootstrap");
1963
1963
  const requestedPort = options.port || parseInt(process.env.PORT || "3100", 10);
1964
1964
  const port = await findAvailablePort(requestedPort);
1965
1965
  const globalPrefix = options.globalPrefix;
1966
1966
  if (port !== requestedPort) {
1967
- logger2.warn(`Port ${requestedPort} is busy, using port ${port} instead`);
1967
+ logger3.warn(`Port ${requestedPort} is busy, using port ${port} instead`);
1968
1968
  }
1969
1969
  if (globalPrefix) {
1970
1970
  app.setGlobalPrefix(globalPrefix);
@@ -1983,13 +1983,13 @@ async function bootstrap(AppModule, options = {}) {
1983
1983
  SwaggerModule.setup("api/docs", app, document);
1984
1984
  await app.listen(port);
1985
1985
  const baseUrl = globalPrefix ? `http://localhost:${port}/${globalPrefix}` : `http://localhost:${port}`;
1986
- logger2.log(`\u{1F680} Graph service is running on: ${baseUrl}`);
1987
- logger2.log(`\u{1F4DA} API Documentation: http://localhost:${port}/api/docs`);
1986
+ logger3.log(`\u{1F680} Graph service is running on: ${baseUrl}`);
1987
+ logger3.log(`\u{1F4DA} API Documentation: http://localhost:${port}/api/docs`);
1988
1988
  if (process.env.NODE_ENV !== "production") {
1989
- logger2.debug(`Attempting service discovery registration (NODE_ENV: ${process.env.NODE_ENV || "undefined"})`);
1990
- await registerWithServiceDiscovery(AppModule, port, logger2, app);
1989
+ logger3.debug(`Attempting service discovery registration (NODE_ENV: ${process.env.NODE_ENV || "undefined"})`);
1990
+ await registerWithServiceDiscovery(AppModule, port, logger3, app);
1991
1991
  } else {
1992
- logger2.debug(`Skipping service discovery registration (NODE_ENV: ${process.env.NODE_ENV})`);
1992
+ logger3.debug(`Skipping service discovery registration (NODE_ENV: ${process.env.NODE_ENV})`);
1993
1993
  }
1994
1994
  return app;
1995
1995
  }
@@ -4842,7 +4842,7 @@ function clearAttachmentDataStore(threadId) {
4842
4842
  }
4843
4843
  __name(clearAttachmentDataStore, "clearAttachmentDataStore");
4844
4844
  async function executeToolWithAttachments(params) {
4845
- const { toolCall, mcpClient, enrichedArgs, executionContext, config, attachments, logger: logger2, threshold = DEFAULT_ATTACHMENT_THRESHOLD, injectIntoArg = "data", sourceAttachmentId, threadId, toolSchema, mcpServers } = params;
4845
+ const { toolCall, mcpClient, enrichedArgs, executionContext, config, attachments, logger: logger3, threshold = DEFAULT_ATTACHMENT_THRESHOLD, injectIntoArg = "data", sourceAttachmentId, threadId, toolSchema, mcpServers } = params;
4846
4846
  const argsWithInjection = {
4847
4847
  ...enrichedArgs
4848
4848
  };
@@ -4855,12 +4855,12 @@ async function executeToolWithAttachments(params) {
4855
4855
  const data = storedData !== void 0 ? storedData : attachment.data;
4856
4856
  if (data != null) {
4857
4857
  argsWithInjection[injectIntoArg] = typeof data === "string" ? data : JSON.stringify(data);
4858
- logger2?.debug(`[Attachment] Auto-injected data from attachment "${attachment.toolCallId}" into ${toolCall.name}.${injectIntoArg} (source: ${storedData !== void 0 ? "memory" : "state"})`);
4858
+ logger3?.debug(`[Attachment] Auto-injected data from attachment "${attachment.toolCallId}" into ${toolCall.name}.${injectIntoArg} (source: ${storedData !== void 0 ? "memory" : "state"})`);
4859
4859
  }
4860
4860
  }
4861
4861
  }
4862
4862
  } catch (e) {
4863
- logger2?.warn(`[Attachment] Auto-injection failed: ${e}`);
4863
+ logger3?.warn(`[Attachment] Auto-injection failed: ${e}`);
4864
4864
  }
4865
4865
  const { content, success, rawResult } = await mcpClient.executeToolWithEvents(toolCall.id, toolCall.name, argsWithInjection, executionContext, config, mcpServers);
4866
4866
  try {
@@ -4871,7 +4871,7 @@ async function executeToolWithAttachments(params) {
4871
4871
  ...attachment,
4872
4872
  data: null
4873
4873
  };
4874
- logger2?.debug(`[Attachment] Stored large result (${content.length} chars) as attachment "${toolCall.id}" (data in memory, metadata in state)`);
4874
+ logger3?.debug(`[Attachment] Stored large result (${content.length} chars) as attachment "${toolCall.id}" (data in memory, metadata in state)`);
4875
4875
  const toolMessage2 = new ToolMessage({
4876
4876
  content: attachment.summary,
4877
4877
  tool_call_id: toolCall.id,
@@ -4886,7 +4886,7 @@ async function executeToolWithAttachments(params) {
4886
4886
  };
4887
4887
  }
4888
4888
  } catch (e) {
4889
- logger2?.warn(`[Attachment] Failed to create attachment, using full content: ${e}`);
4889
+ logger3?.warn(`[Attachment] Failed to create attachment, using full content: ${e}`);
4890
4890
  }
4891
4891
  const toolMessage = new ToolMessage({
4892
4892
  content,
@@ -6200,7 +6200,7 @@ function createMetaBuilder(config, versionedGraphService, moduleRef) {
6200
6200
  }
6201
6201
  __name(createMetaBuilder, "createMetaBuilder");
6202
6202
  function buildCheckpointerProviders(options) {
6203
- const logger2 = new Logger("UniversalGraphModule");
6203
+ const logger3 = new Logger("UniversalGraphModule");
6204
6204
  if (options.postgres !== void 0) {
6205
6205
  return [
6206
6206
  {
@@ -6214,7 +6214,7 @@ function buildCheckpointerProviders(options) {
6214
6214
  if (!connString) {
6215
6215
  throw new Error("[UniversalGraphModule] Postgres checkpointer: provide postgres.connectionString or set the DATABASE_URL environment variable.");
6216
6216
  }
6217
- logger2.log(`Checkpointer: PostgreSQL (${connString.replace(/:[^:@]+@/, ":***@")})`);
6217
+ logger3.log(`Checkpointer: PostgreSQL (${connString.replace(/:[^:@]+@/, ":***@")})`);
6218
6218
  const saver = PostgresSaver.fromConnString(connString, {
6219
6219
  ...options.postgres.schema ? {
6220
6220
  schema: options.postgres.schema
@@ -6236,7 +6236,7 @@ function buildCheckpointerProviders(options) {
6236
6236
  if (!mongoUri) {
6237
6237
  throw new Error("[UniversalGraphModule] MongoDB checkpointer: provide mongodb.uri or set the MONGODB_URI environment variable.");
6238
6238
  }
6239
- logger2.log(`Checkpointer: MongoDB (${mongoUri.substring(0, 50)}...)`);
6239
+ logger3.log(`Checkpointer: MongoDB (${mongoUri.substring(0, 50)}...)`);
6240
6240
  await mongoose.connect(mongoUri, {
6241
6241
  dbName
6242
6242
  });
@@ -6270,7 +6270,7 @@ function buildCheckpointerProviders(options) {
6270
6270
  provide: "CHECKPOINTER",
6271
6271
  useFactory: /* @__PURE__ */ __name(async () => {
6272
6272
  const { MemorySaver } = await import('@langchain/langgraph');
6273
- logger2.warn("Checkpointer: MemorySaver (in-process, no persistence). Configure postgres or mongodb in UniversalGraphModule.forRoot() for production.");
6273
+ logger3.warn("Checkpointer: MemorySaver (in-process, no persistence). Configure postgres or mongodb in UniversalGraphModule.forRoot() for production.");
6274
6274
  return new MemorySaver();
6275
6275
  }, "useFactory")
6276
6276
  }
@@ -6309,8 +6309,8 @@ var UniversalGraphModule = class _UniversalGraphModule {
6309
6309
  const redisUrl = options.redis?.url ?? process.env.REDIS_URL;
6310
6310
  if (redisUrl) {
6311
6311
  const Redis2 = __require("ioredis");
6312
- const logger2 = new Logger("UniversalGraphModule");
6313
- logger2.log(`Callbacks: Redis (${redisUrl.replace(/:[^:@]+@/, ":***@")})`);
6312
+ const logger3 = new Logger("UniversalGraphModule");
6313
+ logger3.log(`Callbacks: Redis (${redisUrl.replace(/:[^:@]+@/, ":***@")})`);
6314
6314
  return new Redis2(redisUrl);
6315
6315
  }
6316
6316
  const IORedisMock = __require("ioredis-mock");
@@ -6594,7 +6594,7 @@ var McpConverter = class _McpConverter {
6594
6594
  * Convert a single MCP tool to LangChain DynamicStructuredTool
6595
6595
  */
6596
6596
  convertTool(mcpTool) {
6597
- const logger2 = this.logger;
6597
+ const logger3 = this.logger;
6598
6598
  const mcpRuntimeUrl = this.mcpRuntimeUrl;
6599
6599
  let enhancedDescription = mcpTool.description;
6600
6600
  if (mcpTool.inputSchema?.properties) {
@@ -6614,12 +6614,12 @@ ${paramDescriptions.join("\n")}`;
6614
6614
  }
6615
6615
  }
6616
6616
  const schema = this.jsonSchemaToZod(mcpTool.inputSchema);
6617
- logger2.debug(`\u{1F527} [${mcpTool.name}] Original schema:`, JSON.stringify(mcpTool.inputSchema, null, 2));
6618
- logger2.debug(`\u{1F527} [${mcpTool.name}] Using schema type: ${schema?._def?.typeName ?? "unknown"}`);
6617
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Original schema:`, JSON.stringify(mcpTool.inputSchema, null, 2));
6618
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Using schema type: ${schema?._def?.typeName ?? "unknown"}`);
6619
6619
  if (schema?._def?.shape && typeof schema._def.shape === "function") {
6620
6620
  try {
6621
6621
  const shape = schema._def.shape();
6622
- logger2.debug(`\u{1F527} [${mcpTool.name}] Converted Zod schema shape:`, JSON.stringify(Object.entries(shape).reduce((acc, [key, val]) => {
6622
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Converted Zod schema shape:`, JSON.stringify(Object.entries(shape).reduce((acc, [key, val]) => {
6623
6623
  acc[key] = {
6624
6624
  type: val?._def?.typeName,
6625
6625
  description: val?._def?.description,
@@ -6628,50 +6628,50 @@ ${paramDescriptions.join("\n")}`;
6628
6628
  return acc;
6629
6629
  }, {}), null, 2));
6630
6630
  } catch (error) {
6631
- logger2.debug(`\u{1F527} [${mcpTool.name}] Could not extract Zod schema shape: ${error}`);
6631
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Could not extract Zod schema shape: ${error}`);
6632
6632
  }
6633
6633
  }
6634
6634
  try {
6635
6635
  const convertedJsonSchema = zodToJsonSchema(schema);
6636
- logger2.warn(`\u{1F527} [${mcpTool.name}] JSON Schema that LangChain will use:`, JSON.stringify(convertedJsonSchema, null, 2));
6636
+ logger3.warn(`\u{1F527} [${mcpTool.name}] JSON Schema that LangChain will use:`, JSON.stringify(convertedJsonSchema, null, 2));
6637
6637
  } catch (error) {
6638
- logger2.warn(`\u{1F527} [${mcpTool.name}] Could not convert Zod to JSON Schema: ${error}`);
6638
+ logger3.warn(`\u{1F527} [${mcpTool.name}] Could not convert Zod to JSON Schema: ${error}`);
6639
6639
  }
6640
6640
  return new DynamicStructuredTool({
6641
6641
  name: mcpTool.name,
6642
6642
  description: enhancedDescription,
6643
6643
  schema,
6644
6644
  func: /* @__PURE__ */ __name(async (input, _runManager, config) => {
6645
- logger2.log(`\u{1F527} [${mcpTool.name}] LLM INPUT: ${JSON.stringify(input)}`);
6645
+ logger3.log(`\u{1F527} [${mcpTool.name}] LLM INPUT: ${JSON.stringify(input)}`);
6646
6646
  const configurable = config?.configurable;
6647
6647
  const context = {
6648
6648
  agentId: configurable?.agentId,
6649
6649
  userId: configurable?.userId,
6650
6650
  threadId: configurable?.thread_id
6651
6651
  };
6652
- logger2.debug(`\u{1F527} [${mcpTool.name}] Execution context: ${JSON.stringify(context)}`);
6652
+ logger3.debug(`\u{1F527} [${mcpTool.name}] Execution context: ${JSON.stringify(context)}`);
6653
6653
  try {
6654
6654
  const request = {
6655
6655
  name: mcpTool.name,
6656
6656
  arguments: input ?? {},
6657
6657
  context
6658
6658
  };
6659
- logger2.log(`\u{1F527} [${mcpTool.name}] Calling MCP Runtime...`);
6659
+ logger3.log(`\u{1F527} [${mcpTool.name}] Calling MCP Runtime...`);
6660
6660
  const response = await axios2.post(`${mcpRuntimeUrl}/tools/execute`, request, {
6661
6661
  timeout: 3e4
6662
6662
  });
6663
6663
  const result = response.data;
6664
- logger2.log(`\u{1F527} [${mcpTool.name}] MCP Runtime response: success=${result.success}`);
6664
+ logger3.log(`\u{1F527} [${mcpTool.name}] MCP Runtime response: success=${result.success}`);
6665
6665
  if (!result.success) {
6666
6666
  const errorMessage = result.error || "Tool execution failed";
6667
- logger2.error(`\u{1F527} [${mcpTool.name}] MCP Runtime error: ${errorMessage}`);
6667
+ logger3.error(`\u{1F527} [${mcpTool.name}] MCP Runtime error: ${errorMessage}`);
6668
6668
  throw new Error(errorMessage);
6669
6669
  }
6670
6670
  const output = typeof result.result === "string" ? result.result : JSON.stringify(result.result, null, 2);
6671
- logger2.log(`\u{1F527} [${mcpTool.name}] TOOL OUTPUT: ${output.length > 200 ? output.substring(0, 200) + "..." : output}`);
6671
+ logger3.log(`\u{1F527} [${mcpTool.name}] TOOL OUTPUT: ${output.length > 200 ? output.substring(0, 200) + "..." : output}`);
6672
6672
  return output;
6673
6673
  } catch (error) {
6674
- logger2.error(`\u{1F527} [${mcpTool.name}] Exception during execution`, error);
6674
+ logger3.error(`\u{1F527} [${mcpTool.name}] Exception during execution`, error);
6675
6675
  if (axios2.isAxiosError(error)) {
6676
6676
  throw new Error(`MCP Runtime error: ${error.message}`);
6677
6677
  }
@@ -7046,6 +7046,68 @@ function isReasoningModel(modelName) {
7046
7046
  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);
7047
7047
  }
7048
7048
  __name(isReasoningModel, "isReasoningModel");
7049
+ function toOptionalNumber(value) {
7050
+ if (value === void 0 || value === null || value === "") return void 0;
7051
+ const n = Number(value);
7052
+ return Number.isFinite(n) ? n : void 0;
7053
+ }
7054
+ __name(toOptionalNumber, "toOptionalNumber");
7055
+ var SAMPLING_PARAM_FREE_THRESHOLDS = {
7056
+ opus: {
7057
+ major: 4,
7058
+ minor: 7
7059
+ },
7060
+ sonnet: {
7061
+ major: 5,
7062
+ minor: 0
7063
+ },
7064
+ haiku: {
7065
+ major: 5,
7066
+ minor: 0
7067
+ }
7068
+ };
7069
+ var SAMPLING_PARAM_FREE_FAMILIES = /claude-(fable|mythos)\b/;
7070
+ var CLAUDE_FAMILY_VERSION = /claude-(opus|sonnet|haiku)-(\d{1,2})(?:-(\d{1,2}))?(?![\d.])/;
7071
+ function modelAcceptsSamplingParams(modelIdentifier) {
7072
+ if (!modelIdentifier) return true;
7073
+ const id = modelIdentifier.toLowerCase();
7074
+ if (SAMPLING_PARAM_FREE_FAMILIES.test(id)) return false;
7075
+ const match = CLAUDE_FAMILY_VERSION.exec(id);
7076
+ if (!match) return true;
7077
+ const [, family, majorRaw, minorRaw] = match;
7078
+ const threshold = SAMPLING_PARAM_FREE_THRESHOLDS[family];
7079
+ if (!threshold) return true;
7080
+ const major = Number(majorRaw);
7081
+ const minor = minorRaw === void 0 ? 0 : Number(minorRaw);
7082
+ const atOrAboveThreshold = major > threshold.major || major === threshold.major && minor >= threshold.minor;
7083
+ return !atOrAboveThreshold;
7084
+ }
7085
+ __name(modelAcceptsSamplingParams, "modelAcceptsSamplingParams");
7086
+ function resolveSamplingParams(modelIdentifiers, requested, supportsSamplingParams) {
7087
+ const accepted = supportsSamplingParams ?? modelIdentifiers.every((id) => modelAcceptsSamplingParams(id));
7088
+ if (accepted) {
7089
+ const params = {};
7090
+ if (requested.temperature !== void 0) params.temperature = requested.temperature;
7091
+ if (requested.topP !== void 0) params.topP = requested.topP;
7092
+ if (requested.topK !== void 0) params.topK = requested.topK;
7093
+ return {
7094
+ params,
7095
+ dropped: [],
7096
+ accepted: true
7097
+ };
7098
+ }
7099
+ const dropped = [
7100
+ "temperature",
7101
+ "topP",
7102
+ "topK"
7103
+ ].filter((key) => requested[key] !== void 0);
7104
+ return {
7105
+ params: {},
7106
+ dropped,
7107
+ accepted: false
7108
+ };
7109
+ }
7110
+ __name(resolveSamplingParams, "resolveSamplingParams");
7049
7111
  function hashToolsConfig(toolsConfig) {
7050
7112
  const sorted = toolsConfig.map((t) => `${t.toolName}:${t.enabled}:${JSON.stringify(t.config || {})}`).sort().join("|");
7051
7113
  return createHash("md5").update(sorted).digest("hex").slice(0, 16);
@@ -7098,13 +7160,122 @@ function buildOpenAIModelConfig(modelName, temperature, maxTokens, apiToken) {
7098
7160
  }
7099
7161
  return {
7100
7162
  modelName,
7101
- temperature,
7163
+ // Omit the key entirely when absent — an explicit `undefined` would still
7164
+ // be enumerable and can be forwarded as a null-ish value downstream.
7165
+ ...temperature !== void 0 && {
7166
+ temperature
7167
+ },
7102
7168
  maxTokens,
7103
7169
  streaming: true,
7104
7170
  openAIApiKey: apiToken
7105
7171
  };
7106
7172
  }
7107
7173
  __name(buildOpenAIModelConfig, "buildOpenAIModelConfig");
7174
+
7175
+ // src/models/reasoning-content.logic.ts
7176
+ function isReasoningBlock(block) {
7177
+ return typeof block === "object" && block !== null && block.type === "reasoning_content";
7178
+ }
7179
+ __name(isReasoningBlock, "isReasoningBlock");
7180
+ function isSendableReasoningBlock(block) {
7181
+ if (typeof block.redactedContent === "string" && block.redactedContent !== "") return true;
7182
+ const text = block.reasoningText?.text;
7183
+ return typeof text === "string" && text !== "";
7184
+ }
7185
+ __name(isSendableReasoningBlock, "isSendableReasoningBlock");
7186
+ function normalizeUnsendableBlock(block) {
7187
+ const signature = block.reasoningText?.signature;
7188
+ if (typeof signature !== "string" || signature === "") return null;
7189
+ return {
7190
+ type: "reasoning_content",
7191
+ reasoningText: {
7192
+ text: "",
7193
+ signature
7194
+ }
7195
+ };
7196
+ }
7197
+ __name(normalizeUnsendableBlock, "normalizeUnsendableBlock");
7198
+ function hasToolCalls(message) {
7199
+ const toolCalls = message.tool_calls;
7200
+ return Array.isArray(toolCalls) && toolCalls.length > 0;
7201
+ }
7202
+ __name(hasToolCalls, "hasToolCalls");
7203
+ function withContent(message, content) {
7204
+ const clone = Object.assign(Object.create(Object.getPrototypeOf(message)), message, {
7205
+ content
7206
+ });
7207
+ if (clone.lc_kwargs) clone.lc_kwargs = {
7208
+ ...clone.lc_kwargs,
7209
+ content
7210
+ };
7211
+ return clone;
7212
+ }
7213
+ __name(withContent, "withContent");
7214
+ function sanitizeMessageReasoning(message) {
7215
+ if (message.getType() !== "ai") return message;
7216
+ const content = message.content;
7217
+ if (!Array.isArray(content)) return message;
7218
+ const unsendable = content.filter((block) => isReasoningBlock(block) && !isSendableReasoningBlock(block));
7219
+ if (unsendable.length === 0) return message;
7220
+ const kept = content.filter((block) => !unsendable.includes(block));
7221
+ if (kept.length === 0 && !hasToolCalls(message)) {
7222
+ for (let i = unsendable.length - 1; i >= 0; i--) {
7223
+ const normalized = normalizeUnsendableBlock(unsendable[i]);
7224
+ if (normalized) return withContent(message, [
7225
+ normalized
7226
+ ]);
7227
+ }
7228
+ }
7229
+ return withContent(message, kept);
7230
+ }
7231
+ __name(sanitizeMessageReasoning, "sanitizeMessageReasoning");
7232
+ function sanitizeReasoningForBedrock(messages) {
7233
+ let sanitized = 0;
7234
+ let next;
7235
+ for (let i = 0; i < messages.length; i++) {
7236
+ const cleaned = sanitizeMessageReasoning(messages[i]);
7237
+ if (cleaned === messages[i]) continue;
7238
+ if (!next) next = [
7239
+ ...messages
7240
+ ];
7241
+ next[i] = cleaned;
7242
+ const before = messages[i].content.length;
7243
+ const after = cleaned.content.length;
7244
+ sanitized += Math.max(1, before - after);
7245
+ }
7246
+ return {
7247
+ messages: next ?? messages,
7248
+ sanitized
7249
+ };
7250
+ }
7251
+ __name(sanitizeReasoningForBedrock, "sanitizeReasoningForBedrock");
7252
+
7253
+ // src/models/bedrock-chat-model.ts
7254
+ var logger2 = new Logger("FlutchChatBedrockConverse");
7255
+ var FlutchChatBedrockConverse = class extends ChatBedrockConverse {
7256
+ static {
7257
+ __name(this, "FlutchChatBedrockConverse");
7258
+ }
7259
+ static lc_name() {
7260
+ return "FlutchChatBedrockConverse";
7261
+ }
7262
+ sanitize(messages) {
7263
+ const { messages: cleaned, sanitized } = sanitizeReasoningForBedrock(messages);
7264
+ if (sanitized > 0) {
7265
+ logger2.debug(`Dropped ${sanitized} unsendable reasoning block(s) from outgoing history (model=${this.model})`);
7266
+ }
7267
+ return cleaned;
7268
+ }
7269
+ /** `.invoke()` / `.generate()` path. */
7270
+ async _generate(messages, options, runManager) {
7271
+ return super._generate(this.sanitize(messages), options, runManager);
7272
+ }
7273
+ /** `.stream()` / `streamEvents()` path (also used by `_generate` when the
7274
+ * model is constructed with `streaming: true` — sanitizing is idempotent). */
7275
+ async *_streamResponseChunks(messages, options, runManager) {
7276
+ yield* super._streamResponseChunks(this.sanitize(messages), options, runManager);
7277
+ }
7278
+ };
7108
7279
  var VoyageAIRerank = class extends BaseDocumentCompressor {
7109
7280
  static {
7110
7281
  __name(this, "VoyageAIRerank");
@@ -7176,10 +7347,10 @@ var ModelInitializer = class _ModelInitializer {
7176
7347
  [ModelProvider.COHERE]: "COHERE_API_KEY",
7177
7348
  [ModelProvider.VOYAGEAI]: "VOYAGEAI_API_KEY"
7178
7349
  };
7179
- constructor(configFetcher, logger2, apiKeyResolver) {
7350
+ constructor(configFetcher, logger3, apiKeyResolver) {
7180
7351
  this.configFetcher = configFetcher;
7181
7352
  this.apiKeyResolver = apiKeyResolver;
7182
- this.logger = logger2 || new Logger(_ModelInitializer.name);
7353
+ this.logger = logger3 || new Logger(_ModelInitializer.name);
7183
7354
  }
7184
7355
  /**
7185
7356
  * Resolve API key for a provider.
@@ -7202,6 +7373,32 @@ var ModelInitializer = class _ModelInitializer {
7202
7373
  return process.env.BEDROCK_AWS_REGION || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || "us-east-1";
7203
7374
  }
7204
7375
  /**
7376
+ * Resolve sampling parameters for a model, dropping them when the model
7377
+ * does not accept them (Claude Opus 4.7+, Claude 5 and newer).
7378
+ *
7379
+ * An explicitly requested value on such a model is **ignored with a warning**
7380
+ * rather than raising: the request must keep working, and the model runs at
7381
+ * its own default sampling behaviour. Pass `supportsSamplingParams: true` in
7382
+ * the config to force the params through anyway.
7383
+ *
7384
+ * @param modelIdentifiers every name the model is known by (catalog model
7385
+ * name, Bedrock model id, …) — a match on any of them drops the params
7386
+ * @param wasExplicit whether the caller explicitly asked for these values
7387
+ * (as opposed to inheriting a catalog/SDK default) — controls log level
7388
+ */
7389
+ resolveSampling(modelIdentifiers, requested, supportsSamplingParams, wasExplicit = false) {
7390
+ const resolved = resolveSamplingParams(modelIdentifiers, requested, supportsSamplingParams);
7391
+ if (!resolved.accepted && resolved.dropped.length > 0) {
7392
+ const message = `Model ${modelIdentifiers.filter(Boolean).join(" / ")} does not accept sampling parameters \u2014 ignoring ${resolved.dropped.join(", ")}. Set supportsSamplingParams: true to override.`;
7393
+ if (wasExplicit) {
7394
+ this.logger.warn(message);
7395
+ } else {
7396
+ this.logger.debug(message);
7397
+ }
7398
+ }
7399
+ return resolved.params;
7400
+ }
7401
+ /**
7205
7402
  * Generate hash from toolsConfig for cache key
7206
7403
  * Uses MD5 hash to create short, unique identifier
7207
7404
  */
@@ -7215,10 +7412,8 @@ var ModelInitializer = class _ModelInitializer {
7215
7412
  */
7216
7413
  generateModelCacheKey(config) {
7217
7414
  const base = generateModelCacheKey(config.modelId, config.temperature, config.maxTokens, config.toolsConfig, config.baseURL);
7218
- if (config.mcpServers && config.mcpServers.length > 0) {
7219
- return `${base}:mcp:${JSON.stringify(config.mcpServers)}`;
7220
- }
7221
- return base;
7415
+ const withMcp = config.mcpServers && config.mcpServers.length > 0 ? `${base}:mcp:${JSON.stringify(config.mcpServers)}` : base;
7416
+ return config.supportsSamplingParams === void 0 ? withMcp : `${withMcp}:sp:${config.supportsSamplingParams}`;
7222
7417
  }
7223
7418
  // Chat model creators
7224
7419
  chatModelCreators = {
@@ -7237,15 +7432,12 @@ var ModelInitializer = class _ModelInitializer {
7237
7432
  const routerURL = resolveRouterURL(baseURL);
7238
7433
  return new ChatAnthropic({
7239
7434
  modelName,
7240
- temperature: defaultTemperature,
7435
+ // Claude Opus 4.7+ / Claude 5 reject `temperature` outright — the key
7436
+ // must be absent, not `undefined`.
7437
+ ...defaultTemperature !== void 0 && {
7438
+ temperature: defaultTemperature
7439
+ },
7241
7440
  maxTokens: defaultMaxTokens,
7242
- // Stream tokens even under `.invoke()` so LangGraph `streamEvents`
7243
- // emits `on_chat_model_stream`. Without it, nodes that call
7244
- // `model.invoke()` (e.g. campaigns DefaultBehaviorNode) surface only
7245
- // coarse `on_chain_*` events: no live SSE deltas, a sparse trace, and
7246
- // a content chain collapsed into one text block (no tool_use
7247
- // boundaries). Matches the Bedrock path, which already sets this.
7248
- streaming: true,
7249
7441
  anthropicApiKey: apiToken || this.resolveApiKey(ModelProvider.ANTHROPIC),
7250
7442
  ...routerURL && {
7251
7443
  anthropicApiUrl: routerURL,
@@ -7260,7 +7452,9 @@ var ModelInitializer = class _ModelInitializer {
7260
7452
  const token = apiToken || this.resolveApiKey(ModelProvider.COHERE);
7261
7453
  return routerURL ? new ChatCohere({
7262
7454
  model: modelName,
7263
- temperature: defaultTemperature,
7455
+ ...defaultTemperature !== void 0 && {
7456
+ temperature: defaultTemperature
7457
+ },
7264
7458
  client: new CohereClient({
7265
7459
  token,
7266
7460
  baseUrl: routerURL,
@@ -7270,7 +7464,9 @@ var ModelInitializer = class _ModelInitializer {
7270
7464
  })
7271
7465
  }) : new ChatCohere({
7272
7466
  model: modelName,
7273
- temperature: defaultTemperature,
7467
+ ...defaultTemperature !== void 0 && {
7468
+ temperature: defaultTemperature
7469
+ },
7274
7470
  apiKey: token
7275
7471
  });
7276
7472
  },
@@ -7278,7 +7474,9 @@ var ModelInitializer = class _ModelInitializer {
7278
7474
  const routerURL = resolveRouterURL(baseURL);
7279
7475
  return new ChatMistralAI({
7280
7476
  model: modelName,
7281
- temperature: defaultTemperature,
7477
+ ...defaultTemperature !== void 0 && {
7478
+ temperature: defaultTemperature
7479
+ },
7282
7480
  maxTokens: defaultMaxTokens,
7283
7481
  apiKey: apiToken || this.resolveApiKey(ModelProvider.MISTRAL),
7284
7482
  ...routerURL && {
@@ -7368,7 +7566,8 @@ var ModelInitializer = class _ModelInitializer {
7368
7566
  async initializeChatModelDirect(config, customTools) {
7369
7567
  const toolsConfig = normalizeToolConfigs(config.tools);
7370
7568
  const modelIdentifier = `${config.provider}:${config.modelName}`;
7371
- const cacheKey = generateModelCacheKey(modelIdentifier, config.temperature, config.maxTokens, toolsConfig, config.baseURL);
7569
+ const baseCacheKey = generateModelCacheKey(modelIdentifier, config.temperature, config.maxTokens, toolsConfig, config.baseURL);
7570
+ const cacheKey = config.supportsSamplingParams === void 0 ? baseCacheKey : `${baseCacheKey}:sp:${config.supportsSamplingParams}`;
7372
7571
  const cached = this.modelInstanceCache.get(cacheKey);
7373
7572
  if (cached) {
7374
7573
  this.logger.debug(`Using cached chat model instance: ${cacheKey}`);
@@ -7379,18 +7578,23 @@ var ModelInitializer = class _ModelInitializer {
7379
7578
  throw new Error(`Unknown provider "${provider}". Valid: ${Object.values(ModelProvider).join(", ")}`);
7380
7579
  }
7381
7580
  const apiToken = this.resolveApiKey(provider);
7382
- const temperature = config.temperature ?? 0.7;
7383
- const maxTokens = config.maxTokens ?? 4096;
7581
+ const maxTokens = toOptionalNumber(config.maxTokens) ?? 4096;
7582
+ const sampling = this.resolveSampling([
7583
+ config.modelName
7584
+ ], {
7585
+ temperature: toOptionalNumber(config.temperature) ?? 0.7
7586
+ }, config.supportsSamplingParams, config.temperature !== void 0);
7384
7587
  const modelConfig = {
7385
7588
  modelId: modelIdentifier,
7386
7589
  modelName: config.modelName,
7387
7590
  provider,
7388
7591
  modelType: ModelType.CHAT,
7389
- defaultTemperature: Number(temperature),
7390
- defaultMaxTokens: Number(maxTokens),
7592
+ defaultTemperature: sampling.temperature,
7593
+ defaultMaxTokens: maxTokens,
7391
7594
  apiToken,
7392
7595
  requiresApiKey: true,
7393
- baseURL: config.baseURL
7596
+ baseURL: config.baseURL,
7597
+ supportsSamplingParams: config.supportsSamplingParams
7394
7598
  };
7395
7599
  this.logger.debug(`Creating chat model: ${modelIdentifier} (apiKeyResolved=${!!apiToken})`);
7396
7600
  const creator = this.chatModelCreators[provider];
@@ -7425,19 +7629,29 @@ var ModelInitializer = class _ModelInitializer {
7425
7629
  if (modelConfig.modelType !== ModelType.CHAT) {
7426
7630
  throw new Error(`Model ${config.modelId} is not a chat model (type: ${modelConfig.modelType})`);
7427
7631
  }
7632
+ const requestedTemperature = toOptionalNumber(config.temperature) ?? toOptionalNumber(modelConfig.defaultTemperature);
7633
+ const sampling = this.resolveSampling([
7634
+ modelConfig.modelName,
7635
+ modelConfig.bedrockModelId
7636
+ ], {
7637
+ temperature: requestedTemperature
7638
+ }, config.supportsSamplingParams ?? modelConfig.supportsSamplingParams, config.temperature !== void 0);
7428
7639
  const finalConfig = {
7429
7640
  ...modelConfig,
7430
- defaultTemperature: Number(config.temperature ?? modelConfig.defaultTemperature),
7431
- defaultMaxTokens: Number(config.maxTokens ?? modelConfig.defaultMaxTokens),
7641
+ defaultTemperature: sampling.temperature,
7642
+ defaultMaxTokens: toOptionalNumber(config.maxTokens) ?? toOptionalNumber(modelConfig.defaultMaxTokens),
7432
7643
  baseURL: config.baseURL ?? modelConfig.baseURL
7433
7644
  };
7434
7645
  this.logger.debug(`Creating new chat model instance: ${cacheKey}`);
7435
7646
  let model;
7436
7647
  if (finalConfig.useBedrock && finalConfig.bedrockModelId) {
7437
- model = new ChatBedrockConverse({
7648
+ model = new FlutchChatBedrockConverse({
7438
7649
  model: finalConfig.bedrockModelId,
7439
7650
  region: this.resolveBedrockRegion(),
7440
- temperature: finalConfig.defaultTemperature,
7651
+ // Key omitted (not `undefined`) for models that reject sampling params.
7652
+ ...finalConfig.defaultTemperature !== void 0 && {
7653
+ temperature: finalConfig.defaultTemperature
7654
+ },
7441
7655
  maxTokens: finalConfig.defaultMaxTokens,
7442
7656
  streaming: true
7443
7657
  });
@@ -8283,6 +8497,6 @@ var MongoTokenStore = class {
8283
8497
  }
8284
8498
  };
8285
8499
 
8286
- export { AbstractGraphBuilder, AttachmentType, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, CallbackController, CallbackMetrics, CallbackPatchService, CallbackRateLimiter, CallbackRegistry, CallbackStore, CallbackTokenGuard, ChatFeature, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, ENDPOINT_METADATA_KEY, Endpoint, EndpointRegistry, EventProcessor, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, IdempotencyManager, IdempotencyStatus, LangGraphEngine, McpConverter, McpRuntimeHttpClient, McpToolFilter, ModelInitializer, ModelProvider, ModelType, MongoTokenStore, OAuthTokenManager, RetrieverSearchType, RetrieverService, SmartCallbackRouter, StaticDiscovery, StreamChannel, TelegramPatchHandler, UIDispatchController, UIEndpoint, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, UniversalGraphService, VersionedGraphService, VoyageAIRerank, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, flutchFetch, flutchHeaders, flutchMistralHook, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getFlutchContext, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isInternalMode, isReasoningModel, loadOAuthProviders, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, sanitizeTraceData, storeAttachmentData, traceApiCall, withFlutchContext, wrapCohereFetcher };
8500
+ export { AbstractGraphBuilder, AttachmentType, GraphController as BaseGraphServiceController, UniversalGraphModule as BaseGraphServiceModule, BuilderRegistryService, Callback, CallbackACL, CallbackAuditAction, CallbackAuditor, CallbackController, CallbackMetrics, CallbackPatchService, CallbackRateLimiter, CallbackRegistry, CallbackStore, CallbackTokenGuard, ChatFeature, DEFAULT_ATTACHMENT_THRESHOLD, DEFAULT_ROUTER_URL, DEFAULT_TRACER_OPTIONS, ENDPOINT_METADATA_KEY, Endpoint, EndpointRegistry, EventProcessor, ExternalGraphBuilder, FileBasedDiscovery, FileTokenStore, FlutchChatBedrockConverse, GraphController, GraphEngineFactory, GraphEngineType, GraphManifestSchema, GraphManifestValidator, GraphServiceTokens, GraphTypeUtils, IdempotencyManager, IdempotencyStatus, LangGraphEngine, McpConverter, McpRuntimeHttpClient, McpToolFilter, ModelInitializer, ModelProvider, ModelType, MongoTokenStore, OAuthTokenManager, RetrieverSearchType, RetrieverService, SAMPLING_PARAM_FREE_THRESHOLDS, SmartCallbackRouter, StaticDiscovery, StreamChannel, TelegramPatchHandler, UIDispatchController, UIEndpoint, UIEndpointsDiscoveryService, UniversalCallbackService, UniversalGraphModule, UniversalGraphService, VersionedGraphService, VoyageAIRerank, WebPatchHandler, WithCallbacks, WithEndpoints, WithUIEndpoints, _internals, bootstrap, buildOAuthAuthorizationUrl, buildOpenAIModelConfig, clearAttachmentDataStore, createEndpointDescriptors, createGraphAttachment, createMongoClientAdapter, createStaticMessage, decryptTokens, dispatchAttachments, encryptTokens, executeToolWithAttachments, findCallbackMethod, findEndpointMethod, flutchFetch, flutchHeaders, flutchMistralHook, generateAttachmentSummary, generateModelCacheKey, getAttachmentData, getCallbackMetadata, getEndpointMetadata, getFlutchContext, getOAuthProvider, getOAuthProviderNames, getUIEndpointClassMetadata, getUIEndpointMethodsMetadata, hasCallbacks, hasUIEndpoints, hashToolsConfig, isInternalMode, isReasoningBlock, isReasoningModel, isSendableReasoningBlock, loadOAuthProviders, modelAcceptsSamplingParams, normalizeToolConfigs, registerFinanceExampleCallback, registerUIEndpointsFromClass, resolveOAuthProviderConfig, resolveRouterURL, resolveSamplingParams, sanitizeMessageReasoning, sanitizeReasoningForBedrock, sanitizeTraceData, storeAttachmentData, toOptionalNumber, traceApiCall, withFlutchContext, wrapCohereFetcher };
8287
8501
  //# sourceMappingURL=index.js.map
8288
8502
  //# sourceMappingURL=index.js.map