@inkeep/agents-run-api 0.37.2 → 0.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import { flushBatchProcessor } from './chunk-QOUOKHYQ.js';
2
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-BQB27EXW.js';
3
- import { dbClient_default } from './chunk-W6UIBREL.js';
4
- import { env } from './chunk-CDYXP4BN.js';
1
+ import { defaultSDK, flushBatchProcessor } from './chunk-UC2EPLSW.js';
2
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-KCJWSIDZ.js';
3
+ import { dbClient_default } from './chunk-EVOISBFH.js';
4
+ import { env } from './chunk-KBZIYCPJ.js';
5
5
  import { getLogger } from './chunk-A2S7GSHL.js';
6
- import { SESSION_CLEANUP_INTERVAL_MS, AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS, SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS, STREAM_MAX_LIFETIME_MS, STREAM_BUFFER_MAX_SIZE_BYTES, STREAM_TEXT_GAP_THRESHOLD_MS, ARTIFACT_GENERATION_MAX_RETRIES, ARTIFACT_SESSION_MAX_PENDING, STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS, STATUS_UPDATE_DEFAULT_NUM_EVENTS, ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES, AGENT_EXECUTION_MAX_GENERATION_STEPS, FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS, ARTIFACT_GENERATION_BACKOFF_INITIAL_MS, ARTIFACT_GENERATION_BACKOFF_MAX_MS, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING, LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS, DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS, DELEGATION_TOOL_BACKOFF_EXPONENT, DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS, DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS, STREAM_PARSER_MAX_SNAPSHOT_SIZE, STREAM_PARSER_MAX_STREAMED_SIZE, STREAM_PARSER_MAX_COLLECTED_PARTS } from './chunk-SUUSOBLI.js';
7
- import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, getConversation, createDefaultCredentialStores, CredentialStoreRegistry, createTask, getTask, updateTask, setSpanWithError, AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, updateConversation, handleApiError, TaskState, getAgentById, getProject, setActiveAgentForThread, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getTeamAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, CONVERSATION_HISTORY_DEFAULT_LIMIT, ModelFactory, verifyTempToken, validateAndGetApiKey, verifyServiceToken, validateTargetAgent, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, getContextConfigById, getFullAgentDefinition, TemplateEngine, listTaskIdsByContextId, getLedgerArtifacts, agentHasArtifactComponents, upsertLedgerArtifact, MCPTransportType, SPAN_KEYS, headers, generateServiceToken } from '@inkeep/agents-core';
6
+ import { SESSION_CLEANUP_INTERVAL_MS, AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS, SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS, STREAM_MAX_LIFETIME_MS, STREAM_BUFFER_MAX_SIZE_BYTES, STREAM_TEXT_GAP_THRESHOLD_MS, ARTIFACT_GENERATION_MAX_RETRIES, ARTIFACT_SESSION_MAX_PENDING, STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS, STATUS_UPDATE_DEFAULT_NUM_EVENTS, ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES, AGENT_EXECUTION_MAX_GENERATION_STEPS, FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS, ARTIFACT_GENERATION_BACKOFF_INITIAL_MS, ARTIFACT_GENERATION_BACKOFF_MAX_MS, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING, LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS, DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS, DELEGATION_TOOL_BACKOFF_EXPONENT, DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS, DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS, STREAM_PARSER_MAX_SNAPSHOT_SIZE, STREAM_PARSER_MAX_STREAMED_SIZE, STREAM_PARSER_MAX_COLLECTED_PARTS } from './chunk-THWNUGWP.js';
7
+ import { getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentWithDefaultSubAgent, contextValidationMiddleware, getConversationId, getFullAgent, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getSubAgentById, handleContextResolution, createMessage, generateId, commonGetErrorResponses, loggerFactory, getConversation, createDefaultCredentialStores, CredentialStoreRegistry, createTask, getTask, updateTask, setSpanWithError, AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT, updateConversation, handleApiError, TaskState, getAgentById, getProject, setActiveAgentForThread, getRelatedAgentsForAgent, getExternalAgentsForSubAgent, getTeamAgentsForSubAgent, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT, CONVERSATION_HISTORY_DEFAULT_LIMIT, ModelFactory, getLedgerArtifacts, verifyTempToken, validateAndGetApiKey, verifyServiceToken, validateTargetAgent, ContextResolver, CredentialStuffer, MCPServerType, getUserScopedCredentialReference, getCredentialReference, McpClient, getFunctionToolsForSubAgent, getFunction, jsonSchemaToZod, getContextConfigById, getFullAgentDefinition, TemplateEngine, listTaskIdsByContextId, agentHasArtifactComponents, upsertLedgerArtifact, MCPTransportType, SPAN_KEYS, headers, generateServiceToken } from '@inkeep/agents-core';
8
8
  import { otel } from '@hono/otel';
9
- import { OpenAPIHono, createRoute, z } from '@hono/zod-openapi';
9
+ import { OpenAPIHono, createRoute, z as z$1 } from '@hono/zod-openapi';
10
10
  import { trace, propagation, context, SpanStatusCode } from '@opentelemetry/api';
11
11
  import { Hono } from 'hono';
12
12
  import { cors } from 'hono/cors';
@@ -18,6 +18,8 @@ import { streamSSE, stream } from 'hono/streaming';
18
18
  import { createUIMessageStream, JsonToSseTransformStream, parsePartialJson, generateObject, tool, streamText, generateText, streamObject } from 'ai';
19
19
  import jmespath from 'jmespath';
20
20
  import Ajv from 'ajv';
21
+ import { randomUUID } from 'crypto';
22
+ import { z } from 'zod';
21
23
  import destr from 'destr';
22
24
  import traverse from 'traverse';
23
25
  import { McpServer } from '@alcyone-labs/modelcontextprotocol-sdk/server/mcp.js';
@@ -25,6 +27,10 @@ import { StreamableHTTPServerTransport } from '@alcyone-labs/modelcontextprotoco
25
27
  import { toReqRes, toFetchResponse } from 'fetch-to-node';
26
28
 
27
29
  // src/types/execution-context.ts
30
+ function getUserIdFromContext(ctx) {
31
+ const metadata = ctx.metadata;
32
+ return metadata?.initiatedBy?.type === "user" ? metadata.initiatedBy.id : void 0;
33
+ }
28
34
  function createExecutionContext(params) {
29
35
  return {
30
36
  apiKey: params.apiKey,
@@ -1611,7 +1617,7 @@ var ArtifactService = class _ArtifactService {
1611
1617
  const summaryValidation = validateAgainstSchema(summaryData, previewSchema);
1612
1618
  const fullValidation = validateAgainstSchema(fullData, fullSchema);
1613
1619
  if (!summaryValidation.hasRequiredFields) {
1614
- const error = new Error(
1620
+ new Error(
1615
1621
  `Cannot save artifact: Missing required fields [${summaryValidation.missingRequired.join(", ")}] for '${artifactType}' schema. Required: [${summaryValidation.missingRequired.join(", ")}]. Found: [${summaryValidation.actualFields.join(", ")}]. Consider using a different artifact component type that matches your data structure.`
1616
1622
  );
1617
1623
  logger5.error(
@@ -1622,9 +1628,13 @@ var ArtifactService = class _ArtifactService {
1622
1628
  actualFields: summaryValidation.actualFields,
1623
1629
  schemaExpected: previewSchema?.properties ? Object.keys(previewSchema.properties) : []
1624
1630
  },
1625
- "Blocking artifact save due to missing required fields"
1631
+ "Artifact creation failed due to missing required fields - continuing with generation"
1626
1632
  );
1627
- throw error;
1633
+ return {
1634
+ summary: summaryValidation,
1635
+ full: fullValidation,
1636
+ schemaFound: !!previewSchema
1637
+ };
1628
1638
  }
1629
1639
  if (!summaryValidation.hasExpectedFields || summaryValidation.extraFields.length > 0) {
1630
1640
  logger5.warn(
@@ -1774,7 +1784,7 @@ var ArtifactService = class _ArtifactService {
1774
1784
  * Used by AgentSession to save artifacts after name/description generation
1775
1785
  */
1776
1786
  async saveArtifact(artifact) {
1777
- let summaryData = artifact.data;
1787
+ let summaryData = artifact.summaryData || artifact.data;
1778
1788
  let fullData = artifact.data;
1779
1789
  if (this.context.artifactComponents) {
1780
1790
  const artifactComponent = this.context.artifactComponents.find(
@@ -2362,7 +2372,6 @@ var AgentSession = class {
2362
2372
  * Send data operation to stream when emit operations is enabled
2363
2373
  */
2364
2374
  async sendDataOperation(event) {
2365
- console.log("sendDataOperation called with event", Date.now());
2366
2375
  try {
2367
2376
  const streamHelper = getStreamHelper(this.sessionId);
2368
2377
  if (streamHelper) {
@@ -2413,6 +2422,8 @@ var AgentSession = class {
2413
2422
  return `Task completed: ${event.data.targetSubAgent} \u2192 ${event.data.fromSubAgent}`;
2414
2423
  case "artifact_saved":
2415
2424
  return `Artifact saved: ${event.data.artifactType || "unknown type"}`;
2425
+ case "compression":
2426
+ return `Compressed ${event.data.messageCount} messages and ${event.data.artifactCount} artifacts (${event.data.reason})`;
2416
2427
  default:
2417
2428
  return `${event.eventType} event`;
2418
2429
  }
@@ -2659,13 +2670,30 @@ var AgentSession = class {
2659
2670
  /**
2660
2671
  * Clean up status update resources when session ends
2661
2672
  */
2662
- cleanup() {
2673
+ async cleanup() {
2663
2674
  this.isEnded = true;
2664
2675
  if (this.statusUpdateTimer) {
2665
2676
  clearInterval(this.statusUpdateTimer);
2666
2677
  this.statusUpdateTimer = void 0;
2667
2678
  }
2668
2679
  this.statusUpdateState = void 0;
2680
+ if (this.pendingArtifacts.size > 0) {
2681
+ const maxWaitTime = 1e4;
2682
+ const startTime = Date.now();
2683
+ while (this.pendingArtifacts.size > 0 && Date.now() - startTime < maxWaitTime) {
2684
+ await new Promise((resolve) => setTimeout(resolve, 100));
2685
+ }
2686
+ if (this.pendingArtifacts.size > 0) {
2687
+ logger7.warn(
2688
+ {
2689
+ sessionId: this.sessionId,
2690
+ pendingCount: this.pendingArtifacts.size,
2691
+ pendingIds: Array.from(this.pendingArtifacts)
2692
+ },
2693
+ "Cleanup proceeding with pending artifacts still processing"
2694
+ );
2695
+ }
2696
+ }
2669
2697
  this.pendingArtifacts.clear();
2670
2698
  this.artifactProcessingErrors.clear();
2671
2699
  this.artifactCache.clear();
@@ -2908,12 +2936,12 @@ ${conversationHistory}
2908
2936
  Previous updates sent to user:
2909
2937
  ${previousSummaries.map((s, i) => `${i + 1}. ${s}`).join("\n")}
2910
2938
  ` : "";
2911
- const selectionSchema = z.object(
2939
+ const selectionSchema = z$1.object(
2912
2940
  Object.fromEntries([
2913
2941
  [
2914
2942
  "no_relevant_updates",
2915
- z.object({
2916
- no_updates: z.boolean().default(true)
2943
+ z$1.object({
2944
+ no_updates: z$1.boolean().default(true)
2917
2945
  }).optional().describe(
2918
2946
  "Use when nothing substantially new to report. Should only use on its own."
2919
2947
  )
@@ -3047,8 +3075,8 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3047
3075
  if (component.detailsSchema && "properties" in component.detailsSchema) {
3048
3076
  return this.buildZodSchemaFromJson(component.detailsSchema);
3049
3077
  }
3050
- return z.object({
3051
- label: z.string().describe(
3078
+ return z$1.object({
3079
+ label: z$1.string().describe(
3052
3080
  'A short 3-5 word phrase, that is a descriptive label for the update component. This Label must be EXTREMELY unique to represent the UNIQUE update we are providing. The ACTUAL finding or result, not the action. What specific information was discovered? (e.g., "Slack requires OAuth 2.0 setup", "Found 5 integration methods", "API rate limit is 100/minute"). Include the actual detail or insight, not just that you searched or processed. CRITICAL: Only use facts explicitly found in the activities - NEVER invent names, people, organizations, or details that are not present in the actual tool results.'
3053
3081
  )
3054
3082
  });
@@ -3058,56 +3086,56 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3058
3086
  */
3059
3087
  buildZodSchemaFromJson(jsonSchema) {
3060
3088
  const properties = {};
3061
- properties.label = z.string().describe(
3089
+ properties.label = z$1.string().describe(
3062
3090
  'A short 3-5 word phrase, that is a descriptive label for the update component. This Label must be EXTREMELY unique to represent the UNIQUE update we are providing. The SPECIFIC finding, result, or insight discovered (e.g., "Slack bot needs workspace admin role", "Found ingestion requires 3 steps", "Channel history limited to 10k messages"). State the ACTUAL information found, not that you searched. What did you LEARN or DISCOVER? What specific detail is now known? CRITICAL: Only use facts explicitly found in the activities - NEVER invent names, people, organizations, or details that are not present in the actual tool results.'
3063
3091
  );
3064
3092
  for (const [key, value] of Object.entries(jsonSchema.properties)) {
3065
3093
  let zodType;
3066
3094
  if (value.enum && Array.isArray(value.enum)) {
3067
3095
  if (value.enum.length === 1) {
3068
- zodType = z.literal(value.enum[0]);
3096
+ zodType = z$1.literal(value.enum[0]);
3069
3097
  } else {
3070
3098
  const [first, ...rest] = value.enum;
3071
- zodType = z.enum([first, ...rest]);
3099
+ zodType = z$1.enum([first, ...rest]);
3072
3100
  }
3073
3101
  } else if (value.type === "string") {
3074
- zodType = z.string();
3102
+ zodType = z$1.string();
3075
3103
  if (value.minLength) zodType = zodType.min(value.minLength);
3076
3104
  if (value.maxLength) zodType = zodType.max(value.maxLength);
3077
3105
  if (value.format === "email") zodType = zodType.email();
3078
3106
  if (value.format === "url" || value.format === "uri")
3079
3107
  zodType = zodType.url();
3080
3108
  } else if (value.type === "number" || value.type === "integer") {
3081
- zodType = value.type === "integer" ? z.number().int() : z.number();
3109
+ zodType = value.type === "integer" ? z$1.number().int() : z$1.number();
3082
3110
  if (value.minimum !== void 0) zodType = zodType.min(value.minimum);
3083
3111
  if (value.maximum !== void 0) zodType = zodType.max(value.maximum);
3084
3112
  } else if (value.type === "boolean") {
3085
- zodType = z.boolean();
3113
+ zodType = z$1.boolean();
3086
3114
  } else if (value.type === "array") {
3087
3115
  if (value.items) {
3088
3116
  if (value.items.enum && Array.isArray(value.items.enum)) {
3089
3117
  const [first, ...rest] = value.items.enum;
3090
- zodType = z.array(z.enum([first, ...rest]));
3118
+ zodType = z$1.array(z$1.enum([first, ...rest]));
3091
3119
  } else if (value.items.type === "string") {
3092
- zodType = z.array(z.string());
3120
+ zodType = z$1.array(z$1.string());
3093
3121
  } else if (value.items.type === "number") {
3094
- zodType = z.array(z.number());
3122
+ zodType = z$1.array(z$1.number());
3095
3123
  } else if (value.items.type === "boolean") {
3096
- zodType = z.array(z.boolean());
3124
+ zodType = z$1.array(z$1.boolean());
3097
3125
  } else if (value.items.type === "object") {
3098
- zodType = z.array(z.record(z.string(), z.any()));
3126
+ zodType = z$1.array(z$1.record(z$1.string(), z$1.any()));
3099
3127
  } else {
3100
- zodType = z.array(z.any());
3128
+ zodType = z$1.array(z$1.any());
3101
3129
  }
3102
3130
  } else {
3103
- zodType = z.array(z.any());
3131
+ zodType = z$1.array(z$1.any());
3104
3132
  }
3105
3133
  if (value.minItems) zodType = zodType.min(value.minItems);
3106
3134
  if (value.maxItems) zodType = zodType.max(value.maxItems);
3107
3135
  } else if (value.type === "object") {
3108
- zodType = z.record(z.string(), z.any());
3136
+ zodType = z$1.record(z$1.string(), z$1.any());
3109
3137
  } else {
3110
- zodType = z.any();
3138
+ zodType = z$1.any();
3111
3139
  }
3112
3140
  if (value.description) {
3113
3141
  zodType = zodType.describe(value.description);
@@ -3117,7 +3145,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3117
3145
  }
3118
3146
  properties[key] = zodType;
3119
3147
  }
3120
- return z.object(properties);
3148
+ return z$1.object(properties);
3121
3149
  }
3122
3150
  /**
3123
3151
  * Extract user-visible activities with rich formatting and complete information
@@ -3278,17 +3306,59 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3278
3306
  (event) => event.eventType === "tool_result" && event.data && "toolCallId" in event.data && event.data.toolCallId === artifactData.metadata?.toolCallId
3279
3307
  );
3280
3308
  const toolContext = toolCallEvent ? {
3281
- toolName: toolCallEvent.data.toolName,
3282
3309
  args: toolCallEvent.data.args
3283
3310
  } : null;
3284
- const prompt = `Name this artifact (max 50 chars) and describe it (max 150 chars).
3311
+ let existingNames = [];
3312
+ try {
3313
+ if (artifactData.tenantId && artifactData.projectId && artifactData.taskId) {
3314
+ const existingArtifacts = await getLedgerArtifacts(dbClient_default)({
3315
+ scopes: { tenantId: artifactData.tenantId, projectId: artifactData.projectId },
3316
+ taskId: artifactData.taskId
3317
+ });
3318
+ existingNames = existingArtifacts.map((a) => a.name).filter(Boolean);
3319
+ }
3320
+ } catch (error) {
3321
+ logger7.warn(
3322
+ {
3323
+ sessionId: this.sessionId,
3324
+ artifactId: artifactData.artifactId,
3325
+ error: error instanceof Error ? error.message : "Unknown error"
3326
+ },
3327
+ "Failed to fetch existing artifact names for context"
3328
+ );
3329
+ }
3330
+ const toolName = artifactData.metadata?.toolName || "unknown";
3331
+ const toolCallId = artifactData.metadata?.toolCallId || "unknown";
3332
+ const prompt = `Create a unique name and description for this tool result artifact.
3285
3333
 
3286
- Tool Context: ${toolContext ? JSON.stringify(toolContext, null, 2) : "No tool context"}
3287
- Context: ${conversationHistory?.slice(-200) || "Processing"}
3288
- Type: ${artifactData.artifactType || "data"}
3289
- Data: ${JSON.stringify(artifactData.data || artifactData.summaryData, null, 2)}
3334
+ CRITICAL: Your name must be different from these existing artifacts: ${existingNames.length > 0 ? existingNames.join(", ") : "None yet"}
3290
3335
 
3291
- Make it specific and relevant.`;
3336
+ Tool Context: ${toolContext ? JSON.stringify(toolContext.args, null, 2) : "No args"}
3337
+ Context: ${conversationHistory?.slice(-200) || "No context"}
3338
+ Type: ${artifactData.artifactType || "data"}
3339
+ Data: ${JSON.stringify(artifactData.data || artifactData.summaryData || {}, null, 2)}
3340
+
3341
+ Requirements:
3342
+ - Name: Max 50 chars, be extremely specific to THIS EXACT tool execution
3343
+ - Description: Max 150 chars, describe what THIS SPECIFIC tool call returned
3344
+ - Focus on the unique aspects of this particular tool execution result
3345
+ - Be descriptive about the actual content returned, not just the tool type
3346
+
3347
+ BAD Examples (too generic):
3348
+ - "Search Results"
3349
+ - "Tool Results"
3350
+ - "${toolName} Results"
3351
+ - "Data from ${toolName}"
3352
+ - "Tool Output"
3353
+ - "Search Data"
3354
+
3355
+ GOOD Examples:
3356
+ - "GitHub API Rate Limits & Auth Methods"
3357
+ - "React Component Props Documentation"
3358
+ - "Database Schema for User Tables"
3359
+ - "Pricing Tiers with Enterprise Features"
3360
+
3361
+ Make the name extremely specific to what this tool call actually returned, not generic.`;
3292
3362
  let modelToUse = this.statusUpdateState?.summarizerModel;
3293
3363
  if (!modelToUse?.model?.trim()) {
3294
3364
  if (!this.statusUpdateState?.baseModel?.model?.trim()) {
@@ -3342,15 +3412,16 @@ Make it specific and relevant.`;
3342
3412
  }
3343
3413
  let result;
3344
3414
  if (!modelToUse) {
3415
+ const toolCallSuffix = artifactData.metadata?.toolCallId?.slice(-8) || Date.now().toString().slice(-8);
3345
3416
  result = {
3346
- name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
3347
- description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolCallId || "tool results"}`
3417
+ name: `${artifactData.artifactType || "Artifact"} ${toolCallSuffix}`,
3418
+ description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool"} (${artifactData.metadata?.toolCallId || "tool results"})`
3348
3419
  };
3349
3420
  } else {
3350
3421
  const model = ModelFactory.createModel(modelToUse);
3351
- const schema = z.object({
3352
- name: z.string().describe("Concise, descriptive name for the artifact"),
3353
- description: z.string().describe("Brief description of the artifact's relevance to the user's question")
3422
+ const schema = z$1.object({
3423
+ name: z$1.string().describe("Concise, descriptive name for the artifact"),
3424
+ description: z$1.string().describe("Brief description of the artifact's relevance to the user's question")
3354
3425
  });
3355
3426
  const { object } = await tracer.startActiveSpan(
3356
3427
  "agent_session.generate_artifact_metadata",
@@ -3439,13 +3510,32 @@ Make it specific and relevant.`;
3439
3510
  );
3440
3511
  result = object;
3441
3512
  }
3513
+ if (existingNames.includes(result.name)) {
3514
+ const toolCallSuffix = toolCallId.slice(-8);
3515
+ const originalName = result.name;
3516
+ result.name = result.name.length + toolCallSuffix.length + 1 <= 50 ? `${result.name} ${toolCallSuffix}` : `${result.name.substring(0, 50 - toolCallSuffix.length - 1)} ${toolCallSuffix}`;
3517
+ logger7.info(
3518
+ {
3519
+ sessionId: this.sessionId,
3520
+ artifactId: artifactData.artifactId,
3521
+ originalName,
3522
+ uniqueName: result.name,
3523
+ reason: "Name conflict resolved with toolCallId suffix"
3524
+ },
3525
+ "Updated artifact name for uniqueness"
3526
+ );
3527
+ }
3442
3528
  try {
3529
+ if (!this.artifactService) {
3530
+ throw new Error("ArtifactService is not initialized");
3531
+ }
3443
3532
  await this.artifactService.saveArtifact({
3444
3533
  artifactId: artifactData.artifactId,
3445
3534
  name: result.name,
3446
3535
  description: result.description,
3447
3536
  type: artifactData.artifactType || "source",
3448
3537
  data: artifactData.data || {},
3538
+ summaryData: artifactData.summaryData,
3449
3539
  metadata: artifactData.metadata || {},
3450
3540
  toolCallId: artifactData.toolCallId
3451
3541
  });
@@ -3461,7 +3551,13 @@ Make it specific and relevant.`;
3461
3551
  {
3462
3552
  sessionId: this.sessionId,
3463
3553
  artifactId: artifactData.artifactId,
3464
- error: saveError instanceof Error ? saveError.message : "Unknown error"
3554
+ error: saveError instanceof Error ? saveError.message : "Unknown error",
3555
+ errorName: saveError instanceof Error ? saveError.name : void 0,
3556
+ errorCause: saveError instanceof Error ? saveError.cause : void 0,
3557
+ errorCode: saveError?.code || saveError?.errno || void 0,
3558
+ artifactType: artifactData.artifactType,
3559
+ dataKeys: artifactData.data ? Object.keys(artifactData.data) : [],
3560
+ metadataKeys: artifactData.metadata ? Object.keys(artifactData.metadata) : []
3465
3561
  },
3466
3562
  "Main artifact save failed, will attempt fallback"
3467
3563
  );
@@ -3482,6 +3578,7 @@ Make it specific and relevant.`;
3482
3578
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool results"}`,
3483
3579
  type: artifactData.artifactType || "source",
3484
3580
  data: artifactData.data || {},
3581
+ summaryData: artifactData.summaryData,
3485
3582
  metadata: artifactData.metadata || {},
3486
3583
  toolCallId: artifactData.toolCallId
3487
3584
  });
@@ -3500,7 +3597,13 @@ Make it specific and relevant.`;
3500
3597
  {
3501
3598
  sessionId: this.sessionId,
3502
3599
  artifactId: artifactData.artifactId,
3503
- error: fallbackError instanceof Error ? fallbackError.message : "Unknown error"
3600
+ error: fallbackError instanceof Error ? fallbackError.message : "Unknown error",
3601
+ errorName: fallbackError instanceof Error ? fallbackError.name : void 0,
3602
+ errorCause: fallbackError instanceof Error ? fallbackError.cause : void 0,
3603
+ errorCode: fallbackError?.code || fallbackError?.errno || void 0,
3604
+ artifactType: artifactData.artifactType,
3605
+ dataKeys: artifactData.data ? Object.keys(artifactData.data) : [],
3606
+ metadataKeys: artifactData.metadata ? Object.keys(artifactData.metadata) : []
3504
3607
  },
3505
3608
  "Failed to save artifact even with fallback"
3506
3609
  );
@@ -3629,7 +3732,7 @@ var AgentSessionManager = class {
3629
3732
  /**
3630
3733
  * End a session and return the final event data
3631
3734
  */
3632
- endSession(sessionId) {
3735
+ async endSession(sessionId) {
3633
3736
  const session = this.sessions.get(sessionId);
3634
3737
  if (!session) {
3635
3738
  logger7.warn({ sessionId }, "Attempted to end non-existent session");
@@ -3638,7 +3741,7 @@ var AgentSessionManager = class {
3638
3741
  const events = session.getEvents();
3639
3742
  const summary = session.getSummary();
3640
3743
  logger7.info({ sessionId, summary }, "AgentSession ended");
3641
- session.cleanup();
3744
+ await session.cleanup();
3642
3745
  this.sessions.delete(sessionId);
3643
3746
  return events;
3644
3747
  }
@@ -4134,9 +4237,654 @@ ${chunk}`;
4134
4237
  }
4135
4238
  }
4136
4239
  };
4240
+ var logger9 = getLogger("distill-conversation-tool");
4241
+ var ConversationSummarySchema = z.object({
4242
+ type: z.literal("conversation_summary_v1"),
4243
+ session_id: z.string().nullable().optional(),
4244
+ high_level: z.string().describe("1-3 sentences capturing what was discovered and learned"),
4245
+ user_intent: z.string().describe("Current main goal or what the user wants to accomplish"),
4246
+ decisions: z.array(z.string()).describe("Concrete decisions made about approach or implementation (\u22645 items)"),
4247
+ open_questions: z.array(z.string()).describe("Unresolved questions about the subject matter (\u22645 items)"),
4248
+ next_steps: z.object({
4249
+ for_agent: z.array(z.string()).describe(
4250
+ "Content-focused actions: what to discover, analyze, or present. Don't get trapped in an infinite loop of tool calls. You have already done a lot of work that is why you are being compressed. Don't encourage too much more work."
4251
+ ),
4252
+ for_user: z.array(z.string()).describe("Actions for user based on discovered content")
4253
+ }),
4254
+ related_artifacts: z.array(
4255
+ z.object({
4256
+ id: z.string().describe("Artifact ID"),
4257
+ name: z.string().describe("Human-readable name describing the content"),
4258
+ tool_name: z.string().describe("Tool that generated this artifact (e.g. search-inkeep-docs)"),
4259
+ tool_call_id: z.string().describe("Specific tool call ID for precise referencing"),
4260
+ content_type: z.string().describe("Type of content (e.g. search_results, api_response, documentation)"),
4261
+ key_findings: z.array(z.string()).describe("2-3 most important findings from this specific artifact")
4262
+ })
4263
+ ).optional().describe("Artifacts containing detailed findings with citation info")
4264
+ });
4265
+ async function distillConversation(params) {
4266
+ const { messages, conversationId, currentSummary, summarizerModel, toolCallToArtifactMap } = params;
4267
+ try {
4268
+ const modelToUse = summarizerModel;
4269
+ if (!modelToUse?.model?.trim()) {
4270
+ throw new Error("Summarizer model is required");
4271
+ }
4272
+ const model = ModelFactory.createModel(modelToUse);
4273
+ const existingSummaryContext = currentSummary ? `**Current summary:**
4274
+
4275
+ \`\`\`json
4276
+ ${JSON.stringify(currentSummary, null, 2)}
4277
+ \`\`\`` : "**Current summary:** None (first distillation)";
4278
+ const formattedMessages = messages.map((msg) => {
4279
+ const parts = [];
4280
+ if (typeof msg.content === "string") {
4281
+ parts.push(msg.content);
4282
+ } else if (Array.isArray(msg.content)) {
4283
+ for (const block of msg.content) {
4284
+ if (block.type === "text") {
4285
+ parts.push(block.text);
4286
+ } else if (block.type === "tool-call") {
4287
+ parts.push(
4288
+ `[TOOL CALL] ${block.toolName}(${JSON.stringify(block.input)}) [ID: ${block.toolCallId}]`
4289
+ );
4290
+ } else if (block.type === "tool-result") {
4291
+ const artifactId = toolCallToArtifactMap?.[block.toolCallId];
4292
+ const artifactInfo = artifactId ? `
4293
+ [ARTIFACT CREATED: ${artifactId}]` : "";
4294
+ parts.push(
4295
+ `[TOOL RESULT] ${block.toolName} [ID: ${block.toolCallId}]${artifactInfo}
4296
+ Result: ${JSON.stringify(block.result)}`
4297
+ );
4298
+ }
4299
+ }
4300
+ } else if (msg.content?.text) {
4301
+ parts.push(msg.content.text);
4302
+ }
4303
+ return parts.length > 0 ? `${msg.role || "system"}: ${parts.join("\n")}` : "";
4304
+ }).filter((line) => line.trim().length > 0).join("\n\n");
4305
+ logger9.debug(
4306
+ {
4307
+ conversationId,
4308
+ messageCount: messages.length,
4309
+ formattedLength: formattedMessages.length,
4310
+ sampleMessages: messages.slice(0, 2).map((m) => ({ role: m.role, contentType: typeof m.content, hasContent: !!m.content }))
4311
+ },
4312
+ "Formatting messages for distillation"
4313
+ );
4314
+ const prompt = `You are a conversation summarization assistant. Your job is to create or update a compact, structured summary that captures VALUABLE CONTENT and FINDINGS, not just operational details.
4315
+
4316
+ ${existingSummaryContext}
4317
+
4318
+ **Messages to summarize:**
4319
+
4320
+ \`\`\`text
4321
+ ${formattedMessages}
4322
+ \`\`\`
4323
+
4324
+ Create/update a summary using this exact JSON schema:
4325
+
4326
+ \`\`\`json
4327
+ {
4328
+ "type": "conversation_summary_v1",
4329
+ "session_id": "<conversationId>",
4330
+ "high_level": "<1\u20133 sentences capturing what was discovered and learned>",
4331
+ "user_intent": "<current main goal>",
4332
+ "decisions": ["<concrete decisions made>"],
4333
+ "open_questions": ["<unresolved issues>"],
4334
+ "next_steps": {
4335
+ "for_agent": ["<what agent should do>"],
4336
+ "for_user": ["<what user should do>"]
4337
+ },
4338
+ "related_artifacts": [
4339
+ {
4340
+ "id": "<artifact_id>",
4341
+ "name": "<descriptive name>",
4342
+ "tool_name": "<tool_name>",
4343
+ "tool_call_id": "<tool_call_id>",
4344
+ "content_type": "<search_results|api_response|documentation>",
4345
+ "key_findings": ["<important finding 1>", "<important finding 2>"]
4346
+ }
4347
+ ]
4348
+ }
4349
+ \`\`\`
4350
+
4351
+ **CRITICAL RULES - FOCUS ON CONTENT NOT OPERATIONS:**
4352
+ \u{1F3AF} **EXTRACT VALUABLE FINDINGS**: Capture the actual information discovered, data retrieved, insights gained
4353
+ \u{1F3AF} **IGNORE OPERATIONAL DETAILS**: Don't mention "tool was used", "artifact was created", "messages were compressed"
4354
+ \u{1F3AF} **PRESERVE SUBSTANCE**: Include specific facts, features, capabilities, configurations, results found
4355
+ \u{1F3AF} **BUILD KNOWLEDGE**: When updating existing summary, ADD new discoveries to existing knowledge
4356
+ \u{1F3AF} **BE CONCRETE**: Use specific details from tool results, not generic descriptions
4357
+ \u{1F3AF} **BE CONCISE**: Keep ALL fields brief - you are compressing to save context, not writing a report
4358
+ \u{1F3AF} **LIMIT NEXT STEPS**: Agent has already done substantial work - suggest minimal follow-up actions only
4359
+
4360
+ **Examples:**
4361
+ \u274C BAD: "Assistant used search tool and created artifacts"
4362
+ \u2705 GOOD: "Inkeep supports streaming structured objects, OpenAI-compatible APIs, analytics logging, and Zendesk integration"
4363
+
4364
+ \u274C BAD: "Tool calls were made to gather information"
4365
+ \u2705 GOOD: "Platform includes 10 feature categories: chat widgets, knowledge base, analytics, integrations, theming options"
4366
+
4367
+ **Focus on WHAT WAS LEARNED, not HOW IT WAS LEARNED**
4368
+
4369
+ Return **only** valid JSON.`;
4370
+ const { object: summary } = await generateObject({
4371
+ model,
4372
+ prompt,
4373
+ schema: ConversationSummarySchema
4374
+ });
4375
+ summary.session_id = conversationId;
4376
+ logger9.info(
4377
+ {
4378
+ conversationId,
4379
+ messageCount: messages.length,
4380
+ artifactsCount: summary.related_artifacts?.length || 0,
4381
+ decisionsCount: summary.decisions.length
4382
+ },
4383
+ "Successfully distilled conversation"
4384
+ );
4385
+ return summary;
4386
+ } catch (error) {
4387
+ logger9.error(
4388
+ {
4389
+ conversationId,
4390
+ messageCount: messages.length,
4391
+ error: error instanceof Error ? error.message : "Unknown error"
4392
+ },
4393
+ "Failed to distill conversation"
4394
+ );
4395
+ return {
4396
+ type: "conversation_summary_v1",
4397
+ session_id: conversationId,
4398
+ high_level: "Ongoing conversation session",
4399
+ user_intent: "Continue working on current task",
4400
+ related_artifacts: [],
4401
+ decisions: [],
4402
+ open_questions: ["Review recent work and determine next steps"],
4403
+ next_steps: {
4404
+ for_agent: ["Continue with current task"],
4405
+ for_user: ["Provide additional guidance if needed"]
4406
+ }
4407
+ };
4408
+ }
4409
+ }
4410
+
4411
+ // src/services/MidGenerationCompressor.ts
4412
+ var logger10 = getLogger("MidGenerationCompressor");
4413
+ function getCompressionConfigFromEnv() {
4414
+ return {
4415
+ hardLimit: parseInt(process.env.AGENTS_COMPRESSION_HARD_LIMIT || "120000"),
4416
+ safetyBuffer: parseInt(process.env.AGENTS_COMPRESSION_SAFETY_BUFFER || "20000"),
4417
+ enabled: process.env.AGENTS_COMPRESSION_ENABLED !== "false"
4418
+ // Default enabled
4419
+ };
4420
+ }
4421
+ var MidGenerationCompressor = class {
4422
+ // Track cumulative summary across compression cycles
4423
+ constructor(sessionId, conversationId, tenantId, projectId, config, summarizerModel, baseModel) {
4424
+ this.sessionId = sessionId;
4425
+ this.conversationId = conversationId;
4426
+ this.tenantId = tenantId;
4427
+ this.projectId = projectId;
4428
+ this.config = config;
4429
+ this.summarizerModel = summarizerModel;
4430
+ this.baseModel = baseModel;
4431
+ }
4432
+ shouldCompress = false;
4433
+ processedToolCalls = /* @__PURE__ */ new Set();
4434
+ // Track already compressed tool call IDs
4435
+ lastProcessedMessageIndex = 0;
4436
+ // Track where we left off in message processing
4437
+ cumulativeSummary = null;
4438
+ /**
4439
+ * Get the hard limit for compression decisions
4440
+ */
4441
+ getHardLimit() {
4442
+ return this.config.hardLimit;
4443
+ }
4444
+ /**
4445
+ * Estimate tokens (4 chars = 1 token)
4446
+ */
4447
+ estimateTokens(content) {
4448
+ const text = typeof content === "string" ? content : JSON.stringify(content);
4449
+ return Math.ceil(text.length / 4);
4450
+ }
4451
+ /**
4452
+ * Calculate total context size
4453
+ */
4454
+ calculateContextSize(messages) {
4455
+ const messageTokens = messages.reduce((total, msg) => {
4456
+ let msgTokens = 0;
4457
+ if (Array.isArray(msg.content)) {
4458
+ for (const block of msg.content) {
4459
+ if (block.type === "text") {
4460
+ msgTokens += this.estimateTokens(block.text || "");
4461
+ } else if (block.type === "tool-call") {
4462
+ msgTokens += this.estimateTokens(
4463
+ JSON.stringify({
4464
+ toolCallId: block.toolCallId,
4465
+ toolName: block.toolName,
4466
+ input: block.input
4467
+ })
4468
+ );
4469
+ } else if (block.type === "tool-result") {
4470
+ msgTokens += this.estimateTokens(
4471
+ JSON.stringify({
4472
+ toolCallId: block.toolCallId,
4473
+ toolName: block.toolName,
4474
+ output: block.output
4475
+ })
4476
+ );
4477
+ }
4478
+ }
4479
+ } else if (typeof msg.content === "string") {
4480
+ msgTokens += this.estimateTokens(msg.content);
4481
+ } else if (msg.content) {
4482
+ msgTokens += this.estimateTokens(JSON.stringify(msg.content));
4483
+ }
4484
+ return total + msgTokens;
4485
+ }, 0);
4486
+ return messageTokens;
4487
+ }
4488
+ /**
4489
+ * Manual compression request from LLM tool
4490
+ */
4491
+ requestManualCompression(reason) {
4492
+ this.shouldCompress = true;
4493
+ logger10.info(
4494
+ {
4495
+ sessionId: this.sessionId,
4496
+ reason: reason || "Manual request from LLM"
4497
+ },
4498
+ "Manual compression requested"
4499
+ );
4500
+ }
4501
+ /**
4502
+ * Check if compression is needed (either automatic or manual)
4503
+ */
4504
+ isCompressionNeeded(messages) {
4505
+ if (this.shouldCompress) return true;
4506
+ const contextSize = this.calculateContextSize(messages);
4507
+ const remaining = this.config.hardLimit - contextSize;
4508
+ return remaining <= this.config.safetyBuffer;
4509
+ }
4510
+ /**
4511
+ * Perform compression: save all tool results as artifacts and create summary
4512
+ */
4513
+ async compress(messages) {
4514
+ const contextSizeBefore = this.calculateContextSize(messages);
4515
+ logger10.info(
4516
+ {
4517
+ sessionId: this.sessionId,
4518
+ messageCount: messages.length,
4519
+ contextSize: contextSizeBefore
4520
+ },
4521
+ "COMPRESSION: Starting compression"
4522
+ );
4523
+ const toolResultCount = messages.reduce((count, msg) => {
4524
+ if (Array.isArray(msg.content)) {
4525
+ return count + msg.content.filter((block) => block.type === "tool-result").length;
4526
+ }
4527
+ return count;
4528
+ }, 0);
4529
+ logger10.debug({ toolResultCount }, "Tool results found for compression");
4530
+ const toolCallToArtifactMap = await this.saveToolResultsAsArtifacts(messages);
4531
+ const summary = await this.createConversationSummary(messages, toolCallToArtifactMap);
4532
+ const contextSizeAfter = this.estimateTokens(JSON.stringify(summary));
4533
+ const session = agentSessionManager.getSession(this.sessionId);
4534
+ if (session) {
4535
+ const wasManualRequest = this.shouldCompress;
4536
+ session.recordEvent("compression", this.sessionId, {
4537
+ reason: wasManualRequest ? "manual" : "automatic",
4538
+ messageCount: messages.length,
4539
+ artifactCount: Object.keys(toolCallToArtifactMap).length,
4540
+ contextSizeBefore,
4541
+ contextSizeAfter,
4542
+ compressionType: "mid_generation"
4543
+ });
4544
+ }
4545
+ this.shouldCompress = false;
4546
+ logger10.info(
4547
+ {
4548
+ sessionId: this.sessionId,
4549
+ artifactsCreated: Object.keys(toolCallToArtifactMap).length,
4550
+ messageCount: messages.length,
4551
+ contextSizeBefore,
4552
+ contextSizeAfter,
4553
+ artifactIds: Object.values(toolCallToArtifactMap)
4554
+ },
4555
+ "COMPRESSION: Compression completed successfully"
4556
+ );
4557
+ return { artifactIds: Object.values(toolCallToArtifactMap), summary };
4558
+ }
4559
+ /**
4560
+ * 1. Save NEW tool results as artifacts (only process messages since last compression)
4561
+ */
4562
+ async saveToolResultsAsArtifacts(messages) {
4563
+ const session = agentSessionManager.getSession(this.sessionId);
4564
+ if (!session) {
4565
+ throw new Error(`No session found: ${this.sessionId}`);
4566
+ }
4567
+ const toolCallToArtifactMap = {};
4568
+ const newMessages = messages.slice(this.lastProcessedMessageIndex);
4569
+ logger10.debug(
4570
+ {
4571
+ totalMessages: messages.length,
4572
+ newMessages: newMessages.length,
4573
+ startIndex: this.lastProcessedMessageIndex
4574
+ },
4575
+ "Starting compression artifact processing"
4576
+ );
4577
+ for (const message of newMessages) {
4578
+ if (Array.isArray(message.content)) {
4579
+ for (const block of message.content) {
4580
+ if (block.type === "tool-result") {
4581
+ if (block.toolName === "get_reference_artifact" || block.toolName === "thinking_complete") {
4582
+ logger10.debug(
4583
+ {
4584
+ toolCallId: block.toolCallId,
4585
+ toolName: block.toolName
4586
+ },
4587
+ "Skipping special tool - not creating artifacts"
4588
+ );
4589
+ this.processedToolCalls.add(block.toolCallId);
4590
+ continue;
4591
+ }
4592
+ if (this.processedToolCalls.has(block.toolCallId)) {
4593
+ logger10.debug(
4594
+ {
4595
+ toolCallId: block.toolCallId,
4596
+ toolName: block.toolName
4597
+ },
4598
+ "Skipping already processed tool call"
4599
+ );
4600
+ continue;
4601
+ }
4602
+ const artifactId = `compress_${block.toolName || "tool"}_${block.toolCallId || Date.now()}_${randomUUID().slice(0, 8)}`;
4603
+ logger10.debug(
4604
+ {
4605
+ artifactId,
4606
+ toolName: block.toolName,
4607
+ toolCallId: block.toolCallId
4608
+ },
4609
+ "Saving compression artifact"
4610
+ );
4611
+ let toolInput = null;
4612
+ if (Array.isArray(message.content)) {
4613
+ const toolCall = message.content.find(
4614
+ (b) => b.type === "tool-call" && b.toolCallId === block.toolCallId
4615
+ );
4616
+ toolInput = toolCall?.input;
4617
+ }
4618
+ const cleanToolResult = this.removeStructureHints(block.output);
4619
+ const toolResultData = {
4620
+ toolName: block.toolName,
4621
+ toolInput,
4622
+ toolResult: cleanToolResult,
4623
+ compressedAt: (/* @__PURE__ */ new Date()).toISOString()
4624
+ };
4625
+ if (this.isEmpty(toolResultData)) {
4626
+ logger10.debug(
4627
+ {
4628
+ toolName: block.toolName,
4629
+ toolCallId: block.toolCallId
4630
+ },
4631
+ "Skipping empty tool result"
4632
+ );
4633
+ continue;
4634
+ }
4635
+ const artifactData = {
4636
+ artifactId,
4637
+ taskId: `task_${this.conversationId}-${this.sessionId}`,
4638
+ toolCallId: block.toolCallId,
4639
+ artifactType: "tool_result",
4640
+ pendingGeneration: true,
4641
+ // Triggers LLM-generated name/description
4642
+ tenantId: this.tenantId,
4643
+ projectId: this.projectId,
4644
+ contextId: this.conversationId,
4645
+ subAgentId: this.sessionId,
4646
+ metadata: {
4647
+ toolCallId: block.toolCallId,
4648
+ toolName: block.toolName,
4649
+ compressionReason: "mid_generation_context_limit"
4650
+ },
4651
+ // Pass data in the format expected by ArtifactSavedData interface
4652
+ summaryData: {
4653
+ toolName: block.toolName,
4654
+ note: "Compressed tool result - see full data for details"
4655
+ },
4656
+ data: toolResultData
4657
+ // Full tool result data
4658
+ };
4659
+ const fullData = artifactData.data;
4660
+ const hasFullData = fullData && typeof fullData === "object" && Object.keys(fullData).length > 0 && // Check if toolResult specifically has content
4661
+ fullData.toolResult && (typeof fullData.toolResult !== "object" || Object.keys(fullData.toolResult).length > 0);
4662
+ if (!hasFullData) {
4663
+ logger10.debug(
4664
+ {
4665
+ artifactId,
4666
+ toolName: block.toolName,
4667
+ toolCallId: block.toolCallId
4668
+ },
4669
+ "Skipping empty compression artifact"
4670
+ );
4671
+ continue;
4672
+ }
4673
+ session.recordEvent("artifact_saved", this.sessionId, artifactData);
4674
+ this.processedToolCalls.add(block.toolCallId);
4675
+ toolCallToArtifactMap[block.toolCallId] = artifactId;
4676
+ }
4677
+ }
4678
+ }
4679
+ }
4680
+ this.lastProcessedMessageIndex = messages.length;
4681
+ logger10.debug(
4682
+ {
4683
+ totalArtifactsCreated: Object.keys(toolCallToArtifactMap).length,
4684
+ newMessageIndex: this.lastProcessedMessageIndex
4685
+ },
4686
+ "Compression artifact processing completed"
4687
+ );
4688
+ return toolCallToArtifactMap;
4689
+ }
4690
+ /**
4691
+ * 3. Create conversation summary with artifact references
4692
+ */
4693
+ async createConversationSummary(messages, toolCallToArtifactMap) {
4694
+ const textMessages = this.extractTextMessages(messages, toolCallToArtifactMap);
4695
+ logger10.debug(
4696
+ {
4697
+ sessionId: this.sessionId,
4698
+ messageCount: messages.length,
4699
+ textMessageCount: textMessages.length,
4700
+ artifactCount: Object.keys(toolCallToArtifactMap).length,
4701
+ sampleMessages: messages.slice(0, 2).map((m) => ({
4702
+ role: m.role,
4703
+ contentType: typeof m.content,
4704
+ contentPreview: typeof m.content === "string" ? m.content.substring(0, 100) : "array/object"
4705
+ }))
4706
+ },
4707
+ "Starting distillation with debug info"
4708
+ );
4709
+ const summary = await distillConversation({
4710
+ messages,
4711
+ conversationId: this.conversationId,
4712
+ currentSummary: this.cumulativeSummary,
4713
+ // Pass existing summary for cumulative building
4714
+ summarizerModel: this.summarizerModel,
4715
+ toolCallToArtifactMap
4716
+ // Pass mapping for message formatting
4717
+ });
4718
+ this.cumulativeSummary = summary;
4719
+ logger10.debug(
4720
+ {
4721
+ sessionId: this.sessionId,
4722
+ summaryGenerated: !!summary,
4723
+ summaryHighLevel: summary?.high_level,
4724
+ artifactsCount: summary?.related_artifacts?.length || 0
4725
+ },
4726
+ "Distillation completed"
4727
+ );
4728
+ return {
4729
+ text_messages: textMessages,
4730
+ summary
4731
+ };
4732
+ }
4733
+ /**
4734
+ * Extract text messages and convert tool calls to descriptive text
4735
+ * Avoids API tool-call/tool-result pairing issues while preserving context
4736
+ */
4737
+ extractTextMessages(messages, toolCallToArtifactMap) {
4738
+ const textMessages = [];
4739
+ const toolCallPairs = /* @__PURE__ */ new Map();
4740
+ for (const message of messages) {
4741
+ if (Array.isArray(message.content)) {
4742
+ for (const block of message.content) {
4743
+ if (block.type === "tool-call") {
4744
+ if (!toolCallPairs.has(block.toolCallId)) {
4745
+ toolCallPairs.set(block.toolCallId, { call: block, result: null });
4746
+ } else {
4747
+ toolCallPairs.get(block.toolCallId).call = block;
4748
+ }
4749
+ } else if (block.type === "tool-result") {
4750
+ if (!toolCallPairs.has(block.toolCallId)) {
4751
+ toolCallPairs.set(block.toolCallId, { call: null, result: block });
4752
+ } else {
4753
+ toolCallPairs.get(block.toolCallId).result = block;
4754
+ }
4755
+ }
4756
+ }
4757
+ }
4758
+ }
4759
+ for (const message of messages) {
4760
+ if (message.role === "assistant" && typeof message.content === "string") {
4761
+ textMessages.push({
4762
+ role: message.role,
4763
+ content: message.content
4764
+ });
4765
+ } else if (message.role === "assistant" && Array.isArray(message.content)) {
4766
+ const textParts = [];
4767
+ const toolCallsInMessage = /* @__PURE__ */ new Set();
4768
+ const preservedBlocks = [];
4769
+ for (const block of message.content) {
4770
+ if (block.type === "text") {
4771
+ textParts.push(block.text);
4772
+ } else if (block.type === "tool-call" && block.toolName === "thinking_complete") ; else if (block.type === "tool-call") {
4773
+ toolCallsInMessage.add(block.toolCallId);
4774
+ }
4775
+ }
4776
+ for (const toolCallId of toolCallsInMessage) {
4777
+ const pair = toolCallPairs.get(toolCallId);
4778
+ const artifactId = toolCallToArtifactMap[toolCallId];
4779
+ if (pair?.call) {
4780
+ const args = JSON.stringify(pair.call.input);
4781
+ const artifactText = artifactId ? ` Results compressed into artifact: ${artifactId}.` : " Results were compressed but not saved.";
4782
+ textParts.push(`I called ${pair.call.toolName}(${args}).${artifactText}`);
4783
+ }
4784
+ }
4785
+ if (preservedBlocks.length > 0 && textParts.length > 0) {
4786
+ const content = [...preservedBlocks];
4787
+ if (textParts.length > 0) {
4788
+ content.push({ type: "text", text: textParts.join("\n\n") });
4789
+ }
4790
+ textMessages.push({
4791
+ role: message.role,
4792
+ content
4793
+ });
4794
+ } else if (preservedBlocks.length > 0) {
4795
+ textMessages.push({
4796
+ role: message.role,
4797
+ content: preservedBlocks
4798
+ });
4799
+ } else if (textParts.length > 0) {
4800
+ textMessages.push({
4801
+ role: message.role,
4802
+ content: textParts.join("\n\n")
4803
+ });
4804
+ }
4805
+ }
4806
+ }
4807
+ return textMessages;
4808
+ }
4809
+ // Removed focus hint helper methods - no longer needed since tool results are in formatted messages
4810
+ /**
4811
+ * Check if tool result data is effectively empty
4812
+ */
4813
+ isEmpty(toolResultData) {
4814
+ if (!toolResultData || typeof toolResultData !== "object") {
4815
+ return true;
4816
+ }
4817
+ const { toolResult } = toolResultData;
4818
+ if (!toolResult) {
4819
+ return true;
4820
+ }
4821
+ if (typeof toolResult === "object" && !Array.isArray(toolResult)) {
4822
+ const keys = Object.keys(toolResult);
4823
+ if (keys.length === 0) {
4824
+ return true;
4825
+ }
4826
+ return keys.every((key) => {
4827
+ const value = toolResult[key];
4828
+ if (value === null || value === void 0 || value === "") {
4829
+ return true;
4830
+ }
4831
+ if (Array.isArray(value) && value.length === 0) {
4832
+ return true;
4833
+ }
4834
+ if (typeof value === "object" && Object.keys(value).length === 0) {
4835
+ return true;
4836
+ }
4837
+ return false;
4838
+ });
4839
+ }
4840
+ if (Array.isArray(toolResult) && toolResult.length === 0) {
4841
+ return true;
4842
+ }
4843
+ if (typeof toolResult === "string" && toolResult.trim() === "") {
4844
+ return true;
4845
+ }
4846
+ return false;
4847
+ }
4848
+ /**
4849
+ * Recursively remove _structureHints from an object
4850
+ */
4851
+ removeStructureHints(obj) {
4852
+ if (obj === null || obj === void 0) {
4853
+ return obj;
4854
+ }
4855
+ if (Array.isArray(obj)) {
4856
+ return obj.map((item) => this.removeStructureHints(item));
4857
+ }
4858
+ if (typeof obj === "object") {
4859
+ const cleaned = {};
4860
+ for (const [key, value] of Object.entries(obj)) {
4861
+ if (key !== "_structureHints") {
4862
+ cleaned[key] = this.removeStructureHints(value);
4863
+ }
4864
+ }
4865
+ return cleaned;
4866
+ }
4867
+ return obj;
4868
+ }
4869
+ /**
4870
+ * Get current state for debugging
4871
+ */
4872
+ getState() {
4873
+ return {
4874
+ shouldCompress: this.shouldCompress,
4875
+ config: this.config
4876
+ };
4877
+ }
4878
+ /**
4879
+ * Get the current compression summary
4880
+ */
4881
+ getCompressionSummary() {
4882
+ return this.cumulativeSummary;
4883
+ }
4884
+ };
4137
4885
 
4138
4886
  // src/services/PendingToolApprovalManager.ts
4139
- var logger9 = getLogger("PendingToolApprovalManager");
4887
+ var logger11 = getLogger("PendingToolApprovalManager");
4140
4888
  var APPROVAL_CLEANUP_INTERVAL_MS = 2 * 60 * 1e3;
4141
4889
  var APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
4142
4890
  var PendingToolApprovalManager = class _PendingToolApprovalManager {
@@ -4175,7 +4923,7 @@ var PendingToolApprovalManager = class _PendingToolApprovalManager {
4175
4923
  timeoutId
4176
4924
  };
4177
4925
  this.pendingApprovals.set(toolCallId, approval);
4178
- logger9.info(
4926
+ logger11.info(
4179
4927
  {
4180
4928
  toolCallId,
4181
4929
  toolName,
@@ -4192,10 +4940,10 @@ var PendingToolApprovalManager = class _PendingToolApprovalManager {
4192
4940
  approveToolCall(toolCallId) {
4193
4941
  const approval = this.pendingApprovals.get(toolCallId);
4194
4942
  if (!approval) {
4195
- logger9.warn({ toolCallId }, "Tool approval not found or already processed");
4943
+ logger11.warn({ toolCallId }, "Tool approval not found or already processed");
4196
4944
  return false;
4197
4945
  }
4198
- logger9.info(
4946
+ logger11.info(
4199
4947
  {
4200
4948
  toolCallId,
4201
4949
  toolName: approval.toolName,
@@ -4214,10 +4962,10 @@ var PendingToolApprovalManager = class _PendingToolApprovalManager {
4214
4962
  denyToolCall(toolCallId, reason) {
4215
4963
  const approval = this.pendingApprovals.get(toolCallId);
4216
4964
  if (!approval) {
4217
- logger9.warn({ toolCallId }, "Tool approval not found or already processed");
4965
+ logger11.warn({ toolCallId }, "Tool approval not found or already processed");
4218
4966
  return false;
4219
4967
  }
4220
- logger9.info(
4968
+ logger11.info(
4221
4969
  {
4222
4970
  toolCallId,
4223
4971
  toolName: approval.toolName,
@@ -4249,7 +4997,7 @@ var PendingToolApprovalManager = class _PendingToolApprovalManager {
4249
4997
  }
4250
4998
  }
4251
4999
  if (cleanedUp > 0) {
4252
- logger9.info({ cleanedUp }, "Cleaned up expired tool approvals");
5000
+ logger11.info({ cleanedUp }, "Cleaned up expired tool approvals");
4253
5001
  }
4254
5002
  }
4255
5003
  /**
@@ -4272,7 +5020,7 @@ var PendingToolApprovalManager = class _PendingToolApprovalManager {
4272
5020
  var pendingToolApprovalManager = PendingToolApprovalManager.getInstance();
4273
5021
 
4274
5022
  // src/services/ResponseFormatter.ts
4275
- var logger10 = getLogger("ResponseFormatter");
5023
+ var logger12 = getLogger("ResponseFormatter");
4276
5024
  var ResponseFormatter = class {
4277
5025
  artifactParser;
4278
5026
  subAgentId;
@@ -4331,7 +5079,7 @@ var ResponseFormatter = class {
4331
5079
  return { parts };
4332
5080
  } catch (error) {
4333
5081
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4334
- logger10.error({ error, responseObject }, "Error formatting object response");
5082
+ logger12.error({ error, responseObject }, "Error formatting object response");
4335
5083
  return {
4336
5084
  parts: [{ kind: "data", data: responseObject }]
4337
5085
  };
@@ -4387,7 +5135,7 @@ var ResponseFormatter = class {
4387
5135
  return { parts };
4388
5136
  } catch (error) {
4389
5137
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4390
- logger10.error({ error, responseText }, "Error formatting response");
5138
+ logger12.error({ error, responseText }, "Error formatting response");
4391
5139
  return { text: responseText };
4392
5140
  } finally {
4393
5141
  span.end();
@@ -4463,46 +5211,6 @@ function errorOp(message, subAgentId, severity = "error", code) {
4463
5211
  function generateToolId() {
4464
5212
  return `tool_${generateId(8)}`;
4465
5213
  }
4466
- var logger11 = getLogger("DataComponentSchema");
4467
- function jsonSchemaToZod(jsonSchema) {
4468
- if (!jsonSchema || typeof jsonSchema !== "object") {
4469
- logger11.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
4470
- return z.string();
4471
- }
4472
- switch (jsonSchema.type) {
4473
- case "object":
4474
- if (jsonSchema.properties) {
4475
- const shape = {};
4476
- for (const [key, prop] of Object.entries(jsonSchema.properties)) {
4477
- shape[key] = jsonSchemaToZod(prop);
4478
- }
4479
- return z.object(shape);
4480
- }
4481
- return z.record(z.string(), z.unknown());
4482
- case "array": {
4483
- const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z.unknown();
4484
- return z.array(itemSchema);
4485
- }
4486
- case "string":
4487
- return z.string();
4488
- case "number":
4489
- case "integer":
4490
- return z.number();
4491
- case "boolean":
4492
- return z.boolean();
4493
- case "null":
4494
- return z.null();
4495
- default:
4496
- logger11.warn(
4497
- {
4498
- unsupportedType: jsonSchema.type,
4499
- schema: jsonSchema
4500
- },
4501
- "Unsupported JSON schema type, using unknown validation"
4502
- );
4503
- return z.unknown();
4504
- }
4505
- }
4506
5214
  var SchemaProcessor = class _SchemaProcessor {
4507
5215
  static logger = getLogger("SchemaProcessor");
4508
5216
  /**
@@ -4744,9 +5452,9 @@ var ArtifactReferenceSchema = class _ArtifactReferenceSchema {
4744
5452
  * Get the standard Zod schema for artifact reference components
4745
5453
  */
4746
5454
  static getSchema() {
4747
- return z.object({
4748
- id: z.string(),
4749
- name: z.literal("Artifact"),
5455
+ return z$1.object({
5456
+ id: z$1.string(),
5457
+ name: z$1.literal("Artifact"),
4750
5458
  props: jsonSchemaToZod(_ArtifactReferenceSchema.ARTIFACT_PROPS_SCHEMA)
4751
5459
  });
4752
5460
  }
@@ -4797,9 +5505,9 @@ var ArtifactCreateSchema = class {
4797
5505
  },
4798
5506
  required: ["id", "tool_call_id", "type", "base_selector"]
4799
5507
  };
4800
- return z.object({
4801
- id: z.string(),
4802
- name: z.literal(`ArtifactCreate_${component.name}`),
5508
+ return z$1.object({
5509
+ id: z$1.string(),
5510
+ name: z$1.literal(`ArtifactCreate_${component.name}`),
4803
5511
  props: jsonSchemaToZod(propsSchema)
4804
5512
  });
4805
5513
  });
@@ -4859,7 +5567,7 @@ function parseEmbeddedJson(data) {
4859
5567
  }
4860
5568
 
4861
5569
  // src/a2a/client.ts
4862
- var logger12 = getLogger("a2aClient");
5570
+ var logger13 = getLogger("a2aClient");
4863
5571
  var DEFAULT_BACKOFF = {
4864
5572
  initialInterval: 500,
4865
5573
  maxInterval: 6e4,
@@ -5066,7 +5774,7 @@ var A2AClient = class {
5066
5774
  try {
5067
5775
  const res = await fn();
5068
5776
  if (attempt > 0) {
5069
- logger12.info(
5777
+ logger13.info(
5070
5778
  {
5071
5779
  attempts: attempt + 1,
5072
5780
  elapsedTime: Date.now() - start
@@ -5081,7 +5789,7 @@ var A2AClient = class {
5081
5789
  }
5082
5790
  const elapsed = Date.now() - start;
5083
5791
  if (elapsed > maxElapsedTime) {
5084
- logger12.warn(
5792
+ logger13.warn(
5085
5793
  {
5086
5794
  attempts: attempt + 1,
5087
5795
  elapsedTime: elapsed,
@@ -5102,7 +5810,7 @@ var A2AClient = class {
5102
5810
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
5103
5811
  }
5104
5812
  const delayMs = Math.min(retryInterval, maxInterval);
5105
- logger12.info(
5813
+ logger13.info(
5106
5814
  {
5107
5815
  attempt: attempt + 1,
5108
5816
  delayMs,
@@ -5193,7 +5901,7 @@ var A2AClient = class {
5193
5901
  });
5194
5902
  }
5195
5903
  if (rpcResponse.id !== requestId2) {
5196
- logger12.warn(
5904
+ logger13.warn(
5197
5905
  {
5198
5906
  method,
5199
5907
  expectedId: requestId2,
@@ -5390,7 +6098,7 @@ var A2AClient = class {
5390
6098
  try {
5391
6099
  while (true) {
5392
6100
  const { done, value } = await reader.read();
5393
- logger12.info({ done, value }, "parseA2ASseStream");
6101
+ logger13.info({ done, value }, "parseA2ASseStream");
5394
6102
  if (done) {
5395
6103
  if (eventDataBuffer.trim()) {
5396
6104
  const result = this._processSseEventData(
@@ -5477,7 +6185,7 @@ var A2AClient = class {
5477
6185
  };
5478
6186
 
5479
6187
  // src/agents/relationTools.ts
5480
- var logger13 = getLogger("relationships Tools");
6188
+ var logger14 = getLogger("relationships Tools");
5481
6189
  var A2A_RETRY_STATUS_CODES = ["429", "500", "502", "503", "504"];
5482
6190
  var generateTransferToolDescription = (config) => {
5483
6191
  let toolsSection = "";
@@ -5502,9 +6210,9 @@ Can Delegate To:
5502
6210
  ${delegateList}`;
5503
6211
  }
5504
6212
  if (config.tools && config.tools.length > 0) {
5505
- const toolDescriptions = config.tools.map((tool3) => {
5506
- const toolsList = tool3.availableTools?.map((t) => ` - ${t.name}: ${t.description || "No description available"}`).join("\n") || "";
5507
- return `MCP Server: ${tool3.name}
6213
+ const toolDescriptions = config.tools.map((tool4) => {
6214
+ const toolsList = tool4.availableTools?.map((t) => ` - ${t.name}: ${t.description || "No description available"}`).join("\n") || "";
6215
+ return `MCP Server: ${tool4.name}
5508
6216
  ${toolsList}`;
5509
6217
  }).join("\n\n");
5510
6218
  toolsSection = `
@@ -5530,9 +6238,9 @@ var generateDelegateToolDescription = (delegateRelation) => {
5530
6238
  if (delegateRelation.type === "internal" && "tools" in config) {
5531
6239
  const agentConfig = config;
5532
6240
  if (agentConfig.tools && agentConfig.tools.length > 0) {
5533
- const toolDescriptions = agentConfig.tools.map((tool3) => {
5534
- const toolsList = tool3.availableTools?.map((t) => ` - ${t.name}: ${t.description || "No description available"}`).join("\n") || "";
5535
- return `MCP Server: ${tool3.name}
6241
+ const toolDescriptions = agentConfig.tools.map((tool4) => {
6242
+ const toolsList = tool4.availableTools?.map((t) => ` - ${t.name}: ${t.description || "No description available"}`).join("\n") || "";
6243
+ return `MCP Server: ${tool4.name}
5536
6244
  ${toolsList}`;
5537
6245
  }).join("\n\n");
5538
6246
  toolsSection = `
@@ -5579,7 +6287,7 @@ var createTransferToAgentTool = ({
5579
6287
  const toolDescription = generateTransferToolDescription(transferConfig);
5580
6288
  return tool({
5581
6289
  description: toolDescription,
5582
- inputSchema: z.object({}),
6290
+ inputSchema: z$1.object({}),
5583
6291
  execute: async () => {
5584
6292
  const activeSpan = trace.getActiveSpan();
5585
6293
  if (activeSpan) {
@@ -5588,7 +6296,7 @@ var createTransferToAgentTool = ({
5588
6296
  [SPAN_KEYS.TRANSFER_TO_SUB_AGENT_ID]: transferConfig.id ?? "unknown"
5589
6297
  });
5590
6298
  }
5591
- logger13.info(
6299
+ logger14.info(
5592
6300
  {
5593
6301
  transferTo: transferConfig.id ?? "unknown",
5594
6302
  fromSubAgent: callingAgentId
@@ -5609,7 +6317,7 @@ var createTransferToAgentTool = ({
5609
6317
  fromSubAgentId: callingAgentId
5610
6318
  // Include the calling agent ID for tracking
5611
6319
  };
5612
- logger13.info(
6320
+ logger14.info(
5613
6321
  {
5614
6322
  transferResult,
5615
6323
  transferResultKeys: Object.keys(transferResult)
@@ -5634,7 +6342,7 @@ function createDelegateToAgentTool({
5634
6342
  }) {
5635
6343
  return tool({
5636
6344
  description: generateDelegateToolDescription(delegateConfig),
5637
- inputSchema: z.object({ message: z.string() }),
6345
+ inputSchema: z$1.object({ message: z$1.string() }),
5638
6346
  execute: async (input, context) => {
5639
6347
  const delegationId = `del_${generateId()}`;
5640
6348
  const activeSpan = trace.getActiveSpan();
@@ -5756,7 +6464,7 @@ function createDelegateToAgentTool({
5756
6464
  ...isInternal ? { fromSubAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
5757
6465
  }
5758
6466
  };
5759
- logger13.info({ messageToSend }, "messageToSend");
6467
+ logger14.info({ messageToSend }, "messageToSend");
5760
6468
  await createMessage(dbClient_default)({
5761
6469
  id: generateId(),
5762
6470
  tenantId,
@@ -5818,7 +6526,7 @@ function createDelegateToAgentTool({
5818
6526
  }
5819
6527
 
5820
6528
  // src/agents/SystemPromptBuilder.ts
5821
- var logger14 = getLogger("SystemPromptBuilder");
6529
+ var logger15 = getLogger("SystemPromptBuilder");
5822
6530
  var SystemPromptBuilder = class {
5823
6531
  constructor(version, versionConfig) {
5824
6532
  this.version = version;
@@ -5834,12 +6542,12 @@ var SystemPromptBuilder = class {
5834
6542
  this.templates.set(name, content);
5835
6543
  }
5836
6544
  this.loaded = true;
5837
- logger14.debug(
6545
+ logger15.debug(
5838
6546
  { templateCount: this.templates.size, version: this.version },
5839
6547
  `Loaded ${this.templates.size} templates for version ${this.version}`
5840
6548
  );
5841
6549
  } catch (error) {
5842
- logger14.error({ error }, `Failed to load templates for version ${this.version}`);
6550
+ logger15.error({ error }, `Failed to load templates for version ${this.version}`);
5843
6551
  throw new Error(`Template loading failed: ${error}`);
5844
6552
  }
5845
6553
  }
@@ -6079,7 +6787,14 @@ var Phase1Config = class _Phase1Config {
6079
6787
  throw new Error("System prompt template not loaded");
6080
6788
  }
6081
6789
  let systemPrompt = systemPromptTemplate;
6082
- systemPrompt = systemPrompt.replace("{{CORE_INSTRUCTIONS}}", config.corePrompt);
6790
+ if (config.corePrompt && config.corePrompt.trim()) {
6791
+ systemPrompt = systemPrompt.replace("{{CORE_INSTRUCTIONS}}", config.corePrompt);
6792
+ } else {
6793
+ systemPrompt = systemPrompt.replace(
6794
+ /<core_instructions>\s*\{\{CORE_INSTRUCTIONS\}\}\s*<\/core_instructions>/g,
6795
+ ""
6796
+ );
6797
+ }
6083
6798
  const agentContextSection = this.generateAgentContextSection(config.prompt);
6084
6799
  systemPrompt = systemPrompt.replace("{{AGENT_CONTEXT_SECTION}}", agentContextSection);
6085
6800
  const toolData = this.isToolDataArray(config.tools) ? config.tools : _Phase1Config.convertMcpToolsToToolData(config.tools);
@@ -6109,7 +6824,7 @@ var Phase1Config = class _Phase1Config {
6109
6824
  return systemPrompt;
6110
6825
  }
6111
6826
  generateAgentContextSection(prompt) {
6112
- if (!prompt) {
6827
+ if (!prompt || prompt.trim() === "") {
6113
6828
  return "";
6114
6829
  }
6115
6830
  return `
@@ -6222,6 +6937,8 @@ CREATING ARTIFACTS (SERVES AS CITATION):
6222
6937
  Use the artifact:create annotation to extract data from tool results. The creation itself serves as a citation.
6223
6938
  Format: <artifact:create id="unique-id" tool="tool_call_id" type="TypeName" base="selector.path" details='{"key":"jmespath_selector"}' />
6224
6939
 
6940
+ \u26A0\uFE0F IMPORTANT: Do not create artifacts from get_reference_artifact tool results - these are already compressed artifacts being retrieved. Only create artifacts from original research and analysis tools.
6941
+
6225
6942
  \u{1F6A8} CRITICAL: DETAILS PROPS USE JMESPATH SELECTORS, NOT LITERAL VALUES! \u{1F6A8}
6226
6943
 
6227
6944
  \u274C WRONG - Using literal values:
@@ -6246,6 +6963,8 @@ THE details PROPERTY MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE
6246
6963
  \u274C NEVER: [?text ~ contains(@, 'word')] (~ with @ operator)
6247
6964
  \u274C NEVER: contains(@, 'text') (@ operator usage)
6248
6965
  \u274C NEVER: [?field=="value"] (double quotes in filters)
6966
+ \u274C NEVER: [?field=='value'] (escaped quotes in filters)
6967
+ \u274C NEVER: [?field=='"'"'value'"'"'] (nightmare quote mixing)
6249
6968
  \u274C NEVER: result.items[?type=='doc'][?status=='active'] (chained filters)
6250
6969
 
6251
6970
  \u2705 CORRECT JMESPATH SYNTAX:
@@ -6257,6 +6976,11 @@ THE details PROPERTY MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE
6257
6976
  \u2705 [?contains(text, 'Founder')] (contains haystack, needle format)
6258
6977
  \u2705 source.content[?contains(text, 'Founder')].text (correct filter usage)
6259
6978
 
6979
+ \u{1F6A8} MANDATORY QUOTE PATTERN - FOLLOW EXACTLY:
6980
+ - ALWAYS: base="path[?field=='value']" (double quotes outside, single inside)
6981
+ - This is the ONLY allowed pattern - any other pattern WILL FAIL
6982
+ - NEVER escape quotes, NEVER mix quote types, NEVER use complex quoting
6983
+
6260
6984
  \u{1F6A8} CRITICAL: EXAMINE TOOL RESULTS BEFORE CREATING SELECTORS! \u{1F6A8}
6261
6985
 
6262
6986
  STEP 1: INSPECT THE ACTUAL DATA FIRST
@@ -6295,7 +7019,7 @@ Only use artifact:ref when you need to cite the SAME artifact again for a differ
6295
7019
  Format: <artifact:ref id="artifact-id" tool="tool_call_id" />
6296
7020
 
6297
7021
  EXAMPLE TEXT RESPONSE:
6298
- "I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base='result.documents[?type=="auth"]' details='{"title":"metadata.title","endpoint":"api.endpoint","description":"content.description","parameters":"spec.parameters","examples":"examples.sample_code"}' /> The documentation explains OAuth 2.0 implementation in detail.
7022
+ "I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base="result.documents[?type=='auth']" details='{"title":"metadata.title","endpoint":"api.endpoint","description":"content.description","parameters":"spec.parameters","examples":"examples.sample_code"}' /> The documentation explains OAuth 2.0 implementation in detail.
6299
7023
 
6300
7024
  The process involves three main steps: registration, token exchange, and API calls. As mentioned in the authentication documentation <artifact:ref id='auth-doc-1' tool='call_xyz789' />, you'll need to register your application first."
6301
7025
 
@@ -6433,27 +7157,27 @@ ${creationInstructions}
6433
7157
  if (tools.length === 0) {
6434
7158
  return '<available_tools description="No tools are currently available"></available_tools>';
6435
7159
  }
6436
- const toolsXml = tools.map((tool3) => this.generateToolXml(templates, tool3)).join("\n ");
7160
+ const toolsXml = tools.map((tool4) => this.generateToolXml(templates, tool4)).join("\n ");
6437
7161
  return `<available_tools description="These are the tools available for you to use to accomplish tasks">
6438
7162
  ${toolsXml}
6439
7163
  </available_tools>`;
6440
7164
  }
6441
- generateToolXml(templates, tool3) {
7165
+ generateToolXml(templates, tool4) {
6442
7166
  const toolTemplate = templates.get("tool");
6443
7167
  if (!toolTemplate) {
6444
7168
  throw new Error("Tool template not loaded");
6445
7169
  }
6446
7170
  let toolXml = toolTemplate;
6447
- toolXml = toolXml.replace("{{TOOL_NAME}}", tool3.name);
7171
+ toolXml = toolXml.replace("{{TOOL_NAME}}", tool4.name);
6448
7172
  toolXml = toolXml.replace(
6449
7173
  "{{TOOL_DESCRIPTION}}",
6450
- tool3.description || "No description available"
7174
+ tool4.description || "No description available"
6451
7175
  );
6452
7176
  toolXml = toolXml.replace(
6453
7177
  "{{TOOL_USAGE_GUIDELINES}}",
6454
- tool3.usageGuidelines || "Use this tool when appropriate."
7178
+ tool4.usageGuidelines || "Use this tool when appropriate."
6455
7179
  );
6456
- const parametersXml = this.generateParametersXml(tool3.inputSchema);
7180
+ const parametersXml = this.generateParametersXml(tool4.inputSchema);
6457
7181
  toolXml = toolXml.replace("{{TOOL_PARAMETERS_SCHEMA}}", parametersXml);
6458
7182
  return toolXml;
6459
7183
  }
@@ -6636,6 +7360,8 @@ CREATING ARTIFACTS (SERVES AS CITATION):
6636
7360
  Use the appropriate ArtifactCreate_[Type] component to extract and structure data from tool results.
6637
7361
  The creation itself serves as a citation - no additional reference needed.
6638
7362
 
7363
+ \u26A0\uFE0F IMPORTANT: Do not create artifacts from get_reference_artifact tool results - these are already compressed artifacts being retrieved. Only create artifacts from original research and analysis tools.
7364
+
6639
7365
  \u{1F6AB} FORBIDDEN JMESPATH PATTERNS:
6640
7366
  \u274C NEVER: [?title~'.*text.*'] (regex patterns with ~ operator)
6641
7367
  \u274C NEVER: [?field~'pattern.*'] (any ~ operator usage)
@@ -6793,7 +7519,7 @@ ${componentDescriptions}`;
6793
7519
  dataComponentXml = dataComponentXml.replace("{{COMPONENT_NAME}}", dataComponent.name);
6794
7520
  dataComponentXml = dataComponentXml.replace(
6795
7521
  "{{COMPONENT_DESCRIPTION}}",
6796
- dataComponent.description
7522
+ dataComponent.description || ""
6797
7523
  );
6798
7524
  dataComponentXml = dataComponentXml.replace(
6799
7525
  "{{COMPONENT_PROPS_SCHEMA}}",
@@ -6889,7 +7615,14 @@ ${artifact_retrieval_guidance_default}
6889
7615
  artifactComponents
6890
7616
  );
6891
7617
  let phase2Prompt = system_prompt_default2;
6892
- phase2Prompt = phase2Prompt.replace("{{CORE_INSTRUCTIONS}}", corePrompt);
7618
+ if (corePrompt && corePrompt.trim()) {
7619
+ phase2Prompt = phase2Prompt.replace("{{CORE_INSTRUCTIONS}}", corePrompt);
7620
+ } else {
7621
+ phase2Prompt = phase2Prompt.replace(
7622
+ /<core_instructions>\s*\{\{CORE_INSTRUCTIONS\}\}\s*<\/core_instructions>/g,
7623
+ ""
7624
+ );
7625
+ }
6893
7626
  phase2Prompt = phase2Prompt.replace("{{DATA_COMPONENTS_SECTION}}", dataComponentsSection);
6894
7627
  phase2Prompt = phase2Prompt.replace("{{ARTIFACTS_SECTION}}", artifactsSection);
6895
7628
  phase2Prompt = phase2Prompt.replace("{{ARTIFACT_GUIDANCE_SECTION}}", artifactGuidance);
@@ -6908,7 +7641,7 @@ function hasToolCallWithPrefix(prefix) {
6908
7641
  return false;
6909
7642
  };
6910
7643
  }
6911
- var logger15 = getLogger("Agent");
7644
+ var logger16 = getLogger("Agent");
6912
7645
  function validateModel(modelString, modelType) {
6913
7646
  if (!modelString?.trim()) {
6914
7647
  throw new Error(
@@ -6917,8 +7650,8 @@ function validateModel(modelString, modelType) {
6917
7650
  }
6918
7651
  return modelString.trim();
6919
7652
  }
6920
- function isValidTool(tool3) {
6921
- return tool3 && typeof tool3 === "object" && typeof tool3.description === "string" && tool3.inputSchema && typeof tool3.execute === "function";
7653
+ function isValidTool(tool4) {
7654
+ return tool4 && typeof tool4 === "object" && typeof tool4.description === "string" && tool4.inputSchema && typeof tool4.execute === "function";
6922
7655
  }
6923
7656
  var Agent = class {
6924
7657
  config;
@@ -6934,6 +7667,7 @@ var Agent = class {
6934
7667
  credentialStoreRegistry;
6935
7668
  mcpClientCache = /* @__PURE__ */ new Map();
6936
7669
  mcpConnectionLocks = /* @__PURE__ */ new Map();
7670
+ currentCompressor = null;
6937
7671
  constructor(config, credentialStoreRegistry) {
6938
7672
  this.artifactComponents = config.artifactComponents || [];
6939
7673
  let processedDataComponents = config.dataComponents || [];
@@ -7014,6 +7748,32 @@ var Agent = class {
7014
7748
  }
7015
7749
  return sanitizedTools;
7016
7750
  }
7751
+ #createRelationToolName(prefix, targetId) {
7752
+ return `${prefix}_to_${targetId.toLowerCase().replace(/\s+/g, "_")}`;
7753
+ }
7754
+ #getRelationshipIdForTool(toolName, toolType) {
7755
+ if (toolType === "mcp") {
7756
+ const matchingTool = this.config.tools?.find((tool4) => {
7757
+ if (tool4.config?.type !== "mcp") {
7758
+ return false;
7759
+ }
7760
+ if (tool4.availableTools?.some((available) => available.name === toolName)) {
7761
+ return true;
7762
+ }
7763
+ if (tool4.config.mcp.activeTools?.includes(toolName)) {
7764
+ return true;
7765
+ }
7766
+ return tool4.name === toolName;
7767
+ });
7768
+ return matchingTool?.relationshipId;
7769
+ }
7770
+ if (toolType === "delegation") {
7771
+ const relation = this.config.delegateRelations.find(
7772
+ (relation2) => this.#createRelationToolName("delegate", relation2.config.id) === toolName
7773
+ );
7774
+ return relation?.config.relationId;
7775
+ }
7776
+ }
7017
7777
  /**
7018
7778
  * Get the primary model settings for text generation and thinking
7019
7779
  * Requires model to be configured at project level
@@ -7057,9 +7817,59 @@ var Agent = class {
7057
7817
  providerOptions: baseConfig.providerOptions
7058
7818
  };
7059
7819
  }
7820
+ /**
7821
+ * Get the model settings for summarization/distillation
7822
+ * Falls back to base model if summarizer not configured
7823
+ */
7824
+ getSummarizerModel() {
7825
+ if (!this.config.models) {
7826
+ throw new Error(
7827
+ "Model configuration is required. Please configure models at the project level."
7828
+ );
7829
+ }
7830
+ const summarizerConfig = this.config.models.summarizer;
7831
+ const baseConfig = this.config.models.base;
7832
+ if (summarizerConfig) {
7833
+ return {
7834
+ model: validateModel(summarizerConfig.model, "Summarizer"),
7835
+ providerOptions: summarizerConfig.providerOptions
7836
+ };
7837
+ }
7838
+ if (!baseConfig) {
7839
+ throw new Error(
7840
+ "Base model configuration is required for summarizer fallback. Please configure models at the project level."
7841
+ );
7842
+ }
7843
+ return {
7844
+ model: validateModel(baseConfig.model, "Base (fallback for summarizer)"),
7845
+ providerOptions: baseConfig.providerOptions
7846
+ };
7847
+ }
7060
7848
  setConversationId(conversationId) {
7061
7849
  this.conversationId = conversationId;
7062
7850
  }
7851
+ /**
7852
+ * Simple compression fallback: drop oldest messages to fit under token limit
7853
+ */
7854
+ simpleCompression(messages, targetTokens) {
7855
+ if (messages.length === 0) return messages;
7856
+ const estimateTokens = (msg) => {
7857
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
7858
+ return Math.ceil(content.length / 4);
7859
+ };
7860
+ let totalTokens = messages.reduce((sum, msg) => sum + estimateTokens(msg), 0);
7861
+ if (totalTokens <= targetTokens) {
7862
+ return messages;
7863
+ }
7864
+ const result = [...messages];
7865
+ while (totalTokens > targetTokens && result.length > 1) {
7866
+ const dropped = result.shift();
7867
+ if (dropped) {
7868
+ totalTokens -= estimateTokens(dropped);
7869
+ }
7870
+ }
7871
+ return result;
7872
+ }
7063
7873
  /**
7064
7874
  * Set delegation status for this agent instance
7065
7875
  */
@@ -7082,10 +7892,11 @@ var Agent = class {
7082
7892
  /**
7083
7893
  * Wraps a tool with streaming lifecycle tracking (start, complete, error) and AgentSession recording
7084
7894
  */
7085
- wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, relationshipId, options) {
7895
+ wrapToolWithStreaming(toolName, toolDefinition, streamRequestId, toolType, options) {
7086
7896
  if (!toolDefinition || typeof toolDefinition !== "object" || !("execute" in toolDefinition)) {
7087
7897
  return toolDefinition;
7088
7898
  }
7899
+ const relationshipId = this.#getRelationshipIdForTool(toolName, toolType);
7089
7900
  const originalExecute = toolDefinition.execute;
7090
7901
  return {
7091
7902
  ...toolDefinition,
@@ -7094,14 +7905,21 @@ var Agent = class {
7094
7905
  const toolCallId = context?.toolCallId || generateToolId();
7095
7906
  const activeSpan = trace.getActiveSpan();
7096
7907
  if (activeSpan) {
7097
- activeSpan.setAttributes({
7908
+ const attributes = {
7098
7909
  "conversation.id": this.conversationId,
7099
7910
  "tool.purpose": toolDefinition.description || "No description provided",
7100
7911
  "ai.toolType": toolType || "unknown",
7101
7912
  "subAgent.name": this.config.name || "unknown",
7102
7913
  "subAgent.id": this.config.id || "unknown",
7103
7914
  "agent.id": this.config.agentId || "unknown"
7104
- });
7915
+ };
7916
+ if (options?.mcpServerId) {
7917
+ attributes["ai.toolCall.mcpServerId"] = options.mcpServerId;
7918
+ }
7919
+ if (options?.mcpServerName) {
7920
+ attributes["ai.toolCall.mcpServerName"] = options.mcpServerName;
7921
+ }
7922
+ activeSpan.setAttributes(attributes);
7105
7923
  }
7106
7924
  const isInternalTool = toolName.includes("save_tool_result") || toolName.includes("thinking_complete") || toolName.startsWith("transfer_to_");
7107
7925
  const needsApproval = options?.needsApproval || false;
@@ -7154,7 +7972,7 @@ var Agent = class {
7154
7972
  };
7155
7973
  await createMessage(dbClient_default)(messagePayload);
7156
7974
  } catch (error) {
7157
- logger15.warn(
7975
+ logger16.warn(
7158
7976
  { error, toolName, toolCallId, conversationId: toolResultConversationId },
7159
7977
  "Failed to store tool result in conversation history"
7160
7978
  );
@@ -7192,10 +8010,9 @@ var Agent = class {
7192
8010
  }
7193
8011
  getRelationTools(runtimeContext, sessionId) {
7194
8012
  const { transferRelations = [], delegateRelations = [] } = this.config;
7195
- const createToolName = (prefix, subAgentId) => `${prefix}_to_${subAgentId.toLowerCase().replace(/\s+/g, "_")}`;
7196
8013
  return Object.fromEntries([
7197
8014
  ...transferRelations.map((agentConfig) => {
7198
- const toolName = createToolName("transfer", agentConfig.id);
8015
+ const toolName = this.#createRelationToolName("transfer", agentConfig.id);
7199
8016
  return [
7200
8017
  toolName,
7201
8018
  this.wrapToolWithStreaming(
@@ -7212,7 +8029,7 @@ var Agent = class {
7212
8029
  ];
7213
8030
  }),
7214
8031
  ...delegateRelations.map((relation) => {
7215
- const toolName = createToolName("delegate", relation.config.id);
8032
+ const toolName = this.#createRelationToolName("delegate", relation.config.id);
7216
8033
  return [
7217
8034
  toolName,
7218
8035
  this.wrapToolWithStreaming(
@@ -7243,14 +8060,13 @@ var Agent = class {
7243
8060
  ]);
7244
8061
  }
7245
8062
  async getMcpTools(sessionId, streamRequestId) {
7246
- const mcpTools = this.config.tools?.filter((tool3) => {
7247
- return tool3.config?.type === "mcp";
8063
+ const mcpTools = this.config.tools?.filter((tool4) => {
8064
+ return tool4.config?.type === "mcp";
7248
8065
  }) || [];
7249
- const tools = await Promise.all(mcpTools.map((tool3) => this.getMcpTool(tool3)) || []) || [];
8066
+ const tools = await Promise.all(mcpTools.map((tool4) => this.getMcpTool(tool4)) || []) || [];
7250
8067
  if (!sessionId) {
7251
8068
  const wrappedTools2 = {};
7252
- for (const [index, toolSet] of tools.entries()) {
7253
- const relationshipId = mcpTools[index]?.relationshipId;
8069
+ for (const toolSet of tools) {
7254
8070
  for (const [toolName, toolDef] of Object.entries(toolSet.tools)) {
7255
8071
  const needsApproval = toolSet.toolPolicies?.[toolName]?.needsApproval || false;
7256
8072
  const enhancedTool = {
@@ -7262,23 +8078,25 @@ var Agent = class {
7262
8078
  enhancedTool,
7263
8079
  streamRequestId,
7264
8080
  "mcp",
7265
- relationshipId,
7266
- { needsApproval }
8081
+ {
8082
+ needsApproval,
8083
+ mcpServerId: toolSet.mcpServerId,
8084
+ mcpServerName: toolSet.mcpServerName
8085
+ }
7267
8086
  );
7268
8087
  }
7269
8088
  }
7270
8089
  return wrappedTools2;
7271
8090
  }
7272
8091
  const wrappedTools = {};
7273
- for (const [index, toolResult] of tools.entries()) {
7274
- const relationshipId = mcpTools[index]?.relationshipId;
8092
+ for (const toolResult of tools) {
7275
8093
  for (const [toolName, originalTool] of Object.entries(toolResult.tools)) {
7276
8094
  if (!isValidTool(originalTool)) {
7277
- logger15.error({ toolName }, "Invalid MCP tool structure - missing required properties");
8095
+ logger16.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7278
8096
  continue;
7279
8097
  }
7280
8098
  const needsApproval = toolResult.toolPolicies?.[toolName]?.needsApproval || false;
7281
- logger15.debug(
8099
+ logger16.debug(
7282
8100
  {
7283
8101
  toolName,
7284
8102
  toolPolicies: toolResult.toolPolicies,
@@ -7292,7 +8110,7 @@ var Agent = class {
7292
8110
  inputSchema: originalTool.inputSchema,
7293
8111
  execute: async (args, { toolCallId }) => {
7294
8112
  if (needsApproval) {
7295
- logger15.info(
8113
+ logger16.info(
7296
8114
  { toolName, toolCallId, args },
7297
8115
  "Tool requires approval - waiting for user response"
7298
8116
  );
@@ -7338,7 +8156,7 @@ var Agent = class {
7338
8156
  }
7339
8157
  },
7340
8158
  (denialSpan) => {
7341
- logger15.info(
8159
+ logger16.info(
7342
8160
  { toolName, toolCallId, reason: approvalResult.reason },
7343
8161
  "Tool execution denied by user"
7344
8162
  );
@@ -7359,18 +8177,18 @@ var Agent = class {
7359
8177
  }
7360
8178
  },
7361
8179
  (approvedSpan) => {
7362
- logger15.info({ toolName, toolCallId }, "Tool approved, continuing with execution");
8180
+ logger16.info({ toolName, toolCallId }, "Tool approved, continuing with execution");
7363
8181
  approvedSpan.setStatus({ code: SpanStatusCode.OK });
7364
8182
  approvedSpan.end();
7365
8183
  }
7366
8184
  );
7367
8185
  }
7368
- logger15.debug({ toolName, toolCallId }, "MCP Tool Called");
8186
+ logger16.debug({ toolName, toolCallId }, "MCP Tool Called");
7369
8187
  try {
7370
8188
  const rawResult = await originalTool.execute(args, { toolCallId });
7371
8189
  if (rawResult && typeof rawResult === "object" && rawResult.isError) {
7372
8190
  const errorMessage = rawResult.content?.[0]?.text || "MCP tool returned an error";
7373
- logger15.error(
8191
+ logger16.error(
7374
8192
  { toolName, toolCallId, errorMessage, rawResult },
7375
8193
  "MCP tool returned error status"
7376
8194
  );
@@ -7382,6 +8200,7 @@ var Agent = class {
7382
8200
  timestamp: Date.now()
7383
8201
  });
7384
8202
  if (streamRequestId) {
8203
+ const relationshipId = this.#getRelationshipIdForTool(toolName, "mcp");
7385
8204
  agentSessionManager.recordEvent(streamRequestId, "error", this.config.id, {
7386
8205
  message: `MCP tool "${toolName}" failed: ${errorMessage}`,
7387
8206
  code: "mcp_tool_error",
@@ -7420,7 +8239,7 @@ var Agent = class {
7420
8239
  });
7421
8240
  return { result: enhancedResult, toolCallId };
7422
8241
  } catch (error) {
7423
- logger15.error({ toolName, toolCallId, error }, "MCP tool execution failed");
8242
+ logger16.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7424
8243
  throw error;
7425
8244
  }
7426
8245
  }
@@ -7430,8 +8249,11 @@ var Agent = class {
7430
8249
  sessionWrappedTool,
7431
8250
  streamRequestId,
7432
8251
  "mcp",
7433
- relationshipId,
7434
- { needsApproval }
8252
+ {
8253
+ needsApproval,
8254
+ mcpServerId: toolResult.mcpServerId,
8255
+ mcpServerName: toolResult.mcpServerName
8256
+ }
7435
8257
  );
7436
8258
  }
7437
8259
  }
@@ -7440,28 +8262,28 @@ var Agent = class {
7440
8262
  /**
7441
8263
  * Convert database McpTool to builder MCPToolConfig format
7442
8264
  */
7443
- convertToMCPToolConfig(tool3, agentToolRelationHeaders) {
7444
- if (tool3.config.type !== "mcp") {
7445
- throw new Error(`Cannot convert non-MCP tool to MCP config: ${tool3.id}`);
8265
+ convertToMCPToolConfig(tool4, agentToolRelationHeaders) {
8266
+ if (tool4.config.type !== "mcp") {
8267
+ throw new Error(`Cannot convert non-MCP tool to MCP config: ${tool4.id}`);
7446
8268
  }
7447
8269
  return {
7448
- id: tool3.id,
7449
- name: tool3.name,
7450
- description: tool3.name,
8270
+ id: tool4.id,
8271
+ name: tool4.name,
8272
+ description: tool4.name,
7451
8273
  // Use name as description fallback
7452
- serverUrl: tool3.config.mcp.server.url,
7453
- activeTools: tool3.config.mcp.activeTools,
7454
- mcpType: tool3.config.mcp.server.url.includes("api.nango.dev") ? MCPServerType.nango : MCPServerType.generic,
7455
- transport: tool3.config.mcp.transport,
8274
+ serverUrl: tool4.config.mcp.server.url,
8275
+ activeTools: tool4.config.mcp.activeTools,
8276
+ mcpType: tool4.config.mcp.server.url.includes("api.nango.dev") ? MCPServerType.nango : MCPServerType.generic,
8277
+ transport: tool4.config.mcp.transport,
7456
8278
  headers: {
7457
- ...tool3.headers,
8279
+ ...tool4.headers,
7458
8280
  ...agentToolRelationHeaders
7459
8281
  }
7460
8282
  };
7461
8283
  }
7462
- async getMcpTool(tool3) {
7463
- const cacheKey = `${this.config.tenantId}-${this.config.projectId}-${tool3.id}-${tool3.credentialReferenceId || "no-cred"}`;
7464
- const credentialReferenceId = tool3.credentialReferenceId;
8284
+ async getMcpTool(tool4) {
8285
+ const cacheKey = `${this.config.tenantId}-${this.config.projectId}-${tool4.id}-${tool4.credentialReferenceId || "no-cred"}`;
8286
+ const credentialReferenceId = tool4.credentialReferenceId;
7465
8287
  const toolsForAgent = await getToolsForAgent(dbClient_default)({
7466
8288
  scopes: {
7467
8289
  tenantId: this.config.tenantId,
@@ -7470,12 +8292,56 @@ var Agent = class {
7470
8292
  subAgentId: this.config.id
7471
8293
  }
7472
8294
  });
7473
- const toolRelation = toolsForAgent.data.find((t) => t.toolId === tool3.id);
8295
+ const toolRelation = toolsForAgent.data.find((t) => t.toolId === tool4.id);
7474
8296
  const agentToolRelationHeaders = toolRelation?.headers || void 0;
7475
8297
  const selectedTools = toolRelation?.selectedTools || void 0;
7476
8298
  const toolPolicies = toolRelation?.toolPolicies || {};
7477
8299
  let serverConfig;
7478
- if (credentialReferenceId && this.credentialStuffer) {
8300
+ const isUserScoped = tool4.credentialScope === "user";
8301
+ const userId = this.config.userId;
8302
+ if (isUserScoped && userId && this.credentialStuffer) {
8303
+ const userCredentialReference = await getUserScopedCredentialReference(dbClient_default)({
8304
+ scopes: {
8305
+ tenantId: this.config.tenantId,
8306
+ projectId: this.config.projectId
8307
+ },
8308
+ toolId: tool4.id,
8309
+ userId
8310
+ });
8311
+ if (userCredentialReference) {
8312
+ const storeReference = {
8313
+ credentialStoreId: userCredentialReference.credentialStoreId,
8314
+ retrievalParams: userCredentialReference.retrievalParams || {}
8315
+ };
8316
+ serverConfig = await this.credentialStuffer.buildMcpServerConfig(
8317
+ {
8318
+ tenantId: this.config.tenantId,
8319
+ projectId: this.config.projectId,
8320
+ contextConfigId: this.config.contextConfigId || void 0,
8321
+ conversationId: this.conversationId || void 0
8322
+ },
8323
+ this.convertToMCPToolConfig(tool4, agentToolRelationHeaders),
8324
+ storeReference,
8325
+ selectedTools
8326
+ );
8327
+ } else {
8328
+ logger16.warn(
8329
+ { toolId: tool4.id, userId },
8330
+ "User-scoped tool has no credential connected for this user"
8331
+ );
8332
+ serverConfig = await this.credentialStuffer.buildMcpServerConfig(
8333
+ {
8334
+ tenantId: this.config.tenantId,
8335
+ projectId: this.config.projectId,
8336
+ contextConfigId: this.config.contextConfigId || void 0,
8337
+ conversationId: this.conversationId || void 0
8338
+ },
8339
+ this.convertToMCPToolConfig(tool4, agentToolRelationHeaders),
8340
+ void 0,
8341
+ selectedTools
8342
+ );
8343
+ }
8344
+ } else if (credentialReferenceId && this.credentialStuffer) {
7479
8345
  const credentialReference = await getCredentialReference(dbClient_default)({
7480
8346
  scopes: {
7481
8347
  tenantId: this.config.tenantId,
@@ -7497,7 +8363,7 @@ var Agent = class {
7497
8363
  contextConfigId: this.config.contextConfigId || void 0,
7498
8364
  conversationId: this.conversationId || void 0
7499
8365
  },
7500
- this.convertToMCPToolConfig(tool3, agentToolRelationHeaders),
8366
+ this.convertToMCPToolConfig(tool4, agentToolRelationHeaders),
7501
8367
  storeReference,
7502
8368
  selectedTools
7503
8369
  );
@@ -7509,28 +8375,41 @@ var Agent = class {
7509
8375
  contextConfigId: this.config.contextConfigId || void 0,
7510
8376
  conversationId: this.conversationId || void 0
7511
8377
  },
7512
- this.convertToMCPToolConfig(tool3, agentToolRelationHeaders),
8378
+ this.convertToMCPToolConfig(tool4, agentToolRelationHeaders),
7513
8379
  void 0,
7514
8380
  selectedTools
7515
8381
  );
7516
8382
  } else {
7517
- if (tool3.config.type !== "mcp") {
7518
- throw new Error(`Cannot build server config for non-MCP tool: ${tool3.id}`);
8383
+ if (tool4.config.type !== "mcp") {
8384
+ throw new Error(`Cannot build server config for non-MCP tool: ${tool4.id}`);
7519
8385
  }
7520
8386
  serverConfig = {
7521
- type: tool3.config.mcp.transport?.type || MCPTransportType.streamableHttp,
7522
- url: tool3.config.mcp.server.url,
7523
- activeTools: tool3.config.mcp.activeTools,
8387
+ type: tool4.config.mcp.transport?.type || MCPTransportType.streamableHttp,
8388
+ url: tool4.config.mcp.server.url,
8389
+ activeTools: tool4.config.mcp.activeTools,
7524
8390
  selectedTools,
7525
8391
  headers: agentToolRelationHeaders
7526
8392
  };
7527
8393
  }
7528
- logger15.info(
8394
+ if (serverConfig.url?.toString().includes("composio.dev")) {
8395
+ const urlObj = new URL(serverConfig.url.toString());
8396
+ if (isUserScoped && userId) {
8397
+ urlObj.searchParams.set("user_id", userId);
8398
+ } else {
8399
+ const SEPARATOR = "||";
8400
+ urlObj.searchParams.set(
8401
+ "user_id",
8402
+ `${this.config.tenantId}${SEPARATOR}${this.config.projectId}`
8403
+ );
8404
+ }
8405
+ serverConfig.url = urlObj.toString();
8406
+ }
8407
+ logger16.info(
7529
8408
  {
7530
- toolName: tool3.name,
8409
+ toolName: tool4.name,
7531
8410
  credentialReferenceId,
7532
8411
  transportType: serverConfig.type,
7533
- headers: tool3.headers
8412
+ headers: tool4.headers
7534
8413
  },
7535
8414
  "Built MCP server config with credentials"
7536
8415
  );
@@ -7542,7 +8421,7 @@ var Agent = class {
7542
8421
  if (!client) {
7543
8422
  let connectionPromise = this.mcpConnectionLocks.get(cacheKey);
7544
8423
  if (!connectionPromise) {
7545
- connectionPromise = this.createMcpConnection(tool3, serverConfig);
8424
+ connectionPromise = this.createMcpConnection(tool4, serverConfig);
7546
8425
  this.mcpConnectionLocks.set(cacheKey, connectionPromise);
7547
8426
  }
7548
8427
  try {
@@ -7550,9 +8429,9 @@ var Agent = class {
7550
8429
  this.mcpClientCache.set(cacheKey, client);
7551
8430
  } catch (error) {
7552
8431
  this.mcpConnectionLocks.delete(cacheKey);
7553
- logger15.error(
8432
+ logger16.error(
7554
8433
  {
7555
- toolName: tool3.name,
8434
+ toolName: tool4.name,
7556
8435
  subAgentId: this.config.id,
7557
8436
  cacheKey,
7558
8437
  error: error instanceof Error ? error.message : String(error)
@@ -7570,13 +8449,13 @@ var Agent = class {
7570
8449
  "ai.toolCall",
7571
8450
  {
7572
8451
  attributes: {
7573
- "ai.toolCall.name": tool3.name,
8452
+ "ai.toolCall.name": tool4.name,
7574
8453
  "ai.toolCall.args": JSON.stringify({ operation: "mcp_tool_discovery" }),
7575
8454
  "ai.toolCall.result": JSON.stringify({
7576
8455
  status: "no_tools_available",
7577
8456
  message: `MCP server has 0 effective tools. Double check the selected tools in your agent and the active tools in the MCP server configuration.`,
7578
- serverUrl: tool3.config.type === "mcp" ? tool3.config.mcp.server.url : "unknown",
7579
- originalToolName: tool3.name
8457
+ serverUrl: tool4.config.type === "mcp" ? tool4.config.mcp.server.url : "unknown",
8458
+ originalToolName: tool4.name
7580
8459
  }),
7581
8460
  "ai.toolType": "mcp",
7582
8461
  "subAgent.name": this.config.name || "unknown",
@@ -7588,14 +8467,14 @@ var Agent = class {
7588
8467
  }
7589
8468
  },
7590
8469
  (span) => {
7591
- setSpanWithError(span, new Error(`0 effective tools available for ${tool3.name}`));
8470
+ setSpanWithError(span, new Error(`0 effective tools available for ${tool4.name}`));
7592
8471
  agentSessionManager.recordEvent(streamRequestId, "error", this.config.id, {
7593
8472
  message: `MCP server has 0 effective tools. Double check the selected tools in your graph and the active tools in the MCP server configuration.`,
7594
8473
  code: "no_tools_available",
7595
8474
  severity: "error",
7596
8475
  context: {
7597
- toolName: tool3.name,
7598
- serverUrl: tool3.config.type === "mcp" ? tool3.config.mcp.server.url : "unknown",
8476
+ toolName: tool4.name,
8477
+ serverUrl: tool4.config.type === "mcp" ? tool4.config.mcp.server.url : "unknown",
7599
8478
  operation: "mcp_tool_discovery"
7600
8479
  }
7601
8480
  });
@@ -7604,20 +8483,20 @@ var Agent = class {
7604
8483
  );
7605
8484
  }
7606
8485
  }
7607
- return { tools, toolPolicies };
8486
+ return { tools, toolPolicies, mcpServerId: tool4.id, mcpServerName: tool4.name };
7608
8487
  }
7609
- async createMcpConnection(tool3, serverConfig) {
8488
+ async createMcpConnection(tool4, serverConfig) {
7610
8489
  const client = new McpClient({
7611
- name: tool3.name,
8490
+ name: tool4.name,
7612
8491
  server: serverConfig
7613
8492
  });
7614
8493
  try {
7615
8494
  await client.connect();
7616
8495
  return client;
7617
8496
  } catch (error) {
7618
- logger15.error(
8497
+ logger16.error(
7619
8498
  {
7620
- toolName: tool3.name,
8499
+ toolName: tool4.name,
7621
8500
  subAgentId: this.config.id,
7622
8501
  error: error instanceof Error ? error.message : String(error)
7623
8502
  },
@@ -7652,12 +8531,12 @@ var Agent = class {
7652
8531
  if (functionToolsData.length === 0) {
7653
8532
  return functionTools;
7654
8533
  }
7655
- const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-A2LTPE2X.js');
8534
+ const { SandboxExecutorFactory } = await import('./SandboxExecutorFactory-2N27SE3B.js');
7656
8535
  const sandboxExecutor = SandboxExecutorFactory.getInstance();
7657
8536
  for (const functionToolDef of functionToolsData) {
7658
8537
  const functionId = functionToolDef.functionId;
7659
8538
  if (!functionId) {
7660
- logger15.warn(
8539
+ logger16.warn(
7661
8540
  { functionToolId: functionToolDef.id },
7662
8541
  "Function tool missing functionId reference"
7663
8542
  );
@@ -7671,7 +8550,7 @@ var Agent = class {
7671
8550
  }
7672
8551
  });
7673
8552
  if (!functionData) {
7674
- logger15.warn(
8553
+ logger16.warn(
7675
8554
  { functionId, functionToolId: functionToolDef.id },
7676
8555
  "Function not found in functions table"
7677
8556
  );
@@ -7682,7 +8561,7 @@ var Agent = class {
7682
8561
  description: functionToolDef.description || functionToolDef.name,
7683
8562
  inputSchema: zodSchema,
7684
8563
  execute: async (args, { toolCallId }) => {
7685
- logger15.debug(
8564
+ logger16.debug(
7686
8565
  { toolName: functionToolDef.name, toolCallId, args },
7687
8566
  "Function Tool Called"
7688
8567
  );
@@ -7709,7 +8588,7 @@ var Agent = class {
7709
8588
  });
7710
8589
  return { result, toolCallId };
7711
8590
  } catch (error) {
7712
- logger15.error(
8591
+ logger16.error(
7713
8592
  {
7714
8593
  toolName: functionToolDef.name,
7715
8594
  toolCallId,
@@ -7729,7 +8608,7 @@ var Agent = class {
7729
8608
  );
7730
8609
  }
7731
8610
  } catch (error) {
7732
- logger15.error({ error }, "Failed to load function tools from database");
8611
+ logger16.error({ error }, "Failed to load function tools from database");
7733
8612
  }
7734
8613
  return functionTools;
7735
8614
  }
@@ -7739,7 +8618,7 @@ var Agent = class {
7739
8618
  async getResolvedContext(conversationId, headers2) {
7740
8619
  try {
7741
8620
  if (!this.config.contextConfigId) {
7742
- logger15.debug({ agentId: this.config.agentId }, "No context config found for agent");
8621
+ logger16.debug({ agentId: this.config.agentId }, "No context config found for agent");
7743
8622
  return null;
7744
8623
  }
7745
8624
  const contextConfig = await getContextConfigById(dbClient_default)({
@@ -7751,7 +8630,7 @@ var Agent = class {
7751
8630
  id: this.config.contextConfigId
7752
8631
  });
7753
8632
  if (!contextConfig) {
7754
- logger15.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
8633
+ logger16.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7755
8634
  return null;
7756
8635
  }
7757
8636
  if (!this.contextResolver) {
@@ -7767,7 +8646,7 @@ var Agent = class {
7767
8646
  ...result.resolvedContext,
7768
8647
  $env: process.env
7769
8648
  };
7770
- logger15.debug(
8649
+ logger16.debug(
7771
8650
  {
7772
8651
  conversationId,
7773
8652
  contextConfigId: contextConfig.id,
@@ -7781,7 +8660,7 @@ var Agent = class {
7781
8660
  );
7782
8661
  return contextWithBuiltins;
7783
8662
  } catch (error) {
7784
- logger15.error(
8663
+ logger16.error(
7785
8664
  {
7786
8665
  conversationId,
7787
8666
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7805,7 +8684,7 @@ var Agent = class {
7805
8684
  });
7806
8685
  return agentDefinition?.prompt || void 0;
7807
8686
  } catch (error) {
7808
- logger15.warn(
8687
+ logger16.warn(
7809
8688
  {
7810
8689
  agentId: this.config.agentId,
7811
8690
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7834,7 +8713,7 @@ var Agent = class {
7834
8713
  (subAgent) => "artifactComponents" in subAgent && subAgent.artifactComponents && subAgent.artifactComponents.length > 0
7835
8714
  );
7836
8715
  } catch (error) {
7837
- logger15.warn(
8716
+ logger16.warn(
7838
8717
  {
7839
8718
  agentId: this.config.agentId,
7840
8719
  tenantId: this.config.tenantId,
@@ -7852,18 +8731,19 @@ var Agent = class {
7852
8731
  */
7853
8732
  async buildPhase2SystemPrompt(runtimeContext) {
7854
8733
  const phase2Config = new Phase2Config();
7855
- const hasAgentArtifactComponents = await this.hasAgentArtifactComponents();
8734
+ const compressionConfig = getCompressionConfigFromEnv();
8735
+ const hasAgentArtifactComponents = await this.hasAgentArtifactComponents() || compressionConfig.enabled;
7856
8736
  const conversationId = runtimeContext?.metadata?.conversationId || runtimeContext?.contextId;
7857
8737
  const resolvedContext = conversationId ? await this.getResolvedContext(conversationId) : null;
7858
- let processedPrompt = this.config.prompt;
7859
- if (resolvedContext) {
8738
+ let processedPrompt = this.config.prompt || "";
8739
+ if (resolvedContext && this.config.prompt) {
7860
8740
  try {
7861
8741
  processedPrompt = TemplateEngine.render(this.config.prompt, resolvedContext, {
7862
8742
  strict: false,
7863
8743
  preserveUnresolved: false
7864
8744
  });
7865
8745
  } catch (error) {
7866
- logger15.error(
8746
+ logger16.error(
7867
8747
  {
7868
8748
  conversationId,
7869
8749
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7902,15 +8782,15 @@ var Agent = class {
7902
8782
  this.setConversationId(conversationId);
7903
8783
  }
7904
8784
  const resolvedContext = conversationId ? await this.getResolvedContext(conversationId) : null;
7905
- let processedPrompt = this.config.prompt;
7906
- if (resolvedContext) {
8785
+ let processedPrompt = this.config.prompt || "";
8786
+ if (resolvedContext && this.config.prompt) {
7907
8787
  try {
7908
8788
  processedPrompt = TemplateEngine.render(this.config.prompt, resolvedContext, {
7909
8789
  strict: false,
7910
8790
  preserveUnresolved: false
7911
8791
  });
7912
8792
  } catch (error) {
7913
- logger15.error(
8793
+ logger16.error(
7914
8794
  {
7915
8795
  conversationId,
7916
8796
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7925,28 +8805,28 @@ var Agent = class {
7925
8805
  const functionTools = await this.getFunctionTools(streamRequestId || "");
7926
8806
  const relationTools = this.getRelationTools(runtimeContext);
7927
8807
  const allTools = { ...mcpTools, ...functionTools, ...relationTools };
7928
- logger15.info(
8808
+ logger16.info(
7929
8809
  {
7930
8810
  mcpTools: Object.keys(mcpTools),
7931
8811
  functionTools: Object.keys(functionTools),
7932
8812
  relationTools: Object.keys(relationTools),
7933
8813
  allTools: Object.keys(allTools),
7934
- functionToolsDetails: Object.entries(functionTools).map(([name, tool3]) => ({
8814
+ functionToolsDetails: Object.entries(functionTools).map(([name, tool4]) => ({
7935
8815
  name,
7936
- hasExecute: typeof tool3.execute === "function",
7937
- hasDescription: !!tool3.description,
7938
- hasInputSchema: !!tool3.inputSchema
8816
+ hasExecute: typeof tool4.execute === "function",
8817
+ hasDescription: !!tool4.description,
8818
+ hasInputSchema: !!tool4.inputSchema
7939
8819
  }))
7940
8820
  },
7941
8821
  "Tools loaded for agent"
7942
8822
  );
7943
- const toolDefinitions = Object.entries(allTools).map(([name, tool3]) => ({
8823
+ const toolDefinitions = Object.entries(allTools).map(([name, tool4]) => ({
7944
8824
  name,
7945
- description: tool3.description || "",
7946
- inputSchema: tool3.inputSchema || tool3.parameters || {},
8825
+ description: tool4.description || "",
8826
+ inputSchema: tool4.inputSchema || tool4.parameters || {},
7947
8827
  usageGuidelines: name.startsWith("transfer_to_") || name.startsWith("delegate_to_") ? `Use this tool to ${name.startsWith("transfer_to_") ? "transfer" : "delegate"} to another agent when appropriate.` : "Use this tool when appropriate for the task at hand."
7948
8828
  }));
7949
- const { getConversationScopedArtifacts } = await import('./conversations-33GSAG2C.js');
8829
+ const { getConversationScopedArtifacts } = await import('./conversations-XPSTWUMK.js');
7950
8830
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
7951
8831
  const referenceArtifacts = await getConversationScopedArtifacts({
7952
8832
  tenantId: this.config.tenantId,
@@ -7964,7 +8844,7 @@ var Agent = class {
7964
8844
  preserveUnresolved: false
7965
8845
  });
7966
8846
  } catch (error) {
7967
- logger15.error(
8847
+ logger16.error(
7968
8848
  {
7969
8849
  conversationId,
7970
8850
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7974,7 +8854,8 @@ var Agent = class {
7974
8854
  }
7975
8855
  }
7976
8856
  const shouldIncludeArtifactComponents = !excludeDataComponents;
7977
- const hasAgentArtifactComponents = await this.hasAgentArtifactComponents();
8857
+ const compressionConfig = getCompressionConfigFromEnv();
8858
+ const hasAgentArtifactComponents = await this.hasAgentArtifactComponents() || compressionConfig.enabled;
7978
8859
  const config = {
7979
8860
  corePrompt: processedPrompt,
7980
8861
  prompt,
@@ -7992,12 +8873,12 @@ var Agent = class {
7992
8873
  getArtifactTools() {
7993
8874
  return tool({
7994
8875
  description: "Call this tool to get the complete artifact data with the given artifactId. This retrieves the full artifact content (not just the summary). Only use this when you need the complete artifact data and the summary shown in your context is insufficient.",
7995
- inputSchema: z.object({
7996
- artifactId: z.string().describe("The unique identifier of the artifact to get."),
7997
- toolCallId: z.string().describe("The tool call ID associated with this artifact.")
8876
+ inputSchema: z$1.object({
8877
+ artifactId: z$1.string().describe("The unique identifier of the artifact to get."),
8878
+ toolCallId: z$1.string().describe("The tool call ID associated with this artifact.")
7998
8879
  }),
7999
8880
  execute: async ({ artifactId, toolCallId }) => {
8000
- logger15.info({ artifactId, toolCallId }, "get_artifact_full executed");
8881
+ logger16.info({ artifactId, toolCallId }, "get_artifact_full executed");
8001
8882
  const streamRequestId = this.getStreamRequestId();
8002
8883
  const artifactService = agentSessionManager.getArtifactService(streamRequestId);
8003
8884
  if (!artifactService) {
@@ -8021,9 +8902,9 @@ var Agent = class {
8021
8902
  createThinkingCompleteTool() {
8022
8903
  return tool({
8023
8904
  description: "\u{1F6A8} CRITICAL: Call this tool IMMEDIATELY when you have gathered enough information to answer the user. This is MANDATORY - you CANNOT provide text responses in thinking mode, only tool calls. Call thinking_complete as soon as you have sufficient data to generate a structured response.",
8024
- inputSchema: z.object({
8025
- complete: z.boolean().describe("ALWAYS set to true - marks end of research phase"),
8026
- summary: z.string().describe(
8905
+ inputSchema: z$1.object({
8906
+ complete: z$1.boolean().describe("ALWAYS set to true - marks end of research phase"),
8907
+ summary: z$1.string().describe(
8027
8908
  "Brief summary of what information was gathered and why it is sufficient to answer the user"
8028
8909
  )
8029
8910
  }),
@@ -8033,7 +8914,8 @@ var Agent = class {
8033
8914
  // Provide a default tool set that is always available to the agent.
8034
8915
  async getDefaultTools(streamRequestId) {
8035
8916
  const defaultTools = {};
8036
- if (await this.agentHasArtifactComponents()) {
8917
+ const compressionConfig = getCompressionConfigFromEnv();
8918
+ if (await this.agentHasArtifactComponents() || compressionConfig.enabled) {
8037
8919
  defaultTools.get_reference_artifact = this.getArtifactTools();
8038
8920
  }
8039
8921
  const hasStructuredOutput = this.config.dataComponents && this.config.dataComponents.length > 0;
@@ -8048,6 +8930,37 @@ var Agent = class {
8048
8930
  );
8049
8931
  }
8050
8932
  }
8933
+ logger16.info(
8934
+ { agentId: this.config.id, streamRequestId },
8935
+ "Adding compress_context tool to defaultTools"
8936
+ );
8937
+ defaultTools.compress_context = tool({
8938
+ description: "Manually compress the current conversation context to save space. Use when shifting topics, completing major tasks, or when context feels cluttered.",
8939
+ inputSchema: z$1.object({
8940
+ reason: z$1.string().describe(
8941
+ 'Why you are requesting compression (e.g., "shifting from research to coding", "completed analysis phase")'
8942
+ )
8943
+ }),
8944
+ execute: async ({ reason }) => {
8945
+ logger16.info(
8946
+ {
8947
+ agentId: this.config.id,
8948
+ streamRequestId,
8949
+ reason
8950
+ },
8951
+ "Manual compression requested by LLM"
8952
+ );
8953
+ if (this.currentCompressor) {
8954
+ this.currentCompressor.requestManualCompression(reason);
8955
+ }
8956
+ return {
8957
+ status: "compression_requested",
8958
+ reason,
8959
+ message: "Context compression will be applied on the next generation step. Previous work has been summarized and saved as artifacts."
8960
+ };
8961
+ }
8962
+ });
8963
+ logger16.info("getDefaultTools returning tools:", Object.keys(defaultTools).join(", "));
8051
8964
  return defaultTools;
8052
8965
  }
8053
8966
  getStreamRequestId() {
@@ -8293,7 +9206,7 @@ ${output}`;
8293
9206
  };
8294
9207
  return enhanced;
8295
9208
  } catch (error) {
8296
- logger15.warn({ error }, "Failed to enhance tool result with structure hints");
9209
+ logger16.warn({ error }, "Failed to enhance tool result with structure hints");
8297
9210
  return result;
8298
9211
  }
8299
9212
  }
@@ -8308,7 +9221,7 @@ ${output}`;
8308
9221
  }
8309
9222
  });
8310
9223
  } catch (error) {
8311
- logger15.error(
9224
+ logger16.error(
8312
9225
  { error, agentId: this.config.agentId },
8313
9226
  "Failed to check agent artifact components"
8314
9227
  );
@@ -8425,7 +9338,7 @@ ${output}`;
8425
9338
  const configuredTimeout = modelSettings.maxDuration ? Math.min(modelSettings.maxDuration * 1e3, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) : shouldStreamPhase1 ? LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING : LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING;
8426
9339
  const timeoutMs = Math.min(configuredTimeout, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS);
8427
9340
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) {
8428
- logger15.warn(
9341
+ logger16.warn(
8429
9342
  {
8430
9343
  requestedTimeout: modelSettings.maxDuration * 1e3,
8431
9344
  appliedTimeout: timeoutMs,
@@ -8444,6 +9357,18 @@ ${output}`;
8444
9357
  role: "user",
8445
9358
  content: userMessage
8446
9359
  });
9360
+ const originalMessageCount = messages.length;
9361
+ const compressionConfig = getCompressionConfigFromEnv();
9362
+ const compressor = compressionConfig.enabled ? new MidGenerationCompressor(
9363
+ sessionId,
9364
+ contextId,
9365
+ this.config.tenantId,
9366
+ this.config.projectId,
9367
+ compressionConfig,
9368
+ this.getSummarizerModel(),
9369
+ primaryModelSettings
9370
+ ) : null;
9371
+ this.currentCompressor = compressor;
8447
9372
  if (shouldStreamPhase1) {
8448
9373
  const streamConfig = {
8449
9374
  ...modelSettings,
@@ -8454,6 +9379,87 @@ ${output}`;
8454
9379
  ...streamConfig,
8455
9380
  messages,
8456
9381
  tools: sanitizedTools,
9382
+ prepareStep: async ({ messages: stepMessages }) => {
9383
+ if (!compressor) {
9384
+ return {};
9385
+ }
9386
+ const compressionNeeded = compressor.isCompressionNeeded(stepMessages);
9387
+ if (compressionNeeded) {
9388
+ logger16.info(
9389
+ {
9390
+ compressorState: compressor.getState()
9391
+ },
9392
+ "Triggering layered mid-generation compression"
9393
+ );
9394
+ try {
9395
+ const originalMessages = stepMessages.slice(0, originalMessageCount);
9396
+ const generatedMessages = stepMessages.slice(originalMessageCount);
9397
+ if (generatedMessages.length > 0) {
9398
+ const compressionResult = await compressor.compress(generatedMessages);
9399
+ const finalMessages = [...originalMessages];
9400
+ if (compressionResult.summary.text_messages && compressionResult.summary.text_messages.length > 0) {
9401
+ finalMessages.push(...compressionResult.summary.text_messages);
9402
+ }
9403
+ const summaryMessage = JSON.stringify({
9404
+ high_level: compressionResult.summary?.summary?.high_level,
9405
+ user_intent: compressionResult.summary?.summary?.user_intent,
9406
+ decisions: compressionResult.summary?.summary?.decisions,
9407
+ open_questions: compressionResult.summary?.summary?.open_questions,
9408
+ next_steps: compressionResult.summary?.summary?.next_steps,
9409
+ related_artifacts: compressionResult?.summary?.summary?.related_artifacts
9410
+ });
9411
+ finalMessages.push({
9412
+ role: "user",
9413
+ content: `Based on your research, here's what you've discovered: ${summaryMessage}
9414
+
9415
+ Now please provide your answer to my original question using this context.`
9416
+ });
9417
+ logger16.info(
9418
+ {
9419
+ originalTotal: stepMessages.length,
9420
+ compressed: finalMessages.length,
9421
+ originalKept: originalMessages.length,
9422
+ generatedCompressed: generatedMessages.length
9423
+ },
9424
+ "Generated content compression completed"
9425
+ );
9426
+ logger16.info({ summaryMessage }, "Summary message");
9427
+ return { messages: finalMessages };
9428
+ }
9429
+ return {};
9430
+ } catch (error) {
9431
+ logger16.error(
9432
+ {
9433
+ error: error instanceof Error ? error.message : String(error),
9434
+ stack: error instanceof Error ? error.stack : void 0
9435
+ },
9436
+ "Smart compression failed, falling back to simple compression"
9437
+ );
9438
+ try {
9439
+ const targetSize = Math.floor(compressor.getHardLimit() * 0.5);
9440
+ const fallbackMessages = this.simpleCompression(stepMessages, targetSize);
9441
+ logger16.info(
9442
+ {
9443
+ originalCount: stepMessages.length,
9444
+ compressedCount: fallbackMessages.length,
9445
+ compressionType: "simple_fallback"
9446
+ },
9447
+ "Simple compression fallback completed"
9448
+ );
9449
+ return { messages: fallbackMessages };
9450
+ } catch (fallbackError) {
9451
+ logger16.error(
9452
+ {
9453
+ error: fallbackError instanceof Error ? fallbackError.message : String(fallbackError)
9454
+ },
9455
+ "Fallback compression also failed, continuing without compression"
9456
+ );
9457
+ return {};
9458
+ }
9459
+ }
9460
+ }
9461
+ return {};
9462
+ },
8457
9463
  stopWhen: async ({ steps }) => {
8458
9464
  const last = steps.at(-1);
8459
9465
  if (last && "text" in last && last.text) {
@@ -8467,7 +9473,7 @@ ${output}`;
8467
9473
  }
8468
9474
  );
8469
9475
  } catch (error) {
8470
- logger15.debug({ error }, "Failed to track agent reasoning");
9476
+ logger16.debug({ error }, "Failed to track agent reasoning");
8471
9477
  }
8472
9478
  }
8473
9479
  if (last && last["content"] && last["content"].length > 0) {
@@ -8589,6 +9595,87 @@ ${output}`;
8589
9595
  ...genConfig,
8590
9596
  messages,
8591
9597
  tools: sanitizedTools,
9598
+ prepareStep: async ({ messages: stepMessages }) => {
9599
+ if (!compressor) {
9600
+ return {};
9601
+ }
9602
+ const compressionNeeded = compressor.isCompressionNeeded(stepMessages);
9603
+ if (compressionNeeded) {
9604
+ logger16.info(
9605
+ {
9606
+ compressorState: compressor.getState()
9607
+ },
9608
+ "Triggering layered mid-generation compression"
9609
+ );
9610
+ try {
9611
+ const originalMessages = stepMessages.slice(0, originalMessageCount);
9612
+ const generatedMessages = stepMessages.slice(originalMessageCount);
9613
+ if (generatedMessages.length > 0) {
9614
+ const compressionResult = await compressor.compress(generatedMessages);
9615
+ const finalMessages = [...originalMessages];
9616
+ if (compressionResult.summary.text_messages && compressionResult.summary.text_messages.length > 0) {
9617
+ finalMessages.push(...compressionResult.summary.text_messages);
9618
+ }
9619
+ const summaryMessage = JSON.stringify({
9620
+ high_level: compressionResult.summary?.summary?.high_level,
9621
+ user_intent: compressionResult.summary?.summary?.user_intent,
9622
+ decisions: compressionResult.summary?.summary?.decisions,
9623
+ open_questions: compressionResult.summary?.summary?.open_questions,
9624
+ next_steps: compressionResult.summary?.summary?.next_steps,
9625
+ related_artifacts: compressionResult?.summary?.summary?.related_artifacts
9626
+ });
9627
+ finalMessages.push({
9628
+ role: "user",
9629
+ content: `Based on your research, here's what you've discovered: ${summaryMessage}
9630
+
9631
+ Now please provide your answer to my original question using this context.`
9632
+ });
9633
+ logger16.info(
9634
+ {
9635
+ originalTotal: stepMessages.length,
9636
+ compressed: finalMessages.length,
9637
+ originalKept: originalMessages.length,
9638
+ generatedCompressed: generatedMessages.length
9639
+ },
9640
+ "Generated content compression completed"
9641
+ );
9642
+ logger16.info({ summaryMessage }, "Summary message");
9643
+ return { messages: finalMessages };
9644
+ }
9645
+ return {};
9646
+ } catch (error) {
9647
+ logger16.error(
9648
+ {
9649
+ error: error instanceof Error ? error.message : String(error),
9650
+ stack: error instanceof Error ? error.stack : void 0
9651
+ },
9652
+ "Smart compression failed, falling back to simple compression"
9653
+ );
9654
+ try {
9655
+ const targetSize = Math.floor(compressor.getHardLimit() * 0.5);
9656
+ const fallbackMessages = this.simpleCompression(stepMessages, targetSize);
9657
+ logger16.info(
9658
+ {
9659
+ originalCount: stepMessages.length,
9660
+ compressedCount: fallbackMessages.length,
9661
+ compressionType: "simple_fallback"
9662
+ },
9663
+ "Simple compression fallback completed"
9664
+ );
9665
+ return { messages: fallbackMessages };
9666
+ } catch (fallbackError) {
9667
+ logger16.error(
9668
+ {
9669
+ error: fallbackError instanceof Error ? fallbackError.message : String(fallbackError)
9670
+ },
9671
+ "Fallback compression also failed, continuing without compression"
9672
+ );
9673
+ return {};
9674
+ }
9675
+ }
9676
+ }
9677
+ return {};
9678
+ },
8592
9679
  stopWhen: async ({ steps }) => {
8593
9680
  const last = steps.at(-1);
8594
9681
  if (last && "text" in last && last.text) {
@@ -8602,7 +9689,7 @@ ${output}`;
8602
9689
  }
8603
9690
  );
8604
9691
  } catch (error) {
8605
- logger15.debug({ error }, "Failed to track agent reasoning");
9692
+ logger16.debug({ error }, "Failed to track agent reasoning");
8606
9693
  }
8607
9694
  }
8608
9695
  if (steps.length >= 2) {
@@ -8640,7 +9727,22 @@ ${output}`;
8640
9727
  const thinkingCompleteCall = response.steps?.flatMap((s) => s.toolCalls || [])?.find((tc) => tc.toolName === "thinking_complete");
8641
9728
  if (thinkingCompleteCall) {
8642
9729
  const reasoningFlow = [];
8643
- if (response.steps) {
9730
+ const compressionSummary = this.currentCompressor?.getCompressionSummary();
9731
+ if (compressionSummary) {
9732
+ const summaryContent = JSON.stringify(compressionSummary, null, 2);
9733
+ reasoningFlow.push({
9734
+ role: "assistant",
9735
+ content: `## Research Summary (Compressed)
9736
+
9737
+ Based on tool executions, here's the comprehensive summary:
9738
+
9739
+ \`\`\`json
9740
+ ${summaryContent}
9741
+ \`\`\`
9742
+
9743
+ This summary represents all tool execution results in compressed form. Full details are preserved in artifacts.`
9744
+ });
9745
+ } else if (response.steps) {
8644
9746
  response.steps.forEach((step) => {
8645
9747
  if (step.toolCalls && step.toolResults) {
8646
9748
  step.toolCalls.forEach((call, index) => {
@@ -8714,9 +9816,9 @@ ${output}${structureHintsFormatted}`;
8714
9816
  this.config.dataComponents.forEach((dc) => {
8715
9817
  const propsSchema = jsonSchemaToZod(dc.props);
8716
9818
  componentSchemas.push(
8717
- z.object({
8718
- id: z.string(),
8719
- name: z.literal(dc.name),
9819
+ z$1.object({
9820
+ id: z$1.string(),
9821
+ name: z$1.literal(dc.name),
8720
9822
  props: propsSchema
8721
9823
  })
8722
9824
  );
@@ -8733,7 +9835,7 @@ ${output}${structureHintsFormatted}`;
8733
9835
  if (componentSchemas.length === 1) {
8734
9836
  dataComponentsSchema = componentSchemas[0];
8735
9837
  } else {
8736
- dataComponentsSchema = z.union(
9838
+ dataComponentsSchema = z$1.union(
8737
9839
  componentSchemas
8738
9840
  );
8739
9841
  }
@@ -8749,7 +9851,7 @@ ${output}${structureHintsFormatted}`;
8749
9851
  LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS
8750
9852
  );
8751
9853
  if (structuredModelSettings.maxDuration && structuredModelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) {
8752
- logger15.warn(
9854
+ logger16.warn(
8753
9855
  {
8754
9856
  requestedTimeout: structuredModelSettings.maxDuration * 1e3,
8755
9857
  appliedTimeout: phase2TimeoutMs,
@@ -8772,11 +9874,17 @@ ${output}${structureHintsFormatted}`;
8772
9874
  }
8773
9875
  phase2Messages.push({ role: "user", content: userMessage });
8774
9876
  phase2Messages.push(...reasoningFlow);
9877
+ if (reasoningFlow.length > 0 && reasoningFlow[reasoningFlow.length - 1]?.role === "assistant") {
9878
+ phase2Messages.push({
9879
+ role: "user",
9880
+ content: "Continue with the structured response."
9881
+ });
9882
+ }
8775
9883
  const streamResult = streamObject({
8776
9884
  ...structuredModelSettings,
8777
9885
  messages: phase2Messages,
8778
- schema: z.object({
8779
- dataComponents: z.array(dataComponentsSchema)
9886
+ schema: z$1.object({
9887
+ dataComponents: z$1.array(dataComponentsSchema)
8780
9888
  }),
8781
9889
  experimental_telemetry: {
8782
9890
  isEnabled: true,
@@ -8842,12 +9950,18 @@ ${output}${structureHintsFormatted}`;
8842
9950
  }
8843
9951
  phase2Messages.push({ role: "user", content: userMessage });
8844
9952
  phase2Messages.push(...reasoningFlow);
9953
+ if (reasoningFlow.length > 0 && reasoningFlow[reasoningFlow.length - 1]?.role === "assistant") {
9954
+ phase2Messages.push({
9955
+ role: "user",
9956
+ content: "Continue with the structured response."
9957
+ });
9958
+ }
8845
9959
  const structuredResponse = await generateObject(
8846
9960
  withJsonPostProcessing({
8847
9961
  ...structuredModelSettings,
8848
9962
  messages: phase2Messages,
8849
- schema: z.object({
8850
- dataComponents: z.array(dataComponentsSchema)
9963
+ schema: z$1.object({
9964
+ dataComponents: z$1.array(dataComponentsSchema)
8851
9965
  }),
8852
9966
  experimental_telemetry: {
8853
9967
  isEnabled: true,
@@ -8912,8 +10026,10 @@ ${output}${structureHintsFormatted}`;
8912
10026
  generationType
8913
10027
  });
8914
10028
  }
10029
+ this.currentCompressor = null;
8915
10030
  return formattedResponse;
8916
10031
  } catch (error) {
10032
+ this.currentCompressor = null;
8917
10033
  const errorToThrow = error instanceof Error ? error : new Error(String(error));
8918
10034
  setSpanWithError(span, errorToThrow);
8919
10035
  span.end();
@@ -8925,7 +10041,7 @@ ${output}${structureHintsFormatted}`;
8925
10041
  };
8926
10042
 
8927
10043
  // src/agents/generateTaskHandler.ts
8928
- var logger16 = getLogger("generateTaskHandler");
10044
+ var logger17 = getLogger("generateTaskHandler");
8929
10045
  var createTaskHandler = (config, credentialStoreRegistry) => {
8930
10046
  return async (task) => {
8931
10047
  try {
@@ -9043,7 +10159,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9043
10159
  return { ...relation, description: enhancedDescription };
9044
10160
  }
9045
10161
  } catch (error) {
9046
- logger16.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
10162
+ logger17.warn({ subAgentId: relation.id, error }, "Failed to enhance agent description");
9047
10163
  }
9048
10164
  return relation;
9049
10165
  })
@@ -9101,7 +10217,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9101
10217
  };
9102
10218
  }
9103
10219
  } catch (error) {
9104
- logger16.warn(
10220
+ logger17.warn(
9105
10221
  { targetAgentId: relation.targetAgentId, error },
9106
10222
  "Failed to enhance team agent description"
9107
10223
  );
@@ -9109,7 +10225,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9109
10225
  return relation;
9110
10226
  })
9111
10227
  );
9112
- const prompt = "prompt" in config.agentSchema ? config.agentSchema.prompt : "";
10228
+ const prompt = "prompt" in config.agentSchema ? config.agentSchema.prompt || void 0 : "";
9113
10229
  const models = "models" in config.agentSchema ? config.agentSchema.models : void 0;
9114
10230
  const stopWhen = "stopWhen" in config.agentSchema ? config.agentSchema.stopWhen : void 0;
9115
10231
  const toolsForAgentResult = await Promise.all(
@@ -9118,11 +10234,12 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9118
10234
  item.tool,
9119
10235
  dbClient_default,
9120
10236
  credentialStoreRegistry,
9121
- item.id
10237
+ item.id,
10238
+ config.userId
9122
10239
  );
9123
10240
  if (item.selectedTools && item.selectedTools.length > 0) {
9124
10241
  const selectedToolsSet = new Set(item.selectedTools);
9125
- mcpTool.availableTools = mcpTool.availableTools?.filter((tool3) => selectedToolsSet.has(tool3.name)) || [];
10242
+ mcpTool.availableTools = mcpTool.availableTools?.filter((tool4) => selectedToolsSet.has(tool4.name)) || [];
9126
10243
  }
9127
10244
  return mcpTool;
9128
10245
  })
@@ -9135,6 +10252,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9135
10252
  agentId: config.agentId,
9136
10253
  baseUrl: config.baseUrl,
9137
10254
  apiKey: config.apiKey,
10255
+ userId: config.userId,
9138
10256
  name: config.name,
9139
10257
  description: config.description || "",
9140
10258
  prompt,
@@ -9148,7 +10266,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9148
10266
  baseUrl: config.baseUrl,
9149
10267
  apiKey: config.apiKey,
9150
10268
  name: relation.name,
9151
- description: relation.description,
10269
+ description: relation.description || void 0,
9152
10270
  prompt: "",
9153
10271
  delegateRelations: [],
9154
10272
  subAgentRelations: [],
@@ -9188,7 +10306,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9188
10306
  targetTransferRelations = transferRel;
9189
10307
  targetDelegateRelations = delegateRel;
9190
10308
  } catch (err) {
9191
- logger16.info(
10309
+ logger17.info(
9192
10310
  {
9193
10311
  agentId: relation.id,
9194
10312
  error: err?.message || "Unknown error"
@@ -9202,12 +10320,13 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9202
10320
  item.tool,
9203
10321
  dbClient_default,
9204
10322
  credentialStoreRegistry,
9205
- item.id
10323
+ item.id,
10324
+ config.userId
9206
10325
  );
9207
10326
  if (item.selectedTools && item.selectedTools.length > 0) {
9208
10327
  const selectedToolsSet = new Set(item.selectedTools);
9209
10328
  mcpTool.availableTools = mcpTool.availableTools?.filter(
9210
- (tool3) => selectedToolsSet.has(tool3.name)
10329
+ (tool4) => selectedToolsSet.has(tool4.name)
9211
10330
  ) || [];
9212
10331
  }
9213
10332
  return mcpTool;
@@ -9251,7 +10370,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9251
10370
  projectId: config.projectId,
9252
10371
  agentId: config.agentId,
9253
10372
  name: relation.name,
9254
- description: relation.description,
10373
+ description: relation.description || void 0,
9255
10374
  prompt: "",
9256
10375
  delegateRelations: targetDelegateRelationsConfig,
9257
10376
  subAgentRelations: [],
@@ -9266,13 +10385,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9266
10385
  type: "internal",
9267
10386
  config: {
9268
10387
  id: relation.id,
10388
+ relationId: relation.relationId,
9269
10389
  tenantId: config.tenantId,
9270
10390
  projectId: config.projectId,
9271
10391
  agentId: config.agentId,
9272
10392
  baseUrl: config.baseUrl,
9273
10393
  apiKey: config.apiKey,
9274
10394
  name: relation.name,
9275
- description: relation.description,
10395
+ description: relation.description || void 0,
9276
10396
  prompt: "",
9277
10397
  delegateRelations: [],
9278
10398
  // Simplified - no nested relations
@@ -9327,7 +10447,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9327
10447
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
9328
10448
  if (taskIdMatch) {
9329
10449
  contextId = taskIdMatch[1];
9330
- logger16.info(
10450
+ logger17.info(
9331
10451
  {
9332
10452
  taskId: task.id,
9333
10453
  extractedContextId: contextId,
@@ -9345,7 +10465,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9345
10465
  agent.setDelegationStatus(isDelegation);
9346
10466
  agent.setDelegationId(delegationId);
9347
10467
  if (isDelegation) {
9348
- logger16.info(
10468
+ logger17.info(
9349
10469
  { subAgentId: config.subAgentId, taskId: task.id, delegationId },
9350
10470
  "Delegated agent - streaming disabled"
9351
10471
  );
@@ -9382,7 +10502,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9382
10502
  const toolResult = allToolResults.find(
9383
10503
  (result) => result.toolCallId === toolCall.toolCallId
9384
10504
  );
9385
- logger16.info(
10505
+ logger17.info(
9386
10506
  {
9387
10507
  toolCallName: toolCall.toolName,
9388
10508
  toolCallId: toolCall.toolCallId,
@@ -9399,7 +10519,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9399
10519
  const transferReason = responseText || allThoughts[allThoughts.length - 1]?.text || "Agent requested transfer. No reason provided.";
9400
10520
  if (toolResult?.output && isValidTransferResult(toolResult.output)) {
9401
10521
  const transferResult = toolResult.output;
9402
- logger16.info(
10522
+ logger17.info(
9403
10523
  {
9404
10524
  validationPassed: true,
9405
10525
  transferResult,
@@ -9416,7 +10536,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9416
10536
  reason: transferReason,
9417
10537
  original_message: userMessage
9418
10538
  };
9419
- logger16.info(
10539
+ logger17.info(
9420
10540
  {
9421
10541
  artifactData,
9422
10542
  artifactDataKeys: Object.keys(artifactData)
@@ -9441,7 +10561,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9441
10561
  ]
9442
10562
  };
9443
10563
  }
9444
- logger16.warn(
10564
+ logger17.warn(
9445
10565
  {
9446
10566
  hasToolResult: !!toolResult,
9447
10567
  hasOutput: !!toolResult?.output,
@@ -9470,7 +10590,9 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
9470
10590
  } catch (error) {
9471
10591
  console.error("Task handler error:", error);
9472
10592
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
9473
- const isConnectionRefused = errorMessage.includes("Connection refused. Please check if the MCP server is running.");
10593
+ const isConnectionRefused = errorMessage.includes(
10594
+ "Connection refused. Please check if the MCP server is running."
10595
+ );
9474
10596
  return {
9475
10597
  status: {
9476
10598
  state: TaskState.Failed,
@@ -9522,15 +10644,16 @@ var createTaskHandlerConfig = async (params) => {
9522
10644
  baseUrl: params.baseUrl,
9523
10645
  apiKey: params.apiKey,
9524
10646
  name: subAgent.name,
9525
- description: subAgent.description,
10647
+ description: subAgent.description || void 0,
9526
10648
  conversationHistoryConfig: effectiveConversationHistoryConfig,
9527
10649
  contextConfigId: agent?.contextConfigId || void 0,
9528
- sandboxConfig: params.sandboxConfig
10650
+ sandboxConfig: params.sandboxConfig,
10651
+ userId: params.userId
9529
10652
  };
9530
10653
  };
9531
10654
 
9532
10655
  // src/data/agents.ts
9533
- var logger17 = getLogger("agents");
10656
+ var logger18 = getLogger("agents");
9534
10657
  function createAgentCard({
9535
10658
  dbAgent,
9536
10659
  baseUrl
@@ -9600,7 +10723,8 @@ async function hydrateAgent({
9600
10723
  baseUrl,
9601
10724
  apiKey,
9602
10725
  credentialStoreRegistry,
9603
- sandboxConfig
10726
+ sandboxConfig,
10727
+ userId
9604
10728
  }) {
9605
10729
  try {
9606
10730
  const taskHandlerConfig = await createTaskHandlerConfig({
@@ -9610,7 +10734,8 @@ async function hydrateAgent({
9610
10734
  subAgentId: dbAgent.id,
9611
10735
  baseUrl,
9612
10736
  apiKey,
9613
- sandboxConfig
10737
+ sandboxConfig,
10738
+ userId
9614
10739
  });
9615
10740
  const taskHandler = createTaskHandler(taskHandlerConfig, credentialStoreRegistry);
9616
10741
  const agentCard = createAgentCard({
@@ -9633,12 +10758,13 @@ async function hydrateAgent({
9633
10758
  async function getRegisteredAgent(params) {
9634
10759
  const { executionContext, credentialStoreRegistry, sandboxConfig } = params;
9635
10760
  const { tenantId, projectId, agentId, subAgentId, baseUrl, apiKey } = executionContext;
10761
+ const userId = getUserIdFromContext(executionContext);
9636
10762
  let dbAgent;
9637
10763
  if (!subAgentId) {
9638
10764
  const agent = await getAgentWithDefaultSubAgent(dbClient_default)({
9639
10765
  scopes: { tenantId, projectId, agentId }
9640
10766
  });
9641
- logger17.info({ agent }, "agent with default sub agent");
10767
+ logger18.info({ agent }, "agent with default sub agent");
9642
10768
  if (!agent || !agent.defaultSubAgent) {
9643
10769
  return null;
9644
10770
  }
@@ -9663,13 +10789,14 @@ async function getRegisteredAgent(params) {
9663
10789
  baseUrl: agentFrameworkBaseUrl,
9664
10790
  credentialStoreRegistry,
9665
10791
  apiKey,
9666
- sandboxConfig
10792
+ sandboxConfig,
10793
+ userId
9667
10794
  });
9668
10795
  }
9669
10796
 
9670
10797
  // src/routes/agents.ts
9671
10798
  var app = new OpenAPIHono();
9672
- var logger18 = getLogger("agents");
10799
+ var logger19 = getLogger("agents");
9673
10800
  app.openapi(
9674
10801
  createRoute({
9675
10802
  method: "get",
@@ -9684,14 +10811,14 @@ app.openapi(
9684
10811
  description: "Agent Card for A2A discovery",
9685
10812
  content: {
9686
10813
  "application/json": {
9687
- schema: z.object({
9688
- name: z.string(),
9689
- description: z.string().optional(),
9690
- url: z.string(),
9691
- version: z.string(),
9692
- defaultInputModes: z.array(z.string()),
9693
- defaultOutputModes: z.array(z.string()),
9694
- skills: z.array(z.any())
10814
+ schema: z$1.object({
10815
+ name: z$1.string(),
10816
+ description: z$1.string().optional(),
10817
+ url: z$1.string(),
10818
+ version: z$1.string(),
10819
+ defaultInputModes: z$1.array(z$1.string()),
10820
+ defaultOutputModes: z$1.array(z$1.string()),
10821
+ skills: z$1.array(z$1.any())
9695
10822
  })
9696
10823
  }
9697
10824
  }
@@ -9707,7 +10834,7 @@ app.openapi(
9707
10834
  tracestate: c.req.header("tracestate"),
9708
10835
  baggage: c.req.header("baggage")
9709
10836
  };
9710
- logger18.info(
10837
+ logger19.info(
9711
10838
  {
9712
10839
  otelHeaders,
9713
10840
  path: c.req.path,
@@ -9717,8 +10844,8 @@ app.openapi(
9717
10844
  );
9718
10845
  const executionContext = getRequestExecutionContext(c);
9719
10846
  const { tenantId, projectId, agentId, subAgentId } = executionContext;
9720
- logger18.info({ executionContext }, "executionContext");
9721
- logger18.info(
10847
+ logger19.info({ executionContext }, "executionContext");
10848
+ logger19.info(
9722
10849
  {
9723
10850
  message: "getRegisteredAgent (agent-level)",
9724
10851
  tenantId,
@@ -9735,7 +10862,7 @@ app.openapi(
9735
10862
  credentialStoreRegistry: credentialStores,
9736
10863
  sandboxConfig
9737
10864
  });
9738
- logger18.info({ agent }, "agent registered: well-known agent.json");
10865
+ logger19.info({ agent }, "agent registered: well-known agent.json");
9739
10866
  if (!agent) {
9740
10867
  throw createApiError({
9741
10868
  code: "not_found",
@@ -9751,7 +10878,7 @@ app.post("/a2a", async (c) => {
9751
10878
  tracestate: c.req.header("tracestate"),
9752
10879
  baggage: c.req.header("baggage")
9753
10880
  };
9754
- logger18.info(
10881
+ logger19.info(
9755
10882
  {
9756
10883
  otelHeaders,
9757
10884
  path: c.req.path,
@@ -9762,7 +10889,7 @@ app.post("/a2a", async (c) => {
9762
10889
  const executionContext = getRequestExecutionContext(c);
9763
10890
  const { tenantId, projectId, agentId, subAgentId } = executionContext;
9764
10891
  if (subAgentId) {
9765
- logger18.info(
10892
+ logger19.info(
9766
10893
  {
9767
10894
  message: "a2a (agent-level)",
9768
10895
  tenantId,
@@ -9791,7 +10918,7 @@ app.post("/a2a", async (c) => {
9791
10918
  }
9792
10919
  return a2aHandler(c, agent2);
9793
10920
  }
9794
- logger18.info(
10921
+ logger19.info(
9795
10922
  {
9796
10923
  message: "a2a (agent-level)",
9797
10924
  tenantId,
@@ -9869,14 +10996,14 @@ function extractTransferData(task) {
9869
10996
  }
9870
10997
 
9871
10998
  // src/a2a/transfer.ts
9872
- var logger19 = getLogger("Transfer");
10999
+ var logger20 = getLogger("Transfer");
9873
11000
  async function executeTransfer({
9874
11001
  tenantId,
9875
11002
  threadId,
9876
11003
  projectId,
9877
11004
  targetSubAgentId
9878
11005
  }) {
9879
- logger19.info(
11006
+ logger20.info(
9880
11007
  {
9881
11008
  targetAgent: targetSubAgentId,
9882
11009
  threadId,
@@ -9891,12 +11018,12 @@ async function executeTransfer({
9891
11018
  threadId,
9892
11019
  subAgentId: targetSubAgentId
9893
11020
  });
9894
- logger19.info(
11021
+ logger20.info(
9895
11022
  { targetAgent: targetSubAgentId, threadId },
9896
11023
  "Successfully updated active_sub_agent_id in database"
9897
11024
  );
9898
11025
  } catch (error) {
9899
- logger19.error(
11026
+ logger20.error(
9900
11027
  { error, targetAgent: targetSubAgentId, threadId },
9901
11028
  "Failed to update active_sub_agent_id"
9902
11029
  );
@@ -10460,7 +11587,7 @@ function createBufferingStreamHelper() {
10460
11587
  var createMCPStreamHelper = createBufferingStreamHelper;
10461
11588
 
10462
11589
  // src/handlers/executionHandler.ts
10463
- var logger20 = getLogger("ExecutionHandler");
11590
+ var logger21 = getLogger("ExecutionHandler");
10464
11591
  var ExecutionHandler = class {
10465
11592
  MAX_ERRORS = AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS;
10466
11593
  /**
@@ -10493,7 +11620,7 @@ var ExecutionHandler = class {
10493
11620
  if (emitOperations) {
10494
11621
  agentSessionManager.enableEmitOperations(requestId2);
10495
11622
  }
10496
- logger20.info(
11623
+ logger21.info(
10497
11624
  { sessionId: requestId2, agentId, conversationId, emitOperations },
10498
11625
  "Created AgentSession for message execution"
10499
11626
  );
@@ -10526,7 +11653,7 @@ var ExecutionHandler = class {
10526
11653
  );
10527
11654
  }
10528
11655
  } catch (modelError) {
10529
- logger20.warn(
11656
+ logger21.warn(
10530
11657
  {
10531
11658
  error: modelError instanceof Error ? modelError.message : "Unknown error",
10532
11659
  agentId
@@ -10541,7 +11668,7 @@ var ExecutionHandler = class {
10541
11668
  }
10542
11669
  }
10543
11670
  } catch (error) {
10544
- logger20.error(
11671
+ logger21.error(
10545
11672
  {
10546
11673
  error: error instanceof Error ? error.message : "Unknown error",
10547
11674
  stack: error instanceof Error ? error.stack : void 0
@@ -10557,7 +11684,7 @@ var ExecutionHandler = class {
10557
11684
  try {
10558
11685
  await sseHelper.writeOperation(agentInitializingOp(requestId2, agentId));
10559
11686
  const taskId = `task_${conversationId}-${requestId2}`;
10560
- logger20.info(
11687
+ logger21.info(
10561
11688
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
10562
11689
  "Attempting to create or reuse existing task"
10563
11690
  );
@@ -10581,7 +11708,7 @@ var ExecutionHandler = class {
10581
11708
  sub_agent_id: currentAgentId
10582
11709
  }
10583
11710
  });
10584
- logger20.info(
11711
+ logger21.info(
10585
11712
  {
10586
11713
  taskId,
10587
11714
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -10590,27 +11717,27 @@ var ExecutionHandler = class {
10590
11717
  );
10591
11718
  } catch (error) {
10592
11719
  if (error?.cause?.code === "23505") {
10593
- logger20.info(
11720
+ logger21.info(
10594
11721
  { taskId, error: error.message },
10595
11722
  "Task already exists, fetching existing task"
10596
11723
  );
10597
11724
  const existingTask = await getTask(dbClient_default)({ id: taskId });
10598
11725
  if (existingTask) {
10599
11726
  task = existingTask;
10600
- logger20.info(
11727
+ logger21.info(
10601
11728
  { taskId, existingTask },
10602
11729
  "Successfully reused existing task from race condition"
10603
11730
  );
10604
11731
  } else {
10605
- logger20.error({ taskId, error }, "Task constraint failed but task not found");
11732
+ logger21.error({ taskId, error }, "Task constraint failed but task not found");
10606
11733
  throw error;
10607
11734
  }
10608
11735
  } else {
10609
- logger20.error({ taskId, error }, "Failed to create task due to non-constraint error");
11736
+ logger21.error({ taskId, error }, "Failed to create task due to non-constraint error");
10610
11737
  throw error;
10611
11738
  }
10612
11739
  }
10613
- logger20.debug(
11740
+ logger21.debug(
10614
11741
  {
10615
11742
  timestamp: /* @__PURE__ */ new Date(),
10616
11743
  executionType: "create_initial_task",
@@ -10629,7 +11756,7 @@ var ExecutionHandler = class {
10629
11756
  const maxTransfers = agentConfig?.stopWhen?.transferCountIs ?? AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT;
10630
11757
  while (iterations < maxTransfers) {
10631
11758
  iterations++;
10632
- logger20.info(
11759
+ logger21.info(
10633
11760
  { iterations, currentAgentId, agentId, conversationId, fromSubAgentId },
10634
11761
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromSubAgentId || "none"}`
10635
11762
  );
@@ -10637,10 +11764,10 @@ var ExecutionHandler = class {
10637
11764
  scopes: { tenantId, projectId },
10638
11765
  conversationId
10639
11766
  });
10640
- logger20.info({ activeAgent }, "activeAgent");
11767
+ logger21.info({ activeAgent }, "activeAgent");
10641
11768
  if (activeAgent && activeAgent.activeSubAgentId !== currentAgentId) {
10642
11769
  currentAgentId = activeAgent.activeSubAgentId;
10643
- logger20.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
11770
+ logger21.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10644
11771
  }
10645
11772
  const agentBaseUrl = `${baseUrl}/agents`;
10646
11773
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -10681,13 +11808,13 @@ var ExecutionHandler = class {
10681
11808
  });
10682
11809
  if (!messageResponse?.result) {
10683
11810
  errorCount++;
10684
- logger20.error(
11811
+ logger21.error(
10685
11812
  { currentAgentId, iterations, errorCount },
10686
11813
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10687
11814
  );
10688
11815
  if (errorCount >= this.MAX_ERRORS) {
10689
11816
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10690
- logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
11817
+ logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10691
11818
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10692
11819
  if (task) {
10693
11820
  await updateTask(dbClient_default)({
@@ -10702,7 +11829,7 @@ var ExecutionHandler = class {
10702
11829
  }
10703
11830
  });
10704
11831
  }
10705
- agentSessionManager.endSession(requestId2);
11832
+ await agentSessionManager.endSession(requestId2);
10706
11833
  unregisterStreamHelper(requestId2);
10707
11834
  return { success: false, error: errorMessage2, iterations };
10708
11835
  }
@@ -10711,7 +11838,7 @@ var ExecutionHandler = class {
10711
11838
  if (isTransferTask(messageResponse.result)) {
10712
11839
  const transferData = extractTransferData(messageResponse.result);
10713
11840
  if (!transferData) {
10714
- logger20.error(
11841
+ logger21.error(
10715
11842
  { result: messageResponse.result },
10716
11843
  "Transfer detected but no transfer data found"
10717
11844
  );
@@ -10720,7 +11847,7 @@ var ExecutionHandler = class {
10720
11847
  const { targetSubAgentId, fromSubAgentId: transferFromAgent } = transferData;
10721
11848
  const firstArtifact = messageResponse.result.artifacts[0];
10722
11849
  const transferReason = firstArtifact?.parts[1]?.kind === "text" ? firstArtifact.parts[1].text : "Transfer initiated";
10723
- logger20.info({ targetSubAgentId, transferReason, transferFromAgent }, "Transfer response");
11850
+ logger21.info({ targetSubAgentId, transferReason, transferFromAgent }, "Transfer response");
10724
11851
  await createMessage(dbClient_default)({
10725
11852
  id: generateId(),
10726
11853
  tenantId,
@@ -10751,7 +11878,7 @@ var ExecutionHandler = class {
10751
11878
  if (success) {
10752
11879
  fromSubAgentId = currentAgentId;
10753
11880
  currentAgentId = newAgentId;
10754
- logger20.info(
11881
+ logger21.info(
10755
11882
  {
10756
11883
  transferFrom: fromSubAgentId,
10757
11884
  transferTo: currentAgentId,
@@ -10765,7 +11892,7 @@ var ExecutionHandler = class {
10765
11892
  let responseParts = [];
10766
11893
  if (messageResponse.result.streamedContent?.parts) {
10767
11894
  responseParts = messageResponse.result.streamedContent.parts;
10768
- logger20.info(
11895
+ logger21.info(
10769
11896
  { partsCount: responseParts.length },
10770
11897
  "Using streamed content for conversation history"
10771
11898
  );
@@ -10773,7 +11900,7 @@ var ExecutionHandler = class {
10773
11900
  responseParts = messageResponse.result.artifacts?.flatMap(
10774
11901
  (artifact) => artifact.parts || []
10775
11902
  ) || [];
10776
- logger20.info(
11903
+ logger21.info(
10777
11904
  { partsCount: responseParts.length },
10778
11905
  "Using artifacts for conversation history (fallback)"
10779
11906
  );
@@ -10782,7 +11909,7 @@ var ExecutionHandler = class {
10782
11909
  const agentSessionData = agentSessionManager.getSession(requestId2);
10783
11910
  if (agentSessionData) {
10784
11911
  const sessionSummary = agentSessionData.getSummary();
10785
- logger20.info(sessionSummary, "AgentSession data after completion");
11912
+ logger21.info(sessionSummary, "AgentSession data after completion");
10786
11913
  }
10787
11914
  let textContent = "";
10788
11915
  for (const part of responseParts) {
@@ -10836,22 +11963,22 @@ var ExecutionHandler = class {
10836
11963
  }
10837
11964
  });
10838
11965
  const updateTaskEnd = Date.now();
10839
- logger20.info(
11966
+ logger21.info(
10840
11967
  { duration: updateTaskEnd - updateTaskStart },
10841
11968
  "Completed updateTask operation"
10842
11969
  );
10843
11970
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
10844
11971
  await sseHelper.complete();
10845
- logger20.info({}, "Ending AgentSession and cleaning up");
10846
- agentSessionManager.endSession(requestId2);
10847
- logger20.info({}, "Cleaning up streamHelper");
11972
+ logger21.info({}, "Ending AgentSession and cleaning up");
11973
+ await agentSessionManager.endSession(requestId2);
11974
+ logger21.info({}, "Cleaning up streamHelper");
10848
11975
  unregisterStreamHelper(requestId2);
10849
11976
  let response;
10850
11977
  if (sseHelper instanceof BufferingStreamHelper) {
10851
11978
  const captured = sseHelper.getCapturedResponse();
10852
11979
  response = captured.text || "No response content";
10853
11980
  }
10854
- logger20.info({}, "ExecutionHandler returning success");
11981
+ logger21.info({}, "ExecutionHandler returning success");
10855
11982
  return { success: true, iterations, response };
10856
11983
  } catch (error) {
10857
11984
  setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -10862,13 +11989,13 @@ var ExecutionHandler = class {
10862
11989
  });
10863
11990
  }
10864
11991
  errorCount++;
10865
- logger20.warn(
11992
+ logger21.warn(
10866
11993
  { iterations, errorCount },
10867
11994
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
10868
11995
  );
10869
11996
  if (errorCount >= this.MAX_ERRORS) {
10870
11997
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
10871
- logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
11998
+ logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10872
11999
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
10873
12000
  if (task) {
10874
12001
  await updateTask(dbClient_default)({
@@ -10883,13 +12010,13 @@ var ExecutionHandler = class {
10883
12010
  }
10884
12011
  });
10885
12012
  }
10886
- agentSessionManager.endSession(requestId2);
12013
+ await agentSessionManager.endSession(requestId2);
10887
12014
  unregisterStreamHelper(requestId2);
10888
12015
  return { success: false, error: errorMessage2, iterations };
10889
12016
  }
10890
12017
  }
10891
12018
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
10892
- logger20.error({ maxTransfers, iterations }, errorMessage);
12019
+ logger21.error({ maxTransfers, iterations }, errorMessage);
10893
12020
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
10894
12021
  if (task) {
10895
12022
  await updateTask(dbClient_default)({
@@ -10904,11 +12031,11 @@ var ExecutionHandler = class {
10904
12031
  }
10905
12032
  });
10906
12033
  }
10907
- agentSessionManager.endSession(requestId2);
12034
+ await agentSessionManager.endSession(requestId2);
10908
12035
  unregisterStreamHelper(requestId2);
10909
12036
  return { success: false, error: errorMessage, iterations };
10910
12037
  } catch (error) {
10911
- logger20.error({ error }, "Error in execution handler");
12038
+ logger21.error({ error }, "Error in execution handler");
10912
12039
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
10913
12040
  await sseHelper.writeOperation(
10914
12041
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -10926,7 +12053,7 @@ var ExecutionHandler = class {
10926
12053
  }
10927
12054
  });
10928
12055
  }
10929
- agentSessionManager.endSession(requestId2);
12056
+ await agentSessionManager.endSession(requestId2);
10930
12057
  unregisterStreamHelper(requestId2);
10931
12058
  return { success: false, error: errorMessage, iterations };
10932
12059
  }
@@ -10935,7 +12062,7 @@ var ExecutionHandler = class {
10935
12062
 
10936
12063
  // src/routes/chat.ts
10937
12064
  var app2 = new OpenAPIHono();
10938
- var logger21 = getLogger("completionsHandler");
12065
+ var logger22 = getLogger("completionsHandler");
10939
12066
  var chatCompletionsRoute = createRoute({
10940
12067
  method: "post",
10941
12068
  path: "/completions",
@@ -10947,36 +12074,36 @@ var chatCompletionsRoute = createRoute({
10947
12074
  body: {
10948
12075
  content: {
10949
12076
  "application/json": {
10950
- schema: z.object({
10951
- model: z.string().describe("The model to use for the completion"),
10952
- messages: z.array(
10953
- z.object({
10954
- role: z.enum(["system", "user", "assistant", "function", "tool"]).describe("The role of the message"),
10955
- content: z.union([
10956
- z.string(),
10957
- z.array(
10958
- z.strictObject({
10959
- type: z.string(),
10960
- text: z.string().optional()
12077
+ schema: z$1.object({
12078
+ model: z$1.string().describe("The model to use for the completion"),
12079
+ messages: z$1.array(
12080
+ z$1.object({
12081
+ role: z$1.enum(["system", "user", "assistant", "function", "tool"]).describe("The role of the message"),
12082
+ content: z$1.union([
12083
+ z$1.string(),
12084
+ z$1.array(
12085
+ z$1.strictObject({
12086
+ type: z$1.string(),
12087
+ text: z$1.string().optional()
10961
12088
  })
10962
12089
  )
10963
12090
  ]).describe("The message content"),
10964
- name: z.string().optional().describe("The name of the message sender")
12091
+ name: z$1.string().optional().describe("The name of the message sender")
10965
12092
  })
10966
12093
  ).describe("The conversation messages"),
10967
- temperature: z.number().optional().describe("Controls randomness (0-1)"),
10968
- top_p: z.number().optional().describe("Controls nucleus sampling"),
10969
- n: z.number().optional().describe("Number of completions to generate"),
10970
- stream: z.boolean().optional().describe("Whether to stream the response"),
10971
- max_tokens: z.number().optional().describe("Maximum tokens to generate"),
10972
- presence_penalty: z.number().optional().describe("Presence penalty (-2 to 2)"),
10973
- frequency_penalty: z.number().optional().describe("Frequency penalty (-2 to 2)"),
10974
- logit_bias: z.record(z.string(), z.number()).optional().describe("Token logit bias"),
10975
- user: z.string().optional().describe("User identifier"),
10976
- conversationId: z.string().optional().describe("Conversation ID for multi-turn chat"),
10977
- tools: z.array(z.string()).optional().describe("Available tools"),
10978
- runConfig: z.record(z.string(), z.unknown()).optional().describe("Run configuration"),
10979
- headers: z.record(z.string(), z.unknown()).optional().describe(
12094
+ temperature: z$1.number().optional().describe("Controls randomness (0-1)"),
12095
+ top_p: z$1.number().optional().describe("Controls nucleus sampling"),
12096
+ n: z$1.number().optional().describe("Number of completions to generate"),
12097
+ stream: z$1.boolean().optional().describe("Whether to stream the response"),
12098
+ max_tokens: z$1.number().optional().describe("Maximum tokens to generate"),
12099
+ presence_penalty: z$1.number().optional().describe("Presence penalty (-2 to 2)"),
12100
+ frequency_penalty: z$1.number().optional().describe("Frequency penalty (-2 to 2)"),
12101
+ logit_bias: z$1.record(z$1.string(), z$1.number()).optional().describe("Token logit bias"),
12102
+ user: z$1.string().optional().describe("User identifier"),
12103
+ conversationId: z$1.string().optional().describe("Conversation ID for multi-turn chat"),
12104
+ tools: z$1.array(z$1.string()).optional().describe("Available tools"),
12105
+ runConfig: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Run configuration"),
12106
+ headers: z$1.record(z$1.string(), z$1.unknown()).optional().describe(
10980
12107
  "Headers data for template processing (validated against context config schema)"
10981
12108
  )
10982
12109
  })
@@ -10987,14 +12114,14 @@ var chatCompletionsRoute = createRoute({
10987
12114
  responses: {
10988
12115
  200: {
10989
12116
  description: "Streaming chat completion response in Server-Sent Events format",
10990
- headers: z.object({
10991
- "Content-Type": z.string().default("text/event-stream"),
10992
- "Cache-Control": z.string().default("no-cache"),
10993
- Connection: z.string().default("keep-alive")
12117
+ headers: z$1.object({
12118
+ "Content-Type": z$1.string().default("text/event-stream"),
12119
+ "Cache-Control": z$1.string().default("no-cache"),
12120
+ Connection: z$1.string().default("keep-alive")
10994
12121
  }),
10995
12122
  content: {
10996
12123
  "text/event-stream": {
10997
- schema: z.string().describe("Server-Sent Events stream with chat completion chunks")
12124
+ schema: z$1.string().describe("Server-Sent Events stream with chat completion chunks")
10998
12125
  }
10999
12126
  }
11000
12127
  },
@@ -11002,13 +12129,13 @@ var chatCompletionsRoute = createRoute({
11002
12129
  description: "Invalid request context or parameters",
11003
12130
  content: {
11004
12131
  "application/json": {
11005
- schema: z.object({
11006
- error: z.string(),
11007
- details: z.array(
11008
- z.object({
11009
- field: z.string(),
11010
- message: z.string(),
11011
- value: z.unknown().optional()
12132
+ schema: z$1.object({
12133
+ error: z$1.string(),
12134
+ details: z$1.array(
12135
+ z$1.object({
12136
+ field: z$1.string(),
12137
+ message: z$1.string(),
12138
+ value: z$1.unknown().optional()
11012
12139
  })
11013
12140
  ).optional()
11014
12141
  })
@@ -11019,8 +12146,8 @@ var chatCompletionsRoute = createRoute({
11019
12146
  description: "Agent or agent not found",
11020
12147
  content: {
11021
12148
  "application/json": {
11022
- schema: z.object({
11023
- error: z.string()
12149
+ schema: z$1.object({
12150
+ error: z$1.string()
11024
12151
  })
11025
12152
  }
11026
12153
  }
@@ -11029,9 +12156,9 @@ var chatCompletionsRoute = createRoute({
11029
12156
  description: "Internal server error",
11030
12157
  content: {
11031
12158
  "application/json": {
11032
- schema: z.object({
11033
- error: z.string(),
11034
- message: z.string()
12159
+ schema: z$1.object({
12160
+ error: z$1.string(),
12161
+ message: z$1.string()
11035
12162
  })
11036
12163
  }
11037
12164
  }
@@ -11053,7 +12180,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11053
12180
  tracestate: c.req.header("tracestate"),
11054
12181
  baggage: c.req.header("baggage")
11055
12182
  };
11056
- logger21.info(
12183
+ logger22.info(
11057
12184
  {
11058
12185
  otelHeaders,
11059
12186
  path: c.req.path,
@@ -11162,7 +12289,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11162
12289
  dbClient: dbClient_default,
11163
12290
  credentialStores
11164
12291
  });
11165
- logger21.info(
12292
+ logger22.info(
11166
12293
  {
11167
12294
  tenantId,
11168
12295
  projectId,
@@ -11210,7 +12337,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11210
12337
  try {
11211
12338
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
11212
12339
  await sseHelper.writeRole();
11213
- logger21.info({ subAgentId }, "Starting execution");
12340
+ logger22.info({ subAgentId }, "Starting execution");
11214
12341
  const emitOperationsHeader = c.req.header("x-emit-operations");
11215
12342
  const emitOperations = emitOperationsHeader === "true";
11216
12343
  const executionHandler = new ExecutionHandler();
@@ -11223,7 +12350,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11223
12350
  sseHelper,
11224
12351
  emitOperations
11225
12352
  });
11226
- logger21.info(
12353
+ logger22.info(
11227
12354
  { result },
11228
12355
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11229
12356
  );
@@ -11237,7 +12364,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11237
12364
  }
11238
12365
  await sseHelper.complete();
11239
12366
  } catch (error) {
11240
- logger21.error(
12367
+ logger22.error(
11241
12368
  {
11242
12369
  error: error instanceof Error ? error.message : error,
11243
12370
  stack: error instanceof Error ? error.stack : void 0
@@ -11254,13 +12381,13 @@ app2.openapi(chatCompletionsRoute, async (c) => {
11254
12381
  );
11255
12382
  await sseHelper.complete();
11256
12383
  } catch (streamError) {
11257
- logger21.error({ streamError }, "Failed to write error to stream");
12384
+ logger22.error({ streamError }, "Failed to write error to stream");
11258
12385
  }
11259
12386
  }
11260
12387
  });
11261
12388
  });
11262
12389
  } catch (error) {
11263
- logger21.error(
12390
+ logger22.error(
11264
12391
  {
11265
12392
  error: error instanceof Error ? error.message : error,
11266
12393
  stack: error instanceof Error ? error.stack : void 0
@@ -11284,7 +12411,7 @@ var getMessageText = (content) => {
11284
12411
  };
11285
12412
  var chat_default = app2;
11286
12413
  var app3 = new OpenAPIHono();
11287
- var logger22 = getLogger("chatDataStream");
12414
+ var logger23 = getLogger("chatDataStream");
11288
12415
  var chatDataStreamRoute = createRoute({
11289
12416
  method: "post",
11290
12417
  path: "/chat",
@@ -11296,29 +12423,29 @@ var chatDataStreamRoute = createRoute({
11296
12423
  body: {
11297
12424
  content: {
11298
12425
  "application/json": {
11299
- schema: z.object({
11300
- model: z.string().optional(),
11301
- messages: z.array(
11302
- z.object({
11303
- role: z.enum(["system", "user", "assistant", "function", "tool"]),
11304
- content: z.any(),
11305
- parts: z.array(
11306
- z.object({
11307
- type: z.union([
11308
- z.enum(["text", "image", "audio", "video", "file"]),
11309
- z.string().regex(/^data-/, 'Type must start with "data-"')
12426
+ schema: z$1.object({
12427
+ model: z$1.string().optional(),
12428
+ messages: z$1.array(
12429
+ z$1.object({
12430
+ role: z$1.enum(["system", "user", "assistant", "function", "tool"]),
12431
+ content: z$1.any(),
12432
+ parts: z$1.array(
12433
+ z$1.object({
12434
+ type: z$1.union([
12435
+ z$1.enum(["text", "image", "audio", "video", "file"]),
12436
+ z$1.string().regex(/^data-/, 'Type must start with "data-"')
11310
12437
  ]),
11311
- text: z.string().optional()
12438
+ text: z$1.string().optional()
11312
12439
  })
11313
12440
  ).optional()
11314
12441
  })
11315
12442
  ),
11316
- id: z.string().optional(),
11317
- conversationId: z.string().optional(),
11318
- stream: z.boolean().optional().describe("Whether to stream the response").default(true),
11319
- max_tokens: z.number().optional().describe("Maximum tokens to generate"),
11320
- headers: z.record(z.string(), z.unknown()).optional().describe("Headers data for template processing"),
11321
- runConfig: z.record(z.string(), z.unknown()).optional().describe("Run configuration")
12443
+ id: z$1.string().optional(),
12444
+ conversationId: z$1.string().optional(),
12445
+ stream: z$1.boolean().optional().describe("Whether to stream the response").default(true),
12446
+ max_tokens: z$1.number().optional().describe("Maximum tokens to generate"),
12447
+ headers: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Headers data for template processing"),
12448
+ runConfig: z$1.record(z$1.string(), z$1.unknown()).optional().describe("Run configuration")
11322
12449
  })
11323
12450
  }
11324
12451
  }
@@ -11327,9 +12454,9 @@ var chatDataStreamRoute = createRoute({
11327
12454
  responses: {
11328
12455
  200: {
11329
12456
  description: "Streamed chat completion",
11330
- headers: z.object({
11331
- "Content-Type": z.string().default("text/plain; charset=utf-8"),
11332
- "x-vercel-ai-data-stream": z.string().default("v1")
12457
+ headers: z$1.object({
12458
+ "Content-Type": z$1.string().default("text/plain; charset=utf-8"),
12459
+ "x-vercel-ai-data-stream": z$1.string().default("v1")
11333
12460
  })
11334
12461
  },
11335
12462
  ...commonGetErrorResponses
@@ -11411,7 +12538,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11411
12538
  });
11412
12539
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
11413
12540
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
11414
- logger22.info({ userText, lastUserMessage }, "userText");
12541
+ logger23.info({ userText, lastUserMessage }, "userText");
11415
12542
  const messageSpan = trace.getActiveSpan();
11416
12543
  if (messageSpan) {
11417
12544
  messageSpan.setAttributes({
@@ -11494,7 +12621,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11494
12621
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
11495
12622
  }
11496
12623
  } catch (err) {
11497
- logger22.error({ err }, "Streaming error");
12624
+ logger23.error({ err }, "Streaming error");
11498
12625
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
11499
12626
  } finally {
11500
12627
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -11516,7 +12643,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
11516
12643
  );
11517
12644
  });
11518
12645
  } catch (error) {
11519
- logger22.error(
12646
+ logger23.error(
11520
12647
  {
11521
12648
  error,
11522
12649
  errorMessage: error instanceof Error ? error.message : String(error),
@@ -11542,11 +12669,11 @@ var toolApprovalRoute = createRoute({
11542
12669
  body: {
11543
12670
  content: {
11544
12671
  "application/json": {
11545
- schema: z.object({
11546
- conversationId: z.string().describe("The conversation ID"),
11547
- toolCallId: z.string().describe("The tool call ID to respond to"),
11548
- approved: z.boolean().describe("Whether the tool execution is approved"),
11549
- reason: z.string().optional().describe("Optional reason for the decision")
12672
+ schema: z$1.object({
12673
+ conversationId: z$1.string().describe("The conversation ID"),
12674
+ toolCallId: z$1.string().describe("The tool call ID to respond to"),
12675
+ approved: z$1.boolean().describe("Whether the tool execution is approved"),
12676
+ reason: z$1.string().optional().describe("Optional reason for the decision")
11550
12677
  })
11551
12678
  }
11552
12679
  }
@@ -11557,9 +12684,9 @@ var toolApprovalRoute = createRoute({
11557
12684
  description: "Tool approval response processed successfully",
11558
12685
  content: {
11559
12686
  "application/json": {
11560
- schema: z.object({
11561
- success: z.boolean(),
11562
- message: z.string().optional()
12687
+ schema: z$1.object({
12688
+ success: z$1.boolean(),
12689
+ message: z$1.string().optional()
11563
12690
  })
11564
12691
  }
11565
12692
  }
@@ -11568,8 +12695,8 @@ var toolApprovalRoute = createRoute({
11568
12695
  description: "Bad request - invalid tool call ID or conversation ID",
11569
12696
  content: {
11570
12697
  "application/json": {
11571
- schema: z.object({
11572
- error: z.string()
12698
+ schema: z$1.object({
12699
+ error: z$1.string()
11573
12700
  })
11574
12701
  }
11575
12702
  }
@@ -11578,8 +12705,8 @@ var toolApprovalRoute = createRoute({
11578
12705
  description: "Tool call not found or already processed",
11579
12706
  content: {
11580
12707
  "application/json": {
11581
- schema: z.object({
11582
- error: z.string()
12708
+ schema: z$1.object({
12709
+ error: z$1.string()
11583
12710
  })
11584
12711
  }
11585
12712
  }
@@ -11588,9 +12715,9 @@ var toolApprovalRoute = createRoute({
11588
12715
  description: "Internal server error",
11589
12716
  content: {
11590
12717
  "application/json": {
11591
- schema: z.object({
11592
- error: z.string(),
11593
- message: z.string()
12718
+ schema: z$1.object({
12719
+ error: z$1.string(),
12720
+ message: z$1.string()
11594
12721
  })
11595
12722
  }
11596
12723
  }
@@ -11605,7 +12732,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
11605
12732
  const { tenantId, projectId } = executionContext;
11606
12733
  const requestBody = await c.req.json();
11607
12734
  const { conversationId, toolCallId, approved, reason } = requestBody;
11608
- logger22.info(
12735
+ logger23.info(
11609
12736
  {
11610
12737
  conversationId,
11611
12738
  toolCallId,
@@ -11634,7 +12761,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
11634
12761
  span.setStatus({ code: 1, message: "Tool call not found" });
11635
12762
  return c.json({ error: "Tool call not found or already processed" }, 404);
11636
12763
  }
11637
- logger22.info({ conversationId, toolCallId, approved }, "Tool approval processed successfully");
12764
+ logger23.info({ conversationId, toolCallId, approved }, "Tool approval processed successfully");
11638
12765
  span.setStatus({ code: 1, message: "Success" });
11639
12766
  return c.json({
11640
12767
  success: true,
@@ -11642,7 +12769,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
11642
12769
  });
11643
12770
  } catch (error) {
11644
12771
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
11645
- logger22.error(
12772
+ logger23.error(
11646
12773
  {
11647
12774
  error: errorMessage,
11648
12775
  stack: error instanceof Error ? error.stack : void 0
@@ -11663,7 +12790,7 @@ app3.openapi(toolApprovalRoute, async (c) => {
11663
12790
  });
11664
12791
  });
11665
12792
  var chatDataStream_default = app3;
11666
- var logger23 = getLogger("mcp");
12793
+ var logger24 = getLogger("mcp");
11667
12794
  var MockResponseSingleton = class _MockResponseSingleton {
11668
12795
  static instance;
11669
12796
  mockRes;
@@ -11717,21 +12844,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
11717
12844
  id: 0
11718
12845
  });
11719
12846
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
11720
- logger23.info({ sessionId }, "Spoofing initialization message to set transport state");
12847
+ logger24.info({ sessionId }, "Spoofing initialization message to set transport state");
11721
12848
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
11722
12849
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
11723
12850
  try {
11724
12851
  await transport.handleRequest(req, mockRes, spoofInitMessage);
11725
- logger23.info({ sessionId }, "Successfully spoofed initialization");
12852
+ logger24.info({ sessionId }, "Successfully spoofed initialization");
11726
12853
  } catch (spoofError) {
11727
- logger23.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
12854
+ logger24.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11728
12855
  }
11729
12856
  };
11730
12857
  var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11731
12858
  const sessionId = req.headers["mcp-session-id"];
11732
- logger23.info({ sessionId }, "Received MCP session ID");
12859
+ logger24.info({ sessionId }, "Received MCP session ID");
11733
12860
  if (!sessionId) {
11734
- logger23.info({ body }, "Missing session ID");
12861
+ logger24.info({ body }, "Missing session ID");
11735
12862
  res.writeHead(400).end(
11736
12863
  JSON.stringify({
11737
12864
  jsonrpc: "2.0",
@@ -11758,7 +12885,7 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11758
12885
  scopes: { tenantId, projectId },
11759
12886
  conversationId: sessionId
11760
12887
  });
11761
- logger23.info(
12888
+ logger24.info(
11762
12889
  {
11763
12890
  sessionId,
11764
12891
  conversationFound: !!conversation,
@@ -11769,7 +12896,7 @@ var validateSession = async (req, res, body, tenantId, projectId, agentId) => {
11769
12896
  "Conversation lookup result"
11770
12897
  );
11771
12898
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.agentId !== agentId) {
11772
- logger23.info(
12899
+ logger24.info(
11773
12900
  { sessionId, conversationId: conversation?.id },
11774
12901
  "MCP session not found or invalid"
11775
12902
  );
@@ -11830,7 +12957,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultS
11830
12957
  requestId: requestId2,
11831
12958
  sseHelper: mcpStreamHelper
11832
12959
  });
11833
- logger23.info(
12960
+ logger24.info(
11834
12961
  { result },
11835
12962
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
11836
12963
  );
@@ -11874,7 +13001,7 @@ var getServer = async (headers2, executionContext, conversationId, credentialSto
11874
13001
  "send-query-to-agent",
11875
13002
  `Send a query to the ${agent.name} agent. The agent has the following description: ${agent.description}`,
11876
13003
  {
11877
- query: z.string().describe("The query to send to the agent")
13004
+ query: z$1.string().describe("The query to send to the agent")
11878
13005
  },
11879
13006
  async ({ query }) => {
11880
13007
  try {
@@ -11914,7 +13041,7 @@ var getServer = async (headers2, executionContext, conversationId, credentialSto
11914
13041
  dbClient: dbClient_default,
11915
13042
  credentialStores
11916
13043
  });
11917
- logger23.info(
13044
+ logger24.info(
11918
13045
  {
11919
13046
  tenantId,
11920
13047
  projectId,
@@ -11976,7 +13103,7 @@ var validateRequestParameters = (c) => {
11976
13103
  };
11977
13104
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
11978
13105
  const { tenantId, projectId, agentId } = executionContext;
11979
- logger23.info({ body }, "Received initialization request");
13106
+ logger24.info({ body }, "Received initialization request");
11980
13107
  const sessionId = getConversationId();
11981
13108
  const activeSpan = trace.getActiveSpan();
11982
13109
  if (activeSpan) {
@@ -12032,7 +13159,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
12032
13159
  }
12033
13160
  }
12034
13161
  });
12035
- logger23.info(
13162
+ logger24.info(
12036
13163
  { sessionId, conversationId: conversation.id },
12037
13164
  "Created MCP session as conversation"
12038
13165
  );
@@ -12041,9 +13168,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
12041
13168
  });
12042
13169
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
12043
13170
  await server.connect(transport);
12044
- logger23.info({ sessionId }, "Server connected for initialization");
13171
+ logger24.info({ sessionId }, "Server connected for initialization");
12045
13172
  res.setHeader("Mcp-Session-Id", sessionId);
12046
- logger23.info(
13173
+ logger24.info(
12047
13174
  {
12048
13175
  sessionId,
12049
13176
  bodyMethod: body?.method,
@@ -12052,7 +13179,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
12052
13179
  "About to handle initialization request"
12053
13180
  );
12054
13181
  await transport.handleRequest(req, res, body);
12055
- logger23.info({ sessionId }, "Successfully handled initialization request");
13182
+ logger24.info({ sessionId }, "Successfully handled initialization request");
12056
13183
  return toFetchResponse(res);
12057
13184
  });
12058
13185
  };
@@ -12079,8 +13206,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
12079
13206
  sessionId,
12080
13207
  conversation.metadata?.session_data?.mcpProtocolVersion
12081
13208
  );
12082
- logger23.info({ sessionId }, "Server connected and transport initialized");
12083
- logger23.info(
13209
+ logger24.info({ sessionId }, "Server connected and transport initialized");
13210
+ logger24.info(
12084
13211
  {
12085
13212
  sessionId,
12086
13213
  bodyKeys: Object.keys(body || {}),
@@ -12094,9 +13221,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
12094
13221
  );
12095
13222
  try {
12096
13223
  await transport.handleRequest(req, res, body);
12097
- logger23.info({ sessionId }, "Successfully handled MCP request");
13224
+ logger24.info({ sessionId }, "Successfully handled MCP request");
12098
13225
  } catch (transportError) {
12099
- logger23.error(
13226
+ logger24.error(
12100
13227
  {
12101
13228
  sessionId,
12102
13229
  error: transportError,
@@ -12147,13 +13274,13 @@ app4.openapi(
12147
13274
  }
12148
13275
  const { executionContext } = paramValidation;
12149
13276
  const body = c.get("requestBody") || {};
12150
- logger23.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
13277
+ logger24.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
12151
13278
  const isInitRequest = body.method === "initialize";
12152
13279
  const { req, res } = toReqRes(c.req.raw);
12153
13280
  const validatedContext = c.get("validatedContext") || {};
12154
13281
  const credentialStores = c.get("credentialStores");
12155
- logger23.info({ validatedContext }, "Validated context");
12156
- logger23.info({ req }, "request");
13282
+ logger24.info({ validatedContext }, "Validated context");
13283
+ logger24.info({ req }, "request");
12157
13284
  if (isInitRequest) {
12158
13285
  return await handleInitializationRequest(
12159
13286
  body,
@@ -12174,7 +13301,7 @@ app4.openapi(
12174
13301
  credentialStores
12175
13302
  );
12176
13303
  } catch (e) {
12177
- logger23.error(
13304
+ logger24.error(
12178
13305
  {
12179
13306
  error: e instanceof Error ? e.message : e,
12180
13307
  stack: e instanceof Error ? e.stack : void 0
@@ -12186,7 +13313,7 @@ app4.openapi(
12186
13313
  }
12187
13314
  );
12188
13315
  app4.get("/", async (c) => {
12189
- logger23.info({}, "Received GET MCP request");
13316
+ logger24.info({}, "Received GET MCP request");
12190
13317
  return c.json(
12191
13318
  {
12192
13319
  jsonrpc: "2.0",
@@ -12200,7 +13327,7 @@ app4.get("/", async (c) => {
12200
13327
  );
12201
13328
  });
12202
13329
  app4.delete("/", async (c) => {
12203
- logger23.info({}, "Received DELETE MCP request");
13330
+ logger24.info({}, "Received DELETE MCP request");
12204
13331
  return c.json(
12205
13332
  {
12206
13333
  jsonrpc: "2.0",
@@ -12213,7 +13340,7 @@ app4.delete("/", async (c) => {
12213
13340
  var mcp_default = app4;
12214
13341
 
12215
13342
  // src/app.ts
12216
- var logger24 = getLogger("agents-run-api");
13343
+ var logger25 = getLogger("agents-run-api");
12217
13344
  function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12218
13345
  const app6 = new OpenAPIHono();
12219
13346
  app6.use("*", otel());
@@ -12232,7 +13359,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12232
13359
  const body = await c.req.json();
12233
13360
  c.set("requestBody", body);
12234
13361
  } catch (error) {
12235
- logger24.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
13362
+ logger25.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
12236
13363
  }
12237
13364
  }
12238
13365
  return next();
@@ -12283,8 +13410,8 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12283
13410
  if (!isExpectedError) {
12284
13411
  const errorMessage = err instanceof Error ? err.message : String(err);
12285
13412
  const errorStack = err instanceof Error ? err.stack : void 0;
12286
- if (logger24) {
12287
- logger24.error(
13413
+ if (logger25) {
13414
+ logger25.error(
12288
13415
  {
12289
13416
  error: err,
12290
13417
  message: errorMessage,
@@ -12296,8 +13423,8 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12296
13423
  );
12297
13424
  }
12298
13425
  } else {
12299
- if (logger24) {
12300
- logger24.error(
13426
+ if (logger25) {
13427
+ logger25.error(
12301
13428
  {
12302
13429
  error: err,
12303
13430
  path: c.req.path,
@@ -12314,8 +13441,8 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12314
13441
  const response = err.getResponse();
12315
13442
  return response;
12316
13443
  } catch (responseError) {
12317
- if (logger24) {
12318
- logger24.error({ error: responseError }, "Error while handling HTTPException response");
13444
+ if (logger25) {
13445
+ logger25.error({ error: responseError }, "Error while handling HTTPException response");
12319
13446
  }
12320
13447
  }
12321
13448
  }
@@ -12349,7 +13476,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12349
13476
  app6.use("*", async (c, next) => {
12350
13477
  const executionContext = c.get("executionContext");
12351
13478
  if (!executionContext) {
12352
- logger24.debug({}, "Empty execution context");
13479
+ logger25.debug({}, "Empty execution context");
12353
13480
  return next();
12354
13481
  }
12355
13482
  const { tenantId, projectId, agentId } = executionContext;
@@ -12358,7 +13485,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12358
13485
  if (requestBody) {
12359
13486
  conversationId = requestBody.conversationId;
12360
13487
  if (!conversationId) {
12361
- logger24.debug({ requestBody }, "No conversation ID found in request body");
13488
+ logger25.debug({ requestBody }, "No conversation ID found in request body");
12362
13489
  }
12363
13490
  }
12364
13491
  const entries = Object.fromEntries(
@@ -12373,7 +13500,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12373
13500
  })
12374
13501
  );
12375
13502
  if (!Object.keys(entries).length) {
12376
- logger24.debug({}, "Empty entries for baggage");
13503
+ logger25.debug({}, "Empty entries for baggage");
12377
13504
  return next();
12378
13505
  }
12379
13506
  const bag = Object.entries(entries).reduce(
@@ -12427,6 +13554,7 @@ function createExecutionHono(serverConfig, credentialStores, sandboxConfig) {
12427
13554
  }
12428
13555
 
12429
13556
  // src/index.ts
13557
+ defaultSDK.start();
12430
13558
  var defaultConfig = {
12431
13559
  port: 3003,
12432
13560
  serverOptions: {