@inkeep/agents-run-api 0.37.0 → 0.37.1

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
@@ -32,12 +32,6 @@ var factory = require('hono/factory');
32
32
  var swaggerUi = require('@hono/swagger-ui');
33
33
  var streaming = require('hono/streaming');
34
34
  var ai = require('ai');
35
- var anthropic = require('@ai-sdk/anthropic');
36
- var gateway = require('@ai-sdk/gateway');
37
- var google = require('@ai-sdk/google');
38
- var openai = require('@ai-sdk/openai');
39
- var openaiCompatible = require('@ai-sdk/openai-compatible');
40
- var aiSdkProvider = require('@openrouter/ai-sdk-provider');
41
35
  var jmespath = require('jmespath');
42
36
  var Ajv = require('ajv');
43
37
  var destr = require('destr');
@@ -95,6 +89,7 @@ var init_env = __esm({
95
89
  ENVIRONMENT: z8.z.enum(["development", "production", "pentest", "test"]).optional().default("development"),
96
90
  DATABASE_URL: z8.z.string().optional(),
97
91
  INKEEP_AGENTS_RUN_API_URL: z8.z.string().optional().default("http://localhost:3003"),
92
+ AGENTS_MANAGE_UI_URL: z8.z.string().optional().default("http://localhost:3000"),
98
93
  LOG_LEVEL: z8.z.enum(["trace", "debug", "info", "warn", "error"]).optional().default("debug"),
99
94
  NANGO_SERVER_URL: z8.z.string().optional().default("https://api.nango.dev"),
100
95
  NANGO_SECRET_KEY: z8.z.string().optional(),
@@ -6741,10 +6736,9 @@ var init_NativeSandboxExecutor = __esm({
6741
6736
  "Reusing cached sandbox"
6742
6737
  );
6743
6738
  return sandbox.sandboxDir;
6744
- } else {
6745
- this.cleanupSandbox(sandbox.sandboxDir);
6746
- delete this.sandboxPool[poolKey];
6747
6739
  }
6740
+ this.cleanupSandbox(sandbox.sandboxDir);
6741
+ delete this.sandboxPool[poolKey];
6748
6742
  }
6749
6743
  return null;
6750
6744
  }
@@ -8588,275 +8582,10 @@ async function handleTasksResubscribe(c2, agent, request) {
8588
8582
  init_dbClient();
8589
8583
  init_logger();
8590
8584
 
8591
- // src/agents/ModelFactory.ts
8592
- init_logger();
8593
- var logger4 = agentsCore.getLogger("ModelFactory");
8594
- var nimDefault = openaiCompatible.createOpenAICompatible({
8595
- name: "nim",
8596
- baseURL: "https://integrate.api.nvidia.com/v1",
8597
- headers: {
8598
- Authorization: `Bearer ${process.env.NIM_API_KEY}`
8599
- }
8600
- });
8601
- var ModelFactory = class _ModelFactory {
8602
- /**
8603
- * Create a provider instance with custom configuration
8604
- */
8605
- static createProvider(provider, config) {
8606
- switch (provider) {
8607
- case "anthropic":
8608
- return anthropic.createAnthropic(config);
8609
- case "openai":
8610
- return openai.createOpenAI(config);
8611
- case "google":
8612
- return google.createGoogleGenerativeAI(config);
8613
- case "openrouter":
8614
- return {
8615
- ...aiSdkProvider.createOpenRouter(config),
8616
- textEmbeddingModel: () => {
8617
- throw new Error("OpenRouter does not support text embeddings");
8618
- },
8619
- imageModel: () => {
8620
- throw new Error("OpenRouter does not support image generation");
8621
- }
8622
- };
8623
- case "gateway":
8624
- return gateway.createGateway(config);
8625
- case "nim": {
8626
- const nimConfig = {
8627
- name: "nim",
8628
- baseURL: "https://integrate.api.nvidia.com/v1",
8629
- headers: {
8630
- Authorization: `Bearer ${process.env.NIM_API_KEY}`
8631
- },
8632
- ...config
8633
- };
8634
- return openaiCompatible.createOpenAICompatible(nimConfig);
8635
- }
8636
- case "custom": {
8637
- if (!config.baseURL && !config.baseUrl) {
8638
- throw new Error(
8639
- "Custom provider requires baseURL. Please provide it in providerOptions.baseURL or providerOptions.baseUrl"
8640
- );
8641
- }
8642
- const customConfig = {
8643
- name: "custom",
8644
- baseURL: config.baseURL || config.baseUrl,
8645
- headers: {
8646
- ...process.env.CUSTOM_LLM_API_KEY && {
8647
- Authorization: `Bearer ${process.env.CUSTOM_LLM_API_KEY}`
8648
- },
8649
- ...config.headers || {}
8650
- },
8651
- ...config
8652
- };
8653
- logger4.info(
8654
- {
8655
- config: {
8656
- baseURL: customConfig.baseURL,
8657
- hasApiKey: !!process.env.CUSTOM_LLM_API_KEY,
8658
- apiKeyPrefix: process.env.CUSTOM_LLM_API_KEY?.substring(0, 10) + "...",
8659
- headers: Object.keys(customConfig.headers || {})
8660
- }
8661
- },
8662
- "Creating custom OpenAI-compatible provider"
8663
- );
8664
- return openaiCompatible.createOpenAICompatible(customConfig);
8665
- }
8666
- default:
8667
- throw new Error(`Unsupported provider: ${provider}`);
8668
- }
8669
- }
8670
- /**
8671
- * Extract provider configuration from providerOptions
8672
- * Only includes settings that go to the provider constructor (baseURL, apiKey, etc.)
8673
- */
8674
- static extractProviderConfig(providerOptions) {
8675
- if (!providerOptions) {
8676
- return {};
8677
- }
8678
- const providerConfig = {};
8679
- if (providerOptions.baseUrl || providerOptions.baseURL) {
8680
- providerConfig.baseURL = providerOptions.baseUrl || providerOptions.baseURL;
8681
- }
8682
- if (providerOptions.headers) {
8683
- providerConfig.headers = providerOptions.headers;
8684
- }
8685
- if (providerOptions.gateway) {
8686
- Object.assign(providerConfig, providerOptions.gateway);
8687
- }
8688
- if (providerOptions.nim) {
8689
- Object.assign(providerConfig, providerOptions.nim);
8690
- }
8691
- if (providerOptions.custom) {
8692
- Object.assign(providerConfig, providerOptions.custom);
8693
- }
8694
- return providerConfig;
8695
- }
8696
- /**
8697
- * Create a language model instance from configuration
8698
- * Throws error if no config provided - models must be configured at project level
8699
- */
8700
- static createModel(config) {
8701
- if (!config?.model?.trim()) {
8702
- throw new Error(
8703
- "Model configuration is required. Please configure models at the project level."
8704
- );
8705
- }
8706
- const modelSettings = config;
8707
- if (!modelSettings.model) {
8708
- throw new Error("Model configuration is required");
8709
- }
8710
- const modelString = modelSettings.model.trim();
8711
- const { provider, modelName } = _ModelFactory.parseModelString(modelString);
8712
- logger4.debug(
8713
- {
8714
- provider,
8715
- model: modelName,
8716
- fullModelString: modelSettings.model,
8717
- hasProviderOptions: !!modelSettings.providerOptions
8718
- },
8719
- "Creating language model from config"
8720
- );
8721
- const providerConfig = _ModelFactory.extractProviderConfig(modelSettings.providerOptions);
8722
- if (Object.keys(providerConfig).length > 0) {
8723
- logger4.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
8724
- const customProvider = _ModelFactory.createProvider(provider, providerConfig);
8725
- return customProvider.languageModel(modelName);
8726
- }
8727
- switch (provider) {
8728
- case "anthropic":
8729
- return anthropic.anthropic(modelName);
8730
- case "openai":
8731
- return openai.openai(modelName);
8732
- case "google":
8733
- return google.google(modelName);
8734
- case "openrouter":
8735
- return aiSdkProvider.openrouter(modelName);
8736
- case "gateway":
8737
- return gateway.gateway(modelName);
8738
- case "nim":
8739
- return nimDefault(modelName);
8740
- case "custom":
8741
- throw new Error(
8742
- "Custom provider requires configuration. Please provide baseURL in providerOptions.custom.baseURL or providerOptions.baseURL"
8743
- );
8744
- default:
8745
- throw new Error(
8746
- `Unsupported provider: ${provider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
8747
- );
8748
- }
8749
- }
8750
- /**
8751
- * Built-in providers that have special handling
8752
- */
8753
- static BUILT_IN_PROVIDERS = [
8754
- "anthropic",
8755
- "openai",
8756
- "google",
8757
- "openrouter",
8758
- "gateway",
8759
- "nim",
8760
- "custom"
8761
- ];
8762
- /**
8763
- * Parse model string to extract provider and model name
8764
- * Examples: "anthropic/claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" }
8765
- * "openrouter/anthropic/claude-sonnet-4" -> { provider: "openrouter", modelName: "anthropic/claude-sonnet-4" }
8766
- * "claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" } (default to anthropic)
8767
- */
8768
- static parseModelString(modelString) {
8769
- if (modelString.includes("/")) {
8770
- const [provider, ...modelParts] = modelString.split("/");
8771
- const normalizedProvider = provider.toLowerCase();
8772
- if (!_ModelFactory.BUILT_IN_PROVIDERS.includes(normalizedProvider)) {
8773
- throw new Error(
8774
- `Unsupported provider: ${normalizedProvider}. Supported providers are: ${_ModelFactory.BUILT_IN_PROVIDERS.join(", ")}. To access other models, use OpenRouter (openrouter/model-id), Vercel AI Gateway (gateway/model-id), NVIDIA NIM (nim/model-id), or Custom OpenAI-compatible (custom/model-id).`
8775
- );
8776
- }
8777
- return {
8778
- provider: normalizedProvider,
8779
- modelName: modelParts.join("/")
8780
- // In case model name has slashes
8781
- };
8782
- }
8783
- throw new Error(`No provider specified in model string: ${modelString}`);
8784
- }
8785
- /**
8786
- * Get generation parameters from provider options
8787
- * These are parameters that get passed to generateText/streamText calls
8788
- */
8789
- static getGenerationParams(providerOptions) {
8790
- if (!providerOptions) {
8791
- return {};
8792
- }
8793
- const excludedKeys = [
8794
- "apiKey",
8795
- "baseURL",
8796
- "baseUrl",
8797
- "maxDuration",
8798
- "headers",
8799
- "gateway",
8800
- "nim",
8801
- "custom"
8802
- ];
8803
- const params = {};
8804
- for (const [key, value] of Object.entries(providerOptions)) {
8805
- if (!excludedKeys.includes(key) && value !== void 0) {
8806
- params[key] = value;
8807
- }
8808
- }
8809
- return params;
8810
- }
8811
- /**
8812
- * Prepare complete generation configuration from model settings
8813
- * Returns model instance and generation parameters ready to spread into generateText/streamText
8814
- * Includes maxDuration if specified in provider options (in seconds, following Vercel standard)
8815
- */
8816
- static prepareGenerationConfig(modelSettings) {
8817
- const modelString = modelSettings?.model?.trim();
8818
- const model = _ModelFactory.createModel({
8819
- model: modelString,
8820
- providerOptions: modelSettings?.providerOptions
8821
- });
8822
- const generationParams = _ModelFactory.getGenerationParams(modelSettings?.providerOptions);
8823
- const maxDuration = modelSettings?.providerOptions?.maxDuration;
8824
- return {
8825
- model,
8826
- ...generationParams,
8827
- ...maxDuration !== void 0 && { maxDuration }
8828
- };
8829
- }
8830
- /**
8831
- * Validate model settingsuration
8832
- * Basic validation only - let AI SDK handle parameter-specific validation
8833
- */
8834
- static validateConfig(config) {
8835
- const errors = [];
8836
- if (!config.model) {
8837
- errors.push("Model name is required");
8838
- }
8839
- if (config.providerOptions) {
8840
- if (config.providerOptions.apiKey) {
8841
- errors.push(
8842
- "API keys should not be stored in provider options. Use environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY) or credential store instead."
8843
- );
8844
- }
8845
- if (config.providerOptions.maxDuration !== void 0) {
8846
- const maxDuration = config.providerOptions.maxDuration;
8847
- if (typeof maxDuration !== "number" || maxDuration <= 0) {
8848
- errors.push("maxDuration must be a positive number (in seconds)");
8849
- }
8850
- }
8851
- }
8852
- return errors;
8853
- }
8854
- };
8855
-
8856
8585
  // src/agents/ToolSessionManager.ts
8857
8586
  init_execution_limits();
8858
8587
  init_logger();
8859
- var logger5 = agentsCore.getLogger("ToolSessionManager");
8588
+ var logger4 = agentsCore.getLogger("ToolSessionManager");
8860
8589
  var ToolSessionManager = class _ToolSessionManager {
8861
8590
  static instance;
8862
8591
  sessions = /* @__PURE__ */ new Map();
@@ -8890,7 +8619,7 @@ var ToolSessionManager = class _ToolSessionManager {
8890
8619
  createdAt: Date.now()
8891
8620
  };
8892
8621
  this.sessions.set(sessionId, session);
8893
- logger5.debug(
8622
+ logger4.debug(
8894
8623
  {
8895
8624
  sessionId,
8896
8625
  tenantId,
@@ -8908,10 +8637,10 @@ var ToolSessionManager = class _ToolSessionManager {
8908
8637
  */
8909
8638
  ensureAgentSession(sessionId, tenantId, projectId, contextId, taskId) {
8910
8639
  if (this.sessions.has(sessionId)) {
8911
- logger5.debug({ sessionId }, "Agent session already exists, reusing");
8640
+ logger4.debug({ sessionId }, "Agent session already exists, reusing");
8912
8641
  return sessionId;
8913
8642
  }
8914
- logger5.debug(
8643
+ logger4.debug(
8915
8644
  { sessionId, tenantId, contextId, taskId },
8916
8645
  "Creating new agent-scoped tool session"
8917
8646
  );
@@ -8923,7 +8652,7 @@ var ToolSessionManager = class _ToolSessionManager {
8923
8652
  recordToolResult(sessionId, toolResult) {
8924
8653
  const session = this.sessions.get(sessionId);
8925
8654
  if (!session) {
8926
- logger5.warn(
8655
+ logger4.warn(
8927
8656
  {
8928
8657
  sessionId,
8929
8658
  toolCallId: toolResult.toolCallId,
@@ -8935,7 +8664,7 @@ var ToolSessionManager = class _ToolSessionManager {
8935
8664
  return;
8936
8665
  }
8937
8666
  session.toolResults.set(toolResult.toolCallId, toolResult);
8938
- logger5.debug(
8667
+ logger4.debug(
8939
8668
  {
8940
8669
  sessionId,
8941
8670
  toolCallId: toolResult.toolCallId,
@@ -8950,7 +8679,7 @@ var ToolSessionManager = class _ToolSessionManager {
8950
8679
  getToolResult(sessionId, toolCallId) {
8951
8680
  const session = this.sessions.get(sessionId);
8952
8681
  if (!session) {
8953
- logger5.warn(
8682
+ logger4.warn(
8954
8683
  {
8955
8684
  sessionId,
8956
8685
  toolCallId,
@@ -8963,7 +8692,7 @@ var ToolSessionManager = class _ToolSessionManager {
8963
8692
  }
8964
8693
  const result = session.toolResults.get(toolCallId);
8965
8694
  if (!result) {
8966
- logger5.warn(
8695
+ logger4.warn(
8967
8696
  {
8968
8697
  sessionId,
8969
8698
  toolCallId,
@@ -8973,7 +8702,7 @@ var ToolSessionManager = class _ToolSessionManager {
8973
8702
  "Tool result not found"
8974
8703
  );
8975
8704
  } else {
8976
- logger5.debug(
8705
+ logger4.debug(
8977
8706
  {
8978
8707
  sessionId,
8979
8708
  toolCallId,
@@ -9012,10 +8741,10 @@ var ToolSessionManager = class _ToolSessionManager {
9012
8741
  }
9013
8742
  for (const sessionId of expiredSessions) {
9014
8743
  this.sessions.delete(sessionId);
9015
- logger5.debug({ sessionId }, "Cleaned up expired tool session");
8744
+ logger4.debug({ sessionId }, "Cleaned up expired tool session");
9016
8745
  }
9017
8746
  if (expiredSessions.length > 0) {
9018
- logger5.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
8747
+ logger4.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
9019
8748
  }
9020
8749
  }
9021
8750
  };
@@ -9097,7 +8826,7 @@ function extractFullFields(schema2) {
9097
8826
  }
9098
8827
 
9099
8828
  // src/services/ArtifactService.ts
9100
- var logger7 = agentsCore.getLogger("ArtifactService");
8829
+ var logger6 = agentsCore.getLogger("ArtifactService");
9101
8830
  var ArtifactService = class _ArtifactService {
9102
8831
  constructor(context) {
9103
8832
  this.context = context;
@@ -9130,7 +8859,7 @@ var ArtifactService = class _ArtifactService {
9130
8859
  id: taskId
9131
8860
  });
9132
8861
  if (!task) {
9133
- logger7.warn({ taskId }, "Task not found when fetching artifacts");
8862
+ logger6.warn({ taskId }, "Task not found when fetching artifacts");
9134
8863
  continue;
9135
8864
  }
9136
8865
  const taskArtifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
@@ -9148,7 +8877,7 @@ var ArtifactService = class _ArtifactService {
9148
8877
  }
9149
8878
  }
9150
8879
  } catch (error) {
9151
- logger7.error({ error, contextId }, "Error loading context artifacts");
8880
+ logger6.error({ error, contextId }, "Error loading context artifacts");
9152
8881
  }
9153
8882
  return artifacts;
9154
8883
  }
@@ -9157,12 +8886,12 @@ var ArtifactService = class _ArtifactService {
9157
8886
  */
9158
8887
  async createArtifact(request, subAgentId) {
9159
8888
  if (!this.context.sessionId) {
9160
- logger7.warn({ request }, "No session ID available for artifact creation");
8889
+ logger6.warn({ request }, "No session ID available for artifact creation");
9161
8890
  return null;
9162
8891
  }
9163
8892
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
9164
8893
  if (!toolResult) {
9165
- logger7.warn(
8894
+ logger6.warn(
9166
8895
  { request, sessionId: this.context.sessionId },
9167
8896
  "Tool result not found for artifact"
9168
8897
  );
@@ -9178,7 +8907,7 @@ var ArtifactService = class _ArtifactService {
9178
8907
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
9179
8908
  }
9180
8909
  if (!selectedData) {
9181
- logger7.warn(
8910
+ logger6.warn(
9182
8911
  {
9183
8912
  request,
9184
8913
  baseSelector: request.baseSelector
@@ -9249,7 +8978,7 @@ var ArtifactService = class _ArtifactService {
9249
8978
  );
9250
8979
  return artifactData;
9251
8980
  } catch (error) {
9252
- logger7.error({ error, request }, "Failed to create artifact");
8981
+ logger6.error({ error, request }, "Failed to create artifact");
9253
8982
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
9254
8983
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
9255
8984
  }
@@ -9278,7 +9007,7 @@ var ArtifactService = class _ArtifactService {
9278
9007
  }
9279
9008
  try {
9280
9009
  if (!this.context.projectId || !this.context.taskId) {
9281
- logger7.warn(
9010
+ logger6.warn(
9282
9011
  { artifactId, toolCallId },
9283
9012
  "No projectId or taskId available for artifact lookup"
9284
9013
  );
@@ -9302,7 +9031,7 @@ var ArtifactService = class _ArtifactService {
9302
9031
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
9303
9032
  }
9304
9033
  } catch (error) {
9305
- logger7.warn(
9034
+ logger6.warn(
9306
9035
  { artifactId, toolCallId, taskId: this.context.taskId, error },
9307
9036
  "Failed to fetch artifact"
9308
9037
  );
@@ -9333,7 +9062,7 @@ var ArtifactService = class _ArtifactService {
9333
9062
  }
9334
9063
  try {
9335
9064
  if (!this.context.projectId || !this.context.taskId) {
9336
- logger7.warn(
9065
+ logger6.warn(
9337
9066
  { artifactId, toolCallId },
9338
9067
  "No projectId or taskId available for artifact lookup"
9339
9068
  );
@@ -9357,7 +9086,7 @@ var ArtifactService = class _ArtifactService {
9357
9086
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
9358
9087
  }
9359
9088
  } catch (error) {
9360
- logger7.warn(
9089
+ logger6.warn(
9361
9090
  { artifactId, toolCallId, taskId: this.context.taskId, error },
9362
9091
  "Failed to fetch artifact"
9363
9092
  );
@@ -9374,7 +9103,7 @@ var ArtifactService = class _ArtifactService {
9374
9103
  data = artifact.parts?.[0]?.data;
9375
9104
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9376
9105
  dataSource = "parts[0].data (fallback)";
9377
- logger7.debug(
9106
+ logger6.debug(
9378
9107
  { artifactId, toolCallId, dataSource },
9379
9108
  "Using fallback data source for artifact summary"
9380
9109
  );
@@ -9382,14 +9111,14 @@ var ArtifactService = class _ArtifactService {
9382
9111
  data = artifact.data;
9383
9112
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9384
9113
  dataSource = "artifact.data (fallback)";
9385
- logger7.debug(
9114
+ logger6.debug(
9386
9115
  { artifactId, toolCallId, dataSource },
9387
9116
  "Using fallback data source for artifact summary"
9388
9117
  );
9389
9118
  } else {
9390
9119
  data = {};
9391
9120
  dataSource = "empty (no data found)";
9392
- logger7.warn(
9121
+ logger6.warn(
9393
9122
  {
9394
9123
  artifactId,
9395
9124
  toolCallId,
@@ -9426,7 +9155,7 @@ var ArtifactService = class _ArtifactService {
9426
9155
  data = artifact.parts?.[0]?.data;
9427
9156
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9428
9157
  dataSource = "parts[0].data (fallback)";
9429
- logger7.debug(
9158
+ logger6.debug(
9430
9159
  { artifactId, toolCallId, dataSource },
9431
9160
  "Using fallback data source for artifact full data"
9432
9161
  );
@@ -9434,14 +9163,14 @@ var ArtifactService = class _ArtifactService {
9434
9163
  data = artifact.data;
9435
9164
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9436
9165
  dataSource = "artifact.data (fallback)";
9437
- logger7.debug(
9166
+ logger6.debug(
9438
9167
  { artifactId, toolCallId, dataSource },
9439
9168
  "Using fallback data source for artifact full data"
9440
9169
  );
9441
9170
  } else {
9442
9171
  data = {};
9443
9172
  dataSource = "empty (no data found)";
9444
- logger7.warn(
9173
+ logger6.warn(
9445
9174
  {
9446
9175
  artifactId,
9447
9176
  toolCallId,
@@ -9495,7 +9224,7 @@ var ArtifactService = class _ArtifactService {
9495
9224
  const error = new Error(
9496
9225
  `Cannot save artifact: Missing required fields [${summaryValidation.missingRequired.join(", ")}] for '${artifactType}' schema. Required: [${summaryValidation.missingRequired.join(", ")}]. Found: [${summaryValidation.actualFields.join(", ")}]. Consider using a different artifact component type that matches your data structure.`
9497
9226
  );
9498
- logger7.error(
9227
+ logger6.error(
9499
9228
  {
9500
9229
  artifactId,
9501
9230
  artifactType,
@@ -9508,7 +9237,7 @@ var ArtifactService = class _ArtifactService {
9508
9237
  throw error;
9509
9238
  }
9510
9239
  if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) {
9511
- logger7.warn(
9240
+ logger6.warn(
9512
9241
  {
9513
9242
  artifactId,
9514
9243
  artifactType,
@@ -9522,7 +9251,7 @@ var ArtifactService = class _ArtifactService {
9522
9251
  );
9523
9252
  }
9524
9253
  if (!fullValidation.hasExpectedFields || fullValidation.extraFields.length > 0) {
9525
- logger7.warn(
9254
+ logger6.warn(
9526
9255
  {
9527
9256
  artifactId,
9528
9257
  artifactType,
@@ -9594,7 +9323,7 @@ var ArtifactService = class _ArtifactService {
9594
9323
  }
9595
9324
  );
9596
9325
  } else {
9597
- logger7.warn(
9326
+ logger6.warn(
9598
9327
  {
9599
9328
  artifactId: request.artifactId,
9600
9329
  hasStreamRequestId: !!this.context.streamRequestId,
@@ -9669,7 +9398,7 @@ var ArtifactService = class _ArtifactService {
9669
9398
  summaryData = this.filterBySchema(artifact.data, previewSchema);
9670
9399
  fullData = this.filterBySchema(artifact.data, fullSchema);
9671
9400
  } catch (error) {
9672
- logger7.warn(
9401
+ logger6.warn(
9673
9402
  {
9674
9403
  artifactType: artifact.type,
9675
9404
  error: error instanceof Error ? error.message : "Unknown error"
@@ -9707,7 +9436,7 @@ var ArtifactService = class _ArtifactService {
9707
9436
  artifact: artifactToSave
9708
9437
  });
9709
9438
  if (!result.created && result.existing) {
9710
- logger7.debug(
9439
+ logger6.debug(
9711
9440
  {
9712
9441
  artifactId: artifact.artifactId,
9713
9442
  taskId: this.context.taskId
@@ -9767,7 +9496,7 @@ var ArtifactService = class _ArtifactService {
9767
9496
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
9768
9497
  }
9769
9498
  } catch (error) {
9770
- logger7.warn(
9499
+ logger6.warn(
9771
9500
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
9772
9501
  "Failed to extract schema field"
9773
9502
  );
@@ -9796,7 +9525,7 @@ var ArtifactService = class _ArtifactService {
9796
9525
  };
9797
9526
 
9798
9527
  // src/services/ArtifactParser.ts
9799
- var logger8 = agentsCore.getLogger("ArtifactParser");
9528
+ var logger7 = agentsCore.getLogger("ArtifactParser");
9800
9529
  var ArtifactParser = class _ArtifactParser {
9801
9530
  static ARTIFACT_CHECK_REGEX = /<artifact:ref\s+(?=.*id=['"][^'"]+['"])(?=.*tool=['"][^'"]+['"])[^>]*\/>/;
9802
9531
  static ATTR_REGEX = /(\w+)="([^"]*)"|(\w+)='([^']*)'|(\w+)=({[^}]+})/g;
@@ -9907,7 +9636,7 @@ var ArtifactParser = class _ArtifactParser {
9907
9636
  attrs[key] = value;
9908
9637
  }
9909
9638
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
9910
- logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
9639
+ logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
9911
9640
  return null;
9912
9641
  }
9913
9642
  return {
@@ -9968,7 +9697,7 @@ var ArtifactParser = class _ArtifactParser {
9968
9697
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
9969
9698
  );
9970
9699
  processedText = processedText.replace(annotation.raw, "");
9971
- logger8.warn(
9700
+ logger7.warn(
9972
9701
  { annotation, artifactData },
9973
9702
  "Removed failed artifact:create annotation from output"
9974
9703
  );
@@ -9979,11 +9708,11 @@ var ArtifactParser = class _ArtifactParser {
9979
9708
  if (annotation.raw) {
9980
9709
  processedText = processedText.replace(annotation.raw, "");
9981
9710
  }
9982
- logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
9711
+ logger7.error({ annotation, error }, "Failed to extract artifact from create annotation");
9983
9712
  }
9984
9713
  }
9985
9714
  if (failedAnnotations.length > 0) {
9986
- logger8.warn(
9715
+ logger7.warn(
9987
9716
  {
9988
9717
  failedCount: failedAnnotations.length,
9989
9718
  failures: failedAnnotations
@@ -10167,7 +9896,7 @@ var ArtifactParser = class _ArtifactParser {
10167
9896
  };
10168
9897
 
10169
9898
  // src/services/AgentSession.ts
10170
- var logger9 = agentsCore.getLogger("AgentSession");
9899
+ var logger8 = agentsCore.getLogger("AgentSession");
10171
9900
  var AgentSession = class {
10172
9901
  // Whether to send data operations
10173
9902
  constructor(sessionId, messageId, agentId, tenantId, projectId, contextId) {
@@ -10177,7 +9906,7 @@ var AgentSession = class {
10177
9906
  this.tenantId = tenantId;
10178
9907
  this.projectId = projectId;
10179
9908
  this.contextId = contextId;
10180
- logger9.debug({ sessionId, messageId, agentId }, "AgentSession created");
9909
+ logger8.debug({ sessionId, messageId, agentId }, "AgentSession created");
10181
9910
  if (tenantId && projectId) {
10182
9911
  toolSessionManager.createSessionWithId(
10183
9912
  sessionId,
@@ -10234,7 +9963,7 @@ var AgentSession = class {
10234
9963
  */
10235
9964
  enableEmitOperations() {
10236
9965
  this.isEmitOperations = true;
10237
- logger9.info(
9966
+ logger8.info(
10238
9967
  { sessionId: this.sessionId },
10239
9968
  "\u{1F50D} DEBUG: Emit operations enabled for AgentSession"
10240
9969
  );
@@ -10243,6 +9972,7 @@ var AgentSession = class {
10243
9972
  * Send data operation to stream when emit operations is enabled
10244
9973
  */
10245
9974
  async sendDataOperation(event) {
9975
+ console.log("sendDataOperation called with event", Date.now());
10246
9976
  try {
10247
9977
  const streamHelper = getStreamHelper(this.sessionId);
10248
9978
  if (streamHelper) {
@@ -10258,7 +9988,7 @@ var AgentSession = class {
10258
9988
  await streamHelper.writeOperation(formattedOperation);
10259
9989
  }
10260
9990
  } catch (error) {
10261
- logger9.error(
9991
+ logger8.error(
10262
9992
  {
10263
9993
  sessionId: this.sessionId,
10264
9994
  eventType: event.eventType,
@@ -10317,7 +10047,7 @@ var AgentSession = class {
10317
10047
  if (this.statusUpdateState.config.timeInSeconds) {
10318
10048
  this.statusUpdateTimer = setInterval(async () => {
10319
10049
  if (!this.statusUpdateState || this.isEnded) {
10320
- logger9.debug(
10050
+ logger8.debug(
10321
10051
  { sessionId: this.sessionId },
10322
10052
  "Timer triggered but session already cleaned up or ended"
10323
10053
  );
@@ -10329,7 +10059,7 @@ var AgentSession = class {
10329
10059
  }
10330
10060
  await this.checkAndSendTimeBasedUpdate();
10331
10061
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
10332
- logger9.info(
10062
+ logger8.info(
10333
10063
  {
10334
10064
  sessionId: this.sessionId,
10335
10065
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -10353,7 +10083,7 @@ var AgentSession = class {
10353
10083
  this.sendDataOperation(dataOpEvent);
10354
10084
  }
10355
10085
  if (this.isEnded) {
10356
- logger9.debug(
10086
+ logger8.debug(
10357
10087
  {
10358
10088
  sessionId: this.sessionId,
10359
10089
  eventType,
@@ -10375,7 +10105,7 @@ var AgentSession = class {
10375
10105
  if (artifactData.pendingGeneration) {
10376
10106
  const artifactId = artifactData.artifactId;
10377
10107
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
10378
- logger9.warn(
10108
+ logger8.warn(
10379
10109
  {
10380
10110
  sessionId: this.sessionId,
10381
10111
  artifactId,
@@ -10397,7 +10127,7 @@ var AgentSession = class {
10397
10127
  this.artifactProcessingErrors.set(artifactId, errorCount);
10398
10128
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
10399
10129
  this.pendingArtifacts.delete(artifactId);
10400
- logger9.error(
10130
+ logger8.error(
10401
10131
  {
10402
10132
  sessionId: this.sessionId,
10403
10133
  artifactId,
@@ -10409,7 +10139,7 @@ var AgentSession = class {
10409
10139
  "Artifact processing failed after max retries, giving up"
10410
10140
  );
10411
10141
  } else {
10412
- logger9.warn(
10142
+ logger8.warn(
10413
10143
  {
10414
10144
  sessionId: this.sessionId,
10415
10145
  artifactId,
@@ -10432,14 +10162,14 @@ var AgentSession = class {
10432
10162
  */
10433
10163
  checkStatusUpdates() {
10434
10164
  if (this.isEnded) {
10435
- logger9.debug(
10165
+ logger8.debug(
10436
10166
  { sessionId: this.sessionId },
10437
10167
  "Session has ended - skipping status update check"
10438
10168
  );
10439
10169
  return;
10440
10170
  }
10441
10171
  if (!this.statusUpdateState) {
10442
- logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
10172
+ logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
10443
10173
  return;
10444
10174
  }
10445
10175
  const statusUpdateState = this.statusUpdateState;
@@ -10450,11 +10180,11 @@ var AgentSession = class {
10450
10180
  */
10451
10181
  async checkAndSendTimeBasedUpdate() {
10452
10182
  if (this.isEnded) {
10453
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
10183
+ logger8.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
10454
10184
  return;
10455
10185
  }
10456
10186
  if (!this.statusUpdateState) {
10457
- logger9.debug(
10187
+ logger8.debug(
10458
10188
  { sessionId: this.sessionId },
10459
10189
  "No status updates configured for time-based check"
10460
10190
  );
@@ -10467,7 +10197,7 @@ var AgentSession = class {
10467
10197
  try {
10468
10198
  await this.generateAndSendUpdate();
10469
10199
  } catch (error) {
10470
- logger9.error(
10200
+ logger8.error(
10471
10201
  {
10472
10202
  sessionId: this.sessionId,
10473
10203
  error: error instanceof Error ? error.message : "Unknown error"
@@ -10570,29 +10300,29 @@ var AgentSession = class {
10570
10300
  */
10571
10301
  async generateAndSendUpdate() {
10572
10302
  if (this.isEnded) {
10573
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
10303
+ logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
10574
10304
  return;
10575
10305
  }
10576
10306
  if (this.isTextStreaming) {
10577
- logger9.debug(
10307
+ logger8.debug(
10578
10308
  { sessionId: this.sessionId },
10579
10309
  "Text is currently streaming - skipping status update"
10580
10310
  );
10581
10311
  return;
10582
10312
  }
10583
10313
  if (this.isGeneratingUpdate) {
10584
- logger9.debug(
10314
+ logger8.debug(
10585
10315
  { sessionId: this.sessionId },
10586
10316
  "Update already in progress - skipping duplicate generation"
10587
10317
  );
10588
10318
  return;
10589
10319
  }
10590
10320
  if (!this.statusUpdateState) {
10591
- logger9.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
10321
+ logger8.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
10592
10322
  return;
10593
10323
  }
10594
10324
  if (!this.agentId) {
10595
- logger9.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
10325
+ logger8.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
10596
10326
  return;
10597
10327
  }
10598
10328
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -10604,7 +10334,7 @@ var AgentSession = class {
10604
10334
  try {
10605
10335
  const streamHelper = getStreamHelper(this.sessionId);
10606
10336
  if (!streamHelper) {
10607
- logger9.warn(
10337
+ logger8.warn(
10608
10338
  { sessionId: this.sessionId },
10609
10339
  "No stream helper found - cannot send status update"
10610
10340
  );
@@ -10624,7 +10354,7 @@ var AgentSession = class {
10624
10354
  if (result.summaries && result.summaries.length > 0) {
10625
10355
  for (const summary of result.summaries) {
10626
10356
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
10627
- logger9.warn(
10357
+ logger8.warn(
10628
10358
  {
10629
10359
  sessionId: this.sessionId,
10630
10360
  summary
@@ -10661,7 +10391,7 @@ var AgentSession = class {
10661
10391
  this.statusUpdateState.lastEventCount = this.events.length;
10662
10392
  }
10663
10393
  } catch (error) {
10664
- logger9.error(
10394
+ logger8.error(
10665
10395
  {
10666
10396
  sessionId: this.sessionId,
10667
10397
  error: error instanceof Error ? error.message : "Unknown error",
@@ -10699,7 +10429,7 @@ var AgentSession = class {
10699
10429
  this.releaseUpdateLock();
10700
10430
  }
10701
10431
  } catch (error) {
10702
- logger9.error(
10432
+ logger8.error(
10703
10433
  {
10704
10434
  sessionId: this.sessionId,
10705
10435
  error: error instanceof Error ? error.message : "Unknown error"
@@ -10778,7 +10508,7 @@ User's Question/Context:
10778
10508
  ${conversationHistory}
10779
10509
  ` : "";
10780
10510
  } catch (error) {
10781
- logger9.warn(
10511
+ logger8.warn(
10782
10512
  { sessionId: this.sessionId, error },
10783
10513
  "Failed to fetch conversation history for structured status update"
10784
10514
  );
@@ -10872,7 +10602,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10872
10602
  if (!modelToUse) {
10873
10603
  throw new Error("No model configuration available");
10874
10604
  }
10875
- const model = ModelFactory.createModel(modelToUse);
10605
+ const model = agentsCore.ModelFactory.createModel(modelToUse);
10876
10606
  const { object } = await ai.generateObject({
10877
10607
  model,
10878
10608
  prompt,
@@ -10889,10 +10619,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10889
10619
  }
10890
10620
  });
10891
10621
  const result = object;
10892
- logger9.info({ result: JSON.stringify(result) }, "DEBUG: Result");
10622
+ logger8.info({ result: JSON.stringify(result) }, "DEBUG: Result");
10893
10623
  const summaries = [];
10894
10624
  for (const [componentId, data] of Object.entries(result)) {
10895
- logger9.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
10625
+ logger8.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
10896
10626
  if (componentId === "no_relevant_updates") {
10897
10627
  continue;
10898
10628
  }
@@ -10912,7 +10642,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10912
10642
  return { summaries };
10913
10643
  } catch (error) {
10914
10644
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
10915
- logger9.error({ error }, "Failed to generate structured update, using fallback");
10645
+ logger8.error({ error }, "Failed to generate structured update, using fallback");
10916
10646
  return { summaries: [] };
10917
10647
  } finally {
10918
10648
  span.end();
@@ -11184,7 +10914,7 @@ Make it specific and relevant.`;
11184
10914
  });
11185
10915
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
11186
10916
  modelToUse = agentData.models.base;
11187
- logger9.info(
10917
+ logger8.info(
11188
10918
  {
11189
10919
  sessionId: this.sessionId,
11190
10920
  artifactId: artifactData.artifactId,
@@ -11195,7 +10925,7 @@ Make it specific and relevant.`;
11195
10925
  );
11196
10926
  }
11197
10927
  } catch (error) {
11198
- logger9.warn(
10928
+ logger8.warn(
11199
10929
  {
11200
10930
  sessionId: this.sessionId,
11201
10931
  artifactId: artifactData.artifactId,
@@ -11207,7 +10937,7 @@ Make it specific and relevant.`;
11207
10937
  }
11208
10938
  }
11209
10939
  if (!modelToUse?.model?.trim()) {
11210
- logger9.warn(
10940
+ logger8.warn(
11211
10941
  {
11212
10942
  sessionId: this.sessionId,
11213
10943
  artifactId: artifactData.artifactId
@@ -11227,7 +10957,7 @@ Make it specific and relevant.`;
11227
10957
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolCallId || "tool results"}`
11228
10958
  };
11229
10959
  } else {
11230
- const model = ModelFactory.createModel(modelToUse);
10960
+ const model = agentsCore.ModelFactory.createModel(modelToUse);
11231
10961
  const schema2 = z8.z.object({
11232
10962
  name: z8.z.string().describe("Concise, descriptive name for the artifact"),
11233
10963
  description: z8.z.string().describe("Brief description of the artifact's relevance to the user's question")
@@ -11289,7 +11019,7 @@ Make it specific and relevant.`;
11289
11019
  return result2;
11290
11020
  } catch (error) {
11291
11021
  lastError = error instanceof Error ? error : new Error(String(error));
11292
- logger9.warn(
11022
+ logger8.warn(
11293
11023
  {
11294
11024
  sessionId: this.sessionId,
11295
11025
  artifactId: artifactData.artifactId,
@@ -11337,7 +11067,7 @@ Make it specific and relevant.`;
11337
11067
  });
11338
11068
  span.setStatus({ code: api.SpanStatusCode.OK });
11339
11069
  } catch (saveError) {
11340
- logger9.error(
11070
+ logger8.error(
11341
11071
  {
11342
11072
  sessionId: this.sessionId,
11343
11073
  artifactId: artifactData.artifactId,
@@ -11365,7 +11095,7 @@ Make it specific and relevant.`;
11365
11095
  metadata: artifactData.metadata || {},
11366
11096
  toolCallId: artifactData.toolCallId
11367
11097
  });
11368
- logger9.info(
11098
+ logger8.info(
11369
11099
  {
11370
11100
  sessionId: this.sessionId,
11371
11101
  artifactId: artifactData.artifactId
@@ -11376,7 +11106,7 @@ Make it specific and relevant.`;
11376
11106
  } catch (fallbackError) {
11377
11107
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
11378
11108
  if (isDuplicateError) ; else {
11379
- logger9.error(
11109
+ logger8.error(
11380
11110
  {
11381
11111
  sessionId: this.sessionId,
11382
11112
  artifactId: artifactData.artifactId,
@@ -11389,7 +11119,7 @@ Make it specific and relevant.`;
11389
11119
  }
11390
11120
  } catch (error) {
11391
11121
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
11392
- logger9.error(
11122
+ logger8.error(
11393
11123
  {
11394
11124
  sessionId: this.sessionId,
11395
11125
  artifactId: artifactData.artifactId,
@@ -11408,7 +11138,7 @@ Make it specific and relevant.`;
11408
11138
  */
11409
11139
  setArtifactCache(key, artifact) {
11410
11140
  this.artifactCache.set(key, artifact);
11411
- logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
11141
+ logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
11412
11142
  }
11413
11143
  /**
11414
11144
  * Get session-scoped ArtifactService instance
@@ -11427,7 +11157,7 @@ Make it specific and relevant.`;
11427
11157
  */
11428
11158
  getArtifactCache(key) {
11429
11159
  const artifact = this.artifactCache.get(key);
11430
- logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
11160
+ logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
11431
11161
  return artifact || null;
11432
11162
  }
11433
11163
  /**
@@ -11448,7 +11178,7 @@ var AgentSessionManager = class {
11448
11178
  const sessionId = messageId;
11449
11179
  const session = new AgentSession(sessionId, messageId, agentId, tenantId, projectId, contextId);
11450
11180
  this.sessions.set(sessionId, session);
11451
- logger9.info(
11181
+ logger8.info(
11452
11182
  { sessionId, messageId, agentId, tenantId, projectId, contextId },
11453
11183
  "AgentSession created"
11454
11184
  );
@@ -11462,7 +11192,7 @@ var AgentSessionManager = class {
11462
11192
  if (session) {
11463
11193
  session.initializeStatusUpdates(config, summarizerModel, baseModel);
11464
11194
  } else {
11465
- logger9.error(
11195
+ logger8.error(
11466
11196
  {
11467
11197
  sessionId,
11468
11198
  availableSessions: Array.from(this.sessions.keys())
@@ -11479,7 +11209,7 @@ var AgentSessionManager = class {
11479
11209
  if (session) {
11480
11210
  session.enableEmitOperations();
11481
11211
  } else {
11482
- logger9.error(
11212
+ logger8.error(
11483
11213
  {
11484
11214
  sessionId,
11485
11215
  availableSessions: Array.from(this.sessions.keys())
@@ -11501,7 +11231,7 @@ var AgentSessionManager = class {
11501
11231
  recordEvent(sessionId, eventType, subAgentId, data) {
11502
11232
  const session = this.sessions.get(sessionId);
11503
11233
  if (!session) {
11504
- logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
11234
+ logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
11505
11235
  return;
11506
11236
  }
11507
11237
  session.recordEvent(eventType, subAgentId, data);
@@ -11512,12 +11242,12 @@ var AgentSessionManager = class {
11512
11242
  endSession(sessionId) {
11513
11243
  const session = this.sessions.get(sessionId);
11514
11244
  if (!session) {
11515
- logger9.warn({ sessionId }, "Attempted to end non-existent session");
11245
+ logger8.warn({ sessionId }, "Attempted to end non-existent session");
11516
11246
  return [];
11517
11247
  }
11518
11248
  const events = session.getEvents();
11519
11249
  const summary = session.getSummary();
11520
- logger9.info({ sessionId, summary }, "AgentSession ended");
11250
+ logger8.info({ sessionId, summary }, "AgentSession ended");
11521
11251
  session.cleanup();
11522
11252
  this.sessions.delete(sessionId);
11523
11253
  return events;
@@ -11627,7 +11357,7 @@ init_logger();
11627
11357
  // src/services/IncrementalStreamParser.ts
11628
11358
  init_execution_limits();
11629
11359
  init_logger();
11630
- var logger10 = agentsCore.getLogger("IncrementalStreamParser");
11360
+ var logger9 = agentsCore.getLogger("IncrementalStreamParser");
11631
11361
  var IncrementalStreamParser = class _IncrementalStreamParser {
11632
11362
  buffer = "";
11633
11363
  pendingTextBuffer = "";
@@ -11685,7 +11415,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
11685
11415
  async initializeArtifactMap() {
11686
11416
  try {
11687
11417
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
11688
- logger10.debug(
11418
+ logger9.debug(
11689
11419
  {
11690
11420
  contextId: this.contextId,
11691
11421
  artifactMapSize: this.artifactMap.size
@@ -11693,7 +11423,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
11693
11423
  "Initialized artifact map for streaming"
11694
11424
  );
11695
11425
  } catch (error) {
11696
- logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
11426
+ logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
11697
11427
  this.artifactMap = /* @__PURE__ */ new Map();
11698
11428
  }
11699
11429
  }
@@ -12026,6 +11756,143 @@ ${chunk}`;
12026
11756
  }
12027
11757
  };
12028
11758
 
11759
+ // src/services/PendingToolApprovalManager.ts
11760
+ init_logger();
11761
+ var logger10 = agentsCore.getLogger("PendingToolApprovalManager");
11762
+ var APPROVAL_CLEANUP_INTERVAL_MS = 2 * 60 * 1e3;
11763
+ var APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
11764
+ var PendingToolApprovalManager = class _PendingToolApprovalManager {
11765
+ static instance;
11766
+ pendingApprovals = /* @__PURE__ */ new Map();
11767
+ constructor() {
11768
+ setInterval(() => this.cleanupExpiredApprovals(), APPROVAL_CLEANUP_INTERVAL_MS);
11769
+ }
11770
+ static getInstance() {
11771
+ if (!_PendingToolApprovalManager.instance) {
11772
+ _PendingToolApprovalManager.instance = new _PendingToolApprovalManager();
11773
+ }
11774
+ return _PendingToolApprovalManager.instance;
11775
+ }
11776
+ /**
11777
+ * Create a new pending approval and return a promise that resolves with approval status
11778
+ */
11779
+ async waitForApproval(toolCallId, toolName, args2, conversationId, subAgentId) {
11780
+ return new Promise((resolve2, reject) => {
11781
+ const timeoutId = setTimeout(() => {
11782
+ this.pendingApprovals.delete(toolCallId);
11783
+ resolve2({
11784
+ approved: false,
11785
+ reason: `Tool approval timeout for ${toolName} (${toolCallId})`
11786
+ });
11787
+ }, APPROVAL_TIMEOUT_MS);
11788
+ const approval = {
11789
+ toolCallId,
11790
+ toolName,
11791
+ args: args2,
11792
+ conversationId,
11793
+ subAgentId,
11794
+ createdAt: Date.now(),
11795
+ resolve: resolve2,
11796
+ reject,
11797
+ timeoutId
11798
+ };
11799
+ this.pendingApprovals.set(toolCallId, approval);
11800
+ logger10.info(
11801
+ {
11802
+ toolCallId,
11803
+ toolName,
11804
+ conversationId,
11805
+ subAgentId
11806
+ },
11807
+ "Tool approval request created, waiting for user response"
11808
+ );
11809
+ });
11810
+ }
11811
+ /**
11812
+ * Approve a pending tool call
11813
+ */
11814
+ approveToolCall(toolCallId) {
11815
+ const approval = this.pendingApprovals.get(toolCallId);
11816
+ if (!approval) {
11817
+ logger10.warn({ toolCallId }, "Tool approval not found or already processed");
11818
+ return false;
11819
+ }
11820
+ logger10.info(
11821
+ {
11822
+ toolCallId,
11823
+ toolName: approval.toolName,
11824
+ conversationId: approval.conversationId
11825
+ },
11826
+ "Tool approved by user, resuming execution"
11827
+ );
11828
+ clearTimeout(approval.timeoutId);
11829
+ this.pendingApprovals.delete(toolCallId);
11830
+ approval.resolve({ approved: true });
11831
+ return true;
11832
+ }
11833
+ /**
11834
+ * Deny a pending tool call
11835
+ */
11836
+ denyToolCall(toolCallId, reason) {
11837
+ const approval = this.pendingApprovals.get(toolCallId);
11838
+ if (!approval) {
11839
+ logger10.warn({ toolCallId }, "Tool approval not found or already processed");
11840
+ return false;
11841
+ }
11842
+ logger10.info(
11843
+ {
11844
+ toolCallId,
11845
+ toolName: approval.toolName,
11846
+ conversationId: approval.conversationId,
11847
+ reason
11848
+ },
11849
+ "Tool execution denied by user"
11850
+ );
11851
+ clearTimeout(approval.timeoutId);
11852
+ this.pendingApprovals.delete(toolCallId);
11853
+ approval.resolve({
11854
+ approved: false,
11855
+ reason: reason || "User denied approval"
11856
+ });
11857
+ return true;
11858
+ }
11859
+ /**
11860
+ * Clean up expired approvals (called by interval timer)
11861
+ */
11862
+ cleanupExpiredApprovals() {
11863
+ const now = Date.now();
11864
+ let cleanedUp = 0;
11865
+ for (const [toolCallId, approval] of this.pendingApprovals) {
11866
+ if (now - approval.createdAt > APPROVAL_TIMEOUT_MS) {
11867
+ clearTimeout(approval.timeoutId);
11868
+ this.pendingApprovals.delete(toolCallId);
11869
+ approval.resolve({ approved: false, reason: "Tool approval expired" });
11870
+ cleanedUp++;
11871
+ }
11872
+ }
11873
+ if (cleanedUp > 0) {
11874
+ logger10.info({ cleanedUp }, "Cleaned up expired tool approvals");
11875
+ }
11876
+ }
11877
+ /**
11878
+ * Get current status for monitoring
11879
+ */
11880
+ getStatus() {
11881
+ return {
11882
+ pendingApprovals: this.pendingApprovals.size,
11883
+ approvals: Array.from(this.pendingApprovals.values()).map((approval) => ({
11884
+ toolCallId: approval.toolCallId,
11885
+ toolName: approval.toolName,
11886
+ conversationId: approval.conversationId,
11887
+ subAgentId: approval.subAgentId,
11888
+ createdAt: approval.createdAt,
11889
+ age: Date.now() - approval.createdAt
11890
+ }))
11891
+ };
11892
+ }
11893
+ };
11894
+ var pendingToolApprovalManager = PendingToolApprovalManager.getInstance();
11895
+
12029
11896
  // src/services/ResponseFormatter.ts
12030
11897
  init_logger();
12031
11898
  var logger11 = agentsCore.getLogger("ResponseFormatter");
@@ -14847,7 +14714,7 @@ var Agent = class {
14847
14714
  /**
14848
14715
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
14849
14716
  */
14850
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId) {
14717
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId, options) {
14851
14718
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
14852
14719
  return toolDefinition;
14853
14720
  }
@@ -14869,13 +14736,24 @@ var Agent = class {
14869
14736
  });
14870
14737
  }
14871
14738
  const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
14739
+ const needsApproval = options?.needsApproval || false;
14872
14740
  if (streamRequestId && !isInternalTool) {
14873
- agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
14741
+ const toolCallData = {
14874
14742
  toolName,
14875
14743
  input: args2,
14876
14744
  toolCallId,
14877
14745
  relationshipId
14878
- });
14746
+ };
14747
+ if (needsApproval) {
14748
+ toolCallData.needsApproval = true;
14749
+ toolCallData.conversationId = this.conversationId;
14750
+ }
14751
+ await agentSessionManager.recordEvent(
14752
+ streamRequestId,
14753
+ "tool_call",
14754
+ this.config.id,
14755
+ toolCallData
14756
+ );
14879
14757
  }
14880
14758
  try {
14881
14759
  const result = await originalExecute(args2, context);
@@ -14920,7 +14798,8 @@ var Agent = class {
14920
14798
  output: result,
14921
14799
  toolCallId,
14922
14800
  duration,
14923
- relationshipId
14801
+ relationshipId,
14802
+ needsApproval
14924
14803
  });
14925
14804
  }
14926
14805
  return result;
@@ -14934,7 +14813,8 @@ var Agent = class {
14934
14813
  toolCallId,
14935
14814
  duration,
14936
14815
  error: errorMessage,
14937
- relationshipId
14816
+ relationshipId,
14817
+ needsApproval
14938
14818
  });
14939
14819
  }
14940
14820
  throw error;
@@ -15003,30 +14883,120 @@ var Agent = class {
15003
14883
  const wrappedTools2 = {};
15004
14884
  for (const [index, toolSet] of tools.entries()) {
15005
14885
  const relationshipId = mcpTools[index]?.relationshipId;
15006
- for (const [toolName, toolDef] of Object.entries(toolSet)) {
14886
+ for (const [toolName, toolDef] of Object.entries(toolSet.tools)) {
14887
+ const needsApproval = toolSet.toolPolicies?.[toolName]?.needsApproval || false;
14888
+ const enhancedTool = {
14889
+ ...toolDef,
14890
+ needsApproval
14891
+ };
15007
14892
  wrappedTools2[toolName] = this.wrapToolWithStreaming(
15008
14893
  toolName,
15009
- toolDef,
14894
+ enhancedTool,
15010
14895
  streamRequestId,
15011
14896
  "mcp",
15012
- relationshipId
14897
+ relationshipId,
14898
+ { needsApproval }
15013
14899
  );
15014
14900
  }
15015
14901
  }
15016
14902
  return wrappedTools2;
15017
14903
  }
15018
14904
  const wrappedTools = {};
15019
- for (const [index, toolSet] of tools.entries()) {
14905
+ for (const [index, toolResult] of tools.entries()) {
15020
14906
  const relationshipId = mcpTools[index]?.relationshipId;
15021
- for (const [toolName, originalTool] of Object.entries(toolSet)) {
14907
+ for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
15022
14908
  if (!isValidTool(originalTool)) {
15023
14909
  logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
15024
14910
  continue;
15025
14911
  }
14912
+ const needsApproval = toolResult.toolPolicies?.[toolName]?.needsApproval || false;
14913
+ logger19.debug(
14914
+ {
14915
+ toolName,
14916
+ toolPolicies: toolResult.toolPolicies,
14917
+ needsApproval,
14918
+ policyForThisTool: toolResult.toolPolicies?.[toolName]
14919
+ },
14920
+ "Tool approval check"
14921
+ );
15026
14922
  const sessionWrappedTool = ai.tool({
15027
14923
  description: originalTool.description,
15028
14924
  inputSchema: originalTool.inputSchema,
15029
14925
  execute: async (args2, { toolCallId }) => {
14926
+ if (needsApproval) {
14927
+ logger19.info(
14928
+ { toolName, toolCallId, args: args2 },
14929
+ "Tool requires approval - waiting for user response"
14930
+ );
14931
+ const currentSpan = api.trace.getActiveSpan();
14932
+ if (currentSpan) {
14933
+ currentSpan.addEvent("tool.approval.requested", {
14934
+ "tool.name": toolName,
14935
+ "tool.callId": toolCallId,
14936
+ "subAgent.id": this.config.id
14937
+ });
14938
+ }
14939
+ tracer.startActiveSpan(
14940
+ "tool.approval_requested",
14941
+ {
14942
+ attributes: {
14943
+ "tool.name": toolName,
14944
+ "tool.callId": toolCallId,
14945
+ "subAgent.id": this.config.id,
14946
+ "subAgent.name": this.config.name
14947
+ }
14948
+ },
14949
+ (requestSpan) => {
14950
+ requestSpan.setStatus({ code: api.SpanStatusCode.OK });
14951
+ requestSpan.end();
14952
+ }
14953
+ );
14954
+ const approvalResult = await pendingToolApprovalManager.waitForApproval(
14955
+ toolCallId,
14956
+ toolName,
14957
+ args2,
14958
+ this.conversationId || "unknown",
14959
+ this.config.id
14960
+ );
14961
+ if (!approvalResult.approved) {
14962
+ return tracer.startActiveSpan(
14963
+ "tool.approval_denied",
14964
+ {
14965
+ attributes: {
14966
+ "tool.name": toolName,
14967
+ "tool.callId": toolCallId,
14968
+ "subAgent.id": this.config.id,
14969
+ "subAgent.name": this.config.name
14970
+ }
14971
+ },
14972
+ (denialSpan) => {
14973
+ logger19.info(
14974
+ { toolName, toolCallId, reason: approvalResult.reason },
14975
+ "Tool execution denied by user"
14976
+ );
14977
+ denialSpan.setStatus({ code: api.SpanStatusCode.OK });
14978
+ denialSpan.end();
14979
+ return `User denied approval to run this tool: ${approvalResult.reason}`;
14980
+ }
14981
+ );
14982
+ }
14983
+ tracer.startActiveSpan(
14984
+ "tool.approval_approved",
14985
+ {
14986
+ attributes: {
14987
+ "tool.name": toolName,
14988
+ "tool.callId": toolCallId,
14989
+ "subAgent.id": this.config.id,
14990
+ "subAgent.name": this.config.name
14991
+ }
14992
+ },
14993
+ (approvedSpan) => {
14994
+ logger19.info({ toolName, toolCallId }, "Tool approved, continuing with execution");
14995
+ approvedSpan.setStatus({ code: api.SpanStatusCode.OK });
14996
+ approvedSpan.end();
14997
+ }
14998
+ );
14999
+ }
15030
15000
  logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
15031
15001
  try {
15032
15002
  const rawResult = await originalTool.execute(args2, { toolCallId });
@@ -15092,7 +15062,8 @@ var Agent = class {
15092
15062
  sessionWrappedTool,
15093
15063
  streamRequestId,
15094
15064
  "mcp",
15095
- relationshipId
15065
+ relationshipId,
15066
+ { needsApproval }
15096
15067
  );
15097
15068
  }
15098
15069
  }
@@ -15131,8 +15102,10 @@ var Agent = class {
15131
15102
  subAgentId: this.config.id
15132
15103
  }
15133
15104
  });
15134
- const agentToolRelationHeaders = toolsForAgent.data.find((t2) => t2.toolId === tool3.id)?.headers || void 0;
15135
- const selectedTools = toolsForAgent.data.find((t2) => t2.toolId === tool3.id)?.selectedTools || void 0;
15105
+ const toolRelation = toolsForAgent.data.find((t2) => t2.toolId === tool3.id);
15106
+ const agentToolRelationHeaders = toolRelation?.headers || void 0;
15107
+ const selectedTools = toolRelation?.selectedTools || void 0;
15108
+ const toolPolicies = toolRelation?.toolPolicies || {};
15136
15109
  let serverConfig;
15137
15110
  if (credentialReferenceId && this.credentialStuffer) {
15138
15111
  const credentialReference = await agentsCore.getCredentialReference(dbClient_default)({
@@ -15263,7 +15236,7 @@ var Agent = class {
15263
15236
  );
15264
15237
  }
15265
15238
  }
15266
- return tools;
15239
+ return { tools, toolPolicies };
15267
15240
  }
15268
15241
  async createMcpConnection(tool3, serverConfig) {
15269
15242
  const client = new agentsCore.McpClient({
@@ -15286,12 +15259,12 @@ var Agent = class {
15286
15259
  if (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) {
15287
15260
  const errorMessage = "Connection refused. Please check if the MCP server is running.";
15288
15261
  throw new Error(errorMessage);
15289
- } else if (error.message.includes("404")) {
15262
+ }
15263
+ if (error.message.includes("404")) {
15290
15264
  const errorMessage = "Error accessing endpoint (HTTP 404)";
15291
15265
  throw new Error(errorMessage);
15292
- } else {
15293
- throw new Error(`MCP server connection failed: ${error.message}`);
15294
15266
  }
15267
+ throw new Error(`MCP server connection failed: ${error.message}`);
15295
15268
  }
15296
15269
  throw error;
15297
15270
  }
@@ -16076,7 +16049,7 @@ ${output}`;
16076
16049
  }
16077
16050
  }
16078
16051
  const primaryModelSettings = this.getPrimaryModel();
16079
- const modelSettings = ModelFactory.prepareGenerationConfig(primaryModelSettings);
16052
+ const modelSettings = agentsCore.ModelFactory.prepareGenerationConfig(primaryModelSettings);
16080
16053
  let response;
16081
16054
  let textResponse;
16082
16055
  const hasStructuredOutput = this.config.dataComponents && this.config.dataComponents.length > 0;
@@ -16189,13 +16162,13 @@ ${output}`;
16189
16162
  parser.markToolResult();
16190
16163
  }
16191
16164
  break;
16192
- case "error":
16165
+ case "error": {
16193
16166
  if (event.error instanceof Error) {
16194
16167
  throw event.error;
16195
- } else {
16196
- const errorMessage = event.error?.error?.message;
16197
- throw new Error(errorMessage);
16198
16168
  }
16169
+ const errorMessage = event.error?.error?.message;
16170
+ throw new Error(errorMessage);
16171
+ }
16199
16172
  }
16200
16173
  }
16201
16174
  await parser.finalize();
@@ -16387,7 +16360,7 @@ ${output}${structureHintsFormatted}`;
16387
16360
  componentSchemas
16388
16361
  );
16389
16362
  }
16390
- const structuredModelSettings = ModelFactory.prepareGenerationConfig(
16363
+ const structuredModelSettings = agentsCore.ModelFactory.prepareGenerationConfig(
16391
16364
  this.getStructuredOutputModel()
16392
16365
  );
16393
16366
  const configuredPhase2Timeout = structuredModelSettings.maxDuration ? Math.min(
@@ -17090,17 +17063,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
17090
17063
  }
17091
17064
  ]
17092
17065
  };
17093
- } else {
17094
- logger20.warn(
17095
- {
17096
- hasToolResult: !!toolResult,
17097
- hasOutput: !!toolResult?.output,
17098
- validationPassed: false,
17099
- output: toolResult?.output
17100
- },
17101
- "[DEBUG] Transfer validation FAILED"
17102
- );
17103
17066
  }
17067
+ logger20.warn(
17068
+ {
17069
+ hasToolResult: !!toolResult,
17070
+ hasOutput: !!toolResult?.output,
17071
+ validationPassed: false,
17072
+ output: toolResult?.output
17073
+ },
17074
+ "[DEBUG] Transfer validation FAILED"
17075
+ );
17104
17076
  }
17105
17077
  }
17106
17078
  }
@@ -18019,7 +17991,7 @@ var VercelDataStreamHelper = class _VercelDataStreamHelper {
18019
17991
  }
18020
17992
  const now = Date.now();
18021
17993
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
18022
- if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
17994
+ if (operation.type !== "tool_call" && operation.type !== "tool_result" && (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS)) {
18023
17995
  this.queuedEvents.push({ type: "data-operation", event: operation });
18024
17996
  return;
18025
17997
  }
@@ -19203,6 +19175,137 @@ app3.openapi(chatDataStreamRoute, async (c2) => {
19203
19175
  });
19204
19176
  }
19205
19177
  });
19178
+ var toolApprovalRoute = zodOpenapi.createRoute({
19179
+ method: "post",
19180
+ path: "/tool-approvals",
19181
+ tags: ["chat"],
19182
+ summary: "Approve or deny tool execution",
19183
+ description: "Handle user approval/denial of tool execution requests during conversations",
19184
+ security: [{ bearerAuth: [] }],
19185
+ request: {
19186
+ body: {
19187
+ content: {
19188
+ "application/json": {
19189
+ schema: zodOpenapi.z.object({
19190
+ conversationId: zodOpenapi.z.string().describe("The conversation ID"),
19191
+ toolCallId: zodOpenapi.z.string().describe("The tool call ID to respond to"),
19192
+ approved: zodOpenapi.z.boolean().describe("Whether the tool execution is approved"),
19193
+ reason: zodOpenapi.z.string().optional().describe("Optional reason for the decision")
19194
+ })
19195
+ }
19196
+ }
19197
+ }
19198
+ },
19199
+ responses: {
19200
+ 200: {
19201
+ description: "Tool approval response processed successfully",
19202
+ content: {
19203
+ "application/json": {
19204
+ schema: zodOpenapi.z.object({
19205
+ success: zodOpenapi.z.boolean(),
19206
+ message: zodOpenapi.z.string().optional()
19207
+ })
19208
+ }
19209
+ }
19210
+ },
19211
+ 400: {
19212
+ description: "Bad request - invalid tool call ID or conversation ID",
19213
+ content: {
19214
+ "application/json": {
19215
+ schema: zodOpenapi.z.object({
19216
+ error: zodOpenapi.z.string()
19217
+ })
19218
+ }
19219
+ }
19220
+ },
19221
+ 404: {
19222
+ description: "Tool call not found or already processed",
19223
+ content: {
19224
+ "application/json": {
19225
+ schema: zodOpenapi.z.object({
19226
+ error: zodOpenapi.z.string()
19227
+ })
19228
+ }
19229
+ }
19230
+ },
19231
+ 500: {
19232
+ description: "Internal server error",
19233
+ content: {
19234
+ "application/json": {
19235
+ schema: zodOpenapi.z.object({
19236
+ error: zodOpenapi.z.string(),
19237
+ message: zodOpenapi.z.string()
19238
+ })
19239
+ }
19240
+ }
19241
+ }
19242
+ }
19243
+ });
19244
+ app3.openapi(toolApprovalRoute, async (c2) => {
19245
+ const tracer2 = api.trace.getTracer("tool-approval-handler");
19246
+ return tracer2.startActiveSpan("tool_approval_request", async (span) => {
19247
+ try {
19248
+ const executionContext = agentsCore.getRequestExecutionContext(c2);
19249
+ const { tenantId, projectId } = executionContext;
19250
+ const requestBody = await c2.req.json();
19251
+ const { conversationId, toolCallId, approved, reason } = requestBody;
19252
+ logger26.info(
19253
+ {
19254
+ conversationId,
19255
+ toolCallId,
19256
+ approved,
19257
+ reason,
19258
+ tenantId,
19259
+ projectId
19260
+ },
19261
+ "Processing tool approval request"
19262
+ );
19263
+ const conversation = await agentsCore.getConversation(dbClient_default)({
19264
+ scopes: { tenantId, projectId },
19265
+ conversationId
19266
+ });
19267
+ if (!conversation) {
19268
+ span.setStatus({ code: 1, message: "Conversation not found" });
19269
+ return c2.json({ error: "Conversation not found" }, 404);
19270
+ }
19271
+ let success = false;
19272
+ if (approved) {
19273
+ success = pendingToolApprovalManager.approveToolCall(toolCallId);
19274
+ } else {
19275
+ success = pendingToolApprovalManager.denyToolCall(toolCallId, reason);
19276
+ }
19277
+ if (!success) {
19278
+ span.setStatus({ code: 1, message: "Tool call not found" });
19279
+ return c2.json({ error: "Tool call not found or already processed" }, 404);
19280
+ }
19281
+ logger26.info({ conversationId, toolCallId, approved }, "Tool approval processed successfully");
19282
+ span.setStatus({ code: 1, message: "Success" });
19283
+ return c2.json({
19284
+ success: true,
19285
+ message: approved ? "Tool execution approved" : "Tool execution denied"
19286
+ });
19287
+ } catch (error) {
19288
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
19289
+ logger26.error(
19290
+ {
19291
+ error: errorMessage,
19292
+ stack: error instanceof Error ? error.stack : void 0
19293
+ },
19294
+ "Failed to process tool approval"
19295
+ );
19296
+ span.setStatus({ code: 2, message: errorMessage });
19297
+ return c2.json(
19298
+ {
19299
+ error: "Internal server error",
19300
+ message: errorMessage
19301
+ },
19302
+ 500
19303
+ );
19304
+ } finally {
19305
+ span.end();
19306
+ }
19307
+ });
19308
+ });
19206
19309
  var chatDataStream_default = app3;
19207
19310
 
19208
19311
  // src/routes/mcp.ts
@@ -19285,7 +19388,8 @@ var validateSession = async (req, res, body2, tenantId, projectId, agentId) => {
19285
19388
  })
19286
19389
  );
19287
19390
  return false;
19288
- } else if (Array.isArray(sessionId)) {
19391
+ }
19392
+ if (Array.isArray(sessionId)) {
19289
19393
  res.writeHead(400).end(
19290
19394
  JSON.stringify({
19291
19395
  jsonrpc: "2.0",
@@ -19708,16 +19812,15 @@ app4.openapi(
19708
19812
  c2,
19709
19813
  credentialStores
19710
19814
  );
19711
- } else {
19712
- return await handleExistingSessionRequest(
19713
- body2,
19714
- executionContext,
19715
- validatedContext,
19716
- req,
19717
- res,
19718
- credentialStores
19719
- );
19720
19815
  }
19816
+ return await handleExistingSessionRequest(
19817
+ body2,
19818
+ executionContext,
19819
+ validatedContext,
19820
+ req,
19821
+ res,
19822
+ credentialStores
19823
+ );
19721
19824
  } catch (e) {
19722
19825
  logger27.error(
19723
19826
  {