@inkeep/agents-run-api 0.11.2 → 0.12.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.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,82 +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
- "prompt.length": prompt.length
2933
- }
2934
- },
2935
- async (generationSpan) => {
2936
- const maxRetries = 3;
2937
- let lastError = null;
2938
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
2909
+ if (artifactData.agentId && artifactData.tenantId && artifactData.projectId) {
2939
2910
  try {
2940
- const result2 = await generateObject({
2941
- model,
2942
- prompt,
2943
- schema,
2944
- experimental_telemetry: {
2945
- isEnabled: true,
2946
- functionId: `artifact_processing_${artifactData.artifactId}`,
2947
- recordInputs: true,
2948
- recordOutputs: true,
2949
- metadata: {
2950
- operation: "artifact_name_description_generation",
2951
- sessionId: this.sessionId,
2952
- attempt
2953
- }
2954
- }
2955
- });
2956
- generationSpan.setAttributes({
2957
- "generation.name_length": result2.object.name.length,
2958
- "generation.description_length": result2.object.description.length,
2959
- "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
2960
2918
  });
2961
- generationSpan.setStatus({ code: SpanStatusCode.OK });
2962
- 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
+ }
2963
2931
  } catch (error) {
2964
- lastError = error instanceof Error ? error : new Error(String(error));
2965
2932
  logger8.warn(
2966
2933
  {
2967
2934
  sessionId: this.sessionId,
2968
2935
  artifactId: artifactData.artifactId,
2969
- attempt,
2970
- maxRetries,
2971
- error: lastError.message
2936
+ agentId: artifactData.agentId,
2937
+ error: error instanceof Error ? error.message : "Unknown error"
2972
2938
  },
2973
- `Artifact name/description generation failed, attempt ${attempt}/${maxRetries}`
2939
+ "Failed to get agent model configuration"
2974
2940
  );
2975
- if (attempt < maxRetries) {
2976
- const backoffMs = Math.min(1e3 * 2 ** (attempt - 1), 1e4);
2977
- await new Promise((resolve) => setTimeout(resolve, backoffMs));
2978
- }
2979
2941
  }
2980
2942
  }
2981
- setSpanWithError(generationSpan, lastError);
2982
- throw new Error(
2983
- `Artifact name/description generation failed after ${maxRetries} attempts: ${lastError?.message}`
2984
- );
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;
2985
2955
  }
2986
- );
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
+ }
2987
3042
  const artifactService = new ArtifactService({
2988
3043
  tenantId: artifactData.tenantId,
2989
3044
  projectId: artifactData.projectId,
@@ -3239,8 +3294,10 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3239
3294
  __publicField(this, "lastStreamedComponents", /* @__PURE__ */ new Map());
3240
3295
  __publicField(this, "componentSnapshots", /* @__PURE__ */ new Map());
3241
3296
  __publicField(this, "artifactMap");
3297
+ __publicField(this, "agentId");
3242
3298
  this.streamHelper = streamHelper;
3243
3299
  this.contextId = contextId;
3300
+ this.agentId = artifactParserOptions?.agentId;
3244
3301
  if (artifactParserOptions?.streamRequestId) {
3245
3302
  const sessionParser = graphSessionManager.getArtifactParser(
3246
3303
  artifactParserOptions.streamRequestId
@@ -3369,7 +3426,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3369
3426
  async streamComponent(component) {
3370
3427
  const parts = await this.artifactParser.parseObject({
3371
3428
  dataComponents: [component]
3372
- });
3429
+ }, this.artifactMap, this.agentId);
3373
3430
  if (!Array.isArray(parts)) {
3374
3431
  console.warn("parseObject returned non-array:", parts);
3375
3432
  return;
@@ -3441,7 +3498,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3441
3498
  if (!hasBeenStreamed && this.isComponentComplete(component) && component.name !== "Text") {
3442
3499
  const parts = await this.artifactParser.parseObject({
3443
3500
  dataComponents: [component]
3444
- });
3501
+ }, this.artifactMap, this.agentId);
3445
3502
  for (const part of parts) {
3446
3503
  await this.streamPart(part);
3447
3504
  }
@@ -3494,7 +3551,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3494
3551
  const safeEnd = this.artifactParser.findSafeTextBoundary(workingBuffer);
3495
3552
  if (safeEnd > 0) {
3496
3553
  const safeText = workingBuffer.slice(0, safeEnd);
3497
- const parts2 = await this.artifactParser.parseText(safeText, this.artifactMap);
3554
+ const parts2 = await this.artifactParser.parseText(safeText, this.artifactMap, this.agentId);
3498
3555
  completeParts.push(...parts2);
3499
3556
  return {
3500
3557
  completeParts,
@@ -3506,7 +3563,7 @@ var _IncrementalStreamParser = class _IncrementalStreamParser {
3506
3563
  remainingBuffer: workingBuffer
3507
3564
  };
3508
3565
  }
3509
- const parts = await this.artifactParser.parseText(workingBuffer, this.artifactMap);
3566
+ const parts = await this.artifactParser.parseText(workingBuffer, this.artifactMap, this.agentId);
3510
3567
  if (parts.length > 0 && parts[parts.length - 1].kind === "text") {
3511
3568
  const lastPart = parts[parts.length - 1];
3512
3569
  const lastText = lastPart.text || "";
@@ -3582,6 +3639,8 @@ var logger10 = getLogger("ResponseFormatter");
3582
3639
  var ResponseFormatter = class {
3583
3640
  constructor(tenantId, artifactParserOptions) {
3584
3641
  __publicField(this, "artifactParser");
3642
+ __publicField(this, "agentId");
3643
+ this.agentId = artifactParserOptions?.agentId;
3585
3644
  if (artifactParserOptions?.streamRequestId) {
3586
3645
  const sessionParser = graphSessionManager.getArtifactParser(artifactParserOptions.streamRequestId);
3587
3646
  if (sessionParser) {
@@ -3602,7 +3661,7 @@ var ResponseFormatter = class {
3602
3661
  "response.type": "object",
3603
3662
  "response.availableArtifacts": artifactMap.size
3604
3663
  });
3605
- const parts = await this.artifactParser.parseObject(responseObject, artifactMap);
3664
+ const parts = await this.artifactParser.parseObject(responseObject, artifactMap, this.agentId);
3606
3665
  const uniqueArtifacts = this.countUniqueArtifacts(parts);
3607
3666
  span.setAttributes({
3608
3667
  "response.dataPartsCount": parts.length,
@@ -3631,8 +3690,9 @@ var ResponseFormatter = class {
3631
3690
  async formatResponse(responseText, contextId) {
3632
3691
  return tracer.startActiveSpan("response.format_response", async (span) => {
3633
3692
  try {
3693
+ const hasMarkers = this.artifactParser.hasArtifactMarkers(responseText);
3634
3694
  span.setAttributes({
3635
- "response.hasArtifactMarkers": this.artifactParser.hasArtifactMarkers(responseText),
3695
+ "response.hasArtifactMarkers": hasMarkers,
3636
3696
  "response.contextId": contextId,
3637
3697
  "response.textLength": responseText.length
3638
3698
  });
@@ -3647,7 +3707,7 @@ var ResponseFormatter = class {
3647
3707
  "response.type": "text",
3648
3708
  "response.availableArtifacts": artifactMap.size
3649
3709
  });
3650
- const parts = await this.artifactParser.parseText(responseText, artifactMap);
3710
+ const parts = await this.artifactParser.parseText(responseText, artifactMap, this.agentId);
3651
3711
  if (parts.length === 1 && parts[0].kind === "text") {
3652
3712
  return { text: parts[0].text };
3653
3713
  }
@@ -5100,6 +5160,14 @@ CITATION PLACEMENT RULES:
5100
5160
 
5101
5161
  \u{1F3AF} **KEY PRINCIPLE**: Information from tools \u2192 Complete thought \u2192 Punctuation \u2192 Citation \u2192 Continue
5102
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
+
5103
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.`;
5104
5172
 
5105
5173
  // templates/v1/phase1/system-prompt.xml?raw
@@ -5138,6 +5206,20 @@ var system_prompt_default = `<system_message>
5138
5206
  - Save important tool results as artifacts when they contain structured data that should be preserved and referenced
5139
5207
  - Ask for clarification when requests are ambiguous
5140
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
+
5141
5223
  \u{1F6A8} TRANSFER TOOL RULES - CRITICAL:
5142
5224
  - When calling transfer_to_* tools, call the tool IMMEDIATELY without any explanatory text
5143
5225
  - Do NOT explain the transfer, do NOT say "I'll hand this off", do NOT provide reasoning
@@ -5205,6 +5287,7 @@ var thinking_preparation_default = `<thinking_preparation_mode>
5205
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> ";
5206
5288
 
5207
5289
  // src/agents/versions/v1/Phase1Config.ts
5290
+ getLogger("Phase1Config");
5208
5291
  var Phase1Config = class _Phase1Config {
5209
5292
  loadTemplates() {
5210
5293
  const templates = /* @__PURE__ */ new Map();
@@ -5297,13 +5380,18 @@ var Phase1Config = class _Phase1Config {
5297
5380
  if (!hasTransferRelations) {
5298
5381
  return "";
5299
5382
  }
5300
- 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`;
5301
5386
  }
5302
5387
  generateDelegationInstructions(hasDelegateRelations) {
5303
5388
  if (!hasDelegateRelations) {
5304
5389
  return "";
5305
5390
  }
5306
- 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`;
5307
5395
  }
5308
5396
  getArtifactCreationGuidance() {
5309
5397
  return `\u{1F6A8} MANDATORY ARTIFACT CREATION \u{1F6A8}
@@ -5480,10 +5568,16 @@ The implementation details show that you need to register your application first
5480
5568
 
5481
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."
5482
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
+
5483
5578
  IMPORTANT GUIDELINES:
5484
- - You can only reference artifacts that already exist
5485
- - Use artifact:ref annotations in your text
5486
- - 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
5487
5581
  - References are automatically converted to interactive elements`;
5488
5582
  }
5489
5583
  return "";
@@ -5624,7 +5718,43 @@ ${propertiesXml}
5624
5718
  };
5625
5719
 
5626
5720
  // templates/v1/phase2/system-prompt.xml?raw
5627
- 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>`;
5628
5758
 
5629
5759
  // templates/v1/phase2/data-components.xml?raw
5630
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>';
@@ -5733,8 +5863,11 @@ COMMON FAILURE POINTS (AVOID THESE):
5733
5863
  if (!shouldShowReferencingRules) {
5734
5864
  return "";
5735
5865
  }
5866
+ const sharedGuidance = artifact_retrieval_guidance_default;
5736
5867
  if (hasArtifactComponents && artifactComponents && artifactComponents.length > 0) {
5737
- return `ARTIFACT MANAGEMENT FOR STRUCTURED RESPONSES:
5868
+ return `${sharedGuidance}
5869
+
5870
+ ARTIFACT MANAGEMENT FOR STRUCTURED RESPONSES:
5738
5871
 
5739
5872
  You will create and reference artifacts using data components in your JSON response.
5740
5873
 
@@ -5814,12 +5947,14 @@ COMPONENT GUIDELINES:
5814
5947
  - Only add Artifact reference components when citing the SAME artifact again for a different point
5815
5948
  - Use tool_call_id exactly as it appears in tool execution results`;
5816
5949
  }
5817
- return `ARTIFACT REFERENCING FOR STRUCTURED RESPONSES:
5950
+ return `${sharedGuidance}
5951
+
5952
+ ARTIFACT REFERENCING FOR STRUCTURED RESPONSES:
5818
5953
 
5819
5954
  You can reference existing artifacts but cannot create new ones.
5820
5955
 
5821
5956
  HOW TO REFERENCE ARTIFACTS:
5822
- 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.
5823
5958
 
5824
5959
  EXAMPLE STRUCTURED RESPONSE:
5825
5960
  \`\`\`json
@@ -5993,7 +6128,7 @@ function hasToolCallWithPrefix(prefix) {
5993
6128
  return false;
5994
6129
  };
5995
6130
  }
5996
- var logger15 = getLogger("Agent");
6131
+ var logger16 = getLogger("Agent");
5997
6132
  var CONSTANTS = {
5998
6133
  MAX_GENERATION_STEPS: 12,
5999
6134
  PHASE_1_TIMEOUT_MS: 27e4,
@@ -6292,14 +6427,14 @@ var Agent = class {
6292
6427
  for (const toolSet of tools) {
6293
6428
  for (const [toolName, originalTool] of Object.entries(toolSet)) {
6294
6429
  if (!isValidTool(originalTool)) {
6295
- logger15.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6430
+ logger16.error({ toolName }, "Invalid MCP tool structure - missing required properties");
6296
6431
  continue;
6297
6432
  }
6298
6433
  const sessionWrappedTool = tool({
6299
6434
  description: originalTool.description,
6300
6435
  inputSchema: originalTool.inputSchema,
6301
6436
  execute: async (args, { toolCallId }) => {
6302
- logger15.debug({ toolName, toolCallId }, "MCP Tool Called");
6437
+ logger16.debug({ toolName, toolCallId }, "MCP Tool Called");
6303
6438
  try {
6304
6439
  const rawResult = await originalTool.execute(args, { toolCallId });
6305
6440
  const parsedResult = parseEmbeddedJson(rawResult);
@@ -6313,7 +6448,7 @@ var Agent = class {
6313
6448
  });
6314
6449
  return { result: enhancedResult, toolCallId };
6315
6450
  } catch (error) {
6316
- logger15.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6451
+ logger16.error({ toolName, toolCallId, error }, "MCP tool execution failed");
6317
6452
  throw error;
6318
6453
  }
6319
6454
  }
@@ -6407,7 +6542,7 @@ var Agent = class {
6407
6542
  headers: agentToolRelationHeaders
6408
6543
  };
6409
6544
  }
6410
- logger15.info(
6545
+ logger16.info(
6411
6546
  {
6412
6547
  toolName: tool3.name,
6413
6548
  credentialReferenceId,
@@ -6447,7 +6582,7 @@ var Agent = class {
6447
6582
  async getResolvedContext(conversationId, requestContext) {
6448
6583
  try {
6449
6584
  if (!this.config.contextConfigId) {
6450
- 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");
6451
6586
  return null;
6452
6587
  }
6453
6588
  const contextConfig = await getContextConfigById(dbClient_default)({
@@ -6455,7 +6590,7 @@ var Agent = class {
6455
6590
  id: this.config.contextConfigId
6456
6591
  });
6457
6592
  if (!contextConfig) {
6458
- logger15.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
6593
+ logger16.warn({ contextConfigId: this.config.contextConfigId }, "Context config not found");
6459
6594
  return null;
6460
6595
  }
6461
6596
  if (!this.contextResolver) {
@@ -6472,7 +6607,7 @@ var Agent = class {
6472
6607
  $now: (/* @__PURE__ */ new Date()).toISOString(),
6473
6608
  $env: process.env
6474
6609
  };
6475
- logger15.debug(
6610
+ logger16.debug(
6476
6611
  {
6477
6612
  conversationId,
6478
6613
  contextConfigId: contextConfig.id,
@@ -6486,7 +6621,7 @@ var Agent = class {
6486
6621
  );
6487
6622
  return contextWithBuiltins;
6488
6623
  } catch (error) {
6489
- logger15.error(
6624
+ logger16.error(
6490
6625
  {
6491
6626
  conversationId,
6492
6627
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6510,7 +6645,7 @@ var Agent = class {
6510
6645
  });
6511
6646
  return graphDefinition?.graphPrompt || void 0;
6512
6647
  } catch (error) {
6513
- logger15.warn(
6648
+ logger16.warn(
6514
6649
  {
6515
6650
  graphId: this.config.graphId,
6516
6651
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6539,7 +6674,7 @@ var Agent = class {
6539
6674
  (agent) => "artifactComponents" in agent && agent.artifactComponents && agent.artifactComponents.length > 0
6540
6675
  );
6541
6676
  } catch (error) {
6542
- logger15.warn(
6677
+ logger16.warn(
6543
6678
  {
6544
6679
  graphId: this.config.graphId,
6545
6680
  tenantId: this.config.tenantId,
@@ -6568,7 +6703,7 @@ var Agent = class {
6568
6703
  preserveUnresolved: false
6569
6704
  });
6570
6705
  } catch (error) {
6571
- logger15.error(
6706
+ logger16.error(
6572
6707
  {
6573
6708
  conversationId,
6574
6709
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6615,7 +6750,7 @@ var Agent = class {
6615
6750
  preserveUnresolved: false
6616
6751
  });
6617
6752
  } catch (error) {
6618
- logger15.error(
6753
+ logger16.error(
6619
6754
  {
6620
6755
  conversationId,
6621
6756
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6654,7 +6789,7 @@ var Agent = class {
6654
6789
  preserveUnresolved: false
6655
6790
  });
6656
6791
  } catch (error) {
6657
- logger15.error(
6792
+ logger16.error(
6658
6793
  {
6659
6794
  conversationId,
6660
6795
  error: error instanceof Error ? error.message : "Unknown error"
@@ -6686,7 +6821,7 @@ var Agent = class {
6686
6821
  artifactId: z.string().describe("The unique identifier of the artifact to get.")
6687
6822
  }),
6688
6823
  execute: async ({ artifactId }) => {
6689
- logger15.info({ artifactId }, "get_artifact executed");
6824
+ logger16.info({ artifactId }, "get_artifact executed");
6690
6825
  const artifact = await getLedgerArtifacts(dbClient_default)({
6691
6826
  scopes: {
6692
6827
  tenantId: this.config.tenantId,
@@ -6936,7 +7071,7 @@ var Agent = class {
6936
7071
  };
6937
7072
  return enhanced;
6938
7073
  } catch (error) {
6939
- logger15.warn({ error }, "Failed to enhance tool result with structure hints");
7074
+ logger16.warn({ error }, "Failed to enhance tool result with structure hints");
6940
7075
  return result;
6941
7076
  }
6942
7077
  }
@@ -6951,7 +7086,7 @@ var Agent = class {
6951
7086
  }
6952
7087
  });
6953
7088
  } catch (error) {
6954
- logger15.error(
7089
+ logger16.error(
6955
7090
  { error, graphId: this.config.graphId },
6956
7091
  "Failed to check graph artifact components"
6957
7092
  );
@@ -7051,7 +7186,7 @@ var Agent = class {
7051
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;
7052
7187
  const timeoutMs = Math.min(configuredTimeout, MAX_ALLOWED_TIMEOUT_MS);
7053
7188
  if (modelSettings.maxDuration && modelSettings.maxDuration * 1e3 > MAX_ALLOWED_TIMEOUT_MS) {
7054
- logger15.warn(
7189
+ logger16.warn(
7055
7190
  {
7056
7191
  requestedTimeout: modelSettings.maxDuration * 1e3,
7057
7192
  appliedTimeout: timeoutMs,
@@ -7093,7 +7228,7 @@ var Agent = class {
7093
7228
  }
7094
7229
  );
7095
7230
  } catch (error) {
7096
- logger15.debug({ error }, "Failed to track agent reasoning");
7231
+ logger16.debug({ error }, "Failed to track agent reasoning");
7097
7232
  }
7098
7233
  }
7099
7234
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7190,7 +7325,7 @@ var Agent = class {
7190
7325
  }
7191
7326
  );
7192
7327
  } catch (error) {
7193
- logger15.debug({ error }, "Failed to track agent reasoning");
7328
+ logger16.debug({ error }, "Failed to track agent reasoning");
7194
7329
  }
7195
7330
  }
7196
7331
  if (last && "toolCalls" in last && last.toolCalls) {
@@ -7481,7 +7616,7 @@ ${output}${structureHintsFormatted}`;
7481
7616
  };
7482
7617
 
7483
7618
  // src/agents/generateTaskHandler.ts
7484
- var logger16 = getLogger("generateTaskHandler");
7619
+ var logger17 = getLogger("generateTaskHandler");
7485
7620
  var createTaskHandler = (config, credentialStoreRegistry) => {
7486
7621
  return async (task) => {
7487
7622
  try {
@@ -7534,7 +7669,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7534
7669
  }
7535
7670
  })
7536
7671
  ]);
7537
- logger16.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
7672
+ logger17.info({ toolsForAgent, internalRelations, externalRelations }, "agent stuff");
7538
7673
  const enhancedInternalRelations = await Promise.all(
7539
7674
  internalRelations.map(async (relation) => {
7540
7675
  try {
@@ -7563,7 +7698,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7563
7698
  return { ...relation, description: enhancedDescription };
7564
7699
  }
7565
7700
  } catch (error) {
7566
- logger16.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
7701
+ logger17.warn({ agentId: relation.id, error }, "Failed to enhance agent description");
7567
7702
  }
7568
7703
  return relation;
7569
7704
  })
@@ -7663,7 +7798,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7663
7798
  const taskIdMatch = task.id.match(/^task_([^-]+-[^-]+-\d+)-/);
7664
7799
  if (taskIdMatch) {
7665
7800
  contextId = taskIdMatch[1];
7666
- logger16.info(
7801
+ logger17.info(
7667
7802
  {
7668
7803
  taskId: task.id,
7669
7804
  extractedContextId: contextId,
@@ -7679,7 +7814,7 @@ var createTaskHandler = (config, credentialStoreRegistry) => {
7679
7814
  const isDelegation = task.context?.metadata?.isDelegation === true;
7680
7815
  agent.setDelegationStatus(isDelegation);
7681
7816
  if (isDelegation) {
7682
- logger16.info(
7817
+ logger17.info(
7683
7818
  { agentId: config.agentId, taskId: task.id },
7684
7819
  "Delegated agent - streaming disabled"
7685
7820
  );
@@ -7901,7 +8036,7 @@ async function getRegisteredGraph(executionContext) {
7901
8036
 
7902
8037
  // src/routes/agents.ts
7903
8038
  var app = new OpenAPIHono();
7904
- var logger17 = getLogger("agents");
8039
+ var logger18 = getLogger("agents");
7905
8040
  app.openapi(
7906
8041
  createRoute({
7907
8042
  method: "get",
@@ -7939,7 +8074,7 @@ app.openapi(
7939
8074
  tracestate: c.req.header("tracestate"),
7940
8075
  baggage: c.req.header("baggage")
7941
8076
  };
7942
- logger17.info(
8077
+ logger18.info(
7943
8078
  {
7944
8079
  otelHeaders,
7945
8080
  path: c.req.path,
@@ -7951,7 +8086,7 @@ app.openapi(
7951
8086
  const { tenantId, projectId, graphId, agentId } = executionContext;
7952
8087
  console.dir("executionContext", executionContext);
7953
8088
  if (agentId) {
7954
- logger17.info(
8089
+ logger18.info(
7955
8090
  {
7956
8091
  message: "getRegisteredAgent (agent-level)",
7957
8092
  tenantId,
@@ -7963,7 +8098,7 @@ app.openapi(
7963
8098
  );
7964
8099
  const credentialStores = c.get("credentialStores");
7965
8100
  const agent = await getRegisteredAgent(executionContext, credentialStores);
7966
- logger17.info({ agent }, "agent registered: well-known agent.json");
8101
+ logger18.info({ agent }, "agent registered: well-known agent.json");
7967
8102
  if (!agent) {
7968
8103
  throw createApiError({
7969
8104
  code: "not_found",
@@ -7972,7 +8107,7 @@ app.openapi(
7972
8107
  }
7973
8108
  return c.json(agent.agentCard);
7974
8109
  } else {
7975
- logger17.info(
8110
+ logger18.info(
7976
8111
  {
7977
8112
  message: "getRegisteredGraph (graph-level)",
7978
8113
  tenantId,
@@ -7998,7 +8133,7 @@ app.post("/a2a", async (c) => {
7998
8133
  tracestate: c.req.header("tracestate"),
7999
8134
  baggage: c.req.header("baggage")
8000
8135
  };
8001
- logger17.info(
8136
+ logger18.info(
8002
8137
  {
8003
8138
  otelHeaders,
8004
8139
  path: c.req.path,
@@ -8009,7 +8144,7 @@ app.post("/a2a", async (c) => {
8009
8144
  const executionContext = getRequestExecutionContext(c);
8010
8145
  const { tenantId, projectId, graphId, agentId } = executionContext;
8011
8146
  if (agentId) {
8012
- logger17.info(
8147
+ logger18.info(
8013
8148
  {
8014
8149
  message: "a2a (agent-level)",
8015
8150
  tenantId,
@@ -8033,7 +8168,7 @@ app.post("/a2a", async (c) => {
8033
8168
  }
8034
8169
  return a2aHandler(c, agent);
8035
8170
  } else {
8036
- logger17.info(
8171
+ logger18.info(
8037
8172
  {
8038
8173
  message: "a2a (graph-level)",
8039
8174
  tenantId,
@@ -8082,14 +8217,14 @@ app.post("/a2a", async (c) => {
8082
8217
  }
8083
8218
  });
8084
8219
  var agents_default = app;
8085
- var logger18 = getLogger("Transfer");
8220
+ var logger19 = getLogger("Transfer");
8086
8221
  async function executeTransfer({
8087
8222
  tenantId,
8088
8223
  threadId,
8089
8224
  projectId,
8090
8225
  targetAgentId
8091
8226
  }) {
8092
- logger18.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8227
+ logger19.info({ targetAgent: targetAgentId }, "Executing transfer to agent");
8093
8228
  await setActiveAgentForThread(dbClient_default)({
8094
8229
  scopes: { tenantId, projectId },
8095
8230
  threadId,
@@ -8671,7 +8806,7 @@ function createMCPStreamHelper() {
8671
8806
  }
8672
8807
 
8673
8808
  // src/handlers/executionHandler.ts
8674
- var logger19 = getLogger("ExecutionHandler");
8809
+ var logger20 = getLogger("ExecutionHandler");
8675
8810
  var ExecutionHandler = class {
8676
8811
  constructor() {
8677
8812
  // Hardcoded error limit - separate from configurable stopWhen
@@ -8696,7 +8831,7 @@ var ExecutionHandler = class {
8696
8831
  const { tenantId, projectId, graphId, apiKey, baseUrl } = executionContext;
8697
8832
  registerStreamHelper(requestId2, sseHelper);
8698
8833
  graphSessionManager.createSession(requestId2, graphId, tenantId, projectId, conversationId);
8699
- logger19.info(
8834
+ logger20.info(
8700
8835
  { sessionId: requestId2, graphId, conversationId },
8701
8836
  "Created GraphSession for message execution"
8702
8837
  );
@@ -8711,7 +8846,7 @@ var ExecutionHandler = class {
8711
8846
  );
8712
8847
  }
8713
8848
  } catch (error) {
8714
- logger19.error(
8849
+ logger20.error(
8715
8850
  {
8716
8851
  error: error instanceof Error ? error.message : "Unknown error",
8717
8852
  stack: error instanceof Error ? error.stack : void 0
@@ -8727,7 +8862,7 @@ var ExecutionHandler = class {
8727
8862
  try {
8728
8863
  await sseHelper.writeOperation(agentInitializingOp(requestId2, graphId));
8729
8864
  const taskId = `task_${conversationId}-${requestId2}`;
8730
- logger19.info(
8865
+ logger20.info(
8731
8866
  { taskId, currentAgentId, conversationId, requestId: requestId2 },
8732
8867
  "Attempting to create or reuse existing task"
8733
8868
  );
@@ -8751,7 +8886,7 @@ var ExecutionHandler = class {
8751
8886
  agent_id: currentAgentId
8752
8887
  }
8753
8888
  });
8754
- logger19.info(
8889
+ logger20.info(
8755
8890
  {
8756
8891
  taskId,
8757
8892
  createdTaskMetadata: Array.isArray(task) ? task[0]?.metadata : task?.metadata
@@ -8760,27 +8895,27 @@ var ExecutionHandler = class {
8760
8895
  );
8761
8896
  } catch (error) {
8762
8897
  if (error?.message?.includes("UNIQUE constraint failed") || error?.message?.includes("PRIMARY KEY constraint failed") || error?.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
8763
- logger19.info(
8898
+ logger20.info(
8764
8899
  { taskId, error: error.message },
8765
8900
  "Task already exists, fetching existing task"
8766
8901
  );
8767
8902
  const existingTask = await getTask(dbClient_default)({ id: taskId });
8768
8903
  if (existingTask) {
8769
8904
  task = existingTask;
8770
- logger19.info(
8905
+ logger20.info(
8771
8906
  { taskId, existingTask },
8772
8907
  "Successfully reused existing task from race condition"
8773
8908
  );
8774
8909
  } else {
8775
- logger19.error({ taskId, error }, "Task constraint failed but task not found");
8910
+ logger20.error({ taskId, error }, "Task constraint failed but task not found");
8776
8911
  throw error;
8777
8912
  }
8778
8913
  } else {
8779
- 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");
8780
8915
  throw error;
8781
8916
  }
8782
8917
  }
8783
- logger19.debug(
8918
+ logger20.debug(
8784
8919
  {
8785
8920
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8786
8921
  executionType: "create_initial_task",
@@ -8798,7 +8933,7 @@ var ExecutionHandler = class {
8798
8933
  const maxTransfers = graphConfig?.stopWhen?.transferCountIs ?? 10;
8799
8934
  while (iterations < maxTransfers) {
8800
8935
  iterations++;
8801
- logger19.info(
8936
+ logger20.info(
8802
8937
  { iterations, currentAgentId, graphId, conversationId, fromAgentId },
8803
8938
  `Execution loop iteration ${iterations} with agent ${currentAgentId}, transfer from: ${fromAgentId || "none"}`
8804
8939
  );
@@ -8806,10 +8941,10 @@ var ExecutionHandler = class {
8806
8941
  scopes: { tenantId, projectId },
8807
8942
  conversationId
8808
8943
  });
8809
- logger19.info({ activeAgent }, "activeAgent");
8944
+ logger20.info({ activeAgent }, "activeAgent");
8810
8945
  if (activeAgent && activeAgent.activeAgentId !== currentAgentId) {
8811
8946
  currentAgentId = activeAgent.activeAgentId;
8812
- logger19.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
8947
+ logger20.info({ currentAgentId }, `Updated current agent to: ${currentAgentId}`);
8813
8948
  }
8814
8949
  const agentBaseUrl = `${baseUrl}/agents`;
8815
8950
  const a2aClient = new A2AClient(agentBaseUrl, {
@@ -8850,13 +8985,13 @@ var ExecutionHandler = class {
8850
8985
  });
8851
8986
  if (!messageResponse?.result) {
8852
8987
  errorCount++;
8853
- logger19.error(
8988
+ logger20.error(
8854
8989
  { currentAgentId, iterations, errorCount },
8855
8990
  `No response from agent ${currentAgentId} on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
8856
8991
  );
8857
8992
  if (errorCount >= this.MAX_ERRORS) {
8858
8993
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
8859
- logger19.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
8994
+ logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
8860
8995
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
8861
8996
  if (task) {
8862
8997
  await updateTask(dbClient_default)({
@@ -8881,7 +9016,7 @@ var ExecutionHandler = class {
8881
9016
  const transferResponse = messageResponse.result;
8882
9017
  const targetAgentId = transferResponse.artifacts?.[0]?.parts?.[0]?.data?.targetAgentId;
8883
9018
  const transferReason = transferResponse.artifacts?.[0]?.parts?.[1]?.text;
8884
- logger19.info({ targetAgentId, transferReason }, "transfer response");
9019
+ logger20.info({ targetAgentId, transferReason }, "transfer response");
8885
9020
  currentMessage = `<transfer_context> ${transferReason} </transfer_context>`;
8886
9021
  const { success, targetAgentId: newAgentId } = await executeTransfer({
8887
9022
  projectId,
@@ -8892,7 +9027,7 @@ var ExecutionHandler = class {
8892
9027
  if (success) {
8893
9028
  fromAgentId = currentAgentId;
8894
9029
  currentAgentId = newAgentId;
8895
- logger19.info(
9030
+ logger20.info(
8896
9031
  {
8897
9032
  transferFrom: fromAgentId,
8898
9033
  transferTo: currentAgentId,
@@ -8910,7 +9045,7 @@ var ExecutionHandler = class {
8910
9045
  const graphSessionData = graphSessionManager.getSession(requestId2);
8911
9046
  if (graphSessionData) {
8912
9047
  const sessionSummary = graphSessionData.getSummary();
8913
- logger19.info(sessionSummary, "GraphSession data after completion");
9048
+ logger20.info(sessionSummary, "GraphSession data after completion");
8914
9049
  }
8915
9050
  let textContent = "";
8916
9051
  for (const part of responseParts) {
@@ -8964,22 +9099,22 @@ var ExecutionHandler = class {
8964
9099
  }
8965
9100
  });
8966
9101
  const updateTaskEnd = Date.now();
8967
- logger19.info(
9102
+ logger20.info(
8968
9103
  { duration: updateTaskEnd - updateTaskStart },
8969
9104
  "Completed updateTask operation"
8970
9105
  );
8971
9106
  await sseHelper.writeOperation(completionOp(currentAgentId, iterations));
8972
9107
  await sseHelper.complete();
8973
- logger19.info({}, "Ending GraphSession and cleaning up");
9108
+ logger20.info({}, "Ending GraphSession and cleaning up");
8974
9109
  graphSessionManager.endSession(requestId2);
8975
- logger19.info({}, "Cleaning up streamHelper");
9110
+ logger20.info({}, "Cleaning up streamHelper");
8976
9111
  unregisterStreamHelper(requestId2);
8977
9112
  let response;
8978
9113
  if (sseHelper instanceof MCPStreamHelper) {
8979
9114
  const captured = sseHelper.getCapturedResponse();
8980
9115
  response = captured.text || "No response content";
8981
9116
  }
8982
- logger19.info({}, "ExecutionHandler returning success");
9117
+ logger20.info({}, "ExecutionHandler returning success");
8983
9118
  return { success: true, iterations, response };
8984
9119
  } catch (error) {
8985
9120
  setSpanWithError(span, error);
@@ -8990,13 +9125,13 @@ var ExecutionHandler = class {
8990
9125
  });
8991
9126
  }
8992
9127
  errorCount++;
8993
- logger19.warn(
9128
+ logger20.warn(
8994
9129
  { iterations, errorCount },
8995
9130
  `No valid response or transfer on iteration ${iterations} (error ${errorCount}/${this.MAX_ERRORS})`
8996
9131
  );
8997
9132
  if (errorCount >= this.MAX_ERRORS) {
8998
9133
  const errorMessage2 = `Maximum error limit (${this.MAX_ERRORS}) reached`;
8999
- logger19.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9134
+ logger20.error({ maxErrors: this.MAX_ERRORS, errorCount }, errorMessage2);
9000
9135
  await sseHelper.writeOperation(errorOp(errorMessage2, currentAgentId || "system"));
9001
9136
  if (task) {
9002
9137
  await updateTask(dbClient_default)({
@@ -9017,7 +9152,7 @@ var ExecutionHandler = class {
9017
9152
  }
9018
9153
  }
9019
9154
  const errorMessage = `Maximum transfer limit (${maxTransfers}) reached without completion`;
9020
- logger19.error({ maxTransfers, iterations }, errorMessage);
9155
+ logger20.error({ maxTransfers, iterations }, errorMessage);
9021
9156
  await sseHelper.writeOperation(errorOp(errorMessage, currentAgentId || "system"));
9022
9157
  if (task) {
9023
9158
  await updateTask(dbClient_default)({
@@ -9036,7 +9171,7 @@ var ExecutionHandler = class {
9036
9171
  unregisterStreamHelper(requestId2);
9037
9172
  return { success: false, error: errorMessage, iterations };
9038
9173
  } catch (error) {
9039
- logger19.error({ error }, "Error in execution handler");
9174
+ logger20.error({ error }, "Error in execution handler");
9040
9175
  const errorMessage = error instanceof Error ? error.message : "Unknown execution error";
9041
9176
  await sseHelper.writeOperation(
9042
9177
  errorOp(`Execution error: ${errorMessage}`, currentAgentId || "system")
@@ -9063,7 +9198,7 @@ var ExecutionHandler = class {
9063
9198
 
9064
9199
  // src/routes/chat.ts
9065
9200
  var app2 = new OpenAPIHono();
9066
- var logger20 = getLogger("completionsHandler");
9201
+ var logger21 = getLogger("completionsHandler");
9067
9202
  var chatCompletionsRoute = createRoute({
9068
9203
  method: "post",
9069
9204
  path: "/completions",
@@ -9181,7 +9316,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9181
9316
  tracestate: c.req.header("tracestate"),
9182
9317
  baggage: c.req.header("baggage")
9183
9318
  };
9184
- logger20.info(
9319
+ logger21.info(
9185
9320
  {
9186
9321
  otelHeaders,
9187
9322
  path: c.req.path,
@@ -9274,7 +9409,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9274
9409
  dbClient: dbClient_default,
9275
9410
  credentialStores
9276
9411
  });
9277
- logger20.info(
9412
+ logger21.info(
9278
9413
  {
9279
9414
  tenantId,
9280
9415
  projectId,
@@ -9322,7 +9457,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9322
9457
  try {
9323
9458
  const sseHelper = createSSEStreamHelper(stream2, requestId2, timestamp);
9324
9459
  await sseHelper.writeRole();
9325
- logger20.info({ agentId }, "Starting execution");
9460
+ logger21.info({ agentId }, "Starting execution");
9326
9461
  const executionHandler = new ExecutionHandler();
9327
9462
  const result = await executionHandler.execute({
9328
9463
  executionContext,
@@ -9332,7 +9467,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9332
9467
  requestId: requestId2,
9333
9468
  sseHelper
9334
9469
  });
9335
- logger20.info(
9470
+ logger21.info(
9336
9471
  { result },
9337
9472
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
9338
9473
  );
@@ -9346,7 +9481,7 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9346
9481
  }
9347
9482
  await sseHelper.complete();
9348
9483
  } catch (error) {
9349
- logger20.error(
9484
+ logger21.error(
9350
9485
  {
9351
9486
  error: error instanceof Error ? error.message : error,
9352
9487
  stack: error instanceof Error ? error.stack : void 0
@@ -9363,12 +9498,12 @@ app2.openapi(chatCompletionsRoute, async (c) => {
9363
9498
  );
9364
9499
  await sseHelper.complete();
9365
9500
  } catch (streamError) {
9366
- logger20.error({ streamError }, "Failed to write error to stream");
9501
+ logger21.error({ streamError }, "Failed to write error to stream");
9367
9502
  }
9368
9503
  }
9369
9504
  });
9370
9505
  } catch (error) {
9371
- logger20.error(
9506
+ logger21.error(
9372
9507
  {
9373
9508
  error: error instanceof Error ? error.message : error,
9374
9509
  stack: error instanceof Error ? error.stack : void 0
@@ -9392,7 +9527,7 @@ var getMessageText = (content) => {
9392
9527
  };
9393
9528
  var chat_default = app2;
9394
9529
  var app3 = new OpenAPIHono();
9395
- var logger21 = getLogger("chatDataStream");
9530
+ var logger22 = getLogger("chatDataStream");
9396
9531
  var chatDataStreamRoute = createRoute({
9397
9532
  method: "post",
9398
9533
  path: "/chat",
@@ -9509,7 +9644,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9509
9644
  });
9510
9645
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
9511
9646
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
9512
- logger21.info({ userText, lastUserMessage }, "userText");
9647
+ logger22.info({ userText, lastUserMessage }, "userText");
9513
9648
  const messageSpan = trace.getActiveSpan();
9514
9649
  if (messageSpan) {
9515
9650
  messageSpan.setAttributes({
@@ -9551,7 +9686,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9551
9686
  await streamHelper.writeOperation(errorOp("Unable to process request", "system"));
9552
9687
  }
9553
9688
  } catch (err) {
9554
- logger21.error({ err }, "Streaming error");
9689
+ logger22.error({ err }, "Streaming error");
9555
9690
  await streamHelper.writeOperation(errorOp("Internal server error", "system"));
9556
9691
  } finally {
9557
9692
  if ("cleanup" in streamHelper && typeof streamHelper.cleanup === "function") {
@@ -9572,7 +9707,7 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9572
9707
  )
9573
9708
  );
9574
9709
  } catch (error) {
9575
- logger21.error({ error }, "chatDataStream error");
9710
+ logger22.error({ error }, "chatDataStream error");
9576
9711
  throw createApiError({
9577
9712
  code: "internal_server_error",
9578
9713
  message: "Failed to process chat completion"
@@ -9583,7 +9718,7 @@ var chatDataStream_default = app3;
9583
9718
  function createMCPSchema(schema) {
9584
9719
  return schema;
9585
9720
  }
9586
- var logger22 = getLogger("mcp");
9721
+ var logger23 = getLogger("mcp");
9587
9722
  var _MockResponseSingleton = class _MockResponseSingleton {
9588
9723
  constructor() {
9589
9724
  __publicField(this, "mockRes");
@@ -9638,21 +9773,21 @@ var createSpoofInitMessage = (mcpProtocolVersion) => ({
9638
9773
  id: 0
9639
9774
  });
9640
9775
  var spoofTransportInitialization = async (transport, req, sessionId, mcpProtocolVersion) => {
9641
- logger22.info({ sessionId }, "Spoofing initialization message to set transport state");
9776
+ logger23.info({ sessionId }, "Spoofing initialization message to set transport state");
9642
9777
  const spoofInitMessage = createSpoofInitMessage(mcpProtocolVersion);
9643
9778
  const mockRes = MockResponseSingleton.getInstance().getMockResponse();
9644
9779
  try {
9645
9780
  await transport.handleRequest(req, mockRes, spoofInitMessage);
9646
- logger22.info({ sessionId }, "Successfully spoofed initialization");
9781
+ logger23.info({ sessionId }, "Successfully spoofed initialization");
9647
9782
  } catch (spoofError) {
9648
- logger22.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
9783
+ logger23.warn({ sessionId, error: spoofError }, "Spoof initialization failed, continuing anyway");
9649
9784
  }
9650
9785
  };
9651
9786
  var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9652
9787
  const sessionId = req.headers["mcp-session-id"];
9653
- logger22.info({ sessionId }, "Received MCP session ID");
9788
+ logger23.info({ sessionId }, "Received MCP session ID");
9654
9789
  if (!sessionId) {
9655
- logger22.info({ body }, "Missing session ID");
9790
+ logger23.info({ body }, "Missing session ID");
9656
9791
  res.writeHead(400).end(
9657
9792
  JSON.stringify({
9658
9793
  jsonrpc: "2.0",
@@ -9678,7 +9813,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9678
9813
  scopes: { tenantId, projectId },
9679
9814
  conversationId: sessionId
9680
9815
  });
9681
- logger22.info(
9816
+ logger23.info(
9682
9817
  {
9683
9818
  sessionId,
9684
9819
  conversationFound: !!conversation,
@@ -9689,7 +9824,7 @@ var validateSession = async (req, res, body, tenantId, projectId, graphId) => {
9689
9824
  "Conversation lookup result"
9690
9825
  );
9691
9826
  if (!conversation || conversation.metadata?.sessionData?.sessionType !== "mcp" || conversation.metadata?.sessionData?.graphId !== graphId) {
9692
- logger22.info(
9827
+ logger23.info(
9693
9828
  { sessionId, conversationId: conversation?.id },
9694
9829
  "MCP session not found or invalid"
9695
9830
  );
@@ -9750,7 +9885,7 @@ var executeAgentQuery = async (executionContext, conversationId, query, defaultA
9750
9885
  requestId: requestId2,
9751
9886
  sseHelper: mcpStreamHelper
9752
9887
  });
9753
- logger22.info(
9888
+ logger23.info(
9754
9889
  { result },
9755
9890
  `Execution completed: ${result.success ? "success" : "failed"} after ${result.iterations} iterations`
9756
9891
  );
@@ -9834,7 +9969,7 @@ var getServer = async (requestContext, executionContext, conversationId, credent
9834
9969
  dbClient: dbClient_default,
9835
9970
  credentialStores
9836
9971
  });
9837
- logger22.info(
9972
+ logger23.info(
9838
9973
  {
9839
9974
  tenantId,
9840
9975
  projectId,
@@ -9896,7 +10031,7 @@ var validateRequestParameters = (c) => {
9896
10031
  };
9897
10032
  var handleInitializationRequest = async (body, executionContext, validatedContext, req, res, c, credentialStores) => {
9898
10033
  const { tenantId, projectId, graphId } = executionContext;
9899
- logger22.info({ body }, "Received initialization request");
10034
+ logger23.info({ body }, "Received initialization request");
9900
10035
  const sessionId = nanoid();
9901
10036
  const agentGraph = await getAgentGraphWithDefaultAgent(dbClient_default)({
9902
10037
  scopes: { tenantId, projectId, graphId }
@@ -9936,7 +10071,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
9936
10071
  }
9937
10072
  }
9938
10073
  });
9939
- logger22.info(
10074
+ logger23.info(
9940
10075
  { sessionId, conversationId: conversation.id },
9941
10076
  "Created MCP session as conversation"
9942
10077
  );
@@ -9945,9 +10080,9 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
9945
10080
  });
9946
10081
  const server = await getServer(validatedContext, executionContext, sessionId, credentialStores);
9947
10082
  await server.connect(transport);
9948
- logger22.info({ sessionId }, "Server connected for initialization");
10083
+ logger23.info({ sessionId }, "Server connected for initialization");
9949
10084
  res.setHeader("Mcp-Session-Id", sessionId);
9950
- logger22.info(
10085
+ logger23.info(
9951
10086
  {
9952
10087
  sessionId,
9953
10088
  bodyMethod: body?.method,
@@ -9956,7 +10091,7 @@ var handleInitializationRequest = async (body, executionContext, validatedContex
9956
10091
  "About to handle initialization request"
9957
10092
  );
9958
10093
  await transport.handleRequest(req, res, body);
9959
- logger22.info({ sessionId }, "Successfully handled initialization request");
10094
+ logger23.info({ sessionId }, "Successfully handled initialization request");
9960
10095
  return toFetchResponse(res);
9961
10096
  };
9962
10097
  var handleExistingSessionRequest = async (body, executionContext, validatedContext, req, res, credentialStores) => {
@@ -9984,8 +10119,8 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
9984
10119
  sessionId,
9985
10120
  conversation.metadata?.session_data?.mcpProtocolVersion
9986
10121
  );
9987
- logger22.info({ sessionId }, "Server connected and transport initialized");
9988
- logger22.info(
10122
+ logger23.info({ sessionId }, "Server connected and transport initialized");
10123
+ logger23.info(
9989
10124
  {
9990
10125
  sessionId,
9991
10126
  bodyKeys: Object.keys(body || {}),
@@ -9999,9 +10134,9 @@ var handleExistingSessionRequest = async (body, executionContext, validatedConte
9999
10134
  );
10000
10135
  try {
10001
10136
  await transport.handleRequest(req, res, body);
10002
- logger22.info({ sessionId }, "Successfully handled MCP request");
10137
+ logger23.info({ sessionId }, "Successfully handled MCP request");
10003
10138
  } catch (transportError) {
10004
- logger22.error(
10139
+ logger23.error(
10005
10140
  {
10006
10141
  sessionId,
10007
10142
  error: transportError,
@@ -10052,13 +10187,13 @@ app4.openapi(
10052
10187
  }
10053
10188
  const { executionContext } = paramValidation;
10054
10189
  const body = c.get("requestBody") || {};
10055
- logger22.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10190
+ logger23.info({ body, bodyKeys: Object.keys(body || {}) }, "Parsed request body");
10056
10191
  const isInitRequest = body.method === "initialize";
10057
10192
  const { req, res } = toReqRes(c.req.raw);
10058
10193
  const validatedContext = c.get("validatedContext") || {};
10059
10194
  const credentialStores = c.get("credentialStores");
10060
- logger22.info({ validatedContext }, "Validated context");
10061
- logger22.info({ req }, "request");
10195
+ logger23.info({ validatedContext }, "Validated context");
10196
+ logger23.info({ req }, "request");
10062
10197
  if (isInitRequest) {
10063
10198
  return await handleInitializationRequest(
10064
10199
  body,
@@ -10080,7 +10215,7 @@ app4.openapi(
10080
10215
  );
10081
10216
  }
10082
10217
  } catch (e) {
10083
- logger22.error(
10218
+ logger23.error(
10084
10219
  {
10085
10220
  error: e instanceof Error ? e.message : e,
10086
10221
  stack: e instanceof Error ? e.stack : void 0
@@ -10092,7 +10227,7 @@ app4.openapi(
10092
10227
  }
10093
10228
  );
10094
10229
  app4.get("/", async (c) => {
10095
- logger22.info({}, "Received GET MCP request");
10230
+ logger23.info({}, "Received GET MCP request");
10096
10231
  return c.json(
10097
10232
  {
10098
10233
  jsonrpc: "2.0",
@@ -10106,7 +10241,7 @@ app4.get("/", async (c) => {
10106
10241
  );
10107
10242
  });
10108
10243
  app4.delete("/", async (c) => {
10109
- logger22.info({}, "Received DELETE MCP request");
10244
+ logger23.info({}, "Received DELETE MCP request");
10110
10245
  return c.json(
10111
10246
  {
10112
10247
  jsonrpc: "2.0",
@@ -10119,7 +10254,7 @@ app4.delete("/", async (c) => {
10119
10254
  var mcp_default = app4;
10120
10255
 
10121
10256
  // src/app.ts
10122
- var logger23 = getLogger("agents-run-api");
10257
+ var logger24 = getLogger("agents-run-api");
10123
10258
  function createExecutionHono(serverConfig, credentialStores) {
10124
10259
  const app6 = new OpenAPIHono();
10125
10260
  app6.use("*", otel());
@@ -10135,7 +10270,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10135
10270
  const body = await c.req.json();
10136
10271
  c.set("requestBody", body);
10137
10272
  } catch (error) {
10138
- 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");
10139
10274
  }
10140
10275
  }
10141
10276
  return next();
@@ -10186,8 +10321,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10186
10321
  if (!isExpectedError) {
10187
10322
  const errorMessage = err instanceof Error ? err.message : String(err);
10188
10323
  const errorStack = err instanceof Error ? err.stack : void 0;
10189
- if (logger23) {
10190
- logger23.error(
10324
+ if (logger24) {
10325
+ logger24.error(
10191
10326
  {
10192
10327
  error: err,
10193
10328
  message: errorMessage,
@@ -10199,8 +10334,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10199
10334
  );
10200
10335
  }
10201
10336
  } else {
10202
- if (logger23) {
10203
- logger23.error(
10337
+ if (logger24) {
10338
+ logger24.error(
10204
10339
  {
10205
10340
  error: err,
10206
10341
  path: c.req.path,
@@ -10217,8 +10352,8 @@ function createExecutionHono(serverConfig, credentialStores) {
10217
10352
  const response = err.getResponse();
10218
10353
  return response;
10219
10354
  } catch (responseError) {
10220
- if (logger23) {
10221
- logger23.error({ error: responseError }, "Error while handling HTTPException response");
10355
+ if (logger24) {
10356
+ logger24.error({ error: responseError }, "Error while handling HTTPException response");
10222
10357
  }
10223
10358
  }
10224
10359
  }
@@ -10252,7 +10387,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10252
10387
  app6.use("*", async (c, next) => {
10253
10388
  const executionContext = c.get("executionContext");
10254
10389
  if (!executionContext) {
10255
- logger23.debug({}, "Empty execution context");
10390
+ logger24.debug({}, "Empty execution context");
10256
10391
  return next();
10257
10392
  }
10258
10393
  const { tenantId, projectId, graphId } = executionContext;
@@ -10261,7 +10396,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10261
10396
  if (requestBody) {
10262
10397
  conversationId = requestBody.conversationId;
10263
10398
  if (!conversationId) {
10264
- logger23.debug({ requestBody }, "No conversation ID found in request body");
10399
+ logger24.debug({ requestBody }, "No conversation ID found in request body");
10265
10400
  }
10266
10401
  }
10267
10402
  const entries = Object.fromEntries(
@@ -10276,7 +10411,7 @@ function createExecutionHono(serverConfig, credentialStores) {
10276
10411
  })
10277
10412
  );
10278
10413
  if (!Object.keys(entries).length) {
10279
- logger23.debug({}, "Empty entries for baggage");
10414
+ logger24.debug({}, "Empty entries for baggage");
10280
10415
  return next();
10281
10416
  }
10282
10417
  const bag = Object.entries(entries).reduce(