@inkeep/agents-run-api 0.31.6 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var agentsCore = require('@inkeep/agents-core');
6
- var z6 = require('zod');
6
+ var z7 = require('zod');
7
7
  var child_process = require('child_process');
8
8
  var crypto = require('crypto');
9
9
  var fs = require('fs');
@@ -45,7 +45,7 @@ var fetchToNode = require('fetch-to-node');
45
45
 
46
46
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
47
47
 
48
- var z6__default = /*#__PURE__*/_interopDefault(z6);
48
+ var z7__default = /*#__PURE__*/_interopDefault(z7);
49
49
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
50
50
  var jmespath__default = /*#__PURE__*/_interopDefault(jmespath);
51
51
  var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
@@ -67,30 +67,28 @@ var envSchema, parseEnv, env;
67
67
  var init_env = __esm({
68
68
  "src/env.ts"() {
69
69
  agentsCore.loadEnvironmentFiles();
70
- envSchema = z6.z.object({
71
- NODE_ENV: z6.z.enum(["development", "production", "test"]).optional(),
72
- ENVIRONMENT: z6.z.enum(["development", "production", "pentest", "test"]).optional().default("development"),
73
- DB_FILE_NAME: z6.z.string().optional(),
74
- TURSO_DATABASE_URL: z6.z.string().optional(),
75
- TURSO_AUTH_TOKEN: z6.z.string().optional(),
76
- AGENTS_RUN_API_URL: z6.z.string().optional().default("http://localhost:3003"),
77
- LOG_LEVEL: z6.z.enum(["trace", "debug", "info", "warn", "error"]).optional().default("debug"),
78
- NANGO_SERVER_URL: z6.z.string().optional().default("https://api.nango.dev"),
79
- NANGO_SECRET_KEY: z6.z.string().optional(),
80
- ANTHROPIC_API_KEY: z6.z.string(),
81
- OPENAI_API_KEY: z6.z.string().optional(),
82
- GOOGLE_GENERATIVE_AI_API_KEY: z6.z.string().optional(),
83
- INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z6.z.string().optional(),
84
- INKEEP_AGENTS_JWT_SIGNING_SECRET: z6.z.string().optional(),
85
- OTEL_BSP_SCHEDULE_DELAY: z6.z.coerce.number().optional().default(500),
86
- OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z6.z.coerce.number().optional().default(64)
70
+ envSchema = z7.z.object({
71
+ NODE_ENV: z7.z.enum(["development", "production", "test"]).optional(),
72
+ ENVIRONMENT: z7.z.enum(["development", "production", "pentest", "test"]).optional().default("development"),
73
+ DATABASE_URL: z7.z.string().optional(),
74
+ AGENTS_RUN_API_URL: z7.z.string().optional().default("http://localhost:3003"),
75
+ LOG_LEVEL: z7.z.enum(["trace", "debug", "info", "warn", "error"]).optional().default("debug"),
76
+ NANGO_SERVER_URL: z7.z.string().optional().default("https://api.nango.dev"),
77
+ NANGO_SECRET_KEY: z7.z.string().optional(),
78
+ ANTHROPIC_API_KEY: z7.z.string(),
79
+ OPENAI_API_KEY: z7.z.string().optional(),
80
+ GOOGLE_GENERATIVE_AI_API_KEY: z7.z.string().optional(),
81
+ INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z7.z.string().optional(),
82
+ INKEEP_AGENTS_JWT_SIGNING_SECRET: z7.z.string().optional(),
83
+ OTEL_BSP_SCHEDULE_DELAY: z7.z.coerce.number().optional().default(500),
84
+ OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z7.z.coerce.number().optional().default(64)
87
85
  });
88
86
  parseEnv = () => {
89
87
  try {
90
88
  const parsedEnv = envSchema.parse(process.env);
91
89
  return parsedEnv;
92
90
  } catch (error) {
93
- if (error instanceof z6.z.ZodError) {
91
+ if (error instanceof z7.z.ZodError) {
94
92
  const missingVars = error.issues.map((issue) => issue.path.join("."));
95
93
  throw new Error(
96
94
  `\u274C Invalid environment variables: ${missingVars.join(", ")}
@@ -125,28 +123,228 @@ var init_dbClient = __esm({
125
123
  init_env();
126
124
  getDbConfig = () => {
127
125
  if (env.ENVIRONMENT === "test") {
128
- return { url: ":memory:" };
126
+ return {};
129
127
  }
130
- if (env.TURSO_DATABASE_URL && env.TURSO_AUTH_TOKEN) {
131
- return {
132
- url: env.TURSO_DATABASE_URL,
133
- authToken: env.TURSO_AUTH_TOKEN
134
- };
135
- }
136
- if (!env.DB_FILE_NAME) {
137
- throw new Error(
138
- "Database configuration error: DB_FILE_NAME must be set if Turso is not configured."
139
- );
140
- }
141
- return {
142
- url: env.DB_FILE_NAME
143
- };
128
+ return { connectionString: env.DATABASE_URL };
144
129
  };
145
130
  dbClient = agentsCore.createDatabaseClient(getDbConfig());
146
131
  dbClient_default = dbClient;
147
132
  }
148
133
  });
149
134
 
135
+ // src/constants/execution-limits/defaults.ts
136
+ var executionLimitsDefaults;
137
+ var init_defaults = __esm({
138
+ "src/constants/execution-limits/defaults.ts"() {
139
+ executionLimitsDefaults = {
140
+ // Sub Agent Turn Execution
141
+ // During a Sub Agent's turn, it makes decisions by calling the LLM (language model). Each decision
142
+ // point is called a "generation step" - for example, deciding to call a tool, transfer to another
143
+ // Sub Agent, delegate a subtask, or send a response to the user.
144
+ // AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS: Maximum errors tolerated during a single Sub Agent's turn before stopping execution
145
+ // AGENT_EXECUTION_MAX_GENERATION_STEPS: Maximum LLM inference calls allowed within a single Sub Agent turn
146
+ AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS: 3,
147
+ AGENT_EXECUTION_MAX_GENERATION_STEPS: 5,
148
+ // Sub Agent Decision-Making Timeouts
149
+ // These control how long to wait for the LLM to make decisions during a Sub Agent's turn.
150
+ // "First call" = initial decision at start of turn (may include tool results from previous actions)
151
+ // "Subsequent call" = follow-up decisions after executing tools within the same turn
152
+ // Streaming mode has longer timeout because it waits for the full streamed response to the user
153
+ // LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING: Timeout for initial streaming response to user
154
+ // LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING: Timeout for initial non-streaming (internal) decision
155
+ // LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS: Timeout for follow-up decisions after tool execution
156
+ // LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS: Maximum timeout allowed regardless of configuration
157
+ LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING: 27e4,
158
+ // 4.5 minutes
159
+ LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING: 9e4,
160
+ // 1.5 minutes
161
+ LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS: 9e4,
162
+ // 1.5 minutes
163
+ LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS: 6e5,
164
+ // 10 minutes
165
+ // Function Tool Execution (Sandboxed Environments)
166
+ // Function Tools are custom JavaScript functions that Sub Agents can call. They run in secure
167
+ // isolated sandboxes (containerized environments) to prevent malicious code execution.
168
+ // For performance, sandboxes are cached and reused across multiple tool calls until they expire.
169
+ // FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT: Maximum execution time for a Function Tool call
170
+ // FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT: Virtual CPUs allocated to each sandbox (affects compute capacity)
171
+ // FUNCTION_TOOL_SANDBOX_POOL_TTL_MS: Time-to-live for cached sandboxes (after this, sandbox is discarded)
172
+ // FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT: Maximum reuses of a sandbox before it's refreshed (prevents resource leaks)
173
+ // FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES: Maximum size of Function Tool output (prevents memory exhaustion)
174
+ // FUNCTION_TOOL_SANDBOX_QUEUE_WAIT_TIMEOUT_MS: Maximum wait time for sandbox to become available when pool is full
175
+ // FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS: How often to check for and remove expired sandboxes from the pool
176
+ FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT: 3e4,
177
+ // 30 seconds
178
+ FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT: 4,
179
+ FUNCTION_TOOL_SANDBOX_POOL_TTL_MS: 3e5,
180
+ // 5 minutes
181
+ FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT: 50,
182
+ FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES: 1048576,
183
+ // 1 MB
184
+ FUNCTION_TOOL_SANDBOX_QUEUE_WAIT_TIMEOUT_MS: 3e4,
185
+ // 30 seconds
186
+ FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS: 6e4,
187
+ // 1 minute
188
+ // MCP Tool Execution
189
+ // MCP (Model Context Protocol) Servers are external services that provide tools to Sub Agents.
190
+ // When a Sub Agent calls an MCP Tool, the request is sent to the external MCP Server.
191
+ // Note: MCP connection/retry constants are defined in @inkeep/agents-core/constants/execution-limits-shared
192
+ // MCP_TOOL_REQUEST_TIMEOUT_MS_DEFAULT: Maximum wait time for an MCP tool call to complete
193
+ MCP_TOOL_REQUEST_TIMEOUT_MS_DEFAULT: 6e4,
194
+ // 60 seconds
195
+ // Sub Agent Delegation (Retry Strategy)
196
+ // When a Sub Agent delegates a subtask to another Sub Agent, it uses the A2A (Agent-to-Agent)
197
+ // protocol to communicate. If the delegation request fails, these constants control the
198
+ // exponential backoff retry strategy. Formula: delay = min(INITIAL * EXPONENT^attempt, MAX)
199
+ // DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS: Starting delay before first retry
200
+ // DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS: Maximum delay between retries (caps exponential growth)
201
+ // DELEGATION_TOOL_BACKOFF_EXPONENT: Multiplier applied to delay after each retry (2 = doubles each time)
202
+ // DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS: Total time to keep retrying before giving up
203
+ DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS: 100,
204
+ DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS: 1e4,
205
+ // 10 seconds
206
+ DELEGATION_TOOL_BACKOFF_EXPONENT: 2,
207
+ DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS: 2e4,
208
+ // 20 seconds
209
+ // General Agent-to-Agent (A2A) Communication (Retry Strategy)
210
+ // These control retries for broader A2A protocol operations beyond delegation (e.g., status checks,
211
+ // conversation updates). Uses more conservative retry parameters than delegation-specific retries.
212
+ // A2A_BACKOFF_INITIAL_INTERVAL_MS: Starting delay before first retry
213
+ // A2A_BACKOFF_MAX_INTERVAL_MS: Maximum delay between retries
214
+ // A2A_BACKOFF_EXPONENT: Multiplier for exponential backoff (1.5 = grows 50% each retry)
215
+ // A2A_BACKOFF_MAX_ELAPSED_TIME_MS: Total time to keep retrying before giving up
216
+ A2A_BACKOFF_INITIAL_INTERVAL_MS: 500,
217
+ A2A_BACKOFF_MAX_INTERVAL_MS: 6e4,
218
+ // 1 minute
219
+ A2A_BACKOFF_EXPONENT: 1.5,
220
+ A2A_BACKOFF_MAX_ELAPSED_TIME_MS: 3e4,
221
+ // 30 seconds
222
+ // Artifact Processing
223
+ // Artifacts are tool outputs saved for later reference by Sub Agents or users. When a tool generates
224
+ // an artifact, the system automatically generates a human-readable name and description using the LLM.
225
+ // These constants control artifact name/description generation and context window management.
226
+ // ARTIFACT_GENERATION_MAX_RETRIES: Retry attempts for LLM-based artifact name/description generation
227
+ // ARTIFACT_SESSION_MAX_PENDING: Maximum unprocessed artifacts in queue (prevents unbounded growth)
228
+ // ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES: Historical artifact summaries kept in context for reference
229
+ // ARTIFACT_GENERATION_BACKOFF_INITIAL_MS: Starting delay for retry backoff when generation fails
230
+ // ARTIFACT_GENERATION_BACKOFF_MAX_MS: Maximum delay between retries (formula: min(INITIAL * 2^attempt, MAX))
231
+ ARTIFACT_GENERATION_MAX_RETRIES: 3,
232
+ ARTIFACT_SESSION_MAX_PENDING: 100,
233
+ ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES: 3,
234
+ ARTIFACT_GENERATION_BACKOFF_INITIAL_MS: 1e3,
235
+ // 1 second
236
+ ARTIFACT_GENERATION_BACKOFF_MAX_MS: 1e4,
237
+ // 10 seconds
238
+ // Conversation Session & Cache Management
239
+ // A "session" represents the state of an ongoing conversation with an Agent. Tool results are cached
240
+ // within the session for performance - this is especially important for artifact processing where the
241
+ // same tool outputs may be referenced multiple times across Sub Agent turns.
242
+ // SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS: How long tool results are kept in cache before expiring
243
+ // SESSION_CLEANUP_INTERVAL_MS: How often to check for and remove expired cached tool results
244
+ SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS: 3e5,
245
+ // 5 minutes
246
+ SESSION_CLEANUP_INTERVAL_MS: 6e4,
247
+ // 1 minute
248
+ // Status Updates
249
+ // Status Updates are real-time progress messages sent to users during longer Sub Agent operations.
250
+ // The system automatically generates status updates based on activity thresholds - either after a
251
+ // certain number of significant events OR after a time interval (whichever comes first).
252
+ // Events include: tool calls, Sub Agent transfers, delegations, or other significant activities.
253
+ // STATUS_UPDATE_DEFAULT_NUM_EVENTS: Number of significant events before triggering a status update
254
+ // STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS: Time interval (in seconds) before generating status update
255
+ STATUS_UPDATE_DEFAULT_NUM_EVENTS: 1,
256
+ STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS: 2,
257
+ // Response Streaming (Internal Buffering Limits)
258
+ // These are internal infrastructure limits for streaming responses to users. Streaming enables
259
+ // real-time updates as Sub Agents generate responses, Data Components, and Status Updates.
260
+ // STREAM_PARSER_MAX_SNAPSHOT_SIZE: Maximum Data Component snapshots buffered before clearing old ones
261
+ // STREAM_PARSER_MAX_STREAMED_SIZE: Maximum streamed component IDs tracked simultaneously
262
+ // STREAM_PARSER_MAX_COLLECTED_PARTS: Maximum accumulated stream parts before forcing flush
263
+ // STREAM_BUFFER_MAX_SIZE_BYTES: Maximum total buffer size in bytes (prevents memory exhaustion)
264
+ // STREAM_TEXT_GAP_THRESHOLD_MS: Time gap that triggers bundling text with artifact data vs separate send
265
+ // STREAM_MAX_LIFETIME_MS: Maximum duration a stream can stay open before forced closure
266
+ STREAM_PARSER_MAX_SNAPSHOT_SIZE: 100,
267
+ STREAM_PARSER_MAX_STREAMED_SIZE: 1e3,
268
+ STREAM_PARSER_MAX_COLLECTED_PARTS: 1e4,
269
+ STREAM_BUFFER_MAX_SIZE_BYTES: 5242880,
270
+ // 5 MB
271
+ STREAM_TEXT_GAP_THRESHOLD_MS: 2e3,
272
+ // 2 seconds
273
+ STREAM_MAX_LIFETIME_MS: 6e5,
274
+ // 10 minutes
275
+ // Conversation History Message Retrieval
276
+ // CONVERSATION_HISTORY_DEFAULT_LIMIT: Default number of recent conversation messages to retrieve
277
+ CONVERSATION_HISTORY_DEFAULT_LIMIT: 50
278
+ };
279
+ }
280
+ });
281
+ var constantsSchema, parseConstants, constants, AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS, AGENT_EXECUTION_MAX_GENERATION_STEPS, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING, LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING, LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS, FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT, FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT, FUNCTION_TOOL_SANDBOX_POOL_TTL_MS, FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT, FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES, FUNCTION_TOOL_SANDBOX_QUEUE_WAIT_TIMEOUT_MS, FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS, MCP_TOOL_REQUEST_TIMEOUT_MS_DEFAULT, DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS, DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS, DELEGATION_TOOL_BACKOFF_EXPONENT, DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS, A2A_BACKOFF_INITIAL_INTERVAL_MS, A2A_BACKOFF_MAX_INTERVAL_MS, A2A_BACKOFF_EXPONENT, A2A_BACKOFF_MAX_ELAPSED_TIME_MS, ARTIFACT_GENERATION_MAX_RETRIES, ARTIFACT_SESSION_MAX_PENDING, ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES, ARTIFACT_GENERATION_BACKOFF_INITIAL_MS, ARTIFACT_GENERATION_BACKOFF_MAX_MS, SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS, SESSION_CLEANUP_INTERVAL_MS, STATUS_UPDATE_DEFAULT_NUM_EVENTS, STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS, STREAM_PARSER_MAX_SNAPSHOT_SIZE, STREAM_PARSER_MAX_STREAMED_SIZE, STREAM_PARSER_MAX_COLLECTED_PARTS, STREAM_BUFFER_MAX_SIZE_BYTES, STREAM_TEXT_GAP_THRESHOLD_MS, STREAM_MAX_LIFETIME_MS, CONVERSATION_HISTORY_DEFAULT_LIMIT;
282
+ var init_execution_limits = __esm({
283
+ "src/constants/execution-limits/index.ts"() {
284
+ init_defaults();
285
+ init_defaults();
286
+ agentsCore.loadEnvironmentFiles();
287
+ constantsSchema = z7.z.object(
288
+ Object.fromEntries(
289
+ Object.keys(executionLimitsDefaults).map((key) => [
290
+ `AGENTS_${key}`,
291
+ z7.z.coerce.number().optional()
292
+ ])
293
+ )
294
+ );
295
+ parseConstants = () => {
296
+ const envOverrides = constantsSchema.parse(process.env);
297
+ return Object.fromEntries(
298
+ Object.entries(executionLimitsDefaults).map(([key, defaultValue]) => [
299
+ key,
300
+ envOverrides[`AGENTS_${key}`] ?? defaultValue
301
+ ])
302
+ );
303
+ };
304
+ constants = parseConstants();
305
+ ({
306
+ AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS,
307
+ AGENT_EXECUTION_MAX_GENERATION_STEPS,
308
+ LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_STREAMING,
309
+ LLM_GENERATION_FIRST_CALL_TIMEOUT_MS_NON_STREAMING,
310
+ LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS,
311
+ LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS,
312
+ FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT,
313
+ FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT,
314
+ FUNCTION_TOOL_SANDBOX_POOL_TTL_MS,
315
+ FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT,
316
+ FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES,
317
+ FUNCTION_TOOL_SANDBOX_QUEUE_WAIT_TIMEOUT_MS,
318
+ FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS,
319
+ MCP_TOOL_REQUEST_TIMEOUT_MS_DEFAULT,
320
+ DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS,
321
+ DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS,
322
+ DELEGATION_TOOL_BACKOFF_EXPONENT,
323
+ DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS,
324
+ A2A_BACKOFF_INITIAL_INTERVAL_MS,
325
+ A2A_BACKOFF_MAX_INTERVAL_MS,
326
+ A2A_BACKOFF_EXPONENT,
327
+ A2A_BACKOFF_MAX_ELAPSED_TIME_MS,
328
+ ARTIFACT_GENERATION_MAX_RETRIES,
329
+ ARTIFACT_SESSION_MAX_PENDING,
330
+ ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES,
331
+ ARTIFACT_GENERATION_BACKOFF_INITIAL_MS,
332
+ ARTIFACT_GENERATION_BACKOFF_MAX_MS,
333
+ SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS,
334
+ SESSION_CLEANUP_INTERVAL_MS,
335
+ STATUS_UPDATE_DEFAULT_NUM_EVENTS,
336
+ STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS,
337
+ STREAM_PARSER_MAX_SNAPSHOT_SIZE,
338
+ STREAM_PARSER_MAX_STREAMED_SIZE,
339
+ STREAM_PARSER_MAX_COLLECTED_PARTS,
340
+ STREAM_BUFFER_MAX_SIZE_BYTES,
341
+ STREAM_TEXT_GAP_THRESHOLD_MS,
342
+ STREAM_MAX_LIFETIME_MS,
343
+ CONVERSATION_HISTORY_DEFAULT_LIMIT
344
+ } = constants);
345
+ }
346
+ });
347
+
150
348
  // src/data/conversations.ts
151
349
  var conversations_exports = {};
152
350
  __export(conversations_exports, {
@@ -161,10 +359,10 @@ __export(conversations_exports, {
161
359
  function createDefaultConversationHistoryConfig(mode = "full") {
162
360
  return {
163
361
  mode,
164
- limit: 50,
362
+ limit: CONVERSATION_HISTORY_DEFAULT_LIMIT,
165
363
  includeInternal: true,
166
364
  messageTypes: ["chat"],
167
- maxOutputTokens: 4e3
365
+ maxOutputTokens: agentsCore.CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT
168
366
  };
169
367
  }
170
368
  function extractA2AMessageText(parts) {
@@ -253,7 +451,7 @@ async function getScopedHistory({
253
451
  return [];
254
452
  }
255
453
  }
256
- async function getUserFacingHistory(tenantId, projectId, conversationId, limit = 50) {
454
+ async function getUserFacingHistory(tenantId, projectId, conversationId, limit = CONVERSATION_HISTORY_DEFAULT_LIMIT) {
257
455
  return await agentsCore.getConversationHistory(dbClient_default)({
258
456
  scopes: { tenantId, projectId },
259
457
  conversationId,
@@ -383,6 +581,7 @@ async function getConversationScopedArtifacts(params) {
383
581
  }
384
582
  var init_conversations = __esm({
385
583
  "src/data/conversations.ts"() {
584
+ init_execution_limits();
386
585
  init_dbClient();
387
586
  }
388
587
  });
@@ -438,10 +637,12 @@ var init_sandbox_utils = __esm({
438
637
  var logger16, ExecutionSemaphore, _NativeSandboxExecutor, NativeSandboxExecutor;
439
638
  var init_NativeSandboxExecutor = __esm({
440
639
  "src/tools/NativeSandboxExecutor.ts"() {
640
+ init_execution_limits();
641
+ init_logger();
441
642
  init_sandbox_utils();
442
643
  logger16 = agentsCore.getLogger("native-sandbox-executor");
443
644
  ExecutionSemaphore = class {
444
- constructor(permits, maxWaitTimeMs = 3e4) {
645
+ constructor(permits, maxWaitTimeMs = FUNCTION_TOOL_SANDBOX_QUEUE_WAIT_TIMEOUT_MS) {
445
646
  __publicField(this, "permits");
446
647
  __publicField(this, "waitQueue", []);
447
648
  __publicField(this, "maxWaitTime");
@@ -496,9 +697,6 @@ var init_NativeSandboxExecutor = __esm({
496
697
  constructor() {
497
698
  __publicField(this, "tempDir");
498
699
  __publicField(this, "sandboxPool", {});
499
- __publicField(this, "POOL_TTL", 5 * 60 * 1e3);
500
- // 5 minutes
501
- __publicField(this, "MAX_USE_COUNT", 50);
502
700
  __publicField(this, "executionSemaphores", /* @__PURE__ */ new Map());
503
701
  this.tempDir = path.join(os.tmpdir(), "inkeep-sandboxes");
504
702
  this.ensureTempDir();
@@ -547,7 +745,7 @@ var init_NativeSandboxExecutor = __esm({
547
745
  const sandbox = this.sandboxPool[poolKey];
548
746
  if (sandbox && fs.existsSync(sandbox.sandboxDir)) {
549
747
  const now = Date.now();
550
- if (now - sandbox.lastUsed < this.POOL_TTL && sandbox.useCount < this.MAX_USE_COUNT) {
748
+ if (now - sandbox.lastUsed < FUNCTION_TOOL_SANDBOX_POOL_TTL_MS && sandbox.useCount < FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
551
749
  sandbox.lastUsed = now;
552
750
  sandbox.useCount++;
553
751
  logger16.debug(
@@ -555,7 +753,7 @@ var init_NativeSandboxExecutor = __esm({
555
753
  poolKey,
556
754
  useCount: sandbox.useCount,
557
755
  sandboxDir: sandbox.sandboxDir,
558
- lastUsed: new Date(sandbox.lastUsed).toISOString()
756
+ lastUsed: new Date(sandbox.lastUsed)
559
757
  },
560
758
  "Reusing cached sandbox"
561
759
  );
@@ -593,7 +791,7 @@ var init_NativeSandboxExecutor = __esm({
593
791
  const now = Date.now();
594
792
  const keysToDelete = [];
595
793
  for (const [key, sandbox] of Object.entries(this.sandboxPool)) {
596
- if (now - sandbox.lastUsed > this.POOL_TTL || sandbox.useCount >= this.MAX_USE_COUNT) {
794
+ if (now - sandbox.lastUsed > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || sandbox.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
597
795
  this.cleanupSandbox(sandbox.sandboxDir);
598
796
  keysToDelete.push(key);
599
797
  }
@@ -604,7 +802,7 @@ var init_NativeSandboxExecutor = __esm({
604
802
  if (keysToDelete.length > 0) {
605
803
  logger16.debug({ cleanedCount: keysToDelete.length }, "Cleaned up expired sandboxes");
606
804
  }
607
- }, 6e4);
805
+ }, FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS);
608
806
  }
609
807
  detectModuleType(executeCode, configuredRuntime) {
610
808
  const esmPatterns = [
@@ -714,7 +912,7 @@ var init_NativeSandboxExecutor = __esm({
714
912
  fs.writeFileSync(path.join(sandboxDir, `index.${fileExtension}`), executionCode, "utf8");
715
913
  const result = await this.executeInSandbox(
716
914
  sandboxDir,
717
- config.sandboxConfig?.timeout || 3e4,
915
+ config.sandboxConfig?.timeout || FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT,
718
916
  moduleType,
719
917
  config.sandboxConfig
720
918
  );
@@ -779,13 +977,16 @@ var init_NativeSandboxExecutor = __esm({
779
977
  let stdout = "";
780
978
  let stderr = "";
781
979
  let outputSize = 0;
782
- const MAX_OUTPUT_SIZE = 1024 * 1024;
783
980
  node.stdout?.on("data", (data) => {
784
981
  const dataStr = data.toString();
785
982
  outputSize += dataStr.length;
786
- if (outputSize > MAX_OUTPUT_SIZE) {
983
+ if (outputSize > FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES) {
787
984
  node.kill("SIGTERM");
788
- reject(new Error(`Output size exceeded limit of ${MAX_OUTPUT_SIZE} bytes`));
985
+ reject(
986
+ new Error(
987
+ `Output size exceeded limit of ${FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES} bytes`
988
+ )
989
+ );
789
990
  return;
790
991
  }
791
992
  stdout += dataStr;
@@ -793,9 +994,13 @@ var init_NativeSandboxExecutor = __esm({
793
994
  node.stderr?.on("data", (data) => {
794
995
  const dataStr = data.toString();
795
996
  outputSize += dataStr.length;
796
- if (outputSize > MAX_OUTPUT_SIZE) {
997
+ if (outputSize > FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES) {
797
998
  node.kill("SIGTERM");
798
- reject(new Error(`Output size exceeded limit of ${MAX_OUTPUT_SIZE} bytes`));
999
+ reject(
1000
+ new Error(
1001
+ `Output size exceeded limit of ${FUNCTION_TOOL_SANDBOX_MAX_OUTPUT_SIZE_BYTES} bytes`
1002
+ )
1003
+ );
799
1004
  return;
800
1005
  }
801
1006
  stderr += dataStr;
@@ -852,6 +1057,7 @@ var init_NativeSandboxExecutor = __esm({
852
1057
  var logger17, _VercelSandboxExecutor, VercelSandboxExecutor;
853
1058
  var init_VercelSandboxExecutor = __esm({
854
1059
  "src/tools/VercelSandboxExecutor.ts"() {
1060
+ init_execution_limits();
855
1061
  init_logger();
856
1062
  init_sandbox_utils();
857
1063
  logger17 = agentsCore.getLogger("VercelSandboxExecutor");
@@ -859,9 +1065,6 @@ var init_VercelSandboxExecutor = __esm({
859
1065
  constructor(config) {
860
1066
  __publicField(this, "config");
861
1067
  __publicField(this, "sandboxPool", /* @__PURE__ */ new Map());
862
- __publicField(this, "POOL_TTL", 5 * 60 * 1e3);
863
- // 5 minutes
864
- __publicField(this, "MAX_USE_COUNT", 50);
865
1068
  __publicField(this, "cleanupInterval", null);
866
1069
  this.config = config;
867
1070
  logger17.info(
@@ -900,14 +1103,14 @@ var init_VercelSandboxExecutor = __esm({
900
1103
  if (!cached) return null;
901
1104
  const now = Date.now();
902
1105
  const age = now - cached.createdAt;
903
- if (age > this.POOL_TTL || cached.useCount >= this.MAX_USE_COUNT) {
1106
+ if (age > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || cached.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
904
1107
  logger17.debug(
905
1108
  {
906
1109
  dependencyHash,
907
1110
  age,
908
1111
  useCount: cached.useCount,
909
- ttl: this.POOL_TTL,
910
- maxUseCount: this.MAX_USE_COUNT
1112
+ ttl: FUNCTION_TOOL_SANDBOX_POOL_TTL_MS,
1113
+ maxUseCount: FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT
911
1114
  },
912
1115
  "Sandbox expired, will create new one"
913
1116
  );
@@ -970,32 +1173,28 @@ var init_VercelSandboxExecutor = __esm({
970
1173
  * Start periodic cleanup of expired sandboxes
971
1174
  */
972
1175
  startPoolCleanup() {
973
- this.cleanupInterval = setInterval(
974
- () => {
975
- const now = Date.now();
976
- const toRemove = [];
977
- for (const [hash, cached] of this.sandboxPool.entries()) {
978
- const age = now - cached.createdAt;
979
- if (age > this.POOL_TTL || cached.useCount >= this.MAX_USE_COUNT) {
980
- toRemove.push(hash);
981
- }
1176
+ this.cleanupInterval = setInterval(() => {
1177
+ const now = Date.now();
1178
+ const toRemove = [];
1179
+ for (const [hash, cached] of this.sandboxPool.entries()) {
1180
+ const age = now - cached.createdAt;
1181
+ if (age > FUNCTION_TOOL_SANDBOX_POOL_TTL_MS || cached.useCount >= FUNCTION_TOOL_SANDBOX_MAX_USE_COUNT) {
1182
+ toRemove.push(hash);
982
1183
  }
983
- if (toRemove.length > 0) {
984
- logger17.info(
985
- {
986
- count: toRemove.length,
987
- poolSize: this.sandboxPool.size
988
- },
989
- "Cleaning up expired sandboxes"
990
- );
991
- for (const hash of toRemove) {
992
- this.removeSandbox(hash);
993
- }
1184
+ }
1185
+ if (toRemove.length > 0) {
1186
+ logger17.info(
1187
+ {
1188
+ count: toRemove.length,
1189
+ poolSize: this.sandboxPool.size
1190
+ },
1191
+ "Cleaning up expired sandboxes"
1192
+ );
1193
+ for (const hash of toRemove) {
1194
+ this.removeSandbox(hash);
994
1195
  }
995
- },
996
- 60 * 1e3
997
- // Run every minute
998
- );
1196
+ }
1197
+ }, FUNCTION_TOOL_SANDBOX_CLEANUP_INTERVAL_MS);
999
1198
  }
1000
1199
  /**
1001
1200
  * Cleanup all sandboxes and stop cleanup interval
@@ -2552,14 +2751,13 @@ __publicField(_ModelFactory, "BUILT_IN_PROVIDERS", [
2552
2751
  var ModelFactory = _ModelFactory;
2553
2752
 
2554
2753
  // src/agents/ToolSessionManager.ts
2754
+ init_execution_limits();
2555
2755
  init_logger();
2556
2756
  var logger5 = agentsCore.getLogger("ToolSessionManager");
2557
2757
  var _ToolSessionManager = class _ToolSessionManager {
2558
- // 5 minutes
2559
2758
  constructor() {
2560
2759
  __publicField(this, "sessions", /* @__PURE__ */ new Map());
2561
- __publicField(this, "SESSION_TIMEOUT", 5 * 60 * 1e3);
2562
- setInterval(() => this.cleanupExpiredSessions(), 6e4);
2760
+ setInterval(() => this.cleanupExpiredSessions(), SESSION_CLEANUP_INTERVAL_MS);
2563
2761
  }
2564
2762
  static getInstance() {
2565
2763
  if (!_ToolSessionManager.instance) {
@@ -2704,7 +2902,7 @@ var _ToolSessionManager = class _ToolSessionManager {
2704
2902
  const now = Date.now();
2705
2903
  const expiredSessions = [];
2706
2904
  for (const [sessionId, session] of this.sessions.entries()) {
2707
- if (now - session.createdAt > this.SESSION_TIMEOUT) {
2905
+ if (now - session.createdAt > SESSION_TOOL_RESULT_CACHE_TIMEOUT_MS) {
2708
2906
  expiredSessions.push(sessionId);
2709
2907
  }
2710
2908
  }
@@ -2722,6 +2920,7 @@ var ToolSessionManager = _ToolSessionManager;
2722
2920
  var toolSessionManager = ToolSessionManager.getInstance();
2723
2921
 
2724
2922
  // src/services/AgentSession.ts
2923
+ init_execution_limits();
2725
2924
  init_conversations();
2726
2925
  init_dbClient();
2727
2926
  init_logger();
@@ -2982,7 +3181,16 @@ var _ArtifactService = class _ArtifactService {
2982
3181
  );
2983
3182
  return null;
2984
3183
  }
2985
- const artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
3184
+ let artifacts = [];
3185
+ artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
3186
+ scopes: { tenantId: this.context.tenantId, projectId: this.context.projectId },
3187
+ artifactId,
3188
+ toolCallId
3189
+ });
3190
+ if (artifacts.length > 0) {
3191
+ return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
3192
+ }
3193
+ artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
2986
3194
  scopes: { tenantId: this.context.tenantId, projectId: this.context.projectId },
2987
3195
  artifactId,
2988
3196
  taskId: this.context.taskId
@@ -3028,7 +3236,16 @@ var _ArtifactService = class _ArtifactService {
3028
3236
  );
3029
3237
  return null;
3030
3238
  }
3031
- const artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
3239
+ let artifacts = [];
3240
+ artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
3241
+ scopes: { tenantId: this.context.tenantId, projectId: this.context.projectId },
3242
+ artifactId,
3243
+ toolCallId
3244
+ });
3245
+ if (artifacts.length > 0) {
3246
+ return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
3247
+ }
3248
+ artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
3032
3249
  scopes: { tenantId: this.context.tenantId, projectId: this.context.projectId },
3033
3250
  artifactId,
3034
3251
  taskId: this.context.taskId
@@ -3871,8 +4088,8 @@ var AgentSession = class {
3871
4088
  // Track pending artifact processing
3872
4089
  __publicField(this, "artifactProcessingErrors", /* @__PURE__ */ new Map());
3873
4090
  // Track errors per artifact
3874
- __publicField(this, "MAX_ARTIFACT_RETRIES", 3);
3875
- __publicField(this, "MAX_PENDING_ARTIFACTS", 100);
4091
+ __publicField(this, "MAX_ARTIFACT_RETRIES", ARTIFACT_GENERATION_MAX_RETRIES);
4092
+ __publicField(this, "MAX_PENDING_ARTIFACTS", ARTIFACT_SESSION_MAX_PENDING);
3876
4093
  // Prevent unbounded growth
3877
4094
  __publicField(this, "scheduledTimeouts");
3878
4095
  // Track scheduled timeouts for cleanup
@@ -3992,8 +4209,8 @@ var AgentSession = class {
3992
4209
  summarizerModel,
3993
4210
  baseModel,
3994
4211
  config: {
3995
- numEvents: config.numEvents || 1,
3996
- timeInSeconds: config.timeInSeconds || 2,
4212
+ numEvents: config.numEvents || STATUS_UPDATE_DEFAULT_NUM_EVENTS,
4213
+ timeInSeconds: config.timeInSeconds || STATUS_UPDATE_DEFAULT_INTERVAL_SECONDS,
3997
4214
  ...config
3998
4215
  }
3999
4216
  };
@@ -4336,7 +4553,7 @@ var AgentSession = class {
4336
4553
  }
4337
4554
  return;
4338
4555
  }
4339
- if (this.previousSummaries.length > 3) {
4556
+ if (this.previousSummaries.length > ARTIFACT_SESSION_MAX_PREVIOUS_SUMMARIES) {
4340
4557
  this.previousSummaries.shift();
4341
4558
  }
4342
4559
  if (this.statusUpdateState) {
@@ -4449,9 +4666,8 @@ var AgentSession = class {
4449
4666
  projectId: this.projectId,
4450
4667
  conversationId: this.sessionId,
4451
4668
  options: {
4452
- limit: 10,
4453
- // Get recent conversation context
4454
- maxOutputTokens: 2e3
4669
+ limit: agentsCore.CONVERSATION_HISTORY_DEFAULT_LIMIT,
4670
+ maxOutputTokens: agentsCore.CONVERSATION_HISTORY_MAX_OUTPUT_TOKENS_DEFAULT
4455
4671
  },
4456
4672
  filters: {}
4457
4673
  });
@@ -4470,12 +4686,12 @@ ${conversationHistory}
4470
4686
  Previous updates sent to user:
4471
4687
  ${previousSummaries.map((s, i) => `${i + 1}. ${s}`).join("\n")}
4472
4688
  ` : "";
4473
- const selectionSchema = z6.z.object(
4689
+ const selectionSchema = z7.z.object(
4474
4690
  Object.fromEntries([
4475
4691
  [
4476
4692
  "no_relevant_updates",
4477
- z6.z.object({
4478
- no_updates: z6.z.boolean().default(true)
4693
+ z7.z.object({
4694
+ no_updates: z7.z.boolean().default(true)
4479
4695
  }).optional().describe(
4480
4696
  "Use when nothing substantially new to report. Should only use on its own."
4481
4697
  )
@@ -4607,8 +4823,8 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
4607
4823
  if (component.detailsSchema && "properties" in component.detailsSchema) {
4608
4824
  return this.buildZodSchemaFromJson(component.detailsSchema);
4609
4825
  }
4610
- return z6.z.object({
4611
- label: z6.z.string().describe(
4826
+ return z7.z.object({
4827
+ label: z7.z.string().describe(
4612
4828
  '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.'
4613
4829
  )
4614
4830
  });
@@ -4618,56 +4834,56 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
4618
4834
  */
4619
4835
  buildZodSchemaFromJson(jsonSchema) {
4620
4836
  const properties = {};
4621
- properties.label = z6.z.string().describe(
4837
+ properties.label = z7.z.string().describe(
4622
4838
  '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.'
4623
4839
  );
4624
4840
  for (const [key, value] of Object.entries(jsonSchema.properties)) {
4625
4841
  let zodType;
4626
4842
  if (value.enum && Array.isArray(value.enum)) {
4627
4843
  if (value.enum.length === 1) {
4628
- zodType = z6.z.literal(value.enum[0]);
4844
+ zodType = z7.z.literal(value.enum[0]);
4629
4845
  } else {
4630
4846
  const [first, ...rest] = value.enum;
4631
- zodType = z6.z.enum([first, ...rest]);
4847
+ zodType = z7.z.enum([first, ...rest]);
4632
4848
  }
4633
4849
  } else if (value.type === "string") {
4634
- zodType = z6.z.string();
4850
+ zodType = z7.z.string();
4635
4851
  if (value.minLength) zodType = zodType.min(value.minLength);
4636
4852
  if (value.maxLength) zodType = zodType.max(value.maxLength);
4637
4853
  if (value.format === "email") zodType = zodType.email();
4638
4854
  if (value.format === "url" || value.format === "uri")
4639
4855
  zodType = zodType.url();
4640
4856
  } else if (value.type === "number" || value.type === "integer") {
4641
- zodType = value.type === "integer" ? z6.z.number().int() : z6.z.number();
4857
+ zodType = value.type === "integer" ? z7.z.number().int() : z7.z.number();
4642
4858
  if (value.minimum !== void 0) zodType = zodType.min(value.minimum);
4643
4859
  if (value.maximum !== void 0) zodType = zodType.max(value.maximum);
4644
4860
  } else if (value.type === "boolean") {
4645
- zodType = z6.z.boolean();
4861
+ zodType = z7.z.boolean();
4646
4862
  } else if (value.type === "array") {
4647
4863
  if (value.items) {
4648
4864
  if (value.items.enum && Array.isArray(value.items.enum)) {
4649
4865
  const [first, ...rest] = value.items.enum;
4650
- zodType = z6.z.array(z6.z.enum([first, ...rest]));
4866
+ zodType = z7.z.array(z7.z.enum([first, ...rest]));
4651
4867
  } else if (value.items.type === "string") {
4652
- zodType = z6.z.array(z6.z.string());
4868
+ zodType = z7.z.array(z7.z.string());
4653
4869
  } else if (value.items.type === "number") {
4654
- zodType = z6.z.array(z6.z.number());
4870
+ zodType = z7.z.array(z7.z.number());
4655
4871
  } else if (value.items.type === "boolean") {
4656
- zodType = z6.z.array(z6.z.boolean());
4872
+ zodType = z7.z.array(z7.z.boolean());
4657
4873
  } else if (value.items.type === "object") {
4658
- zodType = z6.z.array(z6.z.record(z6.z.string(), z6.z.any()));
4874
+ zodType = z7.z.array(z7.z.record(z7.z.string(), z7.z.any()));
4659
4875
  } else {
4660
- zodType = z6.z.array(z6.z.any());
4876
+ zodType = z7.z.array(z7.z.any());
4661
4877
  }
4662
4878
  } else {
4663
- zodType = z6.z.array(z6.z.any());
4879
+ zodType = z7.z.array(z7.z.any());
4664
4880
  }
4665
4881
  if (value.minItems) zodType = zodType.min(value.minItems);
4666
4882
  if (value.maxItems) zodType = zodType.max(value.maxItems);
4667
4883
  } else if (value.type === "object") {
4668
- zodType = z6.z.record(z6.z.string(), z6.z.any());
4884
+ zodType = z7.z.record(z7.z.string(), z7.z.any());
4669
4885
  } else {
4670
- zodType = z6.z.any();
4886
+ zodType = z7.z.any();
4671
4887
  }
4672
4888
  if (value.description) {
4673
4889
  zodType = zodType.describe(value.description);
@@ -4677,7 +4893,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
4677
4893
  }
4678
4894
  properties[key] = zodType;
4679
4895
  }
4680
- return z6.z.object(properties);
4896
+ return z7.z.object(properties);
4681
4897
  }
4682
4898
  /**
4683
4899
  * Extract user-visible activities with rich formatting and complete information
@@ -4908,9 +5124,9 @@ Make it specific and relevant.`;
4908
5124
  };
4909
5125
  } else {
4910
5126
  const model = ModelFactory.createModel(modelToUse);
4911
- const schema = z6.z.object({
4912
- name: z6.z.string().describe("Concise, descriptive name for the artifact"),
4913
- description: z6.z.string().describe("Brief description of the artifact's relevance to the user's question")
5127
+ const schema = z7.z.object({
5128
+ name: z7.z.string().describe("Concise, descriptive name for the artifact"),
5129
+ description: z7.z.string().describe("Brief description of the artifact's relevance to the user's question")
4914
5130
  });
4915
5131
  const { object } = await tracer.startActiveSpan(
4916
5132
  "agent_session.generate_artifact_metadata",
@@ -4980,7 +5196,10 @@ Make it specific and relevant.`;
4980
5196
  `Artifact name/description generation failed, attempt ${attempt}/${maxRetries}`
4981
5197
  );
4982
5198
  if (attempt < maxRetries) {
4983
- const backoffMs = Math.min(1e3 * 2 ** (attempt - 1), 1e4);
5199
+ const backoffMs = Math.min(
5200
+ ARTIFACT_GENERATION_BACKOFF_INITIAL_MS * 2 ** (attempt - 1),
5201
+ ARTIFACT_GENERATION_BACKOFF_MAX_MS
5202
+ );
4984
5203
  await new Promise((resolve) => setTimeout(resolve, backoffMs));
4985
5204
  }
4986
5205
  }
@@ -4996,15 +5215,8 @@ Make it specific and relevant.`;
4996
5215
  );
4997
5216
  result = object;
4998
5217
  }
4999
- const artifactService = new ArtifactService({
5000
- tenantId: artifactData.tenantId,
5001
- projectId: artifactData.projectId,
5002
- contextId: artifactData.contextId,
5003
- taskId: artifactData.taskId,
5004
- sessionId: this.sessionId
5005
- });
5006
5218
  try {
5007
- await artifactService.saveArtifact({
5219
+ await this.artifactService.saveArtifact({
5008
5220
  artifactId: artifactData.artifactId,
5009
5221
  name: result.name,
5010
5222
  description: result.description,
@@ -5033,14 +5245,14 @@ Make it specific and relevant.`;
5033
5245
  if (!mainSaveSucceeded) {
5034
5246
  try {
5035
5247
  if (artifactData.tenantId && artifactData.projectId) {
5036
- const artifactService2 = new ArtifactService({
5248
+ const artifactService = new ArtifactService({
5037
5249
  tenantId: artifactData.tenantId,
5038
5250
  projectId: artifactData.projectId,
5039
5251
  contextId: artifactData.contextId || "unknown",
5040
5252
  taskId: artifactData.taskId,
5041
5253
  sessionId: this.sessionId
5042
5254
  });
5043
- await artifactService2.saveArtifact({
5255
+ await artifactService.saveArtifact({
5044
5256
  artifactId: artifactData.artifactId,
5045
5257
  name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
5046
5258
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool results"}`,
@@ -5305,11 +5517,13 @@ async function resolveModelConfig(agentId, subAgent) {
5305
5517
  }
5306
5518
 
5307
5519
  // src/agents/Agent.ts
5520
+ init_execution_limits();
5308
5521
  init_conversations();
5309
5522
  init_dbClient();
5310
5523
  init_logger();
5311
5524
 
5312
5525
  // src/services/IncrementalStreamParser.ts
5526
+ init_execution_limits();
5313
5527
  init_logger();
5314
5528
  var logger10 = agentsCore.getLogger("IncrementalStreamParser");
5315
5529
  var _IncrementalStreamParser = class _IncrementalStreamParser {
@@ -5704,11 +5918,11 @@ ${chunk}`;
5704
5918
  }
5705
5919
  }
5706
5920
  };
5707
- __publicField(_IncrementalStreamParser, "MAX_SNAPSHOT_SIZE", 100);
5921
+ __publicField(_IncrementalStreamParser, "MAX_SNAPSHOT_SIZE", STREAM_PARSER_MAX_SNAPSHOT_SIZE);
5708
5922
  // Max number of snapshots to keep
5709
- __publicField(_IncrementalStreamParser, "MAX_STREAMED_SIZE", 1e3);
5923
+ __publicField(_IncrementalStreamParser, "MAX_STREAMED_SIZE", STREAM_PARSER_MAX_STREAMED_SIZE);
5710
5924
  // Max number of streamed component IDs to track
5711
- __publicField(_IncrementalStreamParser, "MAX_COLLECTED_PARTS", 1e4);
5925
+ __publicField(_IncrementalStreamParser, "MAX_COLLECTED_PARTS", STREAM_PARSER_MAX_COLLECTED_PARTS);
5712
5926
  var IncrementalStreamParser = _IncrementalStreamParser;
5713
5927
 
5714
5928
  // src/services/ResponseFormatter.ts
@@ -5914,7 +6128,7 @@ var logger12 = agentsCore.getLogger("DataComponentSchema");
5914
6128
  function jsonSchemaToZod(jsonSchema) {
5915
6129
  if (!jsonSchema || typeof jsonSchema !== "object") {
5916
6130
  logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
5917
- return z6.z.string();
6131
+ return z7.z.string();
5918
6132
  }
5919
6133
  switch (jsonSchema.type) {
5920
6134
  case "object":
@@ -5923,22 +6137,22 @@ function jsonSchemaToZod(jsonSchema) {
5923
6137
  for (const [key, prop] of Object.entries(jsonSchema.properties)) {
5924
6138
  shape[key] = jsonSchemaToZod(prop);
5925
6139
  }
5926
- return z6.z.object(shape);
6140
+ return z7.z.object(shape);
5927
6141
  }
5928
- return z6.z.record(z6.z.string(), z6.z.unknown());
6142
+ return z7.z.record(z7.z.string(), z7.z.unknown());
5929
6143
  case "array": {
5930
- const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z6.z.unknown();
5931
- return z6.z.array(itemSchema);
6144
+ const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z7.z.unknown();
6145
+ return z7.z.array(itemSchema);
5932
6146
  }
5933
6147
  case "string":
5934
- return z6.z.string();
6148
+ return z7.z.string();
5935
6149
  case "number":
5936
6150
  case "integer":
5937
- return z6.z.number();
6151
+ return z7.z.number();
5938
6152
  case "boolean":
5939
- return z6.z.boolean();
6153
+ return z7.z.boolean();
5940
6154
  case "null":
5941
- return z6.z.null();
6155
+ return z7.z.null();
5942
6156
  default:
5943
6157
  logger12.warn(
5944
6158
  {
@@ -5947,7 +6161,7 @@ function jsonSchemaToZod(jsonSchema) {
5947
6161
  },
5948
6162
  "Unsupported JSON schema type, using unknown validation"
5949
6163
  );
5950
- return z6.z.unknown();
6164
+ return z7.z.unknown();
5951
6165
  }
5952
6166
  }
5953
6167
 
@@ -6180,9 +6394,9 @@ var _ArtifactReferenceSchema = class _ArtifactReferenceSchema {
6180
6394
  * Get the standard Zod schema for artifact reference components
6181
6395
  */
6182
6396
  static getSchema() {
6183
- return z6.z.object({
6184
- id: z6.z.string(),
6185
- name: z6.z.literal("Artifact"),
6397
+ return z7.z.object({
6398
+ id: z7.z.string(),
6399
+ name: z7.z.literal("Artifact"),
6186
6400
  props: jsonSchemaToZod(_ArtifactReferenceSchema.ARTIFACT_PROPS_SCHEMA)
6187
6401
  });
6188
6402
  }
@@ -6249,9 +6463,9 @@ var ArtifactCreateSchema = class {
6249
6463
  },
6250
6464
  required: ["id", "tool_call_id", "type", "base_selector"]
6251
6465
  };
6252
- return z6.z.object({
6253
- id: z6.z.string(),
6254
- name: z6.z.literal(`ArtifactCreate_${component.name}`),
6466
+ return z7.z.object({
6467
+ id: z7.z.string(),
6468
+ name: z7.z.literal(`ArtifactCreate_${component.name}`),
6255
6469
  props: jsonSchemaToZod(propsSchema)
6256
6470
  });
6257
6471
  });
@@ -6923,29 +7137,102 @@ var A2AClient = class {
6923
7137
  };
6924
7138
 
6925
7139
  // src/agents/relationTools.ts
7140
+ init_execution_limits();
6926
7141
  init_conversations();
6927
7142
  init_dbClient();
6928
7143
  init_logger();
6929
7144
  var logger14 = agentsCore.getLogger("relationships Tools");
7145
+ var A2A_RETRY_STATUS_CODES = ["429", "500", "502", "503", "504"];
6930
7146
  var generateTransferToolDescription = (config) => {
6931
- return `Hand off the conversation to agent ${config.id}.
7147
+ let toolsSection = "";
7148
+ let transferSection = "";
7149
+ if (config.transferRelations && config.transferRelations.length > 0) {
7150
+ const transferList = config.transferRelations.map(
7151
+ (transfer) => ` - ${transfer.name || transfer.id}: ${transfer.description || "No description available"}`
7152
+ ).join("\n");
7153
+ transferSection = `
7154
+
7155
+ Can Transfer To:
7156
+ ${transferList}`;
7157
+ }
7158
+ let delegateSection = "";
7159
+ if (config.delegateRelations && config.delegateRelations.length > 0) {
7160
+ const delegateList = config.delegateRelations.map(
7161
+ (delegate) => ` - ${delegate.config.name || delegate.config.id}: ${delegate.config.description || "No description available"} (${delegate.type})`
7162
+ ).join("\n");
7163
+ delegateSection = `
7164
+
7165
+ Can Delegate To:
7166
+ ${delegateList}`;
7167
+ }
7168
+ if (config.tools && config.tools.length > 0) {
7169
+ const toolDescriptions = config.tools.map((tool3) => {
7170
+ const toolsList = tool3.availableTools?.map((t) => ` - ${t.name}: ${t.description || "No description available"}`).join("\n") || "";
7171
+ return `MCP Server: ${tool3.name}
7172
+ ${toolsList}`;
7173
+ }).join("\n\n");
7174
+ toolsSection = `
7175
+
7176
+ Available Tools & Capabilities:
7177
+ ${toolDescriptions}`;
7178
+ }
7179
+ const finalDescription = `Hand off the conversation to agent ${config.id}.
6932
7180
 
6933
7181
  Agent Information:
6934
7182
  - ID: ${config.id}
6935
7183
  - Name: ${config.name ?? "No name provided"}
6936
- - Description: ${config.description ?? "No description provided"}
7184
+ - Description: ${config.description ?? "No description provided"}${toolsSection}${transferSection}${delegateSection}
6937
7185
 
6938
7186
  Hand off the conversation to agent ${config.id} when the user's request would be better handled by this specialized agent.`;
7187
+ return finalDescription;
6939
7188
  };
6940
- var generateDelegateToolDescription = (config) => {
6941
- return `Delegate a specific task to another agent.
7189
+ var generateDelegateToolDescription = (delegateRelation) => {
7190
+ const config = delegateRelation.config;
7191
+ let toolsSection = "";
7192
+ let transferSection = "";
7193
+ let delegateSection = "";
7194
+ if (delegateRelation.type === "internal" && "tools" in config) {
7195
+ const agentConfig = config;
7196
+ if (agentConfig.tools && agentConfig.tools.length > 0) {
7197
+ const toolDescriptions = agentConfig.tools.map((tool3) => {
7198
+ const toolsList = tool3.availableTools?.map((t) => ` - ${t.name}: ${t.description || "No description available"}`).join("\n") || "";
7199
+ return `MCP Server: ${tool3.name}
7200
+ ${toolsList}`;
7201
+ }).join("\n\n");
7202
+ toolsSection = `
7203
+
7204
+ Available Tools & Capabilities:
7205
+ ${toolDescriptions}`;
7206
+ }
7207
+ if (agentConfig.transferRelations && agentConfig.transferRelations.length > 0) {
7208
+ const transferList = agentConfig.transferRelations.map(
7209
+ (transfer) => ` - ${transfer.name || transfer.id}: ${transfer.description || "No description available"}`
7210
+ ).join("\n");
7211
+ transferSection = `
7212
+
7213
+ Can Transfer To:
7214
+ ${transferList}`;
7215
+ }
7216
+ if (agentConfig.delegateRelations && agentConfig.delegateRelations.length > 0) {
7217
+ const delegateList = agentConfig.delegateRelations.map(
7218
+ (delegate) => ` - ${delegate.config.name || delegate.config.id}: ${delegate.config.description || "No description available"} (${delegate.type})`
7219
+ ).join("\n");
7220
+ delegateSection = `
7221
+
7222
+ Can Delegate To:
7223
+ ${delegateList}`;
7224
+ }
7225
+ }
7226
+ const finalDescription = `Delegate a specific task to another agent.
6942
7227
 
6943
7228
  Agent Information:
6944
7229
  - ID: ${config.id}
6945
7230
  - Name: ${config.name}
6946
7231
  - Description: ${config.description || "No description provided"}
7232
+ - Type: ${delegateRelation.type}${toolsSection}${transferSection}${delegateSection}
6947
7233
 
6948
7234
  Delegate a specific task to agent ${config.id} when it seems like the agent can do relevant work.`;
7235
+ return finalDescription;
6949
7236
  };
6950
7237
  var createTransferToAgentTool = ({
6951
7238
  transferConfig,
@@ -6953,9 +7240,10 @@ var createTransferToAgentTool = ({
6953
7240
  subAgent,
6954
7241
  streamRequestId
6955
7242
  }) => {
7243
+ const toolDescription = generateTransferToolDescription(transferConfig);
6956
7244
  return ai.tool({
6957
- description: generateTransferToolDescription(transferConfig),
6958
- inputSchema: z6__default.default.object({}),
7245
+ description: toolDescription,
7246
+ inputSchema: z7__default.default.object({}),
6959
7247
  execute: async () => {
6960
7248
  const activeSpan = api.trace.getActiveSpan();
6961
7249
  if (activeSpan) {
@@ -7009,8 +7297,8 @@ function createDelegateToAgentTool({
7009
7297
  credentialStoreRegistry
7010
7298
  }) {
7011
7299
  return ai.tool({
7012
- description: generateDelegateToolDescription(delegateConfig.config),
7013
- inputSchema: z6__default.default.object({ message: z6__default.default.string() }),
7300
+ description: generateDelegateToolDescription(delegateConfig),
7301
+ inputSchema: z7__default.default.object({ message: z7__default.default.string() }),
7014
7302
  execute: async (input, context) => {
7015
7303
  const delegationId = `del_${agentsCore.generateId()}`;
7016
7304
  const activeSpan = api.trace.getActiveSpan();
@@ -7107,13 +7395,12 @@ function createDelegateToAgentTool({
7107
7395
  retryConfig: {
7108
7396
  strategy: "backoff",
7109
7397
  retryConnectionErrors: true,
7110
- statusCodes: ["429", "500", "502", "503", "504"],
7398
+ statusCodes: [...A2A_RETRY_STATUS_CODES],
7111
7399
  backoff: {
7112
- initialInterval: 100,
7113
- maxInterval: 1e4,
7114
- exponent: 2,
7115
- maxElapsedTime: 2e4
7116
- // 1 minute max retry time
7400
+ initialInterval: DELEGATION_TOOL_BACKOFF_INITIAL_INTERVAL_MS,
7401
+ maxInterval: DELEGATION_TOOL_BACKOFF_MAX_INTERVAL_MS,
7402
+ exponent: DELEGATION_TOOL_BACKOFF_EXPONENT,
7403
+ maxElapsedTime: DELEGATION_TOOL_BACKOFF_MAX_ELAPSED_TIME_MS
7117
7404
  }
7118
7405
  }
7119
7406
  });
@@ -7266,7 +7553,7 @@ var system_prompt_default = `<system_message>
7266
7553
  - You ARE the user's assistant - there are no other agents, specialists, or experts
7267
7554
  - NEVER say you are connecting them to anyone or anything
7268
7555
  - Continue conversations as if you personally have been handling them the entire time
7269
- - Answer questions directly without any transition phrases or transfer language
7556
+ - Answer questions directly without any transition phrases or transfer language except when transferring to another agent or delegating to another agent
7270
7557
  {{TRANSFER_INSTRUCTIONS}}
7271
7558
  {{DELEGATION_INSTRUCTIONS}}
7272
7559
  </security>
@@ -7274,7 +7561,7 @@ var system_prompt_default = `<system_message>
7274
7561
  <interaction_guidelines>
7275
7562
  - Be helpful, accurate, and professional
7276
7563
  - Use tools when appropriate to provide better assistance
7277
- - Explain your reasoning when using tools
7564
+ - Use tools directly without announcing or explaining what you're doing ("Let me search...", "I'll look for...", etc.)
7278
7565
  - Save important tool results as artifacts when they contain structured data that should be preserved and referenced
7279
7566
  - Ask for clarification when requests are ambiguous
7280
7567
 
@@ -7292,11 +7579,6 @@ var system_prompt_default = `<system_message>
7292
7579
  - NEVER mention delegation occurred: just present the results
7293
7580
  - If delegation returns artifacts, reference them as if you created them
7294
7581
 
7295
- \u{1F6A8} TRANSFER TOOL RULES - CRITICAL:
7296
- - When calling transfer_to_* tools, call the tool IMMEDIATELY without any explanatory text
7297
- - Do NOT explain the transfer, do NOT say "I'll hand this off", do NOT provide reasoning
7298
- - Just call the transfer tool directly when you determine it's needed
7299
- - The tool call is sufficient - no additional text should be generated
7300
7582
  </interaction_guidelines>
7301
7583
 
7302
7584
  {{THINKING_PREPARATION_INSTRUCTIONS}}
@@ -7515,9 +7797,24 @@ var Phase1Config = class _Phase1Config {
7515
7797
  if (!hasTransferRelations) {
7516
7798
  return "";
7517
7799
  }
7518
- return `- You have transfer_to_* tools that seamlessly continue the conversation
7519
- - NEVER announce transfers - just call the tool when needed
7520
- - The conversation continues naturally without any transfer language`;
7800
+ return `You are part of a single unified assistant composed of specialized agents. To the user, you must always appear as one continuous, confident voice.
7801
+
7802
+ You have transfer_to_* tools that seamlessly continue the conversation. When you determine another agent should handle a request: ONLY call the appropriate transfer_to_* tool. Do not provide any substantive answer, limitation, or explanation before transferring. NEVER announce, describe, or apologize for a transfer.
7803
+
7804
+ Do NOT stream any text when transferring - call the transfer tool IMMEDIATELY. Do NOT acknowledge the request, do NOT say "Looking into that...", "Let me search...", "I'll help you find...", or provide ANY explanatory text. Place all reasoning or handoff details inside the transfer tool call, not in the user message. The tool call is sufficient - no additional text should be generated.
7805
+
7806
+ CRITICAL: When you receive a user message that ends with "Please continue from where this conversation was left off" - this indicates you are continuing a conversation that another agent started. You should:
7807
+ - Review the conversation history to see what was already communicated to the user
7808
+ - Continue seamlessly from where the previous response left off
7809
+ - Do NOT repeat what was already said in the conversation history
7810
+ - Do NOT announce what you're about to do ("Let me search...", "I'll look for...", etc.)
7811
+ - Proceed directly with the appropriate tool or action
7812
+ - Act as if you have been handling the conversation from the beginning
7813
+
7814
+ When receiving any transfer, act as if you have been engaged from the start. Continue the same tone, context, and style. Never reference other agents, tools, or roles.
7815
+
7816
+ Your goal: preserve the illusion of a single, seamless, intelligent assistant. All user-facing behavior must feel like one continuous conversation, regardless of internal transfers.
7817
+ `;
7521
7818
  }
7522
7819
  generateDelegationInstructions(hasDelegateRelations) {
7523
7820
  if (!hasDelegateRelations) {
@@ -8278,12 +8575,6 @@ function hasToolCallWithPrefix(prefix) {
8278
8575
  };
8279
8576
  }
8280
8577
  var logger19 = agentsCore.getLogger("Agent");
8281
- var CONSTANTS = {
8282
- MAX_GENERATION_STEPS: 12,
8283
- PHASE_1_TIMEOUT_MS: 27e4,
8284
- NON_STREAMING_PHASE_1_TIMEOUT_MS: 9e4,
8285
- PHASE_2_TIMEOUT_MS: 9e4
8286
- };
8287
8578
  function validateModel(modelString, modelType) {
8288
8579
  if (!modelString?.trim()) {
8289
8580
  throw new Error(
@@ -8352,10 +8643,10 @@ var Agent = class {
8352
8643
  }
8353
8644
  /**
8354
8645
  * Get the maximum number of generation steps for this agent
8355
- * Uses agent's stopWhen.stepCountIs config or defaults to CONSTANTS.MAX_GENERATION_STEPS
8646
+ * Uses agent's stopWhen.stepCountIs config or defaults to AGENT_EXECUTION_MAX_GENERATION_STEPS
8356
8647
  */
8357
8648
  getMaxGenerationSteps() {
8358
- return this.config.stopWhen?.stepCountIs ?? CONSTANTS.MAX_GENERATION_STEPS;
8649
+ return this.config.stopWhen?.stepCountIs ?? AGENT_EXECUTION_MAX_GENERATION_STEPS;
8359
8650
  }
8360
8651
  /**
8361
8652
  * Sanitizes tool names at runtime for AI SDK compatibility.
@@ -8911,8 +9202,8 @@ var Agent = class {
8911
9202
  const defaultSandboxConfig = {
8912
9203
  provider: "native",
8913
9204
  runtime: "node22",
8914
- timeout: 3e4,
8915
- vcpus: 4
9205
+ timeout: FUNCTION_TOOL_EXECUTION_TIMEOUT_MS_DEFAULT,
9206
+ vcpus: FUNCTION_TOOL_SANDBOX_VCPUS_DEFAULT
8916
9207
  };
8917
9208
  const result = await sandboxExecutor.executeFunctionTool(functionToolDef.id, args, {
8918
9209
  description: functionToolDef.description || functionToolDef.name,
@@ -9213,9 +9504,9 @@ var Agent = class {
9213
9504
  getArtifactTools() {
9214
9505
  return ai.tool({
9215
9506
  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.",
9216
- inputSchema: z6.z.object({
9217
- artifactId: z6.z.string().describe("The unique identifier of the artifact to get."),
9218
- toolCallId: z6.z.string().describe("The tool call ID associated with this artifact.")
9507
+ inputSchema: z7.z.object({
9508
+ artifactId: z7.z.string().describe("The unique identifier of the artifact to get."),
9509
+ toolCallId: z7.z.string().describe("The tool call ID associated with this artifact.")
9219
9510
  }),
9220
9511
  execute: async ({ artifactId, toolCallId }) => {
9221
9512
  logger19.info({ artifactId, toolCallId }, "get_artifact_full executed");
@@ -9242,9 +9533,9 @@ var Agent = class {
9242
9533
  createThinkingCompleteTool() {
9243
9534
  return ai.tool({
9244
9535
  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.",
9245
- inputSchema: z6.z.object({
9246
- complete: z6.z.boolean().describe("ALWAYS set to true - marks end of research phase"),
9247
- summary: z6.z.string().describe(
9536
+ inputSchema: z7.z.object({
9537
+ complete: z7.z.boolean().describe("ALWAYS set to true - marks end of research phase"),
9538
+ summary: z7.z.string().describe(
9248
9539
  "Brief summary of what information was gathered and why it is sufficient to answer the user"
9249
9540
  )
9250
9541
  }),
@@ -9517,6 +9808,9 @@ var Agent = class {
9517
9808
  try {
9518
9809
  this.streamRequestId = streamRequestId;
9519
9810
  this.streamHelper = streamRequestId ? getStreamHelper(streamRequestId) : void 0;
9811
+ if (streamRequestId && this.artifactComponents.length > 0) {
9812
+ agentSessionManager.updateArtifactComponents(streamRequestId, this.artifactComponents);
9813
+ }
9520
9814
  const conversationId = runtimeContext?.metadata?.conversationId;
9521
9815
  if (conversationId) {
9522
9816
  this.setConversationId(conversationId);
@@ -9598,15 +9892,14 @@ var Agent = class {
9598
9892
  let textResponse;
9599
9893
  const hasStructuredOutput = this.config.dataComponents && this.config.dataComponents.length > 0;
9600
9894
  const shouldStreamPhase1 = this.getStreamingHelper() && !hasStructuredOutput;
9601
- const MAX_ALLOWED_TIMEOUT_MS = 6e5;
9602
- const configuredTimeout = modelSettings.maxDuration ? Math.min(modelSettings.maxDuration * 1e3, MAX_ALLOWED_TIMEOUT_MS) : shouldStreamPhase1 ? CONSTANTS.PHASE_1_TIMEOUT_MS : CONSTANTS.NON_STREAMING_PHASE_1_TIMEOUT_MS;
9603
- const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
9604
- if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
9895
+ 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;
9896
+ const timeoutMs = Math.min(configuredTimeout, LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS);
9897
+ if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) {
9605
9898
  logger19.warn(
9606
9899
  {
9607
9900
  requestedTimeout: modelSettings.maxDuration * 1e3,
9608
9901
  appliedTimeout: timeoutMs,
9609
- maxAllowed: MAX_ALLOWED_TIMEOUT_MS
9902
+ maxAllowed: LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS
9610
9903
  },
9611
9904
  "Requested timeout exceeded maximum allowed, capping to 10 minutes"
9612
9905
  );
@@ -9882,9 +10175,9 @@ ${output}${structureHintsFormatted}`;
9882
10175
  this.config.dataComponents.forEach((dc) => {
9883
10176
  const propsSchema = jsonSchemaToZod(dc.props);
9884
10177
  componentSchemas.push(
9885
- z6.z.object({
9886
- id: z6.z.string(),
9887
- name: z6.z.literal(dc.name),
10178
+ z7.z.object({
10179
+ id: z7.z.string(),
10180
+ name: z7.z.literal(dc.name),
9888
10181
  props: propsSchema
9889
10182
  })
9890
10183
  );
@@ -9901,14 +10194,32 @@ ${output}${structureHintsFormatted}`;
9901
10194
  if (componentSchemas.length === 1) {
9902
10195
  dataComponentsSchema = componentSchemas[0];
9903
10196
  } else {
9904
- dataComponentsSchema = z6.z.union(
10197
+ dataComponentsSchema = z7.z.union(
9905
10198
  componentSchemas
9906
10199
  );
9907
10200
  }
9908
10201
  const structuredModelSettings = ModelFactory.prepareGenerationConfig(
9909
10202
  this.getStructuredOutputModel()
9910
10203
  );
9911
- const phase2TimeoutMs = structuredModelSettings.maxDuration ? structuredModelSettings.maxDuration * 1e3 : CONSTANTS.PHASE_2_TIMEOUT_MS;
10204
+ const configuredPhase2Timeout = structuredModelSettings.maxDuration ? Math.min(
10205
+ structuredModelSettings.maxDuration * 1e3,
10206
+ LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS
10207
+ ) : LLM_GENERATION_SUBSEQUENT_CALL_TIMEOUT_MS;
10208
+ const phase2TimeoutMs = Math.min(
10209
+ configuredPhase2Timeout,
10210
+ LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS
10211
+ );
10212
+ if (structuredModelSettings.maxDuration && structuredModelSettings.maxDuration * 1e3 > LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS) {
10213
+ logger19.warn(
10214
+ {
10215
+ requestedTimeout: structuredModelSettings.maxDuration * 1e3,
10216
+ appliedTimeout: phase2TimeoutMs,
10217
+ maxAllowed: LLM_GENERATION_MAX_ALLOWED_TIMEOUT_MS,
10218
+ phase: "structured_generation"
10219
+ },
10220
+ "Phase 2 requested timeout exceeded maximum allowed, capping to 10 minutes"
10221
+ );
10222
+ }
9912
10223
  const shouldStreamPhase2 = this.getStreamingHelper();
9913
10224
  if (shouldStreamPhase2) {
9914
10225
  const phase2Messages = [
@@ -9925,8 +10236,8 @@ ${output}${structureHintsFormatted}`;
9925
10236
  const streamResult = ai.streamObject({
9926
10237
  ...structuredModelSettings,
9927
10238
  messages: phase2Messages,
9928
- schema: z6.z.object({
9929
- dataComponents: z6.z.array(dataComponentsSchema)
10239
+ schema: z7.z.object({
10240
+ dataComponents: z7.z.array(dataComponentsSchema)
9930
10241
  }),
9931
10242
  experimental_telemetry: {
9932
10243
  isEnabled: true,
@@ -9996,8 +10307,8 @@ ${output}${structureHintsFormatted}`;
9996
10307
  withJsonPostProcessing2({
9997
10308
  ...structuredModelSettings,
9998
10309
  messages: phase2Messages,
9999
- schema: z6.z.object({
10000
- dataComponents: z6.z.array(dataComponentsSchema)
10310
+ schema: z7.z.object({
10311
+ dataComponents: z7.z.array(dataComponentsSchema)
10001
10312
  }),
10002
10313
  experimental_telemetry: {
10003
10314
  isEnabled: true,
@@ -10264,9 +10575,14 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10264
10575
  const models = "models" in config.agentSchema ? config.agentSchema.models : void 0;
10265
10576
  const stopWhen = "stopWhen" in config.agentSchema ? config.agentSchema.stopWhen : void 0;
10266
10577
  const toolsForAgentResult = await Promise.all(
10267
- toolsForAgent.data.map(
10268
- async (item) => await agentsCore.dbResultToMcpTool(item.tool, dbClient_default, credentialStoreRegistry)
10269
- )
10578
+ toolsForAgent.data.map(async (item) => {
10579
+ const mcpTool = await agentsCore.dbResultToMcpTool(item.tool, dbClient_default, credentialStoreRegistry);
10580
+ if (item.selectedTools && item.selectedTools.length > 0) {
10581
+ const selectedToolsSet = new Set(item.selectedTools);
10582
+ mcpTool.availableTools = mcpTool.availableTools?.filter((tool3) => selectedToolsSet.has(tool3.name)) || [];
10583
+ }
10584
+ return mcpTool;
10585
+ })
10270
10586
  ) ?? [];
10271
10587
  const agent = new Agent(
10272
10588
  {
@@ -10295,20 +10611,112 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10295
10611
  subAgentRelations: [],
10296
10612
  transferRelations: []
10297
10613
  })),
10298
- transferRelations: enhancedInternalRelations.filter((relation) => relation.relationType === "transfer").map((relation) => ({
10299
- baseUrl: config.baseUrl,
10300
- apiKey: config.apiKey,
10301
- id: relation.id,
10302
- tenantId: config.tenantId,
10303
- projectId: config.projectId,
10304
- agentId: config.agentId,
10305
- name: relation.name,
10306
- description: relation.description,
10307
- prompt: "",
10308
- delegateRelations: [],
10309
- subAgentRelations: [],
10310
- transferRelations: []
10311
- })),
10614
+ transferRelations: await Promise.all(
10615
+ enhancedInternalRelations.filter((relation) => relation.relationType === "transfer").map(async (relation) => {
10616
+ const targetToolsForAgent = await agentsCore.getToolsForAgent(dbClient_default)({
10617
+ scopes: {
10618
+ tenantId: config.tenantId,
10619
+ projectId: config.projectId,
10620
+ agentId: config.agentId,
10621
+ subAgentId: relation.id
10622
+ }
10623
+ });
10624
+ let targetTransferRelations = { data: [] };
10625
+ let targetDelegateRelations = { data: [] };
10626
+ try {
10627
+ const [transferRel, delegateRel] = await Promise.all([
10628
+ agentsCore.getRelatedAgentsForAgent(dbClient_default)({
10629
+ scopes: {
10630
+ tenantId: config.tenantId,
10631
+ projectId: config.projectId,
10632
+ agentId: config.agentId
10633
+ },
10634
+ subAgentId: relation.id
10635
+ }),
10636
+ agentsCore.getExternalAgentsForSubAgent(dbClient_default)({
10637
+ scopes: {
10638
+ tenantId: config.tenantId,
10639
+ projectId: config.projectId,
10640
+ agentId: config.agentId,
10641
+ subAgentId: relation.id
10642
+ }
10643
+ })
10644
+ ]);
10645
+ targetTransferRelations = transferRel;
10646
+ targetDelegateRelations = delegateRel;
10647
+ } catch (err) {
10648
+ logger20.info(
10649
+ {
10650
+ agentId: relation.id,
10651
+ error: err?.message || "Unknown error"
10652
+ },
10653
+ "Could not fetch relations for target agent (likely external/team agent), using basic info only"
10654
+ );
10655
+ }
10656
+ const targetAgentTools = await Promise.all(
10657
+ targetToolsForAgent.data.map(async (item) => {
10658
+ const mcpTool = await agentsCore.dbResultToMcpTool(
10659
+ item.tool,
10660
+ dbClient_default,
10661
+ credentialStoreRegistry
10662
+ );
10663
+ if (item.selectedTools && item.selectedTools.length > 0) {
10664
+ const selectedToolsSet = new Set(item.selectedTools);
10665
+ mcpTool.availableTools = mcpTool.availableTools?.filter(
10666
+ (tool3) => selectedToolsSet.has(tool3.name)
10667
+ ) || [];
10668
+ }
10669
+ return mcpTool;
10670
+ })
10671
+ ) ?? [];
10672
+ const targetTransferRelationsConfig = targetTransferRelations.data.filter((rel) => rel.relationType === "transfer").map((rel) => ({
10673
+ baseUrl: config.baseUrl,
10674
+ apiKey: config.apiKey,
10675
+ id: rel.id,
10676
+ tenantId: config.tenantId,
10677
+ projectId: config.projectId,
10678
+ agentId: config.agentId,
10679
+ name: rel.name,
10680
+ description: rel.description,
10681
+ prompt: "",
10682
+ delegateRelations: [],
10683
+ subAgentRelations: [],
10684
+ transferRelations: []
10685
+ // Note: Not including tools for nested relations to avoid infinite recursion
10686
+ }));
10687
+ const targetDelegateRelationsConfig = targetDelegateRelations.data.map(
10688
+ (rel) => ({
10689
+ type: "external",
10690
+ config: {
10691
+ id: rel.externalAgent.id,
10692
+ name: rel.externalAgent.name,
10693
+ description: rel.externalAgent.description || "",
10694
+ baseUrl: rel.externalAgent.baseUrl,
10695
+ headers: rel.headers,
10696
+ credentialReferenceId: rel.externalAgent.credentialReferenceId,
10697
+ relationId: rel.id,
10698
+ relationType: "delegate"
10699
+ }
10700
+ })
10701
+ );
10702
+ return {
10703
+ baseUrl: config.baseUrl,
10704
+ apiKey: config.apiKey,
10705
+ id: relation.id,
10706
+ tenantId: config.tenantId,
10707
+ projectId: config.projectId,
10708
+ agentId: config.agentId,
10709
+ name: relation.name,
10710
+ description: relation.description,
10711
+ prompt: "",
10712
+ delegateRelations: targetDelegateRelationsConfig,
10713
+ subAgentRelations: [],
10714
+ transferRelations: targetTransferRelationsConfig,
10715
+ tools: targetAgentTools
10716
+ // Include target agent's tools for transfer descriptions
10717
+ };
10718
+ })
10719
+ ),
10312
10720
  delegateRelations: [
10313
10721
  ...enhancedInternalRelations.filter((relation) => relation.relationType === "delegate").map((relation) => ({
10314
10722
  type: "internal",
@@ -10323,8 +10731,11 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
10323
10731
  description: relation.description,
10324
10732
  prompt: "",
10325
10733
  delegateRelations: [],
10734
+ // Simplified - no nested relations
10326
10735
  subAgentRelations: [],
10327
- transferRelations: []
10736
+ transferRelations: [],
10737
+ tools: []
10738
+ // Tools are defined in config files, not DB
10328
10739
  }
10329
10740
  })),
10330
10741
  ...externalRelations.data.map((relation) => ({
@@ -10729,14 +11140,14 @@ app.openapi(
10729
11140
  description: "Agent Card for A2A discovery",
10730
11141
  content: {
10731
11142
  "application/json": {
10732
- schema: z6.z.object({
10733
- name: z6.z.string(),
10734
- description: z6.z.string().optional(),
10735
- url: z6.z.string(),
10736
- version: z6.z.string(),
10737
- defaultInputModes: z6.z.array(z6.z.string()),
10738
- defaultOutputModes: z6.z.array(z6.z.string()),
10739
- skills: z6.z.array(z6.z.any())
11143
+ schema: z7.z.object({
11144
+ name: z7.z.string(),
11145
+ description: z7.z.string().optional(),
11146
+ url: z7.z.string(),
11147
+ version: z7.z.string(),
11148
+ defaultInputModes: z7.z.array(z7.z.string()),
11149
+ defaultOutputModes: z7.z.array(z7.z.string()),
11150
+ skills: z7.z.array(z7.z.any())
10740
11151
  })
10741
11152
  }
10742
11153
  }
@@ -10983,8 +11394,12 @@ async function executeTransfer({
10983
11394
  }
10984
11395
 
10985
11396
  // src/handlers/executionHandler.ts
11397
+ init_execution_limits();
10986
11398
  init_dbClient();
10987
11399
  init_logger();
11400
+
11401
+ // src/utils/stream-helpers.ts
11402
+ init_execution_limits();
10988
11403
  var SSEStreamHelper = class {
10989
11404
  constructor(stream2, requestId2, timestamp) {
10990
11405
  this.stream = stream2;
@@ -11157,7 +11572,6 @@ function createSSEStreamHelper(stream2, requestId2, timestamp) {
11157
11572
  return new SSEStreamHelper(stream2, requestId2, timestamp);
11158
11573
  }
11159
11574
  var _VercelDataStreamHelper = class _VercelDataStreamHelper {
11160
- // 10 minutes max lifetime
11161
11575
  constructor(writer) {
11162
11576
  this.writer = writer;
11163
11577
  __publicField(this, "textId", null);
@@ -11167,18 +11581,14 @@ var _VercelDataStreamHelper = class _VercelDataStreamHelper {
11167
11581
  __publicField(this, "completedItems", /* @__PURE__ */ new Set());
11168
11582
  // Track completed items
11169
11583
  __publicField(this, "sessionId");
11170
- // 5MB limit (more generous during request)
11171
11584
  __publicField(this, "isCompleted", false);
11172
11585
  __publicField(this, "isTextStreaming", false);
11173
11586
  __publicField(this, "queuedEvents", []);
11174
11587
  __publicField(this, "lastTextEndTimestamp", 0);
11175
- __publicField(this, "TEXT_GAP_THRESHOLD", 2e3);
11176
- // milliseconds - if gap between text sequences is less than this, queue operations
11177
11588
  __publicField(this, "connectionDropTimer");
11178
- __publicField(this, "MAX_LIFETIME_MS", 6e5);
11179
11589
  this.connectionDropTimer = setTimeout(() => {
11180
11590
  this.forceCleanup("Connection lifetime exceeded");
11181
- }, this.MAX_LIFETIME_MS);
11591
+ }, STREAM_MAX_LIFETIME_MS);
11182
11592
  }
11183
11593
  setSessionId(sessionId) {
11184
11594
  this.sessionId = sessionId;
@@ -11232,7 +11642,7 @@ var _VercelDataStreamHelper = class _VercelDataStreamHelper {
11232
11642
  const id = this.textId;
11233
11643
  const startTime = Date.now();
11234
11644
  const gapFromLastSequence = this.lastTextEndTimestamp > 0 ? startTime - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
11235
- if (gapFromLastSequence >= this.TEXT_GAP_THRESHOLD) {
11645
+ if (gapFromLastSequence >= STREAM_TEXT_GAP_THRESHOLD_MS) {
11236
11646
  await this.flushQueuedOperations();
11237
11647
  }
11238
11648
  this.isTextStreaming = true;
@@ -11266,7 +11676,7 @@ var _VercelDataStreamHelper = class _VercelDataStreamHelper {
11266
11676
  if (type === "data-artifact") {
11267
11677
  const now = Date.now();
11268
11678
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
11269
- if (this.isTextStreaming || gapFromLastTextEnd < this.TEXT_GAP_THRESHOLD) {
11679
+ if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
11270
11680
  this.writer.write({
11271
11681
  type: `${type}`,
11272
11682
  data
@@ -11419,7 +11829,7 @@ var _VercelDataStreamHelper = class _VercelDataStreamHelper {
11419
11829
  }
11420
11830
  const now = Date.now();
11421
11831
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
11422
- if (this.isTextStreaming || gapFromLastTextEnd < this.TEXT_GAP_THRESHOLD) {
11832
+ if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
11423
11833
  this.queuedEvents.push({ type: "data-summary", event: summary });
11424
11834
  return;
11425
11835
  }
@@ -11437,7 +11847,7 @@ var _VercelDataStreamHelper = class _VercelDataStreamHelper {
11437
11847
  }
11438
11848
  const now = Date.now();
11439
11849
  const gapFromLastTextEnd = this.lastTextEndTimestamp > 0 ? now - this.lastTextEndTimestamp : Number.MAX_SAFE_INTEGER;
11440
- if (this.isTextStreaming || gapFromLastTextEnd < this.TEXT_GAP_THRESHOLD) {
11850
+ if (this.isTextStreaming || gapFromLastTextEnd < STREAM_TEXT_GAP_THRESHOLD_MS) {
11441
11851
  this.queuedEvents.push({ type: "data-operation", event: operation });
11442
11852
  return;
11443
11853
  }
@@ -11480,7 +11890,7 @@ var _VercelDataStreamHelper = class _VercelDataStreamHelper {
11480
11890
  this.cleanup();
11481
11891
  }
11482
11892
  };
11483
- __publicField(_VercelDataStreamHelper, "MAX_BUFFER_SIZE", 5 * 1024 * 1024);
11893
+ __publicField(_VercelDataStreamHelper, "MAX_BUFFER_SIZE", STREAM_BUFFER_MAX_SIZE_BYTES);
11484
11894
  var VercelDataStreamHelper = _VercelDataStreamHelper;
11485
11895
  function createVercelStreamHelper(writer) {
11486
11896
  return new VercelDataStreamHelper(writer);
@@ -11552,7 +11962,7 @@ var createMCPStreamHelper = createBufferingStreamHelper;
11552
11962
  var logger24 = agentsCore.getLogger("ExecutionHandler");
11553
11963
  var ExecutionHandler = class {
11554
11964
  constructor() {
11555
- __publicField(this, "MAX_ERRORS", 3);
11965
+ __publicField(this, "MAX_ERRORS", AGENT_EXECUTION_MAX_CONSECUTIVE_ERRORS);
11556
11966
  }
11557
11967
  /**
11558
11968
  * performs exeuction loop
@@ -11649,7 +12059,7 @@ var ExecutionHandler = class {
11649
12059
  "Task created with metadata"
11650
12060
  );
11651
12061
  } catch (error) {
11652
- if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
12062
+ if (error?.cause?.code === "23505") {
11653
12063
  logger24.info(
11654
12064
  { taskId, error: error.message },
11655
12065
  "Task already exists, fetching existing task"
@@ -11672,7 +12082,7 @@ var ExecutionHandler = class {
11672
12082
  }
11673
12083
  logger24.debug(
11674
12084
  {
11675
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12085
+ timestamp: /* @__PURE__ */ new Date(),
11676
12086
  executionType: "create_initial_task",
11677
12087
  conversationId,
11678
12088
  agentId,
@@ -11686,7 +12096,7 @@ var ExecutionHandler = class {
11686
12096
  );
11687
12097
  if (Array.isArray(task)) task = task[0];
11688
12098
  let currentMessage = userMessage;
11689
- const maxTransfers = agentConfig?.stopWhen?.transferCountIs ?? 10;
12099
+ const maxTransfers = agentConfig?.stopWhen?.transferCountIs ?? agentsCore.AGENT_EXECUTION_TRANSFER_COUNT_DEFAULT;
11690
12100
  while (iterations < maxTransfers) {
11691
12101
  iterations++;
11692
12102
  logger24.info(
@@ -11781,7 +12191,27 @@ var ExecutionHandler = class {
11781
12191
  const firstArtifact = messageResponse.result.artifacts[0];
11782
12192
  const transferReason = firstArtifact?.parts[1]?.kind === "text" ? firstArtifact.parts[1].text : "Transfer initiated";
11783
12193
  logger24.info({ targetSubAgentId, transferReason, transferFromAgent }, "Transfer response");
11784
- currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
12194
+ await agentsCore.createMessage(dbClient_default)({
12195
+ id: agentsCore.generateId(),
12196
+ tenantId,
12197
+ projectId,
12198
+ conversationId,
12199
+ role: "agent",
12200
+ content: {
12201
+ text: transferReason,
12202
+ parts: [
12203
+ {
12204
+ kind: "text",
12205
+ text: transferReason
12206
+ }
12207
+ ]
12208
+ },
12209
+ visibility: "user-facing",
12210
+ messageType: "chat",
12211
+ fromSubAgentId: currentAgentId,
12212
+ taskId: task.id
12213
+ });
12214
+ currentMessage = currentMessage + "\n\nPlease continue this conversation seamlessly. The previous response in conversation history was from another internal agent, but you must continue as if YOU made that response. All responses must appear as one unified agent - do not repeat what was already communicated.";
11785
12215
  const { success, targetSubAgentId: newAgentId } = await executeTransfer({
11786
12216
  projectId,
11787
12217
  tenantId,
@@ -11865,7 +12295,7 @@ var ExecutionHandler = class {
11865
12295
  status: "completed",
11866
12296
  metadata: {
11867
12297
  ...task.metadata,
11868
- completed_at: (/* @__PURE__ */ new Date()).toISOString(),
12298
+ completed_at: /* @__PURE__ */ new Date(),
11869
12299
  response: {
11870
12300
  text: textContent,
11871
12301
  parts: responseParts,
@@ -11917,7 +12347,7 @@ var ExecutionHandler = class {
11917
12347
  status: "failed",
11918
12348
  metadata: {
11919
12349
  ...task.metadata,
11920
- failed_at: (/* @__PURE__ */ new Date()).toISOString(),
12350
+ failed_at: /* @__PURE__ */ new Date(),
11921
12351
  error: errorMessage2
11922
12352
  }
11923
12353
  }
@@ -11938,7 +12368,7 @@ var ExecutionHandler = class {
11938
12368
  status: "failed",
11939
12369
  metadata: {
11940
12370
  ...task.metadata,
11941
- failed_at: (/* @__PURE__ */ new Date()).toISOString(),
12371
+ failed_at: /* @__PURE__ */ new Date(),
11942
12372
  error: errorMessage
11943
12373
  }
11944
12374
  }
@@ -11960,7 +12390,7 @@ var ExecutionHandler = class {
11960
12390
  status: "failed",
11961
12391
  metadata: {
11962
12392
  ...task.metadata,
11963
- failed_at: (/* @__PURE__ */ new Date()).toISOString(),
12393
+ failed_at: /* @__PURE__ */ new Date(),
11964
12394
  error: errorMessage
11965
12395
  }
11966
12396
  }
@@ -11988,36 +12418,36 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
11988
12418
  body: {
11989
12419
  content: {
11990
12420
  "application/json": {
11991
- schema: z6.z.object({
11992
- model: z6.z.string().describe("The model to use for the completion"),
11993
- messages: z6.z.array(
11994
- z6.z.object({
11995
- role: z6.z.enum(["system", "user", "assistant", "function", "tool"]).describe("The role of the message"),
11996
- content: z6.z.union([
11997
- z6.z.string(),
11998
- z6.z.array(
11999
- z6.z.strictObject({
12000
- type: z6.z.string(),
12001
- text: z6.z.string().optional()
12421
+ schema: z7.z.object({
12422
+ model: z7.z.string().describe("The model to use for the completion"),
12423
+ messages: z7.z.array(
12424
+ z7.z.object({
12425
+ role: z7.z.enum(["system", "user", "assistant", "function", "tool"]).describe("The role of the message"),
12426
+ content: z7.z.union([
12427
+ z7.z.string(),
12428
+ z7.z.array(
12429
+ z7.z.strictObject({
12430
+ type: z7.z.string(),
12431
+ text: z7.z.string().optional()
12002
12432
  })
12003
12433
  )
12004
12434
  ]).describe("The message content"),
12005
- name: z6.z.string().optional().describe("The name of the message sender")
12435
+ name: z7.z.string().optional().describe("The name of the message sender")
12006
12436
  })
12007
12437
  ).describe("The conversation messages"),
12008
- temperature: z6.z.number().optional().describe("Controls randomness (0-1)"),
12009
- top_p: z6.z.number().optional().describe("Controls nucleus sampling"),
12010
- n: z6.z.number().optional().describe("Number of completions to generate"),
12011
- stream: z6.z.boolean().optional().describe("Whether to stream the response"),
12012
- max_tokens: z6.z.number().optional().describe("Maximum tokens to generate"),
12013
- presence_penalty: z6.z.number().optional().describe("Presence penalty (-2 to 2)"),
12014
- frequency_penalty: z6.z.number().optional().describe("Frequency penalty (-2 to 2)"),
12015
- logit_bias: z6.z.record(z6.z.string(), z6.z.number()).optional().describe("Token logit bias"),
12016
- user: z6.z.string().optional().describe("User identifier"),
12017
- conversationId: z6.z.string().optional().describe("Conversation ID for multi-turn chat"),
12018
- tools: z6.z.array(z6.z.string()).optional().describe("Available tools"),
12019
- runConfig: z6.z.record(z6.z.string(), z6.z.unknown()).optional().describe("Run configuration"),
12020
- headers: z6.z.record(z6.z.string(), z6.z.unknown()).optional().describe(
12438
+ temperature: z7.z.number().optional().describe("Controls randomness (0-1)"),
12439
+ top_p: z7.z.number().optional().describe("Controls nucleus sampling"),
12440
+ n: z7.z.number().optional().describe("Number of completions to generate"),
12441
+ stream: z7.z.boolean().optional().describe("Whether to stream the response"),
12442
+ max_tokens: z7.z.number().optional().describe("Maximum tokens to generate"),
12443
+ presence_penalty: z7.z.number().optional().describe("Presence penalty (-2 to 2)"),
12444
+ frequency_penalty: z7.z.number().optional().describe("Frequency penalty (-2 to 2)"),
12445
+ logit_bias: z7.z.record(z7.z.string(), z7.z.number()).optional().describe("Token logit bias"),
12446
+ user: z7.z.string().optional().describe("User identifier"),
12447
+ conversationId: z7.z.string().optional().describe("Conversation ID for multi-turn chat"),
12448
+ tools: z7.z.array(z7.z.string()).optional().describe("Available tools"),
12449
+ runConfig: z7.z.record(z7.z.string(), z7.z.unknown()).optional().describe("Run configuration"),
12450
+ headers: z7.z.record(z7.z.string(), z7.z.unknown()).optional().describe(
12021
12451
  "Headers data for template processing (validated against context config schema)"
12022
12452
  )
12023
12453
  })
@@ -12028,14 +12458,14 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
12028
12458
  responses: {
12029
12459
  200: {
12030
12460
  description: "Streaming chat completion response in Server-Sent Events format",
12031
- headers: z6.z.object({
12032
- "Content-Type": z6.z.string().default("text/event-stream"),
12033
- "Cache-Control": z6.z.string().default("no-cache"),
12034
- Connection: z6.z.string().default("keep-alive")
12461
+ headers: z7.z.object({
12462
+ "Content-Type": z7.z.string().default("text/event-stream"),
12463
+ "Cache-Control": z7.z.string().default("no-cache"),
12464
+ Connection: z7.z.string().default("keep-alive")
12035
12465
  }),
12036
12466
  content: {
12037
12467
  "text/event-stream": {
12038
- schema: z6.z.string().describe("Server-Sent Events stream with chat completion chunks")
12468
+ schema: z7.z.string().describe("Server-Sent Events stream with chat completion chunks")
12039
12469
  }
12040
12470
  }
12041
12471
  },
@@ -12043,13 +12473,13 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
12043
12473
  description: "Invalid request context or parameters",
12044
12474
  content: {
12045
12475
  "application/json": {
12046
- schema: z6.z.object({
12047
- error: z6.z.string(),
12048
- details: z6.z.array(
12049
- z6.z.object({
12050
- field: z6.z.string(),
12051
- message: z6.z.string(),
12052
- value: z6.z.unknown().optional()
12476
+ schema: z7.z.object({
12477
+ error: z7.z.string(),
12478
+ details: z7.z.array(
12479
+ z7.z.object({
12480
+ field: z7.z.string(),
12481
+ message: z7.z.string(),
12482
+ value: z7.z.unknown().optional()
12053
12483
  })
12054
12484
  ).optional()
12055
12485
  })
@@ -12060,8 +12490,8 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
12060
12490
  description: "Agent or agent not found",
12061
12491
  content: {
12062
12492
  "application/json": {
12063
- schema: z6.z.object({
12064
- error: z6.z.string()
12493
+ schema: z7.z.object({
12494
+ error: z7.z.string()
12065
12495
  })
12066
12496
  }
12067
12497
  }
@@ -12070,9 +12500,9 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
12070
12500
  description: "Internal server error",
12071
12501
  content: {
12072
12502
  "application/json": {
12073
- schema: z6.z.object({
12074
- error: z6.z.string(),
12075
- message: z6.z.string()
12503
+ schema: z7.z.object({
12504
+ error: z7.z.string(),
12505
+ message: z7.z.string()
12076
12506
  })
12077
12507
  }
12078
12508
  }
@@ -12784,7 +13214,7 @@ var getServer = async (headers2, executionContext, conversationId, credentialSto
12784
13214
  "send-query-to-agent",
12785
13215
  `Send a query to the ${agent.name} agent. The agent has the following description: ${agent.description}`,
12786
13216
  {
12787
- query: z6.z.string().describe("The query to send to the agent")
13217
+ query: z7.z.string().describe("The query to send to the agent")
12788
13218
  },
12789
13219
  async ({ query }) => {
12790
13220
  try {