@inkeep/agents-run-api 0.15.0 → 0.16.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,8 +3,13 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var agentsCore = require('@inkeep/agents-core');
6
- var z5 = require('zod');
6
+ var z6 = require('zod');
7
7
  var nanoid = require('nanoid');
8
+ var child_process = require('child_process');
9
+ var crypto = require('crypto');
10
+ var fs = require('fs');
11
+ var os = require('os');
12
+ var path = require('path');
8
13
  var otel = require('@hono/otel');
9
14
  var zodOpenapi = require('@hono/zod-openapi');
10
15
  var api = require('@opentelemetry/api');
@@ -31,6 +36,7 @@ var google = require('@ai-sdk/google');
31
36
  var openai = require('@ai-sdk/openai');
32
37
  var aiSdkProvider = require('@openrouter/ai-sdk-provider');
33
38
  var jmespath = require('jmespath');
39
+ var Ajv = require('ajv');
34
40
  var destr = require('destr');
35
41
  var traverse = require('traverse');
36
42
  var mcp_js = require('@modelcontextprotocol/sdk/server/mcp.js');
@@ -40,8 +46,9 @@ var fetchToNode = require('fetch-to-node');
40
46
 
41
47
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
42
48
 
43
- var z5__default = /*#__PURE__*/_interopDefault(z5);
49
+ var z6__default = /*#__PURE__*/_interopDefault(z6);
44
50
  var jmespath__default = /*#__PURE__*/_interopDefault(jmespath);
51
+ var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
45
52
  var destr__default = /*#__PURE__*/_interopDefault(destr);
46
53
  var traverse__default = /*#__PURE__*/_interopDefault(traverse);
47
54
 
@@ -60,27 +67,27 @@ var envSchema, parseEnv, env;
60
67
  var init_env = __esm({
61
68
  "src/env.ts"() {
62
69
  agentsCore.loadEnvironmentFiles();
63
- envSchema = z5.z.object({
64
- NODE_ENV: z5.z.enum(["development", "production", "test"]).optional(),
65
- ENVIRONMENT: z5.z.enum(["development", "production", "pentest", "test"]).optional().default("development"),
66
- DB_FILE_NAME: z5.z.string().optional(),
67
- TURSO_DATABASE_URL: z5.z.string().optional(),
68
- TURSO_AUTH_TOKEN: z5.z.string().optional(),
69
- AGENTS_RUN_API_URL: z5.z.string().optional().default("http://localhost:3003"),
70
- LOG_LEVEL: z5.z.enum(["trace", "debug", "info", "warn", "error"]).optional().default("debug"),
71
- NANGO_SECRET_KEY: z5.z.string().optional(),
72
- OPENAI_API_KEY: z5.z.string().optional(),
73
- ANTHROPIC_API_KEY: z5.z.string(),
74
- INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z5.z.string().optional(),
75
- OTEL_BSP_SCHEDULE_DELAY: z5.z.coerce.number().optional().default(500),
76
- OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z5.z.coerce.number().optional().default(64)
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_SECRET_KEY: z6.z.string().optional(),
79
+ OPENAI_API_KEY: z6.z.string().optional(),
80
+ ANTHROPIC_API_KEY: z6.z.string(),
81
+ INKEEP_AGENTS_RUN_API_BYPASS_SECRET: z6.z.string().optional(),
82
+ OTEL_BSP_SCHEDULE_DELAY: z6.z.coerce.number().optional().default(500),
83
+ OTEL_BSP_MAX_EXPORT_BATCH_SIZE: z6.z.coerce.number().optional().default(64)
77
84
  });
78
85
  parseEnv = () => {
79
86
  try {
80
87
  const parsedEnv = envSchema.parse(process.env);
81
88
  return parsedEnv;
82
89
  } catch (error) {
83
- if (error instanceof z5.z.ZodError) {
90
+ if (error instanceof z6.z.ZodError) {
84
91
  const missingVars = error.issues.map((issue) => issue.path.join("."));
85
92
  throw new Error(
86
93
  `\u274C Invalid environment variables: ${missingVars.join(", ")}
@@ -345,8 +352,8 @@ async function getConversationScopedArtifacts(params) {
345
352
  });
346
353
  referenceArtifacts.push(...artifacts);
347
354
  }
348
- const logger26 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
349
- logger26.debug(
355
+ const logger28 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
356
+ logger28.debug(
350
357
  {
351
358
  conversationId,
352
359
  visibleMessages: visibleMessages.length,
@@ -358,8 +365,8 @@ async function getConversationScopedArtifacts(params) {
358
365
  );
359
366
  return referenceArtifacts;
360
367
  } catch (error) {
361
- const logger26 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
362
- logger26.error(
368
+ const logger28 = (await Promise.resolve().then(() => (init_logger(), logger_exports))).getLogger("conversations");
369
+ logger28.error(
363
370
  {
364
371
  error: error instanceof Error ? error.message : "Unknown error",
365
372
  conversationId
@@ -375,6 +382,326 @@ var init_conversations = __esm({
375
382
  }
376
383
  });
377
384
 
385
+ // src/tools/LocalSandboxExecutor.ts
386
+ var LocalSandboxExecutor_exports = {};
387
+ __export(LocalSandboxExecutor_exports, {
388
+ LocalSandboxExecutor: () => LocalSandboxExecutor
389
+ });
390
+ var logger18, _LocalSandboxExecutor, LocalSandboxExecutor;
391
+ var init_LocalSandboxExecutor = __esm({
392
+ "src/tools/LocalSandboxExecutor.ts"() {
393
+ logger18 = agentsCore.getLogger("local-sandbox-executor");
394
+ _LocalSandboxExecutor = class _LocalSandboxExecutor {
395
+ constructor() {
396
+ __publicField(this, "tempDir");
397
+ __publicField(this, "sandboxPool", {});
398
+ __publicField(this, "POOL_TTL", 5 * 60 * 1e3);
399
+ // 5 minutes
400
+ __publicField(this, "MAX_USE_COUNT", 50);
401
+ this.tempDir = path.join(os.tmpdir(), "inkeep-sandboxes");
402
+ this.ensureTempDir();
403
+ this.startPoolCleanup();
404
+ }
405
+ static getInstance() {
406
+ if (!_LocalSandboxExecutor.instance) {
407
+ _LocalSandboxExecutor.instance = new _LocalSandboxExecutor();
408
+ }
409
+ return _LocalSandboxExecutor.instance;
410
+ }
411
+ ensureTempDir() {
412
+ try {
413
+ fs.mkdirSync(this.tempDir, { recursive: true });
414
+ } catch {
415
+ }
416
+ }
417
+ generateDependencyHash(dependencies) {
418
+ const sortedDeps = Object.keys(dependencies).sort().map((key) => `${key}@${dependencies[key]}`).join(",");
419
+ return crypto.createHash("sha256").update(sortedDeps).digest("hex").substring(0, 16);
420
+ }
421
+ getCachedSandbox(dependencyHash) {
422
+ const poolKey = dependencyHash;
423
+ const sandbox = this.sandboxPool[poolKey];
424
+ if (sandbox && fs.existsSync(sandbox.sandboxDir)) {
425
+ const now = Date.now();
426
+ if (now - sandbox.lastUsed < this.POOL_TTL && sandbox.useCount < this.MAX_USE_COUNT) {
427
+ sandbox.lastUsed = now;
428
+ sandbox.useCount++;
429
+ logger18.debug(
430
+ {
431
+ poolKey,
432
+ useCount: sandbox.useCount,
433
+ sandboxDir: sandbox.sandboxDir,
434
+ lastUsed: new Date(sandbox.lastUsed).toISOString()
435
+ },
436
+ "Reusing cached sandbox"
437
+ );
438
+ return sandbox.sandboxDir;
439
+ } else {
440
+ this.cleanupSandbox(sandbox.sandboxDir);
441
+ delete this.sandboxPool[poolKey];
442
+ }
443
+ }
444
+ return null;
445
+ }
446
+ addToPool(dependencyHash, sandboxDir, dependencies) {
447
+ const poolKey = dependencyHash;
448
+ if (this.sandboxPool[poolKey]) {
449
+ this.cleanupSandbox(this.sandboxPool[poolKey].sandboxDir);
450
+ }
451
+ this.sandboxPool[poolKey] = {
452
+ sandboxDir,
453
+ lastUsed: Date.now(),
454
+ useCount: 1,
455
+ dependencies
456
+ };
457
+ logger18.debug({ poolKey, sandboxDir }, "Added sandbox to pool");
458
+ }
459
+ cleanupSandbox(sandboxDir) {
460
+ try {
461
+ fs.rmSync(sandboxDir, { recursive: true, force: true });
462
+ logger18.debug({ sandboxDir }, "Cleaned up sandbox");
463
+ } catch (error) {
464
+ logger18.warn({ sandboxDir, error }, "Failed to clean up sandbox");
465
+ }
466
+ }
467
+ startPoolCleanup() {
468
+ setInterval(() => {
469
+ const now = Date.now();
470
+ const keysToDelete = [];
471
+ for (const [key, sandbox] of Object.entries(this.sandboxPool)) {
472
+ if (now - sandbox.lastUsed > this.POOL_TTL || sandbox.useCount >= this.MAX_USE_COUNT) {
473
+ this.cleanupSandbox(sandbox.sandboxDir);
474
+ keysToDelete.push(key);
475
+ }
476
+ }
477
+ keysToDelete.forEach((key) => {
478
+ delete this.sandboxPool[key];
479
+ });
480
+ if (keysToDelete.length > 0) {
481
+ logger18.debug({ cleanedCount: keysToDelete.length }, "Cleaned up expired sandboxes");
482
+ }
483
+ }, 6e4);
484
+ }
485
+ detectModuleType(executeCode) {
486
+ const esmPatterns = [
487
+ /import\s+.*\s+from\s+['"]/g,
488
+ // import ... from '...'
489
+ /import\s*\(/g,
490
+ // import(...)
491
+ /export\s+(default|const|let|var|function|class)/g,
492
+ // export statements
493
+ /export\s*\{/g
494
+ // export { ... }
495
+ ];
496
+ const cjsPatterns = [
497
+ /require\s*\(/g,
498
+ // require(...)
499
+ /module\.exports/g,
500
+ // module.exports
501
+ /exports\./g
502
+ // exports.something
503
+ ];
504
+ const hasEsmSyntax = esmPatterns.some((pattern) => pattern.test(executeCode));
505
+ const hasCjsSyntax = cjsPatterns.some((pattern) => pattern.test(executeCode));
506
+ if (hasEsmSyntax && hasCjsSyntax) {
507
+ logger18.warn(
508
+ { executeCode: `${executeCode.substring(0, 100)}...` },
509
+ "Both ESM and CommonJS syntax detected, defaulting to ESM"
510
+ );
511
+ return "esm";
512
+ }
513
+ if (hasEsmSyntax) {
514
+ return "esm";
515
+ }
516
+ if (hasCjsSyntax) {
517
+ return "cjs";
518
+ }
519
+ return "cjs";
520
+ }
521
+ async executeFunctionTool(toolId, args, config) {
522
+ const dependencies = config.dependencies || {};
523
+ const dependencyHash = this.generateDependencyHash(dependencies);
524
+ logger18.debug(
525
+ {
526
+ toolId,
527
+ dependencies,
528
+ dependencyHash,
529
+ poolSize: Object.keys(this.sandboxPool).length
530
+ },
531
+ "Executing function tool"
532
+ );
533
+ let sandboxDir = this.getCachedSandbox(dependencyHash);
534
+ let isNewSandbox = false;
535
+ if (!sandboxDir) {
536
+ sandboxDir = path.join(this.tempDir, `sandbox-${dependencyHash}-${Date.now()}`);
537
+ fs.mkdirSync(sandboxDir, { recursive: true });
538
+ isNewSandbox = true;
539
+ logger18.debug(
540
+ {
541
+ toolId,
542
+ dependencyHash,
543
+ sandboxDir,
544
+ dependencies
545
+ },
546
+ "Creating new sandbox"
547
+ );
548
+ const moduleType = this.detectModuleType(config.executeCode);
549
+ const packageJson = {
550
+ name: `function-tool-${toolId}`,
551
+ version: "1.0.0",
552
+ ...moduleType === "esm" && { type: "module" },
553
+ dependencies,
554
+ scripts: {
555
+ start: moduleType === "esm" ? "node index.mjs" : "node index.js"
556
+ }
557
+ };
558
+ fs.writeFileSync(path.join(sandboxDir, "package.json"), JSON.stringify(packageJson, null, 2), "utf8");
559
+ if (Object.keys(dependencies).length > 0) {
560
+ await this.installDependencies(sandboxDir);
561
+ }
562
+ this.addToPool(dependencyHash, sandboxDir, dependencies);
563
+ }
564
+ try {
565
+ const moduleType = this.detectModuleType(config.executeCode);
566
+ const executionCode = this.wrapFunctionCode(config.executeCode, args);
567
+ const fileExtension = moduleType === "esm" ? "mjs" : "js";
568
+ fs.writeFileSync(path.join(sandboxDir, `index.${fileExtension}`), executionCode, "utf8");
569
+ const result = await this.executeInSandbox(
570
+ sandboxDir,
571
+ config.sandboxConfig?.timeout || 3e4,
572
+ moduleType
573
+ );
574
+ return result;
575
+ } catch (error) {
576
+ if (isNewSandbox) {
577
+ this.cleanupSandbox(sandboxDir);
578
+ const poolKey = dependencyHash;
579
+ delete this.sandboxPool[poolKey];
580
+ }
581
+ throw error;
582
+ }
583
+ }
584
+ async installDependencies(sandboxDir) {
585
+ return new Promise((resolve, reject) => {
586
+ const npm = child_process.spawn("npm", ["install"], {
587
+ cwd: sandboxDir,
588
+ stdio: "pipe"
589
+ });
590
+ let stderr = "";
591
+ npm.stdout?.on("data", () => {
592
+ });
593
+ npm.stderr?.on("data", (data) => {
594
+ stderr += data.toString();
595
+ });
596
+ npm.on("close", (code) => {
597
+ if (code === 0) {
598
+ logger18.debug({ sandboxDir }, "Dependencies installed successfully");
599
+ resolve();
600
+ } else {
601
+ logger18.error({ sandboxDir, code, stderr }, "Failed to install dependencies");
602
+ reject(new Error(`npm install failed with code ${code}: ${stderr}`));
603
+ }
604
+ });
605
+ npm.on("error", (err) => {
606
+ logger18.error({ sandboxDir, error: err }, "Failed to spawn npm install");
607
+ reject(err);
608
+ });
609
+ });
610
+ }
611
+ async executeInSandbox(sandboxDir, timeout, moduleType) {
612
+ return new Promise((resolve, reject) => {
613
+ const fileExtension = moduleType === "esm" ? "mjs" : "js";
614
+ const spawnOptions = {
615
+ cwd: sandboxDir,
616
+ stdio: "pipe",
617
+ // Security: drop privileges and limit resources
618
+ uid: process.getuid ? process.getuid() : void 0,
619
+ gid: process.getgid ? process.getgid() : void 0
620
+ };
621
+ const node = child_process.spawn("node", [`index.${fileExtension}`], spawnOptions);
622
+ let stdout = "";
623
+ let stderr = "";
624
+ let outputSize = 0;
625
+ const MAX_OUTPUT_SIZE = 1024 * 1024;
626
+ node.stdout?.on("data", (data) => {
627
+ const dataStr = data.toString();
628
+ outputSize += dataStr.length;
629
+ if (outputSize > MAX_OUTPUT_SIZE) {
630
+ node.kill("SIGTERM");
631
+ reject(new Error(`Output size exceeded limit of ${MAX_OUTPUT_SIZE} bytes`));
632
+ return;
633
+ }
634
+ stdout += dataStr;
635
+ });
636
+ node.stderr?.on("data", (data) => {
637
+ const dataStr = data.toString();
638
+ outputSize += dataStr.length;
639
+ if (outputSize > MAX_OUTPUT_SIZE) {
640
+ node.kill("SIGTERM");
641
+ reject(new Error(`Output size exceeded limit of ${MAX_OUTPUT_SIZE} bytes`));
642
+ return;
643
+ }
644
+ stderr += dataStr;
645
+ });
646
+ const timeoutId = setTimeout(() => {
647
+ logger18.warn({ sandboxDir, timeout }, "Function execution timed out, killing process");
648
+ node.kill("SIGTERM");
649
+ setTimeout(() => {
650
+ try {
651
+ node.kill("SIGKILL");
652
+ } catch {
653
+ }
654
+ }, 5e3);
655
+ reject(new Error(`Function execution timed out after ${timeout}ms`));
656
+ }, timeout);
657
+ node.on("close", (code, signal) => {
658
+ clearTimeout(timeoutId);
659
+ if (code === 0) {
660
+ try {
661
+ const result = JSON.parse(stdout);
662
+ if (result.success) {
663
+ resolve(result.result);
664
+ } else {
665
+ reject(new Error(result.error || "Function execution failed"));
666
+ }
667
+ } catch (parseError) {
668
+ logger18.error({ stdout, stderr, parseError }, "Failed to parse function result");
669
+ reject(new Error(`Invalid function result: ${stdout}`));
670
+ }
671
+ } else {
672
+ const errorMsg = signal ? `Function execution killed by signal ${signal}: ${stderr}` : `Function execution failed with code ${code}: ${stderr}`;
673
+ logger18.error({ code, signal, stderr }, "Function execution failed");
674
+ reject(new Error(errorMsg));
675
+ }
676
+ });
677
+ node.on("error", (error) => {
678
+ clearTimeout(timeoutId);
679
+ logger18.error({ sandboxDir, error }, "Failed to spawn node process");
680
+ reject(error);
681
+ });
682
+ });
683
+ }
684
+ wrapFunctionCode(executeCode, args) {
685
+ return `
686
+ // Wrapped function execution (ESM)
687
+ const execute = ${executeCode};
688
+ const args = ${JSON.stringify(args)};
689
+
690
+ execute(args)
691
+ .then(result => {
692
+ console.log(JSON.stringify({ success: true, result }));
693
+ })
694
+ .catch(error => {
695
+ console.log(JSON.stringify({ success: false, error: error.message }));
696
+ });
697
+ `;
698
+ }
699
+ };
700
+ __publicField(_LocalSandboxExecutor, "instance", null);
701
+ LocalSandboxExecutor = _LocalSandboxExecutor;
702
+ }
703
+ });
704
+
378
705
  // src/utils/json-postprocessor.ts
379
706
  var json_postprocessor_exports = {};
380
707
  __export(json_postprocessor_exports, {
@@ -496,7 +823,9 @@ var apiKeyAuth = () => factory.createMiddleware(async (c, next) => {
496
823
  const projectId = c.req.header("x-inkeep-project-id");
497
824
  const graphId = c.req.header("x-inkeep-graph-id");
498
825
  const agentId = c.req.header("x-inkeep-agent-id");
499
- const baseUrl = new URL(c.req.url).origin;
826
+ const proto = c.req.header("x-forwarded-proto") ?? "http";
827
+ const host = c.req.header("x-forwarded-host") ?? c.req.header("host");
828
+ const baseUrl = `${proto}://${host}`;
500
829
  if (process.env.ENVIRONMENT === "development" || process.env.ENVIRONMENT === "test") {
501
830
  let executionContext;
502
831
  if (authHeader?.startsWith("Bearer ")) {
@@ -1394,46 +1723,6 @@ async function getRegisteredAgent(executionContext, credentialStoreRegistry) {
1394
1723
  init_dbClient();
1395
1724
  init_logger();
1396
1725
 
1397
- // src/utils/model-resolver.ts
1398
- init_dbClient();
1399
- async function resolveModelConfig(graphId, agent) {
1400
- if (agent.models?.base?.model) {
1401
- return {
1402
- base: agent.models.base,
1403
- structuredOutput: agent.models.structuredOutput || agent.models.base,
1404
- summarizer: agent.models.summarizer || agent.models.base
1405
- };
1406
- }
1407
- const graph = await agentsCore.getAgentGraphById(dbClient_default)({
1408
- scopes: { tenantId: agent.tenantId, projectId: agent.projectId, graphId }
1409
- });
1410
- if (graph?.models?.base?.model) {
1411
- return {
1412
- base: graph.models.base,
1413
- structuredOutput: agent.models?.structuredOutput || graph.models.structuredOutput || graph.models.base,
1414
- summarizer: agent.models?.summarizer || graph.models.summarizer || graph.models.base
1415
- };
1416
- }
1417
- const project = await agentsCore.getProject(dbClient_default)({
1418
- scopes: { tenantId: agent.tenantId, projectId: agent.projectId }
1419
- });
1420
- if (project?.models?.base?.model) {
1421
- return {
1422
- base: project.models.base,
1423
- structuredOutput: agent.models?.structuredOutput || project.models.structuredOutput || project.models.base,
1424
- summarizer: agent.models?.summarizer || project.models.summarizer || project.models.base
1425
- };
1426
- }
1427
- throw new Error(
1428
- "Base model configuration is required. Please configure models at the project level."
1429
- );
1430
- }
1431
-
1432
- // src/agents/Agent.ts
1433
- init_conversations();
1434
- init_dbClient();
1435
- init_logger();
1436
-
1437
1726
  // src/agents/ModelFactory.ts
1438
1727
  init_logger();
1439
1728
  var logger5 = agentsCore.getLogger("ModelFactory");
@@ -1832,7 +2121,46 @@ var tracer = agentsCore.getTracer("agents-run-api");
1832
2121
  init_logger();
1833
2122
  init_dbClient();
1834
2123
  init_logger();
1835
- var logger7 = agentsCore.getLogger("ArtifactService");
2124
+
2125
+ // src/utils/schema-validation.ts
2126
+ init_logger();
2127
+ agentsCore.getLogger("SchemaValidation");
2128
+ new Ajv__default.default({ allErrors: true, strict: false });
2129
+ function extractPreviewFields(schema) {
2130
+ const previewProperties = {};
2131
+ if (schema.properties) {
2132
+ for (const [key, prop] of Object.entries(schema.properties)) {
2133
+ if (prop.inPreview === true) {
2134
+ const cleanProp = { ...prop };
2135
+ delete cleanProp.inPreview;
2136
+ previewProperties[key] = cleanProp;
2137
+ }
2138
+ }
2139
+ }
2140
+ return {
2141
+ type: "object",
2142
+ properties: previewProperties,
2143
+ required: schema.required?.filter((field) => previewProperties[field])
2144
+ };
2145
+ }
2146
+ function extractFullFields(schema) {
2147
+ const fullProperties = {};
2148
+ if (schema.properties) {
2149
+ for (const [key, prop] of Object.entries(schema.properties)) {
2150
+ const cleanProp = { ...prop };
2151
+ delete cleanProp.inPreview;
2152
+ fullProperties[key] = cleanProp;
2153
+ }
2154
+ }
2155
+ return {
2156
+ type: "object",
2157
+ properties: fullProperties,
2158
+ required: schema.required
2159
+ };
2160
+ }
2161
+
2162
+ // src/services/ArtifactService.ts
2163
+ var logger8 = agentsCore.getLogger("ArtifactService");
1836
2164
  var _ArtifactService = class _ArtifactService {
1837
2165
  constructor(context) {
1838
2166
  this.context = context;
@@ -1844,6 +2172,12 @@ var _ArtifactService = class _ArtifactService {
1844
2172
  static clearCaches() {
1845
2173
  _ArtifactService.selectorCache.clear();
1846
2174
  }
2175
+ /**
2176
+ * Update artifact components in the context
2177
+ */
2178
+ updateArtifactComponents(artifactComponents) {
2179
+ this.context.artifactComponents = artifactComponents;
2180
+ }
1847
2181
  /**
1848
2182
  * Get all artifacts for a context from database
1849
2183
  */
@@ -1858,7 +2192,7 @@ var _ArtifactService = class _ArtifactService {
1858
2192
  id: taskId
1859
2193
  });
1860
2194
  if (!task) {
1861
- logger7.warn({ taskId }, "Task not found when fetching artifacts");
2195
+ logger8.warn({ taskId }, "Task not found when fetching artifacts");
1862
2196
  continue;
1863
2197
  }
1864
2198
  const taskArtifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
@@ -1876,7 +2210,7 @@ var _ArtifactService = class _ArtifactService {
1876
2210
  }
1877
2211
  }
1878
2212
  } catch (error) {
1879
- logger7.error({ error, contextId }, "Error loading context artifacts");
2213
+ logger8.error({ error, contextId }, "Error loading context artifacts");
1880
2214
  }
1881
2215
  return artifacts;
1882
2216
  }
@@ -1885,12 +2219,12 @@ var _ArtifactService = class _ArtifactService {
1885
2219
  */
1886
2220
  async createArtifact(request, agentId) {
1887
2221
  if (!this.context.sessionId) {
1888
- logger7.warn({ request }, "No session ID available for artifact creation");
2222
+ logger8.warn({ request }, "No session ID available for artifact creation");
1889
2223
  return null;
1890
2224
  }
1891
2225
  const toolResult = toolSessionManager.getToolResult(this.context.sessionId, request.toolCallId);
1892
2226
  if (!toolResult) {
1893
- logger7.warn(
2227
+ logger8.warn(
1894
2228
  { request, sessionId: this.context.sessionId },
1895
2229
  "Tool result not found for artifact"
1896
2230
  );
@@ -1906,7 +2240,7 @@ var _ArtifactService = class _ArtifactService {
1906
2240
  selectedData = selectedData.length > 0 ? selectedData[0] : {};
1907
2241
  }
1908
2242
  if (!selectedData) {
1909
- logger7.warn(
2243
+ logger8.warn(
1910
2244
  {
1911
2245
  request,
1912
2246
  baseSelector: request.baseSelector
@@ -1915,8 +2249,26 @@ var _ArtifactService = class _ArtifactService {
1915
2249
  );
1916
2250
  selectedData = {};
1917
2251
  }
1918
- const summaryData = this.extractProps(selectedData, request.summaryProps || {});
1919
- let fullData = this.extractProps(selectedData, request.fullProps || {});
2252
+ const component = this.context.artifactComponents?.find((ac) => ac.name === request.type);
2253
+ let summaryData = {};
2254
+ let fullData = {};
2255
+ if (component?.props) {
2256
+ const previewSchema = extractPreviewFields(component.props);
2257
+ const fullSchema = extractFullFields(component.props);
2258
+ summaryData = this.extractPropsFromSchema(
2259
+ selectedData,
2260
+ previewSchema,
2261
+ request.detailsSelector || {}
2262
+ );
2263
+ fullData = this.extractPropsFromSchema(
2264
+ selectedData,
2265
+ fullSchema,
2266
+ request.detailsSelector || {}
2267
+ );
2268
+ } else {
2269
+ summaryData = selectedData;
2270
+ fullData = selectedData;
2271
+ }
1920
2272
  const isFullDataEmpty = !fullData || Object.keys(fullData).length === 0 || Object.values(fullData).every(
1921
2273
  (val) => val === null || val === void 0 || val === "" || Array.isArray(val) && val.length === 0 || typeof val === "object" && Object.keys(val).length === 0
1922
2274
  );
@@ -1925,14 +2277,13 @@ var _ArtifactService = class _ArtifactService {
1925
2277
  }
1926
2278
  const cleanedSummaryData = this.cleanEscapedContent(summaryData);
1927
2279
  const cleanedFullData = this.cleanEscapedContent(fullData);
1928
- const component = this.context.artifactComponents?.find((ac) => ac.name === request.type);
1929
2280
  const artifactData = {
1930
2281
  artifactId: request.artifactId,
1931
2282
  toolCallId: request.toolCallId,
1932
2283
  name: "Processing...",
1933
2284
  description: "Name and description being generated...",
1934
2285
  type: request.type,
1935
- artifactSummary: component?.summaryProps ? this.filterBySchema(cleanedSummaryData, component.summaryProps) : cleanedSummaryData
2286
+ data: cleanedSummaryData
1936
2287
  };
1937
2288
  await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, agentId);
1938
2289
  await this.cacheArtifact(
@@ -1943,15 +2294,15 @@ var _ArtifactService = class _ArtifactService {
1943
2294
  );
1944
2295
  return artifactData;
1945
2296
  } catch (error) {
1946
- logger7.error({ error, request }, "Failed to create artifact");
2297
+ logger8.error({ error, request }, "Failed to create artifact");
1947
2298
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
1948
2299
  throw new Error(`Artifact creation failed for ${request.artifactId}: ${errorMessage}`);
1949
2300
  }
1950
2301
  }
1951
2302
  /**
1952
- * Get artifact data by ID and tool call ID
2303
+ * Get artifact summary data by ID and tool call ID
1953
2304
  */
1954
- async getArtifactData(artifactId, toolCallId, artifactMap) {
2305
+ async getArtifactSummary(artifactId, toolCallId, artifactMap) {
1955
2306
  const key = `${artifactId}:${toolCallId}`;
1956
2307
  if (this.context.streamRequestId) {
1957
2308
  const cachedArtifact = await graphSessionManager.getArtifactCache(
@@ -1959,20 +2310,20 @@ var _ArtifactService = class _ArtifactService {
1959
2310
  key
1960
2311
  );
1961
2312
  if (cachedArtifact) {
1962
- return this.formatArtifactData(cachedArtifact, artifactId, toolCallId);
2313
+ return this.formatArtifactSummaryData(cachedArtifact, artifactId, toolCallId);
1963
2314
  }
1964
2315
  }
1965
2316
  if (this.createdArtifacts.has(key)) {
1966
2317
  const cached = this.createdArtifacts.get(key);
1967
- return this.formatArtifactData(cached, artifactId, toolCallId);
2318
+ return this.formatArtifactSummaryData(cached, artifactId, toolCallId);
1968
2319
  }
1969
2320
  if (artifactMap?.has(key)) {
1970
2321
  const artifact = artifactMap.get(key);
1971
- return this.formatArtifactData(artifact, artifactId, toolCallId);
2322
+ return this.formatArtifactSummaryData(artifact, artifactId, toolCallId);
1972
2323
  }
1973
2324
  try {
1974
2325
  if (!this.context.projectId || !this.context.taskId) {
1975
- logger7.warn(
2326
+ logger8.warn(
1976
2327
  { artifactId, toolCallId },
1977
2328
  "No projectId or taskId available for artifact lookup"
1978
2329
  );
@@ -1984,10 +2335,10 @@ var _ArtifactService = class _ArtifactService {
1984
2335
  taskId: this.context.taskId
1985
2336
  });
1986
2337
  if (artifacts.length > 0) {
1987
- return this.formatArtifactData(artifacts[0], artifactId, toolCallId);
2338
+ return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
1988
2339
  }
1989
2340
  } catch (error) {
1990
- logger7.warn(
2341
+ logger8.warn(
1991
2342
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1992
2343
  "Failed to fetch artifact"
1993
2344
  );
@@ -1995,16 +2346,75 @@ var _ArtifactService = class _ArtifactService {
1995
2346
  return null;
1996
2347
  }
1997
2348
  /**
1998
- * Format raw artifact to standardized data format
2349
+ * Get artifact full data by ID and tool call ID
1999
2350
  */
2000
- formatArtifactData(artifact, artifactId, toolCallId) {
2351
+ async getArtifactFull(artifactId, toolCallId, artifactMap) {
2352
+ const key = `${artifactId}:${toolCallId}`;
2353
+ if (this.context.streamRequestId) {
2354
+ const cachedArtifact = await graphSessionManager.getArtifactCache(
2355
+ this.context.streamRequestId,
2356
+ key
2357
+ );
2358
+ if (cachedArtifact) {
2359
+ return this.formatArtifactFullData(cachedArtifact, artifactId, toolCallId);
2360
+ }
2361
+ }
2362
+ if (this.createdArtifacts.has(key)) {
2363
+ const cached = this.createdArtifacts.get(key);
2364
+ return this.formatArtifactFullData(cached, artifactId, toolCallId);
2365
+ }
2366
+ if (artifactMap?.has(key)) {
2367
+ const artifact = artifactMap.get(key);
2368
+ return this.formatArtifactFullData(artifact, artifactId, toolCallId);
2369
+ }
2370
+ try {
2371
+ if (!this.context.projectId || !this.context.taskId) {
2372
+ logger8.warn(
2373
+ { artifactId, toolCallId },
2374
+ "No projectId or taskId available for artifact lookup"
2375
+ );
2376
+ return null;
2377
+ }
2378
+ const artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
2379
+ scopes: { tenantId: this.context.tenantId, projectId: this.context.projectId },
2380
+ artifactId,
2381
+ taskId: this.context.taskId
2382
+ });
2383
+ if (artifacts.length > 0) {
2384
+ return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
2385
+ }
2386
+ } catch (error) {
2387
+ logger8.warn(
2388
+ { artifactId, toolCallId, taskId: this.context.taskId, error },
2389
+ "Failed to fetch artifact"
2390
+ );
2391
+ }
2392
+ return null;
2393
+ }
2394
+ /**
2395
+ * Format raw artifact to standardized summary data format
2396
+ */
2397
+ formatArtifactSummaryData(artifact, artifactId, toolCallId) {
2001
2398
  return {
2002
2399
  artifactId,
2003
2400
  toolCallId,
2004
2401
  name: artifact.name || "Processing...",
2005
2402
  description: artifact.description || "Name and description being generated...",
2006
2403
  type: artifact.metadata?.artifactType || artifact.artifactType,
2007
- artifactSummary: artifact.parts?.[0]?.data?.summary || {}
2404
+ data: artifact.parts?.[0]?.data?.summary || {}
2405
+ };
2406
+ }
2407
+ /**
2408
+ * Format raw artifact to standardized full data format
2409
+ */
2410
+ formatArtifactFullData(artifact, artifactId, toolCallId) {
2411
+ return {
2412
+ artifactId,
2413
+ toolCallId,
2414
+ name: artifact.name || "Processing...",
2415
+ description: artifact.description || "Name and description being generated...",
2416
+ type: artifact.metadata?.artifactType || artifact.artifactType,
2417
+ data: artifact.parts?.[0]?.data?.full || {}
2008
2418
  };
2009
2419
  }
2010
2420
  /**
@@ -2022,14 +2432,13 @@ var _ArtifactService = class _ArtifactService {
2022
2432
  taskId: this.context.taskId,
2023
2433
  toolCallId: request.toolCallId,
2024
2434
  artifactType: request.type,
2025
- summaryProps: summaryData,
2026
- fullProps: fullData,
2435
+ summaryData,
2436
+ data: fullData,
2027
2437
  agentId: effectiveAgentId,
2028
2438
  metadata: {
2029
2439
  toolCallId: request.toolCallId,
2030
2440
  baseSelector: request.baseSelector,
2031
- summaryProps: request.summaryProps,
2032
- fullProps: request.fullProps,
2441
+ detailsSelector: request.detailsSelector,
2033
2442
  sessionId: this.context.sessionId,
2034
2443
  artifactType: request.type
2035
2444
  },
@@ -2040,14 +2449,17 @@ var _ArtifactService = class _ArtifactService {
2040
2449
  }
2041
2450
  );
2042
2451
  } else {
2043
- logger7.warn({
2044
- artifactId: request.artifactId,
2045
- hasStreamRequestId: !!this.context.streamRequestId,
2046
- hasAgentId: !!effectiveAgentId,
2047
- hasTaskId: !!this.context.taskId,
2048
- passedAgentId: agentId,
2049
- contextAgentId: this.context.agentId
2050
- }, "Skipping artifact_saved event - missing required context");
2452
+ logger8.warn(
2453
+ {
2454
+ artifactId: request.artifactId,
2455
+ hasStreamRequestId: !!this.context.streamRequestId,
2456
+ hasAgentId: !!effectiveAgentId,
2457
+ hasTaskId: !!this.context.taskId,
2458
+ passedAgentId: agentId,
2459
+ contextAgentId: this.context.agentId
2460
+ },
2461
+ "Skipping artifact_saved event - missing required context"
2462
+ );
2051
2463
  }
2052
2464
  }
2053
2465
  /**
@@ -2057,7 +2469,7 @@ var _ArtifactService = class _ArtifactService {
2057
2469
  const cacheKey = `${artifactId}:${toolCallId}`;
2058
2470
  const artifactForCache = {
2059
2471
  ...artifactData,
2060
- parts: [{ data: { summary: artifactData.artifactSummary, full: fullData } }],
2472
+ parts: [{ data: { summary: artifactData.data, data: fullData } }],
2061
2473
  metadata: { artifactType: artifactData.type, toolCallId },
2062
2474
  taskId: this.context.taskId
2063
2475
  };
@@ -2098,6 +2510,30 @@ var _ArtifactService = class _ArtifactService {
2098
2510
  * Used by GraphSession to save artifacts after name/description generation
2099
2511
  */
2100
2512
  async saveArtifact(artifact) {
2513
+ let summaryData = artifact.data;
2514
+ let fullData = artifact.data;
2515
+ if (this.context.artifactComponents) {
2516
+ const artifactComponent = this.context.artifactComponents.find(
2517
+ (ac) => ac.name === artifact.type
2518
+ );
2519
+ if (artifactComponent?.props) {
2520
+ try {
2521
+ const schema = artifactComponent.props;
2522
+ const previewSchema = extractPreviewFields(schema);
2523
+ const fullSchema = extractFullFields(schema);
2524
+ summaryData = this.filterBySchema(artifact.data, previewSchema);
2525
+ fullData = this.filterBySchema(artifact.data, fullSchema);
2526
+ } catch (error) {
2527
+ logger8.warn(
2528
+ {
2529
+ artifactType: artifact.type,
2530
+ error: error instanceof Error ? error.message : "Unknown error"
2531
+ },
2532
+ "Failed to extract preview/full fields from schema, using full data for both"
2533
+ );
2534
+ }
2535
+ }
2536
+ }
2101
2537
  const artifactToSave = {
2102
2538
  artifactId: artifact.artifactId,
2103
2539
  name: artifact.name,
@@ -2108,8 +2544,8 @@ var _ArtifactService = class _ArtifactService {
2108
2544
  {
2109
2545
  kind: "data",
2110
2546
  data: {
2111
- summary: artifact.summaryProps,
2112
- full: artifact.fullProps
2547
+ summary: summaryData,
2548
+ full: fullData
2113
2549
  }
2114
2550
  }
2115
2551
  ],
@@ -2122,10 +2558,11 @@ var _ArtifactService = class _ArtifactService {
2122
2558
  },
2123
2559
  contextId: this.context.contextId,
2124
2560
  taskId: this.context.taskId,
2561
+ toolCallId: artifact.toolCallId,
2125
2562
  artifact: artifactToSave
2126
2563
  });
2127
2564
  if (!result.created && result.existing) {
2128
- logger7.debug(
2565
+ logger8.debug(
2129
2566
  {
2130
2567
  artifactId: artifact.artifactId,
2131
2568
  taskId: this.context.taskId
@@ -2178,7 +2615,7 @@ var _ArtifactService = class _ArtifactService {
2178
2615
  extracted[propName] = this.cleanEscapedContent(rawValue);
2179
2616
  }
2180
2617
  } catch (error) {
2181
- logger7.warn(
2618
+ logger8.warn(
2182
2619
  { propName, selector, error: error instanceof Error ? error.message : "Unknown error" },
2183
2620
  "Failed to extract property"
2184
2621
  );
@@ -2190,6 +2627,39 @@ var _ArtifactService = class _ArtifactService {
2190
2627
  }
2191
2628
  return extracted;
2192
2629
  }
2630
+ /**
2631
+ * Extract properties from data using schema-defined fields and custom selectors
2632
+ */
2633
+ extractPropsFromSchema(item, schema, customSelectors) {
2634
+ const extracted = {};
2635
+ if (schema.properties) {
2636
+ for (const fieldName of Object.keys(schema.properties)) {
2637
+ try {
2638
+ const customSelector = customSelectors[fieldName];
2639
+ let rawValue;
2640
+ if (customSelector) {
2641
+ const sanitizedSelector = this.sanitizeJMESPathSelector(customSelector);
2642
+ rawValue = jmespath__default.default.search(item, sanitizedSelector);
2643
+ } else {
2644
+ rawValue = item[fieldName];
2645
+ }
2646
+ if (rawValue !== null && rawValue !== void 0) {
2647
+ extracted[fieldName] = this.cleanEscapedContent(rawValue);
2648
+ }
2649
+ } catch (error) {
2650
+ logger8.warn(
2651
+ { fieldName, error: error instanceof Error ? error.message : "Unknown error" },
2652
+ "Failed to extract schema field"
2653
+ );
2654
+ const fallbackValue = item[fieldName];
2655
+ if (fallbackValue !== null && fallbackValue !== void 0) {
2656
+ extracted[fieldName] = this.cleanEscapedContent(fallbackValue);
2657
+ }
2658
+ }
2659
+ }
2660
+ }
2661
+ return extracted;
2662
+ }
2193
2663
  /**
2194
2664
  * Filter extracted props based on schema
2195
2665
  */
@@ -2208,15 +2678,19 @@ __publicField(_ArtifactService, "selectorCache", /* @__PURE__ */ new Map());
2208
2678
  var ArtifactService = _ArtifactService;
2209
2679
 
2210
2680
  // src/services/ArtifactParser.ts
2211
- var logger8 = agentsCore.getLogger("ArtifactParser");
2681
+ var logger9 = agentsCore.getLogger("ArtifactParser");
2212
2682
  var _ArtifactParser = class _ArtifactParser {
2213
2683
  constructor(tenantId, options) {
2214
2684
  __publicField(this, "artifactService");
2215
- const context = {
2216
- tenantId,
2217
- ...options
2218
- };
2219
- this.artifactService = new ArtifactService(context);
2685
+ if (options?.artifactService) {
2686
+ this.artifactService = options.artifactService;
2687
+ } else {
2688
+ const context = {
2689
+ tenantId,
2690
+ ...options
2691
+ };
2692
+ this.artifactService = new ArtifactService(context);
2693
+ }
2220
2694
  }
2221
2695
  /**
2222
2696
  * Check if text contains complete artifact markers (ref or create)
@@ -2292,7 +2766,7 @@ var _ArtifactParser = class _ArtifactParser {
2292
2766
  attrs[key] = value;
2293
2767
  }
2294
2768
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
2295
- logger8.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2769
+ logger9.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
2296
2770
  return null;
2297
2771
  }
2298
2772
  return {
@@ -2300,8 +2774,7 @@ var _ArtifactParser = class _ArtifactParser {
2300
2774
  toolCallId: attrs.tool,
2301
2775
  type: attrs.type,
2302
2776
  baseSelector: attrs.base,
2303
- summaryProps: attrs.summary || {},
2304
- fullProps: attrs.full || {}
2777
+ detailsSelector: attrs.details || {}
2305
2778
  };
2306
2779
  }
2307
2780
  /**
@@ -2330,8 +2803,7 @@ var _ArtifactParser = class _ArtifactParser {
2330
2803
  toolCallId: annotation.toolCallId,
2331
2804
  type: annotation.type,
2332
2805
  baseSelector: annotation.baseSelector,
2333
- summaryProps: annotation.summaryProps,
2334
- fullProps: annotation.fullProps
2806
+ detailsSelector: annotation.detailsSelector
2335
2807
  };
2336
2808
  return this.artifactService.createArtifact(request, agentId);
2337
2809
  }
@@ -2351,9 +2823,14 @@ var _ArtifactParser = class _ArtifactParser {
2351
2823
  if (artifactData && annotation.raw) {
2352
2824
  createdArtifactData.set(annotation.raw, artifactData);
2353
2825
  } else if (annotation.raw) {
2354
- failedAnnotations.push(`Failed to create artifact "${annotation.artifactId}": Missing or invalid data`);
2826
+ failedAnnotations.push(
2827
+ `Failed to create artifact "${annotation.artifactId}": Missing or invalid data`
2828
+ );
2355
2829
  processedText = processedText.replace(annotation.raw, "");
2356
- logger8.warn({ annotation, artifactData }, "Removed failed artifact:create annotation from output");
2830
+ logger9.warn(
2831
+ { annotation, artifactData },
2832
+ "Removed failed artifact:create annotation from output"
2833
+ );
2357
2834
  }
2358
2835
  } catch (error) {
2359
2836
  const errorMsg = error instanceof Error ? error.message : "Unknown error";
@@ -2361,14 +2838,17 @@ var _ArtifactParser = class _ArtifactParser {
2361
2838
  if (annotation.raw) {
2362
2839
  processedText = processedText.replace(annotation.raw, "");
2363
2840
  }
2364
- logger8.error({ annotation, error }, "Failed to extract artifact from create annotation");
2841
+ logger9.error({ annotation, error }, "Failed to extract artifact from create annotation");
2365
2842
  }
2366
2843
  }
2367
2844
  if (failedAnnotations.length > 0) {
2368
- logger8.warn({
2369
- failedCount: failedAnnotations.length,
2370
- failures: failedAnnotations
2371
- }, "Some artifact creation attempts failed");
2845
+ logger9.warn(
2846
+ {
2847
+ failedCount: failedAnnotations.length,
2848
+ failures: failedAnnotations
2849
+ },
2850
+ "Some artifact creation attempts failed"
2851
+ );
2372
2852
  }
2373
2853
  const parts = [];
2374
2854
  const createRegex = /<artifact:create\s+([^>]+?)(?:\s*\/)?>(?:(.*?)<\/artifact:create>)?/gs;
@@ -2401,7 +2881,17 @@ var _ArtifactParser = class _ArtifactParser {
2401
2881
  artifactData = await this.getArtifactData(artifactId, toolCallId, artifactMap);
2402
2882
  }
2403
2883
  if (artifactData) {
2404
- parts.push({ kind: "data", data: artifactData });
2884
+ parts.push({
2885
+ kind: "data",
2886
+ data: {
2887
+ artifactId: artifactData.artifactId,
2888
+ toolCallId: artifactData.toolCallId,
2889
+ name: artifactData.name,
2890
+ description: artifactData.description,
2891
+ type: artifactData.type,
2892
+ artifactSummary: artifactData.data
2893
+ }
2894
+ });
2405
2895
  }
2406
2896
  lastIndex = matchStart + fullMatch.length;
2407
2897
  }
@@ -2427,12 +2917,32 @@ var _ArtifactParser = class _ArtifactParser {
2427
2917
  artifactMap
2428
2918
  );
2429
2919
  if (artifactData) {
2430
- parts.push({ kind: "data", data: artifactData });
2920
+ parts.push({
2921
+ kind: "data",
2922
+ data: {
2923
+ artifactId: artifactData.artifactId,
2924
+ toolCallId: artifactData.toolCallId,
2925
+ name: artifactData.name,
2926
+ description: artifactData.description,
2927
+ type: artifactData.type,
2928
+ artifactSummary: artifactData.data
2929
+ }
2930
+ });
2431
2931
  }
2432
2932
  } else if (this.isArtifactCreateComponent(component)) {
2433
2933
  const createData = await this.extractFromArtifactCreateComponent(component, agentId);
2434
2934
  if (createData) {
2435
- parts.push({ kind: "data", data: createData });
2935
+ parts.push({
2936
+ kind: "data",
2937
+ data: {
2938
+ artifactId: createData.artifactId,
2939
+ toolCallId: createData.toolCallId,
2940
+ name: createData.name,
2941
+ description: createData.description,
2942
+ type: createData.type,
2943
+ artifactSummary: createData.data
2944
+ }
2945
+ });
2436
2946
  }
2437
2947
  } else {
2438
2948
  parts.push({ kind: "data", data: component });
@@ -2446,11 +2956,35 @@ var _ArtifactParser = class _ArtifactParser {
2446
2956
  obj.props.tool_call_id,
2447
2957
  artifactMap
2448
2958
  );
2449
- return artifactData ? [{ kind: "data", data: artifactData }] : [];
2959
+ return artifactData ? [
2960
+ {
2961
+ kind: "data",
2962
+ data: {
2963
+ artifactId: artifactData.artifactId,
2964
+ toolCallId: artifactData.toolCallId,
2965
+ name: artifactData.name,
2966
+ description: artifactData.description,
2967
+ type: artifactData.type,
2968
+ artifactSummary: artifactData.data
2969
+ }
2970
+ }
2971
+ ] : [];
2450
2972
  }
2451
2973
  if (this.isArtifactCreateComponent(obj)) {
2452
2974
  const createData = await this.extractFromArtifactCreateComponent(obj, agentId);
2453
- return createData ? [{ kind: "data", data: createData }] : [];
2975
+ return createData ? [
2976
+ {
2977
+ kind: "data",
2978
+ data: {
2979
+ artifactId: createData.artifactId,
2980
+ toolCallId: createData.toolCallId,
2981
+ name: createData.name,
2982
+ description: createData.description,
2983
+ type: createData.type,
2984
+ artifactSummary: createData.data
2985
+ }
2986
+ }
2987
+ ] : [];
2454
2988
  }
2455
2989
  return [{ kind: "data", data: obj }];
2456
2990
  }
@@ -2479,8 +3013,7 @@ var _ArtifactParser = class _ArtifactParser {
2479
3013
  toolCallId: props.tool_call_id,
2480
3014
  type: props.type,
2481
3015
  baseSelector: props.base_selector,
2482
- summaryProps: props.summary_props || {},
2483
- fullProps: props.full_props || {}
3016
+ detailsSelector: props.details_selector || {}
2484
3017
  };
2485
3018
  return await this.extractFromCreateAnnotation(annotation, agentId);
2486
3019
  }
@@ -2488,7 +3021,7 @@ var _ArtifactParser = class _ArtifactParser {
2488
3021
  * Get artifact data - delegates to service
2489
3022
  */
2490
3023
  async getArtifactData(artifactId, toolCallId, artifactMap) {
2491
- return this.artifactService.getArtifactData(artifactId, toolCallId, artifactMap);
3024
+ return await this.artifactService.getArtifactSummary(artifactId, toolCallId, artifactMap);
2492
3025
  }
2493
3026
  };
2494
3027
  // Shared regex patterns - support both single and double quotes
@@ -2522,7 +3055,7 @@ __publicField(_ArtifactParser, "INCOMPLETE_CREATE_REGEX", /<artifact:create(?![^
2522
3055
  var ArtifactParser = _ArtifactParser;
2523
3056
 
2524
3057
  // src/services/GraphSession.ts
2525
- var logger9 = agentsCore.getLogger("GraphSession");
3058
+ var logger10 = agentsCore.getLogger("GraphSession");
2526
3059
  var GraphSession = class {
2527
3060
  // Whether to send data operations
2528
3061
  constructor(sessionId, messageId, graphId, tenantId, projectId, contextId) {
@@ -2555,7 +3088,7 @@ var GraphSession = class {
2555
3088
  __publicField(this, "artifactParser");
2556
3089
  // Session-scoped ArtifactParser instance
2557
3090
  __publicField(this, "isEmitOperations", false);
2558
- logger9.debug({ sessionId, messageId, graphId }, "GraphSession created");
3091
+ logger10.debug({ sessionId, messageId, graphId }, "GraphSession created");
2559
3092
  if (tenantId && projectId) {
2560
3093
  toolSessionManager.createSessionWithId(
2561
3094
  sessionId,
@@ -2579,7 +3112,9 @@ var GraphSession = class {
2579
3112
  sessionId,
2580
3113
  contextId,
2581
3114
  taskId: `task_${contextId}-${messageId}`,
2582
- streamRequestId: sessionId
3115
+ streamRequestId: sessionId,
3116
+ artifactService: this.artifactService
3117
+ // Pass the shared ArtifactService
2583
3118
  });
2584
3119
  }
2585
3120
  }
@@ -2588,7 +3123,7 @@ var GraphSession = class {
2588
3123
  */
2589
3124
  enableEmitOperations() {
2590
3125
  this.isEmitOperations = true;
2591
- logger9.info(
3126
+ logger10.info(
2592
3127
  { sessionId: this.sessionId },
2593
3128
  "\u{1F50D} DEBUG: Emit operations enabled for GraphSession"
2594
3129
  );
@@ -2612,7 +3147,7 @@ var GraphSession = class {
2612
3147
  await streamHelper.writeOperation(formattedOperation);
2613
3148
  }
2614
3149
  } catch (error) {
2615
- logger9.error(
3150
+ logger10.error(
2616
3151
  {
2617
3152
  sessionId: this.sessionId,
2618
3153
  eventType: event.eventType,
@@ -2675,7 +3210,7 @@ var GraphSession = class {
2675
3210
  if (this.statusUpdateState.config.timeInSeconds) {
2676
3211
  this.statusUpdateTimer = setInterval(async () => {
2677
3212
  if (!this.statusUpdateState || this.isEnded) {
2678
- logger9.debug(
3213
+ logger10.debug(
2679
3214
  { sessionId: this.sessionId },
2680
3215
  "Timer triggered but session already cleaned up or ended"
2681
3216
  );
@@ -2687,7 +3222,7 @@ var GraphSession = class {
2687
3222
  }
2688
3223
  await this.checkAndSendTimeBasedUpdate();
2689
3224
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2690
- logger9.info(
3225
+ logger10.info(
2691
3226
  {
2692
3227
  sessionId: this.sessionId,
2693
3228
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -2709,7 +3244,7 @@ var GraphSession = class {
2709
3244
  });
2710
3245
  }
2711
3246
  if (this.isEnded) {
2712
- logger9.debug(
3247
+ logger10.debug(
2713
3248
  {
2714
3249
  sessionId: this.sessionId,
2715
3250
  eventType,
@@ -2729,7 +3264,7 @@ var GraphSession = class {
2729
3264
  if (eventType === "artifact_saved" && data.pendingGeneration) {
2730
3265
  const artifactId = data.artifactId;
2731
3266
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2732
- logger9.warn(
3267
+ logger10.warn(
2733
3268
  {
2734
3269
  sessionId: this.sessionId,
2735
3270
  artifactId,
@@ -2751,7 +3286,7 @@ var GraphSession = class {
2751
3286
  this.artifactProcessingErrors.set(artifactId, errorCount);
2752
3287
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2753
3288
  this.pendingArtifacts.delete(artifactId);
2754
- logger9.error(
3289
+ logger10.error(
2755
3290
  {
2756
3291
  sessionId: this.sessionId,
2757
3292
  artifactId,
@@ -2763,7 +3298,7 @@ var GraphSession = class {
2763
3298
  "Artifact processing failed after max retries, giving up"
2764
3299
  );
2765
3300
  } else {
2766
- logger9.warn(
3301
+ logger10.warn(
2767
3302
  {
2768
3303
  sessionId: this.sessionId,
2769
3304
  artifactId,
@@ -2785,14 +3320,14 @@ var GraphSession = class {
2785
3320
  */
2786
3321
  checkStatusUpdates() {
2787
3322
  if (this.isEnded) {
2788
- logger9.debug(
3323
+ logger10.debug(
2789
3324
  { sessionId: this.sessionId },
2790
3325
  "Session has ended - skipping status update check"
2791
3326
  );
2792
3327
  return;
2793
3328
  }
2794
3329
  if (!this.statusUpdateState) {
2795
- logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
3330
+ logger10.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2796
3331
  return;
2797
3332
  }
2798
3333
  const statusUpdateState = this.statusUpdateState;
@@ -2803,11 +3338,11 @@ var GraphSession = class {
2803
3338
  */
2804
3339
  async checkAndSendTimeBasedUpdate() {
2805
3340
  if (this.isEnded) {
2806
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
3341
+ logger10.debug({ sessionId: this.sessionId }, "Session has ended - skipping time-based update");
2807
3342
  return;
2808
3343
  }
2809
3344
  if (!this.statusUpdateState) {
2810
- logger9.debug(
3345
+ logger10.debug(
2811
3346
  { sessionId: this.sessionId },
2812
3347
  "No status updates configured for time-based check"
2813
3348
  );
@@ -2820,7 +3355,7 @@ var GraphSession = class {
2820
3355
  try {
2821
3356
  await this.generateAndSendUpdate();
2822
3357
  } catch (error) {
2823
- logger9.error(
3358
+ logger10.error(
2824
3359
  {
2825
3360
  sessionId: this.sessionId,
2826
3361
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2923,29 +3458,29 @@ var GraphSession = class {
2923
3458
  */
2924
3459
  async generateAndSendUpdate() {
2925
3460
  if (this.isEnded) {
2926
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
3461
+ logger10.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2927
3462
  return;
2928
3463
  }
2929
3464
  if (this.isTextStreaming) {
2930
- logger9.debug(
3465
+ logger10.debug(
2931
3466
  { sessionId: this.sessionId },
2932
3467
  "Text is currently streaming - skipping status update"
2933
3468
  );
2934
3469
  return;
2935
3470
  }
2936
3471
  if (this.isGeneratingUpdate) {
2937
- logger9.debug(
3472
+ logger10.debug(
2938
3473
  { sessionId: this.sessionId },
2939
3474
  "Update already in progress - skipping duplicate generation"
2940
3475
  );
2941
3476
  return;
2942
3477
  }
2943
3478
  if (!this.statusUpdateState) {
2944
- logger9.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
3479
+ logger10.warn({ sessionId: this.sessionId }, "No status update state - cannot generate update");
2945
3480
  return;
2946
3481
  }
2947
3482
  if (!this.graphId) {
2948
- logger9.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
3483
+ logger10.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2949
3484
  return;
2950
3485
  }
2951
3486
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -2957,7 +3492,7 @@ var GraphSession = class {
2957
3492
  try {
2958
3493
  const streamHelper = getStreamHelper(this.sessionId);
2959
3494
  if (!streamHelper) {
2960
- logger9.warn(
3495
+ logger10.warn(
2961
3496
  { sessionId: this.sessionId },
2962
3497
  "No stream helper found - cannot send status update"
2963
3498
  );
@@ -2977,7 +3512,7 @@ var GraphSession = class {
2977
3512
  if (result.summaries && result.summaries.length > 0) {
2978
3513
  for (const summary of result.summaries) {
2979
3514
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
2980
- logger9.warn(
3515
+ logger10.warn(
2981
3516
  {
2982
3517
  sessionId: this.sessionId,
2983
3518
  summary
@@ -3014,7 +3549,7 @@ var GraphSession = class {
3014
3549
  this.statusUpdateState.lastEventCount = this.events.length;
3015
3550
  }
3016
3551
  } catch (error) {
3017
- logger9.error(
3552
+ logger10.error(
3018
3553
  {
3019
3554
  sessionId: this.sessionId,
3020
3555
  error: error instanceof Error ? error.message : "Unknown error",
@@ -3052,7 +3587,7 @@ var GraphSession = class {
3052
3587
  this.releaseUpdateLock();
3053
3588
  }
3054
3589
  } catch (error) {
3055
- logger9.error(
3590
+ logger10.error(
3056
3591
  {
3057
3592
  sessionId: this.sessionId,
3058
3593
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3130,7 +3665,7 @@ User's Question/Context:
3130
3665
  ${conversationHistory}
3131
3666
  ` : "";
3132
3667
  } catch (error) {
3133
- logger9.warn(
3668
+ logger10.warn(
3134
3669
  { sessionId: this.sessionId, error },
3135
3670
  "Failed to fetch conversation history for structured status update"
3136
3671
  );
@@ -3140,13 +3675,13 @@ ${conversationHistory}
3140
3675
  Previous updates sent to user:
3141
3676
  ${previousSummaries.map((s, i) => `${i + 1}. ${s}`).join("\n")}
3142
3677
  ` : "";
3143
- const selectionSchema = z5.z.object(
3678
+ const selectionSchema = z6.z.object(
3144
3679
  Object.fromEntries([
3145
3680
  // Add no_relevant_updates schema
3146
3681
  [
3147
3682
  "no_relevant_updates",
3148
- z5.z.object({
3149
- no_updates: z5.z.boolean().default(true)
3683
+ z6.z.object({
3684
+ no_updates: z6.z.boolean().default(true)
3150
3685
  }).optional().describe(
3151
3686
  "Use when nothing substantially new to report. Should only use on its own."
3152
3687
  )
@@ -3264,7 +3799,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3264
3799
  return { summaries };
3265
3800
  } catch (error) {
3266
3801
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3267
- logger9.error({ error }, "Failed to generate structured update, using fallback");
3802
+ logger10.error({ error }, "Failed to generate structured update, using fallback");
3268
3803
  return { summaries: [] };
3269
3804
  } finally {
3270
3805
  span.end();
@@ -3279,8 +3814,8 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3279
3814
  if (component.detailsSchema && "properties" in component.detailsSchema) {
3280
3815
  return this.buildZodSchemaFromJson(component.detailsSchema);
3281
3816
  }
3282
- return z5.z.object({
3283
- label: z5.z.string().describe(
3817
+ return z6.z.object({
3818
+ label: z6.z.string().describe(
3284
3819
  '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.'
3285
3820
  )
3286
3821
  });
@@ -3290,56 +3825,56 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3290
3825
  */
3291
3826
  buildZodSchemaFromJson(jsonSchema) {
3292
3827
  const properties = {};
3293
- properties["label"] = z5.z.string().describe(
3828
+ properties["label"] = z6.z.string().describe(
3294
3829
  '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.'
3295
3830
  );
3296
3831
  for (const [key, value] of Object.entries(jsonSchema.properties)) {
3297
3832
  let zodType;
3298
3833
  if (value.enum && Array.isArray(value.enum)) {
3299
3834
  if (value.enum.length === 1) {
3300
- zodType = z5.z.literal(value.enum[0]);
3835
+ zodType = z6.z.literal(value.enum[0]);
3301
3836
  } else {
3302
3837
  const [first, ...rest] = value.enum;
3303
- zodType = z5.z.enum([first, ...rest]);
3838
+ zodType = z6.z.enum([first, ...rest]);
3304
3839
  }
3305
3840
  } else if (value.type === "string") {
3306
- zodType = z5.z.string();
3841
+ zodType = z6.z.string();
3307
3842
  if (value.minLength) zodType = zodType.min(value.minLength);
3308
3843
  if (value.maxLength) zodType = zodType.max(value.maxLength);
3309
3844
  if (value.format === "email") zodType = zodType.email();
3310
3845
  if (value.format === "url" || value.format === "uri")
3311
3846
  zodType = zodType.url();
3312
3847
  } else if (value.type === "number" || value.type === "integer") {
3313
- zodType = value.type === "integer" ? z5.z.number().int() : z5.z.number();
3848
+ zodType = value.type === "integer" ? z6.z.number().int() : z6.z.number();
3314
3849
  if (value.minimum !== void 0) zodType = zodType.min(value.minimum);
3315
3850
  if (value.maximum !== void 0) zodType = zodType.max(value.maximum);
3316
3851
  } else if (value.type === "boolean") {
3317
- zodType = z5.z.boolean();
3852
+ zodType = z6.z.boolean();
3318
3853
  } else if (value.type === "array") {
3319
3854
  if (value.items) {
3320
3855
  if (value.items.enum && Array.isArray(value.items.enum)) {
3321
3856
  const [first, ...rest] = value.items.enum;
3322
- zodType = z5.z.array(z5.z.enum([first, ...rest]));
3857
+ zodType = z6.z.array(z6.z.enum([first, ...rest]));
3323
3858
  } else if (value.items.type === "string") {
3324
- zodType = z5.z.array(z5.z.string());
3859
+ zodType = z6.z.array(z6.z.string());
3325
3860
  } else if (value.items.type === "number") {
3326
- zodType = z5.z.array(z5.z.number());
3861
+ zodType = z6.z.array(z6.z.number());
3327
3862
  } else if (value.items.type === "boolean") {
3328
- zodType = z5.z.array(z5.z.boolean());
3863
+ zodType = z6.z.array(z6.z.boolean());
3329
3864
  } else if (value.items.type === "object") {
3330
- zodType = z5.z.array(z5.z.record(z5.z.string(), z5.z.any()));
3865
+ zodType = z6.z.array(z6.z.record(z6.z.string(), z6.z.any()));
3331
3866
  } else {
3332
- zodType = z5.z.array(z5.z.any());
3867
+ zodType = z6.z.array(z6.z.any());
3333
3868
  }
3334
3869
  } else {
3335
- zodType = z5.z.array(z5.z.any());
3870
+ zodType = z6.z.array(z6.z.any());
3336
3871
  }
3337
3872
  if (value.minItems) zodType = zodType.min(value.minItems);
3338
3873
  if (value.maxItems) zodType = zodType.max(value.maxItems);
3339
3874
  } else if (value.type === "object") {
3340
- zodType = z5.z.record(z5.z.string(), z5.z.any());
3875
+ zodType = z6.z.record(z6.z.string(), z6.z.any());
3341
3876
  } else {
3342
- zodType = z5.z.any();
3877
+ zodType = z6.z.any();
3343
3878
  }
3344
3879
  if (value.description) {
3345
3880
  zodType = zodType.describe(value.description);
@@ -3349,7 +3884,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3349
3884
  }
3350
3885
  properties[key] = zodType;
3351
3886
  }
3352
- return z5.z.object(properties);
3887
+ return z6.z.object(properties);
3353
3888
  }
3354
3889
  /**
3355
3890
  * Extract user-visible activities with rich formatting and complete information
@@ -3409,6 +3944,9 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3409
3944
  "graph_session.id": this.sessionId,
3410
3945
  "artifact.id": artifactData.artifactId,
3411
3946
  "artifact.type": artifactData.artifactType || "unknown",
3947
+ "artifact.agent_id": artifactData.agentId || "unknown",
3948
+ "artifact.tool_call_id": artifactData.metadata?.toolCallId || "unknown",
3949
+ "artifact.data": JSON.stringify(artifactData.data, null, 2),
3412
3950
  "tenant.id": artifactData.tenantId || "unknown",
3413
3951
  "project.id": artifactData.projectId || "unknown",
3414
3952
  "context.id": artifactData.contextId || "unknown",
@@ -3459,8 +3997,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3459
3997
  Tool Context: ${toolContext ? JSON.stringify(toolContext, null, 2) : "No tool context"}
3460
3998
  Context: ${conversationHistory?.slice(-200) || "Processing"}
3461
3999
  Type: ${artifactData.artifactType || "data"}
3462
- Summary: ${JSON.stringify(artifactData.summaryProps, null, 2)}
3463
- Full: ${JSON.stringify(artifactData.fullProps, null, 2)}
4000
+ Data: ${JSON.stringify(artifactData.data || artifactData.summaryData, null, 2)}
3464
4001
 
3465
4002
  Make it specific and relevant.`;
3466
4003
  let modelToUse = this.statusUpdateState?.summarizerModel;
@@ -3478,7 +4015,7 @@ Make it specific and relevant.`;
3478
4015
  });
3479
4016
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
3480
4017
  modelToUse = agentData.models.base;
3481
- logger9.info(
4018
+ logger10.info(
3482
4019
  {
3483
4020
  sessionId: this.sessionId,
3484
4021
  artifactId: artifactData.artifactId,
@@ -3489,7 +4026,7 @@ Make it specific and relevant.`;
3489
4026
  );
3490
4027
  }
3491
4028
  } catch (error) {
3492
- logger9.warn(
4029
+ logger10.warn(
3493
4030
  {
3494
4031
  sessionId: this.sessionId,
3495
4032
  artifactId: artifactData.artifactId,
@@ -3501,7 +4038,7 @@ Make it specific and relevant.`;
3501
4038
  }
3502
4039
  }
3503
4040
  if (!modelToUse?.model?.trim()) {
3504
- logger9.warn(
4041
+ logger10.warn(
3505
4042
  {
3506
4043
  sessionId: this.sessionId,
3507
4044
  artifactId: artifactData.artifactId
@@ -3522,9 +4059,9 @@ Make it specific and relevant.`;
3522
4059
  };
3523
4060
  } else {
3524
4061
  const model = ModelFactory.createModel(modelToUse);
3525
- const schema = z5.z.object({
3526
- name: z5.z.string().describe("Concise, descriptive name for the artifact"),
3527
- description: z5.z.string().describe("Brief description of the artifact's relevance to the user's question")
4062
+ const schema = z6.z.object({
4063
+ name: z6.z.string().describe("Concise, descriptive name for the artifact"),
4064
+ description: z6.z.string().describe("Brief description of the artifact's relevance to the user's question")
3528
4065
  });
3529
4066
  const { object } = await tracer.startActiveSpan(
3530
4067
  "graph_session.generate_artifact_metadata",
@@ -3534,8 +4071,12 @@ Make it specific and relevant.`;
3534
4071
  "llm.operation": "generate_object",
3535
4072
  "artifact.id": artifactData.artifactId,
3536
4073
  "artifact.type": artifactData.artifactType,
3537
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3538
- "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
4074
+ "artifact.summary": JSON.stringify(artifactData.summaryData, null, 2),
4075
+ "artifact.full": JSON.stringify(
4076
+ artifactData.data || artifactData.summaryData,
4077
+ null,
4078
+ 2
4079
+ ),
3539
4080
  "prompt.length": prompt.length
3540
4081
  }
3541
4082
  },
@@ -3565,8 +4106,12 @@ Make it specific and relevant.`;
3565
4106
  "artifact.type": artifactData.artifactType,
3566
4107
  "artifact.name": result2.object.name,
3567
4108
  "artifact.description": result2.object.description,
3568
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3569
- "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
4109
+ "artifact.summary": JSON.stringify(artifactData.summaryData, null, 2),
4110
+ "artifact.full": JSON.stringify(
4111
+ artifactData.data || artifactData.summaryData,
4112
+ null,
4113
+ 2
4114
+ ),
3570
4115
  "generation.name_length": result2.object.name.length,
3571
4116
  "generation.description_length": result2.object.description.length,
3572
4117
  "generation.attempts": attempt
@@ -3575,7 +4120,7 @@ Make it specific and relevant.`;
3575
4120
  return result2;
3576
4121
  } catch (error) {
3577
4122
  lastError = error instanceof Error ? error : new Error(String(error));
3578
- logger9.warn(
4123
+ logger10.warn(
3579
4124
  {
3580
4125
  sessionId: this.sessionId,
3581
4126
  artifactId: artifactData.artifactId,
@@ -3615,9 +4160,9 @@ Make it specific and relevant.`;
3615
4160
  name: result.name,
3616
4161
  description: result.description,
3617
4162
  type: artifactData.artifactType || "source",
3618
- summaryProps: artifactData.summaryProps || {},
3619
- fullProps: artifactData.fullProps || {},
3620
- metadata: artifactData.metadata || {}
4163
+ data: artifactData.data || {},
4164
+ metadata: artifactData.metadata || {},
4165
+ toolCallId: artifactData.toolCallId
3621
4166
  });
3622
4167
  mainSaveSucceeded = true;
3623
4168
  span.setAttributes({
@@ -3627,7 +4172,7 @@ Make it specific and relevant.`;
3627
4172
  });
3628
4173
  span.setStatus({ code: api.SpanStatusCode.OK });
3629
4174
  } catch (saveError) {
3630
- logger9.error(
4175
+ logger10.error(
3631
4176
  {
3632
4177
  sessionId: this.sessionId,
3633
4178
  artifactId: artifactData.artifactId,
@@ -3651,11 +4196,11 @@ Make it specific and relevant.`;
3651
4196
  name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
3652
4197
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool results"}`,
3653
4198
  type: artifactData.artifactType || "source",
3654
- summaryProps: artifactData.summaryProps || {},
3655
- fullProps: artifactData.fullProps || {},
3656
- metadata: artifactData.metadata || {}
4199
+ data: artifactData.data || {},
4200
+ metadata: artifactData.metadata || {},
4201
+ toolCallId: artifactData.toolCallId
3657
4202
  });
3658
- logger9.info(
4203
+ logger10.info(
3659
4204
  {
3660
4205
  sessionId: this.sessionId,
3661
4206
  artifactId: artifactData.artifactId
@@ -3666,7 +4211,7 @@ Make it specific and relevant.`;
3666
4211
  } catch (fallbackError) {
3667
4212
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
3668
4213
  if (isDuplicateError) ; else {
3669
- logger9.error(
4214
+ logger10.error(
3670
4215
  {
3671
4216
  sessionId: this.sessionId,
3672
4217
  artifactId: artifactData.artifactId,
@@ -3679,7 +4224,7 @@ Make it specific and relevant.`;
3679
4224
  }
3680
4225
  } catch (error) {
3681
4226
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3682
- logger9.error(
4227
+ logger10.error(
3683
4228
  {
3684
4229
  sessionId: this.sessionId,
3685
4230
  artifactId: artifactData.artifactId,
@@ -3698,7 +4243,7 @@ Make it specific and relevant.`;
3698
4243
  */
3699
4244
  setArtifactCache(key, artifact) {
3700
4245
  this.artifactCache.set(key, artifact);
3701
- logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
4246
+ logger10.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3702
4247
  }
3703
4248
  /**
3704
4249
  * Get session-scoped ArtifactService instance
@@ -3717,9 +4262,17 @@ Make it specific and relevant.`;
3717
4262
  */
3718
4263
  getArtifactCache(key) {
3719
4264
  const artifact = this.artifactCache.get(key);
3720
- logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
4265
+ logger10.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3721
4266
  return artifact || null;
3722
4267
  }
4268
+ /**
4269
+ * Update artifact components in the shared ArtifactService
4270
+ */
4271
+ updateArtifactComponents(artifactComponents) {
4272
+ if (this.artifactService) {
4273
+ this.artifactService.updateArtifactComponents(artifactComponents);
4274
+ }
4275
+ }
3723
4276
  };
3724
4277
  var GraphSessionManager = class {
3725
4278
  constructor() {
@@ -3732,7 +4285,7 @@ var GraphSessionManager = class {
3732
4285
  const sessionId = messageId;
3733
4286
  const session = new GraphSession(sessionId, messageId, graphId, tenantId, projectId, contextId);
3734
4287
  this.sessions.set(sessionId, session);
3735
- logger9.info(
4288
+ logger10.info(
3736
4289
  { sessionId, messageId, graphId, tenantId, projectId, contextId },
3737
4290
  "GraphSession created"
3738
4291
  );
@@ -3746,7 +4299,7 @@ var GraphSessionManager = class {
3746
4299
  if (session) {
3747
4300
  session.initializeStatusUpdates(config, summarizerModel);
3748
4301
  } else {
3749
- logger9.error(
4302
+ logger10.error(
3750
4303
  {
3751
4304
  sessionId,
3752
4305
  availableSessions: Array.from(this.sessions.keys())
@@ -3763,7 +4316,7 @@ var GraphSessionManager = class {
3763
4316
  if (session) {
3764
4317
  session.enableEmitOperations();
3765
4318
  } else {
3766
- logger9.error(
4319
+ logger10.error(
3767
4320
  {
3768
4321
  sessionId,
3769
4322
  availableSessions: Array.from(this.sessions.keys())
@@ -3784,7 +4337,7 @@ var GraphSessionManager = class {
3784
4337
  recordEvent(sessionId, eventType, agentId, data) {
3785
4338
  const session = this.sessions.get(sessionId);
3786
4339
  if (!session) {
3787
- logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
4340
+ logger10.warn({ sessionId }, "Attempted to record event in non-existent session");
3788
4341
  return;
3789
4342
  }
3790
4343
  session.recordEvent(eventType, agentId, data);
@@ -3795,12 +4348,12 @@ var GraphSessionManager = class {
3795
4348
  endSession(sessionId) {
3796
4349
  const session = this.sessions.get(sessionId);
3797
4350
  if (!session) {
3798
- logger9.warn({ sessionId }, "Attempted to end non-existent session");
4351
+ logger10.warn({ sessionId }, "Attempted to end non-existent session");
3799
4352
  return [];
3800
4353
  }
3801
4354
  const events = session.getEvents();
3802
4355
  const summary = session.getSummary();
3803
- logger9.info({ sessionId, summary }, "GraphSession ended");
4356
+ logger10.info({ sessionId, summary }, "GraphSession ended");
3804
4357
  session.cleanup();
3805
4358
  this.sessions.delete(sessionId);
3806
4359
  return events;
@@ -3854,12 +4407,61 @@ var GraphSessionManager = class {
3854
4407
  const session = this.sessions.get(sessionId);
3855
4408
  return session ? session.getArtifactParser() : null;
3856
4409
  }
3857
- };
3858
- var graphSessionManager = new GraphSessionManager();
4410
+ /**
4411
+ * Update artifact components for a session
4412
+ */
4413
+ updateArtifactComponents(sessionId, artifactComponents) {
4414
+ const session = this.sessions.get(sessionId);
4415
+ if (session) {
4416
+ session.updateArtifactComponents(artifactComponents);
4417
+ }
4418
+ }
4419
+ };
4420
+ var graphSessionManager = new GraphSessionManager();
4421
+
4422
+ // src/utils/model-resolver.ts
4423
+ init_dbClient();
4424
+ async function resolveModelConfig(graphId, agent) {
4425
+ if (agent.models?.base?.model) {
4426
+ return {
4427
+ base: agent.models.base,
4428
+ structuredOutput: agent.models.structuredOutput || agent.models.base,
4429
+ summarizer: agent.models.summarizer || agent.models.base
4430
+ };
4431
+ }
4432
+ const graph = await agentsCore.getAgentGraphById(dbClient_default)({
4433
+ scopes: { tenantId: agent.tenantId, projectId: agent.projectId, graphId }
4434
+ });
4435
+ if (graph?.models?.base?.model) {
4436
+ return {
4437
+ base: graph.models.base,
4438
+ structuredOutput: agent.models?.structuredOutput || graph.models.structuredOutput || graph.models.base,
4439
+ summarizer: agent.models?.summarizer || graph.models.summarizer || graph.models.base
4440
+ };
4441
+ }
4442
+ const project = await agentsCore.getProject(dbClient_default)({
4443
+ scopes: { tenantId: agent.tenantId, projectId: agent.projectId }
4444
+ });
4445
+ if (project?.models?.base?.model) {
4446
+ return {
4447
+ base: project.models.base,
4448
+ structuredOutput: agent.models?.structuredOutput || project.models.structuredOutput || project.models.base,
4449
+ summarizer: agent.models?.summarizer || project.models.summarizer || project.models.base
4450
+ };
4451
+ }
4452
+ throw new Error(
4453
+ "Base model configuration is required. Please configure models at the project level."
4454
+ );
4455
+ }
4456
+
4457
+ // src/agents/Agent.ts
4458
+ init_conversations();
4459
+ init_dbClient();
4460
+ init_logger();
3859
4461
 
3860
4462
  // src/services/IncrementalStreamParser.ts
3861
4463
  init_logger();
3862
- var logger10 = agentsCore.getLogger("IncrementalStreamParser");
4464
+ var logger11 = agentsCore.getLogger("IncrementalStreamParser");
3863
4465
  var _IncrementalStreamParser = class _IncrementalStreamParser {
3864
4466
  // Max number of collected parts to prevent unbounded growth
3865
4467
  constructor(streamHelper, tenantId, contextId, artifactParserOptions) {
@@ -3888,9 +4490,20 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3888
4490
  return;
3889
4491
  }
3890
4492
  }
4493
+ let sharedArtifactService = null;
4494
+ if (artifactParserOptions?.streamRequestId && typeof graphSessionManager.getArtifactService === "function") {
4495
+ try {
4496
+ sharedArtifactService = graphSessionManager.getArtifactService(
4497
+ artifactParserOptions.streamRequestId
4498
+ );
4499
+ } catch (error) {
4500
+ }
4501
+ }
3891
4502
  this.artifactParser = new ArtifactParser(tenantId, {
3892
4503
  ...artifactParserOptions,
3893
- contextId
4504
+ contextId,
4505
+ artifactService: sharedArtifactService
4506
+ // Use shared ArtifactService if available
3894
4507
  });
3895
4508
  }
3896
4509
  /**
@@ -3900,7 +4513,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3900
4513
  async initializeArtifactMap() {
3901
4514
  try {
3902
4515
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
3903
- logger10.debug(
4516
+ logger11.debug(
3904
4517
  {
3905
4518
  contextId: this.contextId,
3906
4519
  artifactMapSize: this.artifactMap.size
@@ -3908,7 +4521,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3908
4521
  "Initialized artifact map for streaming"
3909
4522
  );
3910
4523
  } catch (error) {
3911
- logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4524
+ logger11.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3912
4525
  this.artifactMap = /* @__PURE__ */ new Map();
3913
4526
  }
3914
4527
  }
@@ -4005,9 +4618,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4005
4618
  * Note: Text components are handled separately with incremental streaming
4006
4619
  */
4007
4620
  async streamComponent(component) {
4008
- const parts = await this.artifactParser.parseObject({
4009
- dataComponents: [component]
4010
- }, this.artifactMap, this.agentId);
4621
+ const parts = await this.artifactParser.parseObject(
4622
+ {
4623
+ dataComponents: [component]
4624
+ },
4625
+ this.artifactMap,
4626
+ this.agentId
4627
+ );
4011
4628
  if (!Array.isArray(parts)) {
4012
4629
  console.warn("parseObject returned non-array:", parts);
4013
4630
  return;
@@ -4077,9 +4694,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4077
4694
  const componentKey = component.id;
4078
4695
  const hasBeenStreamed = this.lastStreamedComponents.has(componentKey);
4079
4696
  if (!hasBeenStreamed && this.isComponentComplete(component) && component.name !== "Text") {
4080
- const parts = await this.artifactParser.parseObject({
4081
- dataComponents: [component]
4082
- }, this.artifactMap, this.agentId);
4697
+ const parts = await this.artifactParser.parseObject(
4698
+ {
4699
+ dataComponents: [component]
4700
+ },
4701
+ this.artifactMap,
4702
+ this.agentId
4703
+ );
4083
4704
  for (const part of parts) {
4084
4705
  await this.streamPart(part);
4085
4706
  }
@@ -4144,7 +4765,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4144
4765
  remainingBuffer: workingBuffer
4145
4766
  };
4146
4767
  }
4147
- const parts = await this.artifactParser.parseText(workingBuffer, this.artifactMap, this.agentId);
4768
+ const parts = await this.artifactParser.parseText(
4769
+ workingBuffer,
4770
+ this.artifactMap,
4771
+ this.agentId
4772
+ );
4148
4773
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
4149
4774
  const lastPart = parts[parts.length - 1];
4150
4775
  const lastText = lastPart.text || "";
@@ -4217,20 +4842,35 @@ var IncrementalStreamParser = _IncrementalStreamParser;
4217
4842
 
4218
4843
  // src/services/ResponseFormatter.ts
4219
4844
  init_logger();
4220
- var logger11 = agentsCore.getLogger("ResponseFormatter");
4845
+ var logger12 = agentsCore.getLogger("ResponseFormatter");
4221
4846
  var ResponseFormatter = class {
4222
4847
  constructor(tenantId, artifactParserOptions) {
4223
4848
  __publicField(this, "artifactParser");
4224
4849
  __publicField(this, "agentId");
4225
4850
  this.agentId = artifactParserOptions?.agentId;
4226
4851
  if (artifactParserOptions?.streamRequestId) {
4227
- const sessionParser = graphSessionManager.getArtifactParser(artifactParserOptions.streamRequestId);
4852
+ const sessionParser = graphSessionManager.getArtifactParser(
4853
+ artifactParserOptions.streamRequestId
4854
+ );
4228
4855
  if (sessionParser) {
4229
4856
  this.artifactParser = sessionParser;
4230
4857
  return;
4231
4858
  }
4232
4859
  }
4233
- this.artifactParser = new ArtifactParser(tenantId, artifactParserOptions);
4860
+ let sharedArtifactService = null;
4861
+ if (artifactParserOptions?.streamRequestId && typeof graphSessionManager.getArtifactService === "function") {
4862
+ try {
4863
+ sharedArtifactService = graphSessionManager.getArtifactService(
4864
+ artifactParserOptions.streamRequestId
4865
+ );
4866
+ } catch (error) {
4867
+ }
4868
+ }
4869
+ this.artifactParser = new ArtifactParser(tenantId, {
4870
+ ...artifactParserOptions,
4871
+ artifactService: sharedArtifactService
4872
+ // Use shared ArtifactService if available
4873
+ });
4234
4874
  }
4235
4875
  /**
4236
4876
  * Process structured object response and replace artifact markers with actual artifacts
@@ -4243,7 +4883,11 @@ var ResponseFormatter = class {
4243
4883
  "response.type": "object",
4244
4884
  "response.availableArtifacts": artifactMap.size
4245
4885
  });
4246
- const parts = await this.artifactParser.parseObject(responseObject, artifactMap, this.agentId);
4886
+ const parts = await this.artifactParser.parseObject(
4887
+ responseObject,
4888
+ artifactMap,
4889
+ this.agentId
4890
+ );
4247
4891
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
4248
4892
  span.setAttributes({
4249
4893
  "response.dataPartsCount": parts.length,
@@ -4257,7 +4901,7 @@ var ResponseFormatter = class {
4257
4901
  return { parts };
4258
4902
  } catch (error) {
4259
4903
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4260
- logger11.error({ error, responseObject }, "Error formatting object response");
4904
+ logger12.error({ error, responseObject }, "Error formatting object response");
4261
4905
  return {
4262
4906
  parts: [{ kind: "data", data: responseObject }]
4263
4907
  };
@@ -4309,7 +4953,7 @@ var ResponseFormatter = class {
4309
4953
  return { parts };
4310
4954
  } catch (error) {
4311
4955
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4312
- logger11.error({ error, responseText }, "Error formatting response");
4956
+ logger12.error({ error, responseText }, "Error formatting response");
4313
4957
  return { text: responseText };
4314
4958
  } finally {
4315
4959
  span.end();
@@ -4391,11 +5035,11 @@ init_logger();
4391
5035
 
4392
5036
  // src/utils/data-component-schema.ts
4393
5037
  init_logger();
4394
- var logger12 = agentsCore.getLogger("DataComponentSchema");
5038
+ var logger13 = agentsCore.getLogger("DataComponentSchema");
4395
5039
  function jsonSchemaToZod(jsonSchema) {
4396
5040
  if (!jsonSchema || typeof jsonSchema !== "object") {
4397
- logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
4398
- return z5.z.string();
5041
+ logger13.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
5042
+ return z6.z.string();
4399
5043
  }
4400
5044
  switch (jsonSchema.type) {
4401
5045
  case "object":
@@ -4404,31 +5048,31 @@ function jsonSchemaToZod(jsonSchema) {
4404
5048
  for (const [key, prop] of Object.entries(jsonSchema.properties)) {
4405
5049
  shape[key] = jsonSchemaToZod(prop);
4406
5050
  }
4407
- return z5.z.object(shape);
5051
+ return z6.z.object(shape);
4408
5052
  }
4409
- return z5.z.record(z5.z.string(), z5.z.unknown());
5053
+ return z6.z.record(z6.z.string(), z6.z.unknown());
4410
5054
  case "array": {
4411
- const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z5.z.unknown();
4412
- return z5.z.array(itemSchema);
5055
+ const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z6.z.unknown();
5056
+ return z6.z.array(itemSchema);
4413
5057
  }
4414
5058
  case "string":
4415
- return z5.z.string();
5059
+ return z6.z.string();
4416
5060
  case "number":
4417
5061
  case "integer":
4418
- return z5.z.number();
5062
+ return z6.z.number();
4419
5063
  case "boolean":
4420
- return z5.z.boolean();
5064
+ return z6.z.boolean();
4421
5065
  case "null":
4422
- return z5.z.null();
5066
+ return z6.z.null();
4423
5067
  default:
4424
- logger12.warn(
5068
+ logger13.warn(
4425
5069
  {
4426
5070
  unsupportedType: jsonSchema.type,
4427
5071
  schema: jsonSchema
4428
5072
  },
4429
5073
  "Unsupported JSON schema type, using unknown validation"
4430
5074
  );
4431
- return z5.z.unknown();
5075
+ return z6.z.unknown();
4432
5076
  }
4433
5077
  }
4434
5078
 
@@ -4656,9 +5300,9 @@ var _ArtifactReferenceSchema = class _ArtifactReferenceSchema {
4656
5300
  * Get the standard Zod schema for artifact reference components
4657
5301
  */
4658
5302
  static getSchema() {
4659
- return z5.z.object({
4660
- id: z5.z.string(),
4661
- name: z5.z.literal("Artifact"),
5303
+ return z6.z.object({
5304
+ id: z6.z.string(),
5305
+ name: z6.z.literal("Artifact"),
4662
5306
  props: jsonSchemaToZod(_ArtifactReferenceSchema.ARTIFACT_PROPS_SCHEMA)
4663
5307
  });
4664
5308
  }
@@ -4700,8 +5344,7 @@ var ArtifactCreateSchema = class {
4700
5344
  */
4701
5345
  static getSchemas(artifactComponents) {
4702
5346
  return artifactComponents.map((component) => {
4703
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4704
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
5347
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4705
5348
  const propsSchema = {
4706
5349
  type: "object",
4707
5350
  properties: {
@@ -4720,16 +5363,15 @@ var ArtifactCreateSchema = class {
4720
5363
  },
4721
5364
  base_selector: {
4722
5365
  type: "string",
4723
- description: `JMESPath selector starting with "result." to navigate to ONE specific item. Summary/full props will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']"). EXAMPLE: For JSON {"result":{"structuredContent":{"content":[{"type":"document","title":"Guide"}]}}} - WRONG: "result.content[?type=='document']" (skips structuredContent) - RIGHT: "result.structuredContent.content[?type=='document']".`
5366
+ description: `JMESPath selector starting with "result." to navigate to ONE specific item. Details selector will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']").`
4724
5367
  },
4725
- summary_props: enhancedSummaryProps,
4726
- full_props: enhancedFullProps
5368
+ details_selector: enhancedSchema
4727
5369
  },
4728
5370
  required: ["id", "tool_call_id", "type", "base_selector"]
4729
5371
  };
4730
- return z5.z.object({
4731
- id: z5.z.string(),
4732
- name: z5.z.literal(`ArtifactCreate_${component.name}`),
5372
+ return z6.z.object({
5373
+ id: z6.z.string(),
5374
+ name: z6.z.literal(`ArtifactCreate_${component.name}`),
4733
5375
  props: jsonSchemaToZod(propsSchema)
4734
5376
  });
4735
5377
  });
@@ -4741,8 +5383,7 @@ var ArtifactCreateSchema = class {
4741
5383
  */
4742
5384
  static getDataComponents(tenantId, projectId = "", artifactComponents) {
4743
5385
  return artifactComponents.map((component) => {
4744
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4745
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
5386
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4746
5387
  const propsSchema = {
4747
5388
  type: "object",
4748
5389
  properties: {
@@ -4761,10 +5402,9 @@ var ArtifactCreateSchema = class {
4761
5402
  },
4762
5403
  base_selector: {
4763
5404
  type: "string",
4764
- description: `JMESPath selector starting with "result." to navigate to ONE specific item. Summary/full props will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']"). EXAMPLE: For JSON {"result":{"structuredContent":{"content":[{"type":"document","title":"Guide"}]}}} - WRONG: "result.content[?type=='document']" (skips structuredContent) - RIGHT: "result.structuredContent.content[?type=='document']".`
5405
+ description: `JMESPath selector starting with "result." to navigate to ONE specific item. Details selector will be relative to this selection. Use filtering to avoid arrays (e.g., "result.items[?type=='guide']").`
4765
5406
  },
4766
- summary_props: enhancedSummaryProps,
4767
- full_props: enhancedFullProps
5407
+ details_selector: enhancedSchema
4768
5408
  },
4769
5409
  required: ["id", "tool_call_id", "type", "base_selector"]
4770
5410
  };
@@ -4792,7 +5432,7 @@ function parseEmbeddedJson(data) {
4792
5432
 
4793
5433
  // src/a2a/client.ts
4794
5434
  init_logger();
4795
- var logger13 = agentsCore.getLogger("a2aClient");
5435
+ var logger14 = agentsCore.getLogger("a2aClient");
4796
5436
  var DEFAULT_BACKOFF = {
4797
5437
  initialInterval: 500,
4798
5438
  maxInterval: 6e4,
@@ -4998,7 +5638,7 @@ var A2AClient = class {
4998
5638
  try {
4999
5639
  const res = await fn();
5000
5640
  if (attempt > 0) {
5001
- logger13.info(
5641
+ logger14.info(
5002
5642
  {
5003
5643
  attempts: attempt + 1,
5004
5644
  elapsedTime: Date.now() - start
@@ -5013,7 +5653,7 @@ var A2AClient = class {
5013
5653
  }
5014
5654
  const elapsed = Date.now() - start;
5015
5655
  if (elapsed > maxElapsedTime) {
5016
- logger13.warn(
5656
+ logger14.warn(
5017
5657
  {
5018
5658
  attempts: attempt + 1,
5019
5659
  elapsedTime: elapsed,
@@ -5034,7 +5674,7 @@ var A2AClient = class {
5034
5674
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
5035
5675
  }
5036
5676
  const delayMs = Math.min(retryInterval, maxInterval);
5037
- logger13.info(
5677
+ logger14.info(
5038
5678
  {
5039
5679
  attempt: attempt + 1,
5040
5680
  delayMs,
@@ -5119,7 +5759,7 @@ var A2AClient = class {
5119
5759
  }
5120
5760
  const rpcResponse = await httpResponse.json();
5121
5761
  if (rpcResponse.id !== requestId2) {
5122
- logger13.warn(
5762
+ logger14.warn(
5123
5763
  {
5124
5764
  method,
5125
5765
  expectedId: requestId2,
@@ -5318,7 +5958,7 @@ var A2AClient = class {
5318
5958
  try {
5319
5959
  while (true) {
5320
5960
  const { done, value } = await reader.read();
5321
- logger13.info({ done, value }, "parseA2ASseStream");
5961
+ logger14.info({ done, value }, "parseA2ASseStream");
5322
5962
  if (done) {
5323
5963
  if (eventDataBuffer.trim()) {
5324
5964
  const result = this._processSseEventData(
@@ -5408,7 +6048,7 @@ var A2AClient = class {
5408
6048
  init_conversations();
5409
6049
  init_dbClient();
5410
6050
  init_logger();
5411
- var logger14 = agentsCore.getLogger("relationships Tools");
6051
+ var logger15 = agentsCore.getLogger("relationships Tools");
5412
6052
  var generateTransferToolDescription = (config) => {
5413
6053
  return `Hand off the conversation to agent ${config.id}.
5414
6054
 
@@ -5437,7 +6077,7 @@ var createTransferToAgentTool = ({
5437
6077
  }) => {
5438
6078
  return ai.tool({
5439
6079
  description: generateTransferToolDescription(transferConfig),
5440
- inputSchema: z5__default.default.object({}),
6080
+ inputSchema: z6__default.default.object({}),
5441
6081
  execute: async () => {
5442
6082
  const activeSpan = api.trace.getActiveSpan();
5443
6083
  if (activeSpan) {
@@ -5446,7 +6086,7 @@ var createTransferToAgentTool = ({
5446
6086
  "transfer.to_agent_id": transferConfig.id ?? "unknown"
5447
6087
  });
5448
6088
  }
5449
- logger14.info(
6089
+ logger15.info(
5450
6090
  {
5451
6091
  transferTo: transferConfig.id ?? "unknown",
5452
6092
  fromAgent: callingAgentId
@@ -5483,7 +6123,7 @@ function createDelegateToAgentTool({
5483
6123
  }) {
5484
6124
  return ai.tool({
5485
6125
  description: generateDelegateToolDescription(delegateConfig.config),
5486
- inputSchema: z5__default.default.object({ message: z5__default.default.string() }),
6126
+ inputSchema: z6__default.default.object({ message: z6__default.default.string() }),
5487
6127
  execute: async (input, context) => {
5488
6128
  const delegationId = `del_${nanoid.nanoid()}`;
5489
6129
  const activeSpan = api.trace.getActiveSpan();
@@ -5595,7 +6235,7 @@ function createDelegateToAgentTool({
5595
6235
  ...isInternal ? { fromAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
5596
6236
  }
5597
6237
  };
5598
- logger14.info({ messageToSend }, "messageToSend");
6238
+ logger15.info({ messageToSend }, "messageToSend");
5599
6239
  await agentsCore.createMessage(dbClient_default)({
5600
6240
  id: nanoid.nanoid(),
5601
6241
  tenantId,
@@ -5658,7 +6298,7 @@ function createDelegateToAgentTool({
5658
6298
 
5659
6299
  // src/agents/SystemPromptBuilder.ts
5660
6300
  init_logger();
5661
- var logger15 = agentsCore.getLogger("SystemPromptBuilder");
6301
+ var logger16 = agentsCore.getLogger("SystemPromptBuilder");
5662
6302
  var SystemPromptBuilder = class {
5663
6303
  constructor(version, versionConfig) {
5664
6304
  this.version = version;
@@ -5674,12 +6314,12 @@ var SystemPromptBuilder = class {
5674
6314
  this.templates.set(name, content);
5675
6315
  }
5676
6316
  this.loaded = true;
5677
- logger15.debug(
6317
+ logger16.debug(
5678
6318
  { templateCount: this.templates.size, version: this.version },
5679
6319
  `Loaded ${this.templates.size} templates for version ${this.version}`
5680
6320
  );
5681
6321
  } catch (error) {
5682
- logger15.error({ error }, `Failed to load templates for version ${this.version}`);
6322
+ logger16.error({ error }, `Failed to load templates for version ${this.version}`);
5683
6323
  throw new Error(`Template loading failed: ${error}`);
5684
6324
  }
5685
6325
  }
@@ -5704,68 +6344,6 @@ var SystemPromptBuilder = class {
5704
6344
  }
5705
6345
  };
5706
6346
 
5707
- // templates/v1/shared/artifact.xml?raw
5708
- var artifact_default = "<artifact>\n <name>{{ARTIFACT_NAME}}</name>\n <description>{{ARTIFACT_DESCRIPTION}}</description>\n <task_id>{{TASK_ID}}</task_id>\n <artifact_id>{{ARTIFACT_ID}}</artifact_id>\n <tool_call_id>{{TOOL_CALL_ID}}</tool_call_id>\n <summary_data>{{ARTIFACT_SUMMARY}}</summary_data>\n</artifact> ";
5709
-
5710
- // templates/v1/shared/artifact-retrieval-guidance.xml?raw
5711
- var artifact_retrieval_guidance_default = `ARTIFACT RETRIEVAL: ACCESSING EXISTING ARTIFACT DATA
5712
-
5713
- \u{1F6A8} **CRITICAL: ALWAYS CHECK EXISTING ARTIFACTS FIRST** \u{1F6A8}
5714
- Before creating new artifacts, ALWAYS examine existing artifacts to see if they contain relevant information for the current topic or question.
5715
-
5716
- You CAN and SHOULD retrieve information from existing artifacts to answer user questions.
5717
- Available artifacts contain structured data that you can access in two ways:
5718
-
5719
- 1. **SUMMARY DATA**: Read the summary_data directly from available artifacts for basic information
5720
- 2. **FULL DATA**: Use the get_artifact tool to retrieve complete artifact data (both summary_data and full_data) when you need detailed information
5721
-
5722
- **REUSE EXISTING ARTIFACTS WHEN POSSIBLE:**
5723
- - Look for artifacts with similar topics, names, or descriptions
5724
- - Check if existing artifacts can answer the current question
5725
- - Use existing artifact data instead of creating duplicates
5726
- - Only create new artifacts if existing ones don't contain the needed information
5727
- - Prioritize reusing relevant existing artifacts over creating new ones
5728
-
5729
- HOW TO USE ARTIFACT DATA:
5730
- - Read summary_data from available artifacts for quick answers
5731
- - Use get_artifact tool when you need comprehensive details
5732
- - Extract specific information to answer user questions accurately
5733
- - Reference artifacts when citing the information source
5734
- - Combine information from multiple existing artifacts when relevant
5735
-
5736
- \u{1F6A8} **MANDATORY CITATION POLICY** \u{1F6A8}
5737
- EVERY piece of information from existing artifacts MUST be properly cited:
5738
- - When referencing information from existing artifacts = MUST cite with artifact reference
5739
- - When discussing artifact data = MUST cite the artifact source
5740
- - When using artifact information = MUST reference the artifact
5741
- - NO INFORMATION from existing artifacts can be presented without proper citation
5742
-
5743
- CITATION PLACEMENT RULES:
5744
- - ALWAYS place artifact citations AFTER complete thoughts and punctuation
5745
- - Never interrupt a sentence or thought with an artifact citation
5746
- - Complete your sentence or thought, add punctuation, THEN add the citation
5747
- - This maintains natural reading flow and professional presentation
5748
-
5749
- \u2705 CORRECT EXAMPLES:
5750
- - "The API uses OAuth 2.0 authentication. <artifact:create id='auth-doc' ...> This process involves three main steps..."
5751
- - "Based on the documentation, there are several authentication methods available. <artifact:create id='auth-methods' ...> The recommended approach is OAuth 2.0."
5752
-
5753
- \u274C WRONG EXAMPLES:
5754
- - "The API uses <artifact:create id='auth-doc' ...> OAuth 2.0 authentication which involves..."
5755
- - "According to <artifact:create id='auth-doc' ...>, the authentication method is OAuth 2.0."
5756
-
5757
- \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
5758
-
5759
- DELEGATION AND ARTIFACTS:
5760
- When you use delegation tools, the response may include artifacts in the parts array. These appear as objects with:
5761
- - kind: "data"
5762
- - data: { artifactId, toolCallId, name, description, type, artifactSummary }
5763
-
5764
- These artifacts become immediately available for you to reference using the artifactId and toolCallId from the response.
5765
- Present delegation results naturally without mentioning the delegation process itself.
5766
-
5767
- IMPORTANT: All agents can retrieve and use information from existing artifacts when the graph has artifact components, regardless of whether the individual agent can create new artifacts.`;
5768
-
5769
6347
  // templates/v1/phase1/system-prompt.xml?raw
5770
6348
  var system_prompt_default = `<system_message>
5771
6349
  <agent_identity>
@@ -5882,6 +6460,68 @@ var thinking_preparation_default = `<thinking_preparation_mode>
5882
6460
  // templates/v1/phase1/tool.xml?raw
5883
6461
  var tool_default = "<tool>\n <name>{{TOOL_NAME}}</name>\n <description>{{TOOL_DESCRIPTION}}</description>\n <parameters>\n <schema>\n {{TOOL_PARAMETERS_SCHEMA}}\n </schema>\n </parameters>\n <usage_guidelines>\n {{TOOL_USAGE_GUIDELINES}}\n </usage_guidelines>\n</tool> ";
5884
6462
 
6463
+ // templates/v1/shared/artifact.xml?raw
6464
+ var artifact_default = "<artifact>\n <name>{{ARTIFACT_NAME}}</name>\n <description>{{ARTIFACT_DESCRIPTION}}</description>\n <task_id>{{TASK_ID}}</task_id>\n <artifact_id>{{ARTIFACT_ID}}</artifact_id>\n <tool_call_id>{{TOOL_CALL_ID}}</tool_call_id>\n <summary_data>{{ARTIFACT_SUMMARY}}</summary_data>\n <!-- NOTE: This shows summary/preview data only. Use get_reference_artifact tool to get complete artifact data if needed. -->\n</artifact> ";
6465
+
6466
+ // templates/v1/shared/artifact-retrieval-guidance.xml?raw
6467
+ var artifact_retrieval_guidance_default = `ARTIFACT RETRIEVAL: ACCESSING EXISTING ARTIFACT DATA
6468
+
6469
+ \u{1F6A8} **CRITICAL: ALWAYS CHECK EXISTING ARTIFACTS FIRST** \u{1F6A8}
6470
+ Before creating new artifacts, ALWAYS examine existing artifacts to see if they contain relevant information for the current topic or question.
6471
+
6472
+ You CAN and SHOULD retrieve information from existing artifacts to answer user questions.
6473
+ Available artifacts contain structured data that you can access in two ways:
6474
+
6475
+ 1. **SUMMARY DATA**: Read the summary_data directly from available artifacts for basic information
6476
+ 2. **FULL DATA**: Use the get_artifact tool to retrieve complete artifact data (both summary_data and full_data) when you need detailed information
6477
+
6478
+ **REUSE EXISTING ARTIFACTS WHEN POSSIBLE:**
6479
+ - Look for artifacts with similar topics, names, or descriptions
6480
+ - Check if existing artifacts can answer the current question
6481
+ - Use existing artifact data instead of creating duplicates
6482
+ - Only create new artifacts if existing ones don't contain the needed information
6483
+ - Prioritize reusing relevant existing artifacts over creating new ones
6484
+
6485
+ HOW TO USE ARTIFACT DATA:
6486
+ - Read summary_data from available artifacts for quick answers
6487
+ - Use get_artifact tool when you need comprehensive details
6488
+ - Extract specific information to answer user questions accurately
6489
+ - Reference artifacts when citing the information source
6490
+ - Combine information from multiple existing artifacts when relevant
6491
+
6492
+ \u{1F6A8} **MANDATORY CITATION POLICY** \u{1F6A8}
6493
+ EVERY piece of information from existing artifacts MUST be properly cited:
6494
+ - When referencing information from existing artifacts = MUST cite with artifact reference
6495
+ - When discussing artifact data = MUST cite the artifact source
6496
+ - When using artifact information = MUST reference the artifact
6497
+ - NO INFORMATION from existing artifacts can be presented without proper citation
6498
+
6499
+ CITATION PLACEMENT RULES:
6500
+ - ALWAYS place artifact citations AFTER complete thoughts and punctuation
6501
+ - Never interrupt a sentence or thought with an artifact citation
6502
+ - Complete your sentence or thought, add punctuation, THEN add the citation
6503
+ - This maintains natural reading flow and professional presentation
6504
+
6505
+ \u2705 CORRECT EXAMPLES:
6506
+ - "The API uses OAuth 2.0 authentication. <artifact:create id='auth-doc' ...> This process involves three main steps..."
6507
+ - "Based on the documentation, there are several authentication methods available. <artifact:create id='auth-methods' ...> The recommended approach is OAuth 2.0."
6508
+
6509
+ \u274C WRONG EXAMPLES:
6510
+ - "The API uses <artifact:create id='auth-doc' ...> OAuth 2.0 authentication which involves..."
6511
+ - "According to <artifact:create id='auth-doc' ...>, the authentication method is OAuth 2.0."
6512
+
6513
+ \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
6514
+
6515
+ DELEGATION AND ARTIFACTS:
6516
+ When you use delegation tools, the response may include artifacts in the parts array. These appear as objects with:
6517
+ - kind: "data"
6518
+ - data: { artifactId, toolCallId, name, description, type, artifactSummary }
6519
+
6520
+ These artifacts become immediately available for you to reference using the artifactId and toolCallId from the response.
6521
+ Present delegation results naturally without mentioning the delegation process itself.
6522
+
6523
+ IMPORTANT: All agents can retrieve and use information from existing artifacts when the graph has artifact components, regardless of whether the individual agent can create new artifacts.`;
6524
+
5885
6525
  // src/agents/versions/v1/Phase1Config.ts
5886
6526
  init_logger();
5887
6527
  agentsCore.getLogger("Phase1Config");
@@ -6018,8 +6658,8 @@ SELECTOR REQUIREMENTS:
6018
6658
 
6019
6659
  CRITICAL: SELECTOR HIERARCHY
6020
6660
  - base_selector: Points to ONE specific item in the tool result
6021
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
6022
- - Example: If base="result.documents[?type=='api']" then summary_props uses "title" not "documents[0].title"
6661
+ - details_selector: Contains JMESPath selectors RELATIVE to the base selector
6662
+ - Example: If base="result.documents[?type=='api']" then details_selector uses "title" not "documents[0].title"
6023
6663
 
6024
6664
  COMMON FAILURE POINTS (AVOID THESE):
6025
6665
  1. **Array Selection**: result.items (returns array) \u274C
@@ -6051,24 +6691,22 @@ You will create and reference artifacts using inline annotations in your text re
6051
6691
 
6052
6692
  CREATING ARTIFACTS (SERVES AS CITATION):
6053
6693
  Use the artifact:create annotation to extract data from tool results. The creation itself serves as a citation.
6054
- Format: <artifact:create id="unique-id" tool="tool_call_id" type="TypeName" base="selector.path" summary='{"key":"jmespath_selector"}' full='{"key":"jmespath_selector"}' />
6694
+ Format: <artifact:create id="unique-id" tool="tool_call_id" type="TypeName" base="selector.path" details='{"key":"jmespath_selector"}' />
6055
6695
 
6056
- \u{1F6A8} CRITICAL: SUMMARY AND FULL PROPS USE JMESPATH SELECTORS, NOT LITERAL VALUES! \u{1F6A8}
6696
+ \u{1F6A8} CRITICAL: DETAILS PROPS USE JMESPATH SELECTORS, NOT LITERAL VALUES! \u{1F6A8}
6057
6697
 
6058
6698
  \u274C WRONG - Using literal values:
6059
- summary='{"title":"API Documentation","type":"guide"}'
6060
- full='{"description":"This is a comprehensive guide..."}'
6699
+ details='{"title":"API Documentation","type":"guide"}'
6061
6700
 
6062
6701
  \u2705 CORRECT - Using JMESPath selectors (relative to base selector):
6063
- summary='{"title":"metadata.title","doc_type":"document_type"}'
6064
- full='{"description":"content.description","main_text":"content.text","author":"metadata.author"}'
6702
+ details='{"title":"metadata.title","doc_type":"document_type","description":"content.description","main_text":"content.text","author":"metadata.author"}'
6065
6703
 
6066
6704
  The selectors extract actual field values from the data structure selected by your base selector.
6067
6705
 
6068
- THE summary AND full PROPERTIES MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE TOOL RESULT!
6069
- - summary: Contains JMESPath selectors relative to the base selector
6070
- - full: Contains JMESPath selectors relative to the base selector
6706
+ THE details PROPERTY MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE TOOL RESULT!
6707
+ - details: Contains JMESPath selectors relative to the base selector that map to artifact schema fields
6071
6708
  - These selectors are evaluated against the tool result to extract the actual values
6709
+ - The system automatically determines which fields are preview vs full based on the artifact schema
6072
6710
  - NEVER put literal values like "Inkeep" or "2023" - always use selectors like "metadata.company" or "founded_year"
6073
6711
 
6074
6712
  \u{1F6AB} FORBIDDEN JMESPATH PATTERNS:
@@ -6128,7 +6766,7 @@ Only use artifact:ref when you need to cite the SAME artifact again for a differ
6128
6766
  Format: <artifact:ref id="artifact-id" tool="tool_call_id" />
6129
6767
 
6130
6768
  EXAMPLE TEXT RESPONSE:
6131
- "I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base='result.documents[?type=="auth"]' summary='{"title":"metadata.title","endpoint":"api.endpoint"}' full='{"description":"content.description","parameters":"spec.parameters","examples":"examples.sample_code"}' /> The documentation explains OAuth 2.0 implementation in detail.
6769
+ "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.
6132
6770
 
6133
6771
  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."
6134
6772
 
@@ -6184,31 +6822,29 @@ IMPORTANT GUIDELINES:
6184
6822
  return "";
6185
6823
  }
6186
6824
  const typeDescriptions = artifactComponents.map((ac) => {
6187
- let summarySchema = "No schema defined";
6188
- let fullSchema = "No schema defined";
6189
- if (ac.summaryProps?.properties) {
6190
- const summaryDetails = Object.entries(ac.summaryProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
6191
- summarySchema = `Required: ${summaryDetails}`;
6192
- }
6193
- if (ac.fullProps?.properties) {
6194
- const fullDetails = Object.entries(ac.fullProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
6195
- fullSchema = `Available: ${fullDetails}`;
6825
+ let schemaDescription = "No schema defined";
6826
+ if (ac.props?.properties) {
6827
+ const fieldDetails = Object.entries(ac.props.properties).map(([key, value]) => {
6828
+ const inPreview = value.inPreview ? " [PREVIEW]" : " [FULL]";
6829
+ return `${key} (${value.description || value.type || "field"})${inPreview}`;
6830
+ }).join(", ");
6831
+ schemaDescription = `Fields: ${fieldDetails}`;
6196
6832
  }
6197
6833
  return ` - "${ac.name}": ${ac.description || "No description available"}
6198
- Summary Props: ${summarySchema}
6199
- Full Props: ${fullSchema}`;
6834
+ ${schemaDescription}`;
6200
6835
  }).join("\n\n");
6201
6836
  return `
6202
6837
  AVAILABLE ARTIFACT TYPES:
6203
6838
 
6204
6839
  ${typeDescriptions}
6205
6840
 
6206
- \u{1F6A8} CRITICAL: SUMMARY AND FULL PROPS MUST MATCH THE ARTIFACT SCHEMA! \u{1F6A8}
6841
+ \u{1F6A8} CRITICAL: DETAILS PROPS MUST MATCH THE ARTIFACT SCHEMA! \u{1F6A8}
6207
6842
  - Only use property names that are defined in the artifact component schema above
6208
6843
  - Do NOT make up arbitrary property names like "founders", "nick_details", "year"
6209
- - Each artifact type has specific required fields in summaryProps and available fields in fullProps
6844
+ - Each artifact type has specific fields defined in its schema
6210
6845
  - Your JMESPath selectors must extract values for these exact schema-defined properties
6211
- - Example: If schema defines "title" and "url", use summary='{"title":"title","url":"url"}' not made-up names
6846
+ - Example: If schema defines "title" and "url", use details='{"title":"title","url":"url"}' not made-up names
6847
+ - The system will automatically determine which fields are preview vs full based on schema configuration
6212
6848
 
6213
6849
  \u{1F6A8} CRITICAL: USE EXACT ARTIFACT TYPE NAMES IN QUOTES! \u{1F6A8}
6214
6850
  - MUST use the exact type name shown in quotes above
@@ -6219,7 +6855,11 @@ ${typeDescriptions}
6219
6855
  }
6220
6856
  generateArtifactsSection(templates, artifacts, hasArtifactComponents = false, artifactComponents, hasGraphArtifactComponents) {
6221
6857
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
6222
- const rules = this.getArtifactReferencingRules(hasArtifactComponents, templates, shouldShowReferencingRules);
6858
+ const rules = this.getArtifactReferencingRules(
6859
+ hasArtifactComponents,
6860
+ templates,
6861
+ shouldShowReferencingRules
6862
+ );
6223
6863
  const creationInstructions = this.getArtifactCreationInstructions(
6224
6864
  hasArtifactComponents,
6225
6865
  artifactComponents
@@ -6314,6 +6954,12 @@ ${propertiesXml}
6314
6954
  }
6315
6955
  };
6316
6956
 
6957
+ // templates/v1/phase2/data-component.xml?raw
6958
+ var data_component_default = "<data-component>\n <name>{{COMPONENT_NAME}}</name>\n <description>{{COMPONENT_DESCRIPTION}}</description>\n <props>\n <schema>\n {{COMPONENT_PROPS_SCHEMA}}\n </schema>\n </props>\n</data-component> ";
6959
+
6960
+ // templates/v1/phase2/data-components.xml?raw
6961
+ var data_components_default = '<data_components_section description="These are the data components available for you to use in generating responses. Each component represents a single structured piece of information. You can create multiple instances of the same component type when needed.\n\n***MANDATORY JSON RESPONSE FORMAT - ABSOLUTELY CRITICAL***:\n- WHEN DATA COMPONENTS ARE AVAILABLE, YOU MUST RESPOND IN JSON FORMAT ONLY\n- DO NOT respond with plain text when data components are defined\n- YOUR RESPONSE MUST BE STRUCTURED JSON WITH dataComponents ARRAY\n- THIS IS NON-NEGOTIABLE - JSON FORMAT IS REQUIRED\n\nCRITICAL JSON FORMATTING RULES - MUST FOLLOW EXACTLY:\n1. Each data component must include id, name, and props fields\n2. The id and name should match the exact component definition\n3. The props field contains the actual component data using exact property names from the schema\n4. NEVER omit the id and name fields\n\nCORRECT: [{\\"id\\": \\"component1\\", \\"name\\": \\"Component1\\", \\"props\\": {\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}, {\\"id\\": \\"component2\\", \\"name\\": \\"Component2\\", \\"props\\": {\\"field3\\": \\"value3\\"}}]\nWRONG: [{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}, {\\"field3\\": \\"value3\\"}]\n\nAVAILABLE DATA COMPONENTS: {{DATA_COMPONENTS_LIST}}">\n\n{{DATA_COMPONENTS_XML}}\n\n</data_components_section>';
6962
+
6317
6963
  // templates/v1/phase2/system-prompt.xml?raw
6318
6964
  var system_prompt_default2 = `<phase2_system_message>
6319
6965
  <instruction>
@@ -6353,12 +6999,6 @@ var system_prompt_default2 = `<phase2_system_message>
6353
6999
  </requirements>
6354
7000
  </phase2_system_message>`;
6355
7001
 
6356
- // templates/v1/phase2/data-components.xml?raw
6357
- var data_components_default = '<data_components_section description="These are the data components available for you to use in generating responses. Each component represents a single structured piece of information. You can create multiple instances of the same component type when needed.\n\n***MANDATORY JSON RESPONSE FORMAT - ABSOLUTELY CRITICAL***:\n- WHEN DATA COMPONENTS ARE AVAILABLE, YOU MUST RESPOND IN JSON FORMAT ONLY\n- DO NOT respond with plain text when data components are defined\n- YOUR RESPONSE MUST BE STRUCTURED JSON WITH dataComponents ARRAY\n- THIS IS NON-NEGOTIABLE - JSON FORMAT IS REQUIRED\n\nCRITICAL JSON FORMATTING RULES - MUST FOLLOW EXACTLY:\n1. Each data component must include id, name, and props fields\n2. The id and name should match the exact component definition\n3. The props field contains the actual component data using exact property names from the schema\n4. NEVER omit the id and name fields\n\nCORRECT: [{\\"id\\": \\"component1\\", \\"name\\": \\"Component1\\", \\"props\\": {\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}, {\\"id\\": \\"component2\\", \\"name\\": \\"Component2\\", \\"props\\": {\\"field3\\": \\"value3\\"}}]\nWRONG: [{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}, {\\"field3\\": \\"value3\\"}]\n\nAVAILABLE DATA COMPONENTS: {{DATA_COMPONENTS_LIST}}">\n\n{{DATA_COMPONENTS_XML}}\n\n</data_components_section>';
6358
-
6359
- // templates/v1/phase2/data-component.xml?raw
6360
- var data_component_default = "<data-component>\n <name>{{COMPONENT_NAME}}</name>\n <description>{{COMPONENT_DESCRIPTION}}</description>\n <props>\n <schema>\n {{COMPONENT_PROPS_SCHEMA}}\n </schema>\n </props>\n</data-component> ";
6361
-
6362
7002
  // src/agents/versions/v1/Phase2Config.ts
6363
7003
  var Phase2Config = class {
6364
7004
  getArtifactCreationGuidance() {
@@ -6404,17 +7044,15 @@ When the same field names appear at different levels (like 'content', 'title', '
6404
7044
 
6405
7045
  CRITICAL: SELECTOR HIERARCHY
6406
7046
  - base_selector: Points to ONE specific item in the tool result
6407
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
6408
- - Example: If base="result.documents[?type=='api']" then summary_props uses "title" not "documents[0].title"
7047
+ - details_selector: Contains JMESPath selectors RELATIVE to the base selector
7048
+ - Example: If base="result.documents[?type=='api']" then details_selector uses "title" not "documents[0].title"
6409
7049
 
6410
7050
  \u274C WRONG EXAMPLE:
6411
7051
  {
6412
7052
  "base_selector": "result.content[?title=='Guide']",
6413
- "summary_props": {
7053
+ "details_selector": {
6414
7054
  "title": "Guide", // \u274C This is a literal value, not a selector!
6415
- "url": "result.content[?title=='Guide'].url" // \u274C This is absolute, not relative!
6416
- },
6417
- "full_props": {
7055
+ "url": "result.content[?title=='Guide'].url", // \u274C This is absolute, not relative!
6418
7056
  "description": "A comprehensive guide", // \u274C Literal value instead of selector!
6419
7057
  "content": "result.content[?title=='Guide'].content" // \u274C Absolute path instead of relative!
6420
7058
  }
@@ -6423,11 +7061,9 @@ CRITICAL: SELECTOR HIERARCHY
6423
7061
  \u2705 CORRECT EXAMPLE:
6424
7062
  {
6425
7063
  "base_selector": "result.content[?title=='Guide']",
6426
- "summary_props": {
7064
+ "details_selector": {
6427
7065
  "title": "title", // \u2705 Relative selector to get title field
6428
- "url": "url" // \u2705 Relative selector to get url field
6429
- },
6430
- "full_props": {
7066
+ "url": "url", // \u2705 Relative selector to get url field
6431
7067
  "description": "description", // \u2705 Relative selector
6432
7068
  "content": "content", // \u2705 Relative selector
6433
7069
  "metadata": "metadata.details" // \u2705 Relative selector with nesting
@@ -6513,8 +7149,7 @@ EXAMPLE STRUCTURED RESPONSE:
6513
7149
  "tool_call_id": "call_abc123",
6514
7150
  "type": "APIDoc",
6515
7151
  "base_selector": "result.documents[?type=='api']",
6516
- "summary_props": {"title": "metadata.title", "endpoint": "api.endpoint"},
6517
- "full_props": {"description": "content.description", "parameters": "spec.parameters", "examples": "examples.sample_code"}
7152
+ "details_selector": {"title": "metadata.title", "endpoint": "api.endpoint", "description": "content.description", "parameters": "spec.parameters", "examples": "examples.sample_code"}
6518
7153
  }
6519
7154
  },
6520
7155
  {
@@ -6594,14 +7229,14 @@ IMPORTANT GUIDELINES:
6594
7229
  return "";
6595
7230
  }
6596
7231
  const componentDescriptions = artifactComponents.map((ac) => {
6597
- const summaryProps = ac.summaryProps?.properties ? Object.entries(ac.summaryProps.properties).map(([key, value]) => ` - ${key}: ${value.description || "Field from tool result"}`).join("\n") : " No properties defined";
6598
- const fullProps = ac.fullProps?.properties ? Object.entries(ac.fullProps.properties).map(([key, value]) => ` - ${key}: ${value.description || "Field from tool result"}`).join("\n") : " No properties defined";
7232
+ const schemaProps = ac.props?.properties ? Object.entries(ac.props.properties).map(([key, value]) => {
7233
+ const inPreview = value.inPreview ? " [PREVIEW]" : " [FULL]";
7234
+ return ` - ${key}: ${value.description || "Field from tool result"}${inPreview}`;
7235
+ }).join("\n") : " No properties defined";
6599
7236
  return ` ArtifactCreate_${ac.name}:
6600
7237
  Description: ${ac.description || "Extract and structure data"}
6601
- Summary Properties:
6602
- ${summaryProps}
6603
- Full Properties:
6604
- ${fullProps}`;
7238
+ Schema Properties:
7239
+ ${schemaProps}`;
6605
7240
  }).join("\n\n");
6606
7241
  return `
6607
7242
  AVAILABLE ARTIFACT TYPES:
@@ -6615,8 +7250,14 @@ ${componentDescriptions}`;
6615
7250
  const dataComponentsDescription = dataComponents.map((dc) => `${dc.name}: ${dc.description}`).join(", ");
6616
7251
  const dataComponentsXml = dataComponents.map((dataComponent) => this.generateDataComponentXml(dataComponent)).join("\n ");
6617
7252
  let dataComponentsSection = data_components_default;
6618
- dataComponentsSection = dataComponentsSection.replace("{{DATA_COMPONENTS_LIST}}", dataComponentsDescription);
6619
- dataComponentsSection = dataComponentsSection.replace("{{DATA_COMPONENTS_XML}}", dataComponentsXml);
7253
+ dataComponentsSection = dataComponentsSection.replace(
7254
+ "{{DATA_COMPONENTS_LIST}}",
7255
+ dataComponentsDescription
7256
+ );
7257
+ dataComponentsSection = dataComponentsSection.replace(
7258
+ "{{DATA_COMPONENTS_XML}}",
7259
+ dataComponentsXml
7260
+ );
6620
7261
  return dataComponentsSection;
6621
7262
  }
6622
7263
  generateDataComponentXml(dataComponent) {
@@ -6688,14 +7329,21 @@ ${artifact_retrieval_guidance_default}
6688
7329
  * Assemble the complete Phase 2 system prompt for structured output generation
6689
7330
  */
6690
7331
  assemblePhase2Prompt(config) {
6691
- const { corePrompt, dataComponents, artifactComponents, hasArtifactComponents, hasGraphArtifactComponents, artifacts = [] } = config;
7332
+ const {
7333
+ corePrompt,
7334
+ dataComponents,
7335
+ artifactComponents,
7336
+ hasArtifactComponents,
7337
+ hasGraphArtifactComponents,
7338
+ artifacts = []
7339
+ } = config;
6692
7340
  let allDataComponents = [...dataComponents];
6693
7341
  if (hasArtifactComponents && artifactComponents) {
6694
7342
  const artifactCreateComponents = ArtifactCreateSchema.getDataComponents(
6695
7343
  "tenant",
6696
7344
  // placeholder - not used in Phase2
6697
7345
  "",
6698
- // placeholder - not used in Phase2
7346
+ // placeholder - not used in Phase2
6699
7347
  artifactComponents
6700
7348
  );
6701
7349
  allDataComponents = [...dataComponents, ...artifactCreateComponents];
@@ -6703,8 +7351,15 @@ ${artifact_retrieval_guidance_default}
6703
7351
  const dataComponentsSection = this.generateDataComponentsSection(allDataComponents);
6704
7352
  const artifactsSection = this.generateArtifactsSection(artifacts);
6705
7353
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
6706
- const artifactGuidance = this.getStructuredArtifactGuidance(hasArtifactComponents, artifactComponents, shouldShowReferencingRules);
6707
- const artifactTypes = this.getArtifactCreationInstructions(hasArtifactComponents, artifactComponents);
7354
+ const artifactGuidance = this.getStructuredArtifactGuidance(
7355
+ hasArtifactComponents,
7356
+ artifactComponents,
7357
+ shouldShowReferencingRules
7358
+ );
7359
+ const artifactTypes = this.getArtifactCreationInstructions(
7360
+ hasArtifactComponents,
7361
+ artifactComponents
7362
+ );
6708
7363
  let phase2Prompt = system_prompt_default2;
6709
7364
  phase2Prompt = phase2Prompt.replace("{{CORE_INSTRUCTIONS}}", corePrompt);
6710
7365
  phase2Prompt = phase2Prompt.replace("{{DATA_COMPONENTS_SECTION}}", dataComponentsSection);
@@ -6725,7 +7380,7 @@ function hasToolCallWithPrefix(prefix) {
6725
7380
  return false;
6726
7381
  };
6727
7382
  }
6728
- var logger17 = agentsCore.getLogger("Agent");
7383
+ var logger19 = agentsCore.getLogger("Agent");
6729
7384
  var CONSTANTS = {
6730
7385
  MAX_GENERATION_STEPS: 12,
6731
7386
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -7006,7 +7661,10 @@ var Agent = class {
7006
7661
  ]);
7007
7662
  }
7008
7663
  async getMcpTools(sessionId, streamRequestId) {
7009
- const tools = await Promise.all(this.config.tools?.map((tool3) => this.getMcpTool(tool3)) || []) || [];
7664
+ const mcpTools = this.config.tools?.filter((tool3) => {
7665
+ return tool3.config?.type === "mcp";
7666
+ }) || [];
7667
+ const tools = await Promise.all(mcpTools.map((tool3) => this.getMcpTool(tool3)) || []) || [];
7010
7668
  if (!sessionId) {
7011
7669
  const combinedTools = tools.reduce((acc, tool3) => {
7012
7670
  return Object.assign(acc, tool3);
@@ -7026,14 +7684,14 @@ var Agent = class {
7026
7684
  for (const toolSet of tools) {
7027
7685
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
7028
7686
  if (!isValidTool(originalTool)) {
7029
- logger17.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7687
+ logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7030
7688
  continue;
7031
7689
  }
7032
7690
  const sessionWrappedTool = ai.tool({
7033
7691
  description: originalTool.description,
7034
7692
  inputSchema: originalTool.inputSchema,
7035
7693
  execute: async (args, { toolCallId }) => {
7036
- logger17.debug({ toolName, toolCallId }, "MCP Tool Called");
7694
+ logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
7037
7695
  try {
7038
7696
  const rawResult = await originalTool.execute(args, { toolCallId });
7039
7697
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -7047,7 +7705,7 @@ var Agent = class {
7047
7705
  });
7048
7706
  return { result: enhancedResult, toolCallId };
7049
7707
  } catch (error) {
7050
- logger17.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7708
+ logger19.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7051
7709
  throw error;
7052
7710
  }
7053
7711
  }
@@ -7066,6 +7724,9 @@ var Agent = class {
7066
7724
  * Convert database McpTool to builder MCPToolConfig format
7067
7725
  */
7068
7726
  convertToMCPToolConfig(tool3, agentToolRelationHeaders) {
7727
+ if (tool3.config.type !== "mcp") {
7728
+ throw new Error(`Cannot convert non-MCP tool to MCP config: ${tool3.id}`);
7729
+ }
7069
7730
  return {
7070
7731
  id: tool3.id,
7071
7732
  name: tool3.name,
@@ -7134,6 +7795,9 @@ var Agent = class {
7134
7795
  selectedTools
7135
7796
  );
7136
7797
  } else {
7798
+ if (tool3.config.type !== "mcp") {
7799
+ throw new Error(`Cannot build server config for non-MCP tool: ${tool3.id}`);
7800
+ }
7137
7801
  serverConfig = {
7138
7802
  type: tool3.config.mcp.transport?.type || agentsCore.MCPTransportType.streamableHttp,
7139
7803
  url: tool3.config.mcp.server.url,
@@ -7142,7 +7806,7 @@ var Agent = class {
7142
7806
  headers: agentToolRelationHeaders
7143
7807
  };
7144
7808
  }
7145
- logger17.info(
7809
+ logger19.info(
7146
7810
  {
7147
7811
  toolName: tool3.name,
7148
7812
  credentialReferenceId,
@@ -7167,7 +7831,7 @@ var Agent = class {
7167
7831
  this.mcpClientCache.set(cacheKey, client);
7168
7832
  } catch (error) {
7169
7833
  this.mcpConnectionLocks.delete(cacheKey);
7170
- logger17.error(
7834
+ logger19.error(
7171
7835
  {
7172
7836
  toolName: tool3.name,
7173
7837
  agentId: this.config.id,
@@ -7191,7 +7855,7 @@ var Agent = class {
7191
7855
  await client.connect();
7192
7856
  return client;
7193
7857
  } catch (error) {
7194
- logger17.error(
7858
+ logger19.error(
7195
7859
  {
7196
7860
  toolName: tool3.name,
7197
7861
  agentId: this.config.id,
@@ -7202,31 +7866,98 @@ var Agent = class {
7202
7866
  throw error;
7203
7867
  }
7204
7868
  }
7205
- getFunctionTools(streamRequestId) {
7206
- if (!this.config.functionTools) return {};
7869
+ async getFunctionTools(sessionId, streamRequestId) {
7207
7870
  const functionTools = {};
7208
- for (const funcTool of this.config.functionTools) {
7209
- const aiTool = ai.tool({
7210
- description: funcTool.description,
7211
- inputSchema: funcTool.schema || z5.z.object({}),
7212
- execute: funcTool.execute
7871
+ try {
7872
+ const toolsForAgent = await agentsCore.getToolsForAgent(dbClient_default)({
7873
+ scopes: {
7874
+ tenantId: this.config.tenantId || "default",
7875
+ projectId: this.config.projectId || "default",
7876
+ graphId: this.config.graphId,
7877
+ agentId: this.config.id
7878
+ }
7213
7879
  });
7214
- functionTools[funcTool.name] = this.wrapToolWithStreaming(
7215
- funcTool.name,
7216
- aiTool,
7217
- streamRequestId,
7218
- "tool"
7219
- );
7880
+ const toolsData = toolsForAgent.data || [];
7881
+ const functionToolDefs = toolsData.filter((tool3) => tool3.tool.config.type === "function");
7882
+ if (functionToolDefs.length === 0) {
7883
+ return functionTools;
7884
+ }
7885
+ const { LocalSandboxExecutor: LocalSandboxExecutor2 } = await Promise.resolve().then(() => (init_LocalSandboxExecutor(), LocalSandboxExecutor_exports));
7886
+ const sandboxExecutor = LocalSandboxExecutor2.getInstance();
7887
+ for (const toolDef of functionToolDefs) {
7888
+ if (toolDef.tool.config?.type === "function") {
7889
+ const functionId = toolDef.tool.functionId;
7890
+ if (!functionId) {
7891
+ logger19.warn({ toolId: toolDef.tool.id }, "Function tool missing functionId reference");
7892
+ continue;
7893
+ }
7894
+ const functionData = await agentsCore.getFunction(dbClient_default)({
7895
+ functionId,
7896
+ scopes: {
7897
+ tenantId: this.config.tenantId || "default",
7898
+ projectId: this.config.projectId || "default"
7899
+ }
7900
+ });
7901
+ if (!functionData) {
7902
+ logger19.warn(
7903
+ { functionId, toolId: toolDef.tool.id },
7904
+ "Function not found in functions table"
7905
+ );
7906
+ continue;
7907
+ }
7908
+ const zodSchema = jsonSchemaToZod(functionData.inputSchema);
7909
+ const aiTool = ai.tool({
7910
+ description: toolDef.tool.description || toolDef.tool.name,
7911
+ inputSchema: zodSchema,
7912
+ execute: async (args, { toolCallId }) => {
7913
+ logger19.debug(
7914
+ { toolName: toolDef.tool.name, toolCallId, args },
7915
+ "Function Tool Called"
7916
+ );
7917
+ try {
7918
+ const result = await sandboxExecutor.executeFunctionTool(toolDef.tool.id, args, {
7919
+ description: toolDef.tool.description || toolDef.tool.name,
7920
+ inputSchema: functionData.inputSchema || {},
7921
+ executeCode: functionData.executeCode,
7922
+ dependencies: functionData.dependencies || {}
7923
+ });
7924
+ toolSessionManager.recordToolResult(sessionId || "", {
7925
+ toolCallId,
7926
+ toolName: toolDef.tool.name,
7927
+ args,
7928
+ result,
7929
+ timestamp: Date.now()
7930
+ });
7931
+ return { result, toolCallId };
7932
+ } catch (error) {
7933
+ logger19.error(
7934
+ { toolName: toolDef.tool.name, toolCallId, error },
7935
+ "Function tool execution failed"
7936
+ );
7937
+ throw error;
7938
+ }
7939
+ }
7940
+ });
7941
+ functionTools[toolDef.tool.name] = this.wrapToolWithStreaming(
7942
+ toolDef.tool.name,
7943
+ aiTool,
7944
+ streamRequestId || "",
7945
+ "tool"
7946
+ );
7947
+ }
7948
+ }
7949
+ } catch (error) {
7950
+ logger19.error({ error }, "Failed to load function tools from database");
7220
7951
  }
7221
7952
  return functionTools;
7222
7953
  }
7223
7954
  /**
7224
7955
  * Get resolved context using ContextResolver - will return cached data or fetch fresh data as needed
7225
7956
  */
7226
- async getResolvedContext(conversationId, requestContext) {
7957
+ async getResolvedContext(conversationId, headers) {
7227
7958
  try {
7228
7959
  if (!this.config.contextConfigId) {
7229
- logger17.debug({ graphId: this.config.graphId }, "No context config found for graph");
7960
+ logger19.debug({ graphId: this.config.graphId }, "No context config found for graph");
7230
7961
  return null;
7231
7962
  }
7232
7963
  const contextConfig = await agentsCore.getContextConfigById(dbClient_default)({
@@ -7238,7 +7969,7 @@ var Agent = class {
7238
7969
  id: this.config.contextConfigId
7239
7970
  });
7240
7971
  if (!contextConfig) {
7241
- logger17.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7972
+ logger19.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7242
7973
  return null;
7243
7974
  }
7244
7975
  if (!this.contextResolver) {
@@ -7247,7 +7978,7 @@ var Agent = class {
7247
7978
  const result = await this.contextResolver.resolve(contextConfig, {
7248
7979
  triggerEvent: "invocation",
7249
7980
  conversationId,
7250
- requestContext: requestContext || {},
7981
+ headers: headers || {},
7251
7982
  tenantId: this.config.tenantId
7252
7983
  });
7253
7984
  const contextWithBuiltins = {
@@ -7255,7 +7986,7 @@ var Agent = class {
7255
7986
  $now: (/* @__PURE__ */ new Date()).toISOString(),
7256
7987
  $env: process.env
7257
7988
  };
7258
- logger17.debug(
7989
+ logger19.debug(
7259
7990
  {
7260
7991
  conversationId,
7261
7992
  contextConfigId: contextConfig.id,
@@ -7269,7 +8000,7 @@ var Agent = class {
7269
8000
  );
7270
8001
  return contextWithBuiltins;
7271
8002
  } catch (error) {
7272
- logger17.error(
8003
+ logger19.error(
7273
8004
  {
7274
8005
  conversationId,
7275
8006
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7293,7 +8024,7 @@ var Agent = class {
7293
8024
  });
7294
8025
  return graphDefinition?.graphPrompt || void 0;
7295
8026
  } catch (error) {
7296
- logger17.warn(
8027
+ logger19.warn(
7297
8028
  {
7298
8029
  graphId: this.config.graphId,
7299
8030
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7322,7 +8053,7 @@ var Agent = class {
7322
8053
  (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
7323
8054
  );
7324
8055
  } catch (error) {
7325
- logger17.warn(
8056
+ logger19.warn(
7326
8057
  {
7327
8058
  graphId: this.config.graphId,
7328
8059
  tenantId: this.config.tenantId,
@@ -7351,7 +8082,7 @@ var Agent = class {
7351
8082
  preserveUnresolved: false
7352
8083
  });
7353
8084
  } catch (error) {
7354
- logger17.error(
8085
+ logger19.error(
7355
8086
  {
7356
8087
  conversationId,
7357
8088
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7398,7 +8129,7 @@ var Agent = class {
7398
8129
  preserveUnresolved: false
7399
8130
  });
7400
8131
  } catch (error) {
7401
- logger17.error(
8132
+ logger19.error(
7402
8133
  {
7403
8134
  conversationId,
7404
8135
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7410,9 +8141,24 @@ var Agent = class {
7410
8141
  }
7411
8142
  const streamRequestId = runtimeContext?.metadata?.streamRequestId;
7412
8143
  const mcpTools = await this.getMcpTools(void 0, streamRequestId);
7413
- const functionTools = this.getFunctionTools(streamRequestId);
8144
+ const functionTools = await this.getFunctionTools(streamRequestId || "");
7414
8145
  const relationTools = this.getRelationTools(runtimeContext);
7415
8146
  const allTools = { ...mcpTools, ...functionTools, ...relationTools };
8147
+ logger19.info(
8148
+ {
8149
+ mcpTools: Object.keys(mcpTools),
8150
+ functionTools: Object.keys(functionTools),
8151
+ relationTools: Object.keys(relationTools),
8152
+ allTools: Object.keys(allTools),
8153
+ functionToolsDetails: Object.entries(functionTools).map(([name, tool3]) => ({
8154
+ name,
8155
+ hasExecute: typeof tool3.execute === "function",
8156
+ hasDescription: !!tool3.description,
8157
+ hasInputSchema: !!tool3.inputSchema
8158
+ }))
8159
+ },
8160
+ "Tools loaded for agent"
8161
+ );
7416
8162
  const toolDefinitions = Object.entries(allTools).map(([name, tool3]) => ({
7417
8163
  name,
7418
8164
  description: tool3.description || "",
@@ -7437,7 +8183,7 @@ var Agent = class {
7437
8183
  preserveUnresolved: false
7438
8184
  });
7439
8185
  } catch (error) {
7440
- logger17.error(
8186
+ logger19.error(
7441
8187
  {
7442
8188
  conversationId,
7443
8189
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7464,23 +8210,29 @@ var Agent = class {
7464
8210
  }
7465
8211
  getArtifactTools() {
7466
8212
  return ai.tool({
7467
- description: "Call this tool to get the artifact with the given artifactId. Only retrieve this when the description of the artifact is insufficient to understand the artifact and you need to see the actual artifact for more context. Please refrain from using this tool unless absolutely necessary.",
7468
- inputSchema: z5.z.object({
7469
- artifactId: z5.z.string().describe("The unique identifier of the artifact to get.")
8213
+ 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.",
8214
+ inputSchema: z6.z.object({
8215
+ artifactId: z6.z.string().describe("The unique identifier of the artifact to get."),
8216
+ toolCallId: z6.z.string().describe("The tool call ID associated with this artifact.")
7470
8217
  }),
7471
- execute: async ({ artifactId }) => {
7472
- logger17.info({ artifactId }, "get_artifact executed");
7473
- const artifact = await agentsCore.getLedgerArtifacts(dbClient_default)({
7474
- scopes: {
7475
- tenantId: this.config.tenantId,
7476
- projectId: this.config.projectId
7477
- },
7478
- artifactId
7479
- });
7480
- if (!artifact) {
7481
- throw new Error(`Artifact ${artifactId} not found`);
8218
+ execute: async ({ artifactId, toolCallId }) => {
8219
+ logger19.info({ artifactId, toolCallId }, "get_artifact_full executed");
8220
+ const streamRequestId = this.getStreamRequestId();
8221
+ const artifactService = graphSessionManager.getArtifactService(streamRequestId);
8222
+ if (!artifactService) {
8223
+ throw new Error(`ArtifactService not found for session ${streamRequestId}`);
7482
8224
  }
7483
- return { artifact: artifact[0] };
8225
+ const artifactData = await artifactService.getArtifactFull(artifactId, toolCallId);
8226
+ if (!artifactData) {
8227
+ throw new Error(`Artifact ${artifactId} with toolCallId ${toolCallId} not found`);
8228
+ }
8229
+ return {
8230
+ artifactId: artifactData.artifactId,
8231
+ name: artifactData.name,
8232
+ description: artifactData.description,
8233
+ type: artifactData.type,
8234
+ data: artifactData.data
8235
+ };
7484
8236
  }
7485
8237
  });
7486
8238
  }
@@ -7488,9 +8240,9 @@ var Agent = class {
7488
8240
  createThinkingCompleteTool() {
7489
8241
  return ai.tool({
7490
8242
  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.",
7491
- inputSchema: z5.z.object({
7492
- complete: z5.z.boolean().describe("ALWAYS set to true - marks end of research phase"),
7493
- summary: z5.z.string().describe(
8243
+ inputSchema: z6.z.object({
8244
+ complete: z6.z.boolean().describe("ALWAYS set to true - marks end of research phase"),
8245
+ summary: z6.z.string().describe(
7494
8246
  "Brief summary of what information was gathered and why it is sufficient to answer the user"
7495
8247
  )
7496
8248
  }),
@@ -7498,7 +8250,7 @@ var Agent = class {
7498
8250
  });
7499
8251
  }
7500
8252
  // Provide a default tool set that is always available to the agent.
7501
- async getDefaultTools(sessionId, streamRequestId) {
8253
+ async getDefaultTools(_sessionId, streamRequestId) {
7502
8254
  const defaultTools = {};
7503
8255
  if (await this.graphHasArtifactComponents()) {
7504
8256
  defaultTools.get_reference_artifact = this.getArtifactTools();
@@ -7586,13 +8338,19 @@ var Agent = class {
7586
8338
  if (Array.isArray(obj)) {
7587
8339
  obj.slice(0, 3).forEach((item) => {
7588
8340
  if (item && typeof item === "object") {
7589
- Object.keys(item).forEach((key) => fields.add(key));
8341
+ Object.keys(item).forEach((key) => {
8342
+ fields.add(key);
8343
+ });
7590
8344
  }
7591
8345
  });
7592
8346
  } else if (obj && typeof obj === "object") {
7593
- Object.keys(obj).forEach((key) => fields.add(key));
8347
+ Object.keys(obj).forEach((key) => {
8348
+ fields.add(key);
8349
+ });
7594
8350
  Object.values(obj).forEach((value) => {
7595
- findCommonFields(value, depth + 1).forEach((field) => fields.add(field));
8351
+ findCommonFields(value, depth + 1).forEach((field) => {
8352
+ fields.add(field);
8353
+ });
7596
8354
  });
7597
8355
  }
7598
8356
  return fields;
@@ -7691,8 +8449,7 @@ var Agent = class {
7691
8449
  artifactGuidance: {
7692
8450
  creationFirst: "\u{1F6A8} CRITICAL: Artifacts must be CREATED before they can be referenced. Use ArtifactCreate_[Type] components FIRST, then reference with Artifact components only if citing the SAME artifact again.",
7693
8451
  baseSelector: `\u{1F3AF} CRITICAL: Use base_selector to navigate to ONE specific item. For deeply nested structures with repeated keys, use full paths with specific filtering (e.g., "result.data.content.items[?type=='guide' && status=='active']")`,
7694
- summaryProps: '\u{1F4DD} Use relative selectors from that item (e.g., "title", "metadata.category", "properties.status")',
7695
- fullProps: '\u{1F4D6} Use relative selectors for detailed data (e.g., "content.details", "specifications.data", "attributes")',
8452
+ detailsSelector: '\u{1F4DD} Use relative selectors for specific fields (e.g., "title", "metadata.category", "properties.status", "content.details")',
7696
8453
  avoidLiterals: "\u274C NEVER use literal values - always use field selectors to extract from data",
7697
8454
  avoidArrays: "\u2728 ALWAYS filter arrays to single items using [?condition] - NEVER use [*] notation which returns arrays",
7698
8455
  nestedKeys: "\u{1F511} For structures with repeated keys (like result.content.data.content.items.content), use full paths with filtering at each level",
@@ -7719,7 +8476,7 @@ var Agent = class {
7719
8476
  };
7720
8477
  return enhanced;
7721
8478
  } catch (error) {
7722
- logger17.warn({ error }, "Failed to enhance tool result with structure hints");
8479
+ logger19.warn({ error }, "Failed to enhance tool result with structure hints");
7723
8480
  return result;
7724
8481
  }
7725
8482
  }
@@ -7734,7 +8491,7 @@ var Agent = class {
7734
8491
  }
7735
8492
  });
7736
8493
  } catch (error) {
7737
- logger17.error(
8494
+ logger19.error(
7738
8495
  { error, graphId: this.config.graphId },
7739
8496
  "Failed to check graph artifact components"
7740
8497
  );
@@ -7777,7 +8534,7 @@ var Agent = class {
7777
8534
  // Normal prompt with data components
7778
8535
  this.buildSystemPrompt(runtimeContext, true),
7779
8536
  // Thinking prompt without data components
7780
- Promise.resolve(this.getFunctionTools(streamRequestId)),
8537
+ this.getFunctionTools(sessionId, streamRequestId),
7781
8538
  Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
7782
8539
  this.getDefaultTools(sessionId, streamRequestId)
7783
8540
  ]);
@@ -7835,7 +8592,7 @@ var Agent = class {
7835
8592
  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;
7836
8593
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
7837
8594
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
7838
- logger17.warn(
8595
+ logger19.warn(
7839
8596
  {
7840
8597
  requestedTimeout: modelSettings.maxDuration * 1e3,
7841
8598
  appliedTimeout: timeoutMs,
@@ -7877,7 +8634,7 @@ var Agent = class {
7877
8634
  }
7878
8635
  );
7879
8636
  } catch (error) {
7880
- logger17.debug({ error }, "Failed to track agent reasoning");
8637
+ logger19.debug({ error }, "Failed to track agent reasoning");
7881
8638
  }
7882
8639
  }
7883
8640
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7981,7 +8738,7 @@ var Agent = class {
7981
8738
  }
7982
8739
  );
7983
8740
  } catch (error) {
7984
- logger17.debug({ error }, "Failed to track agent reasoning");
8741
+ logger19.debug({ error }, "Failed to track agent reasoning");
7985
8742
  }
7986
8743
  }
7987
8744
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -8085,9 +8842,9 @@ ${output}${structureHintsFormatted}`;
8085
8842
  this.config.dataComponents.forEach((dc) => {
8086
8843
  const propsSchema = jsonSchemaToZod(dc.props);
8087
8844
  componentSchemas.push(
8088
- z5.z.object({
8089
- id: z5.z.string(),
8090
- name: z5.z.literal(dc.name),
8845
+ z6.z.object({
8846
+ id: z6.z.string(),
8847
+ name: z6.z.literal(dc.name),
8091
8848
  props: propsSchema
8092
8849
  })
8093
8850
  );
@@ -8104,7 +8861,7 @@ ${output}${structureHintsFormatted}`;
8104
8861
  if (componentSchemas.length === 1) {
8105
8862
  dataComponentsSchema = componentSchemas[0];
8106
8863
  } else {
8107
- dataComponentsSchema = z5.z.union(
8864
+ dataComponentsSchema = z6.z.union(
8108
8865
  componentSchemas
8109
8866
  );
8110
8867
  }
@@ -8128,8 +8885,8 @@ ${output}${structureHintsFormatted}`;
8128
8885
  const streamResult = ai.streamObject({
8129
8886
  ...structuredModelSettings,
8130
8887
  messages: phase2Messages,
8131
- schema: z5.z.object({
8132
- dataComponents: z5.z.array(dataComponentsSchema)
8888
+ schema: z6.z.object({
8889
+ dataComponents: z6.z.array(dataComponentsSchema)
8133
8890
  }),
8134
8891
  experimental_telemetry: {
8135
8892
  isEnabled: true,
@@ -8197,8 +8954,8 @@ ${output}${structureHintsFormatted}`;
8197
8954
  withJsonPostProcessing2({
8198
8955
  ...structuredModelSettings,
8199
8956
  messages: phase2Messages,
8200
- schema: z5.z.object({
8201
- dataComponents: z5.z.array(dataComponentsSchema)
8957
+ schema: z6.z.object({
8958
+ dataComponents: z6.z.array(dataComponentsSchema)
8202
8959
  }),
8203
8960
  experimental_telemetry: {
8204
8961
  isEnabled: true,
@@ -8273,7 +9030,7 @@ ${output}${structureHintsFormatted}`;
8273
9030
  };
8274
9031
 
8275
9032
  // src/agents/generateTaskHandler.ts
8276
- var logger18 = agentsCore.getLogger("generateTaskHandler");
9033
+ var logger20 = agentsCore.getLogger("generateTaskHandler");
8277
9034
  var createTaskHandler = (config, credentialStoreRegistry) => {
8278
9035
  return async (task) => {
8279
9036
  try {
@@ -8326,7 +9083,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8326
9083
  }
8327
9084
  })
8328
9085
  ]);
8329
- logger18.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9086
+ logger20.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8330
9087
  const enhancedInternalRelations = await Promise.all(
8331
9088
  internalRelations.map(async (relation) => {
8332
9089
  try {
@@ -8355,7 +9112,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8355
9112
  return { ...relation, description: enhancedDescription };
8356
9113
  }
8357
9114
  } catch (error) {
8358
- logger18.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
9115
+ logger20.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
8359
9116
  }
8360
9117
  return relation;
8361
9118
  })
@@ -8450,12 +9207,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8450
9207
  },
8451
9208
  credentialStoreRegistry
8452
9209
  );
9210
+ const artifactStreamRequestId = task.context?.metadata?.streamRequestId;
9211
+ if (artifactStreamRequestId && artifactComponents.length > 0) {
9212
+ graphSessionManager.updateArtifactComponents(artifactStreamRequestId, artifactComponents);
9213
+ }
8453
9214
  let contextId = task.context?.conversationId;
8454
9215
  if (!contextId || contextId === "default" || contextId === "") {
8455
9216
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
8456
9217
  if (taskIdMatch) {
8457
9218
  contextId = taskIdMatch[1];
8458
- logger18.info(
9219
+ logger20.info(
8459
9220
  {
8460
9221
  taskId: task.id,
8461
9222
  extractedContextId: contextId,
@@ -8471,7 +9232,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8471
9232
  const isDelegation = task.context?.metadata?.isDelegation === true;
8472
9233
  agent.setDelegationStatus(isDelegation);
8473
9234
  if (isDelegation) {
8474
- logger18.info(
9235
+ logger20.info(
8475
9236
  { agentId: config.agentId, taskId: task.id },
8476
9237
  "Delegated agent - streaming disabled"
8477
9238
  );
@@ -8696,7 +9457,7 @@ async function getRegisteredGraph(executionContext) {
8696
9457
  init_dbClient();
8697
9458
  init_logger();
8698
9459
  var app = new zodOpenapi.OpenAPIHono();
8699
- var logger19 = agentsCore.getLogger("agents");
9460
+ var logger21 = agentsCore.getLogger("agents");
8700
9461
  app.openapi(
8701
9462
  zodOpenapi.createRoute({
8702
9463
  method: "get",
@@ -8711,14 +9472,14 @@ app.openapi(
8711
9472
  description: "Agent Card for A2A discovery",
8712
9473
  content: {
8713
9474
  "application/json": {
8714
- schema: z5.z.object({
8715
- name: z5.z.string(),
8716
- description: z5.z.string().optional(),
8717
- url: z5.z.string(),
8718
- version: z5.z.string(),
8719
- defaultInputModes: z5.z.array(z5.z.string()),
8720
- defaultOutputModes: z5.z.array(z5.z.string()),
8721
- skills: z5.z.array(z5.z.any())
9475
+ schema: z6.z.object({
9476
+ name: z6.z.string(),
9477
+ description: z6.z.string().optional(),
9478
+ url: z6.z.string(),
9479
+ version: z6.z.string(),
9480
+ defaultInputModes: z6.z.array(z6.z.string()),
9481
+ defaultOutputModes: z6.z.array(z6.z.string()),
9482
+ skills: z6.z.array(z6.z.any())
8722
9483
  })
8723
9484
  }
8724
9485
  }
@@ -8734,7 +9495,7 @@ app.openapi(
8734
9495
  tracestate: c.req.header("tracestate"),
8735
9496
  baggage: c.req.header("baggage")
8736
9497
  };
8737
- logger19.info(
9498
+ logger21.info(
8738
9499
  {
8739
9500
  otelHeaders,
8740
9501
  path: c.req.path,
@@ -8746,7 +9507,7 @@ app.openapi(
8746
9507
  const { tenantId, projectId, graphId, agentId } = executionContext;
8747
9508
  console.dir("executionContext", executionContext);
8748
9509
  if (agentId) {
8749
- logger19.info(
9510
+ logger21.info(
8750
9511
  {
8751
9512
  message: "getRegisteredAgent (agent-level)",
8752
9513
  tenantId,
@@ -8758,7 +9519,7 @@ app.openapi(
8758
9519
  );
8759
9520
  const credentialStores = c.get("credentialStores");
8760
9521
  const agent = await getRegisteredAgent(executionContext, credentialStores);
8761
- logger19.info({ agent }, "agent registered: well-known agent.json");
9522
+ logger21.info({ agent }, "agent registered: well-known agent.json");
8762
9523
  if (!agent) {
8763
9524
  throw agentsCore.createApiError({
8764
9525
  code: "not_found",
@@ -8767,7 +9528,7 @@ app.openapi(
8767
9528
  }
8768
9529
  return c.json(agent.agentCard);
8769
9530
  } else {
8770
- logger19.info(
9531
+ logger21.info(
8771
9532
  {
8772
9533
  message: "getRegisteredGraph (graph-level)",
8773
9534
  tenantId,
@@ -8793,7 +9554,7 @@ app.post("/a2a", async (c) => {
8793
9554
  tracestate: c.req.header("tracestate"),
8794
9555
  baggage: c.req.header("baggage")
8795
9556
  };
8796
- logger19.info(
9557
+ logger21.info(
8797
9558
  {
8798
9559
  otelHeaders,
8799
9560
  path: c.req.path,
@@ -8804,7 +9565,7 @@ app.post("/a2a", async (c) => {
8804
9565
  const executionContext = agentsCore.getRequestExecutionContext(c);
8805
9566
  const { tenantId, projectId, graphId, agentId } = executionContext;
8806
9567
  if (agentId) {
8807
- logger19.info(
9568
+ logger21.info(
8808
9569
  {
8809
9570
  message: "a2a (agent-level)",
8810
9571
  tenantId,
@@ -8828,7 +9589,7 @@ app.post("/a2a", async (c) => {
8828
9589
  }
8829
9590
  return a2aHandler(c, agent);
8830
9591
  } else {
8831
- logger19.info(
9592
+ logger21.info(
8832
9593
  {
8833
9594
  message: "a2a (graph-level)",
8834
9595
  tenantId,
@@ -8884,14 +9645,14 @@ init_dbClient();
8884
9645
  // src/a2a/transfer.ts
8885
9646
  init_dbClient();
8886
9647
  init_logger();
8887
- var logger20 = agentsCore.getLogger("Transfer");
9648
+ var logger22 = agentsCore.getLogger("Transfer");
8888
9649
  async function executeTransfer({
8889
9650
  tenantId,
8890
9651
  threadId,
8891
9652
  projectId,
8892
9653
  targetAgentId
8893
9654
  }) {
8894
- logger20.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
9655
+ logger22.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8895
9656
  await agentsCore.setActiveAgentForThread(dbClient_default)({
8896
9657
  scopes: { tenantId, projectId },
8897
9658
  threadId,
@@ -9477,7 +10238,7 @@ function createMCPStreamHelper() {
9477
10238
  }
9478
10239
 
9479
10240
  // src/handlers/executionHandler.ts
9480
- var logger21 = agentsCore.getLogger("ExecutionHandler");
10241
+ var logger23 = agentsCore.getLogger("ExecutionHandler");
9481
10242
  var ExecutionHandler = class {
9482
10243
  constructor() {
9483
10244
  // Hardcoded error limit - separate from configurable stopWhen
@@ -9513,7 +10274,7 @@ var ExecutionHandler = class {
9513
10274
  if (emitOperations) {
9514
10275
  graphSessionManager.enableEmitOperations(requestId2);
9515
10276
  }
9516
- logger21.info(
10277
+ logger23.info(
9517
10278
  { sessionId: requestId2, graphId, conversationId, emitOperations },
9518
10279
  "Created GraphSession for message execution"
9519
10280
  );
@@ -9528,7 +10289,7 @@ var ExecutionHandler = class {
9528
10289
  );
9529
10290
  }
9530
10291
  } catch (error) {
9531
- logger21.error(
10292
+ logger23.error(
9532
10293
  {
9533
10294
  error: error instanceof Error ? error.message : "Unknown error",
9534
10295
  stack: error instanceof Error ? error.stack : void 0
@@ -9544,7 +10305,7 @@ var ExecutionHandler = class {
9544
10305
  try {
9545
10306
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
9546
10307
  const taskId = `task_${conversationId}-${requestId2}`;
9547
- logger21.info(
10308
+ logger23.info(
9548
10309
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
9549
10310
  "Attempting to create or reuse existing task"
9550
10311
  );
@@ -9568,7 +10329,7 @@ var ExecutionHandler = class {
9568
10329
  agent_id: currentAgentId
9569
10330
  }
9570
10331
  });
9571
- logger21.info(
10332
+ logger23.info(
9572
10333
  {
9573
10334
  taskId,
9574
10335
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -9577,27 +10338,27 @@ var ExecutionHandler = class {
9577
10338
  );
9578
10339
  } catch (error) {
9579
10340
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
9580
- logger21.info(
10341
+ logger23.info(
9581
10342
  { taskId, error: error.message },
9582
10343
  "Task already exists, fetching existing task"
9583
10344
  );
9584
10345
  const existingTask = await agentsCore.getTask(dbClient_default)({ id: taskId });
9585
10346
  if (existingTask) {
9586
10347
  task = existingTask;
9587
- logger21.info(
10348
+ logger23.info(
9588
10349
  { taskId, existingTask },
9589
10350
  "Successfully reused existing task from race condition"
9590
10351
  );
9591
10352
  } else {
9592
- logger21.error({ taskId, error }, "Task constraint failed but task not found");
10353
+ logger23.error({ taskId, error }, "Task constraint failed but task not found");
9593
10354
  throw error;
9594
10355
  }
9595
10356
  } else {
9596
- logger21.error({ taskId, error }, "Failed to create task due to non-constraint error");
10357
+ logger23.error({ taskId, error }, "Failed to create task due to non-constraint error");
9597
10358
  throw error;
9598
10359
  }
9599
10360
  }
9600
- logger21.debug(
10361
+ logger23.debug(
9601
10362
  {
9602
10363
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9603
10364
  executionType: "create_initial_task",
@@ -9615,7 +10376,7 @@ var ExecutionHandler = class {
9615
10376
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
9616
10377
  while (iterations < maxTransfers) {
9617
10378
  iterations++;
9618
- logger21.info(
10379
+ logger23.info(
9619
10380
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
9620
10381
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
9621
10382
  );
@@ -9623,10 +10384,10 @@ var ExecutionHandler = class {
9623
10384
  scopes: { tenantId, projectId },
9624
10385
  conversationId
9625
10386
  });
9626
- logger21.info({ activeAgent }, "activeAgent");
10387
+ logger23.info({ activeAgent }, "activeAgent");
9627
10388
  if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
9628
10389
  currentAgentId = activeAgent.activeAgentId;
9629
- logger21.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10390
+ logger23.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9630
10391
  }
9631
10392
  const agentBaseUrl = `${baseUrl}/agents`;
9632
10393
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -9667,13 +10428,13 @@ var ExecutionHandler = class {
9667
10428
  });
9668
10429
  if (!messageResponse?.result) {
9669
10430
  errorCount++;
9670
- logger21.error(
10431
+ logger23.error(
9671
10432
  { currentAgentId, iterations, errorCount },
9672
10433
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9673
10434
  );
9674
10435
  if (errorCount >= this.MAX_ERRORS) {
9675
10436
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9676
- logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10437
+ logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9677
10438
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9678
10439
  if (task) {
9679
10440
  await agentsCore.updateTask(dbClient_default)({
@@ -9698,7 +10459,7 @@ var ExecutionHandler = class {
9698
10459
  const transferResponse = messageResponse.result;
9699
10460
  const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
9700
10461
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
9701
- logger21.info({ targetAgentId, transferReason }, "transfer response");
10462
+ logger23.info({ targetAgentId, transferReason }, "transfer response");
9702
10463
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
9703
10464
  const { success, targetAgentId: newAgentId } = await executeTransfer({
9704
10465
  projectId,
@@ -9709,7 +10470,7 @@ var ExecutionHandler = class {
9709
10470
  if (success) {
9710
10471
  fromAgentId = currentAgentId;
9711
10472
  currentAgentId = newAgentId;
9712
- logger21.info(
10473
+ logger23.info(
9713
10474
  {
9714
10475
  transferFrom: fromAgentId,
9715
10476
  transferTo: currentAgentId,
@@ -9727,7 +10488,7 @@ var ExecutionHandler = class {
9727
10488
  const graphSessionData = graphSessionManager.getSession(requestId2);
9728
10489
  if (graphSessionData) {
9729
10490
  const sessionSummary = graphSessionData.getSummary();
9730
- logger21.info(sessionSummary, "GraphSession data after completion");
10491
+ logger23.info(sessionSummary, "GraphSession data after completion");
9731
10492
  }
9732
10493
  let textContent = "";
9733
10494
  for (const part of responseParts) {
@@ -9781,22 +10542,22 @@ var ExecutionHandler = class {
9781
10542
  }
9782
10543
  });
9783
10544
  const updateTaskEnd = Date.now();
9784
- logger21.info(
10545
+ logger23.info(
9785
10546
  { duration: updateTaskEnd - updateTaskStart },
9786
10547
  "Completed updateTask operation"
9787
10548
  );
9788
10549
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
9789
10550
  await sseHelper.complete();
9790
- logger21.info({}, "Ending GraphSession and cleaning up");
10551
+ logger23.info({}, "Ending GraphSession and cleaning up");
9791
10552
  graphSessionManager.endSession(requestId2);
9792
- logger21.info({}, "Cleaning up streamHelper");
10553
+ logger23.info({}, "Cleaning up streamHelper");
9793
10554
  unregisterStreamHelper(requestId2);
9794
10555
  let response;
9795
10556
  if (sseHelper instanceof MCPStreamHelper) {
9796
10557
  const captured = sseHelper.getCapturedResponse();
9797
10558
  response = captured.text || "No response content";
9798
10559
  }
9799
- logger21.info({}, "ExecutionHandler returning success");
10560
+ logger23.info({}, "ExecutionHandler returning success");
9800
10561
  return { success: true, iterations, response };
9801
10562
  } catch (error) {
9802
10563
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -9807,13 +10568,13 @@ var ExecutionHandler = class {
9807
10568
  });
9808
10569
  }
9809
10570
  errorCount++;
9810
- logger21.warn(
10571
+ logger23.warn(
9811
10572
  { iterations, errorCount },
9812
10573
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9813
10574
  );
9814
10575
  if (errorCount >= this.MAX_ERRORS) {
9815
10576
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9816
- logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10577
+ logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9817
10578
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9818
10579
  if (task) {
9819
10580
  await agentsCore.updateTask(dbClient_default)({
@@ -9834,7 +10595,7 @@ var ExecutionHandler = class {
9834
10595
  }
9835
10596
  }
9836
10597
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
9837
- logger21.error({ maxTransfers, iterations }, errorMessage);
10598
+ logger23.error({ maxTransfers, iterations }, errorMessage);
9838
10599
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
9839
10600
  if (task) {
9840
10601
  await agentsCore.updateTask(dbClient_default)({
@@ -9853,7 +10614,7 @@ var ExecutionHandler = class {
9853
10614
  unregisterStreamHelper(requestId2);
9854
10615
  return { success: false, error: errorMessage, iterations };
9855
10616
  } catch (error) {
9856
- logger21.error({ error }, "Error in execution handler");
10617
+ logger23.error({ error }, "Error in execution handler");
9857
10618
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
9858
10619
  await sseHelper.writeOperation(
9859
10620
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -9881,7 +10642,7 @@ var ExecutionHandler = class {
9881
10642
  // src/routes/chat.ts
9882
10643
  init_logger();
9883
10644
  var app2 = new zodOpenapi.OpenAPIHono();
9884
- var logger22 = agentsCore.getLogger("completionsHandler");
10645
+ var logger24 = agentsCore.getLogger("completionsHandler");
9885
10646
  var chatCompletionsRoute = zodOpenapi.createRoute({
9886
10647
  method: "post",
9887
10648
  path: "/completions",
@@ -9893,37 +10654,37 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9893
10654
  body: {
9894
10655
  content: {
9895
10656
  "application/json": {
9896
- schema: z5.z.object({
9897
- model: z5.z.string().describe("The model to use for the completion"),
9898
- messages: z5.z.array(
9899
- z5.z.object({
9900
- role: z5.z.enum(["system", "user", "assistant", "function", "tool"]).describe("The role of the message"),
9901
- content: z5.z.union([
9902
- z5.z.string(),
9903
- z5.z.array(
9904
- z5.z.strictObject({
9905
- type: z5.z.string(),
9906
- text: z5.z.string().optional()
10657
+ schema: z6.z.object({
10658
+ model: z6.z.string().describe("The model to use for the completion"),
10659
+ messages: z6.z.array(
10660
+ z6.z.object({
10661
+ role: z6.z.enum(["system", "user", "assistant", "function", "tool"]).describe("The role of the message"),
10662
+ content: z6.z.union([
10663
+ z6.z.string(),
10664
+ z6.z.array(
10665
+ z6.z.strictObject({
10666
+ type: z6.z.string(),
10667
+ text: z6.z.string().optional()
9907
10668
  })
9908
10669
  )
9909
10670
  ]).describe("The message content"),
9910
- name: z5.z.string().optional().describe("The name of the message sender")
10671
+ name: z6.z.string().optional().describe("The name of the message sender")
9911
10672
  })
9912
10673
  ).describe("The conversation messages"),
9913
- temperature: z5.z.number().optional().describe("Controls randomness (0-1)"),
9914
- top_p: z5.z.number().optional().describe("Controls nucleus sampling"),
9915
- n: z5.z.number().optional().describe("Number of completions to generate"),
9916
- stream: z5.z.boolean().optional().describe("Whether to stream the response"),
9917
- max_tokens: z5.z.number().optional().describe("Maximum tokens to generate"),
9918
- presence_penalty: z5.z.number().optional().describe("Presence penalty (-2 to 2)"),
9919
- frequency_penalty: z5.z.number().optional().describe("Frequency penalty (-2 to 2)"),
9920
- logit_bias: z5.z.record(z5.z.string(), z5.z.number()).optional().describe("Token logit bias"),
9921
- user: z5.z.string().optional().describe("User identifier"),
9922
- conversationId: z5.z.string().optional().describe("Conversation ID for multi-turn chat"),
9923
- tools: z5.z.array(z5.z.string()).optional().describe("Available tools"),
9924
- runConfig: z5.z.record(z5.z.string(), z5.z.unknown()).optional().describe("Run configuration"),
9925
- requestContext: z5.z.record(z5.z.string(), z5.z.unknown()).optional().describe(
9926
- "Context data for template processing (validated against context config schema)"
10674
+ temperature: z6.z.number().optional().describe("Controls randomness (0-1)"),
10675
+ top_p: z6.z.number().optional().describe("Controls nucleus sampling"),
10676
+ n: z6.z.number().optional().describe("Number of completions to generate"),
10677
+ stream: z6.z.boolean().optional().describe("Whether to stream the response"),
10678
+ max_tokens: z6.z.number().optional().describe("Maximum tokens to generate"),
10679
+ presence_penalty: z6.z.number().optional().describe("Presence penalty (-2 to 2)"),
10680
+ frequency_penalty: z6.z.number().optional().describe("Frequency penalty (-2 to 2)"),
10681
+ logit_bias: z6.z.record(z6.z.string(), z6.z.number()).optional().describe("Token logit bias"),
10682
+ user: z6.z.string().optional().describe("User identifier"),
10683
+ conversationId: z6.z.string().optional().describe("Conversation ID for multi-turn chat"),
10684
+ tools: z6.z.array(z6.z.string()).optional().describe("Available tools"),
10685
+ runConfig: z6.z.record(z6.z.string(), z6.z.unknown()).optional().describe("Run configuration"),
10686
+ headers: z6.z.record(z6.z.string(), z6.z.unknown()).optional().describe(
10687
+ "Headers data for template processing (validated against context config schema)"
9927
10688
  )
9928
10689
  })
9929
10690
  }
@@ -9933,14 +10694,14 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9933
10694
  responses: {
9934
10695
  200: {
9935
10696
  description: "Streaming chat completion response in Server-Sent Events format",
9936
- headers: z5.z.object({
9937
- "Content-Type": z5.z.string().default("text/event-stream"),
9938
- "Cache-Control": z5.z.string().default("no-cache"),
9939
- Connection: z5.z.string().default("keep-alive")
10697
+ headers: z6.z.object({
10698
+ "Content-Type": z6.z.string().default("text/event-stream"),
10699
+ "Cache-Control": z6.z.string().default("no-cache"),
10700
+ Connection: z6.z.string().default("keep-alive")
9940
10701
  }),
9941
10702
  content: {
9942
10703
  "text/event-stream": {
9943
- schema: z5.z.string().describe("Server-Sent Events stream with chat completion chunks")
10704
+ schema: z6.z.string().describe("Server-Sent Events stream with chat completion chunks")
9944
10705
  }
9945
10706
  }
9946
10707
  },
@@ -9948,13 +10709,13 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9948
10709
  description: "Invalid request context or parameters",
9949
10710
  content: {
9950
10711
  "application/json": {
9951
- schema: z5.z.object({
9952
- error: z5.z.string(),
9953
- details: z5.z.array(
9954
- z5.z.object({
9955
- field: z5.z.string(),
9956
- message: z5.z.string(),
9957
- value: z5.z.unknown().optional()
10712
+ schema: z6.z.object({
10713
+ error: z6.z.string(),
10714
+ details: z6.z.array(
10715
+ z6.z.object({
10716
+ field: z6.z.string(),
10717
+ message: z6.z.string(),
10718
+ value: z6.z.unknown().optional()
9958
10719
  })
9959
10720
  ).optional()
9960
10721
  })
@@ -9965,8 +10726,8 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9965
10726
  description: "Agent graph or agent not found",
9966
10727
  content: {
9967
10728
  "application/json": {
9968
- schema: z5.z.object({
9969
- error: z5.z.string()
10729
+ schema: z6.z.object({
10730
+ error: z6.z.string()
9970
10731
  })
9971
10732
  }
9972
10733
  }
@@ -9975,9 +10736,9 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9975
10736
  description: "Internal server error",
9976
10737
  content: {
9977
10738
  "application/json": {
9978
- schema: z5.z.object({
9979
- error: z5.z.string(),
9980
- message: z5.z.string()
10739
+ schema: z6.z.object({
10740
+ error: z6.z.string(),
10741
+ message: z6.z.string()
9981
10742
  })
9982
10743
  }
9983
10744
  }
@@ -9999,7 +10760,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9999
10760
  tracestate: c.req.header("tracestate"),
10000
10761
  baggage: c.req.header("baggage")
10001
10762
  };
10002
- logger22.info(
10763
+ logger24.info(
10003
10764
  {
10004
10765
  otelHeaders,
10005
10766
  path: c.req.path,
@@ -10081,18 +10842,18 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10081
10842
  message: "Agent not found"
10082
10843
  });
10083
10844
  }
10084
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
10845
+ const validatedContext = c.get("validatedContext") || body.headers || {};
10085
10846
  const credentialStores = c.get("credentialStores");
10086
10847
  await agentsCore.handleContextResolution({
10087
10848
  tenantId,
10088
10849
  projectId,
10089
10850
  graphId,
10090
10851
  conversationId,
10091
- requestContext: validatedContext,
10852
+ headers: validatedContext,
10092
10853
  dbClient: dbClient_default,
10093
10854
  credentialStores
10094
10855
  });
10095
- logger22.info(
10856
+ logger24.info(
10096
10857
  {
10097
10858
  tenantId,
10098
10859
  projectId,
@@ -10101,7 +10862,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10101
10862
  defaultAgentId,
10102
10863
  activeAgentId: activeAgent?.activeAgentId || "none",
10103
10864
  hasContextConfig: !!agentGraph.contextConfigId,
10104
- hasRequestContext: !!body.requestContext,
10865
+ hasHeaders: !!body.headers,
10105
10866
  hasValidatedContext: !!validatedContext,
10106
10867
  validatedContextKeys: Object.keys(validatedContext)
10107
10868
  },
@@ -10140,7 +10901,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10140
10901
  try {
10141
10902
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10142
10903
  await sseHelper.writeRole();
10143
- logger22.info({ agentId }, "Starting execution");
10904
+ logger24.info({ agentId }, "Starting execution");
10144
10905
  const emitOperationsHeader = c.req.header("x-emit-operations");
10145
10906
  const emitOperations = emitOperationsHeader === "true";
10146
10907
  const executionHandler = new ExecutionHandler();
@@ -10153,7 +10914,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10153
10914
  sseHelper,
10154
10915
  emitOperations
10155
10916
  });
10156
- logger22.info(
10917
+ logger24.info(
10157
10918
  { result },
10158
10919
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10159
10920
  );
@@ -10167,7 +10928,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10167
10928
  }
10168
10929
  await sseHelper.complete();
10169
10930
  } catch (error) {
10170
- logger22.error(
10931
+ logger24.error(
10171
10932
  {
10172
10933
  error: error instanceof Error ? error.message : error,
10173
10934
  stack: error instanceof Error ? error.stack : void 0
@@ -10184,12 +10945,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10184
10945
  );
10185
10946
  await sseHelper.complete();
10186
10947
  } catch (streamError) {
10187
- logger22.error({ streamError }, "Failed to write error to stream");
10948
+ logger24.error({ streamError }, "Failed to write error to stream");
10188
10949
  }
10189
10950
  }
10190
10951
  });
10191
10952
  } catch (error) {
10192
- logger22.error(
10953
+ logger24.error(
10193
10954
  {
10194
10955
  error: error instanceof Error ? error.message : error,
10195
10956
  stack: error instanceof Error ? error.stack : void 0
@@ -10217,7 +10978,7 @@ var chat_default = app2;
10217
10978
  init_dbClient();
10218
10979
  init_logger();
10219
10980
  var app3 = new zodOpenapi.OpenAPIHono();
10220
- var logger23 = agentsCore.getLogger("chatDataStream");
10981
+ var logger25 = agentsCore.getLogger("chatDataStream");
10221
10982
  var chatDataStreamRoute = zodOpenapi.createRoute({
10222
10983
  method: "post",
10223
10984
  path: "/chat",
@@ -10248,7 +11009,7 @@ var chatDataStreamRoute = zodOpenapi.createRoute({
10248
11009
  ),
10249
11010
  id: zodOpenapi.z.string().optional(),
10250
11011
  conversationId: zodOpenapi.z.string().optional(),
10251
- requestContext: zodOpenapi.z.record(zodOpenapi.z.string(), zodOpenapi.z.unknown()).optional().describe("Context data for template processing")
11012
+ headers: zodOpenapi.z.record(zodOpenapi.z.string(), zodOpenapi.z.unknown()).optional().describe("Headers data for template processing")
10252
11013
  })
10253
11014
  }
10254
11015
  }
@@ -10321,20 +11082,20 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10321
11082
  message: "Agent not found"
10322
11083
  });
10323
11084
  }
10324
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
11085
+ const validatedContext = c.get("validatedContext") || body.headers || {};
10325
11086
  const credentialStores = c.get("credentialStores");
10326
11087
  await agentsCore.handleContextResolution({
10327
11088
  tenantId,
10328
11089
  projectId,
10329
11090
  graphId,
10330
11091
  conversationId,
10331
- requestContext: validatedContext,
11092
+ headers: validatedContext,
10332
11093
  dbClient: dbClient_default,
10333
11094
  credentialStores
10334
11095
  });
10335
11096
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
10336
11097
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
10337
- logger23.info({ userText, lastUserMessage }, "userText");
11098
+ logger25.info({ userText, lastUserMessage }, "userText");
10338
11099
  const messageSpan = api.trace.getActiveSpan();
10339
11100
  if (messageSpan) {
10340
11101
  messageSpan.setAttributes({
@@ -10379,7 +11140,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10379
11140
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
10380
11141
  }
10381
11142
  } catch (err) {
10382
- logger23.error({ err }, "Streaming error");
11143
+ logger25.error({ err }, "Streaming error");
10383
11144
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
10384
11145
  } finally {
10385
11146
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -10400,7 +11161,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10400
11161
  )
10401
11162
  );
10402
11163
  } catch (error) {
10403
- logger23.error({ error }, "chatDataStream error");
11164
+ logger25.error({ error }, "chatDataStream error");
10404
11165
  throw agentsCore.createApiError({
10405
11166
  code: "internal_server_error",
10406
11167
  message: "Failed to process chat completion"
@@ -10415,7 +11176,7 @@ init_logger();
10415
11176
  function createMCPSchema(schema) {
10416
11177
  return schema;
10417
11178
  }
10418
- var logger24 = agentsCore.getLogger("mcp");
11179
+ var logger26 = agentsCore.getLogger("mcp");
10419
11180
  var _MockResponseSingleton = class _MockResponseSingleton {
10420
11181
  constructor() {
10421
11182
  __publicField(this, "mockRes");
@@ -10470,21 +11231,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
10470
11231
  id: 0
10471
11232
  });
10472
11233
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
10473
- logger24.info({ sessionId }, "Spoofing initialization message to set transport state");
11234
+ logger26.info({ sessionId }, "Spoofing initialization message to set transport state");
10474
11235
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
10475
11236
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
10476
11237
  try {
10477
11238
  await transport.handleRequest(req, mockRes, spoofInitMessage);
10478
- logger24.info({ sessionId }, "Successfully spoofed initialization");
11239
+ logger26.info({ sessionId }, "Successfully spoofed initialization");
10479
11240
  } catch (spoofError) {
10480
- logger24.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11241
+ logger26.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
10481
11242
  }
10482
11243
  };
10483
11244
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10484
11245
  const sessionId = req.headers["mcp-session-id"];
10485
- logger24.info({ sessionId }, "Received MCP session ID");
11246
+ logger26.info({ sessionId }, "Received MCP session ID");
10486
11247
  if (!sessionId) {
10487
- logger24.info({ body }, "Missing session ID");
11248
+ logger26.info({ body }, "Missing session ID");
10488
11249
  res.writeHead(400).end(
10489
11250
  JSON.stringify({
10490
11251
  jsonrpc: "2.0",
@@ -10510,7 +11271,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10510
11271
  scopes: { tenantId, projectId },
10511
11272
  conversationId: sessionId
10512
11273
  });
10513
- logger24.info(
11274
+ logger26.info(
10514
11275
  {
10515
11276
  sessionId,
10516
11277
  conversationFound: !!conversation,
@@ -10521,7 +11282,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10521
11282
  "Conversation lookup result"
10522
11283
  );
10523
11284
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
10524
- logger24.info(
11285
+ logger26.info(
10525
11286
  { sessionId, conversationId: conversation?.id },
10526
11287
  "MCP session not found or invalid"
10527
11288
  );
@@ -10582,7 +11343,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10582
11343
  requestId: requestId2,
10583
11344
  sseHelper: mcpStreamHelper
10584
11345
  });
10585
- logger24.info(
11346
+ logger26.info(
10586
11347
  { result },
10587
11348
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10588
11349
  );
@@ -10606,7 +11367,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10606
11367
  ]
10607
11368
  };
10608
11369
  };
10609
- var getServer = async (requestContext, executionContext, conversationId, credentialStores) => {
11370
+ var getServer = async (headers, executionContext, conversationId, credentialStores) => {
10610
11371
  const { tenantId, projectId, graphId } = executionContext;
10611
11372
  setupTracing(conversationId, tenantId, graphId);
10612
11373
  const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
@@ -10662,18 +11423,18 @@ var getServer = async (requestContext, executionContext, conversationId, credent
10662
11423
  projectId,
10663
11424
  graphId,
10664
11425
  conversationId,
10665
- requestContext,
11426
+ headers,
10666
11427
  dbClient: dbClient_default,
10667
11428
  credentialStores
10668
11429
  });
10669
- logger24.info(
11430
+ logger26.info(
10670
11431
  {
10671
11432
  tenantId,
10672
11433
  projectId,
10673
11434
  graphId,
10674
11435
  conversationId,
10675
11436
  hasContextConfig: !!agentGraph.contextConfigId,
10676
- hasRequestContext: !!requestContext,
11437
+ hasHeaders: !!headers,
10677
11438
  hasValidatedContext: !!resolvedContext
10678
11439
  },
10679
11440
  "parameters"
@@ -10728,7 +11489,7 @@ var validateRequestParameters = (c) => {
10728
11489
  };
10729
11490
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
10730
11491
  const { tenantId, projectId, graphId } = executionContext;
10731
- logger24.info({ body }, "Received initialization request");
11492
+ logger26.info({ body }, "Received initialization request");
10732
11493
  const sessionId = agentsCore.getConversationId();
10733
11494
  const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
10734
11495
  scopes: { tenantId, projectId, graphId }
@@ -10768,7 +11529,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10768
11529
  }
10769
11530
  }
10770
11531
  });
10771
- logger24.info(
11532
+ logger26.info(
10772
11533
  { sessionId, conversationId: conversation.id },
10773
11534
  "Created MCP session as conversation"
10774
11535
  );
@@ -10777,9 +11538,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10777
11538
  });
10778
11539
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
10779
11540
  await server.connect(transport);
10780
- logger24.info({ sessionId }, "Server connected for initialization");
11541
+ logger26.info({ sessionId }, "Server connected for initialization");
10781
11542
  res.setHeader("Mcp-Session-Id", sessionId);
10782
- logger24.info(
11543
+ logger26.info(
10783
11544
  {
10784
11545
  sessionId,
10785
11546
  bodyMethod: body?.method,
@@ -10788,7 +11549,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10788
11549
  "About to handle initialization request"
10789
11550
  );
10790
11551
  await transport.handleRequest(req, res, body);
10791
- logger24.info({ sessionId }, "Successfully handled initialization request");
11552
+ logger26.info({ sessionId }, "Successfully handled initialization request");
10792
11553
  return fetchToNode.toFetchResponse(res);
10793
11554
  };
10794
11555
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -10816,8 +11577,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10816
11577
  sessionId,
10817
11578
  conversation.metadata?.session_data?.mcpProtocolVersion
10818
11579
  );
10819
- logger24.info({ sessionId }, "Server connected and transport initialized");
10820
- logger24.info(
11580
+ logger26.info({ sessionId }, "Server connected and transport initialized");
11581
+ logger26.info(
10821
11582
  {
10822
11583
  sessionId,
10823
11584
  bodyKeys: Object.keys(body || {}),
@@ -10831,9 +11592,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10831
11592
  );
10832
11593
  try {
10833
11594
  await transport.handleRequest(req, res, body);
10834
- logger24.info({ sessionId }, "Successfully handled MCP request");
11595
+ logger26.info({ sessionId }, "Successfully handled MCP request");
10835
11596
  } catch (transportError) {
10836
- logger24.error(
11597
+ logger26.error(
10837
11598
  {
10838
11599
  sessionId,
10839
11600
  error: transportError,
@@ -10884,13 +11645,13 @@ app4.openapi(
10884
11645
  }
10885
11646
  const { executionContext } = paramValidation;
10886
11647
  const body = c.get("requestBody") || {};
10887
- logger24.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
11648
+ logger26.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10888
11649
  const isInitRequest = body.method === "initialize";
10889
11650
  const { req, res } = fetchToNode.toReqRes(c.req.raw);
10890
11651
  const validatedContext = c.get("validatedContext") || {};
10891
11652
  const credentialStores = c.get("credentialStores");
10892
- logger24.info({ validatedContext }, "Validated context");
10893
- logger24.info({ req }, "request");
11653
+ logger26.info({ validatedContext }, "Validated context");
11654
+ logger26.info({ req }, "request");
10894
11655
  if (isInitRequest) {
10895
11656
  return await handleInitializationRequest(
10896
11657
  body,
@@ -10912,7 +11673,7 @@ app4.openapi(
10912
11673
  );
10913
11674
  }
10914
11675
  } catch (e) {
10915
- logger24.error(
11676
+ logger26.error(
10916
11677
  {
10917
11678
  error: e instanceof Error ? e.message : e,
10918
11679
  stack: e instanceof Error ? e.stack : void 0
@@ -10924,7 +11685,7 @@ app4.openapi(
10924
11685
  }
10925
11686
  );
10926
11687
  app4.get("/", async (c) => {
10927
- logger24.info({}, "Received GET MCP request");
11688
+ logger26.info({}, "Received GET MCP request");
10928
11689
  return c.json(
10929
11690
  {
10930
11691
  jsonrpc: "2.0",
@@ -10938,7 +11699,7 @@ app4.get("/", async (c) => {
10938
11699
  );
10939
11700
  });
10940
11701
  app4.delete("/", async (c) => {
10941
- logger24.info({}, "Received DELETE MCP request");
11702
+ logger26.info({}, "Received DELETE MCP request");
10942
11703
  return c.json(
10943
11704
  {
10944
11705
  jsonrpc: "2.0",
@@ -10951,7 +11712,7 @@ app4.delete("/", async (c) => {
10951
11712
  var mcp_default = app4;
10952
11713
 
10953
11714
  // src/app.ts
10954
- var logger25 = agentsCore.getLogger("agents-run-api");
11715
+ var logger27 = agentsCore.getLogger("agents-run-api");
10955
11716
  function createExecutionHono(serverConfig, credentialStores) {
10956
11717
  const app6 = new zodOpenapi.OpenAPIHono();
10957
11718
  app6.use("*", otel.otel());
@@ -10967,7 +11728,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10967
11728
  const body = await c.req.json();
10968
11729
  c.set("requestBody", body);
10969
11730
  } catch (error) {
10970
- logger25.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
11731
+ logger27.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
10971
11732
  }
10972
11733
  }
10973
11734
  return next();
@@ -11018,8 +11779,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11018
11779
  if (!isExpectedError) {
11019
11780
  const errorMessage = err instanceof Error ? err.message : String(err);
11020
11781
  const errorStack = err instanceof Error ? err.stack : void 0;
11021
- if (logger25) {
11022
- logger25.error(
11782
+ if (logger27) {
11783
+ logger27.error(
11023
11784
  {
11024
11785
  error: err,
11025
11786
  message: errorMessage,
@@ -11031,8 +11792,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11031
11792
  );
11032
11793
  }
11033
11794
  } else {
11034
- if (logger25) {
11035
- logger25.error(
11795
+ if (logger27) {
11796
+ logger27.error(
11036
11797
  {
11037
11798
  error: err,
11038
11799
  path: c.req.path,
@@ -11049,8 +11810,8 @@ function createExecutionHono(serverConfig, credentialStores) {
11049
11810
  const response = err.getResponse();
11050
11811
  return response;
11051
11812
  } catch (responseError) {
11052
- if (logger25) {
11053
- logger25.error({ error: responseError }, "Error while handling HTTPException response");
11813
+ if (logger27) {
11814
+ logger27.error({ error: responseError }, "Error while handling HTTPException response");
11054
11815
  }
11055
11816
  }
11056
11817
  }
@@ -11084,7 +11845,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11084
11845
  app6.use("*", async (c, next) => {
11085
11846
  const executionContext = c.get("executionContext");
11086
11847
  if (!executionContext) {
11087
- logger25.debug({}, "Empty execution context");
11848
+ logger27.debug({}, "Empty execution context");
11088
11849
  return next();
11089
11850
  }
11090
11851
  const { tenantId, projectId, graphId } = executionContext;
@@ -11093,7 +11854,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11093
11854
  if (requestBody) {
11094
11855
  conversationId = requestBody.conversationId;
11095
11856
  if (!conversationId) {
11096
- logger25.debug({ requestBody }, "No conversation ID found in request body");
11857
+ logger27.debug({ requestBody }, "No conversation ID found in request body");
11097
11858
  }
11098
11859
  }
11099
11860
  const entries = Object.fromEntries(
@@ -11108,7 +11869,7 @@ function createExecutionHono(serverConfig, credentialStores) {
11108
11869
  })
11109
11870
  );
11110
11871
  if (!Object.keys(entries).length) {
11111
- logger25.debug({}, "Empty entries for baggage");
11872
+ logger27.debug({}, "Empty entries for baggage");
11112
11873
  return next();
11113
11874
  }
11114
11875
  const bag = Object.entries(entries).reduce(