@inkeep/agents-run-api 0.14.3 → 0.14.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { dbClient_default } from './chunk-TWVQBIUL.js';
1
+ import { dbClient_default } from './chunk-7IMXW4RD.js';
2
2
  import { createMessage, getConversationHistory } from '@inkeep/agents-core';
3
3
  import { nanoid } from 'nanoid';
4
4
 
@@ -189,7 +189,7 @@ async function getConversationScopedArtifacts(params) {
189
189
  return [];
190
190
  }
191
191
  const { getLedgerArtifacts } = await import('@inkeep/agents-core');
192
- const dbClient = (await import('./dbClient-GGR4KMBD.js')).default;
192
+ const dbClient = (await import('./dbClient-UQHVUUUY.js')).default;
193
193
  const visibleTaskIds = visibleMessages.map((msg) => msg.taskId).filter((taskId) => Boolean(taskId));
194
194
  const referenceArtifacts = [];
195
195
  for (const taskId of visibleTaskIds) {
@@ -0,0 +1,26 @@
1
+ import { env } from './chunk-NZHNG4A3.js';
2
+ import { createDatabaseClient } from '@inkeep/agents-core';
3
+
4
+ var getDbConfig = () => {
5
+ if (env.ENVIRONMENT === "test") {
6
+ return { url: ":memory:" };
7
+ }
8
+ if (env.TURSO_DATABASE_URL && env.TURSO_AUTH_TOKEN) {
9
+ return {
10
+ url: env.TURSO_DATABASE_URL,
11
+ authToken: env.TURSO_AUTH_TOKEN
12
+ };
13
+ }
14
+ if (!env.DB_FILE_NAME) {
15
+ throw new Error(
16
+ "Database configuration error: DB_FILE_NAME must be set if Turso is not configured."
17
+ );
18
+ }
19
+ return {
20
+ url: env.DB_FILE_NAME
21
+ };
22
+ };
23
+ var dbClient = createDatabaseClient(getDbConfig());
24
+ var dbClient_default = dbClient;
25
+
26
+ export { dbClient_default };
@@ -1,7 +1,7 @@
1
- import { loadEnvironmentFiles, createDatabaseClient } from '@inkeep/agents-core';
1
+ import { loadEnvironmentFiles } from '@inkeep/agents-core';
2
2
  import { z } from 'zod';
3
3
 
4
- // src/data/db/dbClient.ts
4
+ // src/env.ts
5
5
  loadEnvironmentFiles();
6
6
  var envSchema = z.object({
7
7
  NODE_ENV: z.enum(["development", "production", "test"]).optional(),
@@ -14,7 +14,9 @@ var envSchema = z.object({
14
14
  NANGO_SECRET_KEY: z.string().optional(),
15
15
  OPENAI_API_KEY: z.string().optional(),
16
16
  ANTHROPIC_API_KEY: z.string(),
17
- INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z.string().optional()
17
+ INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z.string().optional(),
18
+ OTEL_BSP_SCHEDULE_DELAY: z.coerce.number().optional().default(500),
19
+ OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z.coerce.number().optional().default(64)
18
20
  });
19
21
  var parseEnv = () => {
20
22
  try {
@@ -33,27 +35,4 @@ ${error.message}`
33
35
  };
34
36
  var env = parseEnv();
35
37
 
36
- // src/data/db/dbClient.ts
37
- var getDbConfig = () => {
38
- if (env.ENVIRONMENT === "test") {
39
- return { url: ":memory:" };
40
- }
41
- if (env.TURSO_DATABASE_URL && env.TURSO_AUTH_TOKEN) {
42
- return {
43
- url: env.TURSO_DATABASE_URL,
44
- authToken: env.TURSO_AUTH_TOKEN
45
- };
46
- }
47
- if (!env.DB_FILE_NAME) {
48
- throw new Error(
49
- "Database configuration error: DB_FILE_NAME must be set if Turso is not configured."
50
- );
51
- }
52
- return {
53
- url: env.DB_FILE_NAME
54
- };
55
- };
56
- var dbClient = createDatabaseClient(getDbConfig());
57
- var dbClient_default = dbClient;
58
-
59
- export { dbClient_default, env };
38
+ export { env };
@@ -1,4 +1,5 @@
1
1
  import { getLogger } from './chunk-A2S7GSHL.js';
2
+ import { env } from './chunk-NZHNG4A3.js';
2
3
  import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
3
4
  import { BaggageSpanProcessor, ALLOW_ALL_BAGGAGE_KEYS } from '@opentelemetry/baggage-span-processor';
4
5
  import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
@@ -14,7 +15,8 @@ var logger = getLogger("instrumentation");
14
15
  function createSafeBatchProcessor() {
15
16
  try {
16
17
  return new BatchSpanProcessor(otlpExporter, {
17
- scheduledDelayMillis: 1e3
18
+ scheduledDelayMillis: env.OTEL_BSP_SCHEDULE_DELAY,
19
+ maxExportBatchSize: env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE
18
20
  });
19
21
  } catch (error) {
20
22
  logger.warn({ error }, "Failed to create batch processor");
@@ -62,5 +64,12 @@ var defaultSDK = new NodeSDK({
62
64
  spanProcessors: defaultSpanProcessors,
63
65
  instrumentations: defaultInstrumentations
64
66
  });
67
+ async function flushBatchProcessor() {
68
+ try {
69
+ await defaultBatchProcessor.forceFlush();
70
+ } catch (error) {
71
+ logger.warn({ error }, "Failed to flush batch processor");
72
+ }
73
+ }
65
74
 
66
- export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator };
75
+ export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator, flushBatchProcessor };
@@ -1 +1 @@
1
- export { createDefaultConversationHistoryConfig, getConversationScopedArtifacts, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse } from './chunk-F46V23RK.js';
1
+ export { createDefaultConversationHistoryConfig, getConversationScopedArtifacts, getFormattedConversationHistory, getFullConversationContext, getScopedHistory, getUserFacingHistory, saveA2AMessageResponse } from './chunk-5GUNCN5X.js';
@@ -0,0 +1 @@
1
+ export { dbClient_default as default } from './chunk-7IMXW4RD.js';
package/dist/index.cjs CHANGED
@@ -71,7 +71,9 @@ var init_env = __esm({
71
71
  NANGO_SECRET_KEY: z5.z.string().optional(),
72
72
  OPENAI_API_KEY: z5.z.string().optional(),
73
73
  ANTHROPIC_API_KEY: z5.z.string(),
74
- INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z5.z.string().optional()
74
+ INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z5.z.string().optional(),
75
+ OTEL_BSP_SCHEDULE_DELAY: z5.z.coerce.number().optional().default(500),
76
+ OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z5.z.coerce.number().optional().default(64)
75
77
  });
76
78
  parseEnv = () => {
77
79
  try {
@@ -397,13 +399,15 @@ var init_json_postprocessor = __esm({
397
399
  init_env();
398
400
 
399
401
  // src/instrumentation.ts
402
+ init_env();
400
403
  init_logger();
401
404
  var otlpExporter = new exporterTraceOtlpHttp.OTLPTraceExporter();
402
405
  var logger = agentsCore.getLogger("instrumentation");
403
406
  function createSafeBatchProcessor() {
404
407
  try {
405
408
  return new sdkTraceBase.BatchSpanProcessor(otlpExporter, {
406
- scheduledDelayMillis: 1e3
409
+ scheduledDelayMillis: env.OTEL_BSP_SCHEDULE_DELAY,
410
+ maxExportBatchSize: env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE
407
411
  });
408
412
  } catch (error) {
409
413
  logger.warn({ error }, "Failed to create batch processor");
@@ -451,6 +455,13 @@ new sdkNode.NodeSDK({
451
455
  spanProcessors: defaultSpanProcessors,
452
456
  instrumentations: defaultInstrumentations
453
457
  });
458
+ async function flushBatchProcessor() {
459
+ try {
460
+ await defaultBatchProcessor.forceFlush();
461
+ } catch (error) {
462
+ logger.warn({ error }, "Failed to flush batch processor");
463
+ }
464
+ }
454
465
 
455
466
  // src/app.ts
456
467
  init_logger();
@@ -3175,7 +3186,6 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3175
3186
  return { summaries: [] };
3176
3187
  } finally {
3177
3188
  span.end();
3178
- await defaultBatchProcessor.forceFlush();
3179
3189
  }
3180
3190
  }
3181
3191
  );
@@ -3594,7 +3604,6 @@ Make it specific and relevant.`;
3594
3604
  );
3595
3605
  } finally {
3596
3606
  span.end();
3597
- await defaultBatchProcessor.forceFlush();
3598
3607
  }
3599
3608
  }
3600
3609
  );
@@ -4152,7 +4161,6 @@ var ResponseFormatter = class {
4152
4161
  };
4153
4162
  } finally {
4154
4163
  span.end();
4155
- await defaultBatchProcessor.forceFlush();
4156
4164
  }
4157
4165
  });
4158
4166
  }
@@ -4203,7 +4211,6 @@ var ResponseFormatter = class {
4203
4211
  return { text: responseText };
4204
4212
  } finally {
4205
4213
  span.end();
4206
- await defaultBatchProcessor.forceFlush();
4207
4214
  }
4208
4215
  });
4209
4216
  }
@@ -6649,6 +6656,8 @@ var Agent = class {
6649
6656
  __publicField(this, "isDelegatedAgent", false);
6650
6657
  __publicField(this, "contextResolver");
6651
6658
  __publicField(this, "credentialStoreRegistry");
6659
+ __publicField(this, "mcpClientCache", /* @__PURE__ */ new Map());
6660
+ __publicField(this, "mcpConnectionLocks", /* @__PURE__ */ new Map());
6652
6661
  this.artifactComponents = config.artifactComponents || [];
6653
6662
  let processedDataComponents = config.dataComponents || [];
6654
6663
  if (processedDataComponents.length > 0) {
@@ -6971,6 +6980,7 @@ var Agent = class {
6971
6980
  };
6972
6981
  }
6973
6982
  async getMcpTool(tool3) {
6983
+ const cacheKey = `${this.config.tenantId}-${this.config.projectId}-${tool3.id}-${tool3.credentialReferenceId || "no-cred"}`;
6974
6984
  const credentialReferenceId = tool3.credentialReferenceId;
6975
6985
  const toolsForAgent = await agentsCore.getToolsForAgent(dbClient_default)({
6976
6986
  scopes: {
@@ -7039,12 +7049,56 @@ var Agent = class {
7039
7049
  },
7040
7050
  "Built MCP server config with credentials"
7041
7051
  );
7052
+ let client = this.mcpClientCache.get(cacheKey);
7053
+ if (client && !client.isConnected()) {
7054
+ this.mcpClientCache.delete(cacheKey);
7055
+ client = void 0;
7056
+ }
7057
+ if (!client) {
7058
+ let connectionPromise = this.mcpConnectionLocks.get(cacheKey);
7059
+ if (!connectionPromise) {
7060
+ connectionPromise = this.createMcpConnection(tool3, serverConfig);
7061
+ this.mcpConnectionLocks.set(cacheKey, connectionPromise);
7062
+ }
7063
+ try {
7064
+ client = await connectionPromise;
7065
+ this.mcpClientCache.set(cacheKey, client);
7066
+ } catch (error) {
7067
+ this.mcpConnectionLocks.delete(cacheKey);
7068
+ logger17.error(
7069
+ {
7070
+ toolName: tool3.name,
7071
+ agentId: this.config.id,
7072
+ cacheKey,
7073
+ error: error instanceof Error ? error.message : String(error)
7074
+ },
7075
+ "MCP connection failed"
7076
+ );
7077
+ throw error;
7078
+ }
7079
+ }
7080
+ const tools = await client.tools();
7081
+ return tools;
7082
+ }
7083
+ async createMcpConnection(tool3, serverConfig) {
7042
7084
  const client = new agentsCore.McpClient({
7043
7085
  name: tool3.name,
7044
7086
  server: serverConfig
7045
7087
  });
7046
- await client.connect();
7047
- return client.tools();
7088
+ try {
7089
+ await client.connect();
7090
+ return client;
7091
+ } catch (error) {
7092
+ logger17.error(
7093
+ {
7094
+ toolName: tool3.name,
7095
+ agentId: this.config.id,
7096
+ error: error instanceof Error ? error.message : String(error)
7097
+ },
7098
+ "Agent failed to connect to MCP server"
7099
+ );
7100
+ throw error;
7101
+ }
7048
7102
  }
7049
7103
  getFunctionTools(streamRequestId) {
7050
7104
  if (!this.config.functionTools) return {};
@@ -7090,7 +7144,6 @@ var Agent = class {
7090
7144
  requestContext: requestContext || {},
7091
7145
  tenantId: this.config.tenantId
7092
7146
  });
7093
- await defaultBatchProcessor.forceFlush();
7094
7147
  const contextWithBuiltins = {
7095
7148
  ...result.resolvedContext,
7096
7149
  $now: (/* @__PURE__ */ new Date()).toISOString(),
@@ -7629,7 +7682,6 @@ var Agent = class {
7629
7682
  throw err;
7630
7683
  } finally {
7631
7684
  childSpan.end();
7632
- await defaultBatchProcessor.forceFlush();
7633
7685
  }
7634
7686
  }
7635
7687
  );
@@ -8060,7 +8112,6 @@ ${output}${structureHintsFormatted}`;
8060
8112
  }
8061
8113
  span.setStatus({ code: api.SpanStatusCode.OK });
8062
8114
  span.end();
8063
- await defaultBatchProcessor.forceFlush();
8064
8115
  let formattedContent = response.formattedContent || null;
8065
8116
  if (!formattedContent) {
8066
8117
  const session = toolSessionManager.getSession(sessionId);
@@ -9626,7 +9677,6 @@ var ExecutionHandler = class {
9626
9677
  throw error;
9627
9678
  } finally {
9628
9679
  span.end();
9629
- await defaultBatchProcessor.forceFlush();
9630
9680
  }
9631
9681
  });
9632
9682
  }
@@ -10153,7 +10203,6 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10153
10203
  dbClient: dbClient_default,
10154
10204
  credentialStores
10155
10205
  });
10156
- await defaultBatchProcessor.forceFlush();
10157
10206
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
10158
10207
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
10159
10208
  logger23.info({ userText, lastUserMessage }, "userText");
@@ -10961,19 +11010,19 @@ function createExecutionHono(serverConfig, credentialStores) {
10961
11010
  setupOpenAPIRoutes(app6);
10962
11011
  app6.use("/tenants/*", async (_c, next) => {
10963
11012
  await next();
10964
- await defaultBatchProcessor.forceFlush();
11013
+ await flushBatchProcessor();
10965
11014
  });
10966
11015
  app6.use("/agents/*", async (_c, next) => {
10967
11016
  await next();
10968
- await defaultBatchProcessor.forceFlush();
11017
+ await flushBatchProcessor();
10969
11018
  });
10970
11019
  app6.use("/v1/*", async (_c, next) => {
10971
11020
  await next();
10972
- await defaultBatchProcessor.forceFlush();
11021
+ await flushBatchProcessor();
10973
11022
  });
10974
11023
  app6.use("/api/*", async (_c, next) => {
10975
11024
  await next();
10976
- await defaultBatchProcessor.forceFlush();
11025
+ await flushBatchProcessor();
10977
11026
  });
10978
11027
  const baseApp = new hono.Hono();
10979
11028
  baseApp.route("/", app6);
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
- import { defaultBatchProcessor } from './chunk-USFUAR3Y.js';
1
+ import { flushBatchProcessor } from './chunk-XO4RG36I.js';
2
2
  import { getLogger } from './chunk-A2S7GSHL.js';
3
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-F46V23RK.js';
4
- import { dbClient_default, env } from './chunk-TWVQBIUL.js';
3
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-5GUNCN5X.js';
4
+ import { dbClient_default } from './chunk-7IMXW4RD.js';
5
+ import { env } from './chunk-NZHNG4A3.js';
5
6
  import { __publicField } from './chunk-PKBMQBKP.js';
6
7
  import { getLogger as getLogger$1, getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentGraphWithDefaultAgent, contextValidationMiddleware, getFullGraph, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, getAgentGraphById, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getRelatedAgentsForGraph, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getContextConfigById, getFullGraphDefinition, TemplateEngine, graphHasArtifactComponents, MCPTransportType, getExternalAgent } from '@inkeep/agents-core';
7
8
  import { otel } from '@hono/otel';
@@ -2709,7 +2710,6 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2709
2710
  return { summaries: [] };
2710
2711
  } finally {
2711
2712
  span.end();
2712
- await defaultBatchProcessor.forceFlush();
2713
2713
  }
2714
2714
  }
2715
2715
  );
@@ -3128,7 +3128,6 @@ Make it specific and relevant.`;
3128
3128
  );
3129
3129
  } finally {
3130
3130
  span.end();
3131
- await defaultBatchProcessor.forceFlush();
3132
3131
  }
3133
3132
  }
3134
3133
  );
@@ -3684,7 +3683,6 @@ var ResponseFormatter = class {
3684
3683
  };
3685
3684
  } finally {
3686
3685
  span.end();
3687
- await defaultBatchProcessor.forceFlush();
3688
3686
  }
3689
3687
  });
3690
3688
  }
@@ -3735,7 +3733,6 @@ var ResponseFormatter = class {
3735
3733
  return { text: responseText };
3736
3734
  } finally {
3737
3735
  span.end();
3738
- await defaultBatchProcessor.forceFlush();
3739
3736
  }
3740
3737
  });
3741
3738
  }
@@ -6166,6 +6163,8 @@ var Agent = class {
6166
6163
  __publicField(this, "isDelegatedAgent", false);
6167
6164
  __publicField(this, "contextResolver");
6168
6165
  __publicField(this, "credentialStoreRegistry");
6166
+ __publicField(this, "mcpClientCache", /* @__PURE__ */ new Map());
6167
+ __publicField(this, "mcpConnectionLocks", /* @__PURE__ */ new Map());
6169
6168
  this.artifactComponents = config.artifactComponents || [];
6170
6169
  let processedDataComponents = config.dataComponents || [];
6171
6170
  if (processedDataComponents.length > 0) {
@@ -6488,6 +6487,7 @@ var Agent = class {
6488
6487
  };
6489
6488
  }
6490
6489
  async getMcpTool(tool3) {
6490
+ const cacheKey = `${this.config.tenantId}-${this.config.projectId}-${tool3.id}-${tool3.credentialReferenceId || "no-cred"}`;
6491
6491
  const credentialReferenceId = tool3.credentialReferenceId;
6492
6492
  const toolsForAgent = await getToolsForAgent(dbClient_default)({
6493
6493
  scopes: {
@@ -6556,12 +6556,56 @@ var Agent = class {
6556
6556
  },
6557
6557
  "Built MCP server config with credentials"
6558
6558
  );
6559
+ let client = this.mcpClientCache.get(cacheKey);
6560
+ if (client && !client.isConnected()) {
6561
+ this.mcpClientCache.delete(cacheKey);
6562
+ client = void 0;
6563
+ }
6564
+ if (!client) {
6565
+ let connectionPromise = this.mcpConnectionLocks.get(cacheKey);
6566
+ if (!connectionPromise) {
6567
+ connectionPromise = this.createMcpConnection(tool3, serverConfig);
6568
+ this.mcpConnectionLocks.set(cacheKey, connectionPromise);
6569
+ }
6570
+ try {
6571
+ client = await connectionPromise;
6572
+ this.mcpClientCache.set(cacheKey, client);
6573
+ } catch (error) {
6574
+ this.mcpConnectionLocks.delete(cacheKey);
6575
+ logger16.error(
6576
+ {
6577
+ toolName: tool3.name,
6578
+ agentId: this.config.id,
6579
+ cacheKey,
6580
+ error: error instanceof Error ? error.message : String(error)
6581
+ },
6582
+ "MCP connection failed"
6583
+ );
6584
+ throw error;
6585
+ }
6586
+ }
6587
+ const tools = await client.tools();
6588
+ return tools;
6589
+ }
6590
+ async createMcpConnection(tool3, serverConfig) {
6559
6591
  const client = new McpClient({
6560
6592
  name: tool3.name,
6561
6593
  server: serverConfig
6562
6594
  });
6563
- await client.connect();
6564
- return client.tools();
6595
+ try {
6596
+ await client.connect();
6597
+ return client;
6598
+ } catch (error) {
6599
+ logger16.error(
6600
+ {
6601
+ toolName: tool3.name,
6602
+ agentId: this.config.id,
6603
+ error: error instanceof Error ? error.message : String(error)
6604
+ },
6605
+ "Agent failed to connect to MCP server"
6606
+ );
6607
+ throw error;
6608
+ }
6565
6609
  }
6566
6610
  getFunctionTools(streamRequestId) {
6567
6611
  if (!this.config.functionTools) return {};
@@ -6607,7 +6651,6 @@ var Agent = class {
6607
6651
  requestContext: requestContext || {},
6608
6652
  tenantId: this.config.tenantId
6609
6653
  });
6610
- await defaultBatchProcessor.forceFlush();
6611
6654
  const contextWithBuiltins = {
6612
6655
  ...result.resolvedContext,
6613
6656
  $now: (/* @__PURE__ */ new Date()).toISOString(),
@@ -6777,7 +6820,7 @@ var Agent = class {
6777
6820
  inputSchema: tool3.inputSchema || tool3.parameters || {},
6778
6821
  usageGuidelines: name.startsWith("transfer_to_") || name.startsWith("delegate_to_") ? `Use this tool to ${name.startsWith("transfer_to_") ? "transfer" : "delegate"} to another agent when appropriate.` : "Use this tool when appropriate for the task at hand."
6779
6822
  }));
6780
- const { getConversationScopedArtifacts } = await import('./conversations-AP5WZGWA.js');
6823
+ const { getConversationScopedArtifacts } = await import('./conversations-6HJ4FX5F.js');
6781
6824
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
6782
6825
  const referenceArtifacts = await getConversationScopedArtifacts({
6783
6826
  tenantId: this.config.tenantId,
@@ -7146,7 +7189,6 @@ var Agent = class {
7146
7189
  throw err;
7147
7190
  } finally {
7148
7191
  childSpan.end();
7149
- await defaultBatchProcessor.forceFlush();
7150
7192
  }
7151
7193
  }
7152
7194
  );
@@ -7577,7 +7619,6 @@ ${output}${structureHintsFormatted}`;
7577
7619
  }
7578
7620
  span.setStatus({ code: SpanStatusCode.OK });
7579
7621
  span.end();
7580
- await defaultBatchProcessor.forceFlush();
7581
7622
  let formattedContent = response.formattedContent || null;
7582
7623
  if (!formattedContent) {
7583
7624
  const session = toolSessionManager.getSession(sessionId);
@@ -9129,7 +9170,6 @@ var ExecutionHandler = class {
9129
9170
  throw error;
9130
9171
  } finally {
9131
9172
  span.end();
9132
- await defaultBatchProcessor.forceFlush();
9133
9173
  }
9134
9174
  });
9135
9175
  }
@@ -9651,7 +9691,6 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9651
9691
  dbClient: dbClient_default,
9652
9692
  credentialStores
9653
9693
  });
9654
- await defaultBatchProcessor.forceFlush();
9655
9694
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
9656
9695
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
9657
9696
  logger22.info({ userText, lastUserMessage }, "userText");
@@ -10455,19 +10494,19 @@ function createExecutionHono(serverConfig, credentialStores) {
10455
10494
  setupOpenAPIRoutes(app6);
10456
10495
  app6.use("/tenants/*", async (_c, next) => {
10457
10496
  await next();
10458
- await defaultBatchProcessor.forceFlush();
10497
+ await flushBatchProcessor();
10459
10498
  });
10460
10499
  app6.use("/agents/*", async (_c, next) => {
10461
10500
  await next();
10462
- await defaultBatchProcessor.forceFlush();
10501
+ await flushBatchProcessor();
10463
10502
  });
10464
10503
  app6.use("/v1/*", async (_c, next) => {
10465
10504
  await next();
10466
- await defaultBatchProcessor.forceFlush();
10505
+ await flushBatchProcessor();
10467
10506
  });
10468
10507
  app6.use("/api/*", async (_c, next) => {
10469
10508
  await next();
10470
- await defaultBatchProcessor.forceFlush();
10509
+ await flushBatchProcessor();
10471
10510
  });
10472
10511
  const baseApp = new Hono();
10473
10512
  baseApp.route("/", app6);
@@ -10,8 +10,41 @@ var sdkNode = require('@opentelemetry/sdk-node');
10
10
  var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
11
11
  var semanticConventions = require('@opentelemetry/semantic-conventions');
12
12
  var agentsCore = require('@inkeep/agents-core');
13
+ var zod = require('zod');
13
14
 
14
15
  // src/instrumentation.ts
16
+ agentsCore.loadEnvironmentFiles();
17
+ var envSchema = zod.z.object({
18
+ NODE_ENV: zod.z.enum(["development", "production", "test"]).optional(),
19
+ ENVIRONMENT: zod.z.enum(["development", "production", "pentest", "test"]).optional().default("development"),
20
+ DB_FILE_NAME: zod.z.string().optional(),
21
+ TURSO_DATABASE_URL: zod.z.string().optional(),
22
+ TURSO_AUTH_TOKEN: zod.z.string().optional(),
23
+ AGENTS_RUN_API_URL: zod.z.string().optional().default("http://localhost:3003"),
24
+ LOG_LEVEL: zod.z.enum(["trace", "debug", "info", "warn", "error"]).optional().default("debug"),
25
+ NANGO_SECRET_KEY: zod.z.string().optional(),
26
+ OPENAI_API_KEY: zod.z.string().optional(),
27
+ ANTHROPIC_API_KEY: zod.z.string(),
28
+ INKEEP_AGENTS_RUN_API_BYPASS_SECRET: zod.z.string().optional(),
29
+ OTEL_BSP_SCHEDULE_DELAY: zod.z.coerce.number().optional().default(500),
30
+ OTEL_BSP_MAX_EXPORT_BATCH_SIZE: zod.z.coerce.number().optional().default(64)
31
+ });
32
+ var parseEnv = () => {
33
+ try {
34
+ const parsedEnv = envSchema.parse(process.env);
35
+ return parsedEnv;
36
+ } catch (error) {
37
+ if (error instanceof zod.z.ZodError) {
38
+ const missingVars = error.issues.map((issue) => issue.path.join("."));
39
+ throw new Error(
40
+ `\u274C Invalid environment variables: ${missingVars.join(", ")}
41
+ ${error.message}`
42
+ );
43
+ }
44
+ throw error;
45
+ }
46
+ };
47
+ var env = parseEnv();
15
48
 
16
49
  // src/instrumentation.ts
17
50
  var otlpExporter = new exporterTraceOtlpHttp.OTLPTraceExporter();
@@ -19,7 +52,8 @@ var logger = agentsCore.getLogger("instrumentation");
19
52
  function createSafeBatchProcessor() {
20
53
  try {
21
54
  return new sdkTraceBase.BatchSpanProcessor(otlpExporter, {
22
- scheduledDelayMillis: 1e3
55
+ scheduledDelayMillis: env.OTEL_BSP_SCHEDULE_DELAY,
56
+ maxExportBatchSize: env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE
23
57
  });
24
58
  } catch (error) {
25
59
  logger.warn({ error }, "Failed to create batch processor");
@@ -67,6 +101,13 @@ var defaultSDK = new sdkNode.NodeSDK({
67
101
  spanProcessors: defaultSpanProcessors,
68
102
  instrumentations: defaultInstrumentations
69
103
  });
104
+ async function flushBatchProcessor() {
105
+ try {
106
+ await defaultBatchProcessor.forceFlush();
107
+ } catch (error) {
108
+ logger.warn({ error }, "Failed to flush batch processor");
109
+ }
110
+ }
70
111
 
71
112
  exports.defaultBatchProcessor = defaultBatchProcessor;
72
113
  exports.defaultContextManager = defaultContextManager;
@@ -75,3 +116,4 @@ exports.defaultResource = defaultResource;
75
116
  exports.defaultSDK = defaultSDK;
76
117
  exports.defaultSpanProcessors = defaultSpanProcessors;
77
118
  exports.defaultTextMapPropagator = defaultTextMapPropagator;
119
+ exports.flushBatchProcessor = flushBatchProcessor;
@@ -11,5 +11,6 @@ declare const defaultSpanProcessors: SpanProcessor[];
11
11
  declare const defaultContextManager: AsyncLocalStorageContextManager;
12
12
  declare const defaultTextMapPropagator: CompositePropagator;
13
13
  declare const defaultSDK: NodeSDK;
14
+ declare function flushBatchProcessor(): Promise<void>;
14
15
 
15
- export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator };
16
+ export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator, flushBatchProcessor };
@@ -11,5 +11,6 @@ declare const defaultSpanProcessors: SpanProcessor[];
11
11
  declare const defaultContextManager: AsyncLocalStorageContextManager;
12
12
  declare const defaultTextMapPropagator: CompositePropagator;
13
13
  declare const defaultSDK: NodeSDK;
14
+ declare function flushBatchProcessor(): Promise<void>;
14
15
 
15
- export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator };
16
+ export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator, flushBatchProcessor };
@@ -1 +1 @@
1
- export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator } from './chunk-USFUAR3Y.js';
1
+ export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator, flushBatchProcessor } from './chunk-XO4RG36I.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/agents-run-api",
3
- "version": "0.14.3",
3
+ "version": "0.14.5",
4
4
  "description": "Agents Run API for Inkeep Agent Framework - handles chat, agent execution, and streaming",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -51,7 +51,7 @@
51
51
  "traverse": "^0.6.11",
52
52
  "ts-pattern": "^5.7.1",
53
53
  "zod": "^4.1.11",
54
- "@inkeep/agents-core": "^0.14.3"
54
+ "@inkeep/agents-core": "^0.14.5"
55
55
  },
56
56
  "optionalDependencies": {
57
57
  "keytar": "^7.9.0"
@@ -1 +0,0 @@
1
- export { dbClient_default as default } from './chunk-TWVQBIUL.js';