@falai/agent 0.9.0-alpha-2 → 0.9.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 (75) hide show
  1. package/dist/cjs/src/core/Agent.d.ts +31 -41
  2. package/dist/cjs/src/core/Agent.d.ts.map +1 -1
  3. package/dist/cjs/src/core/Agent.js +72 -1075
  4. package/dist/cjs/src/core/Agent.js.map +1 -1
  5. package/dist/cjs/src/core/ResponseModal.d.ts +205 -0
  6. package/dist/cjs/src/core/ResponseModal.d.ts.map +1 -0
  7. package/dist/cjs/src/core/ResponseModal.js +1328 -0
  8. package/dist/cjs/src/core/ResponseModal.js.map +1 -0
  9. package/dist/cjs/src/core/ResponsePipeline.js +1 -1
  10. package/dist/cjs/src/core/ResponsePipeline.js.map +1 -1
  11. package/dist/cjs/src/index.d.ts +3 -1
  12. package/dist/cjs/src/index.d.ts.map +1 -1
  13. package/dist/cjs/src/index.js +7 -1
  14. package/dist/cjs/src/index.js.map +1 -1
  15. package/dist/cjs/src/types/agent.d.ts +1 -0
  16. package/dist/cjs/src/types/agent.d.ts.map +1 -1
  17. package/dist/cjs/src/types/ai.d.ts +1 -1
  18. package/dist/cjs/src/types/ai.d.ts.map +1 -1
  19. package/dist/cjs/src/utils/clone.d.ts.map +1 -1
  20. package/dist/cjs/src/utils/clone.js +0 -4
  21. package/dist/cjs/src/utils/clone.js.map +1 -1
  22. package/dist/cjs/src/utils/history.d.ts +30 -1
  23. package/dist/cjs/src/utils/history.d.ts.map +1 -1
  24. package/dist/cjs/src/utils/history.js +169 -23
  25. package/dist/cjs/src/utils/history.js.map +1 -1
  26. package/dist/cjs/src/utils/index.d.ts +1 -1
  27. package/dist/cjs/src/utils/index.d.ts.map +1 -1
  28. package/dist/cjs/src/utils/index.js +5 -1
  29. package/dist/cjs/src/utils/index.js.map +1 -1
  30. package/dist/src/core/Agent.d.ts +31 -41
  31. package/dist/src/core/Agent.d.ts.map +1 -1
  32. package/dist/src/core/Agent.js +73 -1076
  33. package/dist/src/core/Agent.js.map +1 -1
  34. package/dist/src/core/ResponseModal.d.ts +205 -0
  35. package/dist/src/core/ResponseModal.d.ts.map +1 -0
  36. package/dist/src/core/ResponseModal.js +1323 -0
  37. package/dist/src/core/ResponseModal.js.map +1 -0
  38. package/dist/src/core/ResponsePipeline.js +1 -1
  39. package/dist/src/core/ResponsePipeline.js.map +1 -1
  40. package/dist/src/index.d.ts +3 -1
  41. package/dist/src/index.d.ts.map +1 -1
  42. package/dist/src/index.js +2 -1
  43. package/dist/src/index.js.map +1 -1
  44. package/dist/src/types/agent.d.ts +1 -0
  45. package/dist/src/types/agent.d.ts.map +1 -1
  46. package/dist/src/types/ai.d.ts +1 -1
  47. package/dist/src/types/ai.d.ts.map +1 -1
  48. package/dist/src/utils/clone.d.ts.map +1 -1
  49. package/dist/src/utils/clone.js +0 -4
  50. package/dist/src/utils/clone.js.map +1 -1
  51. package/dist/src/utils/history.d.ts +30 -1
  52. package/dist/src/utils/history.d.ts.map +1 -1
  53. package/dist/src/utils/history.js +165 -23
  54. package/dist/src/utils/history.js.map +1 -1
  55. package/dist/src/utils/index.d.ts +1 -1
  56. package/dist/src/utils/index.d.ts.map +1 -1
  57. package/dist/src/utils/index.js +1 -1
  58. package/dist/src/utils/index.js.map +1 -1
  59. package/docs/README.md +2 -1
  60. package/docs/api/README.md +160 -0
  61. package/docs/api/overview.md +66 -1
  62. package/docs/guides/migration/README.md +72 -0
  63. package/docs/guides/migration/response-modal-refactor.md +518 -0
  64. package/examples/advanced-patterns/streaming-responses.ts +169 -96
  65. package/examples/core-concepts/modern-streaming-api.ts +309 -0
  66. package/package.json +1 -1
  67. package/src/core/Agent.ts +95 -1488
  68. package/src/core/ResponseModal.ts +1722 -0
  69. package/src/core/ResponsePipeline.ts +1 -1
  70. package/src/index.ts +11 -0
  71. package/src/types/agent.ts +1 -0
  72. package/src/types/ai.ts +1 -1
  73. package/src/utils/clone.ts +6 -8
  74. package/src/utils/history.ts +190 -27
  75. package/src/utils/index.ts +4 -0
@@ -5,25 +5,41 @@
5
5
  import { EventKind, MessageRole } from "../types";
6
6
  /**
7
7
  * Convert a simplified history item to an internal Event
8
+ * @param item - The HistoryItem to convert
9
+ * @returns Event with proper type-safe structure
10
+ * @throws Error if the history item is malformed or has invalid data
8
11
  */
9
- function convertHistoryItemToEvent(item) {
12
+ export function historyItemToEvent(item) {
13
+ if (!item || typeof item !== 'object') {
14
+ throw new Error('Invalid history item: must be a non-null object');
15
+ }
16
+ if (!item.role || typeof item.role !== 'string') {
17
+ throw new Error('Invalid history item: role is required and must be a string');
18
+ }
10
19
  const timestamp = new Date().toISOString();
11
20
  switch (item.role) {
12
21
  case "user": {
22
+ const userItem = item;
23
+ if (typeof userItem.content !== 'string') {
24
+ throw new Error('Invalid user history item: content must be a string');
25
+ }
13
26
  return {
14
27
  kind: EventKind.MESSAGE,
15
28
  source: MessageRole.USER,
16
29
  timestamp,
17
30
  data: {
18
31
  participant: {
19
- display_name: item.name || "User",
32
+ display_name: userItem.name || "User",
20
33
  },
21
- message: item.content,
34
+ message: userItem.content,
22
35
  },
23
36
  };
24
37
  }
25
38
  case "assistant": {
26
- // Handle assistant message with optional tool calls
39
+ const assistantItem = item;
40
+ if (assistantItem.content !== null && typeof assistantItem.content !== 'string') {
41
+ throw new Error('Invalid assistant history item: content must be a string or null');
42
+ }
27
43
  const event = {
28
44
  kind: EventKind.MESSAGE,
29
45
  source: MessageRole.ASSISTANT,
@@ -32,17 +48,31 @@ function convertHistoryItemToEvent(item) {
32
48
  participant: {
33
49
  display_name: "Assistant",
34
50
  },
35
- message: item.content || "",
51
+ message: assistantItem.content || "",
36
52
  },
37
53
  };
38
- // If there are tool calls, we need to create a separate tool event
39
- // But for now, we'll just store the tool calls in the message data
40
- if (item.tool_calls && item.tool_calls.length > 0) {
41
- event.data.toolCalls = item.tool_calls;
54
+ // If there are tool calls, validate and add them
55
+ if (assistantItem.tool_calls && assistantItem.tool_calls.length > 0) {
56
+ if (!Array.isArray(assistantItem.tool_calls)) {
57
+ throw new Error('Invalid assistant history item: tool_calls must be an array');
58
+ }
59
+ for (const toolCall of assistantItem.tool_calls) {
60
+ if (!toolCall.id || !toolCall.name || typeof toolCall.arguments !== 'object') {
61
+ throw new Error('Invalid tool call: id, name, and arguments are required');
62
+ }
63
+ }
64
+ event.data.toolCalls = assistantItem.tool_calls;
42
65
  }
43
66
  return event;
44
67
  }
45
68
  case "tool": {
69
+ const toolItem = item;
70
+ if (!toolItem.tool_call_id || typeof toolItem.tool_call_id !== 'string') {
71
+ throw new Error('Invalid tool history item: tool_call_id is required and must be a string');
72
+ }
73
+ if (!toolItem.name || typeof toolItem.name !== 'string') {
74
+ throw new Error('Invalid tool history item: name is required and must be a string');
75
+ }
46
76
  return {
47
77
  kind: EventKind.TOOL,
48
78
  source: MessageRole.AGENT,
@@ -50,10 +80,10 @@ function convertHistoryItemToEvent(item) {
50
80
  data: {
51
81
  tool_calls: [
52
82
  {
53
- tool_id: item.tool_call_id,
83
+ tool_id: toolItem.tool_call_id,
54
84
  arguments: {}, // Tool results don't have arguments
55
85
  result: {
56
- data: item.content,
86
+ data: toolItem.content,
57
87
  },
58
88
  },
59
89
  ],
@@ -61,6 +91,10 @@ function convertHistoryItemToEvent(item) {
61
91
  };
62
92
  }
63
93
  case "system": {
94
+ const systemItem = item;
95
+ if (typeof systemItem.content !== 'string') {
96
+ throw new Error('Invalid system history item: content must be a string');
97
+ }
64
98
  return {
65
99
  kind: EventKind.MESSAGE,
66
100
  source: MessageRole.SYSTEM,
@@ -69,30 +103,138 @@ function convertHistoryItemToEvent(item) {
69
103
  participant: {
70
104
  display_name: "System",
71
105
  },
72
- message: item.content,
106
+ message: systemItem.content,
73
107
  },
74
108
  };
75
109
  }
76
110
  default:
77
- // This should never happen due to TypeScript, but fallback just in case
111
+ throw new Error(`Invalid history item role: ${String(item.role)}`);
112
+ }
113
+ }
114
+ /**
115
+ * Convert an array of HistoryItems to Events
116
+ * @param history - Array of HistoryItems to convert
117
+ * @returns Array of Events with proper type-safe structure
118
+ * @throws Error if any history item is malformed
119
+ */
120
+ export function historyToEvents(history) {
121
+ if (!Array.isArray(history)) {
122
+ throw new Error('Invalid history: must be an array');
123
+ }
124
+ return history.map((item, index) => {
125
+ try {
126
+ return historyItemToEvent(item);
127
+ }
128
+ catch (error) {
129
+ throw new Error(`Error converting history item at index ${index}: ${error instanceof Error ? error.message : 'Unknown error'}`);
130
+ }
131
+ });
132
+ }
133
+ /**
134
+ * Convert an Event back to a HistoryItem
135
+ * @param event - The Event to convert
136
+ * @returns HistoryItem with simplified structure
137
+ * @throws Error if the event is malformed or has invalid data
138
+ */
139
+ export function eventToHistoryItem(event) {
140
+ if (!event || typeof event !== 'object') {
141
+ throw new Error('Invalid event: must be a non-null object');
142
+ }
143
+ if (!event.kind || !event.source || !event.data) {
144
+ throw new Error('Invalid event: kind, source, and data are required');
145
+ }
146
+ switch (event.kind) {
147
+ case EventKind.MESSAGE: {
148
+ const messageData = event.data;
149
+ if (!messageData.message && messageData.message !== '') {
150
+ throw new Error('Invalid message event: message is required');
151
+ }
152
+ switch (event.source) {
153
+ case MessageRole.USER: {
154
+ const userItem = {
155
+ role: "user",
156
+ content: messageData.message,
157
+ };
158
+ if (messageData.participant?.display_name && messageData.participant.display_name !== "User") {
159
+ userItem.name = messageData.participant.display_name;
160
+ }
161
+ return userItem;
162
+ }
163
+ case MessageRole.ASSISTANT: {
164
+ const assistantItem = {
165
+ role: "assistant",
166
+ content: messageData.message || null,
167
+ };
168
+ if (messageData.toolCalls && messageData.toolCalls.length > 0) {
169
+ assistantItem.tool_calls = messageData.toolCalls;
170
+ }
171
+ return assistantItem;
172
+ }
173
+ case MessageRole.SYSTEM: {
174
+ return {
175
+ role: "system",
176
+ content: messageData.message,
177
+ };
178
+ }
179
+ default:
180
+ throw new Error(`Unsupported message source for conversion: ${event.source}`);
181
+ }
182
+ }
183
+ case EventKind.TOOL: {
184
+ const toolData = event.data;
185
+ if (!toolData.tool_calls || !Array.isArray(toolData.tool_calls) || toolData.tool_calls.length === 0) {
186
+ throw new Error('Invalid tool event: tool_calls array is required and must not be empty');
187
+ }
188
+ const firstToolCall = toolData.tool_calls[0];
189
+ if (!firstToolCall.tool_id) {
190
+ throw new Error('Invalid tool call: tool_id is required');
191
+ }
192
+ const toolItem = {
193
+ role: "tool",
194
+ tool_call_id: firstToolCall.tool_id,
195
+ name: firstToolCall.tool_id, // Use tool_id as name for simplicity
196
+ content: firstToolCall.result?.data,
197
+ };
198
+ return toolItem;
199
+ }
200
+ case EventKind.STATUS: {
201
+ // Status events don't have a direct HistoryItem equivalent
202
+ // Convert to system message for compatibility
203
+ const statusData = event.data;
78
204
  return {
79
- kind: EventKind.MESSAGE,
80
- source: MessageRole.SYSTEM,
81
- timestamp,
82
- data: {
83
- participant: {
84
- display_name: "Unknown",
85
- },
86
- message: "Unknown message type",
87
- },
205
+ role: "system",
206
+ content: statusData.status || "Status update",
88
207
  };
208
+ }
209
+ default:
210
+ throw new Error(`Unsupported event kind for conversion: ${String(event.kind)}`);
211
+ }
212
+ }
213
+ /**
214
+ * Convert an array of Events back to HistoryItems
215
+ * @param events - Array of Events to convert
216
+ * @returns Array of HistoryItems with simplified structure
217
+ * @throws Error if any event is malformed
218
+ */
219
+ export function eventsToHistory(events) {
220
+ if (!Array.isArray(events)) {
221
+ throw new Error('Invalid events: must be an array');
89
222
  }
223
+ return events.map((event, index) => {
224
+ try {
225
+ return eventToHistoryItem(event);
226
+ }
227
+ catch (error) {
228
+ throw new Error(`Error converting event at index ${index}: ${error instanceof Error ? error.message : 'Unknown error'}`);
229
+ }
230
+ });
90
231
  }
91
232
  /**
92
233
  * Normalize a simplified history array to internal Event array
234
+ * @deprecated Use historyToEvents instead
93
235
  */
94
236
  export function normalizeHistory(history) {
95
- return history.map(convertHistoryItemToEvent);
237
+ return historyToEvents(history);
96
238
  }
97
239
  /**
98
240
  * Helper function to create a user message
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","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CAAC,mCAAmC,KAAK,KAAK,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC;QAC3H,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgB;IAC/C,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,OAAe,EAAE,IAAa;IACxD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACzC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAC9B,OAAsB,EACtB,SAIE;IAEF,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;AAC/D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CACzB,UAAkB,EAClB,IAAY,EACZ,OAAgB;IAEhB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AACnE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,OAAe;IAC3C,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AACrC,CAAC"}
@@ -6,7 +6,7 @@ export { createSession, createSessionId, enterRoute, enterStep, mergeCollected,
6
6
  export { render, renderMany, renderTemplate, renderTemplateObject, formatKnowledgeBase, } from "./template";
7
7
  export { cloneDeep } from "./clone";
8
8
  export { getLastMessageFromHistory } from "./event";
9
- export { normalizeHistory, userMessage, assistantMessage, toolMessage, systemMessage, } from "./history";
9
+ export { normalizeHistory, historyItemToEvent, historyToEvents, eventToHistoryItem, eventsToHistory, userMessage, assistantMessage, toolMessage, systemMessage, } from "./history";
10
10
  export { LoggerLevel, logger } from "./logger";
11
11
  export type { RetryOptions } from "./retry";
12
12
  export { retry, withTimeoutAndRetry } from "./retry";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EACL,eAAe,EACf,cAAc,EACd,cAAc,EACd,oBAAoB,GACrB,MAAM,MAAM,CAAC;AAGd,OAAO,EACL,aAAa,EACb,eAAe,EACf,UAAU,EACV,SAAS,EACT,cAAc,EACd,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,WAAW,CAAC;AAGnB,OAAO,EACL,MAAM,EACN,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAGpC,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAGpD,OAAO,EACL,gBAAgB,EAChB,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,aAAa,GACd,MAAM,WAAW,CAAC;AAGnB,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAG/C,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EACL,eAAe,EACf,cAAc,EACd,cAAc,EACd,oBAAoB,GACrB,MAAM,MAAM,CAAC;AAGd,OAAO,EACL,aAAa,EACb,eAAe,EACf,UAAU,EACV,SAAS,EACT,cAAc,EACd,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,WAAW,CAAC;AAGnB,OAAO,EACL,MAAM,EACN,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAGpC,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAGpD,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,aAAa,GACd,MAAM,WAAW,CAAC;AAGnB,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAG/C,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC"}
@@ -12,7 +12,7 @@ export { cloneDeep } from "./clone";
12
12
  // Event utilities
13
13
  export { getLastMessageFromHistory } from "./event";
14
14
  // History utilities
15
- export { normalizeHistory, userMessage, assistantMessage, toolMessage, systemMessage, } from "./history";
15
+ export { normalizeHistory, historyItemToEvent, historyToEvents, eventToHistoryItem, eventsToHistory, userMessage, assistantMessage, toolMessage, systemMessage, } from "./history";
16
16
  // Logging
17
17
  export { LoggerLevel, logger } from "./logger";
18
18
  export { retry, withTimeoutAndRetry } from "./retry";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,gBAAgB;AAChB,OAAO,EACL,eAAe,EACf,cAAc,EACd,cAAc,EACd,oBAAoB,GACrB,MAAM,MAAM,CAAC;AAEd,qBAAqB;AACrB,OAAO,EACL,aAAa,EACb,eAAe,EACf,UAAU,EACV,SAAS,EACT,cAAc,EACd,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,WAAW,CAAC;AAEnB,qBAAqB;AACrB,OAAO,EACL,MAAM,EACN,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,oBAAoB;AACpB,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEpC,kBAAkB;AAClB,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAEpD,oBAAoB;AACpB,OAAO,EACL,gBAAgB,EAChB,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,aAAa,GACd,MAAM,WAAW,CAAC;AAEnB,UAAU;AACV,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAI/C,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,gBAAgB;AAChB,OAAO,EACL,eAAe,EACf,cAAc,EACd,cAAc,EACd,oBAAoB,GACrB,MAAM,MAAM,CAAC;AAEd,qBAAqB;AACrB,OAAO,EACL,aAAa,EACb,eAAe,EACf,UAAU,EACV,SAAS,EACT,cAAc,EACd,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,WAAW,CAAC;AAEnB,qBAAqB;AACrB,OAAO,EACL,MAAM,EACN,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,oBAAoB;AACpB,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEpC,kBAAkB;AAClB,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC;AAEpD,oBAAoB;AACpB,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,EACf,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,aAAa,GACd,MAAM,WAAW,CAAC;AAEnB,UAAU;AACV,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAI/C,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC"}
package/docs/README.md CHANGED
@@ -58,6 +58,7 @@ Welcome to the `@falai/agent` documentation! This comprehensive framework enable
58
58
 
59
59
  - **[Building Agents](./guides/building-agents/)** - Complete agent construction patterns
60
60
  - **[Advanced Patterns](./guides/advanced-patterns/)** - Complex use cases & integrations
61
+ - **[Migration Guides](./guides/migration/)** - Upgrade guides for major changes
61
62
  - **[API Reference](./api/README.md)** - Complete API documentation
62
63
 
63
64
  ## 🎯 Quick Links
@@ -93,7 +94,7 @@ Welcome to the `@falai/agent` documentation! This comprehensive framework enable
93
94
  - **AI Integration**: [Providers](./core/ai-integration/providers.md) | [Prompts](./core/ai-integration/prompt-composition.md) | [Responses](./core/ai-integration/response-processing.md)
94
95
  - **Tools & Execution**: [Tool Definition](./core/tools/tool-definition.md) | [Tool Execution](./core/tools/tool-execution.md) | [Tool Scoping](./core/tools/tool-scoping.md)
95
96
  - **Persistence**: [Session Storage](./core/persistence/session-storage.md) | [Adapters](./core/persistence/adapters.md)
96
- - **Advanced**: [Building Agents](./guides/building-agents/) | [Patterns](./guides/advanced-patterns/) | [API Reference](./api/)
97
+ - **Advanced**: [Building Agents](./guides/building-agents/) | [Patterns](./guides/advanced-patterns/) | [Migration](./guides/migration/) | [API Reference](./api/)
97
98
 
98
99
  ## 💡 Examples by Domain
99
100
 
@@ -78,6 +78,8 @@ Adds a behavioral guideline. Returns `this` for chaining.
78
78
 
79
79
  Generates an AI response with session step management, tool execution, data extraction, and intelligent routing.
80
80
 
81
+ **Note:** This method now delegates to the internal `ResponseModal` class for improved architecture and maintainability.
82
+
81
83
  **Enhanced Response Pipeline:**
82
84
 
83
85
  1. **Tool Execution** - Execute tools if current step has `tool` (enriches context before AI response)
@@ -454,6 +456,8 @@ See also: [Custom Database Integration Example](../examples/custom-database-pers
454
456
 
455
457
  Generates an AI response as a real-time stream for better user experience. Provides the same structured output as `respond()` but delivers it incrementally.
456
458
 
459
+ **Note:** This method now delegates to the internal `ResponseModal` class for improved architecture and maintainability.
460
+
457
461
  ```typescript
458
462
  interface StreamChunk {
459
463
  /** The incremental text delta */
@@ -515,6 +519,68 @@ for await (const chunk of agent.respondStream({ history, session })) {
515
519
  }
516
520
  ```
517
521
 
522
+ ##### `stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>`
523
+
524
+ **NEW:** Modern streaming API that provides a simple interface similar to `chat()` but returns a stream. This is the recommended way to implement streaming responses.
525
+
526
+ ```typescript
527
+ interface StreamOptions<TContext = unknown> {
528
+ contextOverride?: Partial<TContext>;
529
+ signal?: AbortSignal;
530
+ history?: History; // Optional: override session history
531
+ }
532
+ ```
533
+
534
+ **Key Features:**
535
+
536
+ - 🎯 **Simple Interface**: Just `agent.stream("message")` - no complex parameters
537
+ - 🔄 **Automatic Session Management**: Handles conversation history automatically
538
+ - 🌊 **Real-time Streaming**: Same performance as `respondStream()` but easier to use
539
+ - 🛑 **Cancellable**: Supports AbortSignal for cancellation
540
+
541
+ **Example:**
542
+
543
+ ```typescript
544
+ // Simple streaming - automatically manages session history
545
+ for await (const chunk of agent.stream("Hello, how are you?")) {
546
+ if (chunk.delta) {
547
+ process.stdout.write(chunk.delta);
548
+ }
549
+
550
+ if (chunk.done) {
551
+ console.log("\n✅ Stream complete!");
552
+ // Session history is automatically updated
553
+ }
554
+ }
555
+
556
+ // With cancellation
557
+ const controller = new AbortController();
558
+ setTimeout(() => controller.abort(), 5000); // Cancel after 5s
559
+
560
+ for await (const chunk of agent.stream("Tell me a long story", {
561
+ signal: controller.signal
562
+ })) {
563
+ process.stdout.write(chunk.delta);
564
+ }
565
+ ```
566
+
567
+ **Migration from `respondStream()`:**
568
+
569
+ ```typescript
570
+ // Old way (still supported)
571
+ for await (const chunk of agent.respondStream({
572
+ history: agent.session.getHistory(),
573
+ session: await agent.session.getOrCreate()
574
+ })) {
575
+ // Handle chunk
576
+ }
577
+
578
+ // New way (recommended)
579
+ for await (const chunk of agent.stream("Your message")) {
580
+ // Handle chunk - session management is automatic
581
+ }
582
+ ```
583
+
518
584
  **With Cancellation:**
519
585
 
520
586
  ```typescript
@@ -582,6 +648,100 @@ Agent's identity template (readonly).
582
648
 
583
649
  ---
584
650
 
651
+ ### `ResponseModal<TContext, TData>`
652
+
653
+ **NEW:** Internal class that handles all response generation logic for the Agent. This class centralizes response processing, provides unified streaming and non-streaming APIs, and improves maintainability.
654
+
655
+ **Note:** This class is primarily used internally by the Agent class. Most users should use the Agent's response methods (`respond`, `respondStream`, `stream`, `chat`) rather than accessing ResponseModal directly.
656
+
657
+ #### Constructor
658
+
659
+ ```typescript
660
+ new ResponseModal<TContext, TData>(
661
+ agent: Agent<TContext, TData>,
662
+ options?: ResponseModalOptions
663
+ )
664
+
665
+ interface ResponseModalOptions {
666
+ /** Maximum number of tool loops allowed during response generation */
667
+ maxToolLoops?: number;
668
+ /** Enable automatic session saving after response generation */
669
+ enableAutoSave?: boolean;
670
+ /** Enable debug mode for detailed logging */
671
+ debugMode?: boolean;
672
+ }
673
+ ```
674
+
675
+ #### Methods
676
+
677
+ ##### `respond(params: RespondParams<TContext, TData>): Promise<AgentResponse<TData>>`
678
+
679
+ Generates a non-streaming response using unified logic. This method consolidates all response generation logic including routing, tool execution, and data collection.
680
+
681
+ ##### `respondStream(params: RespondParams<TContext, TData>): AsyncGenerator<AgentResponseStreamChunk<TData>>`
682
+
683
+ Generates a streaming response using unified logic. Provides the same functionality as `respond()` but delivers results incrementally.
684
+
685
+ ##### `stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>`
686
+
687
+ Modern streaming API with automatic session management. This is the recommended way to implement streaming responses.
688
+
689
+ ```typescript
690
+ // Simple usage
691
+ for await (const chunk of responseModal.stream("Hello")) {
692
+ console.log(chunk.delta);
693
+ }
694
+
695
+ // With options
696
+ for await (const chunk of responseModal.stream("Hello", {
697
+ contextOverride: { userId: "123" },
698
+ signal: abortController.signal
699
+ })) {
700
+ console.log(chunk.delta);
701
+ }
702
+ ```
703
+
704
+ ##### `generate(message?: string, options?: GenerateOptions<TContext>): Promise<AgentResponse<TData>>`
705
+
706
+ Modern non-streaming API equivalent to `chat()` but more explicit. Provides automatic session management for non-streaming responses.
707
+
708
+ ```typescript
709
+ // Simple usage
710
+ const response = await responseModal.generate("Hello");
711
+ console.log(response.message);
712
+
713
+ // With options
714
+ const response = await responseModal.generate("Hello", {
715
+ contextOverride: { userId: "123" }
716
+ });
717
+ ```
718
+
719
+ #### Error Handling
720
+
721
+ ResponseModal includes comprehensive error handling with the `ResponseGenerationError` class:
722
+
723
+ ```typescript
724
+ try {
725
+ const response = await responseModal.respond(params);
726
+ } catch (error) {
727
+ if (ResponseGenerationError.isResponseGenerationError(error)) {
728
+ console.log("Response generation failed:", error.message);
729
+ console.log("Phase:", error.details?.phase);
730
+ console.log("Original error:", error.details?.originalError);
731
+ }
732
+ }
733
+ ```
734
+
735
+ #### Architecture Benefits
736
+
737
+ - **Separation of Concerns**: Agent focuses on configuration and orchestration, ResponseModal handles response generation
738
+ - **Unified Logic**: Both streaming and non-streaming responses use the same underlying logic
739
+ - **Modern APIs**: Provides simple `stream()` and `generate()` methods alongside legacy compatibility
740
+ - **Error Handling**: Comprehensive error handling with detailed context
741
+ - **Performance**: Optimized response pipeline with minimal duplication
742
+
743
+ ---
744
+
585
745
  ### `Route`
586
746
 
587
747
  Represents a conversation flow with steps and transitions.
@@ -6,6 +6,7 @@ Complete API documentation for `@falai/agent`. This framework provides a strongl
6
6
 
7
7
  - [Core Classes](#core-classes)
8
8
  - [Agent](#agent)
9
+ - [ResponseModal](#responsemodal)
9
10
  - [Route](#route)
10
11
  - [Step](#step)
11
12
  - [RoutingEngine](#routingengine)
@@ -117,7 +118,20 @@ respondStream(params: {
117
118
  }>
118
119
  ```
119
120
 
120
- Generates a streaming response with real-time updates.
121
+ Generates a streaming response with real-time updates. **Note:** Now delegates to internal ResponseModal class.
122
+
123
+ ```typescript
124
+ stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>
125
+ ```
126
+
127
+ **NEW:** Modern streaming API with automatic session management. Recommended for new implementations.
128
+
129
+ ```typescript
130
+ // Simple streaming
131
+ for await (const chunk of agent.stream("Hello")) {
132
+ console.log(chunk.delta);
133
+ }
134
+ ```
121
135
 
122
136
  ##### Tool Management
123
137
 
@@ -168,6 +182,57 @@ hasPersistence(): boolean
168
182
 
169
183
  ---
170
184
 
185
+ ### ResponseModal
186
+
187
+ **NEW:** Internal class that centralizes all response generation logic for improved architecture and maintainability.
188
+
189
+ #### Constructor
190
+
191
+ ```typescript
192
+ new ResponseModal<TContext = unknown, TData = unknown>(
193
+ agent: Agent<TContext, TData>,
194
+ options?: ResponseModalOptions
195
+ )
196
+ ```
197
+
198
+ #### Methods
199
+
200
+ ##### Modern APIs (Recommended)
201
+
202
+ ```typescript
203
+ stream(message?: string, options?: StreamOptions<TContext>): AsyncGenerator<AgentResponseStreamChunk<TData>>
204
+ generate(message?: string, options?: GenerateOptions<TContext>): Promise<AgentResponse<TData>>
205
+ ```
206
+
207
+ Modern streaming and non-streaming APIs with automatic session management.
208
+
209
+ ##### Legacy APIs (Backward Compatible)
210
+
211
+ ```typescript
212
+ respond(params: RespondParams<TContext, TData>): Promise<AgentResponse<TData>>
213
+ respondStream(params: RespondParams<TContext, TData>): AsyncGenerator<AgentResponseStreamChunk<TData>>
214
+ ```
215
+
216
+ Legacy APIs that maintain full backward compatibility with existing code.
217
+
218
+ ##### Error Handling
219
+
220
+ ```typescript
221
+ ResponseGenerationError: Error class for response-specific errors
222
+ ```
223
+
224
+ Comprehensive error handling with detailed context and phase information.
225
+
226
+ #### Key Features
227
+
228
+ - **Unified Logic**: Both streaming and non-streaming use the same underlying logic
229
+ - **Modern APIs**: Simple `stream()` and `generate()` methods for new code
230
+ - **Backward Compatibility**: Existing `respond()` and `respondStream()` methods work unchanged
231
+ - **Error Handling**: Detailed error context with phase and original error information
232
+ - **Performance**: Optimized response pipeline with minimal code duplication
233
+
234
+ ---
235
+
171
236
  ### Route
172
237
 
173
238
  Represents a conversational journey with required fields specification and steps that collect data into the agent-level schema.