@flutchai/flutch-sdk 0.2.10 → 0.2.14

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
@@ -2848,8 +2848,8 @@ exports.IdempotencyManager = __decorateClass([
2848
2848
 
2849
2849
  // src/callbacks/smart-callback.router.ts
2850
2850
  exports.SmartCallbackRouter = class SmartCallbackRouter {
2851
- constructor(registry, store, acl, auditor, metrics, rateLimiter, idempotencyManager, patchService) {
2852
- this.registry = registry;
2851
+ constructor(registry2, store, acl, auditor, metrics, rateLimiter, idempotencyManager, patchService) {
2852
+ this.registry = registry2;
2853
2853
  this.store = store;
2854
2854
  this.acl = acl;
2855
2855
  this.auditor = auditor;
@@ -3128,8 +3128,8 @@ var UniversalCallbackService = class {
3128
3128
  };
3129
3129
 
3130
3130
  // src/callbacks/example.callback.ts
3131
- function registerFinanceExampleCallback(registry) {
3132
- registry.register(
3131
+ function registerFinanceExampleCallback(registry2) {
3132
+ registry2.register(
3133
3133
  "example",
3134
3134
  async () => ({
3135
3135
  success: true,
@@ -3654,8 +3654,8 @@ exports.CallbackMetrics = class CallbackMetrics {
3654
3654
  activeCallbacks;
3655
3655
  pendingCallbacks;
3656
3656
  queueSize;
3657
- constructor(registry) {
3658
- this.registry = registry ?? new promClient.Registry();
3657
+ constructor(registry2) {
3658
+ this.registry = registry2 ?? new promClient.Registry();
3659
3659
  promClient.collectDefaultMetrics({ register: this.registry });
3660
3660
  this.callbacksTotal = new promClient.Counter({
3661
3661
  name: "graph_callbacks_total",
@@ -4477,11 +4477,17 @@ async function executeToolWithAttachments(params) {
4477
4477
  threshold = DEFAULT_ATTACHMENT_THRESHOLD,
4478
4478
  injectIntoArg = "data",
4479
4479
  sourceAttachmentId,
4480
- threadId
4480
+ threadId,
4481
+ toolSchema
4481
4482
  } = params;
4482
4483
  const argsWithInjection = { ...enrichedArgs };
4483
4484
  try {
4484
- if (shouldInjectData(argsWithInjection, attachments, injectIntoArg)) {
4485
+ if (shouldInjectData(
4486
+ argsWithInjection,
4487
+ attachments,
4488
+ injectIntoArg,
4489
+ toolSchema
4490
+ )) {
4485
4491
  const attachment = sourceAttachmentId ? attachments[sourceAttachmentId] : getLatestAttachment(attachments);
4486
4492
  if (attachment) {
4487
4493
  const attachmentKey = sourceAttachmentId || attachment.toolCallId;
@@ -4543,9 +4549,17 @@ async function executeToolWithAttachments(params) {
4543
4549
  });
4544
4550
  return { toolMessage };
4545
4551
  }
4546
- function shouldInjectData(args, attachments, dataArgName) {
4552
+ function shouldInjectData(args, attachments, dataArgName, toolSchema) {
4547
4553
  if (Object.keys(attachments).length === 0) return false;
4548
- return args[dataArgName] === void 0;
4554
+ if (args[dataArgName] !== void 0) return false;
4555
+ if (toolSchema) {
4556
+ const hasProperty = toolSchema.properties && dataArgName in toolSchema.properties;
4557
+ const isRequired = toolSchema.required?.includes(dataArgName);
4558
+ if (!hasProperty && !isRequired) {
4559
+ return false;
4560
+ }
4561
+ }
4562
+ return true;
4549
4563
  }
4550
4564
  var _internals = {
4551
4565
  shouldInjectData,
@@ -5658,7 +5672,7 @@ exports.UniversalGraphModule = class UniversalGraphModule {
5658
5672
  },
5659
5673
  {
5660
5674
  provide: exports.CallbackMetrics,
5661
- useFactory: (registry) => new exports.CallbackMetrics(registry),
5675
+ useFactory: (registry2) => new exports.CallbackMetrics(registry2),
5662
5676
  inject: ["PROMETHEUS_REGISTRY"]
5663
5677
  },
5664
5678
  {
@@ -5686,8 +5700,8 @@ exports.UniversalGraphModule = class UniversalGraphModule {
5686
5700
  },
5687
5701
  {
5688
5702
  provide: exports.SmartCallbackRouter,
5689
- useFactory: (registry, store, acl, auditor, metrics, rateLimiter, idempotencyManager, patchService) => new exports.SmartCallbackRouter(
5690
- registry,
5703
+ useFactory: (registry2, store, acl, auditor, metrics, rateLimiter, idempotencyManager, patchService) => new exports.SmartCallbackRouter(
5704
+ registry2,
5691
5705
  store,
5692
5706
  acl,
5693
5707
  auditor,
@@ -5719,8 +5733,8 @@ exports.UniversalGraphModule = class UniversalGraphModule {
5719
5733
  },
5720
5734
  {
5721
5735
  provide: "CALLBACK_EXAMPLE_REGISTRATION",
5722
- useFactory: (registry) => {
5723
- registerFinanceExampleCallback(registry);
5736
+ useFactory: (registry2) => {
5737
+ registerFinanceExampleCallback(registry2);
5724
5738
  },
5725
5739
  inject: [CallbackRegistry]
5726
5740
  },
@@ -5783,8 +5797,8 @@ exports.UniversalGraphModule = class UniversalGraphModule {
5783
5797
  },
5784
5798
  {
5785
5799
  provide: "GRAPH_BUILDERS",
5786
- useFactory: (registry) => {
5787
- return registry.getBuilders();
5800
+ useFactory: (registry2) => {
5801
+ return registry2.getBuilders();
5788
5802
  },
5789
5803
  inject: [exports.BuilderRegistryService]
5790
5804
  },
@@ -6452,12 +6466,19 @@ function hashToolsConfig(toolsConfig) {
6452
6466
  const sorted = toolsConfig.map((t) => `${t.toolName}:${t.enabled}:${JSON.stringify(t.config || {})}`).sort().join("|");
6453
6467
  return crypto.createHash("md5").update(sorted).digest("hex").slice(0, 16);
6454
6468
  }
6455
- function generateModelCacheKey(modelId, temperature, maxTokens, toolsConfig) {
6469
+ var DEFAULT_ROUTER_URL = "https://router.flutch.ai";
6470
+ function resolveRouterURL(baseURL) {
6471
+ return baseURL ?? process.env.FLUTCH_ROUTER_URL ?? DEFAULT_ROUTER_URL;
6472
+ }
6473
+ function generateModelCacheKey(modelId, temperature, maxTokens, toolsConfig, baseURL) {
6456
6474
  const parts = [
6457
6475
  modelId,
6458
6476
  temperature ?? "default",
6459
6477
  maxTokens ?? "default"
6460
6478
  ];
6479
+ if (baseURL) {
6480
+ parts.push(baseURL);
6481
+ }
6461
6482
  if (toolsConfig && toolsConfig.length > 0) {
6462
6483
  parts.push(hashToolsConfig(toolsConfig));
6463
6484
  }
@@ -6585,7 +6606,8 @@ var ModelInitializer = class _ModelInitializer {
6585
6606
  config.modelId,
6586
6607
  config.temperature,
6587
6608
  config.maxTokens,
6588
- config.toolsConfig
6609
+ config.toolsConfig,
6610
+ config.baseURL
6589
6611
  );
6590
6612
  }
6591
6613
  // Chat model creators
@@ -6594,7 +6616,8 @@ var ModelInitializer = class _ModelInitializer {
6594
6616
  modelName,
6595
6617
  defaultTemperature,
6596
6618
  defaultMaxTokens,
6597
- apiToken
6619
+ apiToken,
6620
+ baseURL
6598
6621
  }) => {
6599
6622
  const config = buildOpenAIModelConfig(
6600
6623
  modelName,
@@ -6602,18 +6625,21 @@ var ModelInitializer = class _ModelInitializer {
6602
6625
  defaultMaxTokens,
6603
6626
  apiToken || this.resolveApiKey("openai" /* OPENAI */) || ""
6604
6627
  );
6628
+ config.configuration = { baseURL: `${resolveRouterURL(baseURL)}/v1` };
6605
6629
  return new openai.ChatOpenAI(config);
6606
6630
  },
6607
6631
  ["anthropic" /* ANTHROPIC */]: ({
6608
6632
  modelName,
6609
6633
  defaultTemperature,
6610
6634
  defaultMaxTokens,
6611
- apiToken
6635
+ apiToken,
6636
+ baseURL
6612
6637
  }) => new anthropic.ChatAnthropic({
6613
6638
  modelName,
6614
6639
  temperature: defaultTemperature,
6615
6640
  maxTokens: defaultMaxTokens,
6616
- anthropicApiKey: apiToken || this.resolveApiKey("anthropic" /* ANTHROPIC */)
6641
+ anthropicApiKey: apiToken || this.resolveApiKey("anthropic" /* ANTHROPIC */),
6642
+ anthropicApiUrl: resolveRouterURL(baseURL)
6617
6643
  }),
6618
6644
  ["cohere" /* COHERE */]: ({
6619
6645
  modelName,
@@ -6695,7 +6721,8 @@ var ModelInitializer = class _ModelInitializer {
6695
6721
  ),
6696
6722
  defaultMaxTokens: Number(
6697
6723
  config.maxTokens ?? modelConfig.defaultMaxTokens
6698
- )
6724
+ ),
6725
+ baseURL: config.baseURL ?? modelConfig.baseURL
6699
6726
  };
6700
6727
  this.logger.debug(`Creating new chat model instance: ${cacheKey}`);
6701
6728
  let model;
@@ -7330,11 +7357,7 @@ var ALGORITHM = "aes-256-cbc";
7330
7357
  var IV_LENGTH = 16;
7331
7358
  function encryptTokens(tokens, key) {
7332
7359
  const iv = crypto__namespace.randomBytes(IV_LENGTH);
7333
- const cipher = crypto__namespace.createCipheriv(
7334
- ALGORITHM,
7335
- Buffer.from(key),
7336
- iv
7337
- );
7360
+ const cipher = crypto__namespace.createCipheriv(ALGORITHM, Buffer.from(key), iv);
7338
7361
  const json = JSON.stringify(tokens);
7339
7362
  let encrypted = cipher.update(json, "utf8", "hex");
7340
7363
  encrypted += cipher.final("hex");
@@ -7348,11 +7371,7 @@ function decryptTokens(encrypted, key) {
7348
7371
  const ivHex = encrypted.substring(0, separatorIndex);
7349
7372
  const encryptedData = encrypted.substring(separatorIndex + 1);
7350
7373
  const iv = Buffer.from(ivHex, "hex");
7351
- const decipher = crypto__namespace.createDecipheriv(
7352
- ALGORITHM,
7353
- Buffer.from(key),
7354
- iv
7355
- );
7374
+ const decipher = crypto__namespace.createDecipheriv(ALGORITHM, Buffer.from(key), iv);
7356
7375
  let decrypted = decipher.update(encryptedData, "hex", "utf8");
7357
7376
  decrypted += decipher.final("utf8");
7358
7377
  return JSON.parse(decrypted);
@@ -7393,7 +7412,10 @@ var OAuthTokenManager = class {
7393
7412
  this.setCache(config.provider, tokens.accessToken, tokens.expiresAt);
7394
7413
  return tokens.accessToken;
7395
7414
  }
7396
- const refreshed = await this.refreshAccessToken(config, tokens.refreshToken);
7415
+ const refreshed = await this.refreshAccessToken(
7416
+ config,
7417
+ tokens.refreshToken
7418
+ );
7397
7419
  await this.persistTokens(config.provider, refreshed);
7398
7420
  return refreshed.accessToken;
7399
7421
  }
@@ -7457,6 +7479,56 @@ var OAuthTokenManager = class {
7457
7479
  this.cache.set(provider, { token, expiresAt });
7458
7480
  }
7459
7481
  };
7482
+
7483
+ // src/oauth/oauth-provider.registry.ts
7484
+ var registry = {};
7485
+ function loadOAuthProviders(providers) {
7486
+ registry = { ...providers };
7487
+ }
7488
+ function getOAuthProvider(provider) {
7489
+ const def = registry[provider];
7490
+ if (!def) {
7491
+ throw new Error(`Unknown OAuth provider: ${provider}`);
7492
+ }
7493
+ return def;
7494
+ }
7495
+ function getOAuthProviderNames() {
7496
+ return Object.keys(registry);
7497
+ }
7498
+ function resolveOAuthProviderConfig(provider) {
7499
+ const def = getOAuthProvider(provider);
7500
+ const clientId = process.env[def.clientIdEnvVar];
7501
+ const clientSecret = process.env[def.clientSecretEnvVar];
7502
+ if (!clientId) {
7503
+ throw new Error(`Missing env var: ${def.clientIdEnvVar}`);
7504
+ }
7505
+ if (!clientSecret) {
7506
+ throw new Error(`Missing env var: ${def.clientSecretEnvVar}`);
7507
+ }
7508
+ return {
7509
+ provider: def.name,
7510
+ tokenUrl: def.tokenUrl,
7511
+ clientId,
7512
+ clientSecret
7513
+ };
7514
+ }
7515
+ function buildOAuthAuthorizationUrl(provider, params) {
7516
+ const def = getOAuthProvider(provider);
7517
+ const clientId = process.env[def.clientIdEnvVar];
7518
+ if (!clientId) {
7519
+ throw new Error(`Missing env var: ${def.clientIdEnvVar}`);
7520
+ }
7521
+ const query = new URLSearchParams({
7522
+ client_id: clientId,
7523
+ redirect_uri: params.redirectUri,
7524
+ response_type: "code",
7525
+ state: params.state
7526
+ });
7527
+ if (def.scopes.length > 0) {
7528
+ query.set("scope", def.scopes.join(" "));
7529
+ }
7530
+ return `${def.authorizationUrl}?${query.toString()}`;
7531
+ }
7460
7532
  var FileTokenStore = class {
7461
7533
  constructor(filePath) {
7462
7534
  this.filePath = filePath;
@@ -7560,6 +7632,7 @@ exports.WithEndpoints = WithEndpoints;
7560
7632
  exports.WithUIEndpoints = WithUIEndpoints;
7561
7633
  exports._internals = _internals;
7562
7634
  exports.bootstrap = bootstrap;
7635
+ exports.buildOAuthAuthorizationUrl = buildOAuthAuthorizationUrl;
7563
7636
  exports.clearAttachmentDataStore = clearAttachmentDataStore;
7564
7637
  exports.createEndpointDescriptors = createEndpointDescriptors;
7565
7638
  exports.createGraphAttachment = createGraphAttachment;
@@ -7575,12 +7648,16 @@ exports.generateAttachmentSummary = generateAttachmentSummary;
7575
7648
  exports.getAttachmentData = getAttachmentData;
7576
7649
  exports.getCallbackMetadata = getCallbackMetadata;
7577
7650
  exports.getEndpointMetadata = getEndpointMetadata;
7651
+ exports.getOAuthProvider = getOAuthProvider;
7652
+ exports.getOAuthProviderNames = getOAuthProviderNames;
7578
7653
  exports.getUIEndpointClassMetadata = getUIEndpointClassMetadata;
7579
7654
  exports.getUIEndpointMethodsMetadata = getUIEndpointMethodsMetadata;
7580
7655
  exports.hasCallbacks = hasCallbacks;
7581
7656
  exports.hasUIEndpoints = hasUIEndpoints;
7657
+ exports.loadOAuthProviders = loadOAuthProviders;
7582
7658
  exports.registerFinanceExampleCallback = registerFinanceExampleCallback;
7583
7659
  exports.registerUIEndpointsFromClass = registerUIEndpointsFromClass;
7660
+ exports.resolveOAuthProviderConfig = resolveOAuthProviderConfig;
7584
7661
  exports.sanitizeTraceData = sanitizeTraceData;
7585
7662
  exports.storeAttachmentData = storeAttachmentData;
7586
7663
  exports.traceApiCall = traceApiCall;