@inkeep/agents-run-api 0.11.3 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1405,7 +1405,7 @@ var _ArtifactService = class _ArtifactService {
1405
1405
  /**
1406
1406
  * Create artifact from tool result and request data
1407
1407
  */
1408
- async createArtifact(request) {
1408
+ async createArtifact(request, agentId) {
1409
1409
  if (!this.context.sessionId) {
1410
1410
  logger6.warn({ request }, "No session ID available for artifact creation");
1411
1411
  return null;
@@ -1456,7 +1456,7 @@ var _ArtifactService = class _ArtifactService {
1456
1456
  type: request.type,
1457
1457
  artifactSummary: component?.summaryProps ? this.filterBySchema(cleanedSummaryData, component.summaryProps) : cleanedSummaryData
1458
1458
  };
1459
- await this.persistArtifact(request, cleanedSummaryData, cleanedFullData);
1459
+ await this.persistArtifact(request, cleanedSummaryData, cleanedFullData, agentId);
1460
1460
  await this.cacheArtifact(
1461
1461
  request.artifactId,
1462
1462
  request.toolCallId,
@@ -1532,12 +1532,13 @@ var _ArtifactService = class _ArtifactService {
1532
1532
  /**
1533
1533
  * Persist artifact to database via graph session
1534
1534
  */
1535
- async persistArtifact(request, summaryData, fullData) {
1536
- if (this.context.streamRequestId && this.context.agentId && this.context.taskId) {
1535
+ async persistArtifact(request, summaryData, fullData, agentId) {
1536
+ const effectiveAgentId = agentId || this.context.agentId;
1537
+ if (this.context.streamRequestId && effectiveAgentId && this.context.taskId) {
1537
1538
  await graphSessionManager.recordEvent(
1538
1539
  this.context.streamRequestId,
1539
1540
  "artifact_saved",
1540
- this.context.agentId,
1541
+ effectiveAgentId,
1541
1542
  {
1542
1543
  artifactId: request.artifactId,
1543
1544
  taskId: this.context.taskId,
@@ -1545,6 +1546,7 @@ var _ArtifactService = class _ArtifactService {
1545
1546
  artifactType: request.type,
1546
1547
  summaryProps: summaryData,
1547
1548
  fullProps: fullData,
1549
+ agentId: effectiveAgentId,
1548
1550
  metadata: {
1549
1551
  toolCallId: request.toolCallId,
1550
1552
  baseSelector: request.baseSelector,
@@ -1559,6 +1561,15 @@ var _ArtifactService = class _ArtifactService {
1559
1561
  pendingGeneration: true
1560
1562
  }
1561
1563
  );
1564
+ } else {
1565
+ logger6.warn({
1566
+ artifactId: request.artifactId,
1567
+ hasStreamRequestId: !!this.context.streamRequestId,
1568
+ hasAgentId: !!effectiveAgentId,
1569
+ hasTaskId: !!this.context.taskId,
1570
+ passedAgentId: agentId,
1571
+ contextAgentId: this.context.agentId
1572
+ }, "Skipping artifact_saved event - missing required context");
1562
1573
  }
1563
1574
  }
1564
1575
  /**
@@ -1733,7 +1744,10 @@ var _ArtifactParser = class _ArtifactParser {
1733
1744
  * Check if text contains complete artifact markers (ref or create)
1734
1745
  */
1735
1746
  hasArtifactMarkers(text) {
1736
- return _ArtifactParser.ARTIFACT_CHECK_REGEX.test(text) || _ArtifactParser.ARTIFACT_CREATE_REGEX.test(text);
1747
+ const refMatch = _ArtifactParser.ARTIFACT_CHECK_REGEX.test(text);
1748
+ const createRegex = /<artifact:create\s+([^>]+?)(?:\s*\/)?>(?:(.*?)<\/artifact:create>)?/gs;
1749
+ const createMatch = createRegex.test(text);
1750
+ return refMatch || createMatch;
1737
1751
  }
1738
1752
  /**
1739
1753
  * Check if text has incomplete artifact marker (for streaming)
@@ -1799,7 +1813,6 @@ var _ArtifactParser = class _ArtifactParser {
1799
1813
  }
1800
1814
  attrs[key] = value;
1801
1815
  }
1802
- logger7.debug({ attrs, attrString }, "Parsed artifact:create attributes");
1803
1816
  if (!attrs.id || !attrs.tool || !attrs.type || !attrs.base) {
1804
1817
  logger7.warn({ attrs, attrString }, "Missing required attributes in artifact annotation");
1805
1818
  return null;
@@ -1818,15 +1831,10 @@ var _ArtifactParser = class _ArtifactParser {
1818
1831
  */
1819
1832
  parseCreateAnnotations(text) {
1820
1833
  const annotations = [];
1821
- const matches = [...text.matchAll(_ArtifactParser.ARTIFACT_CREATE_REGEX)];
1822
- logger7.debug({
1823
- textContainsCreate: text.includes("artifact:create"),
1824
- matchCount: matches.length,
1825
- textLength: text.length
1826
- }, "parseCreateAnnotations called");
1834
+ const createRegex = /<artifact:create\s+([^>]+?)(?:\s*\/)?>(?:(.*?)<\/artifact:create>)?/gs;
1835
+ const matches = [...text.matchAll(createRegex)];
1827
1836
  for (const match of matches) {
1828
1837
  const [fullMatch, attributes] = match;
1829
- logger7.debug({ fullMatch, attributes }, "Found artifact:create match");
1830
1838
  const annotation = this.parseCreateAttributes(attributes);
1831
1839
  if (annotation) {
1832
1840
  annotation.raw = fullMatch;
@@ -1838,7 +1846,7 @@ var _ArtifactParser = class _ArtifactParser {
1838
1846
  /**
1839
1847
  * Extract artifact data from a create annotation - delegates to service
1840
1848
  */
1841
- async extractFromCreateAnnotation(annotation) {
1849
+ async extractFromCreateAnnotation(annotation, agentId) {
1842
1850
  const request = {
1843
1851
  artifactId: annotation.artifactId,
1844
1852
  toolCallId: annotation.toolCallId,
@@ -1847,32 +1855,27 @@ var _ArtifactParser = class _ArtifactParser {
1847
1855
  summaryProps: annotation.summaryProps,
1848
1856
  fullProps: annotation.fullProps
1849
1857
  };
1850
- return this.artifactService.createArtifact(request);
1858
+ return this.artifactService.createArtifact(request, agentId);
1851
1859
  }
1852
1860
  /**
1853
1861
  * Parse text with artifact markers into parts array
1854
1862
  * Handles both artifact:ref and artifact:create tags
1855
1863
  * Can work with or without pre-fetched artifact map
1856
1864
  */
1857
- async parseText(text, artifactMap) {
1865
+ async parseText(text, artifactMap, agentId) {
1858
1866
  let processedText = text;
1859
1867
  const createAnnotations = this.parseCreateAnnotations(text);
1860
- logger7.debug({
1861
- hasCreateAnnotations: createAnnotations.length > 0,
1862
- annotationCount: createAnnotations.length,
1863
- textLength: text.length
1864
- }, "Processing text for artifact annotations");
1865
1868
  const createdArtifactData = /* @__PURE__ */ new Map();
1866
1869
  const failedAnnotations = [];
1867
1870
  for (const annotation of createAnnotations) {
1868
1871
  try {
1869
- const artifactData = await this.extractFromCreateAnnotation(annotation);
1872
+ const artifactData = await this.extractFromCreateAnnotation(annotation, agentId);
1870
1873
  if (artifactData && annotation.raw) {
1871
1874
  createdArtifactData.set(annotation.raw, artifactData);
1872
1875
  } else if (annotation.raw) {
1873
1876
  failedAnnotations.push(`Failed to create artifact "${annotation.artifactId}": Missing or invalid data`);
1874
1877
  processedText = processedText.replace(annotation.raw, "");
1875
- logger7.warn({ annotation }, "Removed failed artifact:create annotation from output");
1878
+ logger7.warn({ annotation, artifactData }, "Removed failed artifact:create annotation from output");
1876
1879
  }
1877
1880
  } catch (error) {
1878
1881
  const errorMsg = error instanceof Error ? error.message : "Unknown error";
@@ -1890,8 +1893,10 @@ var _ArtifactParser = class _ArtifactParser {
1890
1893
  }, "Some artifact creation attempts failed");
1891
1894
  }
1892
1895
  const parts = [];
1893
- const createMatches = [...text.matchAll(_ArtifactParser.ARTIFACT_CREATE_REGEX)];
1894
- const refMatches = [...processedText.matchAll(_ArtifactParser.ARTIFACT_REGEX)];
1896
+ const createRegex = /<artifact:create\s+([^>]+?)(?:\s*\/)?>(?:(.*?)<\/artifact:create>)?/gs;
1897
+ const refRegex = /<artifact:ref\s+id=(["'])([^"']*?)\1\s+tool=(["'])([^"']*?)\3\s*\/>/gs;
1898
+ const createMatches = [...text.matchAll(createRegex)];
1899
+ const refMatches = [...processedText.matchAll(refRegex)];
1895
1900
  const allMatches = [
1896
1901
  ...createMatches.map((match) => ({ match, type: "create" })),
1897
1902
  ...refMatches.map((match) => ({ match, type: "ref" }))
@@ -1933,7 +1938,7 @@ var _ArtifactParser = class _ArtifactParser {
1933
1938
  /**
1934
1939
  * Process object/dataComponents for artifact components
1935
1940
  */
1936
- async parseObject(obj, artifactMap) {
1941
+ async parseObject(obj, artifactMap, agentId) {
1937
1942
  if (obj?.dataComponents && Array.isArray(obj.dataComponents)) {
1938
1943
  const parts = [];
1939
1944
  for (const component of obj.dataComponents) {
@@ -1947,7 +1952,7 @@ var _ArtifactParser = class _ArtifactParser {
1947
1952
  parts.push({ kind: "data", data: artifactData });
1948
1953
  }
1949
1954
  } else if (this.isArtifactCreateComponent(component)) {
1950
- const createData = await this.extractFromArtifactCreateComponent(component);
1955
+ const createData = await this.extractFromArtifactCreateComponent(component, agentId);
1951
1956
  if (createData) {
1952
1957
  parts.push({ kind: "data", data: createData });
1953
1958
  }
@@ -1966,7 +1971,7 @@ var _ArtifactParser = class _ArtifactParser {
1966
1971
  return artifactData ? [{ kind: "data", data: artifactData }] : [];
1967
1972
  }
1968
1973
  if (this.isArtifactCreateComponent(obj)) {
1969
- const createData = await this.extractFromArtifactCreateComponent(obj);
1974
+ const createData = await this.extractFromArtifactCreateComponent(obj, agentId);
1970
1975
  return createData ? [{ kind: "data", data: createData }] : [];
1971
1976
  }
1972
1977
  return [{ kind: "data", data: obj }];
@@ -1975,15 +1980,7 @@ var _ArtifactParser = class _ArtifactParser {
1975
1980
  * Check if object is an artifact component
1976
1981
  */
1977
1982
  isArtifactComponent(obj) {
1978
- const result = obj?.name === "Artifact" && obj?.props?.artifact_id && obj?.props?.tool_call_id;
1979
- logger7.debug({
1980
- obj,
1981
- name: obj?.name,
1982
- artifact_id: obj?.props?.artifact_id,
1983
- tool_call_id: obj?.props?.tool_call_id,
1984
- result
1985
- }, "isArtifactComponent check");
1986
- return result;
1983
+ return obj?.name === "Artifact" && obj?.props?.artifact_id && obj?.props?.tool_call_id;
1987
1984
  }
1988
1985
  /**
1989
1986
  * Check if object is an artifact create component
@@ -1994,7 +1991,7 @@ var _ArtifactParser = class _ArtifactParser {
1994
1991
  /**
1995
1992
  * Extract artifact from ArtifactCreate component
1996
1993
  */
1997
- async extractFromArtifactCreateComponent(component) {
1994
+ async extractFromArtifactCreateComponent(component, agentId) {
1998
1995
  const props = component.props;
1999
1996
  if (!props) {
2000
1997
  return null;
@@ -2007,7 +2004,7 @@ var _ArtifactParser = class _ArtifactParser {
2007
2004
  summaryProps: props.summary_props || {},
2008
2005
  fullProps: props.full_props || {}
2009
2006
  };
2010
- return await this.extractFromCreateAnnotation(annotation);
2007
+ return await this.extractFromCreateAnnotation(annotation, agentId);
2011
2008
  }
2012
2009
  /**
2013
2010
  * Get artifact data - delegates to service
@@ -2185,7 +2182,8 @@ var GraphSession = class {
2185
2182
  }
2186
2183
  this.pendingArtifacts.add(artifactId);
2187
2184
  setImmediate(() => {
2188
- this.processArtifact(data).then(() => {
2185
+ const artifactDataWithAgent = { ...data, agentId };
2186
+ this.processArtifact(artifactDataWithAgent).then(() => {
2189
2187
  this.pendingArtifacts.delete(artifactId);
2190
2188
  this.artifactProcessingErrors.delete(artifactId);
2191
2189
  }).catch((error) => {
@@ -2908,91 +2906,139 @@ Make it specific and relevant.`;
2908
2906
  let modelToUse = this.statusUpdateState?.summarizerModel;
2909
2907
  if (!modelToUse?.model?.trim()) {
2910
2908
  if (!this.statusUpdateState?.baseModel?.model?.trim()) {
2911
- throw new Error(
2912
- "Either summarizer or base model is required for artifact name generation. Please configure models at the project level."
2913
- );
2914
- }
2915
- modelToUse = this.statusUpdateState.baseModel;
2916
- }
2917
- if (!modelToUse) {
2918
- throw new Error("No model configuration available");
2919
- }
2920
- const model = ModelFactory.createModel(modelToUse);
2921
- const schema = z.object({
2922
- name: z.string().describe("Concise, descriptive name for the artifact"),
2923
- description: z.string().describe("Brief description of the artifact's relevance to the user's question")
2924
- });
2925
- const { object: result } = await tracer.startActiveSpan(
2926
- "graph_session.generate_artifact_metadata",
2927
- {
2928
- attributes: {
2929
- "llm.model": this.statusUpdateState?.summarizerModel?.model,
2930
- "llm.operation": "generate_object",
2931
- "artifact.id": artifactData.artifactId,
2932
- "artifact.type": artifactData.artifactType,
2933
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
2934
- "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
2935
- "prompt.length": prompt.length
2936
- }
2937
- },
2938
- async (generationSpan) => {
2939
- const maxRetries = 3;
2940
- let lastError = null;
2941
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
2909
+ if (artifactData.agentId && artifactData.tenantId && artifactData.projectId) {
2942
2910
  try {
2943
- const result2 = await generateObject({
2944
- model,
2945
- prompt,
2946
- schema,
2947
- experimental_telemetry: {
2948
- isEnabled: true,
2949
- functionId: `artifact_processing_${artifactData.artifactId}`,
2950
- recordInputs: true,
2951
- recordOutputs: true,
2952
- metadata: {
2953
- operation: "artifact_name_description_generation",
2954
- sessionId: this.sessionId,
2955
- attempt
2956
- }
2957
- }
2958
- });
2959
- generationSpan.setAttributes({
2960
- "artifact.id": artifactData.artifactId,
2961
- "artifact.type": artifactData.artifactType,
2962
- "artifact.name": result2.object.name,
2963
- "artifact.description": result2.object.description,
2964
- "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
2965
- "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
2966
- "generation.name_length": result2.object.name.length,
2967
- "generation.description_length": result2.object.description.length,
2968
- "generation.attempts": attempt
2911
+ const agentData = await getAgentById(dbClient_default)({
2912
+ scopes: {
2913
+ tenantId: artifactData.tenantId,
2914
+ projectId: artifactData.projectId,
2915
+ graphId: this.graphId || ""
2916
+ },
2917
+ agentId: artifactData.agentId
2969
2918
  });
2970
- generationSpan.setStatus({ code: SpanStatusCode.OK });
2971
- return result2;
2919
+ if (agentData && "models" in agentData && agentData.models?.base?.model) {
2920
+ modelToUse = agentData.models.base;
2921
+ logger8.info(
2922
+ {
2923
+ sessionId: this.sessionId,
2924
+ artifactId: artifactData.artifactId,
2925
+ agentId: artifactData.agentId,
2926
+ model: modelToUse.model
2927
+ },
2928
+ "Using agent model configuration for artifact name generation"
2929
+ );
2930
+ }
2972
2931
  } catch (error) {
2973
- lastError = error instanceof Error ? error : new Error(String(error));
2974
2932
  logger8.warn(
2975
2933
  {
2976
2934
  sessionId: this.sessionId,
2977
2935
  artifactId: artifactData.artifactId,
2978
- attempt,
2979
- maxRetries,
2980
- error: lastError.message
2936
+ agentId: artifactData.agentId,
2937
+ error: error instanceof Error ? error.message : "Unknown error"
2981
2938
  },
2982
- `Artifact name/description generation failed, attempt ${attempt}/${maxRetries}`
2939
+ "Failed to get agent model configuration"
2983
2940
  );
2984
- if (attempt < maxRetries) {
2985
- const backoffMs = Math.min(1e3 * 2 ** (attempt - 1), 1e4);
2986
- await new Promise((resolve) => setTimeout(resolve, backoffMs));
2987
- }
2988
2941
  }
2989
2942
  }
2990
- setSpanWithError(generationSpan, lastError);
2991
- throw new Error(
2992
- `Artifact name/description generation failed after ${maxRetries} attempts: ${lastError?.message}`
2993
- );
2943
+ if (!modelToUse?.model?.trim()) {
2944
+ logger8.warn(
2945
+ {
2946
+ sessionId: this.sessionId,
2947
+ artifactId: artifactData.artifactId
2948
+ },
2949
+ "No model configuration available for artifact name generation, will use fallback names"
2950
+ );
2951
+ modelToUse = void 0;
2952
+ }
2953
+ } else {
2954
+ modelToUse = this.statusUpdateState.baseModel;
2994
2955
  }
2995
- );
2956
+ }
2957
+ let result;
2958
+ if (!modelToUse) {
2959
+ result = {
2960
+ name: `Artifact ${artifactData.artifactId.substring(0, 8)}`,
2961
+ description: `${artifactData.artifactType || "Data"} from ${artifactData.metadata?.toolCallId || "tool results"}`
2962
+ };
2963
+ } else {
2964
+ const model = ModelFactory.createModel(modelToUse);
2965
+ const schema = z.object({
2966
+ name: z.string().describe("Concise, descriptive name for the artifact"),
2967
+ description: z.string().describe("Brief description of the artifact's relevance to the user's question")
2968
+ });
2969
+ const { object } = await tracer.startActiveSpan(
2970
+ "graph_session.generate_artifact_metadata",
2971
+ {
2972
+ attributes: {
2973
+ "llm.model": this.statusUpdateState?.summarizerModel?.model,
2974
+ "llm.operation": "generate_object",
2975
+ "artifact.id": artifactData.artifactId,
2976
+ "artifact.type": artifactData.artifactType,
2977
+ "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
2978
+ "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
2979
+ "prompt.length": prompt.length
2980
+ }
2981
+ },
2982
+ async (generationSpan) => {
2983
+ const maxRetries = 3;
2984
+ let lastError = null;
2985
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
2986
+ try {
2987
+ const result2 = await generateObject({
2988
+ model,
2989
+ prompt,
2990
+ schema,
2991
+ experimental_telemetry: {
2992
+ isEnabled: true,
2993
+ functionId: `artifact_processing_${artifactData.artifactId}`,
2994
+ recordInputs: true,
2995
+ recordOutputs: true,
2996
+ metadata: {
2997
+ operation: "artifact_name_description_generation",
2998
+ sessionId: this.sessionId,
2999
+ attempt
3000
+ }
3001
+ }
3002
+ });
3003
+ generationSpan.setAttributes({
3004
+ "artifact.id": artifactData.artifactId,
3005
+ "artifact.type": artifactData.artifactType,
3006
+ "artifact.name": result2.object.name,
3007
+ "artifact.description": result2.object.description,
3008
+ "artifact.summary": JSON.stringify(artifactData.summaryProps, null, 2),
3009
+ "artifact.full": JSON.stringify(artifactData.fullProps, null, 2),
3010
+ "generation.name_length": result2.object.name.length,
3011
+ "generation.description_length": result2.object.description.length,
3012
+ "generation.attempts": attempt
3013
+ });
3014
+ generationSpan.setStatus({ code: SpanStatusCode.OK });
3015
+ return result2;
3016
+ } catch (error) {
3017
+ lastError = error instanceof Error ? error : new Error(String(error));
3018
+ logger8.warn(
3019
+ {
3020
+ sessionId: this.sessionId,
3021
+ artifactId: artifactData.artifactId,
3022
+ attempt,
3023
+ maxRetries,
3024
+ error: lastError.message
3025
+ },
3026
+ `Artifact name/description generation failed, attempt ${attempt}/${maxRetries}`
3027
+ );
3028
+ if (attempt < maxRetries) {
3029
+ const backoffMs = Math.min(1e3 * 2 ** (attempt - 1), 1e4);
3030
+ await new Promise((resolve) => setTimeout(resolve, backoffMs));
3031
+ }
3032
+ }
3033
+ }
3034
+ setSpanWithError(generationSpan, lastError);
3035
+ throw new Error(
3036
+ `Artifact name/description generation failed after ${maxRetries} attempts: ${lastError?.message}`
3037
+ );
3038
+ }
3039
+ );
3040
+ result = object;
3041
+ }
2996
3042
  const artifactService = new ArtifactService({
2997
3043
  tenantId: artifactData.tenantId,
2998
3044
  projectId: artifactData.projectId,
@@ -3248,8 +3294,10 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3248
3294
  __publicField(this, "lastStreamedComponents", /* @__PURE__ */ new Map());
3249
3295
  __publicField(this, "componentSnapshots", /* @__PURE__ */ new Map());
3250
3296
  __publicField(this, "artifactMap");
3297
+ __publicField(this, "agentId");
3251
3298
  this.streamHelper = streamHelper;
3252
3299
  this.contextId = contextId;
3300
+ this.agentId = artifactParserOptions?.agentId;
3253
3301
  if (artifactParserOptions?.streamRequestId) {
3254
3302
  const sessionParser = graphSessionManager.getArtifactParser(
3255
3303
  artifactParserOptions.streamRequestId
@@ -3378,7 +3426,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3378
3426
  async streamComponent(component) {
3379
3427
  const parts = await this.artifactParser.parseObject({
3380
3428
  dataComponents: [component]
3381
- });
3429
+ }, this.artifactMap, this.agentId);
3382
3430
  if (!Array.isArray(parts)) {
3383
3431
  console.warn("parseObject returned non-array:", parts);
3384
3432
  return;
@@ -3450,7 +3498,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3450
3498
  if (!hasBeenStreamed && this.isComponentComplete(component) && component.name !== "Text") {
3451
3499
  const parts = await this.artifactParser.parseObject({
3452
3500
  dataComponents: [component]
3453
- });
3501
+ }, this.artifactMap, this.agentId);
3454
3502
  for (const part of parts) {
3455
3503
  await this.streamPart(part);
3456
3504
  }
@@ -3503,7 +3551,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3503
3551
  const safeEnd = this.artifactParser.findSafeTextBoundary(workingBuffer);
3504
3552
  if (safeEnd > 0) {
3505
3553
  const safeText = workingBuffer.slice(0, safeEnd);
3506
- const parts2 = await this.artifactParser.parseText(safeText, this.artifactMap);
3554
+ const parts2 = await this.artifactParser.parseText(safeText, this.artifactMap, this.agentId);
3507
3555
  completeParts.push(...parts2);
3508
3556
  return {
3509
3557
  completeParts,
@@ -3515,7 +3563,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3515
3563
  remainingBuffer: workingBuffer
3516
3564
  };
3517
3565
  }
3518
- const parts = await this.artifactParser.parseText(workingBuffer, this.artifactMap);
3566
+ const parts = await this.artifactParser.parseText(workingBuffer, this.artifactMap, this.agentId);
3519
3567
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
3520
3568
  const lastPart = parts[parts.length - 1];
3521
3569
  const lastText = lastPart.text || "";
@@ -3591,6 +3639,8 @@ var logger10 = getLogger("ResponseFormatter");
3591
3639
  var ResponseFormatter = class {
3592
3640
  constructor(tenantId, artifactParserOptions) {
3593
3641
  __publicField(this, "artifactParser");
3642
+ __publicField(this, "agentId");
3643
+ this.agentId = artifactParserOptions?.agentId;
3594
3644
  if (artifactParserOptions?.streamRequestId) {
3595
3645
  const sessionParser = graphSessionManager.getArtifactParser(artifactParserOptions.streamRequestId);
3596
3646
  if (sessionParser) {
@@ -3611,7 +3661,7 @@ var ResponseFormatter = class {
3611
3661
  "response.type": "object",
3612
3662
  "response.availableArtifacts": artifactMap.size
3613
3663
  });
3614
- const parts = await this.artifactParser.parseObject(responseObject, artifactMap);
3664
+ const parts = await this.artifactParser.parseObject(responseObject, artifactMap, this.agentId);
3615
3665
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
3616
3666
  span.setAttributes({
3617
3667
  "response.dataPartsCount": parts.length,
@@ -3640,8 +3690,9 @@ var ResponseFormatter = class {
3640
3690
  async formatResponse(responseText, contextId) {
3641
3691
  return tracer.startActiveSpan("response.format_response", async (span) => {
3642
3692
  try {
3693
+ const hasMarkers = this.artifactParser.hasArtifactMarkers(responseText);
3643
3694
  span.setAttributes({
3644
- "response.hasArtifactMarkers": this.artifactParser.hasArtifactMarkers(responseText),
3695
+ "response.hasArtifactMarkers": hasMarkers,
3645
3696
  "response.contextId": contextId,
3646
3697
  "response.textLength": responseText.length
3647
3698
  });
@@ -3656,7 +3707,7 @@ var ResponseFormatter = class {
3656
3707
  "response.type": "text",
3657
3708
  "response.availableArtifacts": artifactMap.size
3658
3709
  });
3659
- const parts = await this.artifactParser.parseText(responseText, artifactMap);
3710
+ const parts = await this.artifactParser.parseText(responseText, artifactMap, this.agentId);
3660
3711
  if (parts.length === 1 && parts[0].kind === "text") {
3661
3712
  return { text: parts[0].text };
3662
3713
  }
@@ -5109,6 +5160,14 @@ CITATION PLACEMENT RULES:
5109
5160
 
5110
5161
  \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
5111
5162
 
5163
+ DELEGATION AND ARTIFACTS:
5164
+ When you use delegation tools, the response may include artifacts in the parts array. These appear as objects with:
5165
+ - kind: "data"
5166
+ - data: { artifactId, toolCallId, name, description, type, artifactSummary }
5167
+
5168
+ These artifacts become immediately available for you to reference using the artifactId and toolCallId from the response.
5169
+ Present delegation results naturally without mentioning the delegation process itself.
5170
+
5112
5171
  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.`;
5113
5172
 
5114
5173
  // templates/v1/phase1/system-prompt.xml?raw
@@ -5147,6 +5206,20 @@ var system_prompt_default = `<system_message>
5147
5206
  - Save important tool results as artifacts when they contain structured data that should be preserved and referenced
5148
5207
  - Ask for clarification when requests are ambiguous
5149
5208
 
5209
+ \u{1F6A8} UNIFIED ASSISTANT PRESENTATION - CRITICAL:
5210
+ - You are the ONLY assistant the user is interacting with
5211
+ - NEVER mention other agents, specialists, experts, or team members
5212
+ - NEVER use phrases like "I'll delegate", "I'll transfer", "I'll ask our specialist"
5213
+ - NEVER say "the weather agent returned" or "the search specialist found"
5214
+ - Present ALL results as if YOU personally performed the work
5215
+ - Use first person: "I found", "I analyzed", "I've gathered"
5216
+
5217
+ \u{1F6A8} DELEGATION TOOL RULES - CRITICAL:
5218
+ - When using delegate_to_* tools, treat them like any other tool
5219
+ - Present results naturally: "I've analyzed the data and found..."
5220
+ - NEVER mention delegation occurred: just present the results
5221
+ - If delegation returns artifacts, reference them as if you created them
5222
+
5150
5223
  \u{1F6A8} TRANSFER TOOL RULES - CRITICAL:
5151
5224
  - When calling transfer_to_* tools, call the tool IMMEDIATELY without any explanatory text
5152
5225
  - Do NOT explain the transfer, do NOT say "I'll hand this off", do NOT provide reasoning
@@ -5214,6 +5287,7 @@ var thinking_preparation_default = `<thinking_preparation_mode>
5214
5287
  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> ";
5215
5288
 
5216
5289
  // src/agents/versions/v1/Phase1Config.ts
5290
+ getLogger("Phase1Config");
5217
5291
  var Phase1Config = class _Phase1Config {
5218
5292
  loadTemplates() {
5219
5293
  const templates = /* @__PURE__ */ new Map();
@@ -5306,13 +5380,18 @@ var Phase1Config = class _Phase1Config {
5306
5380
  if (!hasTransferRelations) {
5307
5381
  return "";
5308
5382
  }
5309
- return "- A transfer entails you passing control of the conversation to another agent that may be better suited to handle the task at hand.";
5383
+ return `- You have transfer_to_* tools that seamlessly continue the conversation
5384
+ - NEVER announce transfers - just call the tool when needed
5385
+ - The conversation continues naturally without any handoff language`;
5310
5386
  }
5311
5387
  generateDelegationInstructions(hasDelegateRelations) {
5312
5388
  if (!hasDelegateRelations) {
5313
5389
  return "";
5314
5390
  }
5315
- return "- A delegation means asking another agent to complete a specific task and return the result to you.";
5391
+ return `- You have delegate_to_* tools that perform specialized tasks
5392
+ - Treat these exactly like other tools - call them to get results
5393
+ - Present results as YOUR work: "I found", "I've analyzed"
5394
+ - NEVER say you're delegating or that another agent helped`;
5316
5395
  }
5317
5396
  getArtifactCreationGuidance() {
5318
5397
  return `\u{1F6A8} MANDATORY ARTIFACT CREATION \u{1F6A8}
@@ -5489,10 +5568,16 @@ The implementation details show that you need to register your application first
5489
5568
 
5490
5569
  For error handling, you can refer to the comprehensive error documentation. <artifact:ref id='existing-error-doc' tool='call_previous012' /> This lists all possible authentication errors and their solutions."
5491
5570
 
5571
+ EXAMPLE REFERENCING DELEGATION ARTIFACTS:
5572
+ After receiving a delegation response with artifacts, reference them naturally:
5573
+
5574
+ "I've gathered the requested data for you. The analysis <artifact:ref id='analysis-results' tool='toolu_abc123' /> shows significant improvements across all metrics.
5575
+
5576
+ Looking at the detailed breakdown <artifact:ref id='performance-metrics' tool='toolu_def456' />, the processing time has decreased by 40% while maintaining accuracy."
5577
+
5492
5578
  IMPORTANT GUIDELINES:
5493
- - You can only reference artifacts that already exist
5494
- - Use artifact:ref annotations in your text
5495
- - Copy artifact_id and tool_call_id exactly from existing artifacts
5579
+ - You can only reference artifacts that already exist or were returned from delegations
5580
+ - Use artifact:ref annotations in your text with the exact artifactId and toolCallId
5496
5581
  - References are automatically converted to interactive elements`;
5497
5582
  }
5498
5583
  return "";
@@ -5633,7 +5718,43 @@ ${propertiesXml}
5633
5718
  };
5634
5719
 
5635
5720
  // templates/v1/phase2/system-prompt.xml?raw
5636
- var system_prompt_default2 = "<phase2_system_message>\n <instruction>\n Generate the final structured JSON response using the configured data components and artifact creation capabilities.\n </instruction>\n\n <core_instructions>\n {{CORE_INSTRUCTIONS}}\n </core_instructions>\n\n {{ARTIFACTS_SECTION}}\n {{DATA_COMPONENTS_SECTION}}\n\n {{ARTIFACT_GUIDANCE_SECTION}}\n\n {{ARTIFACT_TYPES_SECTION}}\n\n <requirements>\n <key_requirements>\n - Create artifacts from tool results to support your information with citations\n - Mix artifact creation and references naturally throughout your dataComponents array\n - Each artifact creation must use EXACT tool_call_id from tool outputs\n - Use appropriate ArtifactCreate_[Type] components for each artifact type\n - IMPORTANT: In Text components, write naturally as if having a conversation - do NOT mention components, schemas, JSON, structured data, or any technical implementation details\n </key_requirements>\n </requirements>\n</phase2_system_message>";
5721
+ var system_prompt_default2 = `<phase2_system_message>
5722
+ <instruction>
5723
+ Generate the final structured JSON response using the configured data components and artifact creation capabilities.
5724
+ </instruction>
5725
+
5726
+ <core_instructions>
5727
+ {{CORE_INSTRUCTIONS}}
5728
+ </core_instructions>
5729
+
5730
+ {{ARTIFACTS_SECTION}}
5731
+ {{DATA_COMPONENTS_SECTION}}
5732
+
5733
+ {{ARTIFACT_GUIDANCE_SECTION}}
5734
+
5735
+ {{ARTIFACT_TYPES_SECTION}}
5736
+
5737
+ <requirements>
5738
+ <key_requirements>
5739
+ - Create artifacts from tool results to support your information with citations
5740
+ - Mix artifact creation and references naturally throughout your dataComponents array
5741
+ - Each artifact creation must use EXACT tool_call_id from tool outputs
5742
+ - Use appropriate ArtifactCreate_[Type] components for each artifact type
5743
+ - IMPORTANT: In Text components, write naturally as if having a conversation - do NOT mention components, schemas, JSON, structured data, or any technical implementation details
5744
+ </key_requirements>
5745
+
5746
+ <unified_presentation>
5747
+ \u{1F6A8} CRITICAL - PRESENT AS ONE UNIFIED ASSISTANT:
5748
+ - You are the ONLY assistant in this conversation
5749
+ - NEVER reference other agents, specialists, or team members
5750
+ - All tool results (including delegate_to_* tools) are YOUR findings
5751
+ - Present delegation results as: "I found", "I've analyzed", "The data shows"
5752
+ - NEVER say: "The specialist returned", "Another agent found", "I delegated this"
5753
+ - Artifacts from delegation are YOUR artifacts - reference them naturally
5754
+ - Maintain consistent first-person perspective throughout
5755
+ </unified_presentation>
5756
+ </requirements>
5757
+ </phase2_system_message>`;
5637
5758
 
5638
5759
  // templates/v1/phase2/data-components.xml?raw
5639
5760
  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>';
@@ -5742,8 +5863,11 @@ COMMON FAILURE POINTS (AVOID THESE):
5742
5863
  if (!shouldShowReferencingRules) {
5743
5864
  return "";
5744
5865
  }
5866
+ const sharedGuidance = artifact_retrieval_guidance_default;
5745
5867
  if (hasArtifactComponents && artifactComponents && artifactComponents.length > 0) {
5746
- return `ARTIFACT MANAGEMENT FOR STRUCTURED RESPONSES:
5868
+ return `${sharedGuidance}
5869
+
5870
+ ARTIFACT MANAGEMENT FOR STRUCTURED RESPONSES:
5747
5871
 
5748
5872
  You will create and reference artifacts using data components in your JSON response.
5749
5873
 
@@ -5823,12 +5947,14 @@ COMPONENT GUIDELINES:
5823
5947
  - Only add Artifact reference components when citing the SAME artifact again for a different point
5824
5948
  - Use tool_call_id exactly as it appears in tool execution results`;
5825
5949
  }
5826
- return `ARTIFACT REFERENCING FOR STRUCTURED RESPONSES:
5950
+ return `${sharedGuidance}
5951
+
5952
+ ARTIFACT REFERENCING FOR STRUCTURED RESPONSES:
5827
5953
 
5828
5954
  You can reference existing artifacts but cannot create new ones.
5829
5955
 
5830
5956
  HOW TO REFERENCE ARTIFACTS:
5831
- Use the Artifact component with artifact_id and tool_call_id from existing artifacts.
5957
+ Use the Artifact component with artifact_id and tool_call_id from existing artifacts or delegation responses.
5832
5958
 
5833
5959
  EXAMPLE STRUCTURED RESPONSE:
5834
5960
  \`\`\`json
@@ -6002,7 +6128,7 @@ function hasToolCallWithPrefix(prefix) {
6002
6128
  return false;
6003
6129
  };
6004
6130
  }
6005
- var logger15 = getLogger("Agent");
6131
+ var logger16 = getLogger("Agent");
6006
6132
  var CONSTANTS = {
6007
6133
  MAX_GENERATION_STEPS: 12,
6008
6134
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -6301,14 +6427,14 @@ var Agent = class {
6301
6427
  for (const toolSet of tools) {
6302
6428
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
6303
6429
  if (!isValidTool(originalTool)) {
6304
- logger15.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6430
+ logger16.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6305
6431
  continue;
6306
6432
  }
6307
6433
  const sessionWrappedTool = tool({
6308
6434
  description: originalTool.description,
6309
6435
  inputSchema: originalTool.inputSchema,
6310
6436
  execute: async (args, { toolCallId }) => {
6311
- logger15.debug({ toolName, toolCallId }, "MCP Tool Called");
6437
+ logger16.debug({ toolName, toolCallId }, "MCP Tool Called");
6312
6438
  try {
6313
6439
  const rawResult = await originalTool.execute(args, { toolCallId });
6314
6440
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -6322,7 +6448,7 @@ var Agent = class {
6322
6448
  });
6323
6449
  return { result: enhancedResult, toolCallId };
6324
6450
  } catch (error) {
6325
- logger15.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6451
+ logger16.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6326
6452
  throw error;
6327
6453
  }
6328
6454
  }
@@ -6416,7 +6542,7 @@ var Agent = class {
6416
6542
  headers: agentToolRelationHeaders
6417
6543
  };
6418
6544
  }
6419
- logger15.info(
6545
+ logger16.info(
6420
6546
  {
6421
6547
  toolName: tool3.name,
6422
6548
  credentialReferenceId,
@@ -6456,7 +6582,7 @@ var Agent = class {
6456
6582
  async getResolvedContext(conversationId, requestContext) {
6457
6583
  try {
6458
6584
  if (!this.config.contextConfigId) {
6459
- logger15.debug({ graphId: this.config.graphId }, "No context config found for graph");
6585
+ logger16.debug({ graphId: this.config.graphId }, "No context config found for graph");
6460
6586
  return null;
6461
6587
  }
6462
6588
  const contextConfig = await getContextConfigById(dbClient_default)({
@@ -6464,7 +6590,7 @@ var Agent = class {
6464
6590
  id: this.config.contextConfigId
6465
6591
  });
6466
6592
  if (!contextConfig) {
6467
- logger15.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
6593
+ logger16.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
6468
6594
  return null;
6469
6595
  }
6470
6596
  if (!this.contextResolver) {
@@ -6481,7 +6607,7 @@ var Agent = class {
6481
6607
  $now: (/* @__PURE__ */ new Date()).toISOString(),
6482
6608
  $env: process.env
6483
6609
  };
6484
- logger15.debug(
6610
+ logger16.debug(
6485
6611
  {
6486
6612
  conversationId,
6487
6613
  contextConfigId: contextConfig.id,
@@ -6495,7 +6621,7 @@ var Agent = class {
6495
6621
  );
6496
6622
  return contextWithBuiltins;
6497
6623
  } catch (error) {
6498
- logger15.error(
6624
+ logger16.error(
6499
6625
  {
6500
6626
  conversationId,
6501
6627
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6519,7 +6645,7 @@ var Agent = class {
6519
6645
  });
6520
6646
  return graphDefinition?.graphPrompt || void 0;
6521
6647
  } catch (error) {
6522
- logger15.warn(
6648
+ logger16.warn(
6523
6649
  {
6524
6650
  graphId: this.config.graphId,
6525
6651
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6548,7 +6674,7 @@ var Agent = class {
6548
6674
  (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
6549
6675
  );
6550
6676
  } catch (error) {
6551
- logger15.warn(
6677
+ logger16.warn(
6552
6678
  {
6553
6679
  graphId: this.config.graphId,
6554
6680
  tenantId: this.config.tenantId,
@@ -6577,7 +6703,7 @@ var Agent = class {
6577
6703
  preserveUnresolved: false
6578
6704
  });
6579
6705
  } catch (error) {
6580
- logger15.error(
6706
+ logger16.error(
6581
6707
  {
6582
6708
  conversationId,
6583
6709
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6624,7 +6750,7 @@ var Agent = class {
6624
6750
  preserveUnresolved: false
6625
6751
  });
6626
6752
  } catch (error) {
6627
- logger15.error(
6753
+ logger16.error(
6628
6754
  {
6629
6755
  conversationId,
6630
6756
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6663,7 +6789,7 @@ var Agent = class {
6663
6789
  preserveUnresolved: false
6664
6790
  });
6665
6791
  } catch (error) {
6666
- logger15.error(
6792
+ logger16.error(
6667
6793
  {
6668
6794
  conversationId,
6669
6795
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6695,7 +6821,7 @@ var Agent = class {
6695
6821
  artifactId: z.string().describe("The unique identifier of the artifact to get.")
6696
6822
  }),
6697
6823
  execute: async ({ artifactId }) => {
6698
- logger15.info({ artifactId }, "get_artifact executed");
6824
+ logger16.info({ artifactId }, "get_artifact executed");
6699
6825
  const artifact = await getLedgerArtifacts(dbClient_default)({
6700
6826
  scopes: {
6701
6827
  tenantId: this.config.tenantId,
@@ -6945,7 +7071,7 @@ var Agent = class {
6945
7071
  };
6946
7072
  return enhanced;
6947
7073
  } catch (error) {
6948
- logger15.warn({ error }, "Failed to enhance tool result with structure hints");
7074
+ logger16.warn({ error }, "Failed to enhance tool result with structure hints");
6949
7075
  return result;
6950
7076
  }
6951
7077
  }
@@ -6960,7 +7086,7 @@ var Agent = class {
6960
7086
  }
6961
7087
  });
6962
7088
  } catch (error) {
6963
- logger15.error(
7089
+ logger16.error(
6964
7090
  { error, graphId: this.config.graphId },
6965
7091
  "Failed to check graph artifact components"
6966
7092
  );
@@ -7060,7 +7186,7 @@ var Agent = class {
7060
7186
  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;
7061
7187
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
7062
7188
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
7063
- logger15.warn(
7189
+ logger16.warn(
7064
7190
  {
7065
7191
  requestedTimeout: modelSettings.maxDuration * 1e3,
7066
7192
  appliedTimeout: timeoutMs,
@@ -7102,7 +7228,7 @@ var Agent = class {
7102
7228
  }
7103
7229
  );
7104
7230
  } catch (error) {
7105
- logger15.debug({ error }, "Failed to track agent reasoning");
7231
+ logger16.debug({ error }, "Failed to track agent reasoning");
7106
7232
  }
7107
7233
  }
7108
7234
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7199,7 +7325,7 @@ var Agent = class {
7199
7325
  }
7200
7326
  );
7201
7327
  } catch (error) {
7202
- logger15.debug({ error }, "Failed to track agent reasoning");
7328
+ logger16.debug({ error }, "Failed to track agent reasoning");
7203
7329
  }
7204
7330
  }
7205
7331
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7490,7 +7616,7 @@ ${output}${structureHintsFormatted}`;
7490
7616
  };
7491
7617
 
7492
7618
  // src/agents/generateTaskHandler.ts
7493
- var logger16 = getLogger("generateTaskHandler");
7619
+ var logger17 = getLogger("generateTaskHandler");
7494
7620
  var createTaskHandler = (config, credentialStoreRegistry) => {
7495
7621
  return async (task) => {
7496
7622
  try {
@@ -7543,7 +7669,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7543
7669
  }
7544
7670
  })
7545
7671
  ]);
7546
- logger16.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
7672
+ logger17.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
7547
7673
  const enhancedInternalRelations = await Promise.all(
7548
7674
  internalRelations.map(async (relation) => {
7549
7675
  try {
@@ -7572,7 +7698,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7572
7698
  return { ...relation, description: enhancedDescription };
7573
7699
  }
7574
7700
  } catch (error) {
7575
- logger16.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
7701
+ logger17.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
7576
7702
  }
7577
7703
  return relation;
7578
7704
  })
@@ -7672,7 +7798,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7672
7798
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
7673
7799
  if (taskIdMatch) {
7674
7800
  contextId = taskIdMatch[1];
7675
- logger16.info(
7801
+ logger17.info(
7676
7802
  {
7677
7803
  taskId: task.id,
7678
7804
  extractedContextId: contextId,
@@ -7688,7 +7814,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7688
7814
  const isDelegation = task.context?.metadata?.isDelegation === true;
7689
7815
  agent.setDelegationStatus(isDelegation);
7690
7816
  if (isDelegation) {
7691
- logger16.info(
7817
+ logger17.info(
7692
7818
  { agentId: config.agentId, taskId: task.id },
7693
7819
  "Delegated agent - streaming disabled"
7694
7820
  );
@@ -7910,7 +8036,7 @@ async function getRegisteredGraph(executionContext) {
7910
8036
 
7911
8037
  // src/routes/agents.ts
7912
8038
  var app = new OpenAPIHono();
7913
- var logger17 = getLogger("agents");
8039
+ var logger18 = getLogger("agents");
7914
8040
  app.openapi(
7915
8041
  createRoute({
7916
8042
  method: "get",
@@ -7948,7 +8074,7 @@ app.openapi(
7948
8074
  tracestate: c.req.header("tracestate"),
7949
8075
  baggage: c.req.header("baggage")
7950
8076
  };
7951
- logger17.info(
8077
+ logger18.info(
7952
8078
  {
7953
8079
  otelHeaders,
7954
8080
  path: c.req.path,
@@ -7960,7 +8086,7 @@ app.openapi(
7960
8086
  const { tenantId, projectId, graphId, agentId } = executionContext;
7961
8087
  console.dir("executionContext", executionContext);
7962
8088
  if (agentId) {
7963
- logger17.info(
8089
+ logger18.info(
7964
8090
  {
7965
8091
  message: "getRegisteredAgent (agent-level)",
7966
8092
  tenantId,
@@ -7972,7 +8098,7 @@ app.openapi(
7972
8098
  );
7973
8099
  const credentialStores = c.get("credentialStores");
7974
8100
  const agent = await getRegisteredAgent(executionContext, credentialStores);
7975
- logger17.info({ agent }, "agent registered: well-known agent.json");
8101
+ logger18.info({ agent }, "agent registered: well-known agent.json");
7976
8102
  if (!agent) {
7977
8103
  throw createApiError({
7978
8104
  code: "not_found",
@@ -7981,7 +8107,7 @@ app.openapi(
7981
8107
  }
7982
8108
  return c.json(agent.agentCard);
7983
8109
  } else {
7984
- logger17.info(
8110
+ logger18.info(
7985
8111
  {
7986
8112
  message: "getRegisteredGraph (graph-level)",
7987
8113
  tenantId,
@@ -8007,7 +8133,7 @@ app.post("/a2a", async (c) => {
8007
8133
  tracestate: c.req.header("tracestate"),
8008
8134
  baggage: c.req.header("baggage")
8009
8135
  };
8010
- logger17.info(
8136
+ logger18.info(
8011
8137
  {
8012
8138
  otelHeaders,
8013
8139
  path: c.req.path,
@@ -8018,7 +8144,7 @@ app.post("/a2a", async (c) => {
8018
8144
  const executionContext = getRequestExecutionContext(c);
8019
8145
  const { tenantId, projectId, graphId, agentId } = executionContext;
8020
8146
  if (agentId) {
8021
- logger17.info(
8147
+ logger18.info(
8022
8148
  {
8023
8149
  message: "a2a (agent-level)",
8024
8150
  tenantId,
@@ -8042,7 +8168,7 @@ app.post("/a2a", async (c) => {
8042
8168
  }
8043
8169
  return a2aHandler(c, agent);
8044
8170
  } else {
8045
- logger17.info(
8171
+ logger18.info(
8046
8172
  {
8047
8173
  message: "a2a (graph-level)",
8048
8174
  tenantId,
@@ -8091,14 +8217,14 @@ app.post("/a2a", async (c) => {
8091
8217
  }
8092
8218
  });
8093
8219
  var agents_default = app;
8094
- var logger18 = getLogger("Transfer");
8220
+ var logger19 = getLogger("Transfer");
8095
8221
  async function executeTransfer({
8096
8222
  tenantId,
8097
8223
  threadId,
8098
8224
  projectId,
8099
8225
  targetAgentId
8100
8226
  }) {
8101
- logger18.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8227
+ logger19.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8102
8228
  await setActiveAgentForThread(dbClient_default)({
8103
8229
  scopes: { tenantId, projectId },
8104
8230
  threadId,
@@ -8680,7 +8806,7 @@ function createMCPStreamHelper() {
8680
8806
  }
8681
8807
 
8682
8808
  // src/handlers/executionHandler.ts
8683
- var logger19 = getLogger("ExecutionHandler");
8809
+ var logger20 = getLogger("ExecutionHandler");
8684
8810
  var ExecutionHandler = class {
8685
8811
  constructor() {
8686
8812
  // Hardcoded error limit - separate from configurable stopWhen
@@ -8705,7 +8831,7 @@ var ExecutionHandler = class {
8705
8831
  const { tenantId, projectId, graphId, apiKey, baseUrl } = executionContext;
8706
8832
  registerStreamHelper(requestId2, sseHelper);
8707
8833
  graphSessionManager.createSession(requestId2, graphId, tenantId, projectId, conversationId);
8708
- logger19.info(
8834
+ logger20.info(
8709
8835
  { sessionId: requestId2, graphId, conversationId },
8710
8836
  "Created GraphSession for message execution"
8711
8837
  );
@@ -8720,7 +8846,7 @@ var ExecutionHandler = class {
8720
8846
  );
8721
8847
  }
8722
8848
  } catch (error) {
8723
- logger19.error(
8849
+ logger20.error(
8724
8850
  {
8725
8851
  error: error instanceof Error ? error.message : "Unknown error",
8726
8852
  stack: error instanceof Error ? error.stack : void 0
@@ -8736,7 +8862,7 @@ var ExecutionHandler = class {
8736
8862
  try {
8737
8863
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
8738
8864
  const taskId = `task_${conversationId}-${requestId2}`;
8739
- logger19.info(
8865
+ logger20.info(
8740
8866
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
8741
8867
  "Attempting to create or reuse existing task"
8742
8868
  );
@@ -8760,7 +8886,7 @@ var ExecutionHandler = class {
8760
8886
  agent_id: currentAgentId
8761
8887
  }
8762
8888
  });
8763
- logger19.info(
8889
+ logger20.info(
8764
8890
  {
8765
8891
  taskId,
8766
8892
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -8769,27 +8895,27 @@ var ExecutionHandler = class {
8769
8895
  );
8770
8896
  } catch (error) {
8771
8897
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
8772
- logger19.info(
8898
+ logger20.info(
8773
8899
  { taskId, error: error.message },
8774
8900
  "Task already exists, fetching existing task"
8775
8901
  );
8776
8902
  const existingTask = await getTask(dbClient_default)({ id: taskId });
8777
8903
  if (existingTask) {
8778
8904
  task = existingTask;
8779
- logger19.info(
8905
+ logger20.info(
8780
8906
  { taskId, existingTask },
8781
8907
  "Successfully reused existing task from race condition"
8782
8908
  );
8783
8909
  } else {
8784
- logger19.error({ taskId, error }, "Task constraint failed but task not found");
8910
+ logger20.error({ taskId, error }, "Task constraint failed but task not found");
8785
8911
  throw error;
8786
8912
  }
8787
8913
  } else {
8788
- logger19.error({ taskId, error }, "Failed to create task due to non-constraint error");
8914
+ logger20.error({ taskId, error }, "Failed to create task due to non-constraint error");
8789
8915
  throw error;
8790
8916
  }
8791
8917
  }
8792
- logger19.debug(
8918
+ logger20.debug(
8793
8919
  {
8794
8920
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8795
8921
  executionType: "create_initial_task",
@@ -8807,7 +8933,7 @@ var ExecutionHandler = class {
8807
8933
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
8808
8934
  while (iterations < maxTransfers) {
8809
8935
  iterations++;
8810
- logger19.info(
8936
+ logger20.info(
8811
8937
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
8812
8938
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
8813
8939
  );
@@ -8815,10 +8941,10 @@ var ExecutionHandler = class {
8815
8941
  scopes: { tenantId, projectId },
8816
8942
  conversationId
8817
8943
  });
8818
- logger19.info({ activeAgent }, "activeAgent");
8944
+ logger20.info({ activeAgent }, "activeAgent");
8819
8945
  if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
8820
8946
  currentAgentId = activeAgent.activeAgentId;
8821
- logger19.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
8947
+ logger20.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
8822
8948
  }
8823
8949
  const agentBaseUrl = `${baseUrl}/agents`;
8824
8950
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -8859,13 +8985,13 @@ var ExecutionHandler = class {
8859
8985
  });
8860
8986
  if (!messageResponse?.result) {
8861
8987
  errorCount++;
8862
- logger19.error(
8988
+ logger20.error(
8863
8989
  { currentAgentId, iterations, errorCount },
8864
8990
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
8865
8991
  );
8866
8992
  if (errorCount >= this.MAX_ERRORS) {
8867
8993
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
8868
- logger19.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
8994
+ logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
8869
8995
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
8870
8996
  if (task) {
8871
8997
  await updateTask(dbClient_default)({
@@ -8890,7 +9016,7 @@ var ExecutionHandler = class {
8890
9016
  const transferResponse = messageResponse.result;
8891
9017
  const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
8892
9018
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
8893
- logger19.info({ targetAgentId, transferReason }, "transfer response");
9019
+ logger20.info({ targetAgentId, transferReason }, "transfer response");
8894
9020
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
8895
9021
  const { success, targetAgentId: newAgentId } = await executeTransfer({
8896
9022
  projectId,
@@ -8901,7 +9027,7 @@ var ExecutionHandler = class {
8901
9027
  if (success) {
8902
9028
  fromAgentId = currentAgentId;
8903
9029
  currentAgentId = newAgentId;
8904
- logger19.info(
9030
+ logger20.info(
8905
9031
  {
8906
9032
  transferFrom: fromAgentId,
8907
9033
  transferTo: currentAgentId,
@@ -8919,7 +9045,7 @@ var ExecutionHandler = class {
8919
9045
  const graphSessionData = graphSessionManager.getSession(requestId2);
8920
9046
  if (graphSessionData) {
8921
9047
  const sessionSummary = graphSessionData.getSummary();
8922
- logger19.info(sessionSummary, "GraphSession data after completion");
9048
+ logger20.info(sessionSummary, "GraphSession data after completion");
8923
9049
  }
8924
9050
  let textContent = "";
8925
9051
  for (const part of responseParts) {
@@ -8973,22 +9099,22 @@ var ExecutionHandler = class {
8973
9099
  }
8974
9100
  });
8975
9101
  const updateTaskEnd = Date.now();
8976
- logger19.info(
9102
+ logger20.info(
8977
9103
  { duration: updateTaskEnd - updateTaskStart },
8978
9104
  "Completed updateTask operation"
8979
9105
  );
8980
9106
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
8981
9107
  await sseHelper.complete();
8982
- logger19.info({}, "Ending GraphSession and cleaning up");
9108
+ logger20.info({}, "Ending GraphSession and cleaning up");
8983
9109
  graphSessionManager.endSession(requestId2);
8984
- logger19.info({}, "Cleaning up streamHelper");
9110
+ logger20.info({}, "Cleaning up streamHelper");
8985
9111
  unregisterStreamHelper(requestId2);
8986
9112
  let response;
8987
9113
  if (sseHelper instanceof MCPStreamHelper) {
8988
9114
  const captured = sseHelper.getCapturedResponse();
8989
9115
  response = captured.text || "No response content";
8990
9116
  }
8991
- logger19.info({}, "ExecutionHandler returning success");
9117
+ logger20.info({}, "ExecutionHandler returning success");
8992
9118
  return { success: true, iterations, response };
8993
9119
  } catch (error) {
8994
9120
  setSpanWithError(span, error);
@@ -8999,13 +9125,13 @@ var ExecutionHandler = class {
8999
9125
  });
9000
9126
  }
9001
9127
  errorCount++;
9002
- logger19.warn(
9128
+ logger20.warn(
9003
9129
  { iterations, errorCount },
9004
9130
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
9005
9131
  );
9006
9132
  if (errorCount >= this.MAX_ERRORS) {
9007
9133
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
9008
- logger19.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9134
+ logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9009
9135
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9010
9136
  if (task) {
9011
9137
  await updateTask(dbClient_default)({
@@ -9026,7 +9152,7 @@ var ExecutionHandler = class {
9026
9152
  }
9027
9153
  }
9028
9154
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
9029
- logger19.error({ maxTransfers, iterations }, errorMessage);
9155
+ logger20.error({ maxTransfers, iterations }, errorMessage);
9030
9156
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
9031
9157
  if (task) {
9032
9158
  await updateTask(dbClient_default)({
@@ -9045,7 +9171,7 @@ var ExecutionHandler = class {
9045
9171
  unregisterStreamHelper(requestId2);
9046
9172
  return { success: false, error: errorMessage, iterations };
9047
9173
  } catch (error) {
9048
- logger19.error({ error }, "Error in execution handler");
9174
+ logger20.error({ error }, "Error in execution handler");
9049
9175
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
9050
9176
  await sseHelper.writeOperation(
9051
9177
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -9072,7 +9198,7 @@ var ExecutionHandler = class {
9072
9198
 
9073
9199
  // src/routes/chat.ts
9074
9200
  var app2 = new OpenAPIHono();
9075
- var logger20 = getLogger("completionsHandler");
9201
+ var logger21 = getLogger("completionsHandler");
9076
9202
  var chatCompletionsRoute = createRoute({
9077
9203
  method: "post",
9078
9204
  path: "/completions",
@@ -9190,7 +9316,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9190
9316
  tracestate: c.req.header("tracestate"),
9191
9317
  baggage: c.req.header("baggage")
9192
9318
  };
9193
- logger20.info(
9319
+ logger21.info(
9194
9320
  {
9195
9321
  otelHeaders,
9196
9322
  path: c.req.path,
@@ -9283,7 +9409,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9283
9409
  dbClient: dbClient_default,
9284
9410
  credentialStores
9285
9411
  });
9286
- logger20.info(
9412
+ logger21.info(
9287
9413
  {
9288
9414
  tenantId,
9289
9415
  projectId,
@@ -9331,7 +9457,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9331
9457
  try {
9332
9458
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
9333
9459
  await sseHelper.writeRole();
9334
- logger20.info({ agentId }, "Starting execution");
9460
+ logger21.info({ agentId }, "Starting execution");
9335
9461
  const executionHandler = new ExecutionHandler();
9336
9462
  const result = await executionHandler.execute({
9337
9463
  executionContext,
@@ -9341,7 +9467,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9341
9467
  requestId: requestId2,
9342
9468
  sseHelper
9343
9469
  });
9344
- logger20.info(
9470
+ logger21.info(
9345
9471
  { result },
9346
9472
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
9347
9473
  );
@@ -9355,7 +9481,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9355
9481
  }
9356
9482
  await sseHelper.complete();
9357
9483
  } catch (error) {
9358
- logger20.error(
9484
+ logger21.error(
9359
9485
  {
9360
9486
  error: error instanceof Error ? error.message : error,
9361
9487
  stack: error instanceof Error ? error.stack : void 0
@@ -9372,12 +9498,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9372
9498
  );
9373
9499
  await sseHelper.complete();
9374
9500
  } catch (streamError) {
9375
- logger20.error({ streamError }, "Failed to write error to stream");
9501
+ logger21.error({ streamError }, "Failed to write error to stream");
9376
9502
  }
9377
9503
  }
9378
9504
  });
9379
9505
  } catch (error) {
9380
- logger20.error(
9506
+ logger21.error(
9381
9507
  {
9382
9508
  error: error instanceof Error ? error.message : error,
9383
9509
  stack: error instanceof Error ? error.stack : void 0
@@ -9401,7 +9527,7 @@ var getMessageText = (content) => {
9401
9527
  };
9402
9528
  var chat_default = app2;
9403
9529
  var app3 = new OpenAPIHono();
9404
- var logger21 = getLogger("chatDataStream");
9530
+ var logger22 = getLogger("chatDataStream");
9405
9531
  var chatDataStreamRoute = createRoute({
9406
9532
  method: "post",
9407
9533
  path: "/chat",
@@ -9518,7 +9644,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9518
9644
  });
9519
9645
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
9520
9646
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
9521
- logger21.info({ userText, lastUserMessage }, "userText");
9647
+ logger22.info({ userText, lastUserMessage }, "userText");
9522
9648
  const messageSpan = trace.getActiveSpan();
9523
9649
  if (messageSpan) {
9524
9650
  messageSpan.setAttributes({
@@ -9560,7 +9686,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9560
9686
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
9561
9687
  }
9562
9688
  } catch (err) {
9563
- logger21.error({ err }, "Streaming error");
9689
+ logger22.error({ err }, "Streaming error");
9564
9690
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
9565
9691
  } finally {
9566
9692
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -9581,7 +9707,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9581
9707
  )
9582
9708
  );
9583
9709
  } catch (error) {
9584
- logger21.error({ error }, "chatDataStream error");
9710
+ logger22.error({ error }, "chatDataStream error");
9585
9711
  throw createApiError({
9586
9712
  code: "internal_server_error",
9587
9713
  message: "Failed to process chat completion"
@@ -9592,7 +9718,7 @@ var chatDataStream_default = app3;
9592
9718
  function createMCPSchema(schema) {
9593
9719
  return schema;
9594
9720
  }
9595
- var logger22 = getLogger("mcp");
9721
+ var logger23 = getLogger("mcp");
9596
9722
  var _MockResponseSingleton = class _MockResponseSingleton {
9597
9723
  constructor() {
9598
9724
  __publicField(this, "mockRes");
@@ -9647,21 +9773,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
9647
9773
  id: 0
9648
9774
  });
9649
9775
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
9650
- logger22.info({ sessionId }, "Spoofing initialization message to set transport state");
9776
+ logger23.info({ sessionId }, "Spoofing initialization message to set transport state");
9651
9777
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
9652
9778
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
9653
9779
  try {
9654
9780
  await transport.handleRequest(req, mockRes, spoofInitMessage);
9655
- logger22.info({ sessionId }, "Successfully spoofed initialization");
9781
+ logger23.info({ sessionId }, "Successfully spoofed initialization");
9656
9782
  } catch (spoofError) {
9657
- logger22.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
9783
+ logger23.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
9658
9784
  }
9659
9785
  };
9660
9786
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9661
9787
  const sessionId = req.headers["mcp-session-id"];
9662
- logger22.info({ sessionId }, "Received MCP session ID");
9788
+ logger23.info({ sessionId }, "Received MCP session ID");
9663
9789
  if (!sessionId) {
9664
- logger22.info({ body }, "Missing session ID");
9790
+ logger23.info({ body }, "Missing session ID");
9665
9791
  res.writeHead(400).end(
9666
9792
  JSON.stringify({
9667
9793
  jsonrpc: "2.0",
@@ -9687,7 +9813,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9687
9813
  scopes: { tenantId, projectId },
9688
9814
  conversationId: sessionId
9689
9815
  });
9690
- logger22.info(
9816
+ logger23.info(
9691
9817
  {
9692
9818
  sessionId,
9693
9819
  conversationFound: !!conversation,
@@ -9698,7 +9824,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9698
9824
  "Conversation lookup result"
9699
9825
  );
9700
9826
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
9701
- logger22.info(
9827
+ logger23.info(
9702
9828
  { sessionId, conversationId: conversation?.id },
9703
9829
  "MCP session not found or invalid"
9704
9830
  );
@@ -9759,7 +9885,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
9759
9885
  requestId: requestId2,
9760
9886
  sseHelper: mcpStreamHelper
9761
9887
  });
9762
- logger22.info(
9888
+ logger23.info(
9763
9889
  { result },
9764
9890
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
9765
9891
  );
@@ -9843,7 +9969,7 @@ var getServer = async (requestContext, executionContext, conversationId, credent
9843
9969
  dbClient: dbClient_default,
9844
9970
  credentialStores
9845
9971
  });
9846
- logger22.info(
9972
+ logger23.info(
9847
9973
  {
9848
9974
  tenantId,
9849
9975
  projectId,
@@ -9905,7 +10031,7 @@ var validateRequestParameters = (c) => {
9905
10031
  };
9906
10032
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
9907
10033
  const { tenantId, projectId, graphId } = executionContext;
9908
- logger22.info({ body }, "Received initialization request");
10034
+ logger23.info({ body }, "Received initialization request");
9909
10035
  const sessionId = nanoid();
9910
10036
  const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
9911
10037
  scopes: { tenantId, projectId, graphId }
@@ -9945,7 +10071,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
9945
10071
  }
9946
10072
  }
9947
10073
  });
9948
- logger22.info(
10074
+ logger23.info(
9949
10075
  { sessionId, conversationId: conversation.id },
9950
10076
  "Created MCP session as conversation"
9951
10077
  );
@@ -9954,9 +10080,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
9954
10080
  });
9955
10081
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
9956
10082
  await server.connect(transport);
9957
- logger22.info({ sessionId }, "Server connected for initialization");
10083
+ logger23.info({ sessionId }, "Server connected for initialization");
9958
10084
  res.setHeader("Mcp-Session-Id", sessionId);
9959
- logger22.info(
10085
+ logger23.info(
9960
10086
  {
9961
10087
  sessionId,
9962
10088
  bodyMethod: body?.method,
@@ -9965,7 +10091,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
9965
10091
  "About to handle initialization request"
9966
10092
  );
9967
10093
  await transport.handleRequest(req, res, body);
9968
- logger22.info({ sessionId }, "Successfully handled initialization request");
10094
+ logger23.info({ sessionId }, "Successfully handled initialization request");
9969
10095
  return toFetchResponse(res);
9970
10096
  };
9971
10097
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -9993,8 +10119,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
9993
10119
  sessionId,
9994
10120
  conversation.metadata?.session_data?.mcpProtocolVersion
9995
10121
  );
9996
- logger22.info({ sessionId }, "Server connected and transport initialized");
9997
- logger22.info(
10122
+ logger23.info({ sessionId }, "Server connected and transport initialized");
10123
+ logger23.info(
9998
10124
  {
9999
10125
  sessionId,
10000
10126
  bodyKeys: Object.keys(body || {}),
@@ -10008,9 +10134,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
10008
10134
  );
10009
10135
  try {
10010
10136
  await transport.handleRequest(req, res, body);
10011
- logger22.info({ sessionId }, "Successfully handled MCP request");
10137
+ logger23.info({ sessionId }, "Successfully handled MCP request");
10012
10138
  } catch (transportError) {
10013
- logger22.error(
10139
+ logger23.error(
10014
10140
  {
10015
10141
  sessionId,
10016
10142
  error: transportError,
@@ -10061,13 +10187,13 @@ app4.openapi(
10061
10187
  }
10062
10188
  const { executionContext } = paramValidation;
10063
10189
  const body = c.get("requestBody") || {};
10064
- logger22.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10190
+ logger23.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10065
10191
  const isInitRequest = body.method === "initialize";
10066
10192
  const { req, res } = toReqRes(c.req.raw);
10067
10193
  const validatedContext = c.get("validatedContext") || {};
10068
10194
  const credentialStores = c.get("credentialStores");
10069
- logger22.info({ validatedContext }, "Validated context");
10070
- logger22.info({ req }, "request");
10195
+ logger23.info({ validatedContext }, "Validated context");
10196
+ logger23.info({ req }, "request");
10071
10197
  if (isInitRequest) {
10072
10198
  return await handleInitializationRequest(
10073
10199
  body,
@@ -10089,7 +10215,7 @@ app4.openapi(
10089
10215
  );
10090
10216
  }
10091
10217
  } catch (e) {
10092
- logger22.error(
10218
+ logger23.error(
10093
10219
  {
10094
10220
  error: e instanceof Error ? e.message : e,
10095
10221
  stack: e instanceof Error ? e.stack : void 0
@@ -10101,7 +10227,7 @@ app4.openapi(
10101
10227
  }
10102
10228
  );
10103
10229
  app4.get("/", async (c) => {
10104
- logger22.info({}, "Received GET MCP request");
10230
+ logger23.info({}, "Received GET MCP request");
10105
10231
  return c.json(
10106
10232
  {
10107
10233
  jsonrpc: "2.0",
@@ -10115,7 +10241,7 @@ app4.get("/", async (c) => {
10115
10241
  );
10116
10242
  });
10117
10243
  app4.delete("/", async (c) => {
10118
- logger22.info({}, "Received DELETE MCP request");
10244
+ logger23.info({}, "Received DELETE MCP request");
10119
10245
  return c.json(
10120
10246
  {
10121
10247
  jsonrpc: "2.0",
@@ -10128,7 +10254,7 @@ app4.delete("/", async (c) => {
10128
10254
  var mcp_default = app4;
10129
10255
 
10130
10256
  // src/app.ts
10131
- var logger23 = getLogger("agents-run-api");
10257
+ var logger24 = getLogger("agents-run-api");
10132
10258
  function createExecutionHono(serverConfig, credentialStores) {
10133
10259
  const app6 = new OpenAPIHono();
10134
10260
  app6.use("*", otel());
@@ -10144,7 +10270,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10144
10270
  const body = await c.req.json();
10145
10271
  c.set("requestBody", body);
10146
10272
  } catch (error) {
10147
- logger23.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
10273
+ logger24.debug({ error }, "Failed to parse JSON body, continuing without parsed body");
10148
10274
  }
10149
10275
  }
10150
10276
  return next();
@@ -10195,8 +10321,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10195
10321
  if (!isExpectedError) {
10196
10322
  const errorMessage = err instanceof Error ? err.message : String(err);
10197
10323
  const errorStack = err instanceof Error ? err.stack : void 0;
10198
- if (logger23) {
10199
- logger23.error(
10324
+ if (logger24) {
10325
+ logger24.error(
10200
10326
  {
10201
10327
  error: err,
10202
10328
  message: errorMessage,
@@ -10208,8 +10334,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10208
10334
  );
10209
10335
  }
10210
10336
  } else {
10211
- if (logger23) {
10212
- logger23.error(
10337
+ if (logger24) {
10338
+ logger24.error(
10213
10339
  {
10214
10340
  error: err,
10215
10341
  path: c.req.path,
@@ -10226,8 +10352,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10226
10352
  const response = err.getResponse();
10227
10353
  return response;
10228
10354
  } catch (responseError) {
10229
- if (logger23) {
10230
- logger23.error({ error: responseError }, "Error while handling HTTPException response");
10355
+ if (logger24) {
10356
+ logger24.error({ error: responseError }, "Error while handling HTTPException response");
10231
10357
  }
10232
10358
  }
10233
10359
  }
@@ -10261,7 +10387,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10261
10387
  app6.use("*", async (c, next) => {
10262
10388
  const executionContext = c.get("executionContext");
10263
10389
  if (!executionContext) {
10264
- logger23.debug({}, "Empty execution context");
10390
+ logger24.debug({}, "Empty execution context");
10265
10391
  return next();
10266
10392
  }
10267
10393
  const { tenantId, projectId, graphId } = executionContext;
@@ -10270,7 +10396,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10270
10396
  if (requestBody) {
10271
10397
  conversationId = requestBody.conversationId;
10272
10398
  if (!conversationId) {
10273
- logger23.debug({ requestBody }, "No conversation ID found in request body");
10399
+ logger24.debug({ requestBody }, "No conversation ID found in request body");
10274
10400
  }
10275
10401
  }
10276
10402
  const entries = Object.fromEntries(
@@ -10285,7 +10411,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10285
10411
  })
10286
10412
  );
10287
10413
  if (!Object.keys(entries).length) {
10288
- logger23.debug({}, "Empty entries for baggage");
10414
+ logger24.debug({}, "Empty entries for baggage");
10289
10415
  return next();
10290
10416
  }
10291
10417
  const bag = Object.entries(entries).reduce(