@inkeep/agents-run-api 0.0.0-dev-20251124223719 → 0.0.0-dev-20251125020527

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(),
@@ -8588,275 +8583,10 @@ async function handleTasksResubscribe(c2, agent, request) {
8588
8583
  init_dbClient();
8589
8584
  init_logger();
8590
8585
 
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
8586
  // src/agents/ToolSessionManager.ts
8857
8587
  init_execution_limits();
8858
8588
  init_logger();
8859
- var logger5 = agentsCore.getLogger("ToolSessionManager");
8589
+ var logger4 = agentsCore.getLogger("ToolSessionManager");
8860
8590
  var ToolSessionManager = class _ToolSessionManager {
8861
8591
  static instance;
8862
8592
  sessions = /* @__PURE__ */ new Map();
@@ -8890,7 +8620,7 @@ var ToolSessionManager = class _ToolSessionManager {
8890
8620
  createdAt: Date.now()
8891
8621
  };
8892
8622
  this.sessions.set(sessionId, session);
8893
- logger5.debug(
8623
+ logger4.debug(
8894
8624
  {
8895
8625
  sessionId,
8896
8626
  tenantId,
@@ -8908,10 +8638,10 @@ var ToolSessionManager = class _ToolSessionManager {
8908
8638
  */
8909
8639
  ensureAgentSession(sessionId, tenantId, projectId, contextId, taskId) {
8910
8640
  if (this.sessions.has(sessionId)) {
8911
- logger5.debug({ sessionId }, "Agent session already exists, reusing");
8641
+ logger4.debug({ sessionId }, "Agent session already exists, reusing");
8912
8642
  return sessionId;
8913
8643
  }
8914
- logger5.debug(
8644
+ logger4.debug(
8915
8645
  { sessionId, tenantId, contextId, taskId },
8916
8646
  "Creating new agent-scoped tool session"
8917
8647
  );
@@ -8923,7 +8653,7 @@ var ToolSessionManager = class _ToolSessionManager {
8923
8653
  recordToolResult(sessionId, toolResult) {
8924
8654
  const session = this.sessions.get(sessionId);
8925
8655
  if (!session) {
8926
- logger5.warn(
8656
+ logger4.warn(
8927
8657
  {
8928
8658
  sessionId,
8929
8659
  toolCallId: toolResult.toolCallId,
@@ -8935,7 +8665,7 @@ var ToolSessionManager = class _ToolSessionManager {
8935
8665
  return;
8936
8666
  }
8937
8667
  session.toolResults.set(toolResult.toolCallId, toolResult);
8938
- logger5.debug(
8668
+ logger4.debug(
8939
8669
  {
8940
8670
  sessionId,
8941
8671
  toolCallId: toolResult.toolCallId,
@@ -8950,7 +8680,7 @@ var ToolSessionManager = class _ToolSessionManager {
8950
8680
  getToolResult(sessionId, toolCallId) {
8951
8681
  const session = this.sessions.get(sessionId);
8952
8682
  if (!session) {
8953
- logger5.warn(
8683
+ logger4.warn(
8954
8684
  {
8955
8685
  sessionId,
8956
8686
  toolCallId,
@@ -8963,7 +8693,7 @@ var ToolSessionManager = class _ToolSessionManager {
8963
8693
  }
8964
8694
  const result = session.toolResults.get(toolCallId);
8965
8695
  if (!result) {
8966
- logger5.warn(
8696
+ logger4.warn(
8967
8697
  {
8968
8698
  sessionId,
8969
8699
  toolCallId,
@@ -8973,7 +8703,7 @@ var ToolSessionManager = class _ToolSessionManager {
8973
8703
  "Tool result not found"
8974
8704
  );
8975
8705
  } else {
8976
- logger5.debug(
8706
+ logger4.debug(
8977
8707
  {
8978
8708
  sessionId,
8979
8709
  toolCallId,
@@ -9012,10 +8742,10 @@ var ToolSessionManager = class _ToolSessionManager {
9012
8742
  }
9013
8743
  for (const sessionId of expiredSessions) {
9014
8744
  this.sessions.delete(sessionId);
9015
- logger5.debug({ sessionId }, "Cleaned up expired tool session");
8745
+ logger4.debug({ sessionId }, "Cleaned up expired tool session");
9016
8746
  }
9017
8747
  if (expiredSessions.length > 0) {
9018
- logger5.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
8748
+ logger4.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
9019
8749
  }
9020
8750
  }
9021
8751
  };
@@ -9097,7 +8827,7 @@ function extractFullFields(schema2) {
9097
8827
  }
9098
8828
 
9099
8829
  // src/services/ArtifactService.ts
9100
- var logger7 = agentsCore.getLogger("ArtifactService");
8830
+ var logger6 = agentsCore.getLogger("ArtifactService");
9101
8831
  var ArtifactService = class _ArtifactService {
9102
8832
  constructor(context) {
9103
8833
  this.context = context;
@@ -9130,7 +8860,7 @@ var ArtifactService = class _ArtifactService {
9130
8860
  id: taskId
9131
8861
  });
9132
8862
  if (!task) {
9133
- logger7.warn({ taskId }, "Task not found when fetching artifacts");
8863
+ logger6.warn({ taskId }, "Task not found when fetching artifacts");
9134
8864
  continue;
9135
8865
  }
9136
8866
  const taskArtifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
@@ -9148,7 +8878,7 @@ var ArtifactService = class _ArtifactService {
9148
8878
  }
9149
8879
  }
9150
8880
  } catch (error) {
9151
- logger7.error({ error, contextId }, "Error loading context artifacts");
8881
+ logger6.error({ error, contextId }, "Error loading context artifacts");
9152
8882
  }
9153
8883
  return artifacts;
9154
8884
  }
@@ -9157,12 +8887,12 @@ var ArtifactService = class _ArtifactService {
9157
8887
  */
9158
8888
  async createArtifact(request, subAgentId) {
9159
8889
  if (!this.context.sessionId) {
9160
- logger7.warn({ request }, "No session ID available for artifact creation");
8890
+ logger6.warn({ request }, "No session ID available for artifact creation");
9161
8891
  return null;
9162
8892
  }
9163
8893
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
9164
8894
  if (!toolResult) {
9165
- logger7.warn(
8895
+ logger6.warn(
9166
8896
  { request, sessionId: this.context.sessionId },
9167
8897
  "Tool result not found for artifact"
9168
8898
  );
@@ -9178,7 +8908,7 @@ var ArtifactService = class _ArtifactService {
9178
8908
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
9179
8909
  }
9180
8910
  if (!selectedData) {
9181
- logger7.warn(
8911
+ logger6.warn(
9182
8912
  {
9183
8913
  request,
9184
8914
  baseSelector: request.baseSelector
@@ -9249,7 +8979,7 @@ var ArtifactService = class _ArtifactService {
9249
8979
  );
9250
8980
  return artifactData;
9251
8981
  } catch (error) {
9252
- logger7.error({ error, request }, "Failed to create artifact");
8982
+ logger6.error({ error, request }, "Failed to create artifact");
9253
8983
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
9254
8984
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
9255
8985
  }
@@ -9278,7 +9008,7 @@ var ArtifactService = class _ArtifactService {
9278
9008
  }
9279
9009
  try {
9280
9010
  if (!this.context.projectId || !this.context.taskId) {
9281
- logger7.warn(
9011
+ logger6.warn(
9282
9012
  { artifactId, toolCallId },
9283
9013
  "No projectId or taskId available for artifact lookup"
9284
9014
  );
@@ -9302,7 +9032,7 @@ var ArtifactService = class _ArtifactService {
9302
9032
  return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
9303
9033
  }
9304
9034
  } catch (error) {
9305
- logger7.warn(
9035
+ logger6.warn(
9306
9036
  { artifactId, toolCallId, taskId: this.context.taskId, error },
9307
9037
  "Failed to fetch artifact"
9308
9038
  );
@@ -9333,7 +9063,7 @@ var ArtifactService = class _ArtifactService {
9333
9063
  }
9334
9064
  try {
9335
9065
  if (!this.context.projectId || !this.context.taskId) {
9336
- logger7.warn(
9066
+ logger6.warn(
9337
9067
  { artifactId, toolCallId },
9338
9068
  "No projectId or taskId available for artifact lookup"
9339
9069
  );
@@ -9357,7 +9087,7 @@ var ArtifactService = class _ArtifactService {
9357
9087
  return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
9358
9088
  }
9359
9089
  } catch (error) {
9360
- logger7.warn(
9090
+ logger6.warn(
9361
9091
  { artifactId, toolCallId, taskId: this.context.taskId, error },
9362
9092
  "Failed to fetch artifact"
9363
9093
  );
@@ -9374,7 +9104,7 @@ var ArtifactService = class _ArtifactService {
9374
9104
  data = artifact.parts?.[0]?.data;
9375
9105
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9376
9106
  dataSource = "parts[0].data (fallback)";
9377
- logger7.debug(
9107
+ logger6.debug(
9378
9108
  { artifactId, toolCallId, dataSource },
9379
9109
  "Using fallback data source for artifact summary"
9380
9110
  );
@@ -9382,14 +9112,14 @@ var ArtifactService = class _ArtifactService {
9382
9112
  data = artifact.data;
9383
9113
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9384
9114
  dataSource = "artifact.data (fallback)";
9385
- logger7.debug(
9115
+ logger6.debug(
9386
9116
  { artifactId, toolCallId, dataSource },
9387
9117
  "Using fallback data source for artifact summary"
9388
9118
  );
9389
9119
  } else {
9390
9120
  data = {};
9391
9121
  dataSource = "empty (no data found)";
9392
- logger7.warn(
9122
+ logger6.warn(
9393
9123
  {
9394
9124
  artifactId,
9395
9125
  toolCallId,
@@ -9426,7 +9156,7 @@ var ArtifactService = class _ArtifactService {
9426
9156
  data = artifact.parts?.[0]?.data;
9427
9157
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9428
9158
  dataSource = "parts[0].data (fallback)";
9429
- logger7.debug(
9159
+ logger6.debug(
9430
9160
  { artifactId, toolCallId, dataSource },
9431
9161
  "Using fallback data source for artifact full data"
9432
9162
  );
@@ -9434,14 +9164,14 @@ var ArtifactService = class _ArtifactService {
9434
9164
  data = artifact.data;
9435
9165
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
9436
9166
  dataSource = "artifact.data (fallback)";
9437
- logger7.debug(
9167
+ logger6.debug(
9438
9168
  { artifactId, toolCallId, dataSource },
9439
9169
  "Using fallback data source for artifact full data"
9440
9170
  );
9441
9171
  } else {
9442
9172
  data = {};
9443
9173
  dataSource = "empty (no data found)";
9444
- logger7.warn(
9174
+ logger6.warn(
9445
9175
  {
9446
9176
  artifactId,
9447
9177
  toolCallId,
@@ -9495,7 +9225,7 @@ var ArtifactService = class _ArtifactService {
9495
9225
  const error = new Error(
9496
9226
  `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
9227
  );
9498
- logger7.error(
9228
+ logger6.error(
9499
9229
  {
9500
9230
  artifactId,
9501
9231
  artifactType,
@@ -9508,7 +9238,7 @@ var ArtifactService = class _ArtifactService {
9508
9238
  throw error;
9509
9239
  }
9510
9240
  if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) {
9511
- logger7.warn(
9241
+ logger6.warn(
9512
9242
  {
9513
9243
  artifactId,
9514
9244
  artifactType,
@@ -9522,7 +9252,7 @@ var ArtifactService = class _ArtifactService {
9522
9252
  );
9523
9253
  }
9524
9254
  if (!fullValidation.hasExpectedFields || fullValidation.extraFields.length > 0) {
9525
- logger7.warn(
9255
+ logger6.warn(
9526
9256
  {
9527
9257
  artifactId,
9528
9258
  artifactType,
@@ -9594,7 +9324,7 @@ var ArtifactService = class _ArtifactService {
9594
9324
  }
9595
9325
  );
9596
9326
  } else {
9597
- logger7.warn(
9327
+ logger6.warn(
9598
9328
  {
9599
9329
  artifactId: request.artifactId,
9600
9330
  hasStreamRequestId: !!this.context.streamRequestId,
@@ -9669,7 +9399,7 @@ var ArtifactService = class _ArtifactService {
9669
9399
  summaryData = this.filterBySchema(artifact.data, previewSchema);
9670
9400
  fullData = this.filterBySchema(artifact.data, fullSchema);
9671
9401
  } catch (error) {
9672
- logger7.warn(
9402
+ logger6.warn(
9673
9403
  {
9674
9404
  artifactType: artifact.type,
9675
9405
  error: error instanceof Error ? error.message : "Unknown error"
@@ -9707,7 +9437,7 @@ var ArtifactService = class _ArtifactService {
9707
9437
  artifact: artifactToSave
9708
9438
  });
9709
9439
  if (!result.created && result.existing) {
9710
- logger7.debug(
9440
+ logger6.debug(
9711
9441
  {
9712
9442
  artifactId: artifact.artifactId,
9713
9443
  taskId: this.context.taskId
@@ -9767,7 +9497,7 @@ var ArtifactService = class _ArtifactService {
9767
9497
  extracted[fieldName] = this.cleanEscapedContent(rawValue);
9768
9498
  }
9769
9499
  } catch (error) {
9770
- logger7.warn(
9500
+ logger6.warn(
9771
9501
  { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
9772
9502
  "Failed to extract schema field"
9773
9503
  );
@@ -9796,7 +9526,7 @@ var ArtifactService = class _ArtifactService {
9796
9526
  };
9797
9527
 
9798
9528
  // src/services/ArtifactParser.ts
9799
- var logger8 = agentsCore.getLogger("ArtifactParser");
9529
+ var logger7 = agentsCore.getLogger("ArtifactParser");
9800
9530
  var ArtifactParser = class _ArtifactParser {
9801
9531
  static ARTIFACT_CHECK_REGEX = /<artifact:ref\s+(?=.*id=['"][^'"]+['"])(?=.*tool=['"][^'"]+['"])[^>]*\/>/;
9802
9532
  static ATTR_REGEX = /(\w+)="([^"]*)"|(\w+)='([^']*)'|(\w+)=({[^}]+})/g;
@@ -9907,7 +9637,7 @@ var ArtifactParser = class _ArtifactParser {
9907
9637
  attrs[key] = value;
9908
9638
  }
9909
9639
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
9910
- logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
9640
+ logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
9911
9641
  return null;
9912
9642
  }
9913
9643
  return {
@@ -9968,7 +9698,7 @@ var ArtifactParser = class _ArtifactParser {
9968
9698
  `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
9969
9699
  );
9970
9700
  processedText = processedText.replace(annotation.raw, "");
9971
- logger8.warn(
9701
+ logger7.warn(
9972
9702
  { annotation, artifactData },
9973
9703
  "Removed failed artifact:create annotation from output"
9974
9704
  );
@@ -9979,11 +9709,11 @@ var ArtifactParser = class _ArtifactParser {
9979
9709
  if (annotation.raw) {
9980
9710
  processedText = processedText.replace(annotation.raw, "");
9981
9711
  }
9982
- logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
9712
+ logger7.error({ annotation, error }, "Failed to extract artifact from create annotation");
9983
9713
  }
9984
9714
  }
9985
9715
  if (failedAnnotations.length > 0) {
9986
- logger8.warn(
9716
+ logger7.warn(
9987
9717
  {
9988
9718
  failedCount: failedAnnotations.length,
9989
9719
  failures: failedAnnotations
@@ -10167,7 +9897,7 @@ var ArtifactParser = class _ArtifactParser {
10167
9897
  };
10168
9898
 
10169
9899
  // src/services/AgentSession.ts
10170
- var logger9 = agentsCore.getLogger("AgentSession");
9900
+ var logger8 = agentsCore.getLogger("AgentSession");
10171
9901
  var AgentSession = class {
10172
9902
  // Whether to send data operations
10173
9903
  constructor(sessionId, messageId, agentId, tenantId, projectId, contextId) {
@@ -10177,7 +9907,7 @@ var AgentSession = class {
10177
9907
  this.tenantId = tenantId;
10178
9908
  this.projectId = projectId;
10179
9909
  this.contextId = contextId;
10180
- logger9.debug({ sessionId, messageId, agentId }, "AgentSession created");
9910
+ logger8.debug({ sessionId, messageId, agentId }, "AgentSession created");
10181
9911
  if (tenantId && projectId) {
10182
9912
  toolSessionManager.createSessionWithId(
10183
9913
  sessionId,
@@ -10234,7 +9964,7 @@ var AgentSession = class {
10234
9964
  */
10235
9965
  enableEmitOperations() {
10236
9966
  this.isEmitOperations = true;
10237
- logger9.info(
9967
+ logger8.info(
10238
9968
  { sessionId: this.sessionId },
10239
9969
  "\u{1F50D} DEBUG: Emit operations enabled for AgentSession"
10240
9970
  );
@@ -10243,6 +9973,7 @@ var AgentSession = class {
10243
9973
  * Send data operation to stream when emit operations is enabled
10244
9974
  */
10245
9975
  async sendDataOperation(event) {
9976
+ console.log("sendDataOperation called with event", Date.now());
10246
9977
  try {
10247
9978
  const streamHelper = getStreamHelper(this.sessionId);
10248
9979
  if (streamHelper) {
@@ -10258,7 +9989,7 @@ var AgentSession = class {
10258
9989
  await streamHelper.writeOperation(formattedOperation);
10259
9990
  }
10260
9991
  } catch (error) {
10261
- logger9.error(
9992
+ logger8.error(
10262
9993
  {
10263
9994
  sessionId: this.sessionId,
10264
9995
  eventType: event.eventType,
@@ -10317,7 +10048,7 @@ var AgentSession = class {
10317
10048
  if (this.statusUpdateState.config.timeInSeconds) {
10318
10049
  this.statusUpdateTimer = setInterval(async () => {
10319
10050
  if (!this.statusUpdateState || this.isEnded) {
10320
- logger9.debug(
10051
+ logger8.debug(
10321
10052
  { sessionId: this.sessionId },
10322
10053
  "Timer triggered but session already cleaned up or ended"
10323
10054
  );
@@ -10329,7 +10060,7 @@ var AgentSession = class {
10329
10060
  }
10330
10061
  await this.checkAndSendTimeBasedUpdate();
10331
10062
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
10332
- logger9.info(
10063
+ logger8.info(
10333
10064
  {
10334
10065
  sessionId: this.sessionId,
10335
10066
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -10353,7 +10084,7 @@ var AgentSession = class {
10353
10084
  this.sendDataOperation(dataOpEvent);
10354
10085
  }
10355
10086
  if (this.isEnded) {
10356
- logger9.debug(
10087
+ logger8.debug(
10357
10088
  {
10358
10089
  sessionId: this.sessionId,
10359
10090
  eventType,
@@ -10375,7 +10106,7 @@ var AgentSession = class {
10375
10106
  if (artifactData.pendingGeneration) {
10376
10107
  const artifactId = artifactData.artifactId;
10377
10108
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
10378
- logger9.warn(
10109
+ logger8.warn(
10379
10110
  {
10380
10111
  sessionId: this.sessionId,
10381
10112
  artifactId,
@@ -10397,7 +10128,7 @@ var AgentSession = class {
10397
10128
  this.artifactProcessingErrors.set(artifactId, errorCount);
10398
10129
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
10399
10130
  this.pendingArtifacts.delete(artifactId);
10400
- logger9.error(
10131
+ logger8.error(
10401
10132
  {
10402
10133
  sessionId: this.sessionId,
10403
10134
  artifactId,
@@ -10409,7 +10140,7 @@ var AgentSession = class {
10409
10140
  "Artifact processing failed after max retries, giving up"
10410
10141
  );
10411
10142
  } else {
10412
- logger9.warn(
10143
+ logger8.warn(
10413
10144
  {
10414
10145
  sessionId: this.sessionId,
10415
10146
  artifactId,
@@ -10432,14 +10163,14 @@ var AgentSession = class {
10432
10163
  */
10433
10164
  checkStatusUpdates() {
10434
10165
  if (this.isEnded) {
10435
- logger9.debug(
10166
+ logger8.debug(
10436
10167
  { sessionId: this.sessionId },
10437
10168
  "Session has ended - skipping status update check"
10438
10169
  );
10439
10170
  return;
10440
10171
  }
10441
10172
  if (!this.statusUpdateState) {
10442
- logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
10173
+ logger8.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
10443
10174
  return;
10444
10175
  }
10445
10176
  const statusUpdateState = this.statusUpdateState;
@@ -10450,11 +10181,11 @@ var AgentSession = class {
10450
10181
  */
10451
10182
  async checkAndSendTimeBasedUpdate() {
10452
10183
  if (this.isEnded) {
10453
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
10184
+ logger8.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
10454
10185
  return;
10455
10186
  }
10456
10187
  if (!this.statusUpdateState) {
10457
- logger9.debug(
10188
+ logger8.debug(
10458
10189
  { sessionId: this.sessionId },
10459
10190
  "No status updates configured for time-based check"
10460
10191
  );
@@ -10467,7 +10198,7 @@ var AgentSession = class {
10467
10198
  try {
10468
10199
  await this.generateAndSendUpdate();
10469
10200
  } catch (error) {
10470
- logger9.error(
10201
+ logger8.error(
10471
10202
  {
10472
10203
  sessionId: this.sessionId,
10473
10204
  error: error instanceof Error ? error.message : "Unknown error"
@@ -10570,29 +10301,29 @@ var AgentSession = class {
10570
10301
  */
10571
10302
  async generateAndSendUpdate() {
10572
10303
  if (this.isEnded) {
10573
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
10304
+ logger8.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
10574
10305
  return;
10575
10306
  }
10576
10307
  if (this.isTextStreaming) {
10577
- logger9.debug(
10308
+ logger8.debug(
10578
10309
  { sessionId: this.sessionId },
10579
10310
  "Text is currently streaming - skipping status update"
10580
10311
  );
10581
10312
  return;
10582
10313
  }
10583
10314
  if (this.isGeneratingUpdate) {
10584
- logger9.debug(
10315
+ logger8.debug(
10585
10316
  { sessionId: this.sessionId },
10586
10317
  "Update already in progress - skipping duplicate generation"
10587
10318
  );
10588
10319
  return;
10589
10320
  }
10590
10321
  if (!this.statusUpdateState) {
10591
- logger9.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
10322
+ logger8.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
10592
10323
  return;
10593
10324
  }
10594
10325
  if (!this.agentId) {
10595
- logger9.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
10326
+ logger8.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
10596
10327
  return;
10597
10328
  }
10598
10329
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -10604,7 +10335,7 @@ var AgentSession = class {
10604
10335
  try {
10605
10336
  const streamHelper = getStreamHelper(this.sessionId);
10606
10337
  if (!streamHelper) {
10607
- logger9.warn(
10338
+ logger8.warn(
10608
10339
  { sessionId: this.sessionId },
10609
10340
  "No stream helper found - cannot send status update"
10610
10341
  );
@@ -10624,7 +10355,7 @@ var AgentSession = class {
10624
10355
  if (result.summaries && result.summaries.length > 0) {
10625
10356
  for (const summary of result.summaries) {
10626
10357
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
10627
- logger9.warn(
10358
+ logger8.warn(
10628
10359
  {
10629
10360
  sessionId: this.sessionId,
10630
10361
  summary
@@ -10661,7 +10392,7 @@ var AgentSession = class {
10661
10392
  this.statusUpdateState.lastEventCount = this.events.length;
10662
10393
  }
10663
10394
  } catch (error) {
10664
- logger9.error(
10395
+ logger8.error(
10665
10396
  {
10666
10397
  sessionId: this.sessionId,
10667
10398
  error: error instanceof Error ? error.message : "Unknown error",
@@ -10699,7 +10430,7 @@ var AgentSession = class {
10699
10430
  this.releaseUpdateLock();
10700
10431
  }
10701
10432
  } catch (error) {
10702
- logger9.error(
10433
+ logger8.error(
10703
10434
  {
10704
10435
  sessionId: this.sessionId,
10705
10436
  error: error instanceof Error ? error.message : "Unknown error"
@@ -10778,7 +10509,7 @@ User's Question/Context:
10778
10509
  ${conversationHistory}
10779
10510
  ` : "";
10780
10511
  } catch (error) {
10781
- logger9.warn(
10512
+ logger8.warn(
10782
10513
  { sessionId: this.sessionId, error },
10783
10514
  "Failed to fetch conversation history for structured status update"
10784
10515
  );
@@ -10872,7 +10603,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10872
10603
  if (!modelToUse) {
10873
10604
  throw new Error("No model configuration available");
10874
10605
  }
10875
- const model = ModelFactory.createModel(modelToUse);
10606
+ const model = agentsCore.ModelFactory.createModel(modelToUse);
10876
10607
  const { object } = await ai.generateObject({
10877
10608
  model,
10878
10609
  prompt,
@@ -10889,10 +10620,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10889
10620
  }
10890
10621
  });
10891
10622
  const result = object;
10892
- logger9.info({ result: JSON.stringify(result) }, "DEBUG: Result");
10623
+ logger8.info({ result: JSON.stringify(result) }, "DEBUG: Result");
10893
10624
  const summaries = [];
10894
10625
  for (const [componentId, data] of Object.entries(result)) {
10895
- logger9.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
10626
+ logger8.info({ componentId, data: JSON.stringify(data) }, "DEBUG: Component data");
10896
10627
  if (componentId === "no_relevant_updates") {
10897
10628
  continue;
10898
10629
  }
@@ -10912,7 +10643,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
10912
10643
  return { summaries };
10913
10644
  } catch (error) {
10914
10645
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
10915
- logger9.error({ error }, "Failed to generate structured update, using fallback");
10646
+ logger8.error({ error }, "Failed to generate structured update, using fallback");
10916
10647
  return { summaries: [] };
10917
10648
  } finally {
10918
10649
  span.end();
@@ -11184,7 +10915,7 @@ Make it specific and relevant.`;
11184
10915
  });
11185
10916
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
11186
10917
  modelToUse = agentData.models.base;
11187
- logger9.info(
10918
+ logger8.info(
11188
10919
  {
11189
10920
  sessionId: this.sessionId,
11190
10921
  artifactId: artifactData.artifactId,
@@ -11195,7 +10926,7 @@ Make it specific and relevant.`;
11195
10926
  );
11196
10927
  }
11197
10928
  } catch (error) {
11198
- logger9.warn(
10929
+ logger8.warn(
11199
10930
  {
11200
10931
  sessionId: this.sessionId,
11201
10932
  artifactId: artifactData.artifactId,
@@ -11207,7 +10938,7 @@ Make it specific and relevant.`;
11207
10938
  }
11208
10939
  }
11209
10940
  if (!modelToUse?.model?.trim()) {
11210
- logger9.warn(
10941
+ logger8.warn(
11211
10942
  {
11212
10943
  sessionId: this.sessionId,
11213
10944
  artifactId: artifactData.artifactId
@@ -11227,7 +10958,7 @@ Make it specific and relevant.`;
11227
10958
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolCallId || "tool results"}`
11228
10959
  };
11229
10960
  } else {
11230
- const model = ModelFactory.createModel(modelToUse);
10961
+ const model = agentsCore.ModelFactory.createModel(modelToUse);
11231
10962
  const schema2 = z8.z.object({
11232
10963
  name: z8.z.string().describe("Concise, descriptive name for the artifact"),
11233
10964
  description: z8.z.string().describe("Brief description of the artifact's relevance to the user's question")
@@ -11289,7 +11020,7 @@ Make it specific and relevant.`;
11289
11020
  return result2;
11290
11021
  } catch (error) {
11291
11022
  lastError = error instanceof Error ? error : new Error(String(error));
11292
- logger9.warn(
11023
+ logger8.warn(
11293
11024
  {
11294
11025
  sessionId: this.sessionId,
11295
11026
  artifactId: artifactData.artifactId,
@@ -11337,7 +11068,7 @@ Make it specific and relevant.`;
11337
11068
  });
11338
11069
  span.setStatus({ code: api.SpanStatusCode.OK });
11339
11070
  } catch (saveError) {
11340
- logger9.error(
11071
+ logger8.error(
11341
11072
  {
11342
11073
  sessionId: this.sessionId,
11343
11074
  artifactId: artifactData.artifactId,
@@ -11365,7 +11096,7 @@ Make it specific and relevant.`;
11365
11096
  metadata: artifactData.metadata || {},
11366
11097
  toolCallId: artifactData.toolCallId
11367
11098
  });
11368
- logger9.info(
11099
+ logger8.info(
11369
11100
  {
11370
11101
  sessionId: this.sessionId,
11371
11102
  artifactId: artifactData.artifactId
@@ -11376,7 +11107,7 @@ Make it specific and relevant.`;
11376
11107
  } catch (fallbackError) {
11377
11108
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
11378
11109
  if (isDuplicateError) ; else {
11379
- logger9.error(
11110
+ logger8.error(
11380
11111
  {
11381
11112
  sessionId: this.sessionId,
11382
11113
  artifactId: artifactData.artifactId,
@@ -11389,7 +11120,7 @@ Make it specific and relevant.`;
11389
11120
  }
11390
11121
  } catch (error) {
11391
11122
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
11392
- logger9.error(
11123
+ logger8.error(
11393
11124
  {
11394
11125
  sessionId: this.sessionId,
11395
11126
  artifactId: artifactData.artifactId,
@@ -11408,7 +11139,7 @@ Make it specific and relevant.`;
11408
11139
  */
11409
11140
  setArtifactCache(key, artifact) {
11410
11141
  this.artifactCache.set(key, artifact);
11411
- logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
11142
+ logger8.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
11412
11143
  }
11413
11144
  /**
11414
11145
  * Get session-scoped ArtifactService instance
@@ -11427,7 +11158,7 @@ Make it specific and relevant.`;
11427
11158
  */
11428
11159
  getArtifactCache(key) {
11429
11160
  const artifact = this.artifactCache.get(key);
11430
- logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
11161
+ logger8.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
11431
11162
  return artifact || null;
11432
11163
  }
11433
11164
  /**
@@ -11448,7 +11179,7 @@ var AgentSessionManager = class {
11448
11179
  const sessionId = messageId;
11449
11180
  const session = new AgentSession(sessionId, messageId, agentId, tenantId, projectId, contextId);
11450
11181
  this.sessions.set(sessionId, session);
11451
- logger9.info(
11182
+ logger8.info(
11452
11183
  { sessionId, messageId, agentId, tenantId, projectId, contextId },
11453
11184
  "AgentSession created"
11454
11185
  );
@@ -11462,7 +11193,7 @@ var AgentSessionManager = class {
11462
11193
  if (session) {
11463
11194
  session.initializeStatusUpdates(config, summarizerModel, baseModel);
11464
11195
  } else {
11465
- logger9.error(
11196
+ logger8.error(
11466
11197
  {
11467
11198
  sessionId,
11468
11199
  availableSessions: Array.from(this.sessions.keys())
@@ -11479,7 +11210,7 @@ var AgentSessionManager = class {
11479
11210
  if (session) {
11480
11211
  session.enableEmitOperations();
11481
11212
  } else {
11482
- logger9.error(
11213
+ logger8.error(
11483
11214
  {
11484
11215
  sessionId,
11485
11216
  availableSessions: Array.from(this.sessions.keys())
@@ -11501,7 +11232,7 @@ var AgentSessionManager = class {
11501
11232
  recordEvent(sessionId, eventType, subAgentId, data) {
11502
11233
  const session = this.sessions.get(sessionId);
11503
11234
  if (!session) {
11504
- logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
11235
+ logger8.warn({ sessionId }, "Attempted to record event in non-existent session");
11505
11236
  return;
11506
11237
  }
11507
11238
  session.recordEvent(eventType, subAgentId, data);
@@ -11512,12 +11243,12 @@ var AgentSessionManager = class {
11512
11243
  endSession(sessionId) {
11513
11244
  const session = this.sessions.get(sessionId);
11514
11245
  if (!session) {
11515
- logger9.warn({ sessionId }, "Attempted to end non-existent session");
11246
+ logger8.warn({ sessionId }, "Attempted to end non-existent session");
11516
11247
  return [];
11517
11248
  }
11518
11249
  const events = session.getEvents();
11519
11250
  const summary = session.getSummary();
11520
- logger9.info({ sessionId, summary }, "AgentSession ended");
11251
+ logger8.info({ sessionId, summary }, "AgentSession ended");
11521
11252
  session.cleanup();
11522
11253
  this.sessions.delete(sessionId);
11523
11254
  return events;
@@ -11627,7 +11358,7 @@ init_logger();
11627
11358
  // src/services/IncrementalStreamParser.ts
11628
11359
  init_execution_limits();
11629
11360
  init_logger();
11630
- var logger10 = agentsCore.getLogger("IncrementalStreamParser");
11361
+ var logger9 = agentsCore.getLogger("IncrementalStreamParser");
11631
11362
  var IncrementalStreamParser = class _IncrementalStreamParser {
11632
11363
  buffer = "";
11633
11364
  pendingTextBuffer = "";
@@ -11685,7 +11416,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
11685
11416
  async initializeArtifactMap() {
11686
11417
  try {
11687
11418
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
11688
- logger10.debug(
11419
+ logger9.debug(
11689
11420
  {
11690
11421
  contextId: this.contextId,
11691
11422
  artifactMapSize: this.artifactMap.size
@@ -11693,7 +11424,7 @@ var IncrementalStreamParser = class _IncrementalStreamParser {
11693
11424
  "Initialized artifact map for streaming"
11694
11425
  );
11695
11426
  } catch (error) {
11696
- logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
11427
+ logger9.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
11697
11428
  this.artifactMap = /* @__PURE__ */ new Map();
11698
11429
  }
11699
11430
  }
@@ -12026,6 +11757,143 @@ ${chunk}`;
12026
11757
  }
12027
11758
  };
12028
11759
 
11760
+ // src/services/PendingToolApprovalManager.ts
11761
+ init_logger();
11762
+ var logger10 = agentsCore.getLogger("PendingToolApprovalManager");
11763
+ var APPROVAL_CLEANUP_INTERVAL_MS = 2 * 60 * 1e3;
11764
+ var APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
11765
+ var PendingToolApprovalManager = class _PendingToolApprovalManager {
11766
+ static instance;
11767
+ pendingApprovals = /* @__PURE__ */ new Map();
11768
+ constructor() {
11769
+ setInterval(() => this.cleanupExpiredApprovals(), APPROVAL_CLEANUP_INTERVAL_MS);
11770
+ }
11771
+ static getInstance() {
11772
+ if (!_PendingToolApprovalManager.instance) {
11773
+ _PendingToolApprovalManager.instance = new _PendingToolApprovalManager();
11774
+ }
11775
+ return _PendingToolApprovalManager.instance;
11776
+ }
11777
+ /**
11778
+ * Create a new pending approval and return a promise that resolves with approval status
11779
+ */
11780
+ async waitForApproval(toolCallId, toolName, args2, conversationId, subAgentId) {
11781
+ return new Promise((resolve2, reject) => {
11782
+ const timeoutId = setTimeout(() => {
11783
+ this.pendingApprovals.delete(toolCallId);
11784
+ resolve2({
11785
+ approved: false,
11786
+ reason: `Tool approval timeout for ${toolName} (${toolCallId})`
11787
+ });
11788
+ }, APPROVAL_TIMEOUT_MS);
11789
+ const approval = {
11790
+ toolCallId,
11791
+ toolName,
11792
+ args: args2,
11793
+ conversationId,
11794
+ subAgentId,
11795
+ createdAt: Date.now(),
11796
+ resolve: resolve2,
11797
+ reject,
11798
+ timeoutId
11799
+ };
11800
+ this.pendingApprovals.set(toolCallId, approval);
11801
+ logger10.info(
11802
+ {
11803
+ toolCallId,
11804
+ toolName,
11805
+ conversationId,
11806
+ subAgentId
11807
+ },
11808
+ "Tool approval request created, waiting for user response"
11809
+ );
11810
+ });
11811
+ }
11812
+ /**
11813
+ * Approve a pending tool call
11814
+ */
11815
+ approveToolCall(toolCallId) {
11816
+ const approval = this.pendingApprovals.get(toolCallId);
11817
+ if (!approval) {
11818
+ logger10.warn({ toolCallId }, "Tool approval not found or already processed");
11819
+ return false;
11820
+ }
11821
+ logger10.info(
11822
+ {
11823
+ toolCallId,
11824
+ toolName: approval.toolName,
11825
+ conversationId: approval.conversationId
11826
+ },
11827
+ "Tool approved by user, resuming execution"
11828
+ );
11829
+ clearTimeout(approval.timeoutId);
11830
+ this.pendingApprovals.delete(toolCallId);
11831
+ approval.resolve({ approved: true });
11832
+ return true;
11833
+ }
11834
+ /**
11835
+ * Deny a pending tool call
11836
+ */
11837
+ denyToolCall(toolCallId, reason) {
11838
+ const approval = this.pendingApprovals.get(toolCallId);
11839
+ if (!approval) {
11840
+ logger10.warn({ toolCallId }, "Tool approval not found or already processed");
11841
+ return false;
11842
+ }
11843
+ logger10.info(
11844
+ {
11845
+ toolCallId,
11846
+ toolName: approval.toolName,
11847
+ conversationId: approval.conversationId,
11848
+ reason
11849
+ },
11850
+ "Tool execution denied by user"
11851
+ );
11852
+ clearTimeout(approval.timeoutId);
11853
+ this.pendingApprovals.delete(toolCallId);
11854
+ approval.resolve({
11855
+ approved: false,
11856
+ reason: reason || "User denied approval"
11857
+ });
11858
+ return true;
11859
+ }
11860
+ /**
11861
+ * Clean up expired approvals (called by interval timer)
11862
+ */
11863
+ cleanupExpiredApprovals() {
11864
+ const now = Date.now();
11865
+ let cleanedUp = 0;
11866
+ for (const [toolCallId, approval] of this.pendingApprovals) {
11867
+ if (now - approval.createdAt > APPROVAL_TIMEOUT_MS) {
11868
+ clearTimeout(approval.timeoutId);
11869
+ this.pendingApprovals.delete(toolCallId);
11870
+ approval.resolve({ approved: false, reason: "Tool approval expired" });
11871
+ cleanedUp++;
11872
+ }
11873
+ }
11874
+ if (cleanedUp > 0) {
11875
+ logger10.info({ cleanedUp }, "Cleaned up expired tool approvals");
11876
+ }
11877
+ }
11878
+ /**
11879
+ * Get current status for monitoring
11880
+ */
11881
+ getStatus() {
11882
+ return {
11883
+ pendingApprovals: this.pendingApprovals.size,
11884
+ approvals: Array.from(this.pendingApprovals.values()).map((approval) => ({
11885
+ toolCallId: approval.toolCallId,
11886
+ toolName: approval.toolName,
11887
+ conversationId: approval.conversationId,
11888
+ subAgentId: approval.subAgentId,
11889
+ createdAt: approval.createdAt,
11890
+ age: Date.now() - approval.createdAt
11891
+ }))
11892
+ };
11893
+ }
11894
+ };
11895
+ var pendingToolApprovalManager = PendingToolApprovalManager.getInstance();
11896
+
12029
11897
  // src/services/ResponseFormatter.ts
12030
11898
  init_logger();
12031
11899
  var logger11 = agentsCore.getLogger("ResponseFormatter");
@@ -14847,7 +14715,7 @@ var Agent = class {
14847
14715
  /**
14848
14716
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
14849
14717
  */
14850
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId) {
14718
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId, options) {
14851
14719
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
14852
14720
  return toolDefinition;
14853
14721
  }
@@ -14869,13 +14737,24 @@ var Agent = class {
14869
14737
  });
14870
14738
  }
14871
14739
  const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
14740
+ const needsApproval = options?.needsApproval || false;
14872
14741
  if (streamRequestId && !isInternalTool) {
14873
- agentSessionManager.recordEvent(streamRequestId, "tool_call", this.config.id, {
14742
+ const toolCallData = {
14874
14743
  toolName,
14875
14744
  input: args2,
14876
14745
  toolCallId,
14877
14746
  relationshipId
14878
- });
14747
+ };
14748
+ if (needsApproval) {
14749
+ toolCallData.needsApproval = true;
14750
+ toolCallData.conversationId = this.conversationId;
14751
+ }
14752
+ await agentSessionManager.recordEvent(
14753
+ streamRequestId,
14754
+ "tool_call",
14755
+ this.config.id,
14756
+ toolCallData
14757
+ );
14879
14758
  }
14880
14759
  try {
14881
14760
  const result = await originalExecute(args2, context);
@@ -14920,7 +14799,8 @@ var Agent = class {
14920
14799
  output: result,
14921
14800
  toolCallId,
14922
14801
  duration,
14923
- relationshipId
14802
+ relationshipId,
14803
+ needsApproval
14924
14804
  });
14925
14805
  }
14926
14806
  return result;
@@ -14934,7 +14814,8 @@ var Agent = class {
14934
14814
  toolCallId,
14935
14815
  duration,
14936
14816
  error: errorMessage,
14937
- relationshipId
14817
+ relationshipId,
14818
+ needsApproval
14938
14819
  });
14939
14820
  }
14940
14821
  throw error;
@@ -15003,30 +14884,120 @@ var Agent = class {
15003
14884
  const wrappedTools2 = {};
15004
14885
  for (const [index, toolSet] of tools.entries()) {
15005
14886
  const relationshipId = mcpTools[index]?.relationshipId;
15006
- for (const [toolName, toolDef] of Object.entries(toolSet)) {
14887
+ for (const [toolName, toolDef] of Object.entries(toolSet.tools)) {
14888
+ const needsApproval = toolSet.toolPolicies?.[toolName]?.needsApproval || false;
14889
+ const enhancedTool = {
14890
+ ...toolDef,
14891
+ needsApproval
14892
+ };
15007
14893
  wrappedTools2[toolName] = this.wrapToolWithStreaming(
15008
14894
  toolName,
15009
- toolDef,
14895
+ enhancedTool,
15010
14896
  streamRequestId,
15011
14897
  "mcp",
15012
- relationshipId
14898
+ relationshipId,
14899
+ { needsApproval }
15013
14900
  );
15014
14901
  }
15015
14902
  }
15016
14903
  return wrappedTools2;
15017
14904
  }
15018
14905
  const wrappedTools = {};
15019
- for (const [index, toolSet] of tools.entries()) {
14906
+ for (const [index, toolResult] of tools.entries()) {
15020
14907
  const relationshipId = mcpTools[index]?.relationshipId;
15021
- for (const [toolName, originalTool] of Object.entries(toolSet)) {
14908
+ for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
15022
14909
  if (!isValidTool(originalTool)) {
15023
14910
  logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
15024
14911
  continue;
15025
14912
  }
14913
+ const needsApproval = toolResult.toolPolicies?.[toolName]?.needsApproval || false;
14914
+ logger19.debug(
14915
+ {
14916
+ toolName,
14917
+ toolPolicies: toolResult.toolPolicies,
14918
+ needsApproval,
14919
+ policyForThisTool: toolResult.toolPolicies?.[toolName]
14920
+ },
14921
+ "Tool approval check"
14922
+ );
15026
14923
  const sessionWrappedTool = ai.tool({
15027
14924
  description: originalTool.description,
15028
14925
  inputSchema: originalTool.inputSchema,
15029
14926
  execute: async (args2, { toolCallId }) => {
14927
+ if (needsApproval) {
14928
+ logger19.info(
14929
+ { toolName, toolCallId, args: args2 },
14930
+ "Tool requires approval - waiting for user response"
14931
+ );
14932
+ const currentSpan = api.trace.getActiveSpan();
14933
+ if (currentSpan) {
14934
+ currentSpan.addEvent("tool.approval.requested", {
14935
+ "tool.name": toolName,
14936
+ "tool.callId": toolCallId,
14937
+ "subAgent.id": this.config.id
14938
+ });
14939
+ }
14940
+ tracer.startActiveSpan(
14941
+ "tool.approval_requested",
14942
+ {
14943
+ attributes: {
14944
+ "tool.name": toolName,
14945
+ "tool.callId": toolCallId,
14946
+ "subAgent.id": this.config.id,
14947
+ "subAgent.name": this.config.name
14948
+ }
14949
+ },
14950
+ (requestSpan) => {
14951
+ requestSpan.setStatus({ code: api.SpanStatusCode.OK });
14952
+ requestSpan.end();
14953
+ }
14954
+ );
14955
+ const approvalResult = await pendingToolApprovalManager.waitForApproval(
14956
+ toolCallId,
14957
+ toolName,
14958
+ args2,
14959
+ this.conversationId || "unknown",
14960
+ this.config.id
14961
+ );
14962
+ if (!approvalResult.approved) {
14963
+ return tracer.startActiveSpan(
14964
+ "tool.approval_denied",
14965
+ {
14966
+ attributes: {
14967
+ "tool.name": toolName,
14968
+ "tool.callId": toolCallId,
14969
+ "subAgent.id": this.config.id,
14970
+ "subAgent.name": this.config.name
14971
+ }
14972
+ },
14973
+ (denialSpan) => {
14974
+ logger19.info(
14975
+ { toolName, toolCallId, reason: approvalResult.reason },
14976
+ "Tool execution denied by user"
14977
+ );
14978
+ denialSpan.setStatus({ code: api.SpanStatusCode.OK });
14979
+ denialSpan.end();
14980
+ return `User denied approval to run this tool: ${approvalResult.reason}`;
14981
+ }
14982
+ );
14983
+ }
14984
+ tracer.startActiveSpan(
14985
+ "tool.approval_approved",
14986
+ {
14987
+ attributes: {
14988
+ "tool.name": toolName,
14989
+ "tool.callId": toolCallId,
14990
+ "subAgent.id": this.config.id,
14991
+ "subAgent.name": this.config.name
14992
+ }
14993
+ },
14994
+ (approvedSpan) => {
14995
+ logger19.info({ toolName, toolCallId }, "Tool approved, continuing with execution");
14996
+ approvedSpan.setStatus({ code: api.SpanStatusCode.OK });
14997
+ approvedSpan.end();
14998
+ }
14999
+ );
15000
+ }
15030
15001
  logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
15031
15002
  try {
15032
15003
  const rawResult = await originalTool.execute(args2, { toolCallId });
@@ -15092,7 +15063,8 @@ var Agent = class {
15092
15063
  sessionWrappedTool,
15093
15064
  streamRequestId,
15094
15065
  "mcp",
15095
- relationshipId
15066
+ relationshipId,
15067
+ { needsApproval }
15096
15068
  );
15097
15069
  }
15098
15070
  }
@@ -15131,8 +15103,10 @@ var Agent = class {
15131
15103
  subAgentId: this.config.id
15132
15104
  }
15133
15105
  });
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;
15106
+ const toolRelation = toolsForAgent.data.find((t2) => t2.toolId === tool3.id);
15107
+ const agentToolRelationHeaders = toolRelation?.headers || void 0;
15108
+ const selectedTools = toolRelation?.selectedTools || void 0;
15109
+ const toolPolicies = toolRelation?.toolPolicies || {};
15136
15110
  let serverConfig;
15137
15111
  if (credentialReferenceId && this.credentialStuffer) {
15138
15112
  const credentialReference = await agentsCore.getCredentialReference(dbClient_default)({
@@ -15263,7 +15237,7 @@ var Agent = class {
15263
15237
  );
15264
15238
  }
15265
15239
  }
15266
- return tools;
15240
+ return { tools, toolPolicies };
15267
15241
  }
15268
15242
  async createMcpConnection(tool3, serverConfig) {
15269
15243
  const client = new agentsCore.McpClient({
@@ -15286,12 +15260,12 @@ var Agent = class {
15286
15260
  if (error?.cause && JSON.stringify(error.cause).includes("ECONNREFUSED")) {
15287
15261
  const errorMessage = "Connection refused. Please check if the MCP server is running.";
15288
15262
  throw new Error(errorMessage);
15289
- } else if (error.message.includes("404")) {
15263
+ }
15264
+ if (error.message.includes("404")) {
15290
15265
  const errorMessage = "Error accessing endpoint (HTTP 404)";
15291
15266
  throw new Error(errorMessage);
15292
- } else {
15293
- throw new Error(`MCP server connection failed: ${error.message}`);
15294
15267
  }
15268
+ throw new Error(`MCP server connection failed: ${error.message}`);
15295
15269
  }
15296
15270
  throw error;
15297
15271
  }
@@ -16076,7 +16050,7 @@ ${output}`;
16076
16050
  }
16077
16051
  }
16078
16052
  const primaryModelSettings = this.getPrimaryModel();
16079
- const modelSettings = ModelFactory.prepareGenerationConfig(primaryModelSettings);
16053
+ const modelSettings = agentsCore.ModelFactory.prepareGenerationConfig(primaryModelSettings);
16080
16054
  let response;
16081
16055
  let textResponse;
16082
16056
  const hasStructuredOutput = this.config.dataComponents && this.config.dataComponents.length > 0;
@@ -16189,13 +16163,13 @@ ${output}`;
16189
16163
  parser.markToolResult();
16190
16164
  }
16191
16165
  break;
16192
- case "error":
16166
+ case "error": {
16193
16167
  if (event.error instanceof Error) {
16194
16168
  throw event.error;
16195
- } else {
16196
- const errorMessage = event.error?.error?.message;
16197
- throw new Error(errorMessage);
16198
16169
  }
16170
+ const errorMessage = event.error?.error?.message;
16171
+ throw new Error(errorMessage);
16172
+ }
16199
16173
  }
16200
16174
  }
16201
16175
  await parser.finalize();
@@ -16387,7 +16361,7 @@ ${output}${structureHintsFormatted}`;
16387
16361
  componentSchemas
16388
16362
  );
16389
16363
  }
16390
- const structuredModelSettings = ModelFactory.prepareGenerationConfig(
16364
+ const structuredModelSettings = agentsCore.ModelFactory.prepareGenerationConfig(
16391
16365
  this.getStructuredOutputModel()
16392
16366
  );
16393
16367
  const configuredPhase2Timeout = structuredModelSettings.maxDuration ? Math.min(
@@ -18019,7 +17993,7 @@ var VercelDataStreamHelper = class _VercelDataStreamHelper {
18019
17993
  }
18020
17994
  const now = Date.now();
18021
17995
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
18022
- if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
17996
+ if (operation.type !== "tool_call" && operation.type !== "tool_result" && (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS)) {
18023
17997
  this.queuedEvents.push({ type: "data-operation", event: operation });
18024
17998
  return;
18025
17999
  }
@@ -19203,6 +19177,137 @@ app3.openapi(chatDataStreamRoute, async (c2) => {
19203
19177
  });
19204
19178
  }
19205
19179
  });
19180
+ var toolApprovalRoute = zodOpenapi.createRoute({
19181
+ method: "post",
19182
+ path: "/tool-approvals",
19183
+ tags: ["chat"],
19184
+ summary: "Approve or deny tool execution",
19185
+ description: "Handle user approval/denial of tool execution requests during conversations",
19186
+ security: [{ bearerAuth: [] }],
19187
+ request: {
19188
+ body: {
19189
+ content: {
19190
+ "application/json": {
19191
+ schema: zodOpenapi.z.object({
19192
+ conversationId: zodOpenapi.z.string().describe("The conversation ID"),
19193
+ toolCallId: zodOpenapi.z.string().describe("The tool call ID to respond to"),
19194
+ approved: zodOpenapi.z.boolean().describe("Whether the tool execution is approved"),
19195
+ reason: zodOpenapi.z.string().optional().describe("Optional reason for the decision")
19196
+ })
19197
+ }
19198
+ }
19199
+ }
19200
+ },
19201
+ responses: {
19202
+ 200: {
19203
+ description: "Tool approval response processed successfully",
19204
+ content: {
19205
+ "application/json": {
19206
+ schema: zodOpenapi.z.object({
19207
+ success: zodOpenapi.z.boolean(),
19208
+ message: zodOpenapi.z.string().optional()
19209
+ })
19210
+ }
19211
+ }
19212
+ },
19213
+ 400: {
19214
+ description: "Bad request - invalid tool call ID or conversation ID",
19215
+ content: {
19216
+ "application/json": {
19217
+ schema: zodOpenapi.z.object({
19218
+ error: zodOpenapi.z.string()
19219
+ })
19220
+ }
19221
+ }
19222
+ },
19223
+ 404: {
19224
+ description: "Tool call not found or already processed",
19225
+ content: {
19226
+ "application/json": {
19227
+ schema: zodOpenapi.z.object({
19228
+ error: zodOpenapi.z.string()
19229
+ })
19230
+ }
19231
+ }
19232
+ },
19233
+ 500: {
19234
+ description: "Internal server error",
19235
+ content: {
19236
+ "application/json": {
19237
+ schema: zodOpenapi.z.object({
19238
+ error: zodOpenapi.z.string(),
19239
+ message: zodOpenapi.z.string()
19240
+ })
19241
+ }
19242
+ }
19243
+ }
19244
+ }
19245
+ });
19246
+ app3.openapi(toolApprovalRoute, async (c2) => {
19247
+ const tracer2 = api.trace.getTracer("tool-approval-handler");
19248
+ return tracer2.startActiveSpan("tool_approval_request", async (span) => {
19249
+ try {
19250
+ const executionContext = agentsCore.getRequestExecutionContext(c2);
19251
+ const { tenantId, projectId } = executionContext;
19252
+ const requestBody = await c2.req.json();
19253
+ const { conversationId, toolCallId, approved, reason } = requestBody;
19254
+ logger26.info(
19255
+ {
19256
+ conversationId,
19257
+ toolCallId,
19258
+ approved,
19259
+ reason,
19260
+ tenantId,
19261
+ projectId
19262
+ },
19263
+ "Processing tool approval request"
19264
+ );
19265
+ const conversation = await agentsCore.getConversation(dbClient_default)({
19266
+ scopes: { tenantId, projectId },
19267
+ conversationId
19268
+ });
19269
+ if (!conversation) {
19270
+ span.setStatus({ code: 1, message: "Conversation not found" });
19271
+ return c2.json({ error: "Conversation not found" }, 404);
19272
+ }
19273
+ let success = false;
19274
+ if (approved) {
19275
+ success = pendingToolApprovalManager.approveToolCall(toolCallId);
19276
+ } else {
19277
+ success = pendingToolApprovalManager.denyToolCall(toolCallId, reason);
19278
+ }
19279
+ if (!success) {
19280
+ span.setStatus({ code: 1, message: "Tool call not found" });
19281
+ return c2.json({ error: "Tool call not found or already processed" }, 404);
19282
+ }
19283
+ logger26.info({ conversationId, toolCallId, approved }, "Tool approval processed successfully");
19284
+ span.setStatus({ code: 1, message: "Success" });
19285
+ return c2.json({
19286
+ success: true,
19287
+ message: approved ? "Tool execution approved" : "Tool execution denied"
19288
+ });
19289
+ } catch (error) {
19290
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
19291
+ logger26.error(
19292
+ {
19293
+ error: errorMessage,
19294
+ stack: error instanceof Error ? error.stack : void 0
19295
+ },
19296
+ "Failed to process tool approval"
19297
+ );
19298
+ span.setStatus({ code: 2, message: errorMessage });
19299
+ return c2.json(
19300
+ {
19301
+ error: "Internal server error",
19302
+ message: errorMessage
19303
+ },
19304
+ 500
19305
+ );
19306
+ } finally {
19307
+ span.end();
19308
+ }
19309
+ });
19310
+ });
19206
19311
  var chatDataStream_default = app3;
19207
19312
 
19208
19313
  // src/routes/mcp.ts