@inkeep/agents-run-api 0.14.16 → 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,61 @@ 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) {
2306
+ const key = `${artifactId}:${toolCallId}`;
2307
+ if (this.context.streamRequestId) {
2308
+ const cachedArtifact = await graphSessionManager.getArtifactCache(
2309
+ this.context.streamRequestId,
2310
+ key
2311
+ );
2312
+ if (cachedArtifact) {
2313
+ return this.formatArtifactSummaryData(cachedArtifact, artifactId, toolCallId);
2314
+ }
2315
+ }
2316
+ if (this.createdArtifacts.has(key)) {
2317
+ const cached = this.createdArtifacts.get(key);
2318
+ return this.formatArtifactSummaryData(cached, artifactId, toolCallId);
2319
+ }
2320
+ if (artifactMap?.has(key)) {
2321
+ const artifact = artifactMap.get(key);
2322
+ return this.formatArtifactSummaryData(artifact, artifactId, toolCallId);
2323
+ }
2324
+ try {
2325
+ if (!this.context.projectId || !this.context.taskId) {
2326
+ logger8.warn(
2327
+ { artifactId, toolCallId },
2328
+ "No projectId or taskId available for artifact lookup"
2329
+ );
2330
+ return null;
2331
+ }
2332
+ const artifacts = await agentsCore.getLedgerArtifacts(dbClient_default)({
2333
+ scopes: { tenantId: this.context.tenantId, projectId: this.context.projectId },
2334
+ artifactId,
2335
+ taskId: this.context.taskId
2336
+ });
2337
+ if (artifacts.length > 0) {
2338
+ return this.formatArtifactSummaryData(artifacts[0], artifactId, toolCallId);
2339
+ }
2340
+ } catch (error) {
2341
+ logger8.warn(
2342
+ { artifactId, toolCallId, taskId: this.context.taskId, error },
2343
+ "Failed to fetch artifact"
2344
+ );
2345
+ }
2346
+ return null;
2347
+ }
2348
+ /**
2349
+ * Get artifact full data by ID and tool call ID
2350
+ */
2351
+ async getArtifactFull(artifactId, toolCallId, artifactMap) {
1955
2352
  const key = `${artifactId}:${toolCallId}`;
1956
2353
  if (this.context.streamRequestId) {
1957
2354
  const cachedArtifact = await graphSessionManager.getArtifactCache(
@@ -1959,20 +2356,20 @@ var _ArtifactService = class _ArtifactService {
1959
2356
  key
1960
2357
  );
1961
2358
  if (cachedArtifact) {
1962
- return this.formatArtifactData(cachedArtifact, artifactId, toolCallId);
2359
+ return this.formatArtifactFullData(cachedArtifact, artifactId, toolCallId);
1963
2360
  }
1964
2361
  }
1965
2362
  if (this.createdArtifacts.has(key)) {
1966
2363
  const cached = this.createdArtifacts.get(key);
1967
- return this.formatArtifactData(cached, artifactId, toolCallId);
2364
+ return this.formatArtifactFullData(cached, artifactId, toolCallId);
1968
2365
  }
1969
2366
  if (artifactMap?.has(key)) {
1970
2367
  const artifact = artifactMap.get(key);
1971
- return this.formatArtifactData(artifact, artifactId, toolCallId);
2368
+ return this.formatArtifactFullData(artifact, artifactId, toolCallId);
1972
2369
  }
1973
2370
  try {
1974
2371
  if (!this.context.projectId || !this.context.taskId) {
1975
- logger7.warn(
2372
+ logger8.warn(
1976
2373
  { artifactId, toolCallId },
1977
2374
  "No projectId or taskId available for artifact lookup"
1978
2375
  );
@@ -1984,10 +2381,10 @@ var _ArtifactService = class _ArtifactService {
1984
2381
  taskId: this.context.taskId
1985
2382
  });
1986
2383
  if (artifacts.length > 0) {
1987
- return this.formatArtifactData(artifacts[0], artifactId, toolCallId);
2384
+ return this.formatArtifactFullData(artifacts[0], artifactId, toolCallId);
1988
2385
  }
1989
2386
  } catch (error) {
1990
- logger7.warn(
2387
+ logger8.warn(
1991
2388
  { artifactId, toolCallId, taskId: this.context.taskId, error },
1992
2389
  "Failed to fetch artifact"
1993
2390
  );
@@ -1995,16 +2392,29 @@ var _ArtifactService = class _ArtifactService {
1995
2392
  return null;
1996
2393
  }
1997
2394
  /**
1998
- * Format raw artifact to standardized data format
2395
+ * Format raw artifact to standardized summary data format
1999
2396
  */
2000
- formatArtifactData(artifact, artifactId, toolCallId) {
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,9 +3055,9 @@ __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
- // Session-scoped ArtifactParser instance
3060
+ // Whether to send data operations
2528
3061
  constructor(sessionId, messageId, graphId, tenantId, projectId, contextId) {
2529
3062
  this.sessionId = sessionId;
2530
3063
  this.messageId = messageId;
@@ -2553,7 +3086,9 @@ var GraphSession = class {
2553
3086
  __publicField(this, "artifactService");
2554
3087
  // Session-scoped ArtifactService instance
2555
3088
  __publicField(this, "artifactParser");
2556
- logger9.debug({ sessionId, messageId, graphId }, "GraphSession created");
3089
+ // Session-scoped ArtifactParser instance
3090
+ __publicField(this, "isEmitOperations", false);
3091
+ logger10.debug({ sessionId, messageId, graphId }, "GraphSession created");
2557
3092
  if (tenantId && projectId) {
2558
3093
  toolSessionManager.createSessionWithId(
2559
3094
  sessionId,
@@ -2577,10 +3112,84 @@ var GraphSession = class {
2577
3112
  sessionId,
2578
3113
  contextId,
2579
3114
  taskId: `task_${contextId}-${messageId}`,
2580
- streamRequestId: sessionId
3115
+ streamRequestId: sessionId,
3116
+ artifactService: this.artifactService
3117
+ // Pass the shared ArtifactService
2581
3118
  });
2582
3119
  }
2583
3120
  }
3121
+ /**
3122
+ * Enable emit operations to send data operations
3123
+ */
3124
+ enableEmitOperations() {
3125
+ this.isEmitOperations = true;
3126
+ logger10.info(
3127
+ { sessionId: this.sessionId },
3128
+ "\u{1F50D} DEBUG: Emit operations enabled for GraphSession"
3129
+ );
3130
+ }
3131
+ /**
3132
+ * Send data operation to stream when emit operations is enabled
3133
+ */
3134
+ async sendDataOperation(event) {
3135
+ try {
3136
+ const streamHelper = getStreamHelper(this.sessionId);
3137
+ if (streamHelper) {
3138
+ const formattedOperation = {
3139
+ type: event.eventType,
3140
+ label: this.generateEventLabel(event),
3141
+ details: {
3142
+ timestamp: event.timestamp,
3143
+ agentId: event.agentId,
3144
+ data: event.data
3145
+ }
3146
+ };
3147
+ await streamHelper.writeOperation(formattedOperation);
3148
+ }
3149
+ } catch (error) {
3150
+ logger10.error(
3151
+ {
3152
+ sessionId: this.sessionId,
3153
+ eventType: event.eventType,
3154
+ error: error instanceof Error ? error.message : error
3155
+ },
3156
+ "\u274C DEBUG: Failed to send data operation"
3157
+ );
3158
+ }
3159
+ }
3160
+ /**
3161
+ * Generate human-readable labels for events
3162
+ */
3163
+ generateEventLabel(event) {
3164
+ switch (event.eventType) {
3165
+ case "agent_generate":
3166
+ return `Agent ${event.agentId} generating response`;
3167
+ case "agent_reasoning":
3168
+ return `Agent ${event.agentId} reasoning through request`;
3169
+ case "tool_execution": {
3170
+ const toolData = event.data;
3171
+ return `Tool execution: ${toolData.toolName || "unknown"}`;
3172
+ }
3173
+ case "transfer": {
3174
+ const transferData = event.data;
3175
+ return `Agent transfer: ${transferData.fromAgent} \u2192 ${transferData.targetAgent}`;
3176
+ }
3177
+ case "delegation_sent": {
3178
+ const delegationData = event.data;
3179
+ return `Task delegated: ${delegationData.fromAgent} \u2192 ${delegationData.targetAgent}`;
3180
+ }
3181
+ case "delegation_returned": {
3182
+ const returnData = event.data;
3183
+ return `Task completed: ${returnData.targetAgent} \u2192 ${returnData.fromAgent}`;
3184
+ }
3185
+ case "artifact_saved": {
3186
+ const artifactData = event.data;
3187
+ return `Artifact saved: ${artifactData.artifactType || "unknown type"}`;
3188
+ }
3189
+ default:
3190
+ return `${event.eventType} event`;
3191
+ }
3192
+ }
2584
3193
  /**
2585
3194
  * Initialize status updates for this session
2586
3195
  */
@@ -2601,7 +3210,7 @@ var GraphSession = class {
2601
3210
  if (this.statusUpdateState.config.timeInSeconds) {
2602
3211
  this.statusUpdateTimer = setInterval(async () => {
2603
3212
  if (!this.statusUpdateState || this.isEnded) {
2604
- logger9.debug(
3213
+ logger10.debug(
2605
3214
  { sessionId: this.sessionId },
2606
3215
  "Timer triggered but session already cleaned up or ended"
2607
3216
  );
@@ -2613,7 +3222,7 @@ var GraphSession = class {
2613
3222
  }
2614
3223
  await this.checkAndSendTimeBasedUpdate();
2615
3224
  }, this.statusUpdateState.config.timeInSeconds * 1e3);
2616
- logger9.info(
3225
+ logger10.info(
2617
3226
  {
2618
3227
  sessionId: this.sessionId,
2619
3228
  intervalMs: this.statusUpdateState.config.timeInSeconds * 1e3
@@ -2626,8 +3235,16 @@ var GraphSession = class {
2626
3235
  * Record an event in the session and trigger status updates if configured
2627
3236
  */
2628
3237
  recordEvent(eventType, agentId, data) {
3238
+ if (this.isEmitOperations) {
3239
+ this.sendDataOperation({
3240
+ timestamp: Date.now(),
3241
+ eventType,
3242
+ agentId,
3243
+ data
3244
+ });
3245
+ }
2629
3246
  if (this.isEnded) {
2630
- logger9.debug(
3247
+ logger10.debug(
2631
3248
  {
2632
3249
  sessionId: this.sessionId,
2633
3250
  eventType,
@@ -2647,7 +3264,7 @@ var GraphSession = class {
2647
3264
  if (eventType === "artifact_saved" && data.pendingGeneration) {
2648
3265
  const artifactId = data.artifactId;
2649
3266
  if (this.pendingArtifacts.size >= this.MAX_PENDING_ARTIFACTS) {
2650
- logger9.warn(
3267
+ logger10.warn(
2651
3268
  {
2652
3269
  sessionId: this.sessionId,
2653
3270
  artifactId,
@@ -2669,7 +3286,7 @@ var GraphSession = class {
2669
3286
  this.artifactProcessingErrors.set(artifactId, errorCount);
2670
3287
  if (errorCount >= this.MAX_ARTIFACT_RETRIES) {
2671
3288
  this.pendingArtifacts.delete(artifactId);
2672
- logger9.error(
3289
+ logger10.error(
2673
3290
  {
2674
3291
  sessionId: this.sessionId,
2675
3292
  artifactId,
@@ -2681,7 +3298,7 @@ var GraphSession = class {
2681
3298
  "Artifact processing failed after max retries, giving up"
2682
3299
  );
2683
3300
  } else {
2684
- logger9.warn(
3301
+ logger10.warn(
2685
3302
  {
2686
3303
  sessionId: this.sessionId,
2687
3304
  artifactId,
@@ -2703,14 +3320,14 @@ var GraphSession = class {
2703
3320
  */
2704
3321
  checkStatusUpdates() {
2705
3322
  if (this.isEnded) {
2706
- logger9.debug(
3323
+ logger10.debug(
2707
3324
  { sessionId: this.sessionId },
2708
3325
  "Session has ended - skipping status update check"
2709
3326
  );
2710
3327
  return;
2711
3328
  }
2712
3329
  if (!this.statusUpdateState) {
2713
- logger9.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
3330
+ logger10.debug({ sessionId: this.sessionId }, "No status update state - skipping check");
2714
3331
  return;
2715
3332
  }
2716
3333
  const statusUpdateState = this.statusUpdateState;
@@ -2721,11 +3338,11 @@ var GraphSession = class {
2721
3338
  */
2722
3339
  async checkAndSendTimeBasedUpdate() {
2723
3340
  if (this.isEnded) {
2724
- 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");
2725
3342
  return;
2726
3343
  }
2727
3344
  if (!this.statusUpdateState) {
2728
- logger9.debug(
3345
+ logger10.debug(
2729
3346
  { sessionId: this.sessionId },
2730
3347
  "No status updates configured for time-based check"
2731
3348
  );
@@ -2738,7 +3355,7 @@ var GraphSession = class {
2738
3355
  try {
2739
3356
  await this.generateAndSendUpdate();
2740
3357
  } catch (error) {
2741
- logger9.error(
3358
+ logger10.error(
2742
3359
  {
2743
3360
  sessionId: this.sessionId,
2744
3361
  error: error instanceof Error ? error.message : "Unknown error"
@@ -2841,29 +3458,29 @@ var GraphSession = class {
2841
3458
  */
2842
3459
  async generateAndSendUpdate() {
2843
3460
  if (this.isEnded) {
2844
- logger9.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
3461
+ logger10.debug({ sessionId: this.sessionId }, "Session has ended - not generating update");
2845
3462
  return;
2846
3463
  }
2847
3464
  if (this.isTextStreaming) {
2848
- logger9.debug(
3465
+ logger10.debug(
2849
3466
  { sessionId: this.sessionId },
2850
3467
  "Text is currently streaming - skipping status update"
2851
3468
  );
2852
3469
  return;
2853
3470
  }
2854
3471
  if (this.isGeneratingUpdate) {
2855
- logger9.debug(
3472
+ logger10.debug(
2856
3473
  { sessionId: this.sessionId },
2857
3474
  "Update already in progress - skipping duplicate generation"
2858
3475
  );
2859
3476
  return;
2860
3477
  }
2861
3478
  if (!this.statusUpdateState) {
2862
- 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");
2863
3480
  return;
2864
3481
  }
2865
3482
  if (!this.graphId) {
2866
- logger9.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
3483
+ logger10.warn({ sessionId: this.sessionId }, "No graph ID - cannot generate update");
2867
3484
  return;
2868
3485
  }
2869
3486
  const newEventCount = this.events.length - this.statusUpdateState.lastEventCount;
@@ -2875,7 +3492,7 @@ var GraphSession = class {
2875
3492
  try {
2876
3493
  const streamHelper = getStreamHelper(this.sessionId);
2877
3494
  if (!streamHelper) {
2878
- logger9.warn(
3495
+ logger10.warn(
2879
3496
  { sessionId: this.sessionId },
2880
3497
  "No stream helper found - cannot send status update"
2881
3498
  );
@@ -2895,7 +3512,7 @@ var GraphSession = class {
2895
3512
  if (result.summaries && result.summaries.length > 0) {
2896
3513
  for (const summary of result.summaries) {
2897
3514
  if (!summary || !summary.type || !summary.data || !summary.data.label || Object.keys(summary.data).length === 0) {
2898
- logger9.warn(
3515
+ logger10.warn(
2899
3516
  {
2900
3517
  sessionId: this.sessionId,
2901
3518
  summary
@@ -2932,7 +3549,7 @@ var GraphSession = class {
2932
3549
  this.statusUpdateState.lastEventCount = this.events.length;
2933
3550
  }
2934
3551
  } catch (error) {
2935
- logger9.error(
3552
+ logger10.error(
2936
3553
  {
2937
3554
  sessionId: this.sessionId,
2938
3555
  error: error instanceof Error ? error.message : "Unknown error",
@@ -2970,7 +3587,7 @@ var GraphSession = class {
2970
3587
  this.releaseUpdateLock();
2971
3588
  }
2972
3589
  } catch (error) {
2973
- logger9.error(
3590
+ logger10.error(
2974
3591
  {
2975
3592
  sessionId: this.sessionId,
2976
3593
  error: error instanceof Error ? error.message : "Unknown error"
@@ -3048,7 +3665,7 @@ User's Question/Context:
3048
3665
  ${conversationHistory}
3049
3666
  ` : "";
3050
3667
  } catch (error) {
3051
- logger9.warn(
3668
+ logger10.warn(
3052
3669
  { sessionId: this.sessionId, error },
3053
3670
  "Failed to fetch conversation history for structured status update"
3054
3671
  );
@@ -3058,13 +3675,13 @@ ${conversationHistory}
3058
3675
  Previous updates sent to user:
3059
3676
  ${previousSummaries.map((s, i) => `${i + 1}. ${s}`).join("\n")}
3060
3677
  ` : "";
3061
- const selectionSchema = z5.z.object(
3678
+ const selectionSchema = z6.z.object(
3062
3679
  Object.fromEntries([
3063
3680
  // Add no_relevant_updates schema
3064
3681
  [
3065
3682
  "no_relevant_updates",
3066
- z5.z.object({
3067
- no_updates: z5.z.boolean().default(true)
3683
+ z6.z.object({
3684
+ no_updates: z6.z.boolean().default(true)
3068
3685
  }).optional().describe(
3069
3686
  "Use when nothing substantially new to report. Should only use on its own."
3070
3687
  )
@@ -3182,7 +3799,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3182
3799
  return { summaries };
3183
3800
  } catch (error) {
3184
3801
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3185
- logger9.error({ error }, "Failed to generate structured update, using fallback");
3802
+ logger10.error({ error }, "Failed to generate structured update, using fallback");
3186
3803
  return { summaries: [] };
3187
3804
  } finally {
3188
3805
  span.end();
@@ -3197,8 +3814,8 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3197
3814
  if (component.detailsSchema && "properties" in component.detailsSchema) {
3198
3815
  return this.buildZodSchemaFromJson(component.detailsSchema);
3199
3816
  }
3200
- return z5.z.object({
3201
- label: z5.z.string().describe(
3817
+ return z6.z.object({
3818
+ label: z6.z.string().describe(
3202
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.'
3203
3820
  )
3204
3821
  });
@@ -3208,56 +3825,56 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3208
3825
  */
3209
3826
  buildZodSchemaFromJson(jsonSchema) {
3210
3827
  const properties = {};
3211
- properties["label"] = z5.z.string().describe(
3828
+ properties["label"] = z6.z.string().describe(
3212
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.'
3213
3830
  );
3214
3831
  for (const [key, value] of Object.entries(jsonSchema.properties)) {
3215
3832
  let zodType;
3216
3833
  if (value.enum && Array.isArray(value.enum)) {
3217
3834
  if (value.enum.length === 1) {
3218
- zodType = z5.z.literal(value.enum[0]);
3835
+ zodType = z6.z.literal(value.enum[0]);
3219
3836
  } else {
3220
3837
  const [first, ...rest] = value.enum;
3221
- zodType = z5.z.enum([first, ...rest]);
3838
+ zodType = z6.z.enum([first, ...rest]);
3222
3839
  }
3223
3840
  } else if (value.type === "string") {
3224
- zodType = z5.z.string();
3841
+ zodType = z6.z.string();
3225
3842
  if (value.minLength) zodType = zodType.min(value.minLength);
3226
3843
  if (value.maxLength) zodType = zodType.max(value.maxLength);
3227
3844
  if (value.format === "email") zodType = zodType.email();
3228
3845
  if (value.format === "url" || value.format === "uri")
3229
3846
  zodType = zodType.url();
3230
3847
  } else if (value.type === "number" || value.type === "integer") {
3231
- zodType = value.type === "integer" ? z5.z.number().int() : z5.z.number();
3848
+ zodType = value.type === "integer" ? z6.z.number().int() : z6.z.number();
3232
3849
  if (value.minimum !== void 0) zodType = zodType.min(value.minimum);
3233
3850
  if (value.maximum !== void 0) zodType = zodType.max(value.maximum);
3234
3851
  } else if (value.type === "boolean") {
3235
- zodType = z5.z.boolean();
3852
+ zodType = z6.z.boolean();
3236
3853
  } else if (value.type === "array") {
3237
3854
  if (value.items) {
3238
3855
  if (value.items.enum && Array.isArray(value.items.enum)) {
3239
3856
  const [first, ...rest] = value.items.enum;
3240
- zodType = z5.z.array(z5.z.enum([first, ...rest]));
3857
+ zodType = z6.z.array(z6.z.enum([first, ...rest]));
3241
3858
  } else if (value.items.type === "string") {
3242
- zodType = z5.z.array(z5.z.string());
3859
+ zodType = z6.z.array(z6.z.string());
3243
3860
  } else if (value.items.type === "number") {
3244
- zodType = z5.z.array(z5.z.number());
3861
+ zodType = z6.z.array(z6.z.number());
3245
3862
  } else if (value.items.type === "boolean") {
3246
- zodType = z5.z.array(z5.z.boolean());
3863
+ zodType = z6.z.array(z6.z.boolean());
3247
3864
  } else if (value.items.type === "object") {
3248
- 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()));
3249
3866
  } else {
3250
- zodType = z5.z.array(z5.z.any());
3867
+ zodType = z6.z.array(z6.z.any());
3251
3868
  }
3252
3869
  } else {
3253
- zodType = z5.z.array(z5.z.any());
3870
+ zodType = z6.z.array(z6.z.any());
3254
3871
  }
3255
3872
  if (value.minItems) zodType = zodType.min(value.minItems);
3256
3873
  if (value.maxItems) zodType = zodType.max(value.maxItems);
3257
3874
  } else if (value.type === "object") {
3258
- zodType = z5.z.record(z5.z.string(), z5.z.any());
3875
+ zodType = z6.z.record(z6.z.string(), z6.z.any());
3259
3876
  } else {
3260
- zodType = z5.z.any();
3877
+ zodType = z6.z.any();
3261
3878
  }
3262
3879
  if (value.description) {
3263
3880
  zodType = zodType.describe(value.description);
@@ -3267,7 +3884,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3267
3884
  }
3268
3885
  properties[key] = zodType;
3269
3886
  }
3270
- return z5.z.object(properties);
3887
+ return z6.z.object(properties);
3271
3888
  }
3272
3889
  /**
3273
3890
  * Extract user-visible activities with rich formatting and complete information
@@ -3327,6 +3944,9 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3327
3944
  "graph_session.id": this.sessionId,
3328
3945
  "artifact.id": artifactData.artifactId,
3329
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),
3330
3950
  "tenant.id": artifactData.tenantId || "unknown",
3331
3951
  "project.id": artifactData.projectId || "unknown",
3332
3952
  "context.id": artifactData.contextId || "unknown",
@@ -3377,8 +3997,7 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
3377
3997
  Tool Context: ${toolContext ? JSON.stringify(toolContext, null, 2) : "No tool context"}
3378
3998
  Context: ${conversationHistory?.slice(-200) || "Processing"}
3379
3999
  Type: ${artifactData.artifactType || "data"}
3380
- Summary: ${JSON.stringify(artifactData.summaryProps, null, 2)}
3381
- Full: ${JSON.stringify(artifactData.fullProps, null, 2)}
4000
+ Data: ${JSON.stringify(artifactData.data || artifactData.summaryData, null, 2)}
3382
4001
 
3383
4002
  Make it specific and relevant.`;
3384
4003
  let modelToUse = this.statusUpdateState?.summarizerModel;
@@ -3396,7 +4015,7 @@ Make it specific and relevant.`;
3396
4015
  });
3397
4016
  if (agentData && "models" in agentData && agentData.models?.base?.model) {
3398
4017
  modelToUse = agentData.models.base;
3399
- logger9.info(
4018
+ logger10.info(
3400
4019
  {
3401
4020
  sessionId: this.sessionId,
3402
4021
  artifactId: artifactData.artifactId,
@@ -3407,7 +4026,7 @@ Make it specific and relevant.`;
3407
4026
  );
3408
4027
  }
3409
4028
  } catch (error) {
3410
- logger9.warn(
4029
+ logger10.warn(
3411
4030
  {
3412
4031
  sessionId: this.sessionId,
3413
4032
  artifactId: artifactData.artifactId,
@@ -3419,7 +4038,7 @@ Make it specific and relevant.`;
3419
4038
  }
3420
4039
  }
3421
4040
  if (!modelToUse?.model?.trim()) {
3422
- logger9.warn(
4041
+ logger10.warn(
3423
4042
  {
3424
4043
  sessionId: this.sessionId,
3425
4044
  artifactId: artifactData.artifactId
@@ -3440,9 +4059,9 @@ Make it specific and relevant.`;
3440
4059
  };
3441
4060
  } else {
3442
4061
  const model = ModelFactory.createModel(modelToUse);
3443
- const schema = z5.z.object({
3444
- name: z5.z.string().describe("Concise, descriptive name for the artifact"),
3445
- 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")
3446
4065
  });
3447
4066
  const { object } = await tracer.startActiveSpan(
3448
4067
  "graph_session.generate_artifact_metadata",
@@ -3452,8 +4071,12 @@ Make it specific and relevant.`;
3452
4071
  "llm.operation": "generate_object",
3453
4072
  "artifact.id": artifactData.artifactId,
3454
4073
  "artifact.type": artifactData.artifactType,
3455
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3456
- "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
+ ),
3457
4080
  "prompt.length": prompt.length
3458
4081
  }
3459
4082
  },
@@ -3483,8 +4106,12 @@ Make it specific and relevant.`;
3483
4106
  "artifact.type": artifactData.artifactType,
3484
4107
  "artifact.name": result2.object.name,
3485
4108
  "artifact.description": result2.object.description,
3486
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3487
- "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
+ ),
3488
4115
  "generation.name_length": result2.object.name.length,
3489
4116
  "generation.description_length": result2.object.description.length,
3490
4117
  "generation.attempts": attempt
@@ -3493,7 +4120,7 @@ Make it specific and relevant.`;
3493
4120
  return result2;
3494
4121
  } catch (error) {
3495
4122
  lastError = error instanceof Error ? error : new Error(String(error));
3496
- logger9.warn(
4123
+ logger10.warn(
3497
4124
  {
3498
4125
  sessionId: this.sessionId,
3499
4126
  artifactId: artifactData.artifactId,
@@ -3509,7 +4136,10 @@ Make it specific and relevant.`;
3509
4136
  }
3510
4137
  }
3511
4138
  }
3512
- agentsCore.setSpanWithError(generationSpan, lastError instanceof Error ? lastError : new Error(String(lastError)));
4139
+ agentsCore.setSpanWithError(
4140
+ generationSpan,
4141
+ lastError instanceof Error ? lastError : new Error(String(lastError))
4142
+ );
3513
4143
  throw new Error(
3514
4144
  `Artifact name/description generation failed after ${maxRetries} attempts: ${lastError?.message}`
3515
4145
  );
@@ -3530,9 +4160,9 @@ Make it specific and relevant.`;
3530
4160
  name: result.name,
3531
4161
  description: result.description,
3532
4162
  type: artifactData.artifactType || "source",
3533
- summaryProps: artifactData.summaryProps || {},
3534
- fullProps: artifactData.fullProps || {},
3535
- metadata: artifactData.metadata || {}
4163
+ data: artifactData.data || {},
4164
+ metadata: artifactData.metadata || {},
4165
+ toolCallId: artifactData.toolCallId
3536
4166
  });
3537
4167
  mainSaveSucceeded = true;
3538
4168
  span.setAttributes({
@@ -3542,7 +4172,7 @@ Make it specific and relevant.`;
3542
4172
  });
3543
4173
  span.setStatus({ code: api.SpanStatusCode.OK });
3544
4174
  } catch (saveError) {
3545
- logger9.error(
4175
+ logger10.error(
3546
4176
  {
3547
4177
  sessionId: this.sessionId,
3548
4178
  artifactId: artifactData.artifactId,
@@ -3566,11 +4196,11 @@ Make it specific and relevant.`;
3566
4196
  name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
3567
4197
  description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolName || "tool results"}`,
3568
4198
  type: artifactData.artifactType || "source",
3569
- summaryProps: artifactData.summaryProps || {},
3570
- fullProps: artifactData.fullProps || {},
3571
- metadata: artifactData.metadata || {}
4199
+ data: artifactData.data || {},
4200
+ metadata: artifactData.metadata || {},
4201
+ toolCallId: artifactData.toolCallId
3572
4202
  });
3573
- logger9.info(
4203
+ logger10.info(
3574
4204
  {
3575
4205
  sessionId: this.sessionId,
3576
4206
  artifactId: artifactData.artifactId
@@ -3581,7 +4211,7 @@ Make it specific and relevant.`;
3581
4211
  } catch (fallbackError) {
3582
4212
  const isDuplicateError = fallbackError instanceof Error && (fallbackError.message?.includes("UNIQUE") || fallbackError.message?.includes("duplicate"));
3583
4213
  if (isDuplicateError) ; else {
3584
- logger9.error(
4214
+ logger10.error(
3585
4215
  {
3586
4216
  sessionId: this.sessionId,
3587
4217
  artifactId: artifactData.artifactId,
@@ -3594,7 +4224,7 @@ Make it specific and relevant.`;
3594
4224
  }
3595
4225
  } catch (error) {
3596
4226
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
3597
- logger9.error(
4227
+ logger10.error(
3598
4228
  {
3599
4229
  sessionId: this.sessionId,
3600
4230
  artifactId: artifactData.artifactId,
@@ -3613,7 +4243,7 @@ Make it specific and relevant.`;
3613
4243
  */
3614
4244
  setArtifactCache(key, artifact) {
3615
4245
  this.artifactCache.set(key, artifact);
3616
- logger9.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
4246
+ logger10.debug({ sessionId: this.sessionId, key }, "Artifact cached in session");
3617
4247
  }
3618
4248
  /**
3619
4249
  * Get session-scoped ArtifactService instance
@@ -3632,9 +4262,17 @@ Make it specific and relevant.`;
3632
4262
  */
3633
4263
  getArtifactCache(key) {
3634
4264
  const artifact = this.artifactCache.get(key);
3635
- logger9.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
4265
+ logger10.debug({ sessionId: this.sessionId, key, found: !!artifact }, "Artifact cache lookup");
3636
4266
  return artifact || null;
3637
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
+ }
3638
4276
  };
3639
4277
  var GraphSessionManager = class {
3640
4278
  constructor() {
@@ -3647,7 +4285,7 @@ var GraphSessionManager = class {
3647
4285
  const sessionId = messageId;
3648
4286
  const session = new GraphSession(sessionId, messageId, graphId, tenantId, projectId, contextId);
3649
4287
  this.sessions.set(sessionId, session);
3650
- logger9.info(
4288
+ logger10.info(
3651
4289
  { sessionId, messageId, graphId, tenantId, projectId, contextId },
3652
4290
  "GraphSession created"
3653
4291
  );
@@ -3661,7 +4299,7 @@ var GraphSessionManager = class {
3661
4299
  if (session) {
3662
4300
  session.initializeStatusUpdates(config, summarizerModel);
3663
4301
  } else {
3664
- logger9.error(
4302
+ logger10.error(
3665
4303
  {
3666
4304
  sessionId,
3667
4305
  availableSessions: Array.from(this.sessions.keys())
@@ -3670,6 +4308,23 @@ var GraphSessionManager = class {
3670
4308
  );
3671
4309
  }
3672
4310
  }
4311
+ /**
4312
+ * Enable emit operations for a session to send data operations
4313
+ */
4314
+ enableEmitOperations(sessionId) {
4315
+ const session = this.sessions.get(sessionId);
4316
+ if (session) {
4317
+ session.enableEmitOperations();
4318
+ } else {
4319
+ logger10.error(
4320
+ {
4321
+ sessionId,
4322
+ availableSessions: Array.from(this.sessions.keys())
4323
+ },
4324
+ "Session not found for emit operations enablement"
4325
+ );
4326
+ }
4327
+ }
3673
4328
  /**
3674
4329
  * Get an existing session
3675
4330
  */
@@ -3682,7 +4337,7 @@ var GraphSessionManager = class {
3682
4337
  recordEvent(sessionId, eventType, agentId, data) {
3683
4338
  const session = this.sessions.get(sessionId);
3684
4339
  if (!session) {
3685
- logger9.warn({ sessionId }, "Attempted to record event in non-existent session");
4340
+ logger10.warn({ sessionId }, "Attempted to record event in non-existent session");
3686
4341
  return;
3687
4342
  }
3688
4343
  session.recordEvent(eventType, agentId, data);
@@ -3693,12 +4348,12 @@ var GraphSessionManager = class {
3693
4348
  endSession(sessionId) {
3694
4349
  const session = this.sessions.get(sessionId);
3695
4350
  if (!session) {
3696
- logger9.warn({ sessionId }, "Attempted to end non-existent session");
4351
+ logger10.warn({ sessionId }, "Attempted to end non-existent session");
3697
4352
  return [];
3698
4353
  }
3699
4354
  const events = session.getEvents();
3700
4355
  const summary = session.getSummary();
3701
- logger9.info({ sessionId, summary }, "GraphSession ended");
4356
+ logger10.info({ sessionId, summary }, "GraphSession ended");
3702
4357
  session.cleanup();
3703
4358
  this.sessions.delete(sessionId);
3704
4359
  return events;
@@ -3752,12 +4407,61 @@ var GraphSessionManager = class {
3752
4407
  const session = this.sessions.get(sessionId);
3753
4408
  return session ? session.getArtifactParser() : null;
3754
4409
  }
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
+ }
3755
4419
  };
3756
4420
  var graphSessionManager = new GraphSessionManager();
3757
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();
4461
+
3758
4462
  // src/services/IncrementalStreamParser.ts
3759
4463
  init_logger();
3760
- var logger10 = agentsCore.getLogger("IncrementalStreamParser");
4464
+ var logger11 = agentsCore.getLogger("IncrementalStreamParser");
3761
4465
  var _IncrementalStreamParser = class _IncrementalStreamParser {
3762
4466
  // Max number of collected parts to prevent unbounded growth
3763
4467
  constructor(streamHelper, tenantId, contextId, artifactParserOptions) {
@@ -3786,9 +4490,20 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3786
4490
  return;
3787
4491
  }
3788
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
+ }
3789
4502
  this.artifactParser = new ArtifactParser(tenantId, {
3790
4503
  ...artifactParserOptions,
3791
- contextId
4504
+ contextId,
4505
+ artifactService: sharedArtifactService
4506
+ // Use shared ArtifactService if available
3792
4507
  });
3793
4508
  }
3794
4509
  /**
@@ -3798,7 +4513,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3798
4513
  async initializeArtifactMap() {
3799
4514
  try {
3800
4515
  this.artifactMap = await this.artifactParser.getContextArtifacts(this.contextId);
3801
- logger10.debug(
4516
+ logger11.debug(
3802
4517
  {
3803
4518
  contextId: this.contextId,
3804
4519
  artifactMapSize: this.artifactMap.size
@@ -3806,7 +4521,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3806
4521
  "Initialized artifact map for streaming"
3807
4522
  );
3808
4523
  } catch (error) {
3809
- logger10.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
4524
+ logger11.warn({ error, contextId: this.contextId }, "Failed to initialize artifact map");
3810
4525
  this.artifactMap = /* @__PURE__ */ new Map();
3811
4526
  }
3812
4527
  }
@@ -3903,9 +4618,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3903
4618
  * Note: Text components are handled separately with incremental streaming
3904
4619
  */
3905
4620
  async streamComponent(component) {
3906
- const parts = await this.artifactParser.parseObject({
3907
- dataComponents: [component]
3908
- }, this.artifactMap, this.agentId);
4621
+ const parts = await this.artifactParser.parseObject(
4622
+ {
4623
+ dataComponents: [component]
4624
+ },
4625
+ this.artifactMap,
4626
+ this.agentId
4627
+ );
3909
4628
  if (!Array.isArray(parts)) {
3910
4629
  console.warn("parseObject returned non-array:", parts);
3911
4630
  return;
@@ -3975,9 +4694,13 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3975
4694
  const componentKey = component.id;
3976
4695
  const hasBeenStreamed = this.lastStreamedComponents.has(componentKey);
3977
4696
  if (!hasBeenStreamed && this.isComponentComplete(component) && component.name !== "Text") {
3978
- const parts = await this.artifactParser.parseObject({
3979
- dataComponents: [component]
3980
- }, this.artifactMap, this.agentId);
4697
+ const parts = await this.artifactParser.parseObject(
4698
+ {
4699
+ dataComponents: [component]
4700
+ },
4701
+ this.artifactMap,
4702
+ this.agentId
4703
+ );
3981
4704
  for (const part of parts) {
3982
4705
  await this.streamPart(part);
3983
4706
  }
@@ -4042,7 +4765,11 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
4042
4765
  remainingBuffer: workingBuffer
4043
4766
  };
4044
4767
  }
4045
- 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
+ );
4046
4773
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
4047
4774
  const lastPart = parts[parts.length - 1];
4048
4775
  const lastText = lastPart.text || "";
@@ -4115,20 +4842,35 @@ var IncrementalStreamParser = _IncrementalStreamParser;
4115
4842
 
4116
4843
  // src/services/ResponseFormatter.ts
4117
4844
  init_logger();
4118
- var logger11 = agentsCore.getLogger("ResponseFormatter");
4845
+ var logger12 = agentsCore.getLogger("ResponseFormatter");
4119
4846
  var ResponseFormatter = class {
4120
4847
  constructor(tenantId, artifactParserOptions) {
4121
4848
  __publicField(this, "artifactParser");
4122
4849
  __publicField(this, "agentId");
4123
4850
  this.agentId = artifactParserOptions?.agentId;
4124
4851
  if (artifactParserOptions?.streamRequestId) {
4125
- const sessionParser = graphSessionManager.getArtifactParser(artifactParserOptions.streamRequestId);
4852
+ const sessionParser = graphSessionManager.getArtifactParser(
4853
+ artifactParserOptions.streamRequestId
4854
+ );
4126
4855
  if (sessionParser) {
4127
4856
  this.artifactParser = sessionParser;
4128
4857
  return;
4129
4858
  }
4130
4859
  }
4131
- 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
+ });
4132
4874
  }
4133
4875
  /**
4134
4876
  * Process structured object response and replace artifact markers with actual artifacts
@@ -4141,7 +4883,11 @@ var ResponseFormatter = class {
4141
4883
  "response.type": "object",
4142
4884
  "response.availableArtifacts": artifactMap.size
4143
4885
  });
4144
- 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
+ );
4145
4891
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
4146
4892
  span.setAttributes({
4147
4893
  "response.dataPartsCount": parts.length,
@@ -4155,7 +4901,7 @@ var ResponseFormatter = class {
4155
4901
  return { parts };
4156
4902
  } catch (error) {
4157
4903
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4158
- logger11.error({ error, responseObject }, "Error formatting object response");
4904
+ logger12.error({ error, responseObject }, "Error formatting object response");
4159
4905
  return {
4160
4906
  parts: [{ kind: "data", data: responseObject }]
4161
4907
  };
@@ -4207,7 +4953,7 @@ var ResponseFormatter = class {
4207
4953
  return { parts };
4208
4954
  } catch (error) {
4209
4955
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
4210
- logger11.error({ error, responseText }, "Error formatting response");
4956
+ logger12.error({ error, responseText }, "Error formatting response");
4211
4957
  return { text: responseText };
4212
4958
  } finally {
4213
4959
  span.end();
@@ -4255,7 +5001,7 @@ var ResponseFormatter = class {
4255
5001
  function agentInitializingOp(sessionId, graphId) {
4256
5002
  return {
4257
5003
  type: "agent_initializing",
4258
- ctx: {
5004
+ details: {
4259
5005
  sessionId,
4260
5006
  graphId
4261
5007
  }
@@ -4264,7 +5010,7 @@ function agentInitializingOp(sessionId, graphId) {
4264
5010
  function completionOp(agentId, iterations) {
4265
5011
  return {
4266
5012
  type: "completion",
4267
- ctx: {
5013
+ details: {
4268
5014
  agent: agentId,
4269
5015
  iteration: iterations
4270
5016
  }
@@ -4289,11 +5035,11 @@ init_logger();
4289
5035
 
4290
5036
  // src/utils/data-component-schema.ts
4291
5037
  init_logger();
4292
- var logger12 = agentsCore.getLogger("DataComponentSchema");
5038
+ var logger13 = agentsCore.getLogger("DataComponentSchema");
4293
5039
  function jsonSchemaToZod(jsonSchema) {
4294
5040
  if (!jsonSchema || typeof jsonSchema !== "object") {
4295
- logger12.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
4296
- return z5.z.string();
5041
+ logger13.warn({ jsonSchema }, "Invalid JSON schema provided, using string fallback");
5042
+ return z6.z.string();
4297
5043
  }
4298
5044
  switch (jsonSchema.type) {
4299
5045
  case "object":
@@ -4302,31 +5048,31 @@ function jsonSchemaToZod(jsonSchema) {
4302
5048
  for (const [key, prop] of Object.entries(jsonSchema.properties)) {
4303
5049
  shape[key] = jsonSchemaToZod(prop);
4304
5050
  }
4305
- return z5.z.object(shape);
5051
+ return z6.z.object(shape);
4306
5052
  }
4307
- return z5.z.record(z5.z.string(), z5.z.unknown());
5053
+ return z6.z.record(z6.z.string(), z6.z.unknown());
4308
5054
  case "array": {
4309
- const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z5.z.unknown();
4310
- return z5.z.array(itemSchema);
5055
+ const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z6.z.unknown();
5056
+ return z6.z.array(itemSchema);
4311
5057
  }
4312
5058
  case "string":
4313
- return z5.z.string();
5059
+ return z6.z.string();
4314
5060
  case "number":
4315
5061
  case "integer":
4316
- return z5.z.number();
5062
+ return z6.z.number();
4317
5063
  case "boolean":
4318
- return z5.z.boolean();
5064
+ return z6.z.boolean();
4319
5065
  case "null":
4320
- return z5.z.null();
5066
+ return z6.z.null();
4321
5067
  default:
4322
- logger12.warn(
5068
+ logger13.warn(
4323
5069
  {
4324
5070
  unsupportedType: jsonSchema.type,
4325
5071
  schema: jsonSchema
4326
5072
  },
4327
5073
  "Unsupported JSON schema type, using unknown validation"
4328
5074
  );
4329
- return z5.z.unknown();
5075
+ return z6.z.unknown();
4330
5076
  }
4331
5077
  }
4332
5078
 
@@ -4554,9 +5300,9 @@ var _ArtifactReferenceSchema = class _ArtifactReferenceSchema {
4554
5300
  * Get the standard Zod schema for artifact reference components
4555
5301
  */
4556
5302
  static getSchema() {
4557
- return z5.z.object({
4558
- id: z5.z.string(),
4559
- name: z5.z.literal("Artifact"),
5303
+ return z6.z.object({
5304
+ id: z6.z.string(),
5305
+ name: z6.z.literal("Artifact"),
4560
5306
  props: jsonSchemaToZod(_ArtifactReferenceSchema.ARTIFACT_PROPS_SCHEMA)
4561
5307
  });
4562
5308
  }
@@ -4598,8 +5344,7 @@ var ArtifactCreateSchema = class {
4598
5344
  */
4599
5345
  static getSchemas(artifactComponents) {
4600
5346
  return artifactComponents.map((component) => {
4601
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4602
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
5347
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4603
5348
  const propsSchema = {
4604
5349
  type: "object",
4605
5350
  properties: {
@@ -4618,16 +5363,15 @@ var ArtifactCreateSchema = class {
4618
5363
  },
4619
5364
  base_selector: {
4620
5365
  type: "string",
4621
- 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']").`
4622
5367
  },
4623
- summary_props: enhancedSummaryProps,
4624
- full_props: enhancedFullProps
5368
+ details_selector: enhancedSchema
4625
5369
  },
4626
5370
  required: ["id", "tool_call_id", "type", "base_selector"]
4627
5371
  };
4628
- return z5.z.object({
4629
- id: z5.z.string(),
4630
- 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}`),
4631
5375
  props: jsonSchemaToZod(propsSchema)
4632
5376
  });
4633
5377
  });
@@ -4639,8 +5383,7 @@ var ArtifactCreateSchema = class {
4639
5383
  */
4640
5384
  static getDataComponents(tenantId, projectId = "", artifactComponents) {
4641
5385
  return artifactComponents.map((component) => {
4642
- const enhancedSummaryProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.summaryProps);
4643
- const enhancedFullProps = SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.fullProps);
5386
+ const enhancedSchema = component.props ? SchemaProcessor.enhanceSchemaWithJMESPathGuidance(component.props) : { type: "object", properties: {} };
4644
5387
  const propsSchema = {
4645
5388
  type: "object",
4646
5389
  properties: {
@@ -4659,10 +5402,9 @@ var ArtifactCreateSchema = class {
4659
5402
  },
4660
5403
  base_selector: {
4661
5404
  type: "string",
4662
- 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']").`
4663
5406
  },
4664
- summary_props: enhancedSummaryProps,
4665
- full_props: enhancedFullProps
5407
+ details_selector: enhancedSchema
4666
5408
  },
4667
5409
  required: ["id", "tool_call_id", "type", "base_selector"]
4668
5410
  };
@@ -4690,7 +5432,7 @@ function parseEmbeddedJson(data) {
4690
5432
 
4691
5433
  // src/a2a/client.ts
4692
5434
  init_logger();
4693
- var logger13 = agentsCore.getLogger("a2aClient");
5435
+ var logger14 = agentsCore.getLogger("a2aClient");
4694
5436
  var DEFAULT_BACKOFF = {
4695
5437
  initialInterval: 500,
4696
5438
  maxInterval: 6e4,
@@ -4896,7 +5638,7 @@ var A2AClient = class {
4896
5638
  try {
4897
5639
  const res = await fn();
4898
5640
  if (attempt > 0) {
4899
- logger13.info(
5641
+ logger14.info(
4900
5642
  {
4901
5643
  attempts: attempt + 1,
4902
5644
  elapsedTime: Date.now() - start
@@ -4911,7 +5653,7 @@ var A2AClient = class {
4911
5653
  }
4912
5654
  const elapsed = Date.now() - start;
4913
5655
  if (elapsed > maxElapsedTime) {
4914
- logger13.warn(
5656
+ logger14.warn(
4915
5657
  {
4916
5658
  attempts: attempt + 1,
4917
5659
  elapsedTime: elapsed,
@@ -4932,7 +5674,7 @@ var A2AClient = class {
4932
5674
  retryInterval = initialInterval * attempt ** exponent + Math.random() * 1e3;
4933
5675
  }
4934
5676
  const delayMs = Math.min(retryInterval, maxInterval);
4935
- logger13.info(
5677
+ logger14.info(
4936
5678
  {
4937
5679
  attempt: attempt + 1,
4938
5680
  delayMs,
@@ -5017,7 +5759,7 @@ var A2AClient = class {
5017
5759
  }
5018
5760
  const rpcResponse = await httpResponse.json();
5019
5761
  if (rpcResponse.id !== requestId2) {
5020
- logger13.warn(
5762
+ logger14.warn(
5021
5763
  {
5022
5764
  method,
5023
5765
  expectedId: requestId2,
@@ -5216,7 +5958,7 @@ var A2AClient = class {
5216
5958
  try {
5217
5959
  while (true) {
5218
5960
  const { done, value } = await reader.read();
5219
- logger13.info({ done, value }, "parseA2ASseStream");
5961
+ logger14.info({ done, value }, "parseA2ASseStream");
5220
5962
  if (done) {
5221
5963
  if (eventDataBuffer.trim()) {
5222
5964
  const result = this._processSseEventData(
@@ -5306,7 +6048,7 @@ var A2AClient = class {
5306
6048
  init_conversations();
5307
6049
  init_dbClient();
5308
6050
  init_logger();
5309
- var logger14 = agentsCore.getLogger("relationships Tools");
6051
+ var logger15 = agentsCore.getLogger("relationships Tools");
5310
6052
  var generateTransferToolDescription = (config) => {
5311
6053
  return `Hand off the conversation to agent ${config.id}.
5312
6054
 
@@ -5335,7 +6077,7 @@ var createTransferToAgentTool = ({
5335
6077
  }) => {
5336
6078
  return ai.tool({
5337
6079
  description: generateTransferToolDescription(transferConfig),
5338
- inputSchema: z5__default.default.object({}),
6080
+ inputSchema: z6__default.default.object({}),
5339
6081
  execute: async () => {
5340
6082
  const activeSpan = api.trace.getActiveSpan();
5341
6083
  if (activeSpan) {
@@ -5344,7 +6086,7 @@ var createTransferToAgentTool = ({
5344
6086
  "transfer.to_agent_id": transferConfig.id ?? "unknown"
5345
6087
  });
5346
6088
  }
5347
- logger14.info(
6089
+ logger15.info(
5348
6090
  {
5349
6091
  transferTo: transferConfig.id ?? "unknown",
5350
6092
  fromAgent: callingAgentId
@@ -5381,7 +6123,7 @@ function createDelegateToAgentTool({
5381
6123
  }) {
5382
6124
  return ai.tool({
5383
6125
  description: generateDelegateToolDescription(delegateConfig.config),
5384
- inputSchema: z5__default.default.object({ message: z5__default.default.string() }),
6126
+ inputSchema: z6__default.default.object({ message: z6__default.default.string() }),
5385
6127
  execute: async (input, context) => {
5386
6128
  const delegationId = `del_${nanoid.nanoid()}`;
5387
6129
  const activeSpan = api.trace.getActiveSpan();
@@ -5493,7 +6235,7 @@ function createDelegateToAgentTool({
5493
6235
  ...isInternal ? { fromAgentId: callingAgentId } : { fromExternalAgentId: callingAgentId }
5494
6236
  }
5495
6237
  };
5496
- logger14.info({ messageToSend }, "messageToSend");
6238
+ logger15.info({ messageToSend }, "messageToSend");
5497
6239
  await agentsCore.createMessage(dbClient_default)({
5498
6240
  id: nanoid.nanoid(),
5499
6241
  tenantId,
@@ -5556,7 +6298,7 @@ function createDelegateToAgentTool({
5556
6298
 
5557
6299
  // src/agents/SystemPromptBuilder.ts
5558
6300
  init_logger();
5559
- var logger15 = agentsCore.getLogger("SystemPromptBuilder");
6301
+ var logger16 = agentsCore.getLogger("SystemPromptBuilder");
5560
6302
  var SystemPromptBuilder = class {
5561
6303
  constructor(version, versionConfig) {
5562
6304
  this.version = version;
@@ -5572,12 +6314,12 @@ var SystemPromptBuilder = class {
5572
6314
  this.templates.set(name, content);
5573
6315
  }
5574
6316
  this.loaded = true;
5575
- logger15.debug(
6317
+ logger16.debug(
5576
6318
  { templateCount: this.templates.size, version: this.version },
5577
6319
  `Loaded ${this.templates.size} templates for version ${this.version}`
5578
6320
  );
5579
6321
  } catch (error) {
5580
- logger15.error({ error }, `Failed to load templates for version ${this.version}`);
6322
+ logger16.error({ error }, `Failed to load templates for version ${this.version}`);
5581
6323
  throw new Error(`Template loading failed: ${error}`);
5582
6324
  }
5583
6325
  }
@@ -5602,68 +6344,6 @@ var SystemPromptBuilder = class {
5602
6344
  }
5603
6345
  };
5604
6346
 
5605
- // templates/v1/shared/artifact.xml?raw
5606
- 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> ";
5607
-
5608
- // templates/v1/shared/artifact-retrieval-guidance.xml?raw
5609
- var artifact_retrieval_guidance_default = `ARTIFACT RETRIEVAL: ACCESSING EXISTING ARTIFACT DATA
5610
-
5611
- \u{1F6A8} **CRITICAL: ALWAYS CHECK EXISTING ARTIFACTS FIRST** \u{1F6A8}
5612
- Before creating new artifacts, ALWAYS examine existing artifacts to see if they contain relevant information for the current topic or question.
5613
-
5614
- You CAN and SHOULD retrieve information from existing artifacts to answer user questions.
5615
- Available artifacts contain structured data that you can access in two ways:
5616
-
5617
- 1. **SUMMARY DATA**: Read the summary_data directly from available artifacts for basic information
5618
- 2. **FULL DATA**: Use the get_artifact tool to retrieve complete artifact data (both summary_data and full_data) when you need detailed information
5619
-
5620
- **REUSE EXISTING ARTIFACTS WHEN POSSIBLE:**
5621
- - Look for artifacts with similar topics, names, or descriptions
5622
- - Check if existing artifacts can answer the current question
5623
- - Use existing artifact data instead of creating duplicates
5624
- - Only create new artifacts if existing ones don't contain the needed information
5625
- - Prioritize reusing relevant existing artifacts over creating new ones
5626
-
5627
- HOW TO USE ARTIFACT DATA:
5628
- - Read summary_data from available artifacts for quick answers
5629
- - Use get_artifact tool when you need comprehensive details
5630
- - Extract specific information to answer user questions accurately
5631
- - Reference artifacts when citing the information source
5632
- - Combine information from multiple existing artifacts when relevant
5633
-
5634
- \u{1F6A8} **MANDATORY CITATION POLICY** \u{1F6A8}
5635
- EVERY piece of information from existing artifacts MUST be properly cited:
5636
- - When referencing information from existing artifacts = MUST cite with artifact reference
5637
- - When discussing artifact data = MUST cite the artifact source
5638
- - When using artifact information = MUST reference the artifact
5639
- - NO INFORMATION from existing artifacts can be presented without proper citation
5640
-
5641
- CITATION PLACEMENT RULES:
5642
- - ALWAYS place artifact citations AFTER complete thoughts and punctuation
5643
- - Never interrupt a sentence or thought with an artifact citation
5644
- - Complete your sentence or thought, add punctuation, THEN add the citation
5645
- - This maintains natural reading flow and professional presentation
5646
-
5647
- \u2705 CORRECT EXAMPLES:
5648
- - "The API uses OAuth 2.0 authentication. <artifact:create id='auth-doc' ...> This process involves three main steps..."
5649
- - "Based on the documentation, there are several authentication methods available. <artifact:create id='auth-methods' ...> The recommended approach is OAuth 2.0."
5650
-
5651
- \u274C WRONG EXAMPLES:
5652
- - "The API uses <artifact:create id='auth-doc' ...> OAuth 2.0 authentication which involves..."
5653
- - "According to <artifact:create id='auth-doc' ...>, the authentication method is OAuth 2.0."
5654
-
5655
- \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
5656
-
5657
- DELEGATION AND ARTIFACTS:
5658
- When you use delegation tools, the response may include artifacts in the parts array. These appear as objects with:
5659
- - kind: "data"
5660
- - data: { artifactId, toolCallId, name, description, type, artifactSummary }
5661
-
5662
- These artifacts become immediately available for you to reference using the artifactId and toolCallId from the response.
5663
- Present delegation results naturally without mentioning the delegation process itself.
5664
-
5665
- 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.`;
5666
-
5667
6347
  // templates/v1/phase1/system-prompt.xml?raw
5668
6348
  var system_prompt_default = `<system_message>
5669
6349
  <agent_identity>
@@ -5780,6 +6460,68 @@ var thinking_preparation_default = `<thinking_preparation_mode>
5780
6460
  // templates/v1/phase1/tool.xml?raw
5781
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> ";
5782
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
+
5783
6525
  // src/agents/versions/v1/Phase1Config.ts
5784
6526
  init_logger();
5785
6527
  agentsCore.getLogger("Phase1Config");
@@ -5916,8 +6658,8 @@ SELECTOR REQUIREMENTS:
5916
6658
 
5917
6659
  CRITICAL: SELECTOR HIERARCHY
5918
6660
  - base_selector: Points to ONE specific item in the tool result
5919
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
5920
- - 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"
5921
6663
 
5922
6664
  COMMON FAILURE POINTS (AVOID THESE):
5923
6665
  1. **Array Selection**: result.items (returns array) \u274C
@@ -5949,24 +6691,22 @@ You will create and reference artifacts using inline annotations in your text re
5949
6691
 
5950
6692
  CREATING ARTIFACTS (SERVES AS CITATION):
5951
6693
  Use the artifact:create annotation to extract data from tool results. The creation itself serves as a citation.
5952
- 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"}' />
5953
6695
 
5954
- \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}
5955
6697
 
5956
6698
  \u274C WRONG - Using literal values:
5957
- summary='{"title":"API Documentation","type":"guide"}'
5958
- full='{"description":"This is a comprehensive guide..."}'
6699
+ details='{"title":"API Documentation","type":"guide"}'
5959
6700
 
5960
6701
  \u2705 CORRECT - Using JMESPath selectors (relative to base selector):
5961
- summary='{"title":"metadata.title","doc_type":"document_type"}'
5962
- 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"}'
5963
6703
 
5964
6704
  The selectors extract actual field values from the data structure selected by your base selector.
5965
6705
 
5966
- THE summary AND full PROPERTIES MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE TOOL RESULT!
5967
- - summary: Contains JMESPath selectors relative to the base selector
5968
- - 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
5969
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
5970
6710
  - NEVER put literal values like "Inkeep" or "2023" - always use selectors like "metadata.company" or "founded_year"
5971
6711
 
5972
6712
  \u{1F6AB} FORBIDDEN JMESPATH PATTERNS:
@@ -6026,7 +6766,7 @@ Only use artifact:ref when you need to cite the SAME artifact again for a differ
6026
6766
  Format: <artifact:ref id="artifact-id" tool="tool_call_id" />
6027
6767
 
6028
6768
  EXAMPLE TEXT RESPONSE:
6029
- "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.
6030
6770
 
6031
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."
6032
6772
 
@@ -6082,31 +6822,29 @@ IMPORTANT GUIDELINES:
6082
6822
  return "";
6083
6823
  }
6084
6824
  const typeDescriptions = artifactComponents.map((ac) => {
6085
- let summarySchema = "No schema defined";
6086
- let fullSchema = "No schema defined";
6087
- if (ac.summaryProps?.properties) {
6088
- const summaryDetails = Object.entries(ac.summaryProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
6089
- summarySchema = `Required: ${summaryDetails}`;
6090
- }
6091
- if (ac.fullProps?.properties) {
6092
- const fullDetails = Object.entries(ac.fullProps.properties).map(([key, value]) => `${key} (${value.description || value.type || "field"})`).join(", ");
6093
- 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}`;
6094
6832
  }
6095
6833
  return ` - "${ac.name}": ${ac.description || "No description available"}
6096
- Summary Props: ${summarySchema}
6097
- Full Props: ${fullSchema}`;
6834
+ ${schemaDescription}`;
6098
6835
  }).join("\n\n");
6099
6836
  return `
6100
6837
  AVAILABLE ARTIFACT TYPES:
6101
6838
 
6102
6839
  ${typeDescriptions}
6103
6840
 
6104
- \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}
6105
6842
  - Only use property names that are defined in the artifact component schema above
6106
6843
  - Do NOT make up arbitrary property names like "founders", "nick_details", "year"
6107
- - 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
6108
6845
  - Your JMESPath selectors must extract values for these exact schema-defined properties
6109
- - 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
6110
6848
 
6111
6849
  \u{1F6A8} CRITICAL: USE EXACT ARTIFACT TYPE NAMES IN QUOTES! \u{1F6A8}
6112
6850
  - MUST use the exact type name shown in quotes above
@@ -6117,7 +6855,11 @@ ${typeDescriptions}
6117
6855
  }
6118
6856
  generateArtifactsSection(templates, artifacts, hasArtifactComponents = false, artifactComponents, hasGraphArtifactComponents) {
6119
6857
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
6120
- const rules = this.getArtifactReferencingRules(hasArtifactComponents, templates, shouldShowReferencingRules);
6858
+ const rules = this.getArtifactReferencingRules(
6859
+ hasArtifactComponents,
6860
+ templates,
6861
+ shouldShowReferencingRules
6862
+ );
6121
6863
  const creationInstructions = this.getArtifactCreationInstructions(
6122
6864
  hasArtifactComponents,
6123
6865
  artifactComponents
@@ -6212,6 +6954,12 @@ ${propertiesXml}
6212
6954
  }
6213
6955
  };
6214
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
+
6215
6963
  // templates/v1/phase2/system-prompt.xml?raw
6216
6964
  var system_prompt_default2 = `<phase2_system_message>
6217
6965
  <instruction>
@@ -6251,12 +6999,6 @@ var system_prompt_default2 = `<phase2_system_message>
6251
6999
  </requirements>
6252
7000
  </phase2_system_message>`;
6253
7001
 
6254
- // templates/v1/phase2/data-components.xml?raw
6255
- 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>';
6256
-
6257
- // templates/v1/phase2/data-component.xml?raw
6258
- 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> ";
6259
-
6260
7002
  // src/agents/versions/v1/Phase2Config.ts
6261
7003
  var Phase2Config = class {
6262
7004
  getArtifactCreationGuidance() {
@@ -6302,17 +7044,15 @@ When the same field names appear at different levels (like 'content', 'title', '
6302
7044
 
6303
7045
  CRITICAL: SELECTOR HIERARCHY
6304
7046
  - base_selector: Points to ONE specific item in the tool result
6305
- - summary_props/full_props: Contain JMESPath selectors RELATIVE to the base selector
6306
- - 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"
6307
7049
 
6308
7050
  \u274C WRONG EXAMPLE:
6309
7051
  {
6310
7052
  "base_selector": "result.content[?title=='Guide']",
6311
- "summary_props": {
7053
+ "details_selector": {
6312
7054
  "title": "Guide", // \u274C This is a literal value, not a selector!
6313
- "url": "result.content[?title=='Guide'].url" // \u274C This is absolute, not relative!
6314
- },
6315
- "full_props": {
7055
+ "url": "result.content[?title=='Guide'].url", // \u274C This is absolute, not relative!
6316
7056
  "description": "A comprehensive guide", // \u274C Literal value instead of selector!
6317
7057
  "content": "result.content[?title=='Guide'].content" // \u274C Absolute path instead of relative!
6318
7058
  }
@@ -6321,11 +7061,9 @@ CRITICAL: SELECTOR HIERARCHY
6321
7061
  \u2705 CORRECT EXAMPLE:
6322
7062
  {
6323
7063
  "base_selector": "result.content[?title=='Guide']",
6324
- "summary_props": {
7064
+ "details_selector": {
6325
7065
  "title": "title", // \u2705 Relative selector to get title field
6326
- "url": "url" // \u2705 Relative selector to get url field
6327
- },
6328
- "full_props": {
7066
+ "url": "url", // \u2705 Relative selector to get url field
6329
7067
  "description": "description", // \u2705 Relative selector
6330
7068
  "content": "content", // \u2705 Relative selector
6331
7069
  "metadata": "metadata.details" // \u2705 Relative selector with nesting
@@ -6411,8 +7149,7 @@ EXAMPLE STRUCTURED RESPONSE:
6411
7149
  "tool_call_id": "call_abc123",
6412
7150
  "type": "APIDoc",
6413
7151
  "base_selector": "result.documents[?type=='api']",
6414
- "summary_props": {"title": "metadata.title", "endpoint": "api.endpoint"},
6415
- "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"}
6416
7153
  }
6417
7154
  },
6418
7155
  {
@@ -6492,14 +7229,14 @@ IMPORTANT GUIDELINES:
6492
7229
  return "";
6493
7230
  }
6494
7231
  const componentDescriptions = artifactComponents.map((ac) => {
6495
- 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";
6496
- 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";
6497
7236
  return ` ArtifactCreate_${ac.name}:
6498
7237
  Description: ${ac.description || "Extract and structure data"}
6499
- Summary Properties:
6500
- ${summaryProps}
6501
- Full Properties:
6502
- ${fullProps}`;
7238
+ Schema Properties:
7239
+ ${schemaProps}`;
6503
7240
  }).join("\n\n");
6504
7241
  return `
6505
7242
  AVAILABLE ARTIFACT TYPES:
@@ -6513,8 +7250,14 @@ ${componentDescriptions}`;
6513
7250
  const dataComponentsDescription = dataComponents.map((dc) => `${dc.name}: ${dc.description}`).join(", ");
6514
7251
  const dataComponentsXml = dataComponents.map((dataComponent) => this.generateDataComponentXml(dataComponent)).join("\n ");
6515
7252
  let dataComponentsSection = data_components_default;
6516
- dataComponentsSection = dataComponentsSection.replace("{{DATA_COMPONENTS_LIST}}", dataComponentsDescription);
6517
- 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
+ );
6518
7261
  return dataComponentsSection;
6519
7262
  }
6520
7263
  generateDataComponentXml(dataComponent) {
@@ -6586,14 +7329,21 @@ ${artifact_retrieval_guidance_default}
6586
7329
  * Assemble the complete Phase 2 system prompt for structured output generation
6587
7330
  */
6588
7331
  assemblePhase2Prompt(config) {
6589
- const { corePrompt, dataComponents, artifactComponents, hasArtifactComponents, hasGraphArtifactComponents, artifacts = [] } = config;
7332
+ const {
7333
+ corePrompt,
7334
+ dataComponents,
7335
+ artifactComponents,
7336
+ hasArtifactComponents,
7337
+ hasGraphArtifactComponents,
7338
+ artifacts = []
7339
+ } = config;
6590
7340
  let allDataComponents = [...dataComponents];
6591
7341
  if (hasArtifactComponents && artifactComponents) {
6592
7342
  const artifactCreateComponents = ArtifactCreateSchema.getDataComponents(
6593
7343
  "tenant",
6594
7344
  // placeholder - not used in Phase2
6595
7345
  "",
6596
- // placeholder - not used in Phase2
7346
+ // placeholder - not used in Phase2
6597
7347
  artifactComponents
6598
7348
  );
6599
7349
  allDataComponents = [...dataComponents, ...artifactCreateComponents];
@@ -6601,8 +7351,15 @@ ${artifact_retrieval_guidance_default}
6601
7351
  const dataComponentsSection = this.generateDataComponentsSection(allDataComponents);
6602
7352
  const artifactsSection = this.generateArtifactsSection(artifacts);
6603
7353
  const shouldShowReferencingRules = hasGraphArtifactComponents || artifacts.length > 0;
6604
- const artifactGuidance = this.getStructuredArtifactGuidance(hasArtifactComponents, artifactComponents, shouldShowReferencingRules);
6605
- 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
+ );
6606
7363
  let phase2Prompt = system_prompt_default2;
6607
7364
  phase2Prompt = phase2Prompt.replace("{{CORE_INSTRUCTIONS}}", corePrompt);
6608
7365
  phase2Prompt = phase2Prompt.replace("{{DATA_COMPONENTS_SECTION}}", dataComponentsSection);
@@ -6623,7 +7380,7 @@ function hasToolCallWithPrefix(prefix) {
6623
7380
  return false;
6624
7381
  };
6625
7382
  }
6626
- var logger17 = agentsCore.getLogger("Agent");
7383
+ var logger19 = agentsCore.getLogger("Agent");
6627
7384
  var CONSTANTS = {
6628
7385
  MAX_GENERATION_STEPS: 12,
6629
7386
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -6904,7 +7661,10 @@ var Agent = class {
6904
7661
  ]);
6905
7662
  }
6906
7663
  async getMcpTools(sessionId, streamRequestId) {
6907
- 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)) || []) || [];
6908
7668
  if (!sessionId) {
6909
7669
  const combinedTools = tools.reduce((acc, tool3) => {
6910
7670
  return Object.assign(acc, tool3);
@@ -6924,14 +7684,14 @@ var Agent = class {
6924
7684
  for (const toolSet of tools) {
6925
7685
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
6926
7686
  if (!isValidTool(originalTool)) {
6927
- logger17.error({ toolName }, "Invalid MCP tool structure - missing required properties");
7687
+ logger19.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6928
7688
  continue;
6929
7689
  }
6930
7690
  const sessionWrappedTool = ai.tool({
6931
7691
  description: originalTool.description,
6932
7692
  inputSchema: originalTool.inputSchema,
6933
7693
  execute: async (args, { toolCallId }) => {
6934
- logger17.debug({ toolName, toolCallId }, "MCP Tool Called");
7694
+ logger19.debug({ toolName, toolCallId }, "MCP Tool Called");
6935
7695
  try {
6936
7696
  const rawResult = await originalTool.execute(args, { toolCallId });
6937
7697
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -6945,7 +7705,7 @@ var Agent = class {
6945
7705
  });
6946
7706
  return { result: enhancedResult, toolCallId };
6947
7707
  } catch (error) {
6948
- logger17.error({ toolName, toolCallId, error }, "MCP tool execution failed");
7708
+ logger19.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6949
7709
  throw error;
6950
7710
  }
6951
7711
  }
@@ -6964,6 +7724,9 @@ var Agent = class {
6964
7724
  * Convert database McpTool to builder MCPToolConfig format
6965
7725
  */
6966
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
+ }
6967
7730
  return {
6968
7731
  id: tool3.id,
6969
7732
  name: tool3.name,
@@ -7032,6 +7795,9 @@ var Agent = class {
7032
7795
  selectedTools
7033
7796
  );
7034
7797
  } else {
7798
+ if (tool3.config.type !== "mcp") {
7799
+ throw new Error(`Cannot build server config for non-MCP tool: ${tool3.id}`);
7800
+ }
7035
7801
  serverConfig = {
7036
7802
  type: tool3.config.mcp.transport?.type || agentsCore.MCPTransportType.streamableHttp,
7037
7803
  url: tool3.config.mcp.server.url,
@@ -7040,7 +7806,7 @@ var Agent = class {
7040
7806
  headers: agentToolRelationHeaders
7041
7807
  };
7042
7808
  }
7043
- logger17.info(
7809
+ logger19.info(
7044
7810
  {
7045
7811
  toolName: tool3.name,
7046
7812
  credentialReferenceId,
@@ -7065,7 +7831,7 @@ var Agent = class {
7065
7831
  this.mcpClientCache.set(cacheKey, client);
7066
7832
  } catch (error) {
7067
7833
  this.mcpConnectionLocks.delete(cacheKey);
7068
- logger17.error(
7834
+ logger19.error(
7069
7835
  {
7070
7836
  toolName: tool3.name,
7071
7837
  agentId: this.config.id,
@@ -7089,7 +7855,7 @@ var Agent = class {
7089
7855
  await client.connect();
7090
7856
  return client;
7091
7857
  } catch (error) {
7092
- logger17.error(
7858
+ logger19.error(
7093
7859
  {
7094
7860
  toolName: tool3.name,
7095
7861
  agentId: this.config.id,
@@ -7100,39 +7866,110 @@ var Agent = class {
7100
7866
  throw error;
7101
7867
  }
7102
7868
  }
7103
- getFunctionTools(streamRequestId) {
7104
- if (!this.config.functionTools) return {};
7869
+ async getFunctionTools(sessionId, streamRequestId) {
7105
7870
  const functionTools = {};
7106
- for (const funcTool of this.config.functionTools) {
7107
- const aiTool = ai.tool({
7108
- description: funcTool.description,
7109
- inputSchema: funcTool.schema || z5.z.object({}),
7110
- 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
+ }
7111
7879
  });
7112
- functionTools[funcTool.name] = this.wrapToolWithStreaming(
7113
- funcTool.name,
7114
- aiTool,
7115
- streamRequestId,
7116
- "tool"
7117
- );
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");
7118
7951
  }
7119
7952
  return functionTools;
7120
7953
  }
7121
7954
  /**
7122
7955
  * Get resolved context using ContextResolver - will return cached data or fetch fresh data as needed
7123
7956
  */
7124
- async getResolvedContext(conversationId, requestContext) {
7957
+ async getResolvedContext(conversationId, headers) {
7125
7958
  try {
7126
7959
  if (!this.config.contextConfigId) {
7127
- 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");
7128
7961
  return null;
7129
7962
  }
7130
7963
  const contextConfig = await agentsCore.getContextConfigById(dbClient_default)({
7131
- scopes: { tenantId: this.config.tenantId, projectId: this.config.projectId },
7964
+ scopes: {
7965
+ tenantId: this.config.tenantId,
7966
+ projectId: this.config.projectId,
7967
+ graphId: this.config.graphId
7968
+ },
7132
7969
  id: this.config.contextConfigId
7133
7970
  });
7134
7971
  if (!contextConfig) {
7135
- logger17.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7972
+ logger19.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
7136
7973
  return null;
7137
7974
  }
7138
7975
  if (!this.contextResolver) {
@@ -7141,7 +7978,7 @@ var Agent = class {
7141
7978
  const result = await this.contextResolver.resolve(contextConfig, {
7142
7979
  triggerEvent: "invocation",
7143
7980
  conversationId,
7144
- requestContext: requestContext || {},
7981
+ headers: headers || {},
7145
7982
  tenantId: this.config.tenantId
7146
7983
  });
7147
7984
  const contextWithBuiltins = {
@@ -7149,7 +7986,7 @@ var Agent = class {
7149
7986
  $now: (/* @__PURE__ */ new Date()).toISOString(),
7150
7987
  $env: process.env
7151
7988
  };
7152
- logger17.debug(
7989
+ logger19.debug(
7153
7990
  {
7154
7991
  conversationId,
7155
7992
  contextConfigId: contextConfig.id,
@@ -7163,7 +8000,7 @@ var Agent = class {
7163
8000
  );
7164
8001
  return contextWithBuiltins;
7165
8002
  } catch (error) {
7166
- logger17.error(
8003
+ logger19.error(
7167
8004
  {
7168
8005
  conversationId,
7169
8006
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7187,7 +8024,7 @@ var Agent = class {
7187
8024
  });
7188
8025
  return graphDefinition?.graphPrompt || void 0;
7189
8026
  } catch (error) {
7190
- logger17.warn(
8027
+ logger19.warn(
7191
8028
  {
7192
8029
  graphId: this.config.graphId,
7193
8030
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7216,7 +8053,7 @@ var Agent = class {
7216
8053
  (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
7217
8054
  );
7218
8055
  } catch (error) {
7219
- logger17.warn(
8056
+ logger19.warn(
7220
8057
  {
7221
8058
  graphId: this.config.graphId,
7222
8059
  tenantId: this.config.tenantId,
@@ -7245,7 +8082,7 @@ var Agent = class {
7245
8082
  preserveUnresolved: false
7246
8083
  });
7247
8084
  } catch (error) {
7248
- logger17.error(
8085
+ logger19.error(
7249
8086
  {
7250
8087
  conversationId,
7251
8088
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7292,7 +8129,7 @@ var Agent = class {
7292
8129
  preserveUnresolved: false
7293
8130
  });
7294
8131
  } catch (error) {
7295
- logger17.error(
8132
+ logger19.error(
7296
8133
  {
7297
8134
  conversationId,
7298
8135
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7304,9 +8141,24 @@ var Agent = class {
7304
8141
  }
7305
8142
  const streamRequestId = runtimeContext?.metadata?.streamRequestId;
7306
8143
  const mcpTools = await this.getMcpTools(void 0, streamRequestId);
7307
- const functionTools = this.getFunctionTools(streamRequestId);
8144
+ const functionTools = await this.getFunctionTools(streamRequestId || "");
7308
8145
  const relationTools = this.getRelationTools(runtimeContext);
7309
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
+ );
7310
8162
  const toolDefinitions = Object.entries(allTools).map(([name, tool3]) => ({
7311
8163
  name,
7312
8164
  description: tool3.description || "",
@@ -7331,7 +8183,7 @@ var Agent = class {
7331
8183
  preserveUnresolved: false
7332
8184
  });
7333
8185
  } catch (error) {
7334
- logger17.error(
8186
+ logger19.error(
7335
8187
  {
7336
8188
  conversationId,
7337
8189
  error: error instanceof Error ? error.message : "Unknown error"
@@ -7358,23 +8210,29 @@ var Agent = class {
7358
8210
  }
7359
8211
  getArtifactTools() {
7360
8212
  return ai.tool({
7361
- 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.",
7362
- inputSchema: z5.z.object({
7363
- 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.")
7364
8217
  }),
7365
- execute: async ({ artifactId }) => {
7366
- logger17.info({ artifactId }, "get_artifact executed");
7367
- const artifact = await agentsCore.getLedgerArtifacts(dbClient_default)({
7368
- scopes: {
7369
- tenantId: this.config.tenantId,
7370
- projectId: this.config.projectId
7371
- },
7372
- artifactId
7373
- });
7374
- if (!artifact) {
7375
- 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}`);
7376
8224
  }
7377
- 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
+ };
7378
8236
  }
7379
8237
  });
7380
8238
  }
@@ -7382,9 +8240,9 @@ var Agent = class {
7382
8240
  createThinkingCompleteTool() {
7383
8241
  return ai.tool({
7384
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.",
7385
- inputSchema: z5.z.object({
7386
- complete: z5.z.boolean().describe("ALWAYS set to true - marks end of research phase"),
7387
- 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(
7388
8246
  "Brief summary of what information was gathered and why it is sufficient to answer the user"
7389
8247
  )
7390
8248
  }),
@@ -7392,7 +8250,7 @@ var Agent = class {
7392
8250
  });
7393
8251
  }
7394
8252
  // Provide a default tool set that is always available to the agent.
7395
- async getDefaultTools(sessionId, streamRequestId) {
8253
+ async getDefaultTools(_sessionId, streamRequestId) {
7396
8254
  const defaultTools = {};
7397
8255
  if (await this.graphHasArtifactComponents()) {
7398
8256
  defaultTools.get_reference_artifact = this.getArtifactTools();
@@ -7480,13 +8338,19 @@ var Agent = class {
7480
8338
  if (Array.isArray(obj)) {
7481
8339
  obj.slice(0, 3).forEach((item) => {
7482
8340
  if (item && typeof item === "object") {
7483
- Object.keys(item).forEach((key) => fields.add(key));
8341
+ Object.keys(item).forEach((key) => {
8342
+ fields.add(key);
8343
+ });
7484
8344
  }
7485
8345
  });
7486
8346
  } else if (obj && typeof obj === "object") {
7487
- Object.keys(obj).forEach((key) => fields.add(key));
8347
+ Object.keys(obj).forEach((key) => {
8348
+ fields.add(key);
8349
+ });
7488
8350
  Object.values(obj).forEach((value) => {
7489
- findCommonFields(value, depth + 1).forEach((field) => fields.add(field));
8351
+ findCommonFields(value, depth + 1).forEach((field) => {
8352
+ fields.add(field);
8353
+ });
7490
8354
  });
7491
8355
  }
7492
8356
  return fields;
@@ -7585,8 +8449,7 @@ var Agent = class {
7585
8449
  artifactGuidance: {
7586
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.",
7587
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']")`,
7588
- summaryProps: '\u{1F4DD} Use relative selectors from that item (e.g., "title", "metadata.category", "properties.status")',
7589
- 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")',
7590
8453
  avoidLiterals: "\u274C NEVER use literal values - always use field selectors to extract from data",
7591
8454
  avoidArrays: "\u2728 ALWAYS filter arrays to single items using [?condition] - NEVER use [*] notation which returns arrays",
7592
8455
  nestedKeys: "\u{1F511} For structures with repeated keys (like result.content.data.content.items.content), use full paths with filtering at each level",
@@ -7613,7 +8476,7 @@ var Agent = class {
7613
8476
  };
7614
8477
  return enhanced;
7615
8478
  } catch (error) {
7616
- logger17.warn({ error }, "Failed to enhance tool result with structure hints");
8479
+ logger19.warn({ error }, "Failed to enhance tool result with structure hints");
7617
8480
  return result;
7618
8481
  }
7619
8482
  }
@@ -7628,7 +8491,7 @@ var Agent = class {
7628
8491
  }
7629
8492
  });
7630
8493
  } catch (error) {
7631
- logger17.error(
8494
+ logger19.error(
7632
8495
  { error, graphId: this.config.graphId },
7633
8496
  "Failed to check graph artifact components"
7634
8497
  );
@@ -7671,7 +8534,7 @@ var Agent = class {
7671
8534
  // Normal prompt with data components
7672
8535
  this.buildSystemPrompt(runtimeContext, true),
7673
8536
  // Thinking prompt without data components
7674
- Promise.resolve(this.getFunctionTools(streamRequestId)),
8537
+ this.getFunctionTools(sessionId, streamRequestId),
7675
8538
  Promise.resolve(this.getRelationTools(runtimeContext, sessionId)),
7676
8539
  this.getDefaultTools(sessionId, streamRequestId)
7677
8540
  ]);
@@ -7729,7 +8592,7 @@ var Agent = class {
7729
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;
7730
8593
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
7731
8594
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
7732
- logger17.warn(
8595
+ logger19.warn(
7733
8596
  {
7734
8597
  requestedTimeout: modelSettings.maxDuration * 1e3,
7735
8598
  appliedTimeout: timeoutMs,
@@ -7771,7 +8634,7 @@ var Agent = class {
7771
8634
  }
7772
8635
  );
7773
8636
  } catch (error) {
7774
- logger17.debug({ error }, "Failed to track agent reasoning");
8637
+ logger19.debug({ error }, "Failed to track agent reasoning");
7775
8638
  }
7776
8639
  }
7777
8640
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7875,7 +8738,7 @@ var Agent = class {
7875
8738
  }
7876
8739
  );
7877
8740
  } catch (error) {
7878
- logger17.debug({ error }, "Failed to track agent reasoning");
8741
+ logger19.debug({ error }, "Failed to track agent reasoning");
7879
8742
  }
7880
8743
  }
7881
8744
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7979,9 +8842,9 @@ ${output}${structureHintsFormatted}`;
7979
8842
  this.config.dataComponents.forEach((dc) => {
7980
8843
  const propsSchema = jsonSchemaToZod(dc.props);
7981
8844
  componentSchemas.push(
7982
- z5.z.object({
7983
- id: z5.z.string(),
7984
- name: z5.z.literal(dc.name),
8845
+ z6.z.object({
8846
+ id: z6.z.string(),
8847
+ name: z6.z.literal(dc.name),
7985
8848
  props: propsSchema
7986
8849
  })
7987
8850
  );
@@ -7998,7 +8861,7 @@ ${output}${structureHintsFormatted}`;
7998
8861
  if (componentSchemas.length === 1) {
7999
8862
  dataComponentsSchema = componentSchemas[0];
8000
8863
  } else {
8001
- dataComponentsSchema = z5.z.union(
8864
+ dataComponentsSchema = z6.z.union(
8002
8865
  componentSchemas
8003
8866
  );
8004
8867
  }
@@ -8022,8 +8885,8 @@ ${output}${structureHintsFormatted}`;
8022
8885
  const streamResult = ai.streamObject({
8023
8886
  ...structuredModelSettings,
8024
8887
  messages: phase2Messages,
8025
- schema: z5.z.object({
8026
- dataComponents: z5.z.array(dataComponentsSchema)
8888
+ schema: z6.z.object({
8889
+ dataComponents: z6.z.array(dataComponentsSchema)
8027
8890
  }),
8028
8891
  experimental_telemetry: {
8029
8892
  isEnabled: true,
@@ -8091,8 +8954,8 @@ ${output}${structureHintsFormatted}`;
8091
8954
  withJsonPostProcessing2({
8092
8955
  ...structuredModelSettings,
8093
8956
  messages: phase2Messages,
8094
- schema: z5.z.object({
8095
- dataComponents: z5.z.array(dataComponentsSchema)
8957
+ schema: z6.z.object({
8958
+ dataComponents: z6.z.array(dataComponentsSchema)
8096
8959
  }),
8097
8960
  experimental_telemetry: {
8098
8961
  isEnabled: true,
@@ -8167,7 +9030,7 @@ ${output}${structureHintsFormatted}`;
8167
9030
  };
8168
9031
 
8169
9032
  // src/agents/generateTaskHandler.ts
8170
- var logger18 = agentsCore.getLogger("generateTaskHandler");
9033
+ var logger20 = agentsCore.getLogger("generateTaskHandler");
8171
9034
  var createTaskHandler = (config, credentialStoreRegistry) => {
8172
9035
  return async (task) => {
8173
9036
  try {
@@ -8220,7 +9083,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8220
9083
  }
8221
9084
  })
8222
9085
  ]);
8223
- logger18.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
9086
+ logger20.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
8224
9087
  const enhancedInternalRelations = await Promise.all(
8225
9088
  internalRelations.map(async (relation) => {
8226
9089
  try {
@@ -8249,7 +9112,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8249
9112
  return { ...relation, description: enhancedDescription };
8250
9113
  }
8251
9114
  } catch (error) {
8252
- logger18.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
9115
+ logger20.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
8253
9116
  }
8254
9117
  return relation;
8255
9118
  })
@@ -8344,12 +9207,16 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8344
9207
  },
8345
9208
  credentialStoreRegistry
8346
9209
  );
9210
+ const artifactStreamRequestId = task.context?.metadata?.streamRequestId;
9211
+ if (artifactStreamRequestId && artifactComponents.length > 0) {
9212
+ graphSessionManager.updateArtifactComponents(artifactStreamRequestId, artifactComponents);
9213
+ }
8347
9214
  let contextId = task.context?.conversationId;
8348
9215
  if (!contextId || contextId === "default" || contextId === "") {
8349
9216
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
8350
9217
  if (taskIdMatch) {
8351
9218
  contextId = taskIdMatch[1];
8352
- logger18.info(
9219
+ logger20.info(
8353
9220
  {
8354
9221
  taskId: task.id,
8355
9222
  extractedContextId: contextId,
@@ -8365,7 +9232,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
8365
9232
  const isDelegation = task.context?.metadata?.isDelegation === true;
8366
9233
  agent.setDelegationStatus(isDelegation);
8367
9234
  if (isDelegation) {
8368
- logger18.info(
9235
+ logger20.info(
8369
9236
  { agentId: config.agentId, taskId: task.id },
8370
9237
  "Delegated agent - streaming disabled"
8371
9238
  );
@@ -8590,7 +9457,7 @@ async function getRegisteredGraph(executionContext) {
8590
9457
  init_dbClient();
8591
9458
  init_logger();
8592
9459
  var app = new zodOpenapi.OpenAPIHono();
8593
- var logger19 = agentsCore.getLogger("agents");
9460
+ var logger21 = agentsCore.getLogger("agents");
8594
9461
  app.openapi(
8595
9462
  zodOpenapi.createRoute({
8596
9463
  method: "get",
@@ -8605,14 +9472,14 @@ app.openapi(
8605
9472
  description: "Agent Card for A2A discovery",
8606
9473
  content: {
8607
9474
  "application/json": {
8608
- schema: z5.z.object({
8609
- name: z5.z.string(),
8610
- description: z5.z.string().optional(),
8611
- url: z5.z.string(),
8612
- version: z5.z.string(),
8613
- defaultInputModes: z5.z.array(z5.z.string()),
8614
- defaultOutputModes: z5.z.array(z5.z.string()),
8615
- 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())
8616
9483
  })
8617
9484
  }
8618
9485
  }
@@ -8628,7 +9495,7 @@ app.openapi(
8628
9495
  tracestate: c.req.header("tracestate"),
8629
9496
  baggage: c.req.header("baggage")
8630
9497
  };
8631
- logger19.info(
9498
+ logger21.info(
8632
9499
  {
8633
9500
  otelHeaders,
8634
9501
  path: c.req.path,
@@ -8640,7 +9507,7 @@ app.openapi(
8640
9507
  const { tenantId, projectId, graphId, agentId } = executionContext;
8641
9508
  console.dir("executionContext", executionContext);
8642
9509
  if (agentId) {
8643
- logger19.info(
9510
+ logger21.info(
8644
9511
  {
8645
9512
  message: "getRegisteredAgent (agent-level)",
8646
9513
  tenantId,
@@ -8652,7 +9519,7 @@ app.openapi(
8652
9519
  );
8653
9520
  const credentialStores = c.get("credentialStores");
8654
9521
  const agent = await getRegisteredAgent(executionContext, credentialStores);
8655
- logger19.info({ agent }, "agent registered: well-known agent.json");
9522
+ logger21.info({ agent }, "agent registered: well-known agent.json");
8656
9523
  if (!agent) {
8657
9524
  throw agentsCore.createApiError({
8658
9525
  code: "not_found",
@@ -8661,7 +9528,7 @@ app.openapi(
8661
9528
  }
8662
9529
  return c.json(agent.agentCard);
8663
9530
  } else {
8664
- logger19.info(
9531
+ logger21.info(
8665
9532
  {
8666
9533
  message: "getRegisteredGraph (graph-level)",
8667
9534
  tenantId,
@@ -8687,7 +9554,7 @@ app.post("/a2a", async (c) => {
8687
9554
  tracestate: c.req.header("tracestate"),
8688
9555
  baggage: c.req.header("baggage")
8689
9556
  };
8690
- logger19.info(
9557
+ logger21.info(
8691
9558
  {
8692
9559
  otelHeaders,
8693
9560
  path: c.req.path,
@@ -8698,7 +9565,7 @@ app.post("/a2a", async (c) => {
8698
9565
  const executionContext = agentsCore.getRequestExecutionContext(c);
8699
9566
  const { tenantId, projectId, graphId, agentId } = executionContext;
8700
9567
  if (agentId) {
8701
- logger19.info(
9568
+ logger21.info(
8702
9569
  {
8703
9570
  message: "a2a (agent-level)",
8704
9571
  tenantId,
@@ -8722,7 +9589,7 @@ app.post("/a2a", async (c) => {
8722
9589
  }
8723
9590
  return a2aHandler(c, agent);
8724
9591
  } else {
8725
- logger19.info(
9592
+ logger21.info(
8726
9593
  {
8727
9594
  message: "a2a (graph-level)",
8728
9595
  tenantId,
@@ -8778,14 +9645,14 @@ init_dbClient();
8778
9645
  // src/a2a/transfer.ts
8779
9646
  init_dbClient();
8780
9647
  init_logger();
8781
- var logger20 = agentsCore.getLogger("Transfer");
9648
+ var logger22 = agentsCore.getLogger("Transfer");
8782
9649
  async function executeTransfer({
8783
9650
  tenantId,
8784
9651
  threadId,
8785
9652
  projectId,
8786
9653
  targetAgentId
8787
9654
  }) {
8788
- logger20.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
9655
+ logger22.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8789
9656
  await agentsCore.setActiveAgentForThread(dbClient_default)({
8790
9657
  scopes: { tenantId, projectId },
8791
9658
  threadId,
@@ -9371,7 +10238,7 @@ function createMCPStreamHelper() {
9371
10238
  }
9372
10239
 
9373
10240
  // src/handlers/executionHandler.ts
9374
- var logger21 = agentsCore.getLogger("ExecutionHandler");
10241
+ var logger23 = agentsCore.getLogger("ExecutionHandler");
9375
10242
  var ExecutionHandler = class {
9376
10243
  constructor() {
9377
10244
  // Hardcoded error limit - separate from configurable stopWhen
@@ -9392,12 +10259,23 @@ var ExecutionHandler = class {
9392
10259
  * @returns
9393
10260
  */
9394
10261
  async execute(params) {
9395
- const { executionContext, conversationId, userMessage, initialAgentId, requestId: requestId2, sseHelper } = params;
10262
+ const {
10263
+ executionContext,
10264
+ conversationId,
10265
+ userMessage,
10266
+ initialAgentId,
10267
+ requestId: requestId2,
10268
+ sseHelper,
10269
+ emitOperations
10270
+ } = params;
9396
10271
  const { tenantId, projectId, graphId, apiKey, baseUrl } = executionContext;
9397
10272
  registerStreamHelper(requestId2, sseHelper);
9398
10273
  graphSessionManager.createSession(requestId2, graphId, tenantId, projectId, conversationId);
9399
- logger21.info(
9400
- { sessionId: requestId2, graphId, conversationId },
10274
+ if (emitOperations) {
10275
+ graphSessionManager.enableEmitOperations(requestId2);
10276
+ }
10277
+ logger23.info(
10278
+ { sessionId: requestId2, graphId, conversationId, emitOperations },
9401
10279
  "Created GraphSession for message execution"
9402
10280
  );
9403
10281
  let graphConfig = null;
@@ -9411,7 +10289,7 @@ var ExecutionHandler = class {
9411
10289
  );
9412
10290
  }
9413
10291
  } catch (error) {
9414
- logger21.error(
10292
+ logger23.error(
9415
10293
  {
9416
10294
  error: error instanceof Error ? error.message : "Unknown error",
9417
10295
  stack: error instanceof Error ? error.stack : void 0
@@ -9427,7 +10305,7 @@ var ExecutionHandler = class {
9427
10305
  try {
9428
10306
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
9429
10307
  const taskId = `task_${conversationId}-${requestId2}`;
9430
- logger21.info(
10308
+ logger23.info(
9431
10309
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
9432
10310
  "Attempting to create or reuse existing task"
9433
10311
  );
@@ -9451,7 +10329,7 @@ var ExecutionHandler = class {
9451
10329
  agent_id: currentAgentId
9452
10330
  }
9453
10331
  });
9454
- logger21.info(
10332
+ logger23.info(
9455
10333
  {
9456
10334
  taskId,
9457
10335
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -9460,27 +10338,27 @@ var ExecutionHandler = class {
9460
10338
  );
9461
10339
  } catch (error) {
9462
10340
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
9463
- logger21.info(
10341
+ logger23.info(
9464
10342
  { taskId, error: error.message },
9465
10343
  "Task already exists, fetching existing task"
9466
10344
  );
9467
10345
  const existingTask = await agentsCore.getTask(dbClient_default)({ id: taskId });
9468
10346
  if (existingTask) {
9469
10347
  task = existingTask;
9470
- logger21.info(
10348
+ logger23.info(
9471
10349
  { taskId, existingTask },
9472
10350
  "Successfully reused existing task from race condition"
9473
10351
  );
9474
10352
  } else {
9475
- logger21.error({ taskId, error }, "Task constraint failed but task not found");
10353
+ logger23.error({ taskId, error }, "Task constraint failed but task not found");
9476
10354
  throw error;
9477
10355
  }
9478
10356
  } else {
9479
- 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");
9480
10358
  throw error;
9481
10359
  }
9482
10360
  }
9483
- logger21.debug(
10361
+ logger23.debug(
9484
10362
  {
9485
10363
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9486
10364
  executionType: "create_initial_task",
@@ -9498,7 +10376,7 @@ var ExecutionHandler = class {
9498
10376
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
9499
10377
  while (iterations < maxTransfers) {
9500
10378
  iterations++;
9501
- logger21.info(
10379
+ logger23.info(
9502
10380
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
9503
10381
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
9504
10382
  );
@@ -9506,10 +10384,10 @@ var ExecutionHandler = class {
9506
10384
  scopes: { tenantId, projectId },
9507
10385
  conversationId
9508
10386
  });
9509
- logger21.info({ activeAgent }, "activeAgent");
10387
+ logger23.info({ activeAgent }, "activeAgent");
9510
10388
  if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
9511
10389
  currentAgentId = activeAgent.activeAgentId;
9512
- logger21.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
10390
+ logger23.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
9513
10391
  }
9514
10392
  const agentBaseUrl = `${baseUrl}/agents`;
9515
10393
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -9550,13 +10428,13 @@ var ExecutionHandler = class {
9550
10428
  });
9551
10429
  if (!messageResponse?.result) {
9552
10430
  errorCount++;
9553
- logger21.error(
10431
+ logger23.error(
9554
10432
  { currentAgentId, iterations, errorCount },
9555
10433
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9556
10434
  );
9557
10435
  if (errorCount >= this.MAX_ERRORS) {
9558
10436
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9559
- logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10437
+ logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9560
10438
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9561
10439
  if (task) {
9562
10440
  await agentsCore.updateTask(dbClient_default)({
@@ -9581,7 +10459,7 @@ var ExecutionHandler = class {
9581
10459
  const transferResponse = messageResponse.result;
9582
10460
  const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
9583
10461
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
9584
- logger21.info({ targetAgentId, transferReason }, "transfer response");
10462
+ logger23.info({ targetAgentId, transferReason }, "transfer response");
9585
10463
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
9586
10464
  const { success, targetAgentId: newAgentId } = await executeTransfer({
9587
10465
  projectId,
@@ -9592,7 +10470,7 @@ var ExecutionHandler = class {
9592
10470
  if (success) {
9593
10471
  fromAgentId = currentAgentId;
9594
10472
  currentAgentId = newAgentId;
9595
- logger21.info(
10473
+ logger23.info(
9596
10474
  {
9597
10475
  transferFrom: fromAgentId,
9598
10476
  transferTo: currentAgentId,
@@ -9610,7 +10488,7 @@ var ExecutionHandler = class {
9610
10488
  const graphSessionData = graphSessionManager.getSession(requestId2);
9611
10489
  if (graphSessionData) {
9612
10490
  const sessionSummary = graphSessionData.getSummary();
9613
- logger21.info(sessionSummary, "GraphSession data after completion");
10491
+ logger23.info(sessionSummary, "GraphSession data after completion");
9614
10492
  }
9615
10493
  let textContent = "";
9616
10494
  for (const part of responseParts) {
@@ -9664,22 +10542,22 @@ var ExecutionHandler = class {
9664
10542
  }
9665
10543
  });
9666
10544
  const updateTaskEnd = Date.now();
9667
- logger21.info(
10545
+ logger23.info(
9668
10546
  { duration: updateTaskEnd - updateTaskStart },
9669
10547
  "Completed updateTask operation"
9670
10548
  );
9671
10549
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
9672
10550
  await sseHelper.complete();
9673
- logger21.info({}, "Ending GraphSession and cleaning up");
10551
+ logger23.info({}, "Ending GraphSession and cleaning up");
9674
10552
  graphSessionManager.endSession(requestId2);
9675
- logger21.info({}, "Cleaning up streamHelper");
10553
+ logger23.info({}, "Cleaning up streamHelper");
9676
10554
  unregisterStreamHelper(requestId2);
9677
10555
  let response;
9678
10556
  if (sseHelper instanceof MCPStreamHelper) {
9679
10557
  const captured = sseHelper.getCapturedResponse();
9680
10558
  response = captured.text || "No response content";
9681
10559
  }
9682
- logger21.info({}, "ExecutionHandler returning success");
10560
+ logger23.info({}, "ExecutionHandler returning success");
9683
10561
  return { success: true, iterations, response };
9684
10562
  } catch (error) {
9685
10563
  agentsCore.setSpanWithError(span, error instanceof Error ? error : new Error(String(error)));
@@ -9690,13 +10568,13 @@ var ExecutionHandler = class {
9690
10568
  });
9691
10569
  }
9692
10570
  errorCount++;
9693
- logger21.warn(
10571
+ logger23.warn(
9694
10572
  { iterations, errorCount },
9695
10573
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9696
10574
  );
9697
10575
  if (errorCount >= this.MAX_ERRORS) {
9698
10576
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9699
- logger21.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
10577
+ logger23.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9700
10578
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9701
10579
  if (task) {
9702
10580
  await agentsCore.updateTask(dbClient_default)({
@@ -9717,7 +10595,7 @@ var ExecutionHandler = class {
9717
10595
  }
9718
10596
  }
9719
10597
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
9720
- logger21.error({ maxTransfers, iterations }, errorMessage);
10598
+ logger23.error({ maxTransfers, iterations }, errorMessage);
9721
10599
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
9722
10600
  if (task) {
9723
10601
  await agentsCore.updateTask(dbClient_default)({
@@ -9736,7 +10614,7 @@ var ExecutionHandler = class {
9736
10614
  unregisterStreamHelper(requestId2);
9737
10615
  return { success: false, error: errorMessage, iterations };
9738
10616
  } catch (error) {
9739
- logger21.error({ error }, "Error in execution handler");
10617
+ logger23.error({ error }, "Error in execution handler");
9740
10618
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
9741
10619
  await sseHelper.writeOperation(
9742
10620
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -9764,7 +10642,7 @@ var ExecutionHandler = class {
9764
10642
  // src/routes/chat.ts
9765
10643
  init_logger();
9766
10644
  var app2 = new zodOpenapi.OpenAPIHono();
9767
- var logger22 = agentsCore.getLogger("completionsHandler");
10645
+ var logger24 = agentsCore.getLogger("completionsHandler");
9768
10646
  var chatCompletionsRoute = zodOpenapi.createRoute({
9769
10647
  method: "post",
9770
10648
  path: "/completions",
@@ -9776,37 +10654,37 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9776
10654
  body: {
9777
10655
  content: {
9778
10656
  "application/json": {
9779
- schema: z5.z.object({
9780
- model: z5.z.string().describe("The model to use for the completion"),
9781
- messages: z5.z.array(
9782
- z5.z.object({
9783
- role: z5.z.enum(["system", "user", "assistant", "function", "tool"]).describe("The role of the message"),
9784
- content: z5.z.union([
9785
- z5.z.string(),
9786
- z5.z.array(
9787
- z5.z.strictObject({
9788
- type: z5.z.string(),
9789
- 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()
9790
10668
  })
9791
10669
  )
9792
10670
  ]).describe("The message content"),
9793
- 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")
9794
10672
  })
9795
10673
  ).describe("The conversation messages"),
9796
- temperature: z5.z.number().optional().describe("Controls randomness (0-1)"),
9797
- top_p: z5.z.number().optional().describe("Controls nucleus sampling"),
9798
- n: z5.z.number().optional().describe("Number of completions to generate"),
9799
- stream: z5.z.boolean().optional().describe("Whether to stream the response"),
9800
- max_tokens: z5.z.number().optional().describe("Maximum tokens to generate"),
9801
- presence_penalty: z5.z.number().optional().describe("Presence penalty (-2 to 2)"),
9802
- frequency_penalty: z5.z.number().optional().describe("Frequency penalty (-2 to 2)"),
9803
- logit_bias: z5.z.record(z5.z.string(), z5.z.number()).optional().describe("Token logit bias"),
9804
- user: z5.z.string().optional().describe("User identifier"),
9805
- conversationId: z5.z.string().optional().describe("Conversation ID for multi-turn chat"),
9806
- tools: z5.z.array(z5.z.string()).optional().describe("Available tools"),
9807
- runConfig: z5.z.record(z5.z.string(), z5.z.unknown()).optional().describe("Run configuration"),
9808
- requestContext: z5.z.record(z5.z.string(), z5.z.unknown()).optional().describe(
9809
- "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)"
9810
10688
  )
9811
10689
  })
9812
10690
  }
@@ -9816,14 +10694,14 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9816
10694
  responses: {
9817
10695
  200: {
9818
10696
  description: "Streaming chat completion response in Server-Sent Events format",
9819
- headers: z5.z.object({
9820
- "Content-Type": z5.z.string().default("text/event-stream"),
9821
- "Cache-Control": z5.z.string().default("no-cache"),
9822
- 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")
9823
10701
  }),
9824
10702
  content: {
9825
10703
  "text/event-stream": {
9826
- 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")
9827
10705
  }
9828
10706
  }
9829
10707
  },
@@ -9831,13 +10709,13 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9831
10709
  description: "Invalid request context or parameters",
9832
10710
  content: {
9833
10711
  "application/json": {
9834
- schema: z5.z.object({
9835
- error: z5.z.string(),
9836
- details: z5.z.array(
9837
- z5.z.object({
9838
- field: z5.z.string(),
9839
- message: z5.z.string(),
9840
- 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()
9841
10719
  })
9842
10720
  ).optional()
9843
10721
  })
@@ -9848,8 +10726,8 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9848
10726
  description: "Agent graph or agent not found",
9849
10727
  content: {
9850
10728
  "application/json": {
9851
- schema: z5.z.object({
9852
- error: z5.z.string()
10729
+ schema: z6.z.object({
10730
+ error: z6.z.string()
9853
10731
  })
9854
10732
  }
9855
10733
  }
@@ -9858,9 +10736,9 @@ var chatCompletionsRoute = zodOpenapi.createRoute({
9858
10736
  description: "Internal server error",
9859
10737
  content: {
9860
10738
  "application/json": {
9861
- schema: z5.z.object({
9862
- error: z5.z.string(),
9863
- message: z5.z.string()
10739
+ schema: z6.z.object({
10740
+ error: z6.z.string(),
10741
+ message: z6.z.string()
9864
10742
  })
9865
10743
  }
9866
10744
  }
@@ -9882,7 +10760,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9882
10760
  tracestate: c.req.header("tracestate"),
9883
10761
  baggage: c.req.header("baggage")
9884
10762
  };
9885
- logger22.info(
10763
+ logger24.info(
9886
10764
  {
9887
10765
  otelHeaders,
9888
10766
  path: c.req.path,
@@ -9964,18 +10842,18 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9964
10842
  message: "Agent not found"
9965
10843
  });
9966
10844
  }
9967
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
10845
+ const validatedContext = c.get("validatedContext") || body.headers || {};
9968
10846
  const credentialStores = c.get("credentialStores");
9969
10847
  await agentsCore.handleContextResolution({
9970
10848
  tenantId,
9971
10849
  projectId,
9972
10850
  graphId,
9973
10851
  conversationId,
9974
- requestContext: validatedContext,
10852
+ headers: validatedContext,
9975
10853
  dbClient: dbClient_default,
9976
10854
  credentialStores
9977
10855
  });
9978
- logger22.info(
10856
+ logger24.info(
9979
10857
  {
9980
10858
  tenantId,
9981
10859
  projectId,
@@ -9984,7 +10862,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9984
10862
  defaultAgentId,
9985
10863
  activeAgentId: activeAgent?.activeAgentId || "none",
9986
10864
  hasContextConfig: !!agentGraph.contextConfigId,
9987
- hasRequestContext: !!body.requestContext,
10865
+ hasHeaders: !!body.headers,
9988
10866
  hasValidatedContext: !!validatedContext,
9989
10867
  validatedContextKeys: Object.keys(validatedContext)
9990
10868
  },
@@ -10023,7 +10901,9 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10023
10901
  try {
10024
10902
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
10025
10903
  await sseHelper.writeRole();
10026
- logger22.info({ agentId }, "Starting execution");
10904
+ logger24.info({ agentId }, "Starting execution");
10905
+ const emitOperationsHeader = c.req.header("x-emit-operations");
10906
+ const emitOperations = emitOperationsHeader === "true";
10027
10907
  const executionHandler = new ExecutionHandler();
10028
10908
  const result = await executionHandler.execute({
10029
10909
  executionContext,
@@ -10031,9 +10911,10 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10031
10911
  userMessage,
10032
10912
  initialAgentId: agentId,
10033
10913
  requestId: requestId2,
10034
- sseHelper
10914
+ sseHelper,
10915
+ emitOperations
10035
10916
  });
10036
- logger22.info(
10917
+ logger24.info(
10037
10918
  { result },
10038
10919
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10039
10920
  );
@@ -10047,7 +10928,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10047
10928
  }
10048
10929
  await sseHelper.complete();
10049
10930
  } catch (error) {
10050
- logger22.error(
10931
+ logger24.error(
10051
10932
  {
10052
10933
  error: error instanceof Error ? error.message : error,
10053
10934
  stack: error instanceof Error ? error.stack : void 0
@@ -10064,12 +10945,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
10064
10945
  );
10065
10946
  await sseHelper.complete();
10066
10947
  } catch (streamError) {
10067
- logger22.error({ streamError }, "Failed to write error to stream");
10948
+ logger24.error({ streamError }, "Failed to write error to stream");
10068
10949
  }
10069
10950
  }
10070
10951
  });
10071
10952
  } catch (error) {
10072
- logger22.error(
10953
+ logger24.error(
10073
10954
  {
10074
10955
  error: error instanceof Error ? error.message : error,
10075
10956
  stack: error instanceof Error ? error.stack : void 0
@@ -10097,7 +10978,7 @@ var chat_default = app2;
10097
10978
  init_dbClient();
10098
10979
  init_logger();
10099
10980
  var app3 = new zodOpenapi.OpenAPIHono();
10100
- var logger23 = agentsCore.getLogger("chatDataStream");
10981
+ var logger25 = agentsCore.getLogger("chatDataStream");
10101
10982
  var chatDataStreamRoute = zodOpenapi.createRoute({
10102
10983
  method: "post",
10103
10984
  path: "/chat",
@@ -10128,7 +11009,7 @@ var chatDataStreamRoute = zodOpenapi.createRoute({
10128
11009
  ),
10129
11010
  id: zodOpenapi.z.string().optional(),
10130
11011
  conversationId: zodOpenapi.z.string().optional(),
10131
- 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")
10132
11013
  })
10133
11014
  }
10134
11015
  }
@@ -10201,20 +11082,20 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10201
11082
  message: "Agent not found"
10202
11083
  });
10203
11084
  }
10204
- const validatedContext = c.get("validatedContext") || body.requestContext || {};
11085
+ const validatedContext = c.get("validatedContext") || body.headers || {};
10205
11086
  const credentialStores = c.get("credentialStores");
10206
11087
  await agentsCore.handleContextResolution({
10207
11088
  tenantId,
10208
11089
  projectId,
10209
11090
  graphId,
10210
11091
  conversationId,
10211
- requestContext: validatedContext,
11092
+ headers: validatedContext,
10212
11093
  dbClient: dbClient_default,
10213
11094
  credentialStores
10214
11095
  });
10215
11096
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
10216
11097
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
10217
- logger23.info({ userText, lastUserMessage }, "userText");
11098
+ logger25.info({ userText, lastUserMessage }, "userText");
10218
11099
  const messageSpan = api.trace.getActiveSpan();
10219
11100
  if (messageSpan) {
10220
11101
  messageSpan.setAttributes({
@@ -10243,6 +11124,8 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10243
11124
  execute: async ({ writer }) => {
10244
11125
  const streamHelper = createVercelStreamHelper(writer);
10245
11126
  try {
11127
+ const emitOperationsHeader = c.req.header("x-emit-operations");
11128
+ const emitOperations = emitOperationsHeader === "true";
10246
11129
  const executionHandler = new ExecutionHandler();
10247
11130
  const result = await executionHandler.execute({
10248
11131
  executionContext,
@@ -10250,13 +11133,14 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10250
11133
  userMessage: userText,
10251
11134
  initialAgentId: agentId,
10252
11135
  requestId: `chatds-${Date.now()}`,
10253
- sseHelper: streamHelper
11136
+ sseHelper: streamHelper,
11137
+ emitOperations
10254
11138
  });
10255
11139
  if (!result.success) {
10256
11140
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
10257
11141
  }
10258
11142
  } catch (err) {
10259
- logger23.error({ err }, "Streaming error");
11143
+ logger25.error({ err }, "Streaming error");
10260
11144
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
10261
11145
  } finally {
10262
11146
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -10277,7 +11161,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
10277
11161
  )
10278
11162
  );
10279
11163
  } catch (error) {
10280
- logger23.error({ error }, "chatDataStream error");
11164
+ logger25.error({ error }, "chatDataStream error");
10281
11165
  throw agentsCore.createApiError({
10282
11166
  code: "internal_server_error",
10283
11167
  message: "Failed to process chat completion"
@@ -10292,7 +11176,7 @@ init_logger();
10292
11176
  function createMCPSchema(schema) {
10293
11177
  return schema;
10294
11178
  }
10295
- var logger24 = agentsCore.getLogger("mcp");
11179
+ var logger26 = agentsCore.getLogger("mcp");
10296
11180
  var _MockResponseSingleton = class _MockResponseSingleton {
10297
11181
  constructor() {
10298
11182
  __publicField(this, "mockRes");
@@ -10347,21 +11231,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
10347
11231
  id: 0
10348
11232
  });
10349
11233
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
10350
- logger24.info({ sessionId }, "Spoofing initialization message to set transport state");
11234
+ logger26.info({ sessionId }, "Spoofing initialization message to set transport state");
10351
11235
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
10352
11236
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
10353
11237
  try {
10354
11238
  await transport.handleRequest(req, mockRes, spoofInitMessage);
10355
- logger24.info({ sessionId }, "Successfully spoofed initialization");
11239
+ logger26.info({ sessionId }, "Successfully spoofed initialization");
10356
11240
  } catch (spoofError) {
10357
- logger24.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
11241
+ logger26.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
10358
11242
  }
10359
11243
  };
10360
11244
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10361
11245
  const sessionId = req.headers["mcp-session-id"];
10362
- logger24.info({ sessionId }, "Received MCP session ID");
11246
+ logger26.info({ sessionId }, "Received MCP session ID");
10363
11247
  if (!sessionId) {
10364
- logger24.info({ body }, "Missing session ID");
11248
+ logger26.info({ body }, "Missing session ID");
10365
11249
  res.writeHead(400).end(
10366
11250
  JSON.stringify({
10367
11251
  jsonrpc: "2.0",
@@ -10387,7 +11271,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10387
11271
  scopes: { tenantId, projectId },
10388
11272
  conversationId: sessionId
10389
11273
  });
10390
- logger24.info(
11274
+ logger26.info(
10391
11275
  {
10392
11276
  sessionId,
10393
11277
  conversationFound: !!conversation,
@@ -10398,7 +11282,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
10398
11282
  "Conversation lookup result"
10399
11283
  );
10400
11284
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
10401
- logger24.info(
11285
+ logger26.info(
10402
11286
  { sessionId, conversationId: conversation?.id },
10403
11287
  "MCP session not found or invalid"
10404
11288
  );
@@ -10459,7 +11343,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10459
11343
  requestId: requestId2,
10460
11344
  sseHelper: mcpStreamHelper
10461
11345
  });
10462
- logger24.info(
11346
+ logger26.info(
10463
11347
  { result },
10464
11348
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
10465
11349
  );
@@ -10483,7 +11367,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
10483
11367
  ]
10484
11368
  };
10485
11369
  };
10486
- var getServer = async (requestContext, executionContext, conversationId, credentialStores) => {
11370
+ var getServer = async (headers, executionContext, conversationId, credentialStores) => {
10487
11371
  const { tenantId, projectId, graphId } = executionContext;
10488
11372
  setupTracing(conversationId, tenantId, graphId);
10489
11373
  const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
@@ -10539,18 +11423,18 @@ var getServer = async (requestContext, executionContext, conversationId, credent
10539
11423
  projectId,
10540
11424
  graphId,
10541
11425
  conversationId,
10542
- requestContext,
11426
+ headers,
10543
11427
  dbClient: dbClient_default,
10544
11428
  credentialStores
10545
11429
  });
10546
- logger24.info(
11430
+ logger26.info(
10547
11431
  {
10548
11432
  tenantId,
10549
11433
  projectId,
10550
11434
  graphId,
10551
11435
  conversationId,
10552
11436
  hasContextConfig: !!agentGraph.contextConfigId,
10553
- hasRequestContext: !!requestContext,
11437
+ hasHeaders: !!headers,
10554
11438
  hasValidatedContext: !!resolvedContext
10555
11439
  },
10556
11440
  "parameters"
@@ -10605,7 +11489,7 @@ var validateRequestParameters = (c) => {
10605
11489
  };
10606
11490
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
10607
11491
  const { tenantId, projectId, graphId } = executionContext;
10608
- logger24.info({ body }, "Received initialization request");
11492
+ logger26.info({ body }, "Received initialization request");
10609
11493
  const sessionId = agentsCore.getConversationId();
10610
11494
  const agentGraph = await agentsCore.getAgentGraphWithDefaultAgent(dbClient_default)({
10611
11495
  scopes: { tenantId, projectId, graphId }
@@ -10645,7 +11529,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10645
11529
  }
10646
11530
  }
10647
11531
  });
10648
- logger24.info(
11532
+ logger26.info(
10649
11533
  { sessionId, conversationId: conversation.id },
10650
11534
  "Created MCP session as conversation"
10651
11535
  );
@@ -10654,9 +11538,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10654
11538
  });
10655
11539
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
10656
11540
  await server.connect(transport);
10657
- logger24.info({ sessionId }, "Server connected for initialization");
11541
+ logger26.info({ sessionId }, "Server connected for initialization");
10658
11542
  res.setHeader("Mcp-Session-Id", sessionId);
10659
- logger24.info(
11543
+ logger26.info(
10660
11544
  {
10661
11545
  sessionId,
10662
11546
  bodyMethod: body?.method,
@@ -10665,7 +11549,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
10665
11549
  "About to handle initialization request"
10666
11550
  );
10667
11551
  await transport.handleRequest(req, res, body);
10668
- logger24.info({ sessionId }, "Successfully handled initialization request");
11552
+ logger26.info({ sessionId }, "Successfully handled initialization request");
10669
11553
  return fetchToNode.toFetchResponse(res);
10670
11554
  };
10671
11555
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -10693,8 +11577,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10693
11577
  sessionId,
10694
11578
  conversation.metadata?.session_data?.mcpProtocolVersion
10695
11579
  );
10696
- logger24.info({ sessionId }, "Server connected and transport initialized");
10697
- logger24.info(
11580
+ logger26.info({ sessionId }, "Server connected and transport initialized");
11581
+ logger26.info(
10698
11582
  {
10699
11583
  sessionId,
10700
11584
  bodyKeys: Object.keys(body || {}),
@@ -10708,9 +11592,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10708
11592
  );
10709
11593
  try {
10710
11594
  await transport.handleRequest(req, res, body);
10711
- logger24.info({ sessionId }, "Successfully handled MCP request");
11595
+ logger26.info({ sessionId }, "Successfully handled MCP request");
10712
11596
  } catch (transportError) {
10713
- logger24.error(
11597
+ logger26.error(
10714
11598
  {
10715
11599
  sessionId,
10716
11600
  error: transportError,
@@ -10761,13 +11645,13 @@ app4.openapi(
10761
11645
  }
10762
11646
  const { executionContext } = paramValidation;
10763
11647
  const body = c.get("requestBody") || {};
10764
- logger24.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
11648
+ logger26.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10765
11649
  const isInitRequest = body.method === "initialize";
10766
11650
  const { req, res } = fetchToNode.toReqRes(c.req.raw);
10767
11651
  const validatedContext = c.get("validatedContext") || {};
10768
11652
  const credentialStores = c.get("credentialStores");
10769
- logger24.info({ validatedContext }, "Validated context");
10770
- logger24.info({ req }, "request");
11653
+ logger26.info({ validatedContext }, "Validated context");
11654
+ logger26.info({ req }, "request");
10771
11655
  if (isInitRequest) {
10772
11656
  return await handleInitializationRequest(
10773
11657
  body,
@@ -10789,7 +11673,7 @@ app4.openapi(
10789
11673
  );
10790
11674
  }
10791
11675
  } catch (e) {
10792
- logger24.error(
11676
+ logger26.error(
10793
11677
  {
10794
11678
  error: e instanceof Error ? e.message : e,
10795
11679
  stack: e instanceof Error ? e.stack : void 0
@@ -10801,7 +11685,7 @@ app4.openapi(
10801
11685
  }
10802
11686
  );
10803
11687
  app4.get("/", async (c) => {
10804
- logger24.info({}, "Received GET MCP request");
11688
+ logger26.info({}, "Received GET MCP request");
10805
11689
  return c.json(
10806
11690
  {
10807
11691
  jsonrpc: "2.0",
@@ -10815,7 +11699,7 @@ app4.get("/", async (c) => {
10815
11699
  );
10816
11700
  });
10817
11701
  app4.delete("/", async (c) => {
10818
- logger24.info({}, "Received DELETE MCP request");
11702
+ logger26.info({}, "Received DELETE MCP request");
10819
11703
  return c.json(
10820
11704
  {
10821
11705
  jsonrpc: "2.0",
@@ -10828,7 +11712,7 @@ app4.delete("/", async (c) => {
10828
11712
  var mcp_default = app4;
10829
11713
 
10830
11714
  // src/app.ts
10831
- var logger25 = agentsCore.getLogger("agents-run-api");
11715
+ var logger27 = agentsCore.getLogger("agents-run-api");
10832
11716
  function createExecutionHono(serverConfig, credentialStores) {
10833
11717
  const app6 = new zodOpenapi.OpenAPIHono();
10834
11718
  app6.use("*", otel.otel());
@@ -10844,7 +11728,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10844
11728
  const body = await c.req.json();
10845
11729
  c.set("requestBody", body);
10846
11730
  } catch (error) {
10847
- 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");
10848
11732
  }
10849
11733
  }
10850
11734
  return next();
@@ -10895,8 +11779,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10895
11779
  if (!isExpectedError) {
10896
11780
  const errorMessage = err instanceof Error ? err.message : String(err);
10897
11781
  const errorStack = err instanceof Error ? err.stack : void 0;
10898
- if (logger25) {
10899
- logger25.error(
11782
+ if (logger27) {
11783
+ logger27.error(
10900
11784
  {
10901
11785
  error: err,
10902
11786
  message: errorMessage,
@@ -10908,8 +11792,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10908
11792
  );
10909
11793
  }
10910
11794
  } else {
10911
- if (logger25) {
10912
- logger25.error(
11795
+ if (logger27) {
11796
+ logger27.error(
10913
11797
  {
10914
11798
  error: err,
10915
11799
  path: c.req.path,
@@ -10926,8 +11810,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10926
11810
  const response = err.getResponse();
10927
11811
  return response;
10928
11812
  } catch (responseError) {
10929
- if (logger25) {
10930
- logger25.error({ error: responseError }, "Error while handling HTTPException response");
11813
+ if (logger27) {
11814
+ logger27.error({ error: responseError }, "Error while handling HTTPException response");
10931
11815
  }
10932
11816
  }
10933
11817
  }
@@ -10961,7 +11845,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10961
11845
  app6.use("*", async (c, next) => {
10962
11846
  const executionContext = c.get("executionContext");
10963
11847
  if (!executionContext) {
10964
- logger25.debug({}, "Empty execution context");
11848
+ logger27.debug({}, "Empty execution context");
10965
11849
  return next();
10966
11850
  }
10967
11851
  const { tenantId, projectId, graphId } = executionContext;
@@ -10970,7 +11854,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10970
11854
  if (requestBody) {
10971
11855
  conversationId = requestBody.conversationId;
10972
11856
  if (!conversationId) {
10973
- logger25.debug({ requestBody }, "No conversation ID found in request body");
11857
+ logger27.debug({ requestBody }, "No conversation ID found in request body");
10974
11858
  }
10975
11859
  }
10976
11860
  const entries = Object.fromEntries(
@@ -10985,7 +11869,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10985
11869
  })
10986
11870
  );
10987
11871
  if (!Object.keys(entries).length) {
10988
- logger25.debug({}, "Empty entries for baggage");
11872
+ logger27.debug({}, "Empty entries for baggage");
10989
11873
  return next();
10990
11874
  }
10991
11875
  const bag = Object.entries(entries).reduce(