@codebolt/agent 6.0.1 → 6.1.3

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/README.md CHANGED
@@ -1,211 +1,176 @@
1
1
  # CodeBolt Agent Package
2
2
 
3
- A comprehensive TypeScript framework for building and managing AI agents with CodeBolt. This package provides multiple architectural patterns and utilities to meet different development needs, from simple composable agents to complex multi-step workflows.
3
+ `@codebolt/agent` provides TypeScript utilities for building CodeBolt agents with a unified execution pipeline, reusable processor pieces, tool definitions, workflows, loop detection, and conversation compaction.
4
4
 
5
- ## 🚀 Quick Start
6
-
7
- ```typescript
8
- import { ComposableAgent, createTool } from '@codebolt/agent/composable';
9
- import { z } from 'zod';
10
-
11
- // Create a simple weather tool
12
- const weatherTool = createTool({
13
- id: 'get-weather',
14
- description: 'Get current weather for a location',
15
- inputSchema: z.object({ location: z.string() }),
16
- outputSchema: z.object({ temperature: z.number(), conditions: z.string() }),
17
- execute: async ({ context }) => {
18
- return await getWeatherAPI(context.location);
19
- },
20
- });
21
-
22
- // Create and run agent
23
- const agent = new ComposableAgent({
24
- name: 'Weather Agent',
25
- instructions: 'You are a helpful weather assistant.',
26
- model: 'gpt-4o-mini',
27
- tools: { weatherTool },
28
- memory: createCodeBoltAgentMemory('weather_agent')
29
- });
30
-
31
- const result = await agent.execute('What is the weather in New York?');
32
- ```
33
-
34
- ## ✨ Key Features
35
-
36
- - **Multiple Patterns**: Choose between Composable, Builder, and Processor patterns
37
- - **Type Safety**: Full TypeScript support with Zod validation
38
- - **Memory Management**: Persistent conversation storage with CodeBolt integration
39
- - **Tool System**: Extensible tool framework with validation
40
- - **Workflow Orchestration**: Multi-step agent processes with conditional logic
41
- - **Model Agnostic**: Support for OpenAI, Anthropic, Ollama, and more
42
- - **Stream Support**: Real-time streaming responses
43
-
44
- ## 📦 Installation
5
+ ## Installation
45
6
 
46
7
  ```bash
47
8
  npm install @codebolt/agent
48
9
  ```
49
10
 
50
- ## 📖 Documentation
11
+ ## Public entry points
51
12
 
52
- **📚 [View Complete Documentation](./DOCUMENTATION.md)** - Comprehensive guide with examples, API reference, and best practices
13
+ The package currently publishes these import paths:
53
14
 
54
- ### Quick Links
55
- - [Architectural Patterns](./DOCUMENTATION.md#architectural-patterns) - Choose the right pattern for your use case
56
- - [API Reference](./API_REFERENCE.md) - Complete API documentation
57
- - [Examples](./EXAMPLES.md) - Real-world usage examples and tutorials
58
- - [Best Practices](./DOCUMENTATION.md#best-practices) - Tips for optimal agent development
59
- - [Migration Guide](./DOCUMENTATION.md#migration-guide) - Upgrading from previous versions
15
+ | Import path | Purpose |
16
+ | --- | --- |
17
+ | `@codebolt/agent` | Main entry point; re-exports the unified framework and `ProcessorPieces` namespace. |
18
+ | `@codebolt/agent/unified` | Agent runtime, tools, workflows, compaction services, and core framework types. |
19
+ | `@codebolt/agent/processor-pieces` | Reusable message modifiers and pre/post inference/tool processors. |
60
20
 
61
- ## 🎯 Architecture Patterns
21
+ Older examples that import from `@codebolt/agent/composable`, `@codebolt/agent/builder`, or `@codebolt/agent/processor` are obsolete for this package version.
62
22
 
63
- ### Composable Pattern (Recommended)
64
- **Best for**: Rapid prototyping, simple agents, beginners
23
+ ## Quick start
65
24
 
66
25
  ```typescript
67
- import { ComposableAgent, createTool, createCodeBoltAgentMemory } from '@codebolt/agent/composable';
68
-
69
- const agent = new ComposableAgent({
70
- name: 'My Agent',
71
- instructions: 'You are a helpful assistant.',
72
- model: 'gpt-4o-mini',
73
- tools: { myTool },
74
- memory: createCodeBoltAgentMemory('agent_id')
75
- });
76
-
77
- const result = await agent.execute('Help me with this task');
78
- ```
26
+ import { createCodeboltAgent } from '@codebolt/agent/unified';
79
27
 
80
- ### Builder Pattern
81
- **Best for**: Complex workflows, fine-grained control
28
+ const agent = createCodeboltAgent({
29
+ systemPrompt: 'You are a concise CodeBolt coding assistant.',
30
+ allowedTools: ['read_file', 'write_file'],
31
+ maxTurns: 10,
32
+ });
82
33
 
83
- ```typescript
84
- import { Agent, InitialPromptBuilder, LLMOutputHandler } from '@codebolt/agent/builder';
34
+ const result = await agent.processMessage('Inspect the current project and summarize it.');
85
35
 
86
- const promptBuilder = new InitialPromptBuilder(userMessage)
87
- .addSystemInstructions("You are a coding assistant")
88
- .addFile("./src/main.ts")
89
- .addTaskDetails("Fix compilation errors");
36
+ if (!result.success) {
37
+ throw new Error(result.error);
38
+ }
90
39
 
91
- const prompt = await promptBuilder.build();
92
- const agent = new Agent(tools, systemPrompt);
93
- const result = await agent.runAgent(prompt);
40
+ console.log(result.finalMessage ?? result.result);
94
41
  ```
95
42
 
96
- ### Processor Pattern
97
- **Best for**: Advanced customization, specialized requirements
43
+ ## Unified agent runtime
44
+
45
+ Use `CodeboltAgent` or `createCodeboltAgent` for the default CodeBolt-aware runtime. It automatically adds common message modifiers for chat history, environment context, directory context, IDE context, system prompt injection, tool injection, and `@file` processing.
98
46
 
99
47
  ```typescript
100
- import { BaseProcessor, AgentStep } from '@codebolt/agent/processor';
48
+ import {
49
+ CodeboltAgent,
50
+ ChatCompressionModifier,
51
+ ToolValidationModifier,
52
+ } from '@codebolt/agent/unified';
53
+
54
+ const agent = new CodeboltAgent({
55
+ instructions: 'Help the user safely modify code.',
56
+ processors: {
57
+ preInferenceProcessors: [new ChatCompressionModifier()],
58
+ preToolCallProcessors: [new ToolValidationModifier()],
59
+ },
60
+ enableLogging: true,
61
+ maxTurns: 25,
62
+ });
101
63
 
102
- class CustomProcessor extends BaseProcessor {
103
- async process(messages: any[]): Promise<any> {
104
- return this.executeCustomFlow(messages);
105
- }
106
- }
64
+ const response = await agent.processMessage('Fix the lint errors in this package.');
107
65
  ```
108
66
 
109
- ## 🛠️ Available Exports
67
+ For lower-level control, use `Agent`, `InitialPromptGenerator`, `AgentStep`, and `ResponseExecutor` from `@codebolt/agent/unified`.
110
68
 
111
- ### Composable Pattern
112
- ```typescript
113
- import {
114
- ComposableAgent, createTool, createWorkflow,
115
- Memory, createCodeBoltAgentMemory, MDocument
116
- } from '@codebolt/agent/composable';
117
- ```
69
+ ## Processor pieces
118
70
 
119
- ### Builder Pattern
120
- ```typescript
121
- import {
122
- Agent, InitialPromptBuilder, LLMOutputHandler,
123
- SystemPrompt, TaskInstruction, UserMessage
124
- } from '@codebolt/agent/builder';
125
- ```
71
+ Reusable processor pieces are available both through `@codebolt/agent/processor-pieces` and through the unified entry point.
126
72
 
127
- ### Processor Pattern
128
73
  ```typescript
129
- import {
130
- BaseProcessor, AgentStep, BaseTool,
131
- ChatCompressionProcessor, LoopDetectionProcessor
132
- } from '@codebolt/agent/processor';
74
+ import {
75
+ EnvironmentContextModifier,
76
+ CoreSystemPromptModifier,
77
+ ToolInjectionModifier,
78
+ } from '@codebolt/agent/processor-pieces';
79
+
80
+ const messageModifiers = [
81
+ new EnvironmentContextModifier({ enableFullContext: true }),
82
+ new CoreSystemPromptModifier({ customSystemPrompt: 'You are helpful.' }),
83
+ new ToolInjectionModifier({ includeToolDescriptions: true }),
84
+ ];
133
85
  ```
134
86
 
135
- ## 🏗️ Workflow System
87
+ ## Tools
136
88
 
137
- Create complex multi-agent workflows:
89
+ `createTool` wraps a Zod input schema, optional output schema, and execution function.
138
90
 
139
91
  ```typescript
140
- const workflow = createWorkflow({
141
- name: 'Content Pipeline',
142
- steps: [
143
- createAgentStep({
144
- id: 'research',
145
- agent: researchAgent,
146
- messageTemplate: 'Research: {{topic}}'
147
- }),
148
- createAgentStep({
149
- id: 'write',
150
- agent: writingAgent,
151
- messageTemplate: 'Write article: {{researchData}}'
152
- })
153
- ]
92
+ import { createTool } from '@codebolt/agent/unified';
93
+ import { z } from 'zod';
94
+
95
+ const echoTool = createTool({
96
+ id: 'echo',
97
+ description: 'Echoes the provided text.',
98
+ inputSchema: z.object({
99
+ text: z.string(),
100
+ }),
101
+ outputSchema: z.object({
102
+ text: z.string(),
103
+ }),
104
+ execute: async ({ input }) => ({
105
+ text: input.text,
106
+ }),
154
107
  });
155
108
 
156
- const result = await workflow.execute({ topic: 'AI Ethics' });
109
+ const execution = await echoTool.execute({ text: 'hello' }, {});
157
110
  ```
158
111
 
159
- ## 🧠 Memory & Storage
112
+ ## Workflows
160
113
 
161
- Integrated with CodeBolt's storage system:
114
+ `Workflow` executes workflow steps defined by `@codebolt/types/agent`. Use `executeAsync` when step implementations are asynchronous.
162
115
 
163
116
  ```typescript
164
- // Agent-scoped persistent storage
165
- const agentMemory = createCodeBoltAgentMemory('my_agent');
117
+ import { Workflow } from '@codebolt/agent/unified';
166
118
 
167
- // Project-scoped storage
168
- const projectMemory = createCodeBoltProjectMemory('project_agent');
119
+ const workflow = new Workflow({
120
+ name: 'Example Workflow',
121
+ steps: [
122
+ {
123
+ id: 'first-step',
124
+ name: 'First Step',
125
+ type: 'custom',
126
+ execute: async () => ({
127
+ stepId: 'first-step',
128
+ success: true,
129
+ result: 'done',
130
+ }),
131
+ },
132
+ ],
133
+ });
169
134
 
170
- // Fast access memory database
171
- const dbMemory = createCodeBoltDbMemory('cache_agent');
135
+ const result = await workflow.executeAsync();
172
136
  ```
173
137
 
174
- ## 🔧 Development
138
+ ## Conversation compaction
175
139
 
176
- ```bash
177
- # Install dependencies
178
- npm install
140
+ The unified framework includes layered compaction utilities:
179
141
 
180
- # Build the project
181
- npm run build
142
+ - `CompactionOrchestrator`
143
+ - `SnipCompact`
144
+ - `MicroCompact`
145
+ - `ContextCollapse`
146
+ - `AutoCompact`
147
+ - `ReactiveCompact`
148
+ - `PostCompactCleanup`
149
+ - `TokenEstimator`
182
150
 
183
- # Development mode
184
- npm run dev
151
+ These are used by `Agent` and `CodeboltAgent` to reduce transcript size and recover from token-limit errors.
185
152
 
186
- # Run tests
187
- npm run test
153
+ ## Development
188
154
 
189
- # Lint code
155
+ ```bash
156
+ npm install
157
+ npm run build
190
158
  npm run lint
159
+ npm test
191
160
  ```
192
161
 
193
- ## 📋 Pattern Comparison
194
-
195
- | Pattern | Complexity | Use Case | Learning Curve |
196
- |---------|------------|----------|----------------|
197
- | **Composable** | Low | Rapid prototyping, simple agents | Low |
198
- | **Builder** | Medium | Complex workflows, custom logic | Medium |
199
- | **Processor** | High | Advanced customization | High |
200
-
201
- ## 🤝 Contributing
162
+ Additional documentation generation commands:
202
163
 
203
- See our [Contributing Guide](./DOCUMENTATION.md#contributing) for development setup, coding standards, and submission guidelines.
164
+ ```bash
165
+ npm run docs
166
+ npm run docs:clean
167
+ npm run docs:watch
168
+ ```
204
169
 
205
- ## 📄 License
170
+ ## Package files
206
171
 
207
- MIT - See the main CodeBolt repository for details.
172
+ Only built files from `dist`, `README.md`, and `LICENSE` are published. The `dist` directory is generated by `npm run build` and should not be edited directly.
208
173
 
209
- ---
174
+ ## License
210
175
 
211
- **📚 [Complete Documentation](./DOCUMENTATION.md)** | **🐛 [Report Issues](https://github.com/codeboltai/codeboltjs/issues)** | **💬 [Join Community](https://discord.gg/codebolt)**
176
+ MIT
@@ -33,7 +33,10 @@ class CodeboltAgent {
33
33
  }
34
34
  createDefaultMessageModifiers(systemPrompt, allowedTools) {
35
35
  return [
36
- new processor_pieces_1.ChatHistoryMessageModifier({ enableChatHistory: true }),
36
+ new processor_pieces_1.ChatHistoryMessageModifier({
37
+ enableChatHistory: true,
38
+ includeSystemMessages: false,
39
+ }),
37
40
  new processor_pieces_1.EnvironmentContextModifier({ enableFullContext: true }),
38
41
  new processor_pieces_1.DirectoryContextModifier(),
39
42
  new processor_pieces_1.IdeContextModifier({
@@ -16,7 +16,7 @@ export declare class ResponseExecutor implements AgentResponseExecutor {
16
16
  private extractLastMessageContent;
17
17
  private getToolCalls;
18
18
  private executeTools;
19
- private isConcurrencySafe;
19
+ private sendFinalMessageToChat;
20
20
  private executeSingleToolCall;
21
21
  private executeTool;
22
22
  private parseToolResult;
@@ -146,6 +146,7 @@ class ResponseExecutor {
146
146
  const lastMessageContent = this.extractLastMessageContent(llmResponse);
147
147
  const toolCalls = this.getToolCalls(llmResponse);
148
148
  if (toolCalls.length === 0) {
149
+ await this.sendFinalMessageToChat(lastMessageContent);
149
150
  return {
150
151
  toolResults: [],
151
152
  followUpMessages: [],
@@ -179,44 +180,16 @@ class ResponseExecutor {
179
180
  const toolResults = [];
180
181
  const followUpMessages = [];
181
182
  let userRejectedToolUse = false;
182
- let currentIndex = 0;
183
- while (currentIndex < executionToolCalls.length) {
184
- const currentToolCall = executionToolCalls[currentIndex];
185
- if (!currentToolCall) {
186
- currentIndex += 1;
187
- continue;
188
- }
183
+ for (const currentToolCall of executionToolCalls) {
189
184
  if (userRejectedToolUse) {
190
185
  const skippedResult = this.parseToolResult(currentToolCall.toolUseId, 'Skipping tool execution due to previous tool user rejection.');
191
186
  toolResults.push(skippedResult);
192
- currentIndex += 1;
193
187
  continue;
194
188
  }
195
- if (!this.isConcurrencySafe(currentToolCall)) {
196
- const executionResult = await this.executeSingleToolCall(currentToolCall);
197
- toolResults.push(executionResult.toolResult);
198
- followUpMessages.push(...executionResult.followUpMessages);
199
- userRejectedToolUse = executionResult.didUserReject;
200
- currentIndex += 1;
201
- continue;
202
- }
203
- const parallelBatch = [];
204
- while (currentIndex < executionToolCalls.length) {
205
- const candidateToolCall = executionToolCalls[currentIndex];
206
- if (!candidateToolCall ||
207
- candidateToolCall.waitForPrevious ||
208
- !this.isConcurrencySafe(candidateToolCall)) {
209
- break;
210
- }
211
- parallelBatch.push(candidateToolCall);
212
- currentIndex += 1;
213
- }
214
- const batchResults = await Promise.all(parallelBatch.map((toolCall) => this.executeSingleToolCall(toolCall)));
215
- for (const batchResult of batchResults) {
216
- toolResults.push(batchResult.toolResult);
217
- followUpMessages.push(...batchResult.followUpMessages);
218
- userRejectedToolUse = userRejectedToolUse || batchResult.didUserReject;
219
- }
189
+ const executionResult = await this.executeSingleToolCall(currentToolCall);
190
+ toolResults.push(executionResult.toolResult);
191
+ followUpMessages.push(...executionResult.followUpMessages);
192
+ userRejectedToolUse = executionResult.didUserReject;
220
193
  }
221
194
  if (completionToolCalls.length > 0) {
222
195
  const completionToolCall = completionToolCalls.at(-1);
@@ -236,61 +209,16 @@ class ResponseExecutor {
236
209
  hadToolCalls: true,
237
210
  };
238
211
  }
239
- isConcurrencySafe(toolCall) {
240
- var _a;
241
- if (toolCall.waitForPrevious) {
242
- return false;
212
+ async sendFinalMessageToChat(message) {
213
+ if (!message || message.trim().length === 0) {
214
+ return;
243
215
  }
244
- const normalizedToolName = toolCall.toolName.toLowerCase();
245
- if (normalizedToolName.startsWith('subagent--') ||
246
- normalizedToolName.includes('thread_management')) {
247
- return false;
216
+ try {
217
+ await Promise.resolve(codeboltjs_1.default.chat.sendMessage(message));
248
218
  }
249
- const actualToolName = (_a = normalizedToolName.split('--').at(-1)) !== null && _a !== void 0 ? _a : normalizedToolName;
250
- const toolNameTokens = actualToolName
251
- .split(/[^a-z0-9]+/)
252
- .filter((token) => token.length > 0);
253
- const mutatingKeywords = new Set([
254
- 'write',
255
- 'edit',
256
- 'create',
257
- 'delete',
258
- 'remove',
259
- 'rename',
260
- 'move',
261
- 'copy',
262
- 'apply',
263
- 'shell',
264
- 'command',
265
- 'run',
266
- 'exec',
267
- 'thread_management',
268
- 'attempt_completion',
269
- 'completion',
270
- 'todo',
271
- 'spawn',
272
- 'start',
273
- ]);
274
- if (toolNameTokens.some((token) => mutatingKeywords.has(token))) {
275
- return false;
219
+ catch (error) {
220
+ console.error('[ResponseExecutor] Failed to send final chat message:', error);
276
221
  }
277
- const readOnlyKeywords = new Set([
278
- 'read',
279
- 'search',
280
- 'list',
281
- 'find',
282
- 'glob',
283
- 'grep',
284
- 'view',
285
- 'stat',
286
- 'inspect',
287
- 'get',
288
- 'show',
289
- 'query',
290
- 'ls',
291
- 'cat',
292
- ]);
293
- return toolNameTokens.some((token) => readOnlyKeywords.has(token));
294
222
  }
295
223
  async executeSingleToolCall(toolCall) {
296
224
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codebolt/agent",
3
- "version": "6.0.1",
3
+ "version": "6.1.3",
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",
@@ -14,7 +14,8 @@
14
14
  "clean": "rm -rf dist",
15
15
  "dev": "tsc --watch",
16
16
  "test": "echo \"No tests yet, but build passes\" && exit 0",
17
- "lint:test": "eslint src/**/*.ts && tsc --noEmit",
17
+ "lint": "eslint src/**/*.ts && tsc --noEmit",
18
+ "lint:test": "npm run lint",
18
19
  "docs": "node script/gen-docusaurus-agent-types.js",
19
20
  "docs:clean": "node script/gen-docusaurus-agent-types.js --clean",
20
21
  "docs:watch": "node script/gen-docusaurus-agent-types.js --watch"
@@ -48,13 +49,16 @@
48
49
  "devDependencies": {
49
50
  "@codebolt/codeboltjs": "*",
50
51
  "@codebolt/types": "*",
52
+ "@eslint/js": "^8.57.1",
51
53
  "@types/js-yaml": "^4.0.9",
52
54
  "@types/node": "^20.14.2",
53
55
  "@types/uri-templates": "^0.1.34",
54
56
  "@types/ws": "^8.5.10",
57
+ "eslint": "^8.57.1",
55
58
  "typedoc": "0.28.16",
56
59
  "typedoc-plugin-markdown": "4.9.0",
57
- "typescript": "^5.4.5"
60
+ "typescript": "^5.4.5",
61
+ "typescript-eslint": "^7.18.0"
58
62
  },
59
63
  "exports": {
60
64
  ".": {