@inkeep/agents-run-api 0.36.1 → 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(),
@@ -103,6 +98,7 @@ var init_env = __esm({
103
98
  GOOGLE_GENERATIVE_AI_API_KEY: z8.z.string().optional(),
104
99
  INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z8.z.string().optional(),
105
100
  INKEEP_AGENTS_JWT_SIGNING_SECRET: z8.z.string().optional(),
101
+ INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY: z8.z.string().optional(),
106
102
  OTEL_BSP_SCHEDULE_DELAY: z8.z.coerce.number().optional().default(500),
107
103
  OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z8.z.coerce.number().optional().default(64)
108
104
  });
@@ -6740,10 +6736,9 @@ var init_NativeSandboxExecutor = __esm({
6740
6736
  "Reusing cached sandbox"
6741
6737
  );
6742
6738
  return sandbox.sandboxDir;
6743
- } else {
6744
- this.cleanupSandbox(sandbox.sandboxDir);
6745
- delete this.sandboxPool[poolKey];
6746
6739
  }
6740
+ this.cleanupSandbox(sandbox.sandboxDir);
6741
+ delete this.sandboxPool[poolKey];
6747
6742
  }
6748
6743
  return null;
6749
6744
  }
@@ -7643,6 +7638,31 @@ function createExecutionContext(params) {
7643
7638
 
7644
7639
  // src/middleware/api-key-auth.ts
7645
7640
  var logger2 = agentsCore.getLogger("env-key-auth");
7641
+ async function tryAuthenticateWithTempJwt(apiKey, baseUrl, subAgentId) {
7642
+ if (!apiKey.startsWith("eyJ") || !env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY) {
7643
+ return null;
7644
+ }
7645
+ try {
7646
+ const publicKeyPem = Buffer.from(env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY, "base64").toString(
7647
+ "utf-8"
7648
+ );
7649
+ const payload = await agentsCore.verifyTempToken(publicKeyPem, apiKey);
7650
+ logger2.info({}, "JWT temp token authenticated successfully");
7651
+ return createExecutionContext({
7652
+ apiKey,
7653
+ tenantId: payload.tenantId,
7654
+ projectId: payload.projectId,
7655
+ agentId: payload.agentId,
7656
+ apiKeyId: "temp-jwt",
7657
+ baseUrl,
7658
+ subAgentId,
7659
+ metadata: { initiatedBy: payload.initiatedBy }
7660
+ });
7661
+ } catch (error) {
7662
+ logger2.debug({ error }, "JWT verification failed");
7663
+ return null;
7664
+ }
7665
+ }
7646
7666
  var apiKeyAuth = () => factory.createMiddleware(async (c2, next) => {
7647
7667
  if (c2.req.method === "OPTIONS") {
7648
7668
  await next();
@@ -7663,6 +7683,12 @@ var apiKeyAuth = () => factory.createMiddleware(async (c2, next) => {
7663
7683
  let executionContext;
7664
7684
  if (authHeader?.startsWith("Bearer ")) {
7665
7685
  const apiKey2 = authHeader.substring(7);
7686
+ const jwtContext2 = await tryAuthenticateWithTempJwt(apiKey2, baseUrl, subAgentId);
7687
+ if (jwtContext2) {
7688
+ c2.set("executionContext", jwtContext2);
7689
+ await next();
7690
+ return;
7691
+ }
7666
7692
  try {
7667
7693
  executionContext = await extractContextFromApiKey(apiKey2, baseUrl);
7668
7694
  if (subAgentId) {
@@ -7715,6 +7741,12 @@ var apiKeyAuth = () => factory.createMiddleware(async (c2, next) => {
7715
7741
  });
7716
7742
  }
7717
7743
  const apiKey = authHeader.substring(7);
7744
+ const jwtContext = await tryAuthenticateWithTempJwt(apiKey, baseUrl, subAgentId);
7745
+ if (jwtContext) {
7746
+ c2.set("executionContext", jwtContext);
7747
+ await next();
7748
+ return;
7749
+ }
7718
7750
  if (env.INKEEP_AGENTS_RUN_API_BYPASS_SECRET) {
7719
7751
  if (apiKey === env.INKEEP_AGENTS_RUN_API_BYPASS_SECRET) {
7720
7752
  if (!tenantId || !projectId || !agentId) {
@@ -7735,7 +7767,8 @@ var apiKeyAuth = () => factory.createMiddleware(async (c2, next) => {
7735
7767
  logger2.info({}, "Bypass secret authenticated successfully");
7736
7768
  await next();
7737
7769
  return;
7738
- } else if (apiKey) {
7770
+ }
7771
+ if (apiKey) {
7739
7772
  try {
7740
7773
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
7741
7774
  if (subAgentId) {
@@ -7753,11 +7786,10 @@ var apiKeyAuth = () => factory.createMiddleware(async (c2, next) => {
7753
7786
  }
7754
7787
  await next();
7755
7788
  return;
7756
- } else {
7757
- throw new httpException.HTTPException(401, {
7758
- message: "Invalid Token"
7759
- });
7760
7789
  }
7790
+ throw new httpException.HTTPException(401, {
7791
+ message: "Invalid Token"
7792
+ });
7761
7793
  }
7762
7794
  if (!apiKey || apiKey.length < 16) {
7763
7795
  throw new httpException.HTTPException(401, {
@@ -7906,6 +7938,19 @@ function setupOpenAPIRoutes(app6) {
7906
7938
  }
7907
7939
  ]
7908
7940
  });
7941
+ document2.components = {
7942
+ ...document2.components,
7943
+ securitySchemes: {
7944
+ ...document2.components?.securitySchemes || {},
7945
+ bearerAuth: {
7946
+ type: "http",
7947
+ scheme: "bearer",
7948
+ bearerFormat: "API Key",
7949
+ description: 'API key authentication. All endpoints require a valid API key in the Authorization header as "Bearer <api-key>". API keys can be created in the management UI.'
7950
+ }
7951
+ }
7952
+ };
7953
+ document2.security = [{ bearerAuth: [] }];
7909
7954
  return c2.json(document2);
7910
7955
  } catch (error) {
7911
7956
  console.error("OpenAPI document generation failed:", error);
@@ -8537,275 +8582,10 @@ async function handleTasksResubscribe(c2, agent, request) {
8537
8582
  init_dbClient();
8538
8583
  init_logger();
8539
8584
 
8540
- // src/agents/ModelFactory.ts
8541
- init_logger();
8542
- var logger4 = agentsCore.getLogger("ModelFactory");
8543
- var nimDefault = openaiCompatible.createOpenAICompatible({
8544
- name: "nim",
8545
- baseURL: "https://integrate.api.nvidia.com/v1",
8546
- headers: {
8547
- Authorization: `Bearer ${process.env.NIM_API_KEY}`
8548
- }
8549
- });
8550
- var ModelFactory = class _ModelFactory {
8551
- /**
8552
- * Create a provider instance with custom configuration
8553
- */
8554
- static createProvider(provider, config) {
8555
- switch (provider) {
8556
- case "anthropic":
8557
- return anthropic.createAnthropic(config);
8558
- case "openai":
8559
- return openai.createOpenAI(config);
8560
- case "google":
8561
- return google.createGoogleGenerativeAI(config);
8562
- case "openrouter":
8563
- return {
8564
- ...aiSdkProvider.createOpenRouter(config),
8565
- textEmbeddingModel: () => {
8566
- throw new Error("OpenRouter does not support text embeddings");
8567
- },
8568
- imageModel: () => {
8569
- throw new Error("OpenRouter does not support image generation");
8570
- }
8571
- };
8572
- case "gateway":
8573
- return gateway.createGateway(config);
8574
- case "nim": {
8575
- const nimConfig = {
8576
- name: "nim",
8577
- baseURL: "https://integrate.api.nvidia.com/v1",
8578
- headers: {
8579
- Authorization: `Bearer ${process.env.NIM_API_KEY}`
8580
- },
8581
- ...config
8582
- };
8583
- return openaiCompatible.createOpenAICompatible(nimConfig);
8584
- }
8585
- case "custom": {
8586
- if (!config.baseURL && !config.baseUrl) {
8587
- throw new Error(
8588
- "Custom provider requires baseURL. Please provide it in providerOptions.baseURL or providerOptions.baseUrl"
8589
- );
8590
- }
8591
- const customConfig = {
8592
- name: "custom",
8593
- baseURL: config.baseURL || config.baseUrl,
8594
- headers: {
8595
- ...process.env.CUSTOM_LLM_API_KEY && {
8596
- Authorization: `Bearer ${process.env.CUSTOM_LLM_API_KEY}`
8597
- },
8598
- ...config.headers || {}
8599
- },
8600
- ...config
8601
- };
8602
- logger4.info(
8603
- {
8604
- config: {
8605
- baseURL: customConfig.baseURL,
8606
- hasApiKey: !!process.env.CUSTOM_LLM_API_KEY,
8607
- apiKeyPrefix: process.env.CUSTOM_LLM_API_KEY?.substring(0, 10) + "...",
8608
- headers: Object.keys(customConfig.headers || {})
8609
- }
8610
- },
8611
- "Creating custom OpenAI-compatible provider"
8612
- );
8613
- return openaiCompatible.createOpenAICompatible(customConfig);
8614
- }
8615
- default:
8616
- throw new Error(`Unsupported provider: ${provider}`);
8617
- }
8618
- }
8619
- /**
8620
- * Extract provider configuration from providerOptions
8621
- * Only includes settings that go to the provider constructor (baseURL, apiKey, etc.)
8622
- */
8623
- static extractProviderConfig(providerOptions) {
8624
- if (!providerOptions) {
8625
- return {};
8626
- }
8627
- const providerConfig = {};
8628
- if (providerOptions.baseUrl || providerOptions.baseURL) {
8629
- providerConfig.baseURL = providerOptions.baseUrl || providerOptions.baseURL;
8630
- }
8631
- if (providerOptions.headers) {
8632
- providerConfig.headers = providerOptions.headers;
8633
- }
8634
- if (providerOptions.gateway) {
8635
- Object.assign(providerConfig, providerOptions.gateway);
8636
- }
8637
- if (providerOptions.nim) {
8638
- Object.assign(providerConfig, providerOptions.nim);
8639
- }
8640
- if (providerOptions.custom) {
8641
- Object.assign(providerConfig, providerOptions.custom);
8642
- }
8643
- return providerConfig;
8644
- }
8645
- /**
8646
- * Create a language model instance from configuration
8647
- * Throws error if no config provided - models must be configured at project level
8648
- */
8649
- static createModel(config) {
8650
- if (!config?.model?.trim()) {
8651
- throw new Error(
8652
- "Model configuration is required. Please configure models at the project level."
8653
- );
8654
- }
8655
- const modelSettings = config;
8656
- if (!modelSettings.model) {
8657
- throw new Error("Model configuration is required");
8658
- }
8659
- const modelString = modelSettings.model.trim();
8660
- const { provider, modelName } = _ModelFactory.parseModelString(modelString);
8661
- logger4.debug(
8662
- {
8663
- provider,
8664
- model: modelName,
8665
- fullModelString: modelSettings.model,
8666
- hasProviderOptions: !!modelSettings.providerOptions
8667
- },
8668
- "Creating language model from config"
8669
- );
8670
- const providerConfig = _ModelFactory.extractProviderConfig(modelSettings.providerOptions);
8671
- if (Object.keys(providerConfig).length > 0) {
8672
- logger4.info({ config: providerConfig }, `Applying custom ${provider} provider configuration`);
8673
- const customProvider = _ModelFactory.createProvider(provider, providerConfig);
8674
- return customProvider.languageModel(modelName);
8675
- }
8676
- switch (provider) {
8677
- case "anthropic":
8678
- return anthropic.anthropic(modelName);
8679
- case "openai":
8680
- return openai.openai(modelName);
8681
- case "google":
8682
- return google.google(modelName);
8683
- case "openrouter":
8684
- return aiSdkProvider.openrouter(modelName);
8685
- case "gateway":
8686
- return gateway.gateway(modelName);
8687
- case "nim":
8688
- return nimDefault(modelName);
8689
- case "custom":
8690
- throw new Error(
8691
- "Custom provider requires configuration. Please provide baseURL in providerOptions.custom.baseURL or providerOptions.baseURL"
8692
- );
8693
- default:
8694
- throw new Error(
8695
- `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).`
8696
- );
8697
- }
8698
- }
8699
- /**
8700
- * Built-in providers that have special handling
8701
- */
8702
- static BUILT_IN_PROVIDERS = [
8703
- "anthropic",
8704
- "openai",
8705
- "google",
8706
- "openrouter",
8707
- "gateway",
8708
- "nim",
8709
- "custom"
8710
- ];
8711
- /**
8712
- * Parse model string to extract provider and model name
8713
- * Examples: "anthropic/claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" }
8714
- * "openrouter/anthropic/claude-sonnet-4" -> { provider: "openrouter", modelName: "anthropic/claude-sonnet-4" }
8715
- * "claude-sonnet-4" -> { provider: "anthropic", modelName: "claude-sonnet-4" } (default to anthropic)
8716
- */
8717
- static parseModelString(modelString) {
8718
- if (modelString.includes("/")) {
8719
- const [provider, ...modelParts] = modelString.split("/");
8720
- const normalizedProvider = provider.toLowerCase();
8721
- if (!_ModelFactory.BUILT_IN_PROVIDERS.includes(normalizedProvider)) {
8722
- throw new Error(
8723
- `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).`
8724
- );
8725
- }
8726
- return {
8727
- provider: normalizedProvider,
8728
- modelName: modelParts.join("/")
8729
- // In case model name has slashes
8730
- };
8731
- }
8732
- throw new Error(`No provider specified in model string: ${modelString}`);
8733
- }
8734
- /**
8735
- * Get generation parameters from provider options
8736
- * These are parameters that get passed to generateText/streamText calls
8737
- */
8738
- static getGenerationParams(providerOptions) {
8739
- if (!providerOptions) {
8740
- return {};
8741
- }
8742
- const excludedKeys = [
8743
- "apiKey",
8744
- "baseURL",
8745
- "baseUrl",
8746
- "maxDuration",
8747
- "headers",
8748
- "gateway",
8749
- "nim",
8750
- "custom"
8751
- ];
8752
- const params = {};
8753
- for (const [key, value] of Object.entries(providerOptions)) {
8754
- if (!excludedKeys.includes(key) && value !== void 0) {
8755
- params[key] = value;
8756
- }
8757
- }
8758
- return params;
8759
- }
8760
- /**
8761
- * Prepare complete generation configuration from model settings
8762
- * Returns model instance and generation parameters ready to spread into generateText/streamText
8763
- * Includes maxDuration if specified in provider options (in seconds, following Vercel standard)
8764
- */
8765
- static prepareGenerationConfig(modelSettings) {
8766
- const modelString = modelSettings?.model?.trim();
8767
- const model = _ModelFactory.createModel({
8768
- model: modelString,
8769
- providerOptions: modelSettings?.providerOptions
8770
- });
8771
- const generationParams = _ModelFactory.getGenerationParams(modelSettings?.providerOptions);
8772
- const maxDuration = modelSettings?.providerOptions?.maxDuration;
8773
- return {
8774
- model,
8775
- ...generationParams,
8776
- ...maxDuration !== void 0 && { maxDuration }
8777
- };
8778
- }
8779
- /**
8780
- * Validate model settingsuration
8781
- * Basic validation only - let AI SDK handle parameter-specific validation
8782
- */
8783
- static validateConfig(config) {
8784
- const errors = [];
8785
- if (!config.model) {
8786
- errors.push("Model name is required");
8787
- }
8788
- if (config.providerOptions) {
8789
- if (config.providerOptions.apiKey) {
8790
- errors.push(
8791
- "API keys should not be stored in provider options. Use environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY) or credential store instead."
8792
- );
8793
- }
8794
- if (config.providerOptions.maxDuration !== void 0) {
8795
- const maxDuration = config.providerOptions.maxDuration;
8796
- if (typeof maxDuration !== "number" || maxDuration <= 0) {
8797
- errors.push("maxDuration must be a positive number (in seconds)");
8798
- }
8799
- }
8800
- }
8801
- return errors;
8802
- }
8803
- };
8804
-
8805
8585
  // src/agents/ToolSessionManager.ts
8806
8586
  init_execution_limits();
8807
8587
  init_logger();
8808
- var logger5 = agentsCore.getLogger("ToolSessionManager");
8588
+ var logger4 = agentsCore.getLogger("ToolSessionManager");
8809
8589
  var ToolSessionManager = class _ToolSessionManager {
8810
8590
  static instance;
8811
8591
  sessions = /* @__PURE__ */ new Map();
@@ -8839,7 +8619,7 @@ var ToolSessionManager = class _ToolSessionManager {
8839
8619
  createdAt: Date.now()
8840
8620
  };
8841
8621
  this.sessions.set(sessionId, session);
8842
- logger5.debug(
8622
+ logger4.debug(
8843
8623
  {
8844
8624
  sessionId,
8845
8625
  tenantId,
@@ -8857,10 +8637,10 @@ var ToolSessionManager = class _ToolSessionManager {
8857
8637
  */
8858
8638
  ensureAgentSession(sessionId, tenantId, projectId, contextId, taskId) {
8859
8639
  if (this.sessions.has(sessionId)) {
8860
- logger5.debug({ sessionId }, "Agent session already exists, reusing");
8640
+ logger4.debug({ sessionId }, "Agent session already exists, reusing");
8861
8641
  return sessionId;
8862
8642
  }
8863
- logger5.debug(
8643
+ logger4.debug(
8864
8644
  { sessionId, tenantId, contextId, taskId },
8865
8645
  "Creating new agent-scoped tool session"
8866
8646
  );
@@ -8872,7 +8652,7 @@ var ToolSessionManager = class _ToolSessionManager {
8872
8652
  recordToolResult(sessionId, toolResult) {
8873
8653
  const session = this.sessions.get(sessionId);
8874
8654
  if (!session) {
8875
- logger5.warn(
8655
+ logger4.warn(
8876
8656
  {
8877
8657
  sessionId,
8878
8658
  toolCallId: toolResult.toolCallId,
@@ -8884,7 +8664,7 @@ var ToolSessionManager = class _ToolSessionManager {
8884
8664
  return;
8885
8665
  }
8886
8666
  session.toolResults.set(toolResult.toolCallId, toolResult);
8887
- logger5.debug(
8667
+ logger4.debug(
8888
8668
  {
8889
8669
  sessionId,
8890
8670
  toolCallId: toolResult.toolCallId,
@@ -8899,7 +8679,7 @@ var ToolSessionManager = class _ToolSessionManager {
8899
8679
  getToolResult(sessionId, toolCallId) {
8900
8680
  const session = this.sessions.get(sessionId);
8901
8681
  if (!session) {
8902
- logger5.warn(
8682
+ logger4.warn(
8903
8683
  {
8904
8684
  sessionId,
8905
8685
  toolCallId,
@@ -8912,7 +8692,7 @@ var ToolSessionManager = class _ToolSessionManager {
8912
8692
  }
8913
8693
  const result = session.toolResults.get(toolCallId);
8914
8694
  if (!result) {
8915
- logger5.warn(
8695
+ logger4.warn(
8916
8696
  {
8917
8697
  sessionId,
8918
8698
  toolCallId,
@@ -8922,7 +8702,7 @@ var ToolSessionManager = class _ToolSessionManager {
8922
8702
  "Tool result not found"
8923
8703
  );
8924
8704
  } else {
8925
- logger5.debug(
8705
+ logger4.debug(
8926
8706
  {
8927
8707
  sessionId,
8928
8708
  toolCallId,
@@ -8961,10 +8741,10 @@ var ToolSessionManager = class _ToolSessionManager {
8961
8741
  }
8962
8742
  for (const sessionId of expiredSessions) {
8963
8743
  this.sessions.delete(sessionId);
8964
- logger5.debug({ sessionId }, "Cleaned up expired tool session");
8744
+ logger4.debug({ sessionId }, "Cleaned up expired tool session");
8965
8745
  }
8966
8746
  if (expiredSessions.length > 0) {
8967
- logger5.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
8747
+ logger4.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
8968
8748
  }
8969
8749
  }
8970
8750
  };
@@ -9046,7 +8826,7 @@ function extractFullFields(schema2) {
9046
8826
  }
9047
8827
 
9048
8828
  // src/services/ArtifactService.ts
9049
- var logger7 = agentsCore.getLogger("ArtifactService");
8829
+ var logger6 = agentsCore.getLogger("ArtifactService");
9050
8830
  var ArtifactService = class _ArtifactService {
9051
8831
  constructor(context) {
9052
8832
  this.context = context;
@@ -9079,7 +8859,7 @@ var ArtifactService = class _ArtifactService {
9079
8859
  id: taskId
9080
8860
  });
9081
8861
  if (!task) {
9082
- logger7.warn({ taskId }, "Task not found when fetching artifacts");
8862
+ logger6.warn({ taskId }, "Task not found when fetching artifacts");
9083
8863
  continue;
9084
8864
  }
9085
8865
  const taskArtifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
@@ -9097,7 +8877,7 @@ var ArtifactService = class _ArtifactService {
9097
8877
  }
9098
8878
  }
9099
8879
  } catch (error) {
9100
- logger7.error({ error, contextId }, "Error loading context artifacts");
8880
+ logger6.error({ error, contextId }, "Error loading context artifacts");
9101
8881
  }
9102
8882
  return artifacts;
9103
8883
  }
@@ -9106,12 +8886,12 @@ var ArtifactService = class _ArtifactService {
9106
8886
  */
9107
8887
  async createArtifact(request, subAgentId) {
9108
8888
  if (!this.context.sessionId) {
9109
- logger7.warn({ request }, "No session ID available for artifact creation");
8889
+ logger6.warn({ request }, "No session ID available for artifact creation");
9110
8890
  return null;
9111
8891
  }
9112
8892
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
9113
8893
  if (!toolResult) {
9114
- logger7.warn(
8894
+ logger6.warn(
9115
8895
  { request, sessionId: this.context.sessionId },
9116
8896
  "Tool result not found for artifact"
9117
8897
  );
@@ -9127,7 +8907,7 @@ var ArtifactService = class _ArtifactService {
9127
8907
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
9128
8908
  }
9129
8909
  if (!selectedData) {
9130
- logger7.warn(
8910
+ logger6.warn(
9131
8911
  {
9132
8912
  request,
9133
8913
  baseSelector: request.baseSelector
@@ -9198,7 +8978,7 @@ var ArtifactService = class _ArtifactService {
9198
8978
  );
9199
8979
  return artifactData;
9200
8980
  } catch (error) {
9201
- logger7.error({ error, request }, "Failed to create artifact");
8981
+ logger6.error({ error, request }, "Failed to create artifact");
9202
8982
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
9203
8983
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
9204
8984
  }
@@ -9227,7 +9007,7 @@ var ArtifactService = class _ArtifactService {
9227
9007
  }
9228
9008
  try {
9229
9009
  if (!this.context.projectId || !this.context.taskId) {
9230
- logger7.warn(
9010
+ logger6.warn(
9231
9011
  { artifactId, toolCallId },
9232
9012
  "No projectId or taskId available for artifact lookup"
9233
9013
  );
@@ -9251,7 +9031,7 @@ var ArtifactService = class _ArtifactService {
9251
9031
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
9252
9032
  }
9253
9033
  } catch (error) {
9254
- logger7.warn(
9034
+ logger6.warn(
9255
9035
  { artifactId, toolCallId, taskId: this.context.taskId, error },
9256
9036
  "Failed to fetch artifact"
9257
9037
  );
@@ -9282,7 +9062,7 @@ var ArtifactService = class _ArtifactService {
9282
9062
  }
9283
9063
  try {
9284
9064
  if (!this.context.projectId || !this.context.taskId) {
9285
- logger7.warn(
9065
+ logger6.warn(
9286
9066
  { artifactId, toolCallId },
9287
9067
  "No projectId or taskId available for artifact lookup"
9288
9068
  );
@@ -9306,7 +9086,7 @@ var ArtifactService = class _ArtifactService {
9306
9086
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
9307
9087
  }
9308
9088
  } catch (error) {
9309
- logger7.warn(
9089
+ logger6.warn(
9310
9090
  { artifactId, toolCallId, taskId: this.context.taskId, error },
9311
9091
  "Failed to fetch artifact"
9312
9092
  );
@@ -9323,7 +9103,7 @@ var ArtifactService = class _ArtifactService {
9323
9103
  data = artifact.parts?.[0]?.data;
9324
9104
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9325
9105
  dataSource = "parts[0].data (fallback)";
9326
- logger7.debug(
9106
+ logger6.debug(
9327
9107
  { artifactId, toolCallId, dataSource },
9328
9108
  "Using fallback data source for artifact summary"
9329
9109
  );
@@ -9331,14 +9111,14 @@ var ArtifactService = class _ArtifactService {
9331
9111
  data = artifact.data;
9332
9112
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9333
9113
  dataSource = "artifact.data (fallback)";
9334
- logger7.debug(
9114
+ logger6.debug(
9335
9115
  { artifactId, toolCallId, dataSource },
9336
9116
  "Using fallback data source for artifact summary"
9337
9117
  );
9338
9118
  } else {
9339
9119
  data = {};
9340
9120
  dataSource = "empty (no data found)";
9341
- logger7.warn(
9121
+ logger6.warn(
9342
9122
  {
9343
9123
  artifactId,
9344
9124
  toolCallId,
@@ -9375,7 +9155,7 @@ var ArtifactService = class _ArtifactService {
9375
9155
  data = artifact.parts?.[0]?.data;
9376
9156
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9377
9157
  dataSource = "parts[0].data (fallback)";
9378
- logger7.debug(
9158
+ logger6.debug(
9379
9159
  { artifactId, toolCallId, dataSource },
9380
9160
  "Using fallback data source for artifact full data"
9381
9161
  );
@@ -9383,14 +9163,14 @@ var ArtifactService = class _ArtifactService {
9383
9163
  data = artifact.data;
9384
9164
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9385
9165
  dataSource = "artifact.data (fallback)";
9386
- logger7.debug(
9166
+ logger6.debug(
9387
9167
  { artifactId, toolCallId, dataSource },
9388
9168
  "Using fallback data source for artifact full data"
9389
9169
  );
9390
9170
  } else {
9391
9171
  data = {};
9392
9172
  dataSource = "empty (no data found)";
9393
- logger7.warn(
9173
+ logger6.warn(
9394
9174
  {
9395
9175
  artifactId,
9396
9176
  toolCallId,
@@ -9444,7 +9224,7 @@ var ArtifactService = class _ArtifactService {
9444
9224
  const error = new Error(
9445
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.`
9446
9226
  );
9447
- logger7.error(
9227
+ logger6.error(
9448
9228
  {
9449
9229
  artifactId,
9450
9230
  artifactType,
@@ -9457,7 +9237,7 @@ var ArtifactService = class _ArtifactService {
9457
9237
  throw error;
9458
9238
  }
9459
9239
  if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) {
9460
- logger7.warn(
9240
+ logger6.warn(
9461
9241
  {
9462
9242
  artifactId,
9463
9243
  artifactType,
@@ -9471,7 +9251,7 @@ var ArtifactService = class _ArtifactService {
9471
9251
  );
9472
9252
  }
9473
9253
  if (!fullValidation.hasExpectedFields || fullValidation.extraFields.length > 0) {
9474
- logger7.warn(
9254
+ logger6.warn(
9475
9255
  {
9476
9256
  artifactId,
9477
9257
  artifactType,
@@ -9543,7 +9323,7 @@ var ArtifactService = class _ArtifactService {
9543
9323
  }
9544
9324
  );
9545
9325
  } else {
9546
- logger7.warn(
9326
+ logger6.warn(
9547
9327
  {
9548
9328
  artifactId: request.artifactId,
9549
9329
  hasStreamRequestId: !!this.context.streamRequestId,
@@ -9618,7 +9398,7 @@ var ArtifactService = class _ArtifactService {
9618
9398
  summaryData = this.filterBySchema(artifact.data, previewSchema);
9619
9399
  fullData = this.filterBySchema(artifact.data, fullSchema);
9620
9400
  } catch (error) {
9621
- logger7.warn(
9401
+ logger6.warn(
9622
9402
  {
9623
9403
  artifactType: artifact.type,
9624
9404
  error: error instanceof Error ? error.message : "Unknown error"
@@ -9656,7 +9436,7 @@ var ArtifactService = class _ArtifactService {
9656
9436
  artifact: artifactToSave
9657
9437
  });
9658
9438
  if (!result.created && result.existing) {
9659
- logger7.debug(
9439
+ logger6.debug(
9660
9440
  {
9661
9441
  artifactId: artifact.artifactId,
9662
9442
  taskId: this.context.taskId
@@ -9716,7 +9496,7 @@ var ArtifactService = class _ArtifactService {
9716
9496
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
9717
9497
  }
9718
9498
  } catch (error) {
9719
- logger7.warn(
9499
+ logger6.warn(
9720
9500
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
9721
9501
  "Failed to extract schema field"
9722
9502
  );
@@ -9745,7 +9525,7 @@ var ArtifactService = class _ArtifactService {
9745
9525
  };
9746
9526
 
9747
9527
  // src/services/ArtifactParser.ts
9748
- var logger8 = agentsCore.getLogger("ArtifactParser");
9528
+ var logger7 = agentsCore.getLogger("ArtifactParser");
9749
9529
  var ArtifactParser = class _ArtifactParser {
9750
9530
  static ARTIFACT_CHECK_REGEX = /<artifact:ref\s+(?=.*id=['"][^'"]+['"])(?=.*tool=['"][^'"]+['"])[^>]*\/>/;
9751
9531
  static ATTR_REGEX = /(\w+)="([^"]*)"|(\w+)='([^']*)'|(\w+)=({[^}]+})/g;
@@ -9856,7 +9636,7 @@ var ArtifactParser = class _ArtifactParser {
9856
9636
  attrs[key] = value;
9857
9637
  }
9858
9638
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
9859
- logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
9639
+ logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
9860
9640
  return null;
9861
9641
  }
9862
9642
  return {
@@ -9917,7 +9697,7 @@ var ArtifactParser = class _ArtifactParser {
9917
9697
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
9918
9698
  );
9919
9699
  processedText = processedText.replace(annotation.raw, "");
9920
- logger8.warn(
9700
+ logger7.warn(
9921
9701
  { annotation, artifactData },
9922
9702
  "Removed failed artifact:create annotation from output"
9923
9703
  );
@@ -9928,11 +9708,11 @@ var ArtifactParser = class _ArtifactParser {
9928
9708
  if (annotation.raw) {
9929
9709
  processedText = processedText.replace(annotation.raw, "");
9930
9710
  }
9931
- logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
9711
+ logger7.error({ annotation, error }, "Failed to extract artifact from create annotation");
9932
9712
  }
9933
9713
  }
9934
9714
  if (failedAnnotations.length > 0) {
9935
- logger8.warn(
9715
+ logger7.warn(
9936
9716
  {
9937
9717
  failedCount: failedAnnotations.length,
9938
9718
  failures: failedAnnotations
@@ -10116,7 +9896,7 @@ var ArtifactParser = class _ArtifactParser {
10116
9896
  };
10117
9897
 
10118
9898
  // src/services/AgentSession.ts
10119
- var logger9 = agentsCore.getLogger("AgentSession");
9899
+ var logger8 = agentsCore.getLogger("AgentSession");
10120
9900
  var AgentSession = class {
10121
9901
  // Whether to send data operations
10122
9902
  constructor(sessionId, messageId, agentId, tenantId, projectId, contextId) {
@@ -10126,7 +9906,7 @@ var AgentSession = class {
10126
9906
  this.tenantId = tenantId;
10127
9907
  this.projectId = projectId;
10128
9908
  this.contextId = contextId;
10129
- logger9.debug({ sessionId, messageId, agentId }, "AgentSession created");
9909
+ logger8.debug({ sessionId, messageId, agentId }, "AgentSession created");
10130
9910
  if (tenantId && projectId) {
10131
9911
  toolSessionManager.createSessionWithId(
10132
9912
  sessionId,
@@ -10183,7 +9963,7 @@ var AgentSession = class {
10183
9963
  */
10184
9964
  enableEmitOperations() {
10185
9965
  this.isEmitOperations = true;
10186
- logger9.info(
9966
+ logger8.info(
10187
9967
  { sessionId: this.sessionId },
10188
9968
  "\u{1F50D} DEBUG: Emit operations enabled for AgentSession"
10189
9969
  );
@@ -10192,6 +9972,7 @@ var AgentSession = class {
10192
9972
  * Send data operation to stream when emit operations is enabled
10193
9973
  */
10194
9974
  async sendDataOperation(event) {
9975
+ console.log("sendDataOperation called with event", Date.now());
10195
9976
  try {
10196
9977
  const streamHelper = getStreamHelper(this.sessionId);
10197
9978
  if (streamHelper) {
@@ -10207,7 +9988,7 @@ var AgentSession = class {
10207
9988
  await streamHelper.writeOperation(formattedOperation);
10208
9989
  }
10209
9990
  } catch (error) {
10210
- logger9.error(
9991
+ logger8.error(
10211
9992
  {
10212
9993
  sessionId: this.sessionId,
10213
9994
  eventType: event.eventType,
@@ -10266,7 +10047,7 @@ var AgentSession = class {
10266
10047
  if (this.statusUpdateState.config.timeInSeconds) {
10267
10048
  this.statusUpdateTimer = setInterval(async () => {
10268
10049
  if (!this.statusUpdateState || this.isEnded) {
10269
- logger9.debug(
10050
+ logger8.debug(
10270
10051
  { sessionId: this.sessionId },
10271
10052
  "Timer triggered but session already cleaned up or ended"
10272
10053
  );
@@ -10278,7 +10059,7 @@ var AgentSession = class {
10278
10059
  }
10279
10060
  await this.checkAndSendTimeBasedUpdate();
10280
10061
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
10281
- logger9.info(
10062
+ logger8.info(
10282
10063
  {
10283
10064
  sessionId: this.sessionId,
10284
10065
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -10302,7 +10083,7 @@ var AgentSession = class {
10302
10083
  this.sendDataOperation(dataOpEvent);
10303
10084
  }
10304
10085
  if (this.isEnded) {
10305
- logger9.debug(
10086
+ logger8.debug(
10306
10087
  {
10307
10088
  sessionId: this.sessionId,
10308
10089
  eventType,
@@ -10324,7 +10105,7 @@ var AgentSession = class {
10324
10105
  if (artifactData.pendingGeneration) {
10325
10106
  const artifactId = artifactData.artifactId;
10326
10107
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
10327
- logger9.warn(
10108
+ logger8.warn(
10328
10109
  {
10329
10110
  sessionId: this.sessionId,
10330
10111
  artifactId,
@@ -10346,7 +10127,7 @@ var AgentSession = class {
10346
10127
  this.artifactProcessingErrors.set(artifactId, errorCount);
10347
10128
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
10348
10129
  this.pendingArtifacts.delete(artifactId);
10349
- logger9.error(
10130
+ logger8.error(
10350
10131
  {
10351
10132
  sessionId: this.sessionId,
10352
10133
  artifactId,
@@ -10358,7 +10139,7 @@ var AgentSession = class {
10358
10139
  "Artifact processing failed after max retries, giving up"
10359
10140
  );
10360
10141
  } else {
10361
- logger9.warn(
10142
+ logger8.warn(
10362
10143
  {
10363
10144
  sessionId: this.sessionId,
10364
10145
  artifactId,
@@ -10381,14 +10162,14 @@ var AgentSession = class {
10381
10162
  */
10382
10163
  checkStatusUpdates() {
10383
10164
  if (this.isEnded) {
10384
- logger9.debug(
10165
+ logger8.debug(
10385
10166
  { sessionId: this.sessionId },
10386
10167
  "Session has ended - skipping status update check"
10387
10168
  );
10388
10169
  return;
10389
10170
  }
10390
10171
  if (!this.statusUpdateState) {
10391
- logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
10172
+ logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
10392
10173
  return;
10393
10174
  }
10394
10175
  const statusUpdateState = this.statusUpdateState;
@@ -10399,11 +10180,11 @@ var AgentSession = class {
10399
10180
  */
10400
10181
  async checkAndSendTimeBasedUpdate() {
10401
10182
  if (this.isEnded) {
10402
- 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");
10403
10184
  return;
10404
10185
  }
10405
10186
  if (!this.statusUpdateState) {
10406
- logger9.debug(
10187
+ logger8.debug(
10407
10188
  { sessionId: this.sessionId },
10408
10189
  "No status updates configured for time-based check"
10409
10190
  );
@@ -10416,7 +10197,7 @@ var AgentSession = class {
10416
10197
  try {
10417
10198
  await this.generateAndSendUpdate();
10418
10199
  } catch (error) {
10419
- logger9.error(
10200
+ logger8.error(
10420
10201
  {
10421
10202
  sessionId: this.sessionId,
10422
10203
  error: error instanceof Error ? error.message : "Unknown error"
@@ -10519,29 +10300,29 @@ var AgentSession = class {
10519
10300
  */
10520
10301
  async generateAndSendUpdate() {
10521
10302
  if (this.isEnded) {
10522
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
10303
+ logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
10523
10304
  return;
10524
10305
  }
10525
10306
  if (this.isTextStreaming) {
10526
- logger9.debug(
10307
+ logger8.debug(
10527
10308
  { sessionId: this.sessionId },
10528
10309
  "Text is currently streaming - skipping status update"
10529
10310
  );
10530
10311
  return;
10531
10312
  }
10532
10313
  if (this.isGeneratingUpdate) {
10533
- logger9.debug(
10314
+ logger8.debug(
10534
10315
  { sessionId: this.sessionId },
10535
10316
  "Update already in progress - skipping duplicate generation"
10536
10317
  );
10537
10318
  return;
10538
10319
  }
10539
10320
  if (!this.statusUpdateState) {
10540
- 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");
10541
10322
  return;
10542
10323
  }
10543
10324
  if (!this.agentId) {
10544
- logger9.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
10325
+ logger8.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
10545
10326
  return;
10546
10327
  }
10547
10328
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -10553,7 +10334,7 @@ var AgentSession = class {
10553
10334
  try {
10554
10335
  const streamHelper = getStreamHelper(this.sessionId);
10555
10336
  if (!streamHelper) {
10556
- logger9.warn(
10337
+ logger8.warn(
10557
10338
  { sessionId: this.sessionId },
10558
10339
  "No stream helper found - cannot send status update"
10559
10340
  );
@@ -10573,7 +10354,7 @@ var AgentSession = class {
10573
10354
  if (result.summaries && result.summaries.length > 0) {
10574
10355
  for (const summary of result.summaries) {
10575
10356
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
10576
- logger9.warn(
10357
+ logger8.warn(
10577
10358
  {
10578
10359
  sessionId: this.sessionId,
10579
10360
  summary
@@ -10610,7 +10391,7 @@ var AgentSession = class {
10610
10391
  this.statusUpdateState.lastEventCount = this.events.length;
10611
10392
  }
10612
10393
  } catch (error) {
10613
- logger9.error(
10394
+ logger8.error(
10614
10395
  {
10615
10396
  sessionId: this.sessionId,
10616
10397
  error: error instanceof Error ? error.message : "Unknown error",
@@ -10648,7 +10429,7 @@ var AgentSession = class {
10648
10429
  this.releaseUpdateLock();
10649
10430
  }
10650
10431
  } catch (error) {
10651
- logger9.error(
10432
+ logger8.error(
10652
10433
  {
10653
10434
  sessionId: this.sessionId,
10654
10435
  error: error instanceof Error ? error.message : "Unknown error"
@@ -10727,7 +10508,7 @@ User's Question/Context:
10727
10508
  ${conversationHistory}
10728
10509
  ` : "";
10729
10510
  } catch (error) {
10730
- logger9.warn(
10511
+ logger8.warn(
10731
10512
  { sessionId: this.sessionId, error },
10732
10513
  "Failed to fetch conversation history for structured status update"
10733
10514
  );
@@ -10821,7 +10602,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10821
10602
  if (!modelToUse) {
10822
10603
  throw new Error("No model configuration available");
10823
10604
  }
10824
- const model = ModelFactory.createModel(modelToUse);
10605
+ const model = agentsCore.ModelFactory.createModel(modelToUse);
10825
10606
  const { object } = await ai.generateObject({
10826
10607
  model,
10827
10608
  prompt,
@@ -10838,10 +10619,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10838
10619
  }
10839
10620
  });
10840
10621
  const result = object;
10841
- logger9.info({ result: JSON.stringify(result) }, "DEBUG: Result");
10622
+ logger8.info({ result: JSON.stringify(result) }, "DEBUG: Result");
10842
10623
  const summaries = [];
10843
10624
  for (const [componentId, data] of Object.entries(result)) {
10844
- logger9.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
10625
+ logger8.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
10845
10626
  if (componentId === "no_relevant_updates") {
10846
10627
  continue;
10847
10628
  }
@@ -10861,7 +10642,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10861
10642
  return { summaries };
10862
10643
  } catch (error) {
10863
10644
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
10864
- logger9.error({ error }, "Failed to generate structured update, using fallback");
10645
+ logger8.error({ error }, "Failed to generate structured update, using fallback");
10865
10646
  return { summaries: [] };
10866
10647
  } finally {
10867
10648
  span.end();
@@ -11133,7 +10914,7 @@ Make it specific and relevant.`;
11133
10914
  });
11134
10915
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
11135
10916
  modelToUse = agentData.models.base;
11136
- logger9.info(
10917
+ logger8.info(
11137
10918
  {
11138
10919
  sessionId: this.sessionId,
11139
10920
  artifactId: artifactData.artifactId,
@@ -11144,7 +10925,7 @@ Make it specific and relevant.`;
11144
10925
  );
11145
10926
  }
11146
10927
  } catch (error) {
11147
- logger9.warn(
10928
+ logger8.warn(
11148
10929
  {
11149
10930
  sessionId: this.sessionId,
11150
10931
  artifactId: artifactData.artifactId,
@@ -11156,7 +10937,7 @@ Make it specific and relevant.`;
11156
10937
  }
11157
10938
  }
11158
10939
  if (!modelToUse?.model?.trim()) {
11159
- logger9.warn(
10940
+ logger8.warn(
11160
10941
  {
11161
10942
  sessionId: this.sessionId,
11162
10943
  artifactId: artifactData.artifactId
@@ -11176,7 +10957,7 @@ Make it specific and relevant.`;
11176
10957
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolCallId || "tool results"}`
11177
10958
  };
11178
10959
  } else {
11179
- const model = ModelFactory.createModel(modelToUse);
10960
+ const model = agentsCore.ModelFactory.createModel(modelToUse);
11180
10961
  const schema2 = z8.z.object({
11181
10962
  name: z8.z.string().describe("Concise, descriptive name for the artifact"),
11182
10963
  description: z8.z.string().describe("Brief description of the artifact's relevance to the user's question")
@@ -11238,7 +11019,7 @@ Make it specific and relevant.`;
11238
11019
  return result2;
11239
11020
  } catch (error) {
11240
11021
  lastError = error instanceof Error ? error : new Error(String(error));
11241
- logger9.warn(
11022
+ logger8.warn(
11242
11023
  {
11243
11024
  sessionId: this.sessionId,
11244
11025
  artifactId: artifactData.artifactId,
@@ -11286,7 +11067,7 @@ Make it specific and relevant.`;
11286
11067
  });
11287
11068
  span.setStatus({ code: api.SpanStatusCode.OK });
11288
11069
  } catch (saveError) {
11289
- logger9.error(
11070
+ logger8.error(
11290
11071
  {
11291
11072
  sessionId: this.sessionId,
11292
11073
  artifactId: artifactData.artifactId,
@@ -11314,7 +11095,7 @@ Make it specific and relevant.`;
11314
11095
  metadata: artifactData.metadata || {},
11315
11096
  toolCallId: artifactData.toolCallId
11316
11097
  });
11317
- logger9.info(
11098
+ logger8.info(
11318
11099
  {
11319
11100
  sessionId: this.sessionId,
11320
11101
  artifactId: artifactData.artifactId
@@ -11325,7 +11106,7 @@ Make it specific and relevant.`;
11325
11106
  } catch (fallbackError) {
11326
11107
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
11327
11108
  if (isDuplicateError) ; else {
11328
- logger9.error(
11109
+ logger8.error(
11329
11110
  {
11330
11111
  sessionId: this.sessionId,
11331
11112
  artifactId: artifactData.artifactId,
@@ -11338,7 +11119,7 @@ Make it specific and relevant.`;
11338
11119
  }
11339
11120
  } catch (error) {
11340
11121
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
11341
- logger9.error(
11122
+ logger8.error(
11342
11123
  {
11343
11124
  sessionId: this.sessionId,
11344
11125
  artifactId: artifactData.artifactId,
@@ -11357,7 +11138,7 @@ Make it specific and relevant.`;
11357
11138
  */
11358
11139
  setArtifactCache(key, artifact) {
11359
11140
  this.artifactCache.set(key, artifact);
11360
- logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
11141
+ logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
11361
11142
  }
11362
11143
  /**
11363
11144
  * Get session-scoped ArtifactService instance
@@ -11376,7 +11157,7 @@ Make it specific and relevant.`;
11376
11157
  */
11377
11158
  getArtifactCache(key) {
11378
11159
  const artifact = this.artifactCache.get(key);
11379
- logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
11160
+ logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
11380
11161
  return artifact || null;
11381
11162
  }
11382
11163
  /**
@@ -11397,7 +11178,7 @@ var AgentSessionManager = class {
11397
11178
  const sessionId = messageId;
11398
11179
  const session = new AgentSession(sessionId, messageId, agentId, tenantId, projectId, contextId);
11399
11180
  this.sessions.set(sessionId, session);
11400
- logger9.info(
11181
+ logger8.info(
11401
11182
  { sessionId, messageId, agentId, tenantId, projectId, contextId },
11402
11183
  "AgentSession created"
11403
11184
  );
@@ -11411,7 +11192,7 @@ var AgentSessionManager = class {
11411
11192
  if (session) {
11412
11193
  session.initializeStatusUpdates(config, summarizerModel, baseModel);
11413
11194
  } else {
11414
- logger9.error(
11195
+ logger8.error(
11415
11196
  {
11416
11197
  sessionId,
11417
11198
  availableSessions: Array.from(this.sessions.keys())
@@ -11428,7 +11209,7 @@ var AgentSessionManager = class {
11428
11209
  if (session) {
11429
11210
  session.enableEmitOperations();
11430
11211
  } else {
11431
- logger9.error(
11212
+ logger8.error(
11432
11213
  {
11433
11214
  sessionId,
11434
11215
  availableSessions: Array.from(this.sessions.keys())
@@ -11450,7 +11231,7 @@ var AgentSessionManager = class {
11450
11231
  recordEvent(sessionId, eventType, subAgentId, data) {
11451
11232
  const session = this.sessions.get(sessionId);
11452
11233
  if (!session) {
11453
- logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
11234
+ logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
11454
11235
  return;
11455
11236
  }
11456
11237
  session.recordEvent(eventType, subAgentId, data);
@@ -11461,12 +11242,12 @@ var AgentSessionManager = class {
11461
11242
  endSession(sessionId) {
11462
11243
  const session = this.sessions.get(sessionId);
11463
11244
  if (!session) {
11464
- logger9.warn({ sessionId }, "Attempted to end non-existent session");
11245
+ logger8.warn({ sessionId }, "Attempted to end non-existent session");
11465
11246
  return [];
11466
11247
  }
11467
11248
  const events = session.getEvents();
11468
11249
  const summary = session.getSummary();
11469
- logger9.info({ sessionId, summary }, "AgentSession ended");
11250
+ logger8.info({ sessionId, summary }, "AgentSession ended");
11470
11251
  session.cleanup();
11471
11252
  this.sessions.delete(sessionId);
11472
11253
  return events;
@@ -11576,7 +11357,7 @@ init_logger();
11576
11357
  // src/services/IncrementalStreamParser.ts
11577
11358
  init_execution_limits();
11578
11359
  init_logger();
11579
- var logger10 = agentsCore.getLogger("IncrementalStreamParser");
11360
+ var logger9 = agentsCore.getLogger("IncrementalStreamParser");
11580
11361
  var IncrementalStreamParser = class _IncrementalStreamParser {
11581
11362
  buffer = "";
11582
11363
  pendingTextBuffer = "";
@@ -11634,7 +11415,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
11634
11415
  async initializeArtifactMap() {
11635
11416
  try {
11636
11417
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
11637
- logger10.debug(
11418
+ logger9.debug(
11638
11419
  {
11639
11420
  contextId: this.contextId,
11640
11421
  artifactMapSize: this.artifactMap.size
@@ -11642,7 +11423,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
11642
11423
  "Initialized artifact map for streaming"
11643
11424
  );
11644
11425
  } catch (error) {
11645
- logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
11426
+ logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
11646
11427
  this.artifactMap = /* @__PURE__ */ new Map();
11647
11428
  }
11648
11429
  }
@@ -11975,6 +11756,143 @@ ${chunk}`;
11975
11756
  }
11976
11757
  };
11977
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
+
11978
11896
  // src/services/ResponseFormatter.ts
11979
11897
  init_logger();
11980
11898
  var logger11 = agentsCore.getLogger("ResponseFormatter");
@@ -14796,7 +14714,7 @@ var Agent = class {
14796
14714
  /**
14797
14715
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
14798
14716
  */
14799
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId) {
14717
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId, options) {
14800
14718
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
14801
14719
  return toolDefinition;
14802
14720
  }
@@ -14818,13 +14736,24 @@ var Agent = class {
14818
14736
  });
14819
14737
  }
14820
14738
  const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
14739
+ const needsApproval = options?.needsApproval || false;
14821
14740
  if (streamRequestId && !isInternalTool) {
14822
- agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
14741
+ const toolCallData = {
14823
14742
  toolName,
14824
14743
  input: args2,
14825
14744
  toolCallId,
14826
14745
  relationshipId
14827
- });
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
+ );
14828
14757
  }
14829
14758
  try {
14830
14759
  const result = await originalExecute(args2, context);
@@ -14869,7 +14798,8 @@ var Agent = class {
14869
14798
  output: result,
14870
14799
  toolCallId,
14871
14800
  duration,
14872
- relationshipId
14801
+ relationshipId,
14802
+ needsApproval
14873
14803
  });
14874
14804
  }
14875
14805
  return result;
@@ -14883,7 +14813,8 @@ var Agent = class {
14883
14813
  toolCallId,
14884
14814
  duration,
14885
14815
  error: errorMessage,
14886
- relationshipId
14816
+ relationshipId,
14817
+ needsApproval
14887
14818
  });
14888
14819
  }
14889
14820
  throw error;
@@ -14952,30 +14883,120 @@ var Agent = class {
14952
14883
  const wrappedTools2 = {};
14953
14884
  for (const [index, toolSet] of tools.entries()) {
14954
14885
  const relationshipId = mcpTools[index]?.relationshipId;
14955
- 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
+ };
14956
14892
  wrappedTools2[toolName] = this.wrapToolWithStreaming(
14957
14893
  toolName,
14958
- toolDef,
14894
+ enhancedTool,
14959
14895
  streamRequestId,
14960
14896
  "mcp",
14961
- relationshipId
14897
+ relationshipId,
14898
+ { needsApproval }
14962
14899
  );
14963
14900
  }
14964
14901
  }
14965
14902
  return wrappedTools2;
14966
14903
  }
14967
14904
  const wrappedTools = {};
14968
- for (const [index, toolSet] of tools.entries()) {
14905
+ for (const [index, toolResult] of tools.entries()) {
14969
14906
  const relationshipId = mcpTools[index]?.relationshipId;
14970
- for (const [toolName, originalTool] of Object.entries(toolSet)) {
14907
+ for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
14971
14908
  if (!isValidTool(originalTool)) {
14972
14909
  logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
14973
14910
  continue;
14974
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
+ );
14975
14922
  const sessionWrappedTool = ai.tool({
14976
14923
  description: originalTool.description,
14977
14924
  inputSchema: originalTool.inputSchema,
14978
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
+ }
14979
15000
  logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
14980
15001
  try {
14981
15002
  const rawResult = await originalTool.execute(args2, { toolCallId });
@@ -15041,7 +15062,8 @@ var Agent = class {
15041
15062
  sessionWrappedTool,
15042
15063
  streamRequestId,
15043
15064
  "mcp",
15044
- relationshipId
15065
+ relationshipId,
15066
+ { needsApproval }
15045
15067
  );
15046
15068
  }
15047
15069
  }
@@ -15080,8 +15102,10 @@ var Agent = class {
15080
15102
  subAgentId: this.config.id
15081
15103
  }
15082
15104
  });
15083
- const agentToolRelationHeaders = toolsForAgent.data.find((t2) => t2.toolId === tool3.id)?.headers || void 0;
15084
- 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 || {};
15085
15109
  let serverConfig;
15086
15110
  if (credentialReferenceId && this.credentialStuffer) {
15087
15111
  const credentialReference = await agentsCore.getCredentialReference(dbClient_default)({
@@ -15212,7 +15236,7 @@ var Agent = class {
15212
15236
  );
15213
15237
  }
15214
15238
  }
15215
- return tools;
15239
+ return { tools, toolPolicies };
15216
15240
  }
15217
15241
  async createMcpConnection(tool3, serverConfig) {
15218
15242
  const client = new agentsCore.McpClient({
@@ -15235,12 +15259,12 @@ var Agent = class {
15235
15259
  if (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) {
15236
15260
  const errorMessage = "Connection refused. Please check if the MCP server is running.";
15237
15261
  throw new Error(errorMessage);
15238
- } else if (error.message.includes("404")) {
15262
+ }
15263
+ if (error.message.includes("404")) {
15239
15264
  const errorMessage = "Error accessing endpoint (HTTP 404)";
15240
15265
  throw new Error(errorMessage);
15241
- } else {
15242
- throw new Error(`MCP server connection failed: ${error.message}`);
15243
15266
  }
15267
+ throw new Error(`MCP server connection failed: ${error.message}`);
15244
15268
  }
15245
15269
  throw error;
15246
15270
  }
@@ -16025,7 +16049,7 @@ ${output}`;
16025
16049
  }
16026
16050
  }
16027
16051
  const primaryModelSettings = this.getPrimaryModel();
16028
- const modelSettings = ModelFactory.prepareGenerationConfig(primaryModelSettings);
16052
+ const modelSettings = agentsCore.ModelFactory.prepareGenerationConfig(primaryModelSettings);
16029
16053
  let response;
16030
16054
  let textResponse;
16031
16055
  const hasStructuredOutput = this.config.dataComponents && this.config.dataComponents.length > 0;
@@ -16138,13 +16162,13 @@ ${output}`;
16138
16162
  parser.markToolResult();
16139
16163
  }
16140
16164
  break;
16141
- case "error":
16165
+ case "error": {
16142
16166
  if (event.error instanceof Error) {
16143
16167
  throw event.error;
16144
- } else {
16145
- const errorMessage = event.error?.error?.message;
16146
- throw new Error(errorMessage);
16147
16168
  }
16169
+ const errorMessage = event.error?.error?.message;
16170
+ throw new Error(errorMessage);
16171
+ }
16148
16172
  }
16149
16173
  }
16150
16174
  await parser.finalize();
@@ -16336,7 +16360,7 @@ ${output}${structureHintsFormatted}`;
16336
16360
  componentSchemas
16337
16361
  );
16338
16362
  }
16339
- const structuredModelSettings = ModelFactory.prepareGenerationConfig(
16363
+ const structuredModelSettings = agentsCore.ModelFactory.prepareGenerationConfig(
16340
16364
  this.getStructuredOutputModel()
16341
16365
  );
16342
16366
  const configuredPhase2Timeout = structuredModelSettings.maxDuration ? Math.min(
@@ -17039,17 +17063,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
17039
17063
  }
17040
17064
  ]
17041
17065
  };
17042
- } else {
17043
- logger20.warn(
17044
- {
17045
- hasToolResult: !!toolResult,
17046
- hasOutput: !!toolResult?.output,
17047
- validationPassed: false,
17048
- output: toolResult?.output
17049
- },
17050
- "[DEBUG] Transfer validation FAILED"
17051
- );
17052
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
+ );
17053
17076
  }
17054
17077
  }
17055
17078
  }
@@ -17968,7 +17991,7 @@ var VercelDataStreamHelper = class _VercelDataStreamHelper {
17968
17991
  }
17969
17992
  const now = Date.now();
17970
17993
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
17971
- 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)) {
17972
17995
  this.queuedEvents.push({ type: "data-operation", event: operation });
17973
17996
  return;
17974
17997
  }
@@ -19137,13 +19160,152 @@ app3.openapi(chatDataStreamRoute, async (c2) => {
19137
19160
  );
19138
19161
  });
19139
19162
  } catch (error) {
19140
- logger26.error({ error }, "chatDataStream error");
19163
+ logger26.error(
19164
+ {
19165
+ error,
19166
+ errorMessage: error instanceof Error ? error.message : String(error),
19167
+ errorStack: error instanceof Error ? error.stack : void 0,
19168
+ errorType: error?.constructor?.name
19169
+ },
19170
+ "chatDataStream error - DETAILED"
19171
+ );
19141
19172
  throw agentsCore.createApiError({
19142
19173
  code: "internal_server_error",
19143
19174
  message: "Failed to process chat completion"
19144
19175
  });
19145
19176
  }
19146
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
+ });
19147
19309
  var chatDataStream_default = app3;
19148
19310
 
19149
19311
  // src/routes/mcp.ts
@@ -19226,7 +19388,8 @@ var validateSession = async (req, res, body2, tenantId, projectId, agentId) => {
19226
19388
  })
19227
19389
  );
19228
19390
  return false;
19229
- } else if (Array.isArray(sessionId)) {
19391
+ }
19392
+ if (Array.isArray(sessionId)) {
19230
19393
  res.writeHead(400).end(
19231
19394
  JSON.stringify({
19232
19395
  jsonrpc: "2.0",
@@ -19649,16 +19812,15 @@ app4.openapi(
19649
19812
  c2,
19650
19813
  credentialStores
19651
19814
  );
19652
- } else {
19653
- return await handleExistingSessionRequest(
19654
- body2,
19655
- executionContext,
19656
- validatedContext,
19657
- req,
19658
- res,
19659
- credentialStores
19660
- );
19661
19815
  }
19816
+ return await handleExistingSessionRequest(
19817
+ body2,
19818
+ executionContext,
19819
+ validatedContext,
19820
+ req,
19821
+ res,
19822
+ credentialStores
19823
+ );
19662
19824
  } catch (e) {
19663
19825
  logger27.error(
19664
19826
  {