@inkeep/agents-core 0.0.0-dev-20250911192304 → 0.0.0-dev-20250911210702

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
@@ -23,37 +23,13 @@ var ai = require('ai');
23
23
  var exitHook = require('exit-hook');
24
24
  var tsPattern = require('ts-pattern');
25
25
  var zod = require('zod');
26
- var fs = require('fs');
27
- var path = require('path');
28
- var dotenv = require('dotenv');
29
26
  var node = require('@nangohq/node');
30
27
 
31
28
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
32
29
 
33
- function _interopNamespace(e) {
34
- if (e && e.__esModule) return e;
35
- var n = Object.create(null);
36
- if (e) {
37
- Object.keys(e).forEach(function (k) {
38
- if (k !== 'default') {
39
- var d = Object.getOwnPropertyDescriptor(e, k);
40
- Object.defineProperty(n, k, d.get ? d : {
41
- enumerable: true,
42
- get: function () { return e[k]; }
43
- });
44
- }
45
- });
46
- }
47
- n.default = e;
48
- return Object.freeze(n);
49
- }
50
-
51
30
  var jmespath__default = /*#__PURE__*/_interopDefault(jmespath);
52
31
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
53
32
  var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
54
- var fs__default = /*#__PURE__*/_interopDefault(fs);
55
- var path__default = /*#__PURE__*/_interopDefault(path);
56
- var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
57
33
 
58
34
  var __defProp = Object.defineProperty;
59
35
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -99,8 +75,8 @@ var LoggerFactory = class {
99
75
  /**
100
76
  * Configure the logger factory
101
77
  */
102
- configure(config2) {
103
- this.config = config2;
78
+ configure(config) {
79
+ this.config = config;
104
80
  this.loggers.clear();
105
81
  }
106
82
  /**
@@ -133,8 +109,8 @@ var loggerFactory = new LoggerFactory();
133
109
  function getLogger(name) {
134
110
  return loggerFactory.getLogger(name);
135
111
  }
136
- function configureLogging(config2) {
137
- loggerFactory.configure(config2);
112
+ function configureLogging(config) {
113
+ loggerFactory.configure(config);
138
114
  }
139
115
 
140
116
  // src/db/schema.ts
@@ -512,6 +488,7 @@ var agentToolRelations = sqliteCore.sqliteTable(
512
488
  id: sqliteCore.text("id").notNull(),
513
489
  agentId: sqliteCore.text("agent_id").notNull(),
514
490
  toolId: sqliteCore.text("tool_id").notNull(),
491
+ selectedTools: sqliteCore.blob("selected_tools", { mode: "json" }).$type(),
515
492
  createdAt: sqliteCore.text("created_at").notNull().default(drizzleOrm.sql`CURRENT_TIMESTAMP`),
516
493
  updatedAt: sqliteCore.text("updated_at").notNull().default(drizzleOrm.sql`CURRENT_TIMESTAMP`)
517
494
  },
@@ -1378,7 +1355,8 @@ var AgentToolRelationSelectSchema = drizzleZod.createSelectSchema(agentToolRelat
1378
1355
  var AgentToolRelationInsertSchema = drizzleZod.createInsertSchema(agentToolRelations).extend({
1379
1356
  id: resourceIdSchema,
1380
1357
  agentId: resourceIdSchema,
1381
- toolId: resourceIdSchema
1358
+ toolId: resourceIdSchema,
1359
+ selectedTools: zodOpenapi.z.array(zodOpenapi.z.string()).nullish()
1382
1360
  });
1383
1361
  var AgentToolRelationUpdateSchema = AgentToolRelationInsertSchema.partial();
1384
1362
  var AgentToolRelationApiSelectSchema = createApiSchema(AgentToolRelationSelectSchema);
@@ -1412,6 +1390,7 @@ var StatusUpdateSchema = zodOpenapi.z.object({
1412
1390
  });
1413
1391
  var FullGraphAgentInsertSchema = AgentApiInsertSchema.extend({
1414
1392
  tools: zodOpenapi.z.array(zodOpenapi.z.string()),
1393
+ selectedTools: zodOpenapi.z.record(zodOpenapi.z.string(), zodOpenapi.z.array(zodOpenapi.z.string())).optional(),
1415
1394
  dataComponents: zodOpenapi.z.array(zodOpenapi.z.string()).optional(),
1416
1395
  artifactComponents: zodOpenapi.z.array(zodOpenapi.z.string()).optional(),
1417
1396
  canTransferTo: zodOpenapi.z.array(zodOpenapi.z.string()).optional(),
@@ -1833,8 +1812,8 @@ var _TemplateEngine = class _TemplateEngine {
1833
1812
  * Process variable substitutions {{variable.path}} using JMESPath
1834
1813
  */
1835
1814
  static processVariables(template, context, options) {
1836
- return template.replace(/\{\{([^}]+)\}\}/g, (match2, path2) => {
1837
- const trimmedPath = path2.trim();
1815
+ return template.replace(/\{\{([^}]+)\}\}/g, (match2, path) => {
1816
+ const trimmedPath = path.trim();
1838
1817
  try {
1839
1818
  if (trimmedPath.startsWith("$")) {
1840
1819
  return _TemplateEngine.processBuiltinVariable(trimmedPath);
@@ -2164,7 +2143,7 @@ var CredentialStuffer = class {
2164
2143
  /**
2165
2144
  * Build MCP server configuration with credentials
2166
2145
  */
2167
- async buildMcpServerConfig(context, tool2, storeReference) {
2146
+ async buildMcpServerConfig(context, tool2, storeReference, selectedTools) {
2168
2147
  let credentialHeaders = {};
2169
2148
  if (storeReference || tool2.headers) {
2170
2149
  credentialHeaders = await this.getCredentialHeaders({
@@ -2177,7 +2156,8 @@ var CredentialStuffer = class {
2177
2156
  const baseConfig = {
2178
2157
  type: tool2.transport?.type || MCPTransportType.streamableHttp,
2179
2158
  url: tool2.serverUrl,
2180
- activeTools: tool2.activeTools
2159
+ activeTools: tool2.activeTools,
2160
+ selectedTools
2181
2161
  };
2182
2162
  if (baseConfig.type === MCPTransportType.streamableHttp || baseConfig.type === MCPTransportType.sse) {
2183
2163
  const httpConfig = {
@@ -2193,14 +2173,14 @@ var CredentialStuffer = class {
2193
2173
  return baseConfig;
2194
2174
  }
2195
2175
  };
2196
- function createDatabaseClient(config2) {
2176
+ function createDatabaseClient(config) {
2197
2177
  const client$1 = client.createClient({
2198
- url: config2.url,
2199
- authToken: config2.authToken
2178
+ url: config.url,
2179
+ authToken: config.authToken
2200
2180
  });
2201
2181
  return libsql.drizzle(client$1, {
2202
2182
  schema: schema_exports,
2203
- logger: config2.logger
2183
+ logger: config.logger
2204
2184
  });
2205
2185
  }
2206
2186
  function createInMemoryDatabaseClient() {
@@ -2445,7 +2425,8 @@ var createAgentToolRelation = (db) => async (params) => {
2445
2425
  tenantId: params.scopes.tenantId,
2446
2426
  projectId: params.scopes.projectId,
2447
2427
  agentId: params.data.agentId,
2448
- toolId: params.data.toolId
2428
+ toolId: params.data.toolId,
2429
+ selectedTools: params.data.selectedTools
2449
2430
  }).returning();
2450
2431
  return relation[0];
2451
2432
  };
@@ -2600,6 +2581,7 @@ var getToolsForAgent = (db) => async (params) => {
2600
2581
  tenantId: agentToolRelations.tenantId,
2601
2582
  agentId: agentToolRelations.agentId,
2602
2583
  toolId: agentToolRelations.toolId,
2584
+ selectedTools: agentToolRelations.selectedTools,
2603
2585
  createdAt: agentToolRelations.createdAt,
2604
2586
  updatedAt: agentToolRelations.updatedAt,
2605
2587
  tool: {
@@ -2647,6 +2629,7 @@ var getAgentsForTool = (db) => async (params) => {
2647
2629
  tenantId: agentToolRelations.tenantId,
2648
2630
  agentId: agentToolRelations.agentId,
2649
2631
  toolId: agentToolRelations.toolId,
2632
+ selectedTools: agentToolRelations.selectedTools,
2650
2633
  createdAt: agentToolRelations.createdAt,
2651
2634
  updatedAt: agentToolRelations.updatedAt,
2652
2635
  agent: {
@@ -3231,14 +3214,14 @@ var deleteAgentGraph = (db) => async (params) => {
3231
3214
  ).returning();
3232
3215
  return result.length > 0;
3233
3216
  };
3234
- var fetchComponentRelationships = (db) => async (scopes, agentIds, config2) => {
3217
+ var fetchComponentRelationships = (db) => async (scopes, agentIds, config) => {
3235
3218
  const componentsObject = {};
3236
3219
  if (agentIds.length > 0) {
3237
- const results = await db.select(config2.selectFields).from(config2.relationTable).innerJoin(config2.componentTable, drizzleOrm.eq(config2.relationIdField, config2.componentIdField)).where(
3220
+ const results = await db.select(config.selectFields).from(config.relationTable).innerJoin(config.componentTable, drizzleOrm.eq(config.relationIdField, config.componentIdField)).where(
3238
3221
  drizzleOrm.and(
3239
- drizzleOrm.eq(config2.relationTable.tenantId, scopes.tenantId),
3240
- drizzleOrm.eq(config2.relationTable.projectId, scopes.projectId),
3241
- drizzleOrm.inArray(config2.relationTable.agentId, agentIds)
3222
+ drizzleOrm.eq(config.relationTable.tenantId, scopes.tenantId),
3223
+ drizzleOrm.eq(config.relationTable.projectId, scopes.projectId),
3224
+ drizzleOrm.inArray(config.relationTable.agentId, agentIds)
3242
3225
  )
3243
3226
  );
3244
3227
  for (const component of results) {
@@ -3346,7 +3329,8 @@ var getFullGraphDefinition = (db) => async ({
3346
3329
  lastHealthCheck: tools.lastHealthCheck,
3347
3330
  lastError: tools.lastError,
3348
3331
  availableTools: tools.availableTools,
3349
- lastToolsSync: tools.lastToolsSync
3332
+ lastToolsSync: tools.lastToolsSync,
3333
+ selectedTools: agentToolRelations.selectedTools
3350
3334
  }).from(agentToolRelations).innerJoin(tools, drizzleOrm.eq(agentToolRelations.toolId, tools.id)).where(
3351
3335
  drizzleOrm.and(drizzleOrm.eq(agentToolRelations.tenantId, tenantId), drizzleOrm.eq(agentToolRelations.agentId, agentId))
3352
3336
  );
@@ -3366,6 +3350,12 @@ var getFullGraphDefinition = (db) => async ({
3366
3350
  const agentArtifactComponentIds = agentArtifactComponentRelations.map(
3367
3351
  (rel) => rel.artifactComponentId
3368
3352
  );
3353
+ const selectedTools = {};
3354
+ agentTools.forEach((tool2) => {
3355
+ if (tool2.selectedTools && Array.isArray(tool2.selectedTools)) {
3356
+ selectedTools[tool2.id] = tool2.selectedTools;
3357
+ }
3358
+ });
3369
3359
  return {
3370
3360
  id: agent.id,
3371
3361
  name: agent.name,
@@ -3377,6 +3367,7 @@ var getFullGraphDefinition = (db) => async ({
3377
3367
  canDelegateTo,
3378
3368
  dataComponents: agentDataComponentIds,
3379
3369
  artifactComponents: agentArtifactComponentIds,
3370
+ ...Object.keys(selectedTools).length > 0 && { selectedTools },
3380
3371
  tools: agentTools.map((tool2) => ({
3381
3372
  id: tool2.id,
3382
3373
  name: tool2.name,
@@ -3425,14 +3416,19 @@ var getFullGraphDefinition = (db) => async ({
3425
3416
  } else {
3426
3417
  const toolsData = agent.tools || [];
3427
3418
  const toolIds = [];
3419
+ const agentSelectedTools = {};
3428
3420
  for (const tool2 of toolsData) {
3429
3421
  toolsObject[tool2.id] = tool2;
3430
3422
  toolIds.push(tool2.id);
3423
+ if (tool2.selectedTools !== null && tool2.selectedTools !== void 0) {
3424
+ agentSelectedTools[tool2.id] = tool2.selectedTools;
3425
+ }
3431
3426
  }
3432
3427
  agentsObject[agent.id] = {
3433
3428
  ...agent,
3434
- tools: toolIds
3429
+ tools: toolIds,
3435
3430
  // Replace tool objects with tool IDs
3431
+ ...Object.keys(agentSelectedTools).length > 0 && { selectedTools: agentSelectedTools }
3436
3432
  };
3437
3433
  }
3438
3434
  }
@@ -4958,6 +4954,7 @@ var addToolToAgent = (db) => async (params) => {
4958
4954
  projectId: params.scopes.projectId,
4959
4955
  agentId: params.agentId,
4960
4956
  toolId: params.toolId,
4957
+ selectedTools: params.selectedTools,
4961
4958
  createdAt: now,
4962
4959
  updatedAt: now
4963
4960
  }).returning();
@@ -4986,7 +4983,15 @@ var upsertAgentToolRelation = (db) => async (params) => {
4986
4983
  if (!existing) {
4987
4984
  return await addToolToAgent(db)(params);
4988
4985
  }
4989
- return existing;
4986
+ return await updateAgentToolRelation(db)({
4987
+ scopes: params.scopes,
4988
+ relationId: existing.id,
4989
+ data: {
4990
+ agentId: params.agentId,
4991
+ toolId: params.toolId,
4992
+ selectedTools: params.selectedTools
4993
+ }
4994
+ });
4990
4995
  };
4991
4996
  var updateToolStatus = (db) => async (params) => {
4992
4997
  return updateTool(db)({
@@ -5344,11 +5349,13 @@ var createFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
5344
5349
  agentToolPromises.push(
5345
5350
  (async () => {
5346
5351
  try {
5352
+ const selectedTools = agentData.selectedTools?.[toolId];
5347
5353
  logger11.info({ agentId, toolId }, "Processing agent-tool relation");
5348
5354
  await upsertAgentToolRelation(db)({
5349
5355
  scopes: { tenantId, projectId },
5350
5356
  agentId,
5351
- toolId
5357
+ toolId,
5358
+ selectedTools
5352
5359
  });
5353
5360
  logger11.info({ agentId, toolId }, "Agent-tool relation processed successfully");
5354
5361
  } catch (error) {
@@ -5816,11 +5823,13 @@ var updateFullGraphServerSide = (db, logger11 = defaultLogger) => async (scopes,
5816
5823
  agentToolPromises.push(
5817
5824
  (async () => {
5818
5825
  try {
5826
+ const selectedTools = agentData.selectedTools?.[toolId];
5819
5827
  await createAgentToolRelation(db)({
5820
5828
  scopes: { tenantId, projectId },
5821
5829
  data: {
5822
5830
  agentId,
5823
- toolId
5831
+ toolId,
5832
+ selectedTools
5824
5833
  }
5825
5834
  });
5826
5835
  logger11.info({ agentId, toolId }, "Agent-tool relation created");
@@ -6593,8 +6602,8 @@ var tryWellKnownEndpoints = async (baseUrl, logger11) => {
6593
6602
  return null;
6594
6603
  };
6595
6604
  var checkForOAuthEndpoints = async (serverUrl, logger11) => {
6596
- const config2 = await discoverOAuthEndpoints(serverUrl, logger11);
6597
- return config2 !== null;
6605
+ const config = await discoverOAuthEndpoints(serverUrl, logger11);
6606
+ return config !== null;
6598
6607
  };
6599
6608
  var discoverOAuthEndpoints = async (serverUrl, logger11) => {
6600
6609
  try {
@@ -6974,7 +6983,7 @@ var McpClient = class {
6974
6983
  }
6975
6984
  async connect() {
6976
6985
  if (this.connected) return;
6977
- await tsPattern.match(this.serverConfig).with({ type: MCPTransportType.streamableHttp }, (config2) => this.connectHttp(config2)).with({ type: MCPTransportType.sse }, (config2) => this.connectSSE(config2)).exhaustive();
6986
+ await tsPattern.match(this.serverConfig).with({ type: MCPTransportType.streamableHttp }, (config) => this.connectHttp(config)).with({ type: MCPTransportType.sse }, (config) => this.connectSSE(config)).exhaustive();
6978
6987
  this.connected = true;
6979
6988
  const close = this.client.onclose;
6980
6989
  this.client.onclose = () => {
@@ -6986,25 +6995,25 @@ var McpClient = class {
6986
6995
  exitHook.asyncExitHook(() => this.disconnect(), { wait: 5e3 });
6987
6996
  process.on("SIGTERM", () => exitHook.gracefulExit());
6988
6997
  }
6989
- async connectSSE(config2) {
6990
- const url = typeof config2.url === "string" ? config2.url : config2.url.toString();
6998
+ async connectSSE(config) {
6999
+ const url = typeof config.url === "string" ? config.url : config.url.toString();
6991
7000
  this.transport = new sse_js.SSEClientTransport(new URL(url), {
6992
- eventSourceInit: config2.eventSourceInit,
7001
+ eventSourceInit: config.eventSourceInit,
6993
7002
  requestInit: {
6994
- headers: config2.headers || {}
7003
+ headers: config.headers || {}
6995
7004
  }
6996
7005
  });
6997
7006
  await this.client.connect(this.transport, {
6998
- timeout: config2.timeout ?? this.timeout
7007
+ timeout: config.timeout ?? this.timeout
6999
7008
  });
7000
7009
  }
7001
- async connectHttp(config2) {
7002
- const { url, requestInit } = config2;
7010
+ async connectHttp(config) {
7011
+ const { url, requestInit } = config;
7003
7012
  const mergedRequestInit = {
7004
7013
  ...requestInit,
7005
7014
  headers: {
7006
7015
  ...requestInit?.headers || {},
7007
- ...config2.headers || {}
7016
+ ...config.headers || {}
7008
7017
  }
7009
7018
  };
7010
7019
  const urlObj = new URL(url);
@@ -7015,9 +7024,9 @@ var McpClient = class {
7015
7024
  maxReconnectionDelay: 3e4,
7016
7025
  initialReconnectionDelay: 1e3,
7017
7026
  reconnectionDelayGrowFactor: 1.5,
7018
- ...config2.reconnectionOptions
7027
+ ...config.reconnectionOptions
7019
7028
  },
7020
- sessionId: config2.sessionId
7029
+ sessionId: config.sessionId
7021
7030
  });
7022
7031
  await this.client.connect(this.transport, { timeout: 3e3 });
7023
7032
  }
@@ -7044,11 +7053,18 @@ var McpClient = class {
7044
7053
  }
7045
7054
  async selectTools() {
7046
7055
  const { tools: tools2 } = await this.client.listTools({ timeout: this.timeout });
7047
- const { activeTools } = this.serverConfig;
7048
- if (!activeTools) return tools2;
7056
+ const { selectedTools, activeTools } = this.serverConfig;
7057
+ let toolsToFilter;
7058
+ if (selectedTools && selectedTools.length > 0) {
7059
+ toolsToFilter = selectedTools;
7060
+ } else if (activeTools && activeTools.length > 0) {
7061
+ toolsToFilter = activeTools;
7062
+ } else {
7063
+ return tools2;
7064
+ }
7049
7065
  const toolNames = tools2.map((tool2) => tool2.name);
7050
- this.validateSelectedTools(toolNames, activeTools);
7051
- return tools2.filter((tool2) => activeTools.includes(tool2.name));
7066
+ this.validateSelectedTools(toolNames, toolsToFilter);
7067
+ return tools2.filter((tool2) => toolsToFilter.includes(tool2.name));
7052
7068
  }
7053
7069
  async tools() {
7054
7070
  const tools2 = await this.selectTools();
@@ -7114,52 +7130,7 @@ var McpClient = class {
7114
7130
  return results;
7115
7131
  }
7116
7132
  };
7117
- dotenv__namespace.config({ quiet: true });
7118
- var environmentSchema = zod.z.enum(["development", "pentest", "production", "test"]);
7119
- var criticalEnv = zod.z.object({
7120
- ENVIRONMENT: environmentSchema
7121
- }).parse(process.env);
7122
- var loadEnvFile = () => {
7123
- const envPath = path__default.default.resolve(process.cwd(), `.env.${criticalEnv.ENVIRONMENT}.nonsecret`);
7124
- if (fs__default.default.existsSync(envPath)) {
7125
- const envConfig = dotenv__namespace.parse(fs__default.default.readFileSync(envPath));
7126
- for (const k in envConfig) {
7127
- if (!(k in process.env)) {
7128
- process.env[k] = envConfig[k];
7129
- }
7130
- }
7131
- }
7132
- };
7133
- loadEnvFile();
7134
- var envSchema = zod.z.object({
7135
- ENVIRONMENT: zod.z.enum(["development", "production", "pentest", "test"]).optional(),
7136
- DB_FILE_NAME: zod.z.string().default("file:../../local.db"),
7137
- OTEL_TRACES_FORCE_FLUSH_ENABLED: zod.z.stringbool().optional()
7138
- });
7139
- var parseEnv = () => {
7140
- try {
7141
- const parsedEnv = envSchema.parse(process.env);
7142
- return parsedEnv;
7143
- } catch (error) {
7144
- if (error instanceof zod.z.ZodError) {
7145
- const missingVars = error.issues.map((issue) => issue.path.join("."));
7146
- throw new Error(
7147
- `\u274C Invalid environment variables: ${missingVars.join(", ")}
7148
- ${error.message}`
7149
- );
7150
- }
7151
- throw error;
7152
- }
7153
- };
7154
- var env = parseEnv();
7155
-
7156
- // src/utils/tracer.ts
7157
7133
  var logger4 = getLogger("tracer");
7158
- var FORCE_FLUSH_ENVIRONMENTS = ["development"];
7159
- var BASE = "inkeep-chat";
7160
- var SERVICE_NAME = "inkeep-chat";
7161
- var SERVICE_VERSION = "1.0.0";
7162
- var createSpanName = (suffix) => `${BASE}.${suffix}`;
7163
7134
  var createNoOpSpan = () => ({
7164
7135
  setAttributes: () => ({}),
7165
7136
  recordException: () => ({}),
@@ -7188,8 +7159,7 @@ var noopTracer = {
7188
7159
  return createNoOpSpan();
7189
7160
  }
7190
7161
  };
7191
- var globalTracerInstance = null;
7192
- function handleSpanError(span, error, logger11, logMessage) {
7162
+ function setSpanWithError(span, error, logger11, logMessage) {
7193
7163
  const errorMessage = error instanceof Error ? error.message : String(error);
7194
7164
  span.recordException(error);
7195
7165
  span.setStatus({
@@ -7200,45 +7170,21 @@ function handleSpanError(span, error, logger11, logMessage) {
7200
7170
  logger11.error({ error: errorMessage }, logMessage);
7201
7171
  }
7202
7172
  }
7203
- function getGlobalTracer() {
7204
- if (!globalTracerInstance) {
7205
- try {
7206
- globalTracerInstance = api.trace.getTracer(SERVICE_NAME, SERVICE_VERSION);
7207
- } catch (error) {
7208
- logger4.debug(
7209
- { error: error instanceof Error ? error.message : "Unknown error" },
7210
- "OpenTelemetry tracer not available, using no-op tracer"
7211
- );
7212
- globalTracerInstance = noopTracer;
7213
- }
7214
- }
7215
- return globalTracerInstance;
7216
- }
7217
- async function forceFlushTracer() {
7218
- const isOtelTracesForceFlushEnabled = env.OTEL_TRACES_FORCE_FLUSH_ENABLED;
7219
- const isForceFlushEnvironment = env.ENVIRONMENT && FORCE_FLUSH_ENVIRONMENTS.includes(env.ENVIRONMENT);
7220
- const shouldForceFlush = isOtelTracesForceFlushEnabled === true || isOtelTracesForceFlushEnabled == null && isForceFlushEnvironment;
7221
- if (!shouldForceFlush) {
7222
- return;
7223
- }
7173
+ function getTracer(serviceName, serviceVersion) {
7224
7174
  try {
7225
- const tracerProvider = api.trace.getTracerProvider();
7226
- if (tracerProvider && "forceFlush" in tracerProvider && typeof tracerProvider.forceFlush === "function") {
7227
- await tracerProvider.forceFlush();
7228
- logger4.debug(
7229
- { message: "Tracer provider force flush completed" },
7230
- "Tracer provider force flush completed"
7231
- );
7232
- } else {
7233
- logger4.debug(
7234
- { message: "Tracer provider does not support force flush or is not available" },
7235
- "Tracer provider does not support force flush or is not available"
7236
- );
7237
- }
7238
- } catch (error) {
7239
- logger4.warn({ error }, "Failed to force flush tracer");
7175
+ return api.trace.getTracer(serviceName, serviceVersion);
7176
+ } catch (_error) {
7177
+ logger4.debug({}, "OpenTelemetry tracer not available, using no-op tracer");
7178
+ return noopTracer;
7240
7179
  }
7241
7180
  }
7181
+
7182
+ // package.json
7183
+ var package_default = {
7184
+ version: "0.0.0-dev-20250911210702"};
7185
+
7186
+ // src/utils/tracer.ts
7187
+ var tracer = getTracer("agents-core", package_default.version);
7242
7188
  var logger5 = getLogger("context-cache");
7243
7189
  var ContextCache = class {
7244
7190
  constructor(tenantId, projectId, dbClient) {
@@ -7434,7 +7380,6 @@ var ContextCache = class {
7434
7380
 
7435
7381
  // src/context/ContextResolver.ts
7436
7382
  var logger6 = getLogger("context-resolver");
7437
- var tracer = getGlobalTracer();
7438
7383
  var ContextResolver = class {
7439
7384
  constructor(tenantId, projectId, dbClient, credentialStoreRegistry) {
7440
7385
  __publicField(this, "fetcher");
@@ -7467,7 +7412,7 @@ var ContextResolver = class {
7467
7412
  "Starting context resolution"
7468
7413
  );
7469
7414
  return tracer.startActiveSpan(
7470
- createSpanName("context.resolve"),
7415
+ "context.resolve",
7471
7416
  {
7472
7417
  attributes: {
7473
7418
  "context.config_id": contextConfig2.id,
@@ -7619,7 +7564,7 @@ var ContextResolver = class {
7619
7564
  return result;
7620
7565
  } catch (error) {
7621
7566
  const durationMs = Date.now() - startTime;
7622
- handleSpanError(parentSpan, error);
7567
+ setSpanWithError(parentSpan, error);
7623
7568
  logger6.error(
7624
7569
  {
7625
7570
  contextConfigId: contextConfig2.id,
@@ -7640,7 +7585,7 @@ var ContextResolver = class {
7640
7585
  */
7641
7586
  async resolveSingleFetchDefinition(contextConfig2, definition, templateKey, options, requestHash, result) {
7642
7587
  return tracer.startActiveSpan(
7643
- createSpanName("context-resolver.resolve_single_fetch_definition"),
7588
+ "context-resolver.resolve_single_fetch_definition",
7644
7589
  {
7645
7590
  attributes: {
7646
7591
  "context.definition_id": definition.id,
@@ -7725,7 +7670,7 @@ var ContextResolver = class {
7725
7670
  "Context variable resolved and cached"
7726
7671
  );
7727
7672
  } catch (error) {
7728
- handleSpanError(parentSpan, error);
7673
+ setSpanWithError(parentSpan, error);
7729
7674
  throw error;
7730
7675
  } finally {
7731
7676
  parentSpan.end();
@@ -8316,21 +8261,21 @@ var ContextFetcher = class {
8316
8261
  /**
8317
8262
  * Perform HTTP request
8318
8263
  */
8319
- async performRequest(config2) {
8264
+ async performRequest(config) {
8320
8265
  const startTime = Date.now();
8321
8266
  try {
8322
8267
  logger8.debug(
8323
8268
  {
8324
- url: config2.url,
8325
- method: config2.method
8269
+ url: config.url,
8270
+ method: config.method
8326
8271
  },
8327
8272
  "Performing HTTP request"
8328
8273
  );
8329
- const response = await fetch(config2.url, {
8330
- method: config2.method,
8331
- headers: config2.headers,
8332
- body: config2.body ? JSON.stringify(config2.body) : void 0,
8333
- signal: AbortSignal.timeout(config2.timeout || this.defaultTimeout)
8274
+ const response = await fetch(config.url, {
8275
+ method: config.method,
8276
+ headers: config.headers,
8277
+ body: config.body ? JSON.stringify(config.body) : void 0,
8278
+ signal: AbortSignal.timeout(config.timeout || this.defaultTimeout)
8334
8279
  });
8335
8280
  if (!response.ok) {
8336
8281
  const errorText = await response.text();
@@ -8350,7 +8295,7 @@ var ContextFetcher = class {
8350
8295
  }
8351
8296
  return {
8352
8297
  data,
8353
- source: config2.url,
8298
+ source: config.url,
8354
8299
  durationMs
8355
8300
  };
8356
8301
  } catch (error) {
@@ -8358,7 +8303,7 @@ var ContextFetcher = class {
8358
8303
  const requestError = error instanceof Error ? error : new Error("Unknown error");
8359
8304
  logger8.warn(
8360
8305
  {
8361
- url: config2.url,
8306
+ url: config.url,
8362
8307
  error: requestError.message,
8363
8308
  durationMs
8364
8309
  },
@@ -8446,7 +8391,6 @@ var ContextFetcher = class {
8446
8391
  }
8447
8392
  };
8448
8393
  var logger9 = getLogger("context");
8449
- var tracer2 = getGlobalTracer();
8450
8394
  async function determineContextTrigger(tenantId, projectId, conversationId, dbClient) {
8451
8395
  const conversation = await getConversation(dbClient)({
8452
8396
  scopes: { tenantId, projectId },
@@ -8477,8 +8421,8 @@ async function handleContextConfigChange(tenantId, projectId, conversationId, gr
8477
8421
  }
8478
8422
  }
8479
8423
  async function handleContextResolution(tenantId, projectId, conversationId, graphId, requestContext, dbClient, credentialStores) {
8480
- return tracer2.startActiveSpan(
8481
- createSpanName("context.handle_context_resolution"),
8424
+ return tracer.startActiveSpan(
8425
+ "context.handle_context_resolution",
8482
8426
  {
8483
8427
  attributes: {
8484
8428
  "context.request_context_keys": Object.keys(requestContext)
@@ -8553,7 +8497,6 @@ async function handleContextResolution(tenantId, projectId, conversationId, grap
8553
8497
  } else {
8554
8498
  parentSpan.setStatus({ code: api.SpanStatusCode.OK });
8555
8499
  }
8556
- await forceFlushTracer();
8557
8500
  logger9.info(
8558
8501
  {
8559
8502
  conversationId,
@@ -8571,15 +8514,11 @@ async function handleContextResolution(tenantId, projectId, conversationId, grap
8571
8514
  return resolvedContext;
8572
8515
  } catch (error) {
8573
8516
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
8574
- parentSpan.recordException(error);
8575
8517
  parentSpan.setAttributes({
8576
8518
  "context.final_status": "failed",
8577
8519
  "context.error_message": errorMessage
8578
8520
  });
8579
- parentSpan.setStatus({
8580
- code: api.SpanStatusCode.ERROR,
8581
- message: errorMessage
8582
- });
8521
+ setSpanWithError(parentSpan, error);
8583
8522
  logger9.error(
8584
8523
  {
8585
8524
  error: errorMessage,
@@ -8593,7 +8532,6 @@ async function handleContextResolution(tenantId, projectId, conversationId, grap
8593
8532
  },
8594
8533
  "Failed to resolve context, proceeding without context resolution"
8595
8534
  );
8596
- await forceFlushTracer();
8597
8535
  return null;
8598
8536
  } finally {
8599
8537
  parentSpan.end();
@@ -8943,13 +8881,13 @@ function isSupportedAuthMode(mode) {
8943
8881
  return SUPPORTED_AUTH_MODES.includes(mode);
8944
8882
  }
8945
8883
  var NangoCredentialStore = class {
8946
- constructor(id, config2) {
8884
+ constructor(id, config) {
8947
8885
  __publicField(this, "id");
8948
8886
  __publicField(this, "type", CredentialStoreType.nango);
8949
8887
  __publicField(this, "nangoConfig");
8950
8888
  __publicField(this, "nangoClient");
8951
8889
  this.id = id;
8952
- this.nangoConfig = config2;
8890
+ this.nangoConfig = config;
8953
8891
  this.nangoClient = new node.Nango({
8954
8892
  secretKey: this.nangoConfig.secretKey,
8955
8893
  host: this.nangoConfig.apiUrl
@@ -9176,8 +9114,8 @@ var NangoCredentialStore = class {
9176
9114
  }
9177
9115
  }
9178
9116
  };
9179
- function createNangoCredentialStore(id, config2) {
9180
- const nangoSecretKey = config2?.secretKey || process.env.NANGO_SECRET_KEY;
9117
+ function createNangoCredentialStore(id, config) {
9118
+ const nangoSecretKey = config?.secretKey || process.env.NANGO_SECRET_KEY;
9181
9119
  if (!nangoSecretKey || nangoSecretKey === "your_nango_secret_key" || nangoSecretKey.includes("mock")) {
9182
9120
  throw new Error(
9183
9121
  "NANGO_SECRET_KEY environment variable is required and must be a real Nango secret key (not mock/placeholder)"
@@ -9185,7 +9123,7 @@ function createNangoCredentialStore(id, config2) {
9185
9123
  }
9186
9124
  return new NangoCredentialStore(id, {
9187
9125
  apiUrl: "https://api.nango.dev",
9188
- ...config2,
9126
+ ...config,
9189
9127
  secretKey: nangoSecretKey
9190
9128
  });
9191
9129
  }
@@ -9275,7 +9213,6 @@ exports.ArtifactComponentApiUpdateSchema = ArtifactComponentApiUpdateSchema;
9275
9213
  exports.ArtifactComponentInsertSchema = ArtifactComponentInsertSchema;
9276
9214
  exports.ArtifactComponentSelectSchema = ArtifactComponentSelectSchema;
9277
9215
  exports.ArtifactComponentUpdateSchema = ArtifactComponentUpdateSchema;
9278
- exports.BASE = BASE;
9279
9216
  exports.ConsoleLogger = ConsoleLogger;
9280
9217
  exports.ContextCache = ContextCache;
9281
9218
  exports.ContextCacheApiInsertSchema = ContextCacheApiInsertSchema;
@@ -9372,8 +9309,6 @@ exports.ProjectModelSchema = ProjectModelSchema;
9372
9309
  exports.ProjectSelectSchema = ProjectSelectSchema;
9373
9310
  exports.ProjectUpdateSchema = ProjectUpdateSchema;
9374
9311
  exports.RemovedResponseSchema = RemovedResponseSchema;
9375
- exports.SERVICE_NAME = SERVICE_NAME;
9376
- exports.SERVICE_VERSION = SERVICE_VERSION;
9377
9312
  exports.SingleResponseSchema = SingleResponseSchema;
9378
9313
  exports.StatusComponentSchema = StatusComponentSchema;
9379
9314
  exports.StatusUpdateSchema = StatusUpdateSchema;
@@ -9473,7 +9408,6 @@ exports.createMessage = createMessage;
9473
9408
  exports.createNangoCredentialStore = createNangoCredentialStore;
9474
9409
  exports.createOrGetConversation = createOrGetConversation;
9475
9410
  exports.createProject = createProject;
9476
- exports.createSpanName = createSpanName;
9477
9411
  exports.createTask = createTask;
9478
9412
  exports.createTool = createTool;
9479
9413
  exports.createValidatedDataAccess = createValidatedDataAccess;
@@ -9514,7 +9448,6 @@ exports.externalAgentsRelations = externalAgentsRelations;
9514
9448
  exports.extractPublicId = extractPublicId;
9515
9449
  exports.fetchComponentRelationships = fetchComponentRelationships;
9516
9450
  exports.fetchDefinition = fetchDefinition;
9517
- exports.forceFlushTracer = forceFlushTracer;
9518
9451
  exports.generateAndCreateApiKey = generateAndCreateApiKey;
9519
9452
  exports.generateApiKey = generateApiKey;
9520
9453
  exports.generateIdFromName = generateIdFromName;
@@ -9560,7 +9493,6 @@ exports.getExternalAgentByUrl = getExternalAgentByUrl;
9560
9493
  exports.getExternalAgentRelations = getExternalAgentRelations;
9561
9494
  exports.getFullGraph = getFullGraph;
9562
9495
  exports.getFullGraphDefinition = getFullGraphDefinition;
9563
- exports.getGlobalTracer = getGlobalTracer;
9564
9496
  exports.getGraphAgentInfos = getGraphAgentInfos;
9565
9497
  exports.getHealthyToolsForAgent = getHealthyToolsForAgent;
9566
9498
  exports.getLedgerArtifacts = getLedgerArtifacts;
@@ -9577,12 +9509,12 @@ exports.getTask = getTask;
9577
9509
  exports.getToolById = getToolById;
9578
9510
  exports.getToolsByStatus = getToolsByStatus;
9579
9511
  exports.getToolsForAgent = getToolsForAgent;
9512
+ exports.getTracer = getTracer;
9580
9513
  exports.getVisibleMessages = getVisibleMessages;
9581
9514
  exports.graphHasArtifactComponents = graphHasArtifactComponents;
9582
9515
  exports.handleApiError = handleApiError;
9583
9516
  exports.handleContextConfigChange = handleContextConfigChange;
9584
9517
  exports.handleContextResolution = handleContextResolution;
9585
- exports.handleSpanError = handleSpanError;
9586
9518
  exports.hasApiKey = hasApiKey;
9587
9519
  exports.hasContextConfig = hasContextConfig;
9588
9520
  exports.hasCredentialReference = hasCredentialReference;
@@ -9643,6 +9575,7 @@ exports.resourceIdSchema = resourceIdSchema;
9643
9575
  exports.setActiveAgentForConversation = setActiveAgentForConversation;
9644
9576
  exports.setActiveAgentForThread = setActiveAgentForThread;
9645
9577
  exports.setCacheEntry = setCacheEntry;
9578
+ exports.setSpanWithError = setSpanWithError;
9646
9579
  exports.taskRelations = taskRelations;
9647
9580
  exports.taskRelationsRelations = taskRelationsRelations;
9648
9581
  exports.tasks = tasks;