@codebolt/codeboltjs 2.0.16 → 2.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 (94) hide show
  1. package/dist/core/Codebolt.d.ts +49 -54
  2. package/dist/core/messageManager.d.ts +0 -1
  3. package/dist/modules/chat.d.ts +1 -1
  4. package/dist/modules/codeparsers.js +24 -15
  5. package/dist/modules/codeutils.js +19 -9
  6. package/dist/modules/mcp.d.ts +1 -2
  7. package/dist/modules/mcp.js +2 -0
  8. package/dist/modules/task.d.ts +1 -1
  9. package/dist/modules/terminal.d.ts +0 -1
  10. package/dist/notificationfunctions/agent.js +4 -4
  11. package/dist/notificationfunctions/browser.js +5 -5
  12. package/dist/notificationfunctions/chat.js +5 -5
  13. package/dist/notificationfunctions/codeutils.js +5 -5
  14. package/dist/notificationfunctions/crawler.js +5 -5
  15. package/dist/notificationfunctions/dbmemory.js +5 -5
  16. package/dist/notificationfunctions/fs.js +23 -23
  17. package/dist/notificationfunctions/git.js +25 -25
  18. package/dist/notificationfunctions/history.js +5 -5
  19. package/dist/notificationfunctions/llm.js +5 -5
  20. package/dist/notificationfunctions/mcp.js +9 -9
  21. package/dist/notificationfunctions/search.js +7 -7
  22. package/dist/notificationfunctions/system.js +3 -3
  23. package/dist/notificationfunctions/terminal.js +3 -3
  24. package/dist/notificationfunctions/todo.js +7 -7
  25. package/dist/notificationfunctions/utils.js +8 -8
  26. package/dist/types/InternalTypes.d.ts +0 -3
  27. package/dist/types/commonTypes.d.ts +2 -2
  28. package/dist/types/socketMessageTypes.d.ts +0 -2
  29. package/dist/types/socketMessageTypes.js +6 -7
  30. package/package.json +20 -26
  31. package/dist/agentlib/agent.d.ts +0 -86
  32. package/dist/agentlib/agent.js +0 -326
  33. package/dist/agentlib/followupquestionbuilder.d.ts +0 -75
  34. package/dist/agentlib/followupquestionbuilder.js +0 -193
  35. package/dist/agentlib/llmoutputhandler.d.ts +0 -102
  36. package/dist/agentlib/llmoutputhandler.js +0 -451
  37. package/dist/agentlib/promptbuilder.d.ts +0 -382
  38. package/dist/agentlib/promptbuilder.js +0 -805
  39. package/dist/agentlib/systemprompt.d.ts +0 -20
  40. package/dist/agentlib/systemprompt.js +0 -48
  41. package/dist/agentlib/taskInstruction.d.ts +0 -37
  42. package/dist/agentlib/taskInstruction.js +0 -57
  43. package/dist/agentlib/usermessage.d.ts +0 -70
  44. package/dist/agentlib/usermessage.js +0 -124
  45. package/dist/utils/docutils.d.ts +0 -9
  46. package/dist/utils/docutils.js +0 -69
  47. package/dist/utils/mcpServer.d.ts +0 -481
  48. package/dist/utils/mcpServer.js +0 -779
  49. package/dist/utils/parse-source-code/index.d.ts +0 -9
  50. package/dist/utils/parse-source-code/index.js +0 -233
  51. package/dist/utils/parse-source-code/languageParser.d.ts +0 -2
  52. package/dist/utils/parse-source-code/languageParser.js +0 -137
  53. package/dist/utils/parse-source-code/queries/c-sharp.d.ts +0 -2
  54. package/dist/utils/parse-source-code/queries/c-sharp.js +0 -25
  55. package/dist/utils/parse-source-code/queries/c.d.ts +0 -2
  56. package/dist/utils/parse-source-code/queries/c.js +0 -17
  57. package/dist/utils/parse-source-code/queries/cpp.d.ts +0 -2
  58. package/dist/utils/parse-source-code/queries/cpp.js +0 -25
  59. package/dist/utils/parse-source-code/queries/go.d.ts +0 -2
  60. package/dist/utils/parse-source-code/queries/go.js +0 -29
  61. package/dist/utils/parse-source-code/queries/index.d.ts +0 -12
  62. package/dist/utils/parse-source-code/queries/index.js +0 -30
  63. package/dist/utils/parse-source-code/queries/java.d.ts +0 -2
  64. package/dist/utils/parse-source-code/queries/java.js +0 -17
  65. package/dist/utils/parse-source-code/queries/javascript.d.ts +0 -2
  66. package/dist/utils/parse-source-code/queries/javascript.js +0 -67
  67. package/dist/utils/parse-source-code/queries/php.d.ts +0 -2
  68. package/dist/utils/parse-source-code/queries/php.js +0 -17
  69. package/dist/utils/parse-source-code/queries/python.d.ts +0 -2
  70. package/dist/utils/parse-source-code/queries/python.js +0 -13
  71. package/dist/utils/parse-source-code/queries/ruby.d.ts +0 -2
  72. package/dist/utils/parse-source-code/queries/ruby.js +0 -54
  73. package/dist/utils/parse-source-code/queries/rust.d.ts +0 -2
  74. package/dist/utils/parse-source-code/queries/rust.js +0 -18
  75. package/dist/utils/parse-source-code/queries/swift.d.ts +0 -2
  76. package/dist/utils/parse-source-code/queries/swift.js +0 -47
  77. package/dist/utils/parse-source-code/queries/typescript.d.ts +0 -2
  78. package/dist/utils/parse-source-code/queries/typescript.js +0 -34
  79. package/dist/utils/parse-source-code/tree-sitter-c.wasm +0 -0
  80. package/dist/utils/parse-source-code/tree-sitter-c_sharp.wasm +0 -0
  81. package/dist/utils/parse-source-code/tree-sitter-cpp.wasm +0 -0
  82. package/dist/utils/parse-source-code/tree-sitter-go.wasm +0 -0
  83. package/dist/utils/parse-source-code/tree-sitter-java.wasm +0 -0
  84. package/dist/utils/parse-source-code/tree-sitter-javascript.wasm +0 -0
  85. package/dist/utils/parse-source-code/tree-sitter-php.wasm +0 -0
  86. package/dist/utils/parse-source-code/tree-sitter-python.wasm +0 -0
  87. package/dist/utils/parse-source-code/tree-sitter-ruby.wasm +0 -0
  88. package/dist/utils/parse-source-code/tree-sitter-rust.wasm +0 -0
  89. package/dist/utils/parse-source-code/tree-sitter-swift.wasm +0 -0
  90. package/dist/utils/parse-source-code/tree-sitter-tsx.wasm +0 -0
  91. package/dist/utils/parse-source-code/tree-sitter-typescript.wasm +0 -0
  92. package/dist/utils/parse-source-code/tree-sitter.wasm +0 -0
  93. package/dist/utils.d.ts +0 -9
  94. package/dist/utils.js +0 -24
@@ -1,326 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Agent = void 0;
7
- const chat_1 = __importDefault(require("../modules/chat"));
8
- const mcp_1 = __importDefault(require("../modules/mcp"));
9
- const llm_1 = __importDefault(require("../modules/llm"));
10
- const agent_1 = __importDefault(require("../modules/agent"));
11
- // All interfaces moved to libFunctionTypes.ts
12
- /**
13
- * Agent class that manages conversations with LLMs and tool executions.
14
- * Handles the conversation flow, tool calls, and task completions.
15
- */
16
- class Agent {
17
- /**
18
- * Creates a new Agent instance.
19
- *
20
- * @param tools - The tools available to the agent
21
- * @param systemPrompt - The system prompt providing instructions to the LLM
22
- * @param maxRun - Maximum number of conversation turns (0 means unlimited)
23
- */
24
- constructor(tools = [], systemPrompt, maxRun = 0) {
25
- this.tools = tools;
26
- this.userMessage = [];
27
- this.apiConversationHistory = [];
28
- this.maxRun = maxRun;
29
- this.systemPrompt = systemPrompt;
30
- }
31
- /**
32
- * Runs the agent on a specific task until completion or max runs reached.
33
- *
34
- * @param task - The task instruction to be executed
35
- * @param successCondition - Optional function to determine if the task is successful
36
- * @returns Promise with success status, error (if any), and the last assistant message
37
- */
38
- async run(task, successCondition = () => true) {
39
- var _a, _b;
40
- let mentaionedMCPSTool = await task.userMessage.getMentionedMcpsTools();
41
- this.tools = [
42
- ...this.tools,
43
- ...mentaionedMCPSTool || [],
44
- ];
45
- let mentionedAgents = await task.userMessage.getMentionedAgents();
46
- // Transform agents into tool format
47
- const agentTools = mentionedAgents.map(agent => {
48
- return {
49
- type: "function",
50
- function: {
51
- name: `subagent--${agent.unique_id}`,
52
- description: agent.longDescription || agent.description,
53
- parameters: {
54
- type: "object",
55
- properties: {
56
- task: {
57
- type: "string",
58
- description: "The task to be executed by the tool."
59
- }
60
- },
61
- required: ["task"]
62
- }
63
- }
64
- };
65
- });
66
- this.tools = this.tools.concat(agentTools);
67
- let completed = false;
68
- let userMessages = await task.toPrompt();
69
- this.apiConversationHistory.push({ role: "user", content: userMessages });
70
- let runcomplete = 0;
71
- while (!completed && (runcomplete <= this.maxRun || this.maxRun === 0)) {
72
- try {
73
- runcomplete++;
74
- const response = await this.attemptLlmRequest(this.apiConversationHistory, this.tools);
75
- let isMessagePresentinReply = false;
76
- for (const contentBlock of response.choices) {
77
- if (contentBlock.message) {
78
- isMessagePresentinReply = true;
79
- this.apiConversationHistory.push(contentBlock.message);
80
- if (contentBlock.message.content != null) {
81
- await chat_1.default.sendMessage(contentBlock.message.content, {});
82
- }
83
- }
84
- }
85
- if (!isMessagePresentinReply) {
86
- this.apiConversationHistory.push({
87
- role: "assistant",
88
- content: [{ type: "text", text: "Failure: I did not provide a response." }],
89
- });
90
- }
91
- try {
92
- let toolResults = [];
93
- let taskCompletedBlock;
94
- let userRejectedToolUse = false;
95
- const contentBlock = response.choices[0];
96
- if ((_a = contentBlock.message) === null || _a === void 0 ? void 0 : _a.tool_calls) {
97
- for (const tool of contentBlock.message.tool_calls) {
98
- try {
99
- const { toolInput, toolName, toolUseId } = this.getToolDetail(tool);
100
- if (!userRejectedToolUse) {
101
- if (toolName.includes("attempt_completion")) {
102
- taskCompletedBlock = tool;
103
- }
104
- else {
105
- let [serverName] = toolName.replace('--', ':').split(':');
106
- if (serverName == 'subagent') {
107
- const agentResponse = await agent_1.default.startAgent(toolName.replace("subagent--", ''), toolInput.task);
108
- const [didUserReject, result] = [false, "tool result is successful"];
109
- let toolResult = this.getToolResult(toolUseId, result);
110
- toolResults.push({
111
- role: "tool",
112
- tool_call_id: toolResult.tool_call_id,
113
- content: toolResult.content,
114
- });
115
- if (toolResult.userMessage) {
116
- this.nextUserMessage = {
117
- role: "user",
118
- content: toolResult.userMessage
119
- };
120
- }
121
- if (didUserReject) {
122
- userRejectedToolUse = true;
123
- }
124
- }
125
- else {
126
- const [didUserReject, result] = await this.executeTool(toolName, toolInput);
127
- // toolResults.push(this.getToolResult(toolUseId, result));
128
- let toolResult = this.getToolResult(toolUseId, result);
129
- toolResults.push({
130
- role: "tool",
131
- tool_call_id: toolResult.tool_call_id,
132
- content: toolResult.content,
133
- });
134
- if (toolResult.userMessage) {
135
- this.nextUserMessage = {
136
- role: "user",
137
- content: toolResult.userMessage
138
- };
139
- }
140
- if (didUserReject) {
141
- userRejectedToolUse = true;
142
- }
143
- }
144
- }
145
- }
146
- else {
147
- let toolResult = this.getToolResult(toolUseId, "Skipping tool execution due to previous tool user rejection.");
148
- toolResults.push({
149
- role: "tool",
150
- tool_call_id: toolResult.tool_call_id,
151
- content: toolResult.content,
152
- });
153
- if (toolResult.userMessage) {
154
- this.nextUserMessage = {
155
- role: "user",
156
- content: toolResult.userMessage
157
- };
158
- }
159
- }
160
- }
161
- catch (error) {
162
- toolResults.push({
163
- role: "tool",
164
- tool_call_id: tool.id,
165
- content: `please provide valid json string for tool.function.arguments String(error)`,
166
- });
167
- }
168
- }
169
- }
170
- if (taskCompletedBlock) {
171
- let [_, result] = await this.executeTool(taskCompletedBlock.function.name, JSON.parse(taskCompletedBlock.function.arguments || "{}"));
172
- if (result === "") {
173
- completed = true;
174
- result = "The user is satisfied with the result.";
175
- }
176
- let toolResult = this.getToolResult(taskCompletedBlock.id, result);
177
- toolResults.push({
178
- role: "tool",
179
- tool_call_id: toolResult.tool_call_id,
180
- content: toolResult.content,
181
- });
182
- if (toolResult.userMessage) {
183
- this.nextUserMessage = {
184
- role: "user",
185
- content: toolResult.userMessage
186
- };
187
- }
188
- }
189
- this.apiConversationHistory.push(...toolResults);
190
- if (this.nextUserMessage) {
191
- this.apiConversationHistory.push(this.nextUserMessage);
192
- }
193
- let nextUserMessage = toolResults;
194
- if (toolResults.length === 0) {
195
- nextUserMessage = [{
196
- role: "user",
197
- content: [{
198
- type: "text",
199
- text: "If you have completed the user's task, use the attempt_completion tool. If you require additional information from the user, use the ask_followup_question tool. Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task. (This is an automated message, so do not respond to it conversationally.)"
200
- }]
201
- }];
202
- if (nextUserMessage) {
203
- this.apiConversationHistory.push(nextUserMessage[0]);
204
- }
205
- }
206
- }
207
- catch (error) {
208
- console.error("Error in agent tool call:", error);
209
- return { success: false, error: error instanceof Error ? error.message : String(error), message: null };
210
- }
211
- }
212
- catch (error) {
213
- console.error("Error in agent tool call:", error);
214
- return { success: false, error: error instanceof Error ? error.message : String(error), message: null };
215
- }
216
- }
217
- return {
218
- success: completed,
219
- error: null,
220
- message: ((_b = this.apiConversationHistory
221
- .filter(msg => msg.role === 'assistant')
222
- .pop()) === null || _b === void 0 ? void 0 : _b.content) || ''
223
- };
224
- }
225
- /**
226
- * Attempts to make a request to the LLM with conversation history and tools.
227
- *
228
- * @param apiConversationHistory - The current conversation history
229
- * @param tools - The tools available to the LLM
230
- * @returns Promise with the LLM response
231
- */
232
- async attemptLlmRequest(apiConversationHistory, tools) {
233
- try {
234
- let systemPrompt = await this.systemPrompt.toPromptText();
235
- const aiMessages = [
236
- { role: "system", content: systemPrompt },
237
- ...apiConversationHistory,
238
- ];
239
- const createParams = {
240
- full: true,
241
- messages: aiMessages,
242
- tools: tools,
243
- tool_choice: "auto",
244
- };
245
- //@ts-ignore
246
- const { completion } = await llm_1.default.inference(createParams);
247
- return completion;
248
- }
249
- catch (error) {
250
- return this.attemptApiRequest();
251
- }
252
- }
253
- /**
254
- * Executes a tool with given name and input.
255
- *
256
- * @param toolName - The name of the tool to execute
257
- * @param toolInput - The input parameters for the tool
258
- * @returns Promise with tuple [userRejected, result]
259
- */
260
- async executeTool(toolName, toolInput) {
261
- //codebolttools--readfile
262
- const [toolboxName, actualToolName] = toolName.split('--');
263
- console.log("Toolbox name: ", toolboxName, "Actual tool name: ", actualToolName);
264
- const { data } = await mcp_1.default.executeTool(toolboxName, actualToolName, toolInput);
265
- console.log("Tool result: ", data);
266
- return data;
267
- }
268
- /**
269
- * Starts a sub-agent to handle a specific task.
270
- *
271
- * @param agentName - The name of the sub-agent to start
272
- * @param params - Parameters for the sub-agent
273
- * @returns Promise with tuple [userRejected, result]
274
- */
275
- async startSubAgent(agentName, params) {
276
- return [false, await agent_1.default.startAgent(agentName, params.task)];
277
- }
278
- /**
279
- * Extracts tool details from a tool call object.
280
- *
281
- * @param tool - The tool call object from the LLM response
282
- * @returns ToolDetails object with name, input, and ID
283
- */
284
- getToolDetail(tool) {
285
- return {
286
- toolName: tool.function.name,
287
- toolInput: JSON.parse(tool.function.arguments || "{}"),
288
- toolUseId: tool.id
289
- };
290
- }
291
- /**
292
- * Creates a tool result object from the tool execution response.
293
- *
294
- * @param tool_call_id - The ID of the tool call
295
- * @param content - The content returned by the tool
296
- * @returns ToolResult object
297
- */
298
- getToolResult(tool_call_id, content) {
299
- let userMessage = undefined;
300
- try {
301
- let parsed = JSON.parse(content);
302
- if (parsed.payload && parsed.payload.content) {
303
- content = `The browser action has been executed. The screenshot have been captured for your analysis. The tool response is provided in the next user message`;
304
- // this.apiConversationHistory.push()
305
- userMessage = parsed.payload.content;
306
- }
307
- }
308
- catch (error) {
309
- }
310
- return {
311
- role: "tool",
312
- tool_call_id,
313
- content,
314
- userMessage
315
- };
316
- }
317
- /**
318
- * Fallback method for API requests in case of failures.
319
- *
320
- * @throws Error API request fallback not implemented
321
- */
322
- attemptApiRequest() {
323
- throw new Error("API request fallback not implemented");
324
- }
325
- }
326
- exports.Agent = Agent;
@@ -1,75 +0,0 @@
1
- import type { OpenAIMessage, OpenAITool, ToolResult, CodeboltAPI } from "../types/libFunctionTypes";
2
- /**
3
- * Builds follow-up prompts for continuing conversations with tool results.
4
- * Manages conversation history and summarization when conversations get too long.
5
- */
6
- declare class FollowUpPromptBuilder {
7
- /** Previous conversation messages */
8
- private previousConversation;
9
- /** Tool results to add to the conversation */
10
- private toolResults;
11
- /** Available tools for the conversation */
12
- private tools;
13
- /** The last LLM response, if available */
14
- private llmResponse?;
15
- /** Maximum conversation length before summarization */
16
- private maxConversationLength;
17
- /** Whether to force summarization */
18
- private forceSummarization;
19
- /** Codebolt API instance */
20
- private codebolt?;
21
- /**
22
- * Creates a new FollowUpQuestionBuilder instance.
23
- *
24
- * @param codebolt - Optional codebolt API instance
25
- */
26
- constructor(codebolt?: CodeboltAPI);
27
- /**
28
- * Adds the previous conversation to the builder.
29
- *
30
- * @param previousPrompt - The previous prompt object containing messages and tools
31
- * @returns The FollowUpQuestionBuilder instance for chaining
32
- */
33
- addPreviousConversation(previousPrompt: {
34
- messages: OpenAIMessage[];
35
- tools: OpenAITool[];
36
- tool_choice?: string;
37
- }, llmResponse: {
38
- completion: any;
39
- }): this;
40
- addLLMResponseToConverstaion(llmResponse: {
41
- completion: any;
42
- }): this;
43
- /**
44
- * Adds tool execution results to the conversation.
45
- *
46
- * @param toolResults - Array of tool execution results
47
- * @returns The FollowUpQuestionBuilder instance for chaining
48
- */
49
- addToolResult(toolResults: ToolResult[]): this;
50
- /**
51
- * Checks if the conversation is too long and sets up summarization with custom max length.
52
- *
53
- * @param maxLength - Maximum number of messages before summarization
54
- * @returns The FollowUpQuestionBuilder instance for chaining
55
- */
56
- checkAndSummarizeConversationIfLong(maxLength: number): this;
57
- /**
58
- * Performs conversation summarization if needed.
59
- *
60
- * @returns Promise that resolves to the summarized messages
61
- */
62
- private performSummarization;
63
- /**
64
- * Builds the follow-up conversation prompt with tool results.
65
- *
66
- * @returns Promise that resolves to the conversation prompt object
67
- */
68
- build(): Promise<{
69
- messages: OpenAIMessage[];
70
- tools: OpenAITool[];
71
- tool_choice: "auto";
72
- full: boolean;
73
- }>;
74
- }
75
- export { FollowUpPromptBuilder };
@@ -1,193 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FollowUpPromptBuilder = void 0;
4
- const history_1 = require("../modules/history");
5
- /**
6
- * Builds follow-up prompts for continuing conversations with tool results.
7
- * Manages conversation history and summarization when conversations get too long.
8
- */
9
- class FollowUpPromptBuilder {
10
- /**
11
- * Creates a new FollowUpQuestionBuilder instance.
12
- *
13
- * @param codebolt - Optional codebolt API instance
14
- */
15
- constructor(codebolt) {
16
- /** Previous conversation messages */
17
- this.previousConversation = [];
18
- /** Tool results to add to the conversation */
19
- this.toolResults = [];
20
- /** Available tools for the conversation */
21
- this.tools = [];
22
- /** Maximum conversation length before summarization */
23
- this.maxConversationLength = 50;
24
- /** Whether to force summarization */
25
- this.forceSummarization = false;
26
- this.codebolt = codebolt;
27
- }
28
- /**
29
- * Adds the previous conversation to the builder.
30
- *
31
- * @param previousPrompt - The previous prompt object containing messages and tools
32
- * @returns The FollowUpQuestionBuilder instance for chaining
33
- */
34
- addPreviousConversation(previousPrompt, llmResponse) {
35
- this.previousConversation = [...previousPrompt.messages];
36
- this.tools = [...previousPrompt.tools];
37
- try {
38
- // Resolve the response if it's a promise
39
- const resolvedResponse = llmResponse;
40
- if (!resolvedResponse || !resolvedResponse.completion) {
41
- console.warn("Invalid LLM response provided");
42
- return this;
43
- }
44
- const completion = resolvedResponse.completion;
45
- let assistantMessage = null;
46
- // Handle different response formats
47
- if (completion.choices && completion.choices.length > 0) {
48
- // OpenAI-style response with choices
49
- const choice = completion.choices[0];
50
- if (choice.message) {
51
- assistantMessage = {
52
- role: "assistant",
53
- content: choice.message.content || "",
54
- tool_calls: choice.message.tool_calls || undefined
55
- };
56
- }
57
- }
58
- else if (completion.content) {
59
- // Direct content response
60
- assistantMessage = {
61
- role: "assistant",
62
- content: completion.content
63
- };
64
- }
65
- else if (completion.message) {
66
- // Message format response
67
- assistantMessage = {
68
- role: "assistant",
69
- content: completion.message.content || "",
70
- tool_calls: completion.message.tool_calls || undefined
71
- };
72
- }
73
- // Add the assistant message to conversation history
74
- if (assistantMessage) {
75
- this.previousConversation.push(assistantMessage);
76
- }
77
- else {
78
- // Fallback for cases where no valid message is found
79
- this.previousConversation.push({
80
- role: "assistant",
81
- content: "I apologize, but I was unable to provide a proper response."
82
- });
83
- }
84
- }
85
- catch (error) {
86
- console.error("Error adding LLM response to conversation:", error);
87
- // Add error message to conversation history
88
- this.previousConversation.push({
89
- role: "assistant",
90
- content: "An error occurred while processing my response."
91
- });
92
- }
93
- return this;
94
- }
95
- addLLMResponseToConverstaion(llmResponse) {
96
- return this;
97
- }
98
- /**
99
- * Adds tool execution results to the conversation.
100
- *
101
- * @param toolResults - Array of tool execution results
102
- * @returns The FollowUpQuestionBuilder instance for chaining
103
- */
104
- addToolResult(toolResults) {
105
- toolResults.forEach(toolResult => {
106
- this.previousConversation.push(toolResult);
107
- });
108
- if (!toolResults.length) {
109
- this.previousConversation.push({
110
- role: "user",
111
- content: [{
112
- type: "text",
113
- text: "If you have completed the user's task, use the attempt_completion tool. If you require additional information from the user, use the ask_followup_question tool. Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task. (This is an automated message, so do not respond to it conversationally.)"
114
- }]
115
- });
116
- }
117
- return this;
118
- }
119
- /**
120
- * Checks if the conversation is too long and sets up summarization with custom max length.
121
- *
122
- * @param maxLength - Maximum number of messages before summarization
123
- * @returns The FollowUpQuestionBuilder instance for chaining
124
- */
125
- checkAndSummarizeConversationIfLong(maxLength) {
126
- this.maxConversationLength = maxLength;
127
- this.forceSummarization = this.previousConversation.length > maxLength;
128
- return this;
129
- }
130
- /**
131
- * Performs conversation summarization if needed.
132
- *
133
- * @returns Promise that resolves to the summarized messages
134
- */
135
- async performSummarization() {
136
- const shouldSummarize = this.forceSummarization ||
137
- this.previousConversation.length > this.maxConversationLength;
138
- if (!shouldSummarize) {
139
- return this.previousConversation;
140
- }
141
- try {
142
- console.log("Summarizing conversation due to length:", this.previousConversation.length);
143
- // Convert OpenAI messages to the format expected by chatSummary
144
- const messagesToSummarize = this.previousConversation.map(msg => ({
145
- role: msg.role,
146
- content: typeof msg.content === 'string' ? msg.content :
147
- Array.isArray(msg.content) ? msg.content.map(c => c.text).join(' ') :
148
- String(msg.content)
149
- }));
150
- // Use the chat summary service to summarize the conversation
151
- const summaryResponse = await history_1.chatSummary.summarize(messagesToSummarize, Math.floor(this.maxConversationLength / 2));
152
- if (summaryResponse.payload || summaryResponse.summary) {
153
- const summaryText = summaryResponse.payload || summaryResponse.summary || '';
154
- // Keep the system message if it exists, and replace the rest with summary
155
- const systemMessage = this.previousConversation.find(msg => msg.role === 'system');
156
- const summarizedMessages = [];
157
- if (systemMessage) {
158
- summarizedMessages.push(systemMessage);
159
- }
160
- // Add the summary as a system message
161
- summarizedMessages.push({
162
- role: 'system',
163
- content: `Previous conversation summary: ${summaryText}`
164
- });
165
- // Keep the last few messages for context
166
- const recentMessages = this.previousConversation.slice(-5);
167
- summarizedMessages.push(...recentMessages);
168
- return summarizedMessages;
169
- }
170
- }
171
- catch (error) {
172
- console.error("Error summarizing conversation:", error);
173
- }
174
- // If summarization fails, just return the original conversation
175
- return this.previousConversation;
176
- }
177
- /**
178
- * Builds the follow-up conversation prompt with tool results.
179
- *
180
- * @returns Promise that resolves to the conversation prompt object
181
- */
182
- async build() {
183
- // Perform summarization if needed
184
- let messages = this.previousConversation;
185
- return {
186
- messages,
187
- tools: this.tools,
188
- full: true,
189
- tool_choice: "auto"
190
- };
191
- }
192
- }
193
- exports.FollowUpPromptBuilder = FollowUpPromptBuilder;