@inkeep/agents-run-api 0.1.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.
Files changed (149) hide show
  1. package/README.md +117 -0
  2. package/dist/AgentExecutionServer.d.ts +23 -0
  3. package/dist/AgentExecutionServer.d.ts.map +1 -0
  4. package/dist/AgentExecutionServer.js +32 -0
  5. package/dist/__tests__/setup.d.ts +4 -0
  6. package/dist/__tests__/setup.d.ts.map +1 -0
  7. package/dist/__tests__/setup.js +50 -0
  8. package/dist/__tests__/utils/testProject.d.ts +18 -0
  9. package/dist/__tests__/utils/testProject.d.ts.map +1 -0
  10. package/dist/__tests__/utils/testProject.js +26 -0
  11. package/dist/__tests__/utils/testRequest.d.ts +8 -0
  12. package/dist/__tests__/utils/testRequest.d.ts.map +1 -0
  13. package/dist/__tests__/utils/testRequest.js +32 -0
  14. package/dist/__tests__/utils/testTenant.d.ts +64 -0
  15. package/dist/__tests__/utils/testTenant.d.ts.map +1 -0
  16. package/dist/__tests__/utils/testTenant.js +71 -0
  17. package/dist/a2a/client.d.ts +182 -0
  18. package/dist/a2a/client.d.ts.map +1 -0
  19. package/dist/a2a/client.js +645 -0
  20. package/dist/a2a/handlers.d.ts +4 -0
  21. package/dist/a2a/handlers.d.ts.map +1 -0
  22. package/dist/a2a/handlers.js +657 -0
  23. package/dist/a2a/transfer.d.ts +18 -0
  24. package/dist/a2a/transfer.d.ts.map +1 -0
  25. package/dist/a2a/transfer.js +22 -0
  26. package/dist/a2a/types.d.ts +63 -0
  27. package/dist/a2a/types.d.ts.map +1 -0
  28. package/dist/a2a/types.js +1 -0
  29. package/dist/agents/Agent.d.ts +154 -0
  30. package/dist/agents/Agent.d.ts.map +1 -0
  31. package/dist/agents/Agent.js +1105 -0
  32. package/dist/agents/ModelFactory.d.ts +62 -0
  33. package/dist/agents/ModelFactory.d.ts.map +1 -0
  34. package/dist/agents/ModelFactory.js +208 -0
  35. package/dist/agents/SystemPromptBuilder.d.ts +14 -0
  36. package/dist/agents/SystemPromptBuilder.d.ts.map +1 -0
  37. package/dist/agents/SystemPromptBuilder.js +62 -0
  38. package/dist/agents/ToolSessionManager.d.ts +61 -0
  39. package/dist/agents/ToolSessionManager.d.ts.map +1 -0
  40. package/dist/agents/ToolSessionManager.js +143 -0
  41. package/dist/agents/artifactTools.d.ts +30 -0
  42. package/dist/agents/artifactTools.d.ts.map +1 -0
  43. package/dist/agents/artifactTools.js +463 -0
  44. package/dist/agents/generateTaskHandler.d.ts +41 -0
  45. package/dist/agents/generateTaskHandler.d.ts.map +1 -0
  46. package/dist/agents/generateTaskHandler.js +350 -0
  47. package/dist/agents/relationTools.d.ts +33 -0
  48. package/dist/agents/relationTools.d.ts.map +1 -0
  49. package/dist/agents/relationTools.js +245 -0
  50. package/dist/agents/types.d.ts +23 -0
  51. package/dist/agents/types.d.ts.map +1 -0
  52. package/dist/agents/types.js +1 -0
  53. package/dist/agents/versions/V1Config.d.ts +21 -0
  54. package/dist/agents/versions/V1Config.d.ts.map +1 -0
  55. package/dist/agents/versions/V1Config.js +285 -0
  56. package/dist/app.d.ts +4 -0
  57. package/dist/app.d.ts.map +1 -0
  58. package/dist/app.js +194 -0
  59. package/dist/data/agentGraph.d.ts +4 -0
  60. package/dist/data/agentGraph.d.ts.map +1 -0
  61. package/dist/data/agentGraph.js +73 -0
  62. package/dist/data/agents.d.ts +4 -0
  63. package/dist/data/agents.d.ts.map +1 -0
  64. package/dist/data/agents.js +73 -0
  65. package/dist/data/conversations.d.ts +59 -0
  66. package/dist/data/conversations.d.ts.map +1 -0
  67. package/dist/data/conversations.js +216 -0
  68. package/dist/data/db/clean.d.ts +6 -0
  69. package/dist/data/db/clean.d.ts.map +1 -0
  70. package/dist/data/db/clean.js +77 -0
  71. package/dist/data/db/dbClient.d.ts +3 -0
  72. package/dist/data/db/dbClient.d.ts.map +1 -0
  73. package/dist/data/db/dbClient.js +13 -0
  74. package/dist/env.d.ts +43 -0
  75. package/dist/env.d.ts.map +1 -0
  76. package/dist/env.js +63 -0
  77. package/dist/handlers/executionHandler.d.ts +36 -0
  78. package/dist/handlers/executionHandler.d.ts.map +1 -0
  79. package/dist/handlers/executionHandler.js +402 -0
  80. package/dist/index.d.ts +5 -0
  81. package/dist/index.d.ts.map +1 -0
  82. package/dist/index.js +43 -0
  83. package/dist/instrumentation.d.ts +13 -0
  84. package/dist/instrumentation.d.ts.map +1 -0
  85. package/dist/instrumentation.js +66 -0
  86. package/dist/logger.d.ts +4 -0
  87. package/dist/logger.d.ts.map +1 -0
  88. package/dist/logger.js +32 -0
  89. package/dist/middleware/api-key-auth.d.ts +22 -0
  90. package/dist/middleware/api-key-auth.d.ts.map +1 -0
  91. package/dist/middleware/api-key-auth.js +139 -0
  92. package/dist/middleware/index.d.ts +2 -0
  93. package/dist/middleware/index.d.ts.map +1 -0
  94. package/dist/middleware/index.js +1 -0
  95. package/dist/openapi.d.ts +2 -0
  96. package/dist/openapi.d.ts.map +1 -0
  97. package/dist/openapi.js +36 -0
  98. package/dist/routes/agents.d.ts +4 -0
  99. package/dist/routes/agents.d.ts.map +1 -0
  100. package/dist/routes/agents.js +155 -0
  101. package/dist/routes/chat.d.ts +4 -0
  102. package/dist/routes/chat.d.ts.map +1 -0
  103. package/dist/routes/chat.js +308 -0
  104. package/dist/routes/chatDataStream.d.ts +4 -0
  105. package/dist/routes/chatDataStream.d.ts.map +1 -0
  106. package/dist/routes/chatDataStream.js +179 -0
  107. package/dist/routes/mcp.d.ts +4 -0
  108. package/dist/routes/mcp.d.ts.map +1 -0
  109. package/dist/routes/mcp.js +500 -0
  110. package/dist/tracer.d.ts +24 -0
  111. package/dist/tracer.d.ts.map +1 -0
  112. package/dist/tracer.js +97 -0
  113. package/dist/types/chat.d.ts +25 -0
  114. package/dist/types/chat.d.ts.map +1 -0
  115. package/dist/types/chat.js +1 -0
  116. package/dist/types/execution-context.d.ts +14 -0
  117. package/dist/types/execution-context.d.ts.map +1 -0
  118. package/dist/types/execution-context.js +14 -0
  119. package/dist/utils/agent-operations.d.ts +79 -0
  120. package/dist/utils/agent-operations.d.ts.map +1 -0
  121. package/dist/utils/agent-operations.js +67 -0
  122. package/dist/utils/artifact-component-schema.d.ts +29 -0
  123. package/dist/utils/artifact-component-schema.d.ts.map +1 -0
  124. package/dist/utils/artifact-component-schema.js +119 -0
  125. package/dist/utils/artifact-parser.d.ts +71 -0
  126. package/dist/utils/artifact-parser.d.ts.map +1 -0
  127. package/dist/utils/artifact-parser.js +251 -0
  128. package/dist/utils/cleanup.d.ts +19 -0
  129. package/dist/utils/cleanup.d.ts.map +1 -0
  130. package/dist/utils/cleanup.js +66 -0
  131. package/dist/utils/data-component-schema.d.ts +6 -0
  132. package/dist/utils/data-component-schema.d.ts.map +1 -0
  133. package/dist/utils/data-component-schema.js +43 -0
  134. package/dist/utils/graph-session.d.ts +200 -0
  135. package/dist/utils/graph-session.d.ts.map +1 -0
  136. package/dist/utils/graph-session.js +1009 -0
  137. package/dist/utils/incremental-stream-parser.d.ts +57 -0
  138. package/dist/utils/incremental-stream-parser.d.ts.map +1 -0
  139. package/dist/utils/incremental-stream-parser.js +287 -0
  140. package/dist/utils/response-formatter.d.ts +27 -0
  141. package/dist/utils/response-formatter.d.ts.map +1 -0
  142. package/dist/utils/response-formatter.js +160 -0
  143. package/dist/utils/stream-helpers.d.ts +162 -0
  144. package/dist/utils/stream-helpers.d.ts.map +1 -0
  145. package/dist/utils/stream-helpers.js +385 -0
  146. package/dist/utils/stream-registry.d.ts +18 -0
  147. package/dist/utils/stream-registry.d.ts.map +1 -0
  148. package/dist/utils/stream-registry.js +33 -0
  149. package/package.json +88 -0
@@ -0,0 +1,251 @@
1
+ import { getLedgerArtifacts, getTask, listTaskIdsByContextId } from '@inkeep/agents-core';
2
+ import { getLogger } from '../logger.js';
3
+ import dbClient from '../data/db/dbClient.js';
4
+ const logger = getLogger('ArtifactParser');
5
+ /**
6
+ * Unified artifact parser that handles all artifact-related parsing and formatting
7
+ * Used by both ResponseFormatter and IncrementalStreamParser to eliminate redundancy
8
+ */
9
+ export class ArtifactParser {
10
+ tenantId;
11
+ // Shared regex patterns
12
+ static ARTIFACT_REGEX = /<artifact:ref\s+id="([^"]*?)"\s+task="([^"]*?)"\s*\/>/gs;
13
+ static ARTIFACT_CHECK_REGEX = /<artifact:ref\s+(?=.*id="[^"]+")(?=.*task="[^"]+")[^>]*\/>/;
14
+ // Regex for catching any partial artifact pattern (< + any prefix of "artifact:ref")
15
+ static INCOMPLETE_ARTIFACT_REGEX = /<(a(r(t(i(f(a(c(t(:(r(e(f?)?)?)?)?)?)?)?)?)?)?)?)?$/g;
16
+ constructor(tenantId) {
17
+ this.tenantId = tenantId;
18
+ }
19
+ /**
20
+ * Check if text contains complete artifact markers
21
+ */
22
+ hasArtifactMarkers(text) {
23
+ return ArtifactParser.ARTIFACT_CHECK_REGEX.test(text);
24
+ }
25
+ /**
26
+ * Check if text has incomplete artifact marker (for streaming)
27
+ * More robust detection that handles streaming fragments
28
+ */
29
+ hasIncompleteArtifact(text) {
30
+ // Check if text ends with any partial artifact pattern
31
+ return (/<(a(r(t(i(f(a(c(t(:(r(e(f?)?)?)?)?)?)?)?)?)?)?)?)?$/.test(text) ||
32
+ /<artifact:ref[^>]*$/.test(text) || // Incomplete artifact:ref at end
33
+ this.findSafeTextBoundary(text) < text.length);
34
+ }
35
+ /**
36
+ * Find safe text boundary before incomplete artifacts (for streaming)
37
+ * Enhanced to handle streaming chunks that split in the middle of artifacts
38
+ */
39
+ findSafeTextBoundary(text) {
40
+ // First check for incomplete artifact patterns at the end
41
+ const endPatterns = [
42
+ /<artifact:ref(?![^>]*\/>).*$/, // artifact:ref that doesn't end with />
43
+ /<(a(r(t(i(f(a(c(t(:(r(e(f?)?)?)?)?)?)?)?)?)?)?)?)?$/, // Any partial artifact pattern at end
44
+ ];
45
+ for (const pattern of endPatterns) {
46
+ const match = text.match(pattern);
47
+ if (match && match.index !== undefined) {
48
+ return match.index;
49
+ }
50
+ }
51
+ // Look for incomplete artifact patterns anywhere in text
52
+ const matches = [...text.matchAll(ArtifactParser.INCOMPLETE_ARTIFACT_REGEX)];
53
+ if (matches.length === 0) {
54
+ return text.length;
55
+ }
56
+ // Check each match from the end to find an incomplete artifact
57
+ for (let i = matches.length - 1; i >= 0; i--) {
58
+ const match = matches[i];
59
+ const startIdx = match.index;
60
+ const textAfterMatch = text.slice(startIdx);
61
+ // If the text after this match doesn't contain a closing '/>', it's incomplete
62
+ if (!textAfterMatch.includes('/>')) {
63
+ return startIdx;
64
+ }
65
+ }
66
+ return text.length;
67
+ }
68
+ /**
69
+ * Get all artifacts for a context (with caching opportunity)
70
+ */
71
+ async getContextArtifacts(contextId) {
72
+ const artifacts = new Map();
73
+ try {
74
+ const taskIds = await listTaskIdsByContextId(dbClient)({
75
+ contextId: contextId,
76
+ });
77
+ for (const taskId of taskIds) {
78
+ // Get task to retrieve projectId
79
+ const task = await getTask(dbClient)({
80
+ id: taskId,
81
+ });
82
+ if (!task) {
83
+ logger.warn({ taskId }, 'Task not found when fetching artifacts');
84
+ continue;
85
+ }
86
+ const taskArtifacts = await getLedgerArtifacts(dbClient)({
87
+ scopes: { tenantId: this.tenantId, projectId: task.projectId },
88
+ taskId,
89
+ });
90
+ for (const artifact of taskArtifacts) {
91
+ const key = `${artifact.artifactId}:${artifact.taskId}`;
92
+ artifacts.set(key, artifact);
93
+ }
94
+ }
95
+ logger.debug({ contextId, count: artifacts.size }, 'Loaded context artifacts');
96
+ }
97
+ catch (error) {
98
+ logger.error({ error, contextId }, 'Error loading context artifacts');
99
+ }
100
+ return artifacts;
101
+ }
102
+ /**
103
+ * Convert raw artifact to standardized data format
104
+ */
105
+ formatArtifactData(artifact, artifactId, taskId) {
106
+ return {
107
+ artifactId,
108
+ taskId,
109
+ name: artifact.name || 'Processing...',
110
+ description: artifact.description || 'Name and description being generated...',
111
+ artifactType: artifact.metadata?.artifactType,
112
+ artifactSummary: artifact.parts?.[0]?.data?.summary || {},
113
+ };
114
+ }
115
+ /**
116
+ * Parse text with artifact markers into parts array
117
+ * Can work with or without pre-fetched artifact map
118
+ */
119
+ async parseText(text, artifactMap) {
120
+ const parts = [];
121
+ const matches = [...text.matchAll(ArtifactParser.ARTIFACT_REGEX)];
122
+ if (matches.length === 0) {
123
+ return [{ kind: 'text', text }];
124
+ }
125
+ let lastIndex = 0;
126
+ for (const match of matches) {
127
+ const [fullMatch, artifactId, taskId] = match;
128
+ const matchStart = match.index;
129
+ // Add text before artifact
130
+ if (matchStart > lastIndex) {
131
+ const textBefore = text.slice(lastIndex, matchStart);
132
+ if (textBefore.trim()) {
133
+ parts.push({ kind: 'text', text: textBefore });
134
+ }
135
+ }
136
+ // Get artifact data
137
+ const artifactData = await this.getArtifactData(artifactId, taskId, artifactMap);
138
+ if (artifactData) {
139
+ parts.push({ kind: 'data', data: artifactData });
140
+ }
141
+ // If no artifact found, marker is simply removed
142
+ lastIndex = matchStart + fullMatch.length;
143
+ }
144
+ // Add remaining text
145
+ if (lastIndex < text.length) {
146
+ const remainingText = text.slice(lastIndex);
147
+ if (remainingText.trim()) {
148
+ parts.push({ kind: 'text', text: remainingText });
149
+ }
150
+ }
151
+ return parts;
152
+ }
153
+ /**
154
+ * Process object/dataComponents for artifact components
155
+ */
156
+ async parseObject(obj, artifactMap) {
157
+ // Handle dataComponents array
158
+ if (obj?.dataComponents && Array.isArray(obj.dataComponents)) {
159
+ const parts = [];
160
+ for (const component of obj.dataComponents) {
161
+ if (this.isArtifactComponent(component)) {
162
+ const artifactData = await this.getArtifactData(component.props.artifact_id, component.props.task_id, artifactMap);
163
+ if (artifactData) {
164
+ parts.push({ kind: 'data', data: artifactData });
165
+ }
166
+ }
167
+ else {
168
+ parts.push({ kind: 'data', data: component });
169
+ }
170
+ }
171
+ return parts;
172
+ }
173
+ // Handle single object
174
+ if (this.isArtifactComponent(obj)) {
175
+ const artifactData = await this.getArtifactData(obj.props.artifact_id, obj.props.task_id, artifactMap);
176
+ return artifactData ? [{ kind: 'data', data: artifactData }] : [];
177
+ }
178
+ return [{ kind: 'data', data: obj }];
179
+ }
180
+ /**
181
+ * Check if object is an artifact component
182
+ */
183
+ isArtifactComponent(obj) {
184
+ return obj?.props?.artifact_id && obj?.props?.task_id;
185
+ }
186
+ /**
187
+ * Get artifact data from map or fetch directly
188
+ */
189
+ async getArtifactData(artifactId, taskId, artifactMap) {
190
+ const key = `${artifactId}:${taskId}`;
191
+ // Try map first
192
+ if (artifactMap?.has(key)) {
193
+ const artifact = artifactMap.get(key);
194
+ return this.formatArtifactData(artifact, artifactId, taskId);
195
+ }
196
+ // Fetch directly if no map
197
+ try {
198
+ // Get task to retrieve projectId
199
+ const task = await getTask(dbClient)({
200
+ id: taskId,
201
+ });
202
+ if (!task) {
203
+ logger.warn({ taskId }, 'Task not found when fetching artifact');
204
+ return null;
205
+ }
206
+ const artifacts = await getLedgerArtifacts(dbClient)({
207
+ scopes: { tenantId: this.tenantId, projectId: task.projectId },
208
+ artifactId,
209
+ taskId,
210
+ });
211
+ if (artifacts.length > 0) {
212
+ return this.formatArtifactData(artifacts[0], artifactId, taskId);
213
+ }
214
+ }
215
+ catch (error) {
216
+ logger.warn({ artifactId, taskId, error }, 'Failed to fetch artifact');
217
+ }
218
+ return null;
219
+ }
220
+ /**
221
+ * Parse partial JSON buffer (for streaming)
222
+ */
223
+ parsePartialJSON(buffer) {
224
+ const complete = [];
225
+ let remaining = buffer;
226
+ let braceCount = 0;
227
+ let start = -1;
228
+ for (let i = 0; i < buffer.length; i++) {
229
+ if (buffer[i] === '{') {
230
+ if (braceCount === 0)
231
+ start = i;
232
+ braceCount++;
233
+ }
234
+ else if (buffer[i] === '}') {
235
+ braceCount--;
236
+ if (braceCount === 0 && start !== -1) {
237
+ const jsonStr = buffer.slice(start, i + 1);
238
+ try {
239
+ complete.push(JSON.parse(jsonStr));
240
+ remaining = buffer.slice(i + 1);
241
+ start = -1;
242
+ }
243
+ catch {
244
+ // Invalid JSON, continue
245
+ }
246
+ }
247
+ }
248
+ }
249
+ return { complete, remaining };
250
+ }
251
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Cleanup utilities for gracefully shutting down resources
3
+ * Helps prevent Node.js processes from hanging
4
+ */
5
+ /**
6
+ * Gracefully exit the process after cleaning up resources
7
+ */
8
+ export declare function gracefulExit(code?: number, delayMs?: number, message?: string): void;
9
+ /**
10
+ * Setup signal handlers for graceful shutdown
11
+ */
12
+ export declare function setupGracefulShutdown(cleanupFn?: () => Promise<void> | void, exitDelayMs?: number): void;
13
+ /**
14
+ * Stop all tools associated with agents
15
+ */
16
+ export declare function stopAllAgentTools(agents: Array<{
17
+ getTools: () => Record<string, any>;
18
+ }>): Promise<void>;
19
+ //# sourceMappingURL=cleanup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cleanup.d.ts","sourceRoot":"","sources":["../../src/utils/cleanup.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAMH;;GAEG;AACH,wBAAgB,YAAY,CAAC,IAAI,GAAE,MAAU,EAAE,OAAO,GAAE,MAAa,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAS7F;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,EACtC,WAAW,GAAE,MAAa,GACzB,IAAI,CAyBN;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,KAAK,CAAC;IAAE,QAAQ,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAAE,CAAC,GACrD,OAAO,CAAC,IAAI,CAAC,CAqBf"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Cleanup utilities for gracefully shutting down resources
3
+ * Helps prevent Node.js processes from hanging
4
+ */
5
+ import { getLogger } from '../logger.js';
6
+ const logger = getLogger('cleanup');
7
+ /**
8
+ * Gracefully exit the process after cleaning up resources
9
+ */
10
+ export function gracefulExit(code = 0, delayMs = 1000, message) {
11
+ if (message) {
12
+ logger.info(message);
13
+ }
14
+ setTimeout(() => {
15
+ logger.debug('Forcing process exit after cleanup delay');
16
+ process.exit(code);
17
+ }, delayMs);
18
+ }
19
+ /**
20
+ * Setup signal handlers for graceful shutdown
21
+ */
22
+ export function setupGracefulShutdown(cleanupFn, exitDelayMs = 2000) {
23
+ const signals = ['SIGTERM', 'SIGINT'];
24
+ let isShuttingDown = false;
25
+ for (const signal of signals) {
26
+ process.on(signal, async () => {
27
+ if (isShuttingDown) {
28
+ logger.warn(`Received ${signal} during shutdown, forcing exit`);
29
+ process.exit(1);
30
+ }
31
+ logger.info(`Received ${signal}, starting graceful shutdown`);
32
+ isShuttingDown = true;
33
+ try {
34
+ if (cleanupFn) {
35
+ await cleanupFn();
36
+ }
37
+ }
38
+ catch (error) {
39
+ logger.error({ error }, 'Error during cleanup');
40
+ }
41
+ gracefulExit(0, exitDelayMs, '🚪 Graceful shutdown complete');
42
+ });
43
+ }
44
+ }
45
+ /**
46
+ * Stop all tools associated with agents
47
+ */
48
+ export async function stopAllAgentTools(agents) {
49
+ logger.info('Stopping all agent tools...');
50
+ for (const agent of agents) {
51
+ const tools = agent.getTools();
52
+ for (const toolInstance of Object.values(tools)) {
53
+ if (toolInstance && typeof toolInstance.stop === 'function') {
54
+ try {
55
+ await toolInstance.stop();
56
+ const toolName = toolInstance.config?.name || 'unknown';
57
+ logger.debug(`Stopped tool: ${toolName}`);
58
+ }
59
+ catch (error) {
60
+ logger.warn(`Failed to stop tool: ${error instanceof Error ? error.message : 'Unknown error'}`);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ logger.info('All agent tools stopped');
66
+ }
@@ -0,0 +1,6 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Converts JSON Schema objects to Zod schema types
4
+ */
5
+ export declare function jsonSchemaToZod(jsonSchema: any): z.ZodType<any>;
6
+ //# sourceMappingURL=data-component-schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-component-schema.d.ts","sourceRoot":"","sources":["../../src/utils/data-component-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB;;GAEG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,GAAG,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CA8C/D"}
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import { getLogger } from '../logger.js';
3
+ const logger = getLogger('DataComponentSchema');
4
+ /**
5
+ * Converts JSON Schema objects to Zod schema types
6
+ */
7
+ export function jsonSchemaToZod(jsonSchema) {
8
+ if (!jsonSchema || typeof jsonSchema !== 'object') {
9
+ logger.warn({ jsonSchema }, 'Invalid JSON schema provided, using string fallback');
10
+ return z.string();
11
+ }
12
+ switch (jsonSchema.type) {
13
+ case 'object':
14
+ if (jsonSchema.properties) {
15
+ const shape = {};
16
+ for (const [key, prop] of Object.entries(jsonSchema.properties)) {
17
+ shape[key] = jsonSchemaToZod(prop);
18
+ }
19
+ return z.object(shape);
20
+ }
21
+ return z.record(z.string(), z.unknown());
22
+ case 'array': {
23
+ const itemSchema = jsonSchema.items ? jsonSchemaToZod(jsonSchema.items) : z.unknown();
24
+ return z.array(itemSchema);
25
+ }
26
+ case 'string':
27
+ return z.string();
28
+ case 'number':
29
+ case 'integer':
30
+ return z.number();
31
+ case 'boolean':
32
+ return z.boolean();
33
+ case 'null':
34
+ return z.null();
35
+ default:
36
+ // Log unsupported types for monitoring
37
+ logger.warn({
38
+ unsupportedType: jsonSchema.type,
39
+ schema: jsonSchema,
40
+ }, 'Unsupported JSON schema type, using unknown validation');
41
+ return z.unknown();
42
+ }
43
+ }
@@ -0,0 +1,200 @@
1
+ import type { StatusUpdateSettings, ModelSettings } from '@inkeep/agents-core';
2
+ export type GraphSessionEventType = 'agent_generate' | 'transfer' | 'delegation_sent' | 'delegation_returned' | 'artifact_saved' | 'tool_execution';
3
+ export interface GraphSessionEvent {
4
+ timestamp: number;
5
+ eventType: GraphSessionEventType;
6
+ agentId: string;
7
+ data: EventData;
8
+ }
9
+ export type EventData = AgentGenerateData | TransferData | DelegationSentData | DelegationReturnedData | ArtifactSavedData | ToolExecutionData;
10
+ export interface AgentGenerateData {
11
+ parts: Array<{
12
+ type: 'text' | 'tool_call' | 'tool_result';
13
+ content?: string;
14
+ toolName?: string;
15
+ args?: any;
16
+ result?: any;
17
+ }>;
18
+ generationType: 'text_generation' | 'object_generation' | 'artifact_name_description';
19
+ }
20
+ export interface TransferData {
21
+ fromAgent: string;
22
+ targetAgent: string;
23
+ reason?: string;
24
+ context?: any;
25
+ }
26
+ export interface DelegationSentData {
27
+ delegationId: string;
28
+ fromAgent: string;
29
+ targetAgent: string;
30
+ taskDescription: string;
31
+ context?: any;
32
+ }
33
+ export interface DelegationReturnedData {
34
+ delegationId: string;
35
+ fromAgent: string;
36
+ targetAgent: string;
37
+ result?: any;
38
+ }
39
+ export interface ArtifactSavedData {
40
+ artifactId: string;
41
+ taskId: string;
42
+ artifactType: string;
43
+ summaryData?: Record<string, any>;
44
+ fullData?: Record<string, any>;
45
+ pendingGeneration?: boolean;
46
+ tenantId?: string;
47
+ projectId?: string;
48
+ contextId?: string;
49
+ metadata?: Record<string, any>;
50
+ summaryProps?: Record<string, any>;
51
+ fullProps?: Record<string, any>;
52
+ }
53
+ export interface ToolExecutionData {
54
+ toolName: string;
55
+ args: any;
56
+ result: any;
57
+ toolId?: string;
58
+ duration?: number;
59
+ }
60
+ /**
61
+ * Tracks all agent operations and interactions for a single message
62
+ * Now includes intelligent status update functionality
63
+ */
64
+ export declare class GraphSession {
65
+ readonly sessionId: string;
66
+ readonly messageId: string;
67
+ readonly graphId?: string | undefined;
68
+ readonly tenantId?: string | undefined;
69
+ readonly projectId?: string | undefined;
70
+ private events;
71
+ private statusUpdateState?;
72
+ private statusUpdateTimer?;
73
+ private previousSummaries;
74
+ private isEnded;
75
+ private isTextStreaming;
76
+ private isGeneratingUpdate;
77
+ constructor(sessionId: string, messageId: string, graphId?: string | undefined, tenantId?: string | undefined, projectId?: string | undefined);
78
+ /**
79
+ * Initialize status updates for this session
80
+ */
81
+ initializeStatusUpdates(config: StatusUpdateSettings, summarizerModel?: ModelSettings): void;
82
+ /**
83
+ * Record an event in the session and trigger status updates if configured
84
+ */
85
+ recordEvent(eventType: GraphSessionEventType, agentId: string, data: EventData): void;
86
+ /**
87
+ * Check and send status updates if configured (async, non-blocking)
88
+ */
89
+ private checkStatusUpdates;
90
+ /**
91
+ * Check and send time-based status updates
92
+ */
93
+ private checkAndSendTimeBasedUpdate;
94
+ /**
95
+ * Get all events in chronological order
96
+ */
97
+ getEvents(): GraphSessionEvent[];
98
+ /**
99
+ * Get events filtered by type
100
+ */
101
+ getEventsByType(eventType: GraphSessionEventType): GraphSessionEvent[];
102
+ /**
103
+ * Get events filtered by agent
104
+ */
105
+ getEventsByAgent(agentId: string): GraphSessionEvent[];
106
+ /**
107
+ * Get summary of session activity
108
+ */
109
+ getSummary(): {
110
+ sessionId: string;
111
+ messageId: string;
112
+ graphId: string | undefined;
113
+ totalEvents: number;
114
+ eventCounts: Record<GraphSessionEventType, number>;
115
+ agentCounts: Record<string, number>;
116
+ startTime: number;
117
+ endTime: number;
118
+ duration: number;
119
+ };
120
+ /**
121
+ * Mark that text streaming has started (to suppress status updates)
122
+ */
123
+ setTextStreaming(isStreaming: boolean): void;
124
+ /**
125
+ * Check if text is currently being streamed
126
+ */
127
+ isCurrentlyStreaming(): boolean;
128
+ /**
129
+ * Clean up status update resources when session ends
130
+ */
131
+ cleanup(): void;
132
+ /**
133
+ * Generate and send a status update using graph-level summarizer
134
+ */
135
+ private generateAndSendUpdate;
136
+ /**
137
+ * Generate user-focused progress summary hiding internal operations
138
+ */
139
+ private generateProgressSummary;
140
+ /**
141
+ * Generate structured status update using configured data components
142
+ */
143
+ private generateStructuredStatusUpdate;
144
+ /**
145
+ * Build Zod schema from JSON schema configuration
146
+ */
147
+ private buildZodSchema;
148
+ /**
149
+ * Extract user-visible activities with rich formatting and complete information
150
+ */
151
+ private extractUserVisibleActivities;
152
+ /**
153
+ * Generate fallback summary when LLM fails
154
+ */
155
+ private generateFallbackSummary;
156
+ /**
157
+ * Process a single artifact to generate name and description using conversation context
158
+ */
159
+ private processArtifact;
160
+ }
161
+ /**
162
+ * Manages GraphSession instances for message-level tracking
163
+ */
164
+ export declare class GraphSessionManager {
165
+ private sessions;
166
+ /**
167
+ * Create a new session for a message
168
+ */
169
+ createSession(messageId: string, graphId?: string, tenantId?: string, projectId?: string): string;
170
+ /**
171
+ * Initialize status updates for a session
172
+ */
173
+ initializeStatusUpdates(sessionId: string, config: StatusUpdateSettings, summarizerModel?: ModelSettings): void;
174
+ /**
175
+ * Get an existing session
176
+ */
177
+ getSession(sessionId: string): GraphSession | null;
178
+ /**
179
+ * Record an event in a session
180
+ */
181
+ recordEvent(sessionId: string, eventType: GraphSessionEventType, agentId: string, data: EventData): void;
182
+ /**
183
+ * End a session and return the final event data
184
+ */
185
+ endSession(sessionId: string): GraphSessionEvent[];
186
+ /**
187
+ * Set text streaming state for a session
188
+ */
189
+ setTextStreaming(sessionId: string, isStreaming: boolean): void;
190
+ /**
191
+ * Get summary of all active sessions
192
+ */
193
+ getActiveSessions(): Array<{
194
+ sessionId: string;
195
+ messageId: string;
196
+ eventCount: number;
197
+ }>;
198
+ }
199
+ export declare const graphSessionManager: GraphSessionManager;
200
+ //# sourceMappingURL=graph-session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-session.d.ts","sourceRoot":"","sources":["../../src/utils/graph-session.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,oBAAoB,EAEpB,aAAa,EACd,MAAM,qBAAqB,CAAC;AAO7B,MAAM,MAAM,qBAAqB,GAC7B,gBAAgB,GAChB,UAAU,GACV,iBAAiB,GACjB,qBAAqB,GACrB,gBAAgB,GAChB,gBAAgB,CAAC;AAErB,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,MAAM,CAAC;IACl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