@codebolt/codeboltjs 2.0.15 → 2.0.17
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/core/Codebolt.d.ts +1 -1
- package/dist/core/messageManager.d.ts +0 -1
- package/dist/core/messageManager.js +4 -2
- package/dist/core/websocket.js +26 -1
- package/dist/modules/mcp.d.ts +1 -2
- package/dist/modules/mcp.js +2 -0
- package/dist/utils.d.ts +0 -7
- package/dist/utils.js +1 -15
- package/package.json +3 -1
- package/dist/agentlib/agent.d.ts +0 -86
- package/dist/agentlib/agent.js +0 -326
- package/dist/agentlib/followupquestionbuilder.d.ts +0 -75
- package/dist/agentlib/followupquestionbuilder.js +0 -193
- package/dist/agentlib/llmoutputhandler.d.ts +0 -102
- package/dist/agentlib/llmoutputhandler.js +0 -451
- package/dist/agentlib/promptbuilder.d.ts +0 -382
- package/dist/agentlib/promptbuilder.js +0 -805
- package/dist/agentlib/systemprompt.d.ts +0 -20
- package/dist/agentlib/systemprompt.js +0 -48
- package/dist/agentlib/taskInstruction.d.ts +0 -37
- package/dist/agentlib/taskInstruction.js +0 -57
- package/dist/agentlib/usermessage.d.ts +0 -70
- package/dist/agentlib/usermessage.js +0 -124
package/dist/core/Codebolt.d.ts
CHANGED
|
@@ -305,7 +305,7 @@ declare class Codebolt {
|
|
|
305
305
|
mcp: {
|
|
306
306
|
getEnabledMCPServers: () => Promise<import("../types/socketMessageTypes").GetEnabledToolBoxesResponse>;
|
|
307
307
|
getLocalMCPServers: () => Promise<import("../types/socketMessageTypes").GetLocalToolBoxesResponse>;
|
|
308
|
-
getMentionedMCPServers: (userMessage:
|
|
308
|
+
getMentionedMCPServers: (userMessage: any) => Promise<import("../types/socketMessageTypes").GetAvailableToolBoxesResponse>;
|
|
309
309
|
searchAvailableMCPServers: (query: string) => Promise<import("../types/socketMessageTypes").SearchAvailableToolBoxesResponse>;
|
|
310
310
|
listMcpFromServers: (toolBoxes: string[]) => Promise<import("../types/socketMessageTypes").ListToolsFromToolBoxesResponse>;
|
|
311
311
|
configureMCPServer: (name: string, config: any) => Promise<import("../types/socketMessageTypes").ConfigureToolBoxResponse>;
|
|
@@ -8,7 +8,6 @@ import type { PendingRequest } from '../types/commonTypes';
|
|
|
8
8
|
export declare class MessageManager extends EventEmitter {
|
|
9
9
|
pendingRequests: Map<string, PendingRequest>;
|
|
10
10
|
websocket: WebSocket | null;
|
|
11
|
-
requestCounter: number;
|
|
12
11
|
/**
|
|
13
12
|
* Initialize the message manager with a WebSocket instance
|
|
14
13
|
*/
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.MessageManager = void 0;
|
|
4
4
|
const events_1 = require("events");
|
|
5
|
+
const uuid_1 = require("uuid");
|
|
5
6
|
/**
|
|
6
7
|
* Centralized message manager for handling WebSocket communications
|
|
7
8
|
*/
|
|
@@ -10,7 +11,6 @@ class MessageManager extends events_1.EventEmitter {
|
|
|
10
11
|
super(...arguments);
|
|
11
12
|
this.pendingRequests = new Map();
|
|
12
13
|
this.websocket = null;
|
|
13
|
-
this.requestCounter = 0;
|
|
14
14
|
}
|
|
15
15
|
/**
|
|
16
16
|
* Initialize the message manager with a WebSocket instance
|
|
@@ -70,7 +70,7 @@ class MessageManager extends events_1.EventEmitter {
|
|
|
70
70
|
reject(new Error('WebSocket is not initialized'));
|
|
71
71
|
return;
|
|
72
72
|
}
|
|
73
|
-
const requestId =
|
|
73
|
+
const requestId = (0, uuid_1.v4)();
|
|
74
74
|
// Add requestId to the message if it doesn't have one
|
|
75
75
|
const messageWithId = { ...message, requestId };
|
|
76
76
|
// Parse multiple message types separated by pipe
|
|
@@ -110,6 +110,8 @@ class MessageManager extends events_1.EventEmitter {
|
|
|
110
110
|
* Send a message without waiting for response
|
|
111
111
|
*/
|
|
112
112
|
send(message) {
|
|
113
|
+
const requestId = (0, uuid_1.v4)();
|
|
114
|
+
message.requestId = requestId;
|
|
113
115
|
if (!this.websocket) {
|
|
114
116
|
throw new Error('WebSocket is not initialized');
|
|
115
117
|
}
|
package/dist/core/websocket.js
CHANGED
|
@@ -66,7 +66,32 @@ class cbws {
|
|
|
66
66
|
const agentTask = process.env.agentTask ? `&agentTask=${process.env.agentTask}` : '';
|
|
67
67
|
const socketPort = process.env.SOCKET_PORT || '12345';
|
|
68
68
|
const serverUrl = process.env.CODEBOLT_SERVER_URL || 'localhost';
|
|
69
|
-
const
|
|
69
|
+
const threadToken = process.env.threadToken || null;
|
|
70
|
+
console.log('[WebSocket] Logging all relevant variables:');
|
|
71
|
+
console.log('uniqueConnectionId:', uniqueConnectionId);
|
|
72
|
+
console.log('initialMessage:', initialMessage);
|
|
73
|
+
console.log('agentIdParam:', agentIdParam);
|
|
74
|
+
console.log('parentIdParam:', parentIdParam);
|
|
75
|
+
console.log('parentAgentInstanceIdParam:', parentAgentInstanceIdParam);
|
|
76
|
+
console.log('agentTask:', agentTask);
|
|
77
|
+
console.log('socketPort:', socketPort);
|
|
78
|
+
console.log('serverUrl:', serverUrl);
|
|
79
|
+
console.log('threadToken:', threadToken);
|
|
80
|
+
console.log('[WebSocket] Environment variables check:');
|
|
81
|
+
console.log('process.env.agentId:', process.env.agentId);
|
|
82
|
+
console.log('process.env.threadToken:', process.env.threadToken);
|
|
83
|
+
console.log('process.env.parentId:', process.env.parentId);
|
|
84
|
+
console.log('process.env.agentTask:', process.env.agentTask);
|
|
85
|
+
const threadTokenParam = threadToken ? `&threadToken=${encodeURIComponent(threadToken)}` : '';
|
|
86
|
+
// Add all custom environment variables as URL parameters
|
|
87
|
+
const knownEnvVars = ['SOCKET_PORT', 'CODEBOLT_SERVER_URL', 'agentId', 'parentId', 'parentAgentInstanceId', 'agentTask', 'threadToken', 'Is_Dev', 'PATH', 'NODE_ENV', 'HOME', 'USER', 'SHELL'];
|
|
88
|
+
let customParams = '';
|
|
89
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
90
|
+
if (!knownEnvVars.includes(key) && value && !key.startsWith('npm_') && !key.startsWith('_')) {
|
|
91
|
+
customParams += `&${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const wsUrl = `ws://${serverUrl}:${socketPort}/codebolt?id=${uniqueConnectionId}${agentIdParam}${parentIdParam}${parentAgentInstanceIdParam}${agentTask}${threadTokenParam}${customParams}${process.env.Is_Dev ? '&dev=true' : ''}`;
|
|
70
95
|
console.log('[WebSocket] Connecting to:', wsUrl);
|
|
71
96
|
this.websocket = new ws_1.default(wsUrl);
|
|
72
97
|
return new Promise((resolve, reject) => {
|
package/dist/modules/mcp.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { UserMessage } from '../utils';
|
|
2
1
|
import { GetEnabledToolBoxesResponse, GetLocalToolBoxesResponse, GetAvailableToolBoxesResponse, SearchAvailableToolBoxesResponse, ListToolsFromToolBoxesResponse, ConfigureToolBoxResponse, GetToolsResponse, ExecuteToolResponse } from '../types/socketMessageTypes';
|
|
3
2
|
/**
|
|
4
3
|
* Object containing methods for interacting with Codebolt MCP (Model Context Protocol) tools.
|
|
@@ -23,7 +22,7 @@ declare const codeboltMCP: {
|
|
|
23
22
|
* @param userMessage - The user message to extract mentions from
|
|
24
23
|
* @returns Promise with the mentioned toolboxes
|
|
25
24
|
*/
|
|
26
|
-
getMentionedMCPServers: (userMessage:
|
|
25
|
+
getMentionedMCPServers: (userMessage: any) => Promise<GetAvailableToolBoxesResponse>;
|
|
27
26
|
/**
|
|
28
27
|
* Searches for available toolboxes matching a query.
|
|
29
28
|
*
|
package/dist/modules/mcp.js
CHANGED
|
@@ -3,6 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
// UserMessage type removed - using any for compatibility
|
|
7
|
+
// To use UserMessage functionality, install @codebolt/agent-utils
|
|
6
8
|
const websocket_1 = __importDefault(require("../core/websocket"));
|
|
7
9
|
/**
|
|
8
10
|
* Object containing methods for interacting with Codebolt MCP (Model Context Protocol) tools.
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,9 +1,2 @@
|
|
|
1
1
|
export { MCPServer } from './utils/mcpServer';
|
|
2
|
-
export { TaskInstruction } from './agentlib/taskInstruction';
|
|
3
|
-
export { UserMessage } from './agentlib/usermessage';
|
|
4
|
-
export { SystemPrompt } from './agentlib/systemprompt';
|
|
5
|
-
export { Agent } from './agentlib/agent';
|
|
6
|
-
export { InitialPromptBuilder } from './agentlib/promptbuilder';
|
|
7
|
-
export { LLMOutputHandler } from './agentlib/llmoutputhandler';
|
|
8
|
-
export { FollowUpPromptBuilder } from './agentlib/followupquestionbuilder';
|
|
9
2
|
export { default as docutils } from './utils/docutils';
|
package/dist/utils.js
CHANGED
|
@@ -3,22 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.docutils = exports.
|
|
6
|
+
exports.docutils = exports.MCPServer = void 0;
|
|
7
7
|
var mcpServer_1 = require("./utils/mcpServer");
|
|
8
8
|
Object.defineProperty(exports, "MCPServer", { enumerable: true, get: function () { return mcpServer_1.MCPServer; } });
|
|
9
|
-
var taskInstruction_1 = require("./agentlib/taskInstruction");
|
|
10
|
-
Object.defineProperty(exports, "TaskInstruction", { enumerable: true, get: function () { return taskInstruction_1.TaskInstruction; } });
|
|
11
|
-
var usermessage_1 = require("./agentlib/usermessage");
|
|
12
|
-
Object.defineProperty(exports, "UserMessage", { enumerable: true, get: function () { return usermessage_1.UserMessage; } });
|
|
13
|
-
var systemprompt_1 = require("./agentlib/systemprompt");
|
|
14
|
-
Object.defineProperty(exports, "SystemPrompt", { enumerable: true, get: function () { return systemprompt_1.SystemPrompt; } });
|
|
15
|
-
var agent_1 = require("./agentlib/agent");
|
|
16
|
-
Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return agent_1.Agent; } });
|
|
17
|
-
var promptbuilder_1 = require("./agentlib/promptbuilder");
|
|
18
|
-
Object.defineProperty(exports, "InitialPromptBuilder", { enumerable: true, get: function () { return promptbuilder_1.InitialPromptBuilder; } });
|
|
19
|
-
var llmoutputhandler_1 = require("./agentlib/llmoutputhandler");
|
|
20
|
-
Object.defineProperty(exports, "LLMOutputHandler", { enumerable: true, get: function () { return llmoutputhandler_1.LLMOutputHandler; } });
|
|
21
|
-
var followupquestionbuilder_1 = require("./agentlib/followupquestionbuilder");
|
|
22
|
-
Object.defineProperty(exports, "FollowUpPromptBuilder", { enumerable: true, get: function () { return followupquestionbuilder_1.FollowUpPromptBuilder; } });
|
|
23
9
|
var docutils_1 = require("./utils/docutils");
|
|
24
10
|
Object.defineProperty(exports, "docutils", { enumerable: true, get: function () { return __importDefault(docutils_1).default; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codebolt/codeboltjs",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.17",
|
|
4
4
|
"description": "",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"author": "",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"@codebolt/types": "^1.0.10",
|
|
33
33
|
"@modelcontextprotocol/sdk": "^1.4.1",
|
|
34
34
|
"@types/pdf-parse": "^1.1.5",
|
|
35
|
+
"@types/uuid": "^10.0.0",
|
|
35
36
|
"buffer": "^6.0.3",
|
|
36
37
|
"execa": "^9.5.2",
|
|
37
38
|
"file-type": "^19.6.0",
|
|
@@ -48,6 +49,7 @@
|
|
|
48
49
|
"undici": "^7.4.0",
|
|
49
50
|
"uri-templates": "^0.2.0",
|
|
50
51
|
"util": "^0.12.5",
|
|
52
|
+
"uuid": "^11.1.0",
|
|
51
53
|
"web-tree-sitter": "^0.24.1",
|
|
52
54
|
"ws": "^8.17.0",
|
|
53
55
|
"yargs": "^17.7.2",
|
package/dist/agentlib/agent.d.ts
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { SystemPrompt } from "./systemprompt";
|
|
2
|
-
import { TaskInstruction } from "./taskInstruction";
|
|
3
|
-
/**
|
|
4
|
-
* Agent class that manages conversations with LLMs and tool executions.
|
|
5
|
-
* Handles the conversation flow, tool calls, and task completions.
|
|
6
|
-
*/
|
|
7
|
-
declare class Agent {
|
|
8
|
-
/** Available tools for the agent to use */
|
|
9
|
-
private tools;
|
|
10
|
-
/** Full conversation history for API calls */
|
|
11
|
-
private apiConversationHistory;
|
|
12
|
-
/** Maximum number of conversation turns (0 means unlimited) */
|
|
13
|
-
private maxRun;
|
|
14
|
-
/** System prompt that provides instructions to the model */
|
|
15
|
-
private systemPrompt;
|
|
16
|
-
/** Messages from the user */
|
|
17
|
-
private userMessage;
|
|
18
|
-
/** The next user message to be added to the conversation */
|
|
19
|
-
private nextUserMessage;
|
|
20
|
-
/**
|
|
21
|
-
* Creates a new Agent instance.
|
|
22
|
-
*
|
|
23
|
-
* @param tools - The tools available to the agent
|
|
24
|
-
* @param systemPrompt - The system prompt providing instructions to the LLM
|
|
25
|
-
* @param maxRun - Maximum number of conversation turns (0 means unlimited)
|
|
26
|
-
*/
|
|
27
|
-
constructor(tools: any, systemPrompt: SystemPrompt, maxRun?: number);
|
|
28
|
-
/**
|
|
29
|
-
* Runs the agent on a specific task until completion or max runs reached.
|
|
30
|
-
*
|
|
31
|
-
* @param task - The task instruction to be executed
|
|
32
|
-
* @param successCondition - Optional function to determine if the task is successful
|
|
33
|
-
* @returns Promise with success status, error (if any), and the last assistant message
|
|
34
|
-
*/
|
|
35
|
-
run(task: TaskInstruction, successCondition?: () => boolean): Promise<{
|
|
36
|
-
success: boolean;
|
|
37
|
-
error: string | null;
|
|
38
|
-
message: string | null;
|
|
39
|
-
}>;
|
|
40
|
-
/**
|
|
41
|
-
* Attempts to make a request to the LLM with conversation history and tools.
|
|
42
|
-
*
|
|
43
|
-
* @param apiConversationHistory - The current conversation history
|
|
44
|
-
* @param tools - The tools available to the LLM
|
|
45
|
-
* @returns Promise with the LLM response
|
|
46
|
-
*/
|
|
47
|
-
private attemptLlmRequest;
|
|
48
|
-
/**
|
|
49
|
-
* Executes a tool with given name and input.
|
|
50
|
-
*
|
|
51
|
-
* @param toolName - The name of the tool to execute
|
|
52
|
-
* @param toolInput - The input parameters for the tool
|
|
53
|
-
* @returns Promise with tuple [userRejected, result]
|
|
54
|
-
*/
|
|
55
|
-
private executeTool;
|
|
56
|
-
/**
|
|
57
|
-
* Starts a sub-agent to handle a specific task.
|
|
58
|
-
*
|
|
59
|
-
* @param agentName - The name of the sub-agent to start
|
|
60
|
-
* @param params - Parameters for the sub-agent
|
|
61
|
-
* @returns Promise with tuple [userRejected, result]
|
|
62
|
-
*/
|
|
63
|
-
private startSubAgent;
|
|
64
|
-
/**
|
|
65
|
-
* Extracts tool details from a tool call object.
|
|
66
|
-
*
|
|
67
|
-
* @param tool - The tool call object from the LLM response
|
|
68
|
-
* @returns ToolDetails object with name, input, and ID
|
|
69
|
-
*/
|
|
70
|
-
private getToolDetail;
|
|
71
|
-
/**
|
|
72
|
-
* Creates a tool result object from the tool execution response.
|
|
73
|
-
*
|
|
74
|
-
* @param tool_call_id - The ID of the tool call
|
|
75
|
-
* @param content - The content returned by the tool
|
|
76
|
-
* @returns ToolResult object
|
|
77
|
-
*/
|
|
78
|
-
private getToolResult;
|
|
79
|
-
/**
|
|
80
|
-
* Fallback method for API requests in case of failures.
|
|
81
|
-
*
|
|
82
|
-
* @throws Error API request fallback not implemented
|
|
83
|
-
*/
|
|
84
|
-
private attemptApiRequest;
|
|
85
|
-
}
|
|
86
|
-
export { Agent };
|
package/dist/agentlib/agent.js
DELETED
|
@@ -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 };
|