@inkeep/agents-run-api 0.39.3 → 0.39.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.
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ import { convertZodToJsonSchema, isZodSchema } from "@inkeep/agents-core/utils/s
22
22
  import Ajv from "ajv";
23
23
  import { randomUUID } from "crypto";
24
24
  import { z as z$1 } from "zod";
25
+ import { ModelInfoMap } from "llm-info";
25
26
  import { McpServer } from "@alcyone-labs/modelcontextprotocol-sdk/server/mcp.js";
26
27
  import { StreamableHTTPServerTransport } from "@alcyone-labs/modelcontextprotocol-sdk/server/streamableHttp.js";
27
28
  import { toFetchResponse, toReqRes } from "fetch-to-node";
@@ -53,7 +54,7 @@ function createExecutionContext(params) {
53
54
 
54
55
  //#endregion
55
56
  //#region src/middleware/api-key-auth.ts
56
- const logger$24 = getLogger("env-key-auth");
57
+ const logger$25 = getLogger("env-key-auth");
57
58
  /**
58
59
  * Attempts to authenticate using a JWT temporary token
59
60
  * Returns execution context if successful, null if token is invalid or not a JWT
@@ -62,7 +63,7 @@ async function tryAuthenticateWithTempJwt(apiKey, baseUrl, subAgentId) {
62
63
  if (!apiKey.startsWith("eyJ") || !env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY) return null;
63
64
  try {
64
65
  const payload = await verifyTempToken(Buffer.from(env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY, "base64").toString("utf-8"), apiKey);
65
- logger$24.info({}, "JWT temp token authenticated successfully");
66
+ logger$25.info({}, "JWT temp token authenticated successfully");
66
67
  return createExecutionContext({
67
68
  apiKey,
68
69
  tenantId: payload.tenantId,
@@ -74,7 +75,7 @@ async function tryAuthenticateWithTempJwt(apiKey, baseUrl, subAgentId) {
74
75
  metadata: { initiatedBy: payload.initiatedBy }
75
76
  });
76
77
  } catch (error) {
77
- logger$24.debug({ error }, "JWT verification failed");
78
+ logger$25.debug({ error }, "JWT verification failed");
78
79
  return null;
79
80
  }
80
81
  }
@@ -93,7 +94,7 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
93
94
  const reqUrl = new URL(c.req.url);
94
95
  const baseUrl = proto && host ? `${proto}://${host}` : host ? `${reqUrl.protocol}//${host}` : `${reqUrl.origin}`;
95
96
  if (process.env.ENVIRONMENT === "development" || process.env.ENVIRONMENT === "test") {
96
- logger$24.info({}, "development environment");
97
+ logger$25.info({}, "development environment");
97
98
  let executionContext;
98
99
  if (authHeader?.startsWith("Bearer ")) {
99
100
  const apiKey$1 = authHeader.substring(7);
@@ -122,7 +123,7 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
122
123
  subAgentId
123
124
  });
124
125
  c.set("executionContext", executionContext);
125
- logger$24.info({}, "Development/test environment - fallback to default context due to invalid API key");
126
+ logger$25.info({}, "Development/test environment - fallback to default context due to invalid API key");
126
127
  }
127
128
  }
128
129
  } else {
@@ -136,7 +137,7 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
136
137
  subAgentId
137
138
  });
138
139
  c.set("executionContext", executionContext);
139
- logger$24.info({}, "Development/test environment - no API key provided, using default context");
140
+ logger$25.info({}, "Development/test environment - no API key provided, using default context");
140
141
  }
141
142
  await next();
142
143
  return;
@@ -162,7 +163,7 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
162
163
  subAgentId
163
164
  });
164
165
  c.set("executionContext", executionContext);
165
- logger$24.info({}, "Bypass secret authenticated successfully");
166
+ logger$25.info({}, "Bypass secret authenticated successfully");
166
167
  await next();
167
168
  return;
168
169
  }
@@ -171,7 +172,7 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
171
172
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
172
173
  if (subAgentId) executionContext.subAgentId = subAgentId;
173
174
  c.set("executionContext", executionContext);
174
- logger$24.info({}, "API key authenticated successfully");
175
+ logger$25.info({}, "API key authenticated successfully");
175
176
  } catch {
176
177
  const executionContext = await extractContextFromTeamAgentToken(apiKey, baseUrl, subAgentId);
177
178
  c.set("executionContext", executionContext);
@@ -186,7 +187,7 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
186
187
  const executionContext = await extractContextFromApiKey(apiKey, baseUrl);
187
188
  if (subAgentId) executionContext.subAgentId = subAgentId;
188
189
  c.set("executionContext", executionContext);
189
- logger$24.debug({
190
+ logger$25.debug({
190
191
  tenantId: executionContext.tenantId,
191
192
  projectId: executionContext.projectId,
192
193
  agentId: executionContext.agentId,
@@ -200,7 +201,7 @@ const apiKeyAuth = () => createMiddleware(async (c, next) => {
200
201
  await next();
201
202
  } catch (error) {
202
203
  if (error instanceof HTTPException) throw error;
203
- logger$24.error({ error }, "API key authentication error");
204
+ logger$25.error({ error }, "API key authentication error");
204
205
  throw new HTTPException(500, { message: "Authentication failed" });
205
206
  }
206
207
  }
@@ -214,7 +215,7 @@ const extractContextFromApiKey = async (apiKey, baseUrl) => {
214
215
  agentId: apiKeyRecord.agentId
215
216
  } });
216
217
  if (!agent) throw new HTTPException(401, { message: "Invalid or expired API key" });
217
- logger$24.debug({
218
+ logger$25.debug({
218
219
  tenantId: apiKeyRecord.tenantId,
219
220
  projectId: apiKeyRecord.projectId,
220
221
  agentId: apiKeyRecord.agentId,
@@ -237,19 +238,19 @@ const extractContextFromApiKey = async (apiKey, baseUrl) => {
237
238
  const extractContextFromTeamAgentToken = async (token, baseUrl, expectedSubAgentId) => {
238
239
  const result = await verifyServiceToken(token);
239
240
  if (!result.valid || !result.payload) {
240
- logger$24.warn({ error: result.error }, "Invalid team agent JWT token");
241
+ logger$25.warn({ error: result.error }, "Invalid team agent JWT token");
241
242
  throw new HTTPException(401, { message: `Invalid team agent token: ${result.error || "Unknown error"}` });
242
243
  }
243
244
  const payload = result.payload;
244
245
  if (expectedSubAgentId && !validateTargetAgent(payload, expectedSubAgentId)) {
245
- logger$24.error({
246
+ logger$25.error({
246
247
  tokenTargetAgentId: payload.aud,
247
248
  expectedSubAgentId,
248
249
  originAgentId: payload.sub
249
250
  }, "Team agent token target mismatch");
250
251
  throw new HTTPException(403, { message: "Token not valid for the requested agent" });
251
252
  }
252
- logger$24.info({
253
+ logger$25.info({
253
254
  originAgentId: payload.sub,
254
255
  targetAgentId: payload.aud,
255
256
  tenantId: payload.tenantId,
@@ -322,7 +323,7 @@ function setupOpenAPIRoutes(app$5) {
322
323
 
323
324
  //#endregion
324
325
  //#region src/a2a/handlers.ts
325
- const logger$23 = getLogger("a2aHandler");
326
+ const logger$24 = getLogger("a2aHandler");
326
327
  async function a2aHandler(c, agent) {
327
328
  try {
328
329
  const rpcRequest = c.get("requestBody");
@@ -403,14 +404,14 @@ async function handleMessageSend(c, agent, request) {
403
404
  messageId: task.id,
404
405
  kind: "message"
405
406
  });
406
- logger$23.warn({
407
+ logger$24.warn({
407
408
  taskId: task.id,
408
409
  subAgentId: agent.subAgentId,
409
410
  originalMessage: params.message
410
411
  }, "Created fallback message content for empty delegation message");
411
412
  }
412
413
  } catch (error) {
413
- logger$23.error({
414
+ logger$24.error({
414
415
  error,
415
416
  taskId: task.id
416
417
  }, "Failed to serialize message");
@@ -424,7 +425,7 @@ async function handleMessageSend(c, agent, request) {
424
425
  }]
425
426
  });
426
427
  }
427
- logger$23.info({
428
+ logger$24.info({
428
429
  originalContextId: params.message.contextId,
429
430
  taskContextId: task.context?.conversationId,
430
431
  metadataContextId: params.message.metadata?.conversationId,
@@ -451,7 +452,7 @@ async function handleMessageSend(c, agent, request) {
451
452
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
452
453
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
453
454
  });
454
- logger$23.info({ metadata: params.message.metadata }, "message metadata");
455
+ logger$24.info({ metadata: params.message.metadata }, "message metadata");
455
456
  if (params.message.metadata?.fromSubAgentId || params.message.metadata?.fromExternalAgentId || params.message.metadata?.fromTeamAgentId) {
456
457
  const messageText = params.message.parts.filter((part) => part.kind === "text" && "text" in part && part.text).map((part) => part.text).join(" ");
457
458
  try {
@@ -477,7 +478,7 @@ async function handleMessageSend(c, agent, request) {
477
478
  messageData.toTeamAgentId = agent.subAgentId;
478
479
  }
479
480
  await createMessage(dbClient_default)(messageData);
480
- logger$23.info({
481
+ logger$24.info({
481
482
  fromSubAgentId: params.message.metadata.fromSubAgentId,
482
483
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
483
484
  fromTeamAgentId: params.message.metadata.fromTeamAgentId,
@@ -488,7 +489,7 @@ async function handleMessageSend(c, agent, request) {
488
489
  taskId: task.id
489
490
  }, "A2A message stored in database");
490
491
  } catch (error) {
491
- logger$23.error({
492
+ logger$24.error({
492
493
  error,
493
494
  fromSubAgentId: params.message.metadata.fromSubAgentId,
494
495
  fromExternalAgentId: params.message.metadata.fromExternalAgentId,
@@ -517,7 +518,7 @@ async function handleMessageSend(c, agent, request) {
517
518
  if (transferArtifact) {
518
519
  const transferPart = transferArtifact.parts?.find((part) => part.kind === "data" && part.data && typeof part.data === "object" && part.data.type === "transfer");
519
520
  if (transferPart && transferPart.kind === "data" && transferPart.data) {
520
- logger$23.info({ transferPart }, "transferPart");
521
+ logger$24.info({ transferPart }, "transferPart");
521
522
  return c.json({
522
523
  jsonrpc: "2.0",
523
524
  result: {
@@ -875,7 +876,7 @@ async function handleTasksResubscribe(c, agent, request) {
875
876
 
876
877
  //#endregion
877
878
  //#region src/agents/ToolSessionManager.ts
878
- const logger$22 = getLogger("ToolSessionManager");
879
+ const logger$23 = getLogger("ToolSessionManager");
879
880
  /**
880
881
  * Manages tool execution state during agent generation sessions.
881
882
  * Allows tools to access previous tool call results within the same execution.
@@ -911,7 +912,7 @@ var ToolSessionManager = class ToolSessionManager {
911
912
  createdAt: Date.now()
912
913
  };
913
914
  this.sessions.set(sessionId, session);
914
- logger$22.debug({
915
+ logger$23.debug({
915
916
  sessionId,
916
917
  tenantId,
917
918
  contextId,
@@ -926,10 +927,10 @@ var ToolSessionManager = class ToolSessionManager {
926
927
  */
927
928
  ensureAgentSession(sessionId, tenantId, projectId, contextId, taskId) {
928
929
  if (this.sessions.has(sessionId)) {
929
- logger$22.debug({ sessionId }, "Agent session already exists, reusing");
930
+ logger$23.debug({ sessionId }, "Agent session already exists, reusing");
930
931
  return sessionId;
931
932
  }
932
- logger$22.debug({
933
+ logger$23.debug({
933
934
  sessionId,
934
935
  tenantId,
935
936
  contextId,
@@ -943,7 +944,7 @@ var ToolSessionManager = class ToolSessionManager {
943
944
  recordToolResult(sessionId, toolResult) {
944
945
  const session = this.sessions.get(sessionId);
945
946
  if (!session) {
946
- logger$22.warn({
947
+ logger$23.warn({
947
948
  sessionId,
948
949
  toolCallId: toolResult.toolCallId,
949
950
  availableSessionIds: Array.from(this.sessions.keys()),
@@ -952,7 +953,7 @@ var ToolSessionManager = class ToolSessionManager {
952
953
  return;
953
954
  }
954
955
  session.toolResults.set(toolResult.toolCallId, toolResult);
955
- logger$22.debug({
956
+ logger$23.debug({
956
957
  sessionId,
957
958
  toolCallId: toolResult.toolCallId,
958
959
  toolName: toolResult.toolName
@@ -964,7 +965,7 @@ var ToolSessionManager = class ToolSessionManager {
964
965
  getToolResult(sessionId, toolCallId) {
965
966
  const session = this.sessions.get(sessionId);
966
967
  if (!session) {
967
- logger$22.warn({
968
+ logger$23.warn({
968
969
  sessionId,
969
970
  toolCallId,
970
971
  availableSessionIds: Array.from(this.sessions.keys()),
@@ -973,13 +974,13 @@ var ToolSessionManager = class ToolSessionManager {
973
974
  return;
974
975
  }
975
976
  const result = session.toolResults.get(toolCallId);
976
- if (!result) logger$22.warn({
977
+ if (!result) logger$23.warn({
977
978
  sessionId,
978
979
  toolCallId,
979
980
  availableToolResultIds: Array.from(session.toolResults.keys()),
980
981
  totalToolResults: session.toolResults.size
981
982
  }, "Tool result not found");
982
- else logger$22.debug({
983
+ else logger$23.debug({
983
984
  sessionId,
984
985
  toolCallId,
985
986
  toolName: result.toolName
@@ -1007,9 +1008,9 @@ var ToolSessionManager = class ToolSessionManager {
1007
1008
  for (const [sessionId, session] of this.sessions.entries()) if (now - session.createdAt > SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS) expiredSessions.push(sessionId);
1008
1009
  for (const sessionId of expiredSessions) {
1009
1010
  this.sessions.delete(sessionId);
1010
- logger$22.debug({ sessionId }, "Cleaned up expired tool session");
1011
+ logger$23.debug({ sessionId }, "Cleaned up expired tool session");
1011
1012
  }
1012
- if (expiredSessions.length > 0) logger$22.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1013
+ if (expiredSessions.length > 0) logger$23.info({ expiredCount: expiredSessions.length }, "Cleaned up expired tool sessions");
1013
1014
  }
1014
1015
  };
1015
1016
  const toolSessionManager = ToolSessionManager.getInstance();
@@ -1070,7 +1071,7 @@ const tracer = getTracer("agents-run-api");
1070
1071
 
1071
1072
  //#endregion
1072
1073
  //#region src/utils/schema-validation.ts
1073
- const logger$21 = getLogger("SchemaValidation");
1074
+ const logger$22 = getLogger("SchemaValidation");
1074
1075
  const ajv = new Ajv({
1075
1076
  allErrors: true,
1076
1077
  strict: false
@@ -1112,7 +1113,7 @@ function extractFullFields(schema) {
1112
1113
 
1113
1114
  //#endregion
1114
1115
  //#region src/services/ArtifactService.ts
1115
- const logger$20 = getLogger("ArtifactService");
1116
+ const logger$21 = getLogger("ArtifactService");
1116
1117
  /**
1117
1118
  * Service class responsible for artifact business logic operations
1118
1119
  * Handles database persistence, tool result extraction, and artifact management
@@ -1146,7 +1147,7 @@ var ArtifactService = class ArtifactService {
1146
1147
  for (const taskId of taskIds) {
1147
1148
  const task = await getTask(dbClient_default)({ id: taskId });
1148
1149
  if (!task) {
1149
- logger$20.warn({ taskId }, "Task not found when fetching artifacts");
1150
+ logger$21.warn({ taskId }, "Task not found when fetching artifacts");
1150
1151
  continue;
1151
1152
  }
1152
1153
  const taskArtifacts = await getLedgerArtifacts(dbClient_default)({
@@ -1167,7 +1168,7 @@ var ArtifactService = class ArtifactService {
1167
1168
  }
1168
1169
  }
1169
1170
  } catch (error) {
1170
- logger$20.error({
1171
+ logger$21.error({
1171
1172
  error,
1172
1173
  contextId
1173
1174
  }, "Error loading context artifacts");
@@ -1179,12 +1180,12 @@ var ArtifactService = class ArtifactService {
1179
1180
  */
1180
1181
  async createArtifact(request, subAgentId) {
1181
1182
  if (!this.context.sessionId) {
1182
- logger$20.warn({ request }, "No session ID available for artifact creation");
1183
+ logger$21.warn({ request }, "No session ID available for artifact creation");
1183
1184
  return null;
1184
1185
  }
1185
1186
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
1186
1187
  if (!toolResult) {
1187
- logger$20.warn({
1188
+ logger$21.warn({
1188
1189
  request,
1189
1190
  sessionId: this.context.sessionId
1190
1191
  }, "Tool result not found for artifact");
@@ -1196,7 +1197,7 @@ var ArtifactService = class ArtifactService {
1196
1197
  let selectedData = jmespath.search(toolResultData, sanitizedBaseSelector);
1197
1198
  if (Array.isArray(selectedData)) selectedData = selectedData.length > 0 ? selectedData[0] : {};
1198
1199
  if (!selectedData) {
1199
- logger$20.warn({
1200
+ logger$21.warn({
1200
1201
  request,
1201
1202
  baseSelector: request.baseSelector
1202
1203
  }, "Base selector returned no data - using empty object as fallback");
@@ -1232,7 +1233,7 @@ var ArtifactService = class ArtifactService {
1232
1233
  await this.cacheArtifact(request.artifactId, request.toolCallId, artifactData, cleanedFullData);
1233
1234
  return artifactData;
1234
1235
  } catch (error) {
1235
- logger$20.error({
1236
+ logger$21.error({
1236
1237
  error,
1237
1238
  request
1238
1239
  }, "Failed to create artifact");
@@ -1259,7 +1260,7 @@ var ArtifactService = class ArtifactService {
1259
1260
  }
1260
1261
  try {
1261
1262
  if (!this.context.projectId || !this.context.taskId) {
1262
- logger$20.warn({
1263
+ logger$21.warn({
1263
1264
  artifactId,
1264
1265
  toolCallId
1265
1266
  }, "No projectId or taskId available for artifact lookup");
@@ -1285,7 +1286,7 @@ var ArtifactService = class ArtifactService {
1285
1286
  });
1286
1287
  if (artifacts.length > 0) return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
1287
1288
  } catch (error) {
1288
- logger$20.warn({
1289
+ logger$21.warn({
1289
1290
  artifactId,
1290
1291
  toolCallId,
1291
1292
  taskId: this.context.taskId,
@@ -1313,7 +1314,7 @@ var ArtifactService = class ArtifactService {
1313
1314
  }
1314
1315
  try {
1315
1316
  if (!this.context.projectId || !this.context.taskId) {
1316
- logger$20.warn({
1317
+ logger$21.warn({
1317
1318
  artifactId,
1318
1319
  toolCallId
1319
1320
  }, "No projectId or taskId available for artifact lookup");
@@ -1339,7 +1340,7 @@ var ArtifactService = class ArtifactService {
1339
1340
  });
1340
1341
  if (artifacts.length > 0) return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
1341
1342
  } catch (error) {
1342
- logger$20.warn({
1343
+ logger$21.warn({
1343
1344
  artifactId,
1344
1345
  toolCallId,
1345
1346
  taskId: this.context.taskId,
@@ -1358,7 +1359,7 @@ var ArtifactService = class ArtifactService {
1358
1359
  data = artifact.parts?.[0]?.data;
1359
1360
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1360
1361
  dataSource = "parts[0].data (fallback)";
1361
- logger$20.debug({
1362
+ logger$21.debug({
1362
1363
  artifactId,
1363
1364
  toolCallId,
1364
1365
  dataSource
@@ -1367,7 +1368,7 @@ var ArtifactService = class ArtifactService {
1367
1368
  data = artifact.data;
1368
1369
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1369
1370
  dataSource = "artifact.data (fallback)";
1370
- logger$20.debug({
1371
+ logger$21.debug({
1371
1372
  artifactId,
1372
1373
  toolCallId,
1373
1374
  dataSource
@@ -1375,7 +1376,7 @@ var ArtifactService = class ArtifactService {
1375
1376
  } else {
1376
1377
  data = {};
1377
1378
  dataSource = "empty (no data found)";
1378
- logger$20.warn({
1379
+ logger$21.warn({
1379
1380
  artifactId,
1380
1381
  toolCallId,
1381
1382
  artifactStructure: {
@@ -1409,7 +1410,7 @@ var ArtifactService = class ArtifactService {
1409
1410
  data = artifact.parts?.[0]?.data;
1410
1411
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1411
1412
  dataSource = "parts[0].data (fallback)";
1412
- logger$20.debug({
1413
+ logger$21.debug({
1413
1414
  artifactId,
1414
1415
  toolCallId,
1415
1416
  dataSource
@@ -1418,7 +1419,7 @@ var ArtifactService = class ArtifactService {
1418
1419
  data = artifact.data;
1419
1420
  if (data && !(typeof data === "object" && Object.keys(data).length === 0)) {
1420
1421
  dataSource = "artifact.data (fallback)";
1421
- logger$20.debug({
1422
+ logger$21.debug({
1422
1423
  artifactId,
1423
1424
  toolCallId,
1424
1425
  dataSource
@@ -1426,7 +1427,7 @@ var ArtifactService = class ArtifactService {
1426
1427
  } else {
1427
1428
  data = {};
1428
1429
  dataSource = "empty (no data found)";
1429
- logger$20.warn({
1430
+ logger$21.warn({
1430
1431
  artifactId,
1431
1432
  toolCallId,
1432
1433
  artifactStructure: {
@@ -1474,7 +1475,7 @@ var ArtifactService = class ArtifactService {
1474
1475
  const fullValidation = validateAgainstSchema(fullData, fullSchema);
1475
1476
  if (!summaryValidation.hasRequiredFields) {
1476
1477
  `${summaryValidation.missingRequired.join(", ")}${artifactType}${summaryValidation.missingRequired.join(", ")}${summaryValidation.actualFields.join(", ")}`;
1477
- logger$20.error({
1478
+ logger$21.error({
1478
1479
  artifactId,
1479
1480
  artifactType,
1480
1481
  requiredFields: summaryValidation.missingRequired,
@@ -1487,7 +1488,7 @@ var ArtifactService = class ArtifactService {
1487
1488
  schemaFound: !!previewSchema
1488
1489
  };
1489
1490
  }
1490
- if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) logger$20.warn({
1491
+ if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) logger$21.warn({
1491
1492
  artifactId,
1492
1493
  artifactType,
1493
1494
  dataType: "summary",
@@ -1496,7 +1497,7 @@ var ArtifactService = class ArtifactService {
1496
1497
  missingFields: summaryValidation.missingFields,
1497
1498
  extraFields: summaryValidation.extraFields
1498
1499
  }, "Summary data structure does not match preview schema");
1499
- if (!fullValidation.hasExpectedFields || fullValidation.extraFields.length > 0) logger$20.warn({
1500
+ if (!fullValidation.hasExpectedFields || fullValidation.extraFields.length > 0) logger$21.warn({
1500
1501
  artifactId,
1501
1502
  artifactType,
1502
1503
  dataType: "full",
@@ -1557,7 +1558,7 @@ var ArtifactService = class ArtifactService {
1557
1558
  contextId: this.context.contextId,
1558
1559
  pendingGeneration: true
1559
1560
  });
1560
- else logger$20.warn({
1561
+ else logger$21.warn({
1561
1562
  artifactId: request.artifactId,
1562
1563
  hasStreamRequestId: !!this.context.streamRequestId,
1563
1564
  hasAgentId: !!effectiveAgentId,
@@ -1615,7 +1616,7 @@ var ArtifactService = class ArtifactService {
1615
1616
  summaryData = this.filterBySchema(artifact.data, previewSchema);
1616
1617
  fullData = this.filterBySchema(artifact.data, fullSchema);
1617
1618
  } catch (error) {
1618
- logger$20.warn({
1619
+ logger$21.warn({
1619
1620
  artifactType: artifact.type,
1620
1621
  error: error instanceof Error ? error.message : "Unknown error"
1621
1622
  }, "Failed to extract preview/full fields from schema, using full data for both");
@@ -1646,7 +1647,7 @@ var ArtifactService = class ArtifactService {
1646
1647
  toolCallId: artifact.toolCallId,
1647
1648
  artifact: artifactToSave
1648
1649
  });
1649
- if (!result.created && result.existing) logger$20.debug({
1650
+ if (!result.created && result.existing) logger$21.debug({
1650
1651
  artifactId: artifact.artifactId,
1651
1652
  taskId: this.context.taskId
1652
1653
  }, "Artifact already exists, skipping duplicate creation");
@@ -1692,7 +1693,7 @@ var ArtifactService = class ArtifactService {
1692
1693
  } else rawValue = item[fieldName];
1693
1694
  if (rawValue !== null && rawValue !== void 0) extracted[fieldName] = this.cleanEscapedContent(rawValue);
1694
1695
  } catch (error) {
1695
- logger$20.warn({
1696
+ logger$21.warn({
1696
1697
  fieldName,
1697
1698
  error: error instanceof Error ? error.message : "Unknown error"
1698
1699
  }, "Failed to extract schema field");
@@ -1714,7 +1715,7 @@ var ArtifactService = class ArtifactService {
1714
1715
 
1715
1716
  //#endregion
1716
1717
  //#region src/services/ArtifactParser.ts
1717
- const logger$19 = getLogger("ArtifactParser");
1718
+ const logger$20 = getLogger("ArtifactParser");
1718
1719
  /**
1719
1720
  * Artifact parser focused on parsing and text processing responsibilities
1720
1721
  * Delegates business logic operations to ArtifactService
@@ -1807,7 +1808,7 @@ var ArtifactParser = class ArtifactParser {
1807
1808
  attrs[key] = value;
1808
1809
  }
1809
1810
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
1810
- logger$19.warn({
1811
+ logger$20.warn({
1811
1812
  attrs,
1812
1813
  attrString
1813
1814
  }, "Missing required attributes in artifact annotation");
@@ -1866,7 +1867,7 @@ var ArtifactParser = class ArtifactParser {
1866
1867
  else if (annotation.raw) {
1867
1868
  failedAnnotations.push(`Failed to create artifact "${annotation.artifactId}": Missing or invalid data`);
1868
1869
  processedText = processedText.replace(annotation.raw, "");
1869
- logger$19.warn({
1870
+ logger$20.warn({
1870
1871
  annotation,
1871
1872
  artifactData
1872
1873
  }, "Removed failed artifact:create annotation from output");
@@ -1875,12 +1876,12 @@ var ArtifactParser = class ArtifactParser {
1875
1876
  const errorMsg = error instanceof Error ? error.message : "Unknown error";
1876
1877
  failedAnnotations.push(`Failed to create artifact "${annotation.artifactId}": ${errorMsg}`);
1877
1878
  if (annotation.raw) processedText = processedText.replace(annotation.raw, "");
1878
- logger$19.error({
1879
+ logger$20.error({
1879
1880
  annotation,
1880
1881
  error
1881
1882
  }, "Failed to extract artifact from create annotation");
1882
1883
  }
1883
- if (failedAnnotations.length > 0) logger$19.warn({
1884
+ if (failedAnnotations.length > 0) logger$20.warn({
1884
1885
  failedCount: failedAnnotations.length,
1885
1886
  failures: failedAnnotations
1886
1887
  }, "Some artifact creation attempts failed");
@@ -2048,7 +2049,7 @@ var ArtifactParser = class ArtifactParser {
2048
2049
 
2049
2050
  //#endregion
2050
2051
  //#region src/services/AgentSession.ts
2051
- const logger$18 = getLogger("AgentSession");
2052
+ const logger$19 = getLogger("AgentSession");
2052
2053
  /**
2053
2054
  * Tracks all agent operations and interactions for a single message
2054
2055
  * Now includes intelligent status update functionality
@@ -2077,7 +2078,7 @@ var AgentSession = class {
2077
2078
  this.tenantId = tenantId;
2078
2079
  this.projectId = projectId;
2079
2080
  this.contextId = contextId;
2080
- logger$18.debug({
2081
+ logger$19.debug({
2081
2082
  sessionId,
2082
2083
  messageId,
2083
2084
  agentId
@@ -2107,7 +2108,7 @@ var AgentSession = class {
2107
2108
  */
2108
2109
  enableEmitOperations() {
2109
2110
  this.isEmitOperations = true;
2110
- logger$18.info({ sessionId: this.sessionId }, "🔍 DEBUG: Emit operations enabled for AgentSession");
2111
+ logger$19.info({ sessionId: this.sessionId }, "🔍 DEBUG: Emit operations enabled for AgentSession");
2111
2112
  }
2112
2113
  /**
2113
2114
  * Send data operation to stream when emit operations is enabled
@@ -2128,7 +2129,7 @@ var AgentSession = class {
2128
2129
  await streamHelper.writeOperation(formattedOperation);
2129
2130
  }
2130
2131
  } catch (error) {
2131
- logger$18.error({
2132
+ logger$19.error({
2132
2133
  sessionId: this.sessionId,
2133
2134
  eventType: event.eventType,
2134
2135
  error: error instanceof Error ? error.message : error
@@ -2176,7 +2177,7 @@ var AgentSession = class {
2176
2177
  if (this.statusUpdateState.config.timeInSeconds) {
2177
2178
  this.statusUpdateTimer = setInterval(async () => {
2178
2179
  if (!this.statusUpdateState || this.isEnded) {
2179
- logger$18.debug({ sessionId: this.sessionId }, "Timer triggered but session already cleaned up or ended");
2180
+ logger$19.debug({ sessionId: this.sessionId }, "Timer triggered but session already cleaned up or ended");
2180
2181
  if (this.statusUpdateTimer) {
2181
2182
  clearInterval(this.statusUpdateTimer);
2182
2183
  this.statusUpdateTimer = void 0;
@@ -2185,7 +2186,7 @@ var AgentSession = class {
2185
2186
  }
2186
2187
  await this.checkAndSendTimeBasedUpdate();
2187
2188
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2188
- logger$18.info({
2189
+ logger$19.info({
2189
2190
  sessionId: this.sessionId,
2190
2191
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
2191
2192
  }, "Time-based status update timer started");
@@ -2206,7 +2207,7 @@ var AgentSession = class {
2206
2207
  this.sendDataOperation(dataOpEvent);
2207
2208
  }
2208
2209
  if (this.isEnded) {
2209
- logger$18.debug({
2210
+ logger$19.debug({
2210
2211
  sessionId: this.sessionId,
2211
2212
  eventType,
2212
2213
  subAgentId
@@ -2225,7 +2226,7 @@ var AgentSession = class {
2225
2226
  if (artifactData.pendingGeneration) {
2226
2227
  const artifactId = artifactData.artifactId;
2227
2228
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2228
- logger$18.warn({
2229
+ logger$19.warn({
2229
2230
  sessionId: this.sessionId,
2230
2231
  artifactId,
2231
2232
  pendingCount: this.pendingArtifacts.size,
@@ -2247,7 +2248,7 @@ var AgentSession = class {
2247
2248
  this.artifactProcessingErrors.set(artifactId, errorCount);
2248
2249
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2249
2250
  this.pendingArtifacts.delete(artifactId);
2250
- logger$18.error({
2251
+ logger$19.error({
2251
2252
  sessionId: this.sessionId,
2252
2253
  artifactId,
2253
2254
  errorCount,
@@ -2255,7 +2256,7 @@ var AgentSession = class {
2255
2256
  error: error instanceof Error ? error.message : "Unknown error",
2256
2257
  stack: error instanceof Error ? error.stack : void 0
2257
2258
  }, "Artifact processing failed after max retries, giving up");
2258
- } else logger$18.warn({
2259
+ } else logger$19.warn({
2259
2260
  sessionId: this.sessionId,
2260
2261
  artifactId,
2261
2262
  errorCount,
@@ -2272,11 +2273,11 @@ var AgentSession = class {
2272
2273
  */
2273
2274
  checkStatusUpdates() {
2274
2275
  if (this.isEnded) {
2275
- logger$18.debug({ sessionId: this.sessionId }, "Session has ended - skipping status update check");
2276
+ logger$19.debug({ sessionId: this.sessionId }, "Session has ended - skipping status update check");
2276
2277
  return;
2277
2278
  }
2278
2279
  if (!this.statusUpdateState) {
2279
- logger$18.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2280
+ logger$19.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2280
2281
  return;
2281
2282
  }
2282
2283
  const statusUpdateState = this.statusUpdateState;
@@ -2287,18 +2288,18 @@ var AgentSession = class {
2287
2288
  */
2288
2289
  async checkAndSendTimeBasedUpdate() {
2289
2290
  if (this.isEnded) {
2290
- logger$18.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2291
+ logger$19.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2291
2292
  return;
2292
2293
  }
2293
2294
  if (!this.statusUpdateState) {
2294
- logger$18.debug({ sessionId: this.sessionId }, "No status updates configured for time-based check");
2295
+ logger$19.debug({ sessionId: this.sessionId }, "No status updates configured for time-based check");
2295
2296
  return;
2296
2297
  }
2297
2298
  if (this.events.length - this.statusUpdateState.lastEventCount === 0) return;
2298
2299
  try {
2299
2300
  await this.generateAndSendUpdate();
2300
2301
  } catch (error) {
2301
- logger$18.error({
2302
+ logger$19.error({
2302
2303
  sessionId: this.sessionId,
2303
2304
  error: error instanceof Error ? error.message : "Unknown error"
2304
2305
  }, "Failed to send time-based status update");
@@ -2372,7 +2373,7 @@ var AgentSession = class {
2372
2373
  const maxWaitTime = 1e4;
2373
2374
  const startTime = Date.now();
2374
2375
  while (this.pendingArtifacts.size > 0 && Date.now() - startTime < maxWaitTime) await new Promise((resolve) => setTimeout(resolve, 100));
2375
- if (this.pendingArtifacts.size > 0) logger$18.warn({
2376
+ if (this.pendingArtifacts.size > 0) logger$19.warn({
2376
2377
  sessionId: this.sessionId,
2377
2378
  pendingCount: this.pendingArtifacts.size,
2378
2379
  pendingIds: Array.from(this.pendingArtifacts)
@@ -2396,23 +2397,23 @@ var AgentSession = class {
2396
2397
  */
2397
2398
  async generateAndSendUpdate() {
2398
2399
  if (this.isEnded) {
2399
- logger$18.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2400
+ logger$19.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2400
2401
  return;
2401
2402
  }
2402
2403
  if (this.isTextStreaming) {
2403
- logger$18.debug({ sessionId: this.sessionId }, "Text is currently streaming - skipping status update");
2404
+ logger$19.debug({ sessionId: this.sessionId }, "Text is currently streaming - skipping status update");
2404
2405
  return;
2405
2406
  }
2406
2407
  if (this.isGeneratingUpdate) {
2407
- logger$18.debug({ sessionId: this.sessionId }, "Update already in progress - skipping duplicate generation");
2408
+ logger$19.debug({ sessionId: this.sessionId }, "Update already in progress - skipping duplicate generation");
2408
2409
  return;
2409
2410
  }
2410
2411
  if (!this.statusUpdateState) {
2411
- logger$18.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2412
+ logger$19.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2412
2413
  return;
2413
2414
  }
2414
2415
  if (!this.agentId) {
2415
- logger$18.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
2416
+ logger$19.warn({ sessionId: this.sessionId }, "No agent ID - cannot generate update");
2416
2417
  return;
2417
2418
  }
2418
2419
  if (this.events.length - this.statusUpdateState.lastEventCount === 0) return;
@@ -2421,7 +2422,7 @@ var AgentSession = class {
2421
2422
  try {
2422
2423
  const streamHelper = getStreamHelper(this.sessionId);
2423
2424
  if (!streamHelper) {
2424
- logger$18.warn({ sessionId: this.sessionId }, "No stream helper found - cannot send status update");
2425
+ logger$19.warn({ sessionId: this.sessionId }, "No stream helper found - cannot send status update");
2425
2426
  this.isGeneratingUpdate = false;
2426
2427
  return;
2427
2428
  }
@@ -2432,7 +2433,7 @@ var AgentSession = class {
2432
2433
  if (result.summaries && result.summaries.length > 0) {
2433
2434
  for (const summary of result.summaries) {
2434
2435
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
2435
- logger$18.warn({
2436
+ logger$19.warn({
2436
2437
  sessionId: this.sessionId,
2437
2438
  summary
2438
2439
  }, "Skipping empty or invalid structured operation");
@@ -2462,7 +2463,7 @@ var AgentSession = class {
2462
2463
  this.statusUpdateState.lastEventCount = this.events.length;
2463
2464
  }
2464
2465
  } catch (error) {
2465
- logger$18.error({
2466
+ logger$19.error({
2466
2467
  sessionId: this.sessionId,
2467
2468
  error: error instanceof Error ? error.message : "Unknown error",
2468
2469
  stack: error instanceof Error ? error.stack : void 0
@@ -2488,7 +2489,7 @@ var AgentSession = class {
2488
2489
  this.releaseUpdateLock();
2489
2490
  }
2490
2491
  } catch (error) {
2491
- logger$18.error({
2492
+ logger$19.error({
2492
2493
  sessionId: this.sessionId,
2493
2494
  error: error instanceof Error ? error.message : "Unknown error"
2494
2495
  }, "Failed to check status updates during event recording");
@@ -2545,7 +2546,7 @@ var AgentSession = class {
2545
2546
  });
2546
2547
  conversationContext = conversationHistory.trim() ? `\nUser's Question/Context:\n${conversationHistory}\n` : "";
2547
2548
  } catch (error) {
2548
- logger$18.warn({
2549
+ logger$19.warn({
2549
2550
  sessionId: this.sessionId,
2550
2551
  error
2551
2552
  }, "Failed to fetch conversation history for structured status update");
@@ -2627,10 +2628,10 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2627
2628
  }
2628
2629
  });
2629
2630
  const result = object;
2630
- logger$18.info({ result: JSON.stringify(result) }, "DEBUG: Result");
2631
+ logger$19.info({ result: JSON.stringify(result) }, "DEBUG: Result");
2631
2632
  const summaries = [];
2632
2633
  for (const [componentId, data] of Object.entries(result)) {
2633
- logger$18.info({
2634
+ logger$19.info({
2634
2635
  componentId,
2635
2636
  data: JSON.stringify(data)
2636
2637
  }, "DEBUG: Component data");
@@ -2649,7 +2650,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2649
2650
  return { summaries };
2650
2651
  } catch (error) {
2651
2652
  setSpanWithError$1(span, error instanceof Error ? error : new Error(String(error)));
2652
- logger$18.error({ error }, "Failed to generate structured update, using fallback");
2653
+ logger$19.error({ error }, "Failed to generate structured update, using fallback");
2653
2654
  return { summaries: [] };
2654
2655
  } finally {
2655
2656
  span.end();
@@ -2822,7 +2823,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2822
2823
  taskId: artifactData.taskId
2823
2824
  })).map((a) => a.name).filter(Boolean);
2824
2825
  } catch (error) {
2825
- logger$18.warn({
2826
+ logger$19.warn({
2826
2827
  sessionId: this.sessionId,
2827
2828
  artifactId: artifactData.artifactId,
2828
2829
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2873,7 +2874,7 @@ Make the name extremely specific to what this tool call actually returned, not g
2873
2874
  });
2874
2875
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
2875
2876
  modelToUse = agentData.models.base;
2876
- logger$18.info({
2877
+ logger$19.info({
2877
2878
  sessionId: this.sessionId,
2878
2879
  artifactId: artifactData.artifactId,
2879
2880
  subAgentId: artifactData.subAgentId,
@@ -2881,7 +2882,7 @@ Make the name extremely specific to what this tool call actually returned, not g
2881
2882
  }, "Using agent model configuration for artifact name generation");
2882
2883
  }
2883
2884
  } catch (error) {
2884
- logger$18.warn({
2885
+ logger$19.warn({
2885
2886
  sessionId: this.sessionId,
2886
2887
  artifactId: artifactData.artifactId,
2887
2888
  subAgentId: artifactData.subAgentId,
@@ -2889,7 +2890,7 @@ Make the name extremely specific to what this tool call actually returned, not g
2889
2890
  }, "Failed to get agent model configuration");
2890
2891
  }
2891
2892
  if (!modelToUse?.model?.trim()) {
2892
- logger$18.warn({
2893
+ logger$19.warn({
2893
2894
  sessionId: this.sessionId,
2894
2895
  artifactId: artifactData.artifactId
2895
2896
  }, "No model configuration available for artifact name generation, will use fallback names");
@@ -2952,7 +2953,7 @@ Make the name extremely specific to what this tool call actually returned, not g
2952
2953
  return result$1;
2953
2954
  } catch (error) {
2954
2955
  lastError = error instanceof Error ? error : new Error(String(error));
2955
- logger$18.warn({
2956
+ logger$19.warn({
2956
2957
  sessionId: this.sessionId,
2957
2958
  artifactId: artifactData.artifactId,
2958
2959
  attempt,
@@ -2973,7 +2974,7 @@ Make the name extremely specific to what this tool call actually returned, not g
2973
2974
  const toolCallSuffix = toolCallId.slice(-8);
2974
2975
  const originalName = result.name;
2975
2976
  result.name = result.name.length + toolCallSuffix.length + 1 <= 50 ? `${result.name} ${toolCallSuffix}` : `${result.name.substring(0, 50 - toolCallSuffix.length - 1)} ${toolCallSuffix}`;
2976
- logger$18.info({
2977
+ logger$19.info({
2977
2978
  sessionId: this.sessionId,
2978
2979
  artifactId: artifactData.artifactId,
2979
2980
  originalName,
@@ -3001,7 +3002,7 @@ Make the name extremely specific to what this tool call actually returned, not g
3001
3002
  });
3002
3003
  span.setStatus({ code: SpanStatusCode.OK });
3003
3004
  } catch (saveError) {
3004
- logger$18.error({
3005
+ logger$19.error({
3005
3006
  sessionId: this.sessionId,
3006
3007
  artifactId: artifactData.artifactId,
3007
3008
  error: saveError instanceof Error ? saveError.message : "Unknown error",
@@ -3031,13 +3032,13 @@ Make the name extremely specific to what this tool call actually returned, not g
3031
3032
  metadata: artifactData.metadata || {},
3032
3033
  toolCallId: artifactData.toolCallId
3033
3034
  });
3034
- logger$18.info({
3035
+ logger$19.info({
3035
3036
  sessionId: this.sessionId,
3036
3037
  artifactId: artifactData.artifactId
3037
3038
  }, "Saved artifact with fallback name/description after main save failed");
3038
3039
  }
3039
3040
  } catch (fallbackError) {
3040
- if (fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"))) {} else logger$18.error({
3041
+ if (fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"))) {} else logger$19.error({
3041
3042
  sessionId: this.sessionId,
3042
3043
  artifactId: artifactData.artifactId,
3043
3044
  error: fallbackError instanceof Error ? fallbackError.message : "Unknown error",
@@ -3051,7 +3052,7 @@ Make the name extremely specific to what this tool call actually returned, not g
3051
3052
  }
3052
3053
  } catch (error) {
3053
3054
  setSpanWithError$1(span, error instanceof Error ? error : new Error(String(error)));
3054
- logger$18.error({
3055
+ logger$19.error({
3055
3056
  sessionId: this.sessionId,
3056
3057
  artifactId: artifactData.artifactId,
3057
3058
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3066,7 +3067,7 @@ Make the name extremely specific to what this tool call actually returned, not g
3066
3067
  */
3067
3068
  setArtifactCache(key, artifact) {
3068
3069
  this.artifactCache.set(key, artifact);
3069
- logger$18.debug({
3070
+ logger$19.debug({
3070
3071
  sessionId: this.sessionId,
3071
3072
  key
3072
3073
  }, "Artifact cached in session");
@@ -3088,7 +3089,7 @@ Make the name extremely specific to what this tool call actually returned, not g
3088
3089
  */
3089
3090
  getArtifactCache(key) {
3090
3091
  const artifact = this.artifactCache.get(key);
3091
- logger$18.debug({
3092
+ logger$19.debug({
3092
3093
  sessionId: this.sessionId,
3093
3094
  key,
3094
3095
  found: !!artifact
@@ -3114,7 +3115,7 @@ var AgentSessionManager = class {
3114
3115
  const sessionId = messageId;
3115
3116
  const session = new AgentSession(sessionId, messageId, agentId, tenantId, projectId, contextId);
3116
3117
  this.sessions.set(sessionId, session);
3117
- logger$18.info({
3118
+ logger$19.info({
3118
3119
  sessionId,
3119
3120
  messageId,
3120
3121
  agentId,
@@ -3130,7 +3131,7 @@ var AgentSessionManager = class {
3130
3131
  initializeStatusUpdates(sessionId, config, summarizerModel, baseModel) {
3131
3132
  const session = this.sessions.get(sessionId);
3132
3133
  if (session) session.initializeStatusUpdates(config, summarizerModel, baseModel);
3133
- else logger$18.error({
3134
+ else logger$19.error({
3134
3135
  sessionId,
3135
3136
  availableSessions: Array.from(this.sessions.keys())
3136
3137
  }, "Session not found for status updates initialization");
@@ -3141,7 +3142,7 @@ var AgentSessionManager = class {
3141
3142
  enableEmitOperations(sessionId) {
3142
3143
  const session = this.sessions.get(sessionId);
3143
3144
  if (session) session.enableEmitOperations();
3144
- else logger$18.error({
3145
+ else logger$19.error({
3145
3146
  sessionId,
3146
3147
  availableSessions: Array.from(this.sessions.keys())
3147
3148
  }, "Session not found for emit operations enablement");
@@ -3159,7 +3160,7 @@ var AgentSessionManager = class {
3159
3160
  recordEvent(sessionId, eventType, subAgentId, data) {
3160
3161
  const session = this.sessions.get(sessionId);
3161
3162
  if (!session) {
3162
- logger$18.warn({ sessionId }, "Attempted to record event in non-existent session");
3163
+ logger$19.warn({ sessionId }, "Attempted to record event in non-existent session");
3163
3164
  return;
3164
3165
  }
3165
3166
  session.recordEvent(eventType, subAgentId, data);
@@ -3170,12 +3171,12 @@ var AgentSessionManager = class {
3170
3171
  async endSession(sessionId) {
3171
3172
  const session = this.sessions.get(sessionId);
3172
3173
  if (!session) {
3173
- logger$18.warn({ sessionId }, "Attempted to end non-existent session");
3174
+ logger$19.warn({ sessionId }, "Attempted to end non-existent session");
3174
3175
  return [];
3175
3176
  }
3176
3177
  const events = session.getEvents();
3177
3178
  const summary = session.getSummary();
3178
- logger$18.info({
3179
+ logger$19.info({
3179
3180
  sessionId,
3180
3181
  summary
3181
3182
  }, "AgentSession ended");
@@ -3270,7 +3271,7 @@ async function resolveModelConfig(agentId, subAgent) {
3270
3271
 
3271
3272
  //#endregion
3272
3273
  //#region src/services/IncrementalStreamParser.ts
3273
- const logger$17 = getLogger("IncrementalStreamParser");
3274
+ const logger$18 = getLogger("IncrementalStreamParser");
3274
3275
  /**
3275
3276
  * Incremental parser that processes streaming text and formats artifacts/objects as they become complete
3276
3277
  * Uses the unified ArtifactParser to eliminate redundancy
@@ -3321,12 +3322,12 @@ var IncrementalStreamParser = class IncrementalStreamParser {
3321
3322
  async initializeArtifactMap() {
3322
3323
  try {
3323
3324
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
3324
- logger$17.debug({
3325
+ logger$18.debug({
3325
3326
  contextId: this.contextId,
3326
3327
  artifactMapSize: this.artifactMap.size
3327
3328
  }, "Initialized artifact map for streaming");
3328
3329
  } catch (error) {
3329
- logger$17.warn({
3330
+ logger$18.warn({
3330
3331
  error,
3331
3332
  contextId: this.contextId
3332
3333
  }, "Failed to initialize artifact map");
@@ -3591,7 +3592,7 @@ var IncrementalStreamParser = class IncrementalStreamParser {
3591
3592
 
3592
3593
  //#endregion
3593
3594
  //#region src/tools/distill-conversation-tool.ts
3594
- const logger$16 = getLogger("distill-conversation-tool");
3595
+ const logger$17 = getLogger("distill-conversation-tool");
3595
3596
  /**
3596
3597
  * Conversation Summary Schema - structured object for maintaining conversation context
3597
3598
  */
@@ -3639,7 +3640,7 @@ async function distillConversation(params) {
3639
3640
  } else if (msg.content?.text) parts.push(msg.content.text);
3640
3641
  return parts.length > 0 ? `${msg.role || "system"}: ${parts.join("\n")}` : "";
3641
3642
  }).filter((line) => line.trim().length > 0).join("\n\n");
3642
- logger$16.debug({
3643
+ logger$17.debug({
3643
3644
  conversationId,
3644
3645
  messageCount: messages.length,
3645
3646
  formattedLength: formattedMessages.length,
@@ -3710,7 +3711,7 @@ Return **only** valid JSON.`,
3710
3711
  schema: ConversationSummarySchema
3711
3712
  });
3712
3713
  summary.session_id = conversationId;
3713
- logger$16.info({
3714
+ logger$17.info({
3714
3715
  conversationId,
3715
3716
  messageCount: messages.length,
3716
3717
  artifactsCount: summary.related_artifacts?.length || 0,
@@ -3718,7 +3719,7 @@ Return **only** valid JSON.`,
3718
3719
  }, "Successfully distilled conversation");
3719
3720
  return summary;
3720
3721
  } catch (error) {
3721
- logger$16.error({
3722
+ logger$17.error({
3722
3723
  conversationId,
3723
3724
  messageCount: messages.length,
3724
3725
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3741,7 +3742,7 @@ Return **only** valid JSON.`,
3741
3742
 
3742
3743
  //#endregion
3743
3744
  //#region src/services/MidGenerationCompressor.ts
3744
- const logger$15 = getLogger("MidGenerationCompressor");
3745
+ const logger$16 = getLogger("MidGenerationCompressor");
3745
3746
  /**
3746
3747
  * Get compression config from environment variables
3747
3748
  */
@@ -3811,7 +3812,7 @@ var MidGenerationCompressor = class {
3811
3812
  */
3812
3813
  requestManualCompression(reason) {
3813
3814
  this.shouldCompress = true;
3814
- logger$15.info({
3815
+ logger$16.info({
3815
3816
  sessionId: this.sessionId,
3816
3817
  reason: reason || "Manual request from LLM"
3817
3818
  }, "Manual compression requested");
@@ -3829,7 +3830,7 @@ var MidGenerationCompressor = class {
3829
3830
  */
3830
3831
  async compress(messages) {
3831
3832
  const contextSizeBefore = this.calculateContextSize(messages);
3832
- logger$15.info({
3833
+ logger$16.info({
3833
3834
  sessionId: this.sessionId,
3834
3835
  messageCount: messages.length,
3835
3836
  contextSize: contextSizeBefore
@@ -3838,7 +3839,7 @@ var MidGenerationCompressor = class {
3838
3839
  if (Array.isArray(msg.content)) return count + msg.content.filter((block) => block.type === "tool-result").length;
3839
3840
  return count;
3840
3841
  }, 0);
3841
- logger$15.debug({ toolResultCount }, "Tool results found for compression");
3842
+ logger$16.debug({ toolResultCount }, "Tool results found for compression");
3842
3843
  const toolCallToArtifactMap = await this.saveToolResultsAsArtifacts(messages);
3843
3844
  const summary = await this.createConversationSummary(messages, toolCallToArtifactMap);
3844
3845
  const contextSizeAfter = this.estimateTokens(JSON.stringify(summary));
@@ -3855,7 +3856,7 @@ var MidGenerationCompressor = class {
3855
3856
  });
3856
3857
  }
3857
3858
  this.shouldCompress = false;
3858
- logger$15.info({
3859
+ logger$16.info({
3859
3860
  sessionId: this.sessionId,
3860
3861
  artifactsCreated: Object.keys(toolCallToArtifactMap).length,
3861
3862
  messageCount: messages.length,
@@ -3876,7 +3877,7 @@ var MidGenerationCompressor = class {
3876
3877
  if (!session) throw new Error(`No session found: ${this.sessionId}`);
3877
3878
  const toolCallToArtifactMap = {};
3878
3879
  const newMessages = messages.slice(this.lastProcessedMessageIndex);
3879
- logger$15.debug({
3880
+ logger$16.debug({
3880
3881
  totalMessages: messages.length,
3881
3882
  newMessages: newMessages.length,
3882
3883
  startIndex: this.lastProcessedMessageIndex
@@ -3884,7 +3885,7 @@ var MidGenerationCompressor = class {
3884
3885
  for (const message of newMessages) if (Array.isArray(message.content)) {
3885
3886
  for (const block of message.content) if (block.type === "tool-result") {
3886
3887
  if (block.toolName === "get_reference_artifact" || block.toolName === "thinking_complete") {
3887
- logger$15.debug({
3888
+ logger$16.debug({
3888
3889
  toolCallId: block.toolCallId,
3889
3890
  toolName: block.toolName
3890
3891
  }, "Skipping special tool - not creating artifacts");
@@ -3892,14 +3893,14 @@ var MidGenerationCompressor = class {
3892
3893
  continue;
3893
3894
  }
3894
3895
  if (this.processedToolCalls.has(block.toolCallId)) {
3895
- logger$15.debug({
3896
+ logger$16.debug({
3896
3897
  toolCallId: block.toolCallId,
3897
3898
  toolName: block.toolName
3898
3899
  }, "Skipping already processed tool call");
3899
3900
  continue;
3900
3901
  }
3901
3902
  const artifactId = `compress_${block.toolName || "tool"}_${block.toolCallId || Date.now()}_${randomUUID().slice(0, 8)}`;
3902
- logger$15.debug({
3903
+ logger$16.debug({
3903
3904
  artifactId,
3904
3905
  toolName: block.toolName,
3905
3906
  toolCallId: block.toolCallId
@@ -3914,7 +3915,7 @@ var MidGenerationCompressor = class {
3914
3915
  compressedAt: (/* @__PURE__ */ new Date()).toISOString()
3915
3916
  };
3916
3917
  if (this.isEmpty(toolResultData)) {
3917
- logger$15.debug({
3918
+ logger$16.debug({
3918
3919
  toolName: block.toolName,
3919
3920
  toolCallId: block.toolCallId
3920
3921
  }, "Skipping empty tool result");
@@ -3943,7 +3944,7 @@ var MidGenerationCompressor = class {
3943
3944
  };
3944
3945
  const fullData = artifactData.data;
3945
3946
  if (!(fullData && typeof fullData === "object" && Object.keys(fullData).length > 0 && fullData.toolResult && (typeof fullData.toolResult !== "object" || Object.keys(fullData.toolResult).length > 0))) {
3946
- logger$15.debug({
3947
+ logger$16.debug({
3947
3948
  artifactId,
3948
3949
  toolName: block.toolName,
3949
3950
  toolCallId: block.toolCallId
@@ -3956,7 +3957,7 @@ var MidGenerationCompressor = class {
3956
3957
  }
3957
3958
  }
3958
3959
  this.lastProcessedMessageIndex = messages.length;
3959
- logger$15.debug({
3960
+ logger$16.debug({
3960
3961
  totalArtifactsCreated: Object.keys(toolCallToArtifactMap).length,
3961
3962
  newMessageIndex: this.lastProcessedMessageIndex
3962
3963
  }, "Compression artifact processing completed");
@@ -3967,7 +3968,7 @@ var MidGenerationCompressor = class {
3967
3968
  */
3968
3969
  async createConversationSummary(messages, toolCallToArtifactMap) {
3969
3970
  const textMessages = this.extractTextMessages(messages, toolCallToArtifactMap);
3970
- logger$15.debug({
3971
+ logger$16.debug({
3971
3972
  sessionId: this.sessionId,
3972
3973
  messageCount: messages.length,
3973
3974
  textMessageCount: textMessages.length,
@@ -3986,7 +3987,7 @@ var MidGenerationCompressor = class {
3986
3987
  toolCallToArtifactMap
3987
3988
  });
3988
3989
  this.cumulativeSummary = summary;
3989
- logger$15.debug({
3990
+ logger$16.debug({
3990
3991
  sessionId: this.sessionId,
3991
3992
  summaryGenerated: !!summary,
3992
3993
  summaryHighLevel: summary?.high_level,
@@ -4110,7 +4111,7 @@ var MidGenerationCompressor = class {
4110
4111
 
4111
4112
  //#endregion
4112
4113
  //#region src/services/PendingToolApprovalManager.ts
4113
- const logger$14 = getLogger("PendingToolApprovalManager");
4114
+ const logger$15 = getLogger("PendingToolApprovalManager");
4114
4115
  const APPROVAL_CLEANUP_INTERVAL_MS = 120 * 1e3;
4115
4116
  const APPROVAL_TIMEOUT_MS = 600 * 1e3;
4116
4117
  /**
@@ -4152,7 +4153,7 @@ var PendingToolApprovalManager = class PendingToolApprovalManager {
4152
4153
  timeoutId
4153
4154
  };
4154
4155
  this.pendingApprovals.set(toolCallId, approval);
4155
- logger$14.info({
4156
+ logger$15.info({
4156
4157
  toolCallId,
4157
4158
  toolName,
4158
4159
  conversationId,
@@ -4166,10 +4167,10 @@ var PendingToolApprovalManager = class PendingToolApprovalManager {
4166
4167
  approveToolCall(toolCallId) {
4167
4168
  const approval = this.pendingApprovals.get(toolCallId);
4168
4169
  if (!approval) {
4169
- logger$14.warn({ toolCallId }, "Tool approval not found or already processed");
4170
+ logger$15.warn({ toolCallId }, "Tool approval not found or already processed");
4170
4171
  return false;
4171
4172
  }
4172
- logger$14.info({
4173
+ logger$15.info({
4173
4174
  toolCallId,
4174
4175
  toolName: approval.toolName,
4175
4176
  conversationId: approval.conversationId
@@ -4185,10 +4186,10 @@ var PendingToolApprovalManager = class PendingToolApprovalManager {
4185
4186
  denyToolCall(toolCallId, reason) {
4186
4187
  const approval = this.pendingApprovals.get(toolCallId);
4187
4188
  if (!approval) {
4188
- logger$14.warn({ toolCallId }, "Tool approval not found or already processed");
4189
+ logger$15.warn({ toolCallId }, "Tool approval not found or already processed");
4189
4190
  return false;
4190
4191
  }
4191
- logger$14.info({
4192
+ logger$15.info({
4192
4193
  toolCallId,
4193
4194
  toolName: approval.toolName,
4194
4195
  conversationId: approval.conversationId,
@@ -4217,7 +4218,7 @@ var PendingToolApprovalManager = class PendingToolApprovalManager {
4217
4218
  });
4218
4219
  cleanedUp++;
4219
4220
  }
4220
- if (cleanedUp > 0) logger$14.info({ cleanedUp }, "Cleaned up expired tool approvals");
4221
+ if (cleanedUp > 0) logger$15.info({ cleanedUp }, "Cleaned up expired tool approvals");
4221
4222
  }
4222
4223
  /**
4223
4224
  * Get current status for monitoring
@@ -4240,7 +4241,7 @@ const pendingToolApprovalManager = PendingToolApprovalManager.getInstance();
4240
4241
 
4241
4242
  //#endregion
4242
4243
  //#region src/services/ResponseFormatter.ts
4243
- const logger$13 = getLogger("ResponseFormatter");
4244
+ const logger$14 = getLogger("ResponseFormatter");
4244
4245
  /**
4245
4246
  * Response formatter that uses the unified ArtifactParser to convert artifact markers
4246
4247
  * into data parts for consistent artifact handling across all agent responses
@@ -4289,7 +4290,7 @@ var ResponseFormatter = class {
4289
4290
  return { parts };
4290
4291
  } catch (error) {
4291
4292
  setSpanWithError$1(span, error instanceof Error ? error : new Error(String(error)));
4292
- logger$13.error({
4293
+ logger$14.error({
4293
4294
  error,
4294
4295
  responseObject
4295
4296
  }, "Error formatting object response");
@@ -4342,7 +4343,7 @@ var ResponseFormatter = class {
4342
4343
  return { parts };
4343
4344
  } catch (error) {
4344
4345
  setSpanWithError$1(span, error instanceof Error ? error : new Error(String(error)));
4345
- logger$13.error({
4346
+ logger$14.error({
4346
4347
  error,
4347
4348
  responseText
4348
4349
  }, "Error formatting response");
@@ -4760,6 +4761,151 @@ var ArtifactCreateSchema = class {
4760
4761
  }
4761
4762
  };
4762
4763
 
4764
+ //#endregion
4765
+ //#region src/utils/model-context-utils.ts
4766
+ const logger$13 = getLogger("ModelContextUtils");
4767
+ /**
4768
+ * Extract model ID from model settings for llm-info lookup
4769
+ */
4770
+ function extractModelIdForLlmInfo(modelSettings) {
4771
+ if (!modelSettings?.model) return null;
4772
+ const modelString = modelSettings.model.trim();
4773
+ if (modelString.includes("/")) {
4774
+ const parts = modelString.split("/");
4775
+ return parts[parts.length - 1];
4776
+ }
4777
+ return modelString;
4778
+ }
4779
+ /**
4780
+ * Get context window size for a model using llm-info
4781
+ * Falls back to default values if model not found
4782
+ */
4783
+ function getModelContextWindow(modelSettings) {
4784
+ const defaultContextWindow = 12e4;
4785
+ if (!modelSettings?.model) {
4786
+ logger$13.debug({}, "No model settings provided, using fallback");
4787
+ return {
4788
+ contextWindow: defaultContextWindow,
4789
+ hasValidContextWindow: false,
4790
+ modelId: "unknown",
4791
+ source: "fallback"
4792
+ };
4793
+ }
4794
+ const modelId = extractModelIdForLlmInfo(modelSettings);
4795
+ if (!modelId) {
4796
+ logger$13.debug({ modelString: modelSettings.model }, "Could not extract model ID for llm-info lookup");
4797
+ return {
4798
+ contextWindow: defaultContextWindow,
4799
+ hasValidContextWindow: false,
4800
+ modelId: modelSettings.model,
4801
+ source: "fallback"
4802
+ };
4803
+ }
4804
+ try {
4805
+ const modelDetails = ModelInfoMap[modelId];
4806
+ if (modelDetails && modelDetails.contextWindowTokenLimit && modelDetails.contextWindowTokenLimit > 0) {
4807
+ logger$13.debug({
4808
+ modelId,
4809
+ contextWindow: modelDetails.contextWindowTokenLimit,
4810
+ originalModel: modelSettings.model
4811
+ }, "Found context window from llm-info");
4812
+ return {
4813
+ contextWindow: modelDetails.contextWindowTokenLimit,
4814
+ hasValidContextWindow: true,
4815
+ modelId,
4816
+ source: "llm-info"
4817
+ };
4818
+ } else logger$13.debug({
4819
+ modelId,
4820
+ modelDetails,
4821
+ originalModel: modelSettings.model
4822
+ }, "No valid context window found in llm-info");
4823
+ } catch (error) {
4824
+ logger$13.debug({
4825
+ modelId,
4826
+ error: error instanceof Error ? error.message : String(error),
4827
+ originalModel: modelSettings.model
4828
+ }, "Error getting model details from llm-info");
4829
+ }
4830
+ logger$13.debug({
4831
+ modelId,
4832
+ defaultContextWindow
4833
+ }, "Using fallback context window");
4834
+ return {
4835
+ contextWindow: defaultContextWindow,
4836
+ hasValidContextWindow: false,
4837
+ modelId,
4838
+ source: "fallback"
4839
+ };
4840
+ }
4841
+ /**
4842
+ * Get model-size aware compression parameters
4843
+ * Uses aggressive thresholds for better utilization, especially on large models
4844
+ */
4845
+ function getCompressionParams(contextWindow) {
4846
+ if (contextWindow < 1e5) return {
4847
+ threshold: .85,
4848
+ bufferPct: .1
4849
+ };
4850
+ else if (contextWindow < 5e5) return {
4851
+ threshold: .9,
4852
+ bufferPct: .07
4853
+ };
4854
+ else return {
4855
+ threshold: .95,
4856
+ bufferPct: .04
4857
+ };
4858
+ }
4859
+ /**
4860
+ * Get compression configuration based on model context window
4861
+ * Uses actual model context window when available, otherwise falls back to environment variables
4862
+ */
4863
+ function getCompressionConfigForModel(modelSettings) {
4864
+ const modelContextInfo = getModelContextWindow(modelSettings);
4865
+ const envHardLimit = parseInt(process.env.AGENTS_COMPRESSION_HARD_LIMIT || "120000");
4866
+ const envSafetyBuffer = parseInt(process.env.AGENTS_COMPRESSION_SAFETY_BUFFER || "20000");
4867
+ const enabled = process.env.AGENTS_COMPRESSION_ENABLED !== "false";
4868
+ if (modelContextInfo.hasValidContextWindow && modelContextInfo.contextWindow) {
4869
+ const params = getCompressionParams(modelContextInfo.contextWindow);
4870
+ const hardLimit = Math.floor(modelContextInfo.contextWindow * params.threshold);
4871
+ const safetyBuffer = Math.floor(modelContextInfo.contextWindow * params.bufferPct);
4872
+ const triggerPoint = hardLimit - safetyBuffer;
4873
+ const triggerPercentage = (triggerPoint / modelContextInfo.contextWindow * 100).toFixed(1);
4874
+ logger$13.info({
4875
+ modelId: modelContextInfo.modelId,
4876
+ contextWindow: modelContextInfo.contextWindow,
4877
+ hardLimit,
4878
+ safetyBuffer,
4879
+ triggerPoint,
4880
+ triggerPercentage: `${triggerPercentage}%`,
4881
+ threshold: params.threshold,
4882
+ bufferPct: params.bufferPct
4883
+ }, "Using model-size aware compression configuration");
4884
+ return {
4885
+ hardLimit,
4886
+ safetyBuffer,
4887
+ enabled,
4888
+ source: "model-specific",
4889
+ modelContextInfo
4890
+ };
4891
+ } else {
4892
+ const source = process.env.AGENTS_COMPRESSION_HARD_LIMIT ? "environment" : "default";
4893
+ logger$13.debug({
4894
+ modelId: modelContextInfo.modelId,
4895
+ hardLimit: envHardLimit,
4896
+ safetyBuffer: envSafetyBuffer,
4897
+ source
4898
+ }, "Using fallback compression configuration");
4899
+ return {
4900
+ hardLimit: envHardLimit,
4901
+ safetyBuffer: envSafetyBuffer,
4902
+ enabled,
4903
+ source,
4904
+ modelContextInfo
4905
+ };
4906
+ }
4907
+ }
4908
+
4763
4909
  //#endregion
4764
4910
  //#region src/a2a/client.ts
4765
4911
  const logger$12 = getLogger("a2aClient");
@@ -7690,7 +7836,12 @@ ${typeof cleanResult === "string" ? cleanResult : JSON.stringify(cleanResult, nu
7690
7836
  content: userMessage
7691
7837
  });
7692
7838
  const originalMessageCount = messages.length;
7693
- const compressionConfig = getCompressionConfigFromEnv();
7839
+ const compressionConfigResult = getCompressionConfigForModel(primaryModelSettings);
7840
+ const compressionConfig = {
7841
+ hardLimit: compressionConfigResult.hardLimit,
7842
+ safetyBuffer: compressionConfigResult.safetyBuffer,
7843
+ enabled: compressionConfigResult.enabled
7844
+ };
7694
7845
  const compressor = compressionConfig.enabled ? new MidGenerationCompressor(sessionId, contextId, this.config.tenantId, this.config.projectId, compressionConfig, this.getSummarizerModel(), primaryModelSettings) : null;
7695
7846
  this.currentCompressor = compressor;
7696
7847
  if (shouldStreamPhase1) {