@codebolt/agent 6.1.19 → 6.1.21

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 (47) hide show
  1. package/README.md +19 -10
  2. package/dist/processor-pieces/messageModifiers/argumentProcessorModifier.js +11 -15
  3. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.d.ts +0 -1
  4. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +16 -33
  5. package/dist/processor-pieces/messageModifiers/capabilityContextModifier.js +3 -2
  6. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.d.ts +7 -0
  7. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.js +135 -27
  8. package/dist/processor-pieces/messageModifiers/chatRecordingModifier.js +3 -3
  9. package/dist/processor-pieces/messageModifiers/contextAssemblyModifier.js +18 -12
  10. package/dist/processor-pieces/messageModifiers/directoryContextModifier.d.ts +1 -0
  11. package/dist/processor-pieces/messageModifiers/directoryContextModifier.js +15 -15
  12. package/dist/processor-pieces/messageModifiers/environmentContextModifier.d.ts +1 -0
  13. package/dist/processor-pieces/messageModifiers/environmentContextModifier.js +48 -2
  14. package/dist/processor-pieces/messageModifiers/ideContextModifier.js +3 -2
  15. package/dist/processor-pieces/messageModifiers/memoryImportModifier.js +9 -15
  16. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +17 -20
  17. package/dist/processor-pieces/postInferenceProcessors/loopDetectionModifier.js +8 -19
  18. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.d.ts +1 -1
  19. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.js +15 -15
  20. package/dist/processor-pieces/postToolCallProcessors/shellProcessorModifier.js +3 -3
  21. package/dist/processor-pieces/preInferenceProcessors/chatCompressionModifier.js +2 -2
  22. package/dist/processor-pieces/utils/messageModifierHelper.js +3 -3
  23. package/dist/types/libFunctionTypes.d.ts +5 -0
  24. package/dist/unified/agent/agent.d.ts +69 -2
  25. package/dist/unified/agent/agent.js +370 -48
  26. package/dist/unified/agent/tools.d.ts +17 -3
  27. package/dist/unified/agent/tools.js +82 -51
  28. package/dist/unified/base/agentStep.d.ts +1 -0
  29. package/dist/unified/base/agentStep.js +39 -11
  30. package/dist/unified/base/initialPromptGenerator.d.ts +2 -0
  31. package/dist/unified/base/initialPromptGenerator.js +98 -20
  32. package/dist/unified/base/promptContext.d.ts +3 -0
  33. package/dist/unified/base/promptContext.js +193 -15
  34. package/dist/unified/base/responseExecutor.d.ts +9 -1
  35. package/dist/unified/base/responseExecutor.js +248 -68
  36. package/dist/unified/index.d.ts +1 -2
  37. package/dist/unified/index.js +2 -4
  38. package/dist/unified/services/CompressionCoordinator.js +9 -9
  39. package/dist/unified/services/compaction/autoCompact.js +5 -5
  40. package/dist/unified/services/compaction/contextCollapse.js +2 -2
  41. package/dist/unified/services/compaction/reactiveCompact.js +5 -5
  42. package/dist/unified/types/libTypes.d.ts +6 -0
  43. package/dist/unified/utils/agentToolLoader.d.ts +10 -0
  44. package/dist/unified/utils/agentToolLoader.js +90 -24
  45. package/package.json +5 -1
  46. package/dist/unified/agent/codeboltAgent.d.ts +0 -61
  47. package/dist/unified/agent/codeboltAgent.js +0 -334
@@ -181,6 +181,12 @@ export interface CodeboltAPI {
181
181
  executeTool(toolName: string, params: unknown): Promise<{
182
182
  data: unknown;
183
183
  }>;
184
+ /** List registered project-local and plugin MCP tools */
185
+ getRegisteredTools(): Promise<{
186
+ data?: {
187
+ tools: OpenAITool[];
188
+ };
189
+ }>;
184
190
  /** List available MCP tools */
185
191
  listTools(): Promise<string[]>;
186
192
  /** Get tool schema */
@@ -1,13 +1,23 @@
1
+ import type { AgentLocalTool } from '@codebolt/types/agent';
1
2
  import type { Tool } from '@codebolt/types/sdk';
2
3
  type ToolResponse = {
3
4
  data?: {
4
5
  tools?: unknown;
5
6
  } | unknown;
6
7
  };
8
+ export declare class LocalToolConfigurationError extends Error {
9
+ constructor(message: string);
10
+ }
11
+ export interface AgentLocalToolRegistry {
12
+ schemas: Tool[];
13
+ byExecutionName: Map<string, AgentLocalTool>;
14
+ }
7
15
  export declare function normalizeToolForModel(tool: Tool): Tool;
8
16
  export declare function resolveToolExecutionName(modelToolName: string): string;
9
17
  export declare function normalizeToolResponse(response: ToolResponse | undefined): Tool[];
10
18
  export declare function mergeTools(...toolGroups: Tool[][]): Tool[];
19
+ export declare function createAgentLocalToolRegistry(localTools?: AgentLocalTool[]): AgentLocalToolRegistry;
20
+ export declare function assertNoLocalToolSchemaCollisions(localSchemas: Tool[], externalSchemas: Tool[]): void;
11
21
  export declare function listProjectLocalTools(): Promise<Tool[]>;
12
22
  export declare function listAgentAvailableTools(mentionedMCPs?: unknown[]): Promise<Tool[]>;
13
23
  export declare function appendUniqueTools(targetTools: Tool[], toolsToAppend: Tool[]): void;
@@ -3,10 +3,13 @@ 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.LocalToolConfigurationError = void 0;
6
7
  exports.normalizeToolForModel = normalizeToolForModel;
7
8
  exports.resolveToolExecutionName = resolveToolExecutionName;
8
9
  exports.normalizeToolResponse = normalizeToolResponse;
9
10
  exports.mergeTools = mergeTools;
11
+ exports.createAgentLocalToolRegistry = createAgentLocalToolRegistry;
12
+ exports.assertNoLocalToolSchemaCollisions = assertNoLocalToolSchemaCollisions;
10
13
  exports.listProjectLocalTools = listProjectLocalTools;
11
14
  exports.listAgentAvailableTools = listAgentAvailableTools;
12
15
  exports.appendUniqueTools = appendUniqueTools;
@@ -14,13 +17,29 @@ const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
14
17
  const MODEL_TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
15
18
  const LOCAL_TOOL_PREFIX = 'local/';
16
19
  const toolExecutionNameByModelName = new Map();
20
+ class LocalToolConfigurationError extends Error {
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = 'LocalToolConfigurationError';
24
+ }
25
+ }
26
+ exports.LocalToolConfigurationError = LocalToolConfigurationError;
17
27
  function isTool(value) {
18
28
  var _a;
19
29
  if (!value || typeof value !== 'object') {
20
30
  return false;
21
31
  }
22
32
  const candidate = value;
23
- return candidate.type === 'function' && typeof ((_a = candidate.function) === null || _a === void 0 ? void 0 : _a.name) === 'string';
33
+ return candidate.type === 'function' &&
34
+ typeof ((_a = candidate.function) === null || _a === void 0 ? void 0 : _a.name) === 'string' &&
35
+ candidate.function.name.trim().length > 0;
36
+ }
37
+ function getToolName(tool) {
38
+ var _a, _b;
39
+ return ((_b = (_a = tool.function) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.trim()) || '';
40
+ }
41
+ function compareToolsByName(leftTool, rightTool) {
42
+ return getToolName(leftTool).localeCompare(getToolName(rightTool));
24
43
  }
25
44
  function hashString(value) {
26
45
  let hash = 0;
@@ -76,30 +95,87 @@ function normalizeToolResponse(response) {
76
95
  return tools.filter(isTool).map(normalizeToolForModel);
77
96
  }
78
97
  function mergeTools(...toolGroups) {
79
- var _a;
80
98
  const mergedTools = new Map();
81
99
  for (const tools of toolGroups) {
82
100
  for (const tool of tools) {
83
- const toolName = (_a = tool.function) === null || _a === void 0 ? void 0 : _a.name;
101
+ const toolName = getToolName(tool);
84
102
  if (toolName && !mergedTools.has(toolName)) {
85
103
  mergedTools.set(toolName, tool);
86
104
  }
87
105
  }
88
106
  }
89
- return Array.from(mergedTools.values());
107
+ return Array.from(mergedTools.values()).sort(compareToolsByName);
108
+ }
109
+ function isAgentLocalTool(value) {
110
+ if (!value || typeof value !== 'object') {
111
+ return false;
112
+ }
113
+ const candidate = value;
114
+ return typeof candidate.id === 'string' &&
115
+ candidate.id.length > 0 &&
116
+ typeof candidate.execute === 'function' &&
117
+ typeof candidate.toOpenAITool === 'function';
118
+ }
119
+ function createAgentLocalToolRegistry(localTools = []) {
120
+ var _a;
121
+ const schemas = [];
122
+ const byExecutionName = new Map();
123
+ const modelNames = new Set();
124
+ for (const localTool of localTools) {
125
+ if (!isAgentLocalTool(localTool)) {
126
+ throw new LocalToolConfigurationError('Agent local tools must be created with createTool(...) or implement id, execute(...), and toOpenAITool().');
127
+ }
128
+ if (byExecutionName.has(localTool.id)) {
129
+ throw new LocalToolConfigurationError(`Duplicate local agent tool id "${localTool.id}".`);
130
+ }
131
+ const schema = normalizeToolForModel(localTool.toOpenAITool());
132
+ const modelName = (_a = schema.function) === null || _a === void 0 ? void 0 : _a.name;
133
+ if (!modelName) {
134
+ throw new LocalToolConfigurationError(`Local agent tool "${localTool.id}" produced an invalid OpenAI tool schema.`);
135
+ }
136
+ if (modelNames.has(modelName)) {
137
+ throw new LocalToolConfigurationError(`Duplicate local agent tool model name "${modelName}".`);
138
+ }
139
+ schemas.push(schema);
140
+ modelNames.add(modelName);
141
+ byExecutionName.set(localTool.id, localTool);
142
+ }
143
+ return { schemas, byExecutionName };
144
+ }
145
+ function assertNoLocalToolSchemaCollisions(localSchemas, externalSchemas) {
146
+ var _a;
147
+ if (localSchemas.length === 0 || externalSchemas.length === 0) {
148
+ return;
149
+ }
150
+ const localToolNames = new Set(localSchemas
151
+ .map((tool) => { var _a; return (_a = tool.function) === null || _a === void 0 ? void 0 : _a.name; })
152
+ .filter((toolName) => typeof toolName === 'string' && toolName.length > 0));
153
+ for (const externalSchema of externalSchemas) {
154
+ const externalToolName = (_a = externalSchema.function) === null || _a === void 0 ? void 0 : _a.name;
155
+ if (externalToolName && localToolNames.has(externalToolName)) {
156
+ throw new LocalToolConfigurationError(`Local agent tool "${externalToolName}" collides with an existing CodeBolt or MCP tool.`);
157
+ }
158
+ }
90
159
  }
91
160
  async function listProjectLocalTools() {
92
161
  const mcp = codeboltjs_1.default.mcp;
93
- if (typeof mcp.getLocalMCPServers !== 'function') {
94
- return [];
95
- }
96
- try {
97
- return normalizeToolResponse(await mcp.getLocalMCPServers());
162
+ if (typeof mcp.getRegisteredTools === 'function') {
163
+ try {
164
+ return normalizeToolResponse(await mcp.getRegisteredTools());
165
+ }
166
+ catch (error) {
167
+ console.error('[AgentToolLoader] Failed to load registered MCP tools:', error);
168
+ }
98
169
  }
99
- catch (error) {
100
- console.error('[AgentToolLoader] Failed to load project-local tools:', error);
101
- return [];
170
+ if (typeof mcp.getLocalMCPServers === 'function') {
171
+ try {
172
+ return normalizeToolResponse(await mcp.getLocalMCPServers());
173
+ }
174
+ catch (error) {
175
+ console.error('[AgentToolLoader] Failed to load project-local tools:', error);
176
+ }
102
177
  }
178
+ return [];
103
179
  }
104
180
  async function listAgentAvailableTools(mentionedMCPs = []) {
105
181
  let codeboltTools = [];
@@ -123,16 +199,6 @@ async function listAgentAvailableTools(mentionedMCPs = []) {
123
199
  return mergeTools(codeboltTools, localTools, mentionedTools);
124
200
  }
125
201
  function appendUniqueTools(targetTools, toolsToAppend) {
126
- var _a;
127
- const existingToolNames = new Set(targetTools
128
- .map((tool) => { var _a; return (_a = tool.function) === null || _a === void 0 ? void 0 : _a.name; })
129
- .filter((toolName) => typeof toolName === 'string' && toolName.length > 0));
130
- for (const tool of toolsToAppend) {
131
- const toolName = (_a = tool.function) === null || _a === void 0 ? void 0 : _a.name;
132
- if (!toolName || existingToolNames.has(toolName)) {
133
- continue;
134
- }
135
- targetTools.push(tool);
136
- existingToolNames.add(toolName);
137
- }
202
+ const mergedTools = mergeTools(targetTools, toolsToAppend);
203
+ targetTools.splice(0, targetTools.length, ...mergedTools);
138
204
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codebolt/agent",
3
- "version": "6.1.19",
3
+ "version": "6.1.21",
4
4
  "description": "CodeBolt Agent utilities for building and managing AI agents",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -72,6 +72,10 @@
72
72
  "./unified": {
73
73
  "types": "./dist/unified/index.d.ts",
74
74
  "default": "./dist/unified/index.js"
75
+ },
76
+ "./unified/tools": {
77
+ "types": "./dist/unified/agent/tools.d.ts",
78
+ "default": "./dist/unified/agent/tools.js"
75
79
  }
76
80
  }
77
81
  }
@@ -1,61 +0,0 @@
1
- import { AgentConfig, MessageModifier, PostInferenceProcessor, PostToolCallProcessor, PreInferenceProcessor, PreToolCallProcessor, ProcessedMessage } from "@codebolt/types/agent";
2
- import { FlatUserMessage } from "@codebolt/types/sdk";
3
- import { LoopDetectionService } from "../services/LoopDetectionService";
4
- import type { CompactionOrchestratorOptions } from "../services/compaction/types";
5
- export interface CodeboltAgentConfig extends AgentConfig {
6
- enableLogging?: boolean;
7
- context?: ProcessedMessage;
8
- allowedTools?: string[];
9
- compaction?: CompactionOrchestratorOptions;
10
- loopDetectionService?: LoopDetectionService;
11
- maxTurns?: number;
12
- }
13
- export declare class CodeboltAgent {
14
- private readonly config;
15
- private readonly messageModifiers;
16
- private readonly preInferenceProcessors;
17
- private readonly postInferenceProcessors;
18
- private readonly preToolCallProcessors;
19
- private readonly postToolCallProcessors;
20
- private readonly enableLogging;
21
- private readonly baseSystemPrompt;
22
- private readonly context;
23
- private readonly allowedTools;
24
- private readonly compactionOrchestrator;
25
- private readonly loopDetectionService;
26
- private readonly maxTurns;
27
- constructor(config: CodeboltAgentConfig);
28
- private createDefaultMessageModifiers;
29
- private createDefaultUserMessage;
30
- processMessage(message: string | FlatUserMessage, context?: ProcessedMessage): Promise<{
31
- success: boolean;
32
- result: any;
33
- context: ProcessedMessage | null;
34
- finalMessage?: string;
35
- error?: string;
36
- }>;
37
- getConfig(): CodeboltAgentConfig;
38
- getMessageModifiers(): MessageModifier[];
39
- getPreInferenceProcessors(): PreInferenceProcessor[];
40
- getPostInferenceProcessors(): PostInferenceProcessor[];
41
- getPreToolCallProcessors(): PreToolCallProcessor[];
42
- getPostToolCallProcessors(): PostToolCallProcessor[];
43
- private applyCompaction;
44
- private tryRecoverPrompt;
45
- private refreshAvailableTools;
46
- private getAllowedToolNames;
47
- private getRecoverableResponseError;
48
- private collectResponseMessages;
49
- }
50
- export declare function createCodeboltAgent(options: {
51
- systemPrompt: string;
52
- messageModifiers?: MessageModifier[];
53
- preInferenceProcessors?: PreInferenceProcessor[];
54
- postInferenceProcessors?: PostInferenceProcessor[];
55
- preToolCallProcessors?: PreToolCallProcessor[];
56
- postToolCallProcessors?: PostToolCallProcessor[];
57
- enableLogging?: boolean;
58
- compaction?: CompactionOrchestratorOptions;
59
- loopDetectionService?: LoopDetectionService;
60
- maxTurns?: number;
61
- }): CodeboltAgent;
@@ -1,334 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CodeboltAgent = void 0;
4
- exports.createCodeboltAgent = createCodeboltAgent;
5
- const base_1 = require("../base");
6
- const agentStep_1 = require("../base/agentStep");
7
- const responseExecutor_1 = require("../base/responseExecutor");
8
- const promptContext_1 = require("../base/promptContext");
9
- const compactionOrchestrator_1 = require("../services/compaction/compactionOrchestrator");
10
- const agentToolLoader_1 = require("../utils/agentToolLoader");
11
- const processor_pieces_1 = require("../../processor-pieces");
12
- class CodeboltAgent {
13
- constructor(config) {
14
- var _a, _b, _c, _d, _e, _f, _g;
15
- this.config = { ...config };
16
- this.enableLogging = config.enableLogging !== false;
17
- this.baseSystemPrompt = config.instructions || 'Based on User Message send reply';
18
- this.context = config.context;
19
- this.allowedTools = config.allowedTools;
20
- this.messageModifiers = ((_b = (_a = config.processors) === null || _a === void 0 ? void 0 : _a.messageModifiers) === null || _b === void 0 ? void 0 : _b.length)
21
- ? config.processors.messageModifiers
22
- : this.createDefaultMessageModifiers(this.baseSystemPrompt, this.allowedTools);
23
- this.preInferenceProcessors = ((_c = config.processors) === null || _c === void 0 ? void 0 : _c.preInferenceProcessors) || [];
24
- this.postInferenceProcessors = ((_d = config.processors) === null || _d === void 0 ? void 0 : _d.postInferenceProcessors) || [];
25
- this.preToolCallProcessors = ((_e = config.processors) === null || _e === void 0 ? void 0 : _e.preToolCallProcessors) || [];
26
- this.postToolCallProcessors = ((_f = config.processors) === null || _f === void 0 ? void 0 : _f.postToolCallProcessors) || [];
27
- this.compactionOrchestrator = new compactionOrchestrator_1.CompactionOrchestrator(config.compaction);
28
- this.loopDetectionService = config.loopDetectionService;
29
- this.maxTurns = (_g = config.maxTurns) !== null && _g !== void 0 ? _g : 25;
30
- }
31
- createDefaultMessageModifiers(systemPrompt, allowedTools) {
32
- return [
33
- new processor_pieces_1.ChatHistoryMessageModifier({
34
- enableChatHistory: true,
35
- includeSystemMessages: false,
36
- }),
37
- new processor_pieces_1.EnvironmentContextModifier({ enableFullContext: true }),
38
- new processor_pieces_1.DirectoryContextModifier(),
39
- new processor_pieces_1.IdeContextModifier({
40
- includeActiveFile: true,
41
- includeOpenFiles: true,
42
- includeCursorPosition: true,
43
- includeSelectedText: true
44
- }),
45
- new processor_pieces_1.CoreSystemPromptModifier({ customSystemPrompt: systemPrompt }),
46
- new processor_pieces_1.ToolInjectionModifier({
47
- includeToolDescriptions: true,
48
- ...(allowedTools && { allowedTools })
49
- }),
50
- new processor_pieces_1.AtFileProcessorModifier({ enableRecursiveSearch: true })
51
- ];
52
- }
53
- createDefaultUserMessage(message) {
54
- return {
55
- userMessage: message,
56
- selectedAgent: {
57
- id: 'codebolt-agent',
58
- name: 'Codebolt Agent'
59
- },
60
- mentionedFiles: [],
61
- mentionedFullPaths: [],
62
- mentionedFolders: [],
63
- mentionedMCPs: [],
64
- uploadedImages: [],
65
- mentionedAgents: [],
66
- mentionedEnvironments: [],
67
- messageId: `msg-${Date.now()}`,
68
- threadId: `thread-${Date.now()}`
69
- };
70
- }
71
- async processMessage(message, context) {
72
- var _a;
73
- try {
74
- const reqMessage = typeof message === 'string'
75
- ? this.createDefaultUserMessage(message)
76
- : message;
77
- let prompt;
78
- const contextToUse = context || this.context;
79
- if (contextToUse) {
80
- prompt = contextToUse;
81
- }
82
- else {
83
- const promptGenerator = new base_1.InitialPromptGenerator({
84
- processors: this.messageModifiers,
85
- baseSystemPrompt: this.baseSystemPrompt,
86
- enableLogging: this.enableLogging
87
- });
88
- prompt = await promptGenerator.processMessage(reqMessage);
89
- }
90
- let completed = false;
91
- let turnNumber = 0;
92
- let finalMessage;
93
- while (!completed) {
94
- turnNumber += 1;
95
- if (turnNumber > this.maxTurns) {
96
- throw new Error(`Agent exceeded the maximum turn limit of ${this.maxTurns}.`);
97
- }
98
- this.compactionOrchestrator.resetForTurn();
99
- prompt = await this.applyCompaction(prompt);
100
- prompt = await this.refreshAvailableTools(reqMessage, prompt);
101
- const agentStep = new agentStep_1.AgentStep({
102
- preInferenceProcessors: this.preInferenceProcessors,
103
- postInferenceProcessors: this.postInferenceProcessors
104
- });
105
- let stepResult;
106
- while (!stepResult) {
107
- try {
108
- const nextStepResult = await agentStep.executeStep(reqMessage, prompt);
109
- this.compactionOrchestrator.updateModelTokenLimit((_a = nextStepResult.rawLLMResponse) === null || _a === void 0 ? void 0 : _a.tokenLimit);
110
- const recoverableResponseError = this.getRecoverableResponseError(nextStepResult.rawLLMResponse);
111
- if (!recoverableResponseError) {
112
- stepResult = nextStepResult;
113
- break;
114
- }
115
- const recoveredPrompt = await this.tryRecoverPrompt(prompt, new Error(recoverableResponseError));
116
- if (!recoveredPrompt) {
117
- throw new Error(recoverableResponseError);
118
- }
119
- prompt = recoveredPrompt;
120
- }
121
- catch (error) {
122
- const recoveredPrompt = await this.tryRecoverPrompt(prompt, error);
123
- if (!recoveredPrompt) {
124
- throw error;
125
- }
126
- prompt = recoveredPrompt;
127
- }
128
- }
129
- if (!stepResult) {
130
- throw new Error('Agent step did not produce a response.');
131
- }
132
- const responseExecutor = new responseExecutor_1.ResponseExecutor({
133
- preToolCallProcessors: this.preToolCallProcessors,
134
- postToolCallProcessors: this.postToolCallProcessors,
135
- ...(this.loopDetectionService
136
- ? { loopDetectionService: this.loopDetectionService }
137
- : {}),
138
- });
139
- const executionResult = await responseExecutor.executeResponse({
140
- initialUserMessage: reqMessage,
141
- actualMessageSentToLLM: stepResult.actualMessageSentToLLM,
142
- rawLLMOutput: stepResult.rawLLMResponse,
143
- nextMessage: stepResult.nextMessage
144
- });
145
- completed = executionResult.completed;
146
- prompt = executionResult.nextMessage;
147
- finalMessage = executionResult.finalMessage;
148
- }
149
- return {
150
- success: true,
151
- result: prompt,
152
- context: prompt,
153
- ...(finalMessage !== undefined ? { finalMessage } : {}),
154
- };
155
- }
156
- catch (error) {
157
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
158
- if (this.enableLogging) {
159
- console.error('[CodeboltAgent] Execution failed:', error);
160
- }
161
- return {
162
- success: false,
163
- result: null,
164
- context: null,
165
- error: errorMessage
166
- };
167
- }
168
- }
169
- getConfig() {
170
- return { ...this.config };
171
- }
172
- getMessageModifiers() {
173
- return [...this.messageModifiers];
174
- }
175
- getPreInferenceProcessors() {
176
- return [...this.preInferenceProcessors];
177
- }
178
- getPostInferenceProcessors() {
179
- return [...this.postInferenceProcessors];
180
- }
181
- getPreToolCallProcessors() {
182
- return [...this.preToolCallProcessors];
183
- }
184
- getPostToolCallProcessors() {
185
- return [...this.postToolCallProcessors];
186
- }
187
- async applyCompaction(prompt) {
188
- const result = await this.compactionOrchestrator.compact((0, promptContext_1.getTranscriptMessages)(prompt));
189
- if (!result.wasCompacted) {
190
- return prompt;
191
- }
192
- return {
193
- ...(0, promptContext_1.replaceTranscriptMessages)(prompt, result.messages),
194
- metadata: {
195
- ...prompt.metadata,
196
- compaction: {
197
- totalTokensFreed: result.totalTokensFreed,
198
- layersApplied: result.layersApplied,
199
- boundaries: result.boundaries,
200
- timestamp: new Date().toISOString(),
201
- },
202
- },
203
- };
204
- }
205
- async tryRecoverPrompt(prompt, error) {
206
- const errorMessage = error instanceof Error ? error.message : String(error);
207
- if (!this.compactionOrchestrator.getReactiveLayer().isRecoverableError(errorMessage)) {
208
- return null;
209
- }
210
- const recovery = await this.compactionOrchestrator.recoverFromError((0, promptContext_1.getTranscriptMessages)(prompt), error);
211
- if (!recovery.wasCompacted) {
212
- return null;
213
- }
214
- return {
215
- ...(0, promptContext_1.replaceTranscriptMessages)(prompt, recovery.messages),
216
- metadata: {
217
- ...prompt.metadata,
218
- reactiveCompaction: {
219
- totalTokensFreed: recovery.totalTokensFreed,
220
- layersApplied: recovery.layersApplied,
221
- boundaries: recovery.boundaries,
222
- timestamp: new Date().toISOString(),
223
- error: errorMessage,
224
- },
225
- },
226
- };
227
- }
228
- async refreshAvailableTools(originalRequest, prompt) {
229
- var _a, _b, _c;
230
- if (((_a = prompt.metadata) === null || _a === void 0 ? void 0 : _a['toolsInjected']) !== true ||
231
- ((_b = prompt.metadata) === null || _b === void 0 ? void 0 : _b['toolsLocation']) !== 'Tool') {
232
- return prompt;
233
- }
234
- const existingTools = Array.isArray(prompt.message.tools)
235
- ? prompt.message.tools
236
- : [];
237
- try {
238
- const mentionedMCPs = Array.isArray(originalRequest.mentionedMCPs)
239
- ? originalRequest.mentionedMCPs
240
- : [];
241
- let refreshedTools = await (0, agentToolLoader_1.listAgentAvailableTools)(mentionedMCPs);
242
- const allowedToolNames = this.getAllowedToolNames(prompt);
243
- if (allowedToolNames && allowedToolNames.length > 0) {
244
- const allowed = new Set(allowedToolNames);
245
- refreshedTools = refreshedTools.filter((tool) => { var _a; return !!((_a = tool.function) === null || _a === void 0 ? void 0 : _a.name) && allowed.has(tool.function.name); });
246
- }
247
- const mergedTools = (0, agentToolLoader_1.mergeTools)(refreshedTools, existingTools);
248
- return {
249
- ...prompt,
250
- message: {
251
- ...prompt.message,
252
- tools: mergedTools,
253
- ...(mergedTools.length > 0
254
- ? { tool_choice: (_c = prompt.message.tool_choice) !== null && _c !== void 0 ? _c : 'auto' }
255
- : {}),
256
- },
257
- metadata: {
258
- ...prompt.metadata,
259
- toolsCount: mergedTools.length,
260
- toolsRefreshedAt: new Date().toISOString(),
261
- },
262
- };
263
- }
264
- catch (error) {
265
- if (this.enableLogging) {
266
- console.error('[CodeboltAgent] Failed to refresh tools:', error);
267
- }
268
- return prompt;
269
- }
270
- }
271
- getAllowedToolNames(prompt) {
272
- var _a;
273
- const metadataAllowedTools = (_a = prompt.metadata) === null || _a === void 0 ? void 0 : _a['allowedTools'];
274
- if (Array.isArray(metadataAllowedTools)) {
275
- const allowedToolNames = metadataAllowedTools.filter((toolName) => typeof toolName === 'string' && toolName.length > 0);
276
- if (allowedToolNames.length > 0) {
277
- return allowedToolNames;
278
- }
279
- }
280
- return this.allowedTools;
281
- }
282
- getRecoverableResponseError(response) {
283
- var _a, _b, _c, _d;
284
- const reactiveLayer = this.compactionOrchestrator.getReactiveLayer();
285
- const candidateMessages = this.collectResponseMessages(response);
286
- const recoverableMessage = candidateMessages.find((message) => reactiveLayer.isRecoverableError(message));
287
- if (recoverableMessage) {
288
- return recoverableMessage;
289
- }
290
- const finishReasons = [
291
- response.finish_reason,
292
- ...((_a = response.choices) !== null && _a !== void 0 ? _a : []).map((choice) => choice.finish_reason),
293
- ].filter((reason) => typeof reason === 'string');
294
- const hasLengthFinishReason = finishReasons.some((reason) => reason.toLowerCase() === 'length');
295
- const hasToolCalls = ((_c = (_b = response.tool_calls) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 0 ||
296
- ((_d = response.choices) !== null && _d !== void 0 ? _d : []).some((choice) => { var _a, _b, _c; return ((_c = (_b = (_a = choice.message) === null || _a === void 0 ? void 0 : _a.tool_calls) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0) > 0; });
297
- if (hasLengthFinishReason && candidateMessages.length === 0 && !hasToolCalls) {
298
- return 'Too many tokens or token limit reached before producing usable output.';
299
- }
300
- return null;
301
- }
302
- collectResponseMessages(response) {
303
- var _a, _b;
304
- const messages = [];
305
- if (typeof response.content === 'string' && response.content.trim().length > 0) {
306
- messages.push(response.content.trim());
307
- }
308
- for (const choice of (_a = response.choices) !== null && _a !== void 0 ? _a : []) {
309
- if (typeof ((_b = choice.message) === null || _b === void 0 ? void 0 : _b.content) === 'string' &&
310
- choice.message.content.trim().length > 0) {
311
- messages.push(choice.message.content.trim());
312
- }
313
- }
314
- return messages;
315
- }
316
- }
317
- exports.CodeboltAgent = CodeboltAgent;
318
- function createCodeboltAgent(options) {
319
- var _a;
320
- return new CodeboltAgent({
321
- instructions: options.systemPrompt,
322
- processors: {
323
- messageModifiers: options.messageModifiers || [],
324
- preInferenceProcessors: options.preInferenceProcessors || [],
325
- postInferenceProcessors: options.postInferenceProcessors || [],
326
- preToolCallProcessors: options.preToolCallProcessors || [],
327
- postToolCallProcessors: options.postToolCallProcessors || []
328
- },
329
- enableLogging: (_a = options.enableLogging) !== null && _a !== void 0 ? _a : true,
330
- ...(options.compaction ? { compaction: options.compaction } : {}),
331
- ...(options.loopDetectionService ? { loopDetectionService: options.loopDetectionService } : {}),
332
- ...(options.maxTurns !== undefined ? { maxTurns: options.maxTurns } : {}),
333
- });
334
- }