@codebolt/agent 6.1.23 → 6.1.26
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/index.d.ts +1 -0
- package/dist/processor-pieces/messageModifiers/agentEventQueueModifier.d.ts +8 -0
- package/dist/processor-pieces/messageModifiers/agentEventQueueModifier.js +18 -0
- package/dist/processor-pieces/messageModifiers/coreSystemPromptModifier.js +1 -0
- package/dist/processor-pieces/messageModifiers/index.d.ts +2 -0
- package/dist/processor-pieces/messageModifiers/index.js +5 -1
- package/dist/processor-pieces/messageModifiers/toolGroupContextModifier.d.ts +27 -0
- package/dist/processor-pieces/messageModifiers/toolGroupContextModifier.js +111 -0
- package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +3 -5
- package/dist/processor-pieces/postToolCallProcessors/agentEventQueuePostToolCallProcessor.d.ts +7 -0
- package/dist/processor-pieces/postToolCallProcessors/agentEventQueuePostToolCallProcessor.js +21 -0
- package/dist/processor-pieces/postToolCallProcessors/index.d.ts +1 -0
- package/dist/processor-pieces/postToolCallProcessors/index.js +3 -1
- package/dist/processor-pieces/utils/agentEventQueuePrompt.d.ts +21 -0
- package/dist/processor-pieces/utils/agentEventQueuePrompt.js +189 -0
- package/dist/types/automation.d.ts +76 -0
- package/dist/types/automation.js +2 -0
- package/dist/unified/agent/agent.d.ts +25 -2
- package/dist/unified/agent/agent.js +304 -15
- package/dist/unified/base/agentStep.js +1 -1
- package/dist/unified/base/promptContext.js +23 -3
- package/dist/unified/base/responseExecutor.d.ts +1 -1
- package/dist/unified/base/responseExecutor.js +24 -7
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
export * as ProcessorPieces from './processor-pieces';
|
|
2
2
|
export * from './unified';
|
|
3
|
+
export type { Automation, AutomationAction, AutomationActionType, AutomationCalendarOptions, AutomationRun, AutomationRunStatus, AutomationTrigger, Recipient, RecipientAddress, RecipientKind, RecipientOption, RecipientSnapshot, ScheduleDefinition, } from './types/automation';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { MessageModifier, ProcessedMessage } from '@codebolt/types/agent';
|
|
2
|
+
import type { FlatUserMessage } from '@codebolt/types/sdk';
|
|
3
|
+
import { type AgentEventQueueProcessorOptions } from '../utils/agentEventQueuePrompt';
|
|
4
|
+
export declare class AgentEventQueueModifier implements MessageModifier {
|
|
5
|
+
private readonly options;
|
|
6
|
+
constructor(options?: AgentEventQueueProcessorOptions);
|
|
7
|
+
modify(_originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
|
|
8
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
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.AgentEventQueueModifier = void 0;
|
|
7
|
+
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
8
|
+
const agentEventQueuePrompt_1 = require("../utils/agentEventQueuePrompt");
|
|
9
|
+
class AgentEventQueueModifier {
|
|
10
|
+
constructor(options = {}) {
|
|
11
|
+
this.options = options;
|
|
12
|
+
}
|
|
13
|
+
async modify(_originalRequest, createdMessage) {
|
|
14
|
+
const pendingEvents = await codeboltjs_1.default.agentEventQueue.getPendingEvents();
|
|
15
|
+
return (0, agentEventQueuePrompt_1.injectAgentQueueEventsIntoPrompt)(createdMessage, pendingEvents, this.options);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.AgentEventQueueModifier = AgentEventQueueModifier;
|
|
@@ -61,6 +61,7 @@ ${workspaceContext}
|
|
|
61
61
|
- **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
|
|
62
62
|
- **Path Construction:** Before using any file system tool, you must construct the full absolute path for the file_path argument. Always combine the absolute path of the project's root directory with the file's path relative to the root. For example, if the project root is /path/to/project/ and the file is foo/bar/baz.txt, the final path you must use is /path/to/project/foo/bar/baz.txt. If the user provides a relative path, you must resolve it against the root directory to create an absolute path.
|
|
63
63
|
- **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.
|
|
64
|
+
- **Mail notifications:** If you receive a mail notification, treat it as a notification only. The event may include a short message body, but use the mail_get_message tool with the provided messageId when you need full mail details. If mail_get_message is not in your available tools, use tool search to find it.
|
|
64
65
|
|
|
65
66
|
# Primary Workflows
|
|
66
67
|
|
|
@@ -8,9 +8,11 @@ export { ArgumentProcessorModifier, type ArgumentProcessorOptions } from './argu
|
|
|
8
8
|
export { MemoryImportModifier, type MemoryImportOptions } from './memoryImportModifier';
|
|
9
9
|
export { LoopDetectionModifier, type LoopDetectionOptions } from '../postInferenceProcessors/loopDetectionModifier';
|
|
10
10
|
export { ToolInjectionModifier, type ToolInjectionOptions } from './toolInjectionModifier';
|
|
11
|
+
export { ToolGroupContextModifier, type ToolGroupContextOptions } from './toolGroupContextModifier';
|
|
11
12
|
export { ToolManifestPromptModifier, type ToolManifestPromptModifierOptions } from './toolManifestPromptModifier';
|
|
12
13
|
export { ChatRecordingModifier, type ChatRecordingOptions } from './chatRecordingModifier';
|
|
13
14
|
export { ChatHistoryMessageModifier, type ChatHistoryMessageModifierOptions } from './chatHistoryMessageModifier';
|
|
15
|
+
export { AgentEventQueueModifier } from './agentEventQueueModifier';
|
|
14
16
|
export { ContextAssemblyModifier, type ContextAssemblyModifierOptions } from './contextAssemblyModifier';
|
|
15
17
|
export { RuleBasedContextModifier, type RuleBasedContextModifierOptions } from './contextAssemblyModifier';
|
|
16
18
|
export { MemoryTypeContextModifier, type MemoryTypeContextModifierOptions } from './contextAssemblyModifier';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MemoryTypeContextModifier = exports.RuleBasedContextModifier = exports.ContextAssemblyModifier = exports.ChatHistoryMessageModifier = exports.ChatRecordingModifier = exports.ToolManifestPromptModifier = exports.ToolInjectionModifier = exports.LoopDetectionModifier = exports.MemoryImportModifier = exports.ArgumentProcessorModifier = exports.CapabilityContextModifier = exports.AtFileProcessorModifier = exports.IdeContextModifier = exports.DirectoryContextModifier = exports.CoreSystemPromptModifier = exports.EnvironmentContextModifier = void 0;
|
|
3
|
+
exports.MemoryTypeContextModifier = exports.RuleBasedContextModifier = exports.ContextAssemblyModifier = exports.AgentEventQueueModifier = exports.ChatHistoryMessageModifier = exports.ChatRecordingModifier = exports.ToolManifestPromptModifier = exports.ToolGroupContextModifier = exports.ToolInjectionModifier = exports.LoopDetectionModifier = exports.MemoryImportModifier = exports.ArgumentProcessorModifier = exports.CapabilityContextModifier = exports.AtFileProcessorModifier = exports.IdeContextModifier = exports.DirectoryContextModifier = exports.CoreSystemPromptModifier = exports.EnvironmentContextModifier = void 0;
|
|
4
4
|
// Gemini-CLI equivalent modifiers
|
|
5
5
|
var environmentContextModifier_1 = require("./environmentContextModifier");
|
|
6
6
|
Object.defineProperty(exports, "EnvironmentContextModifier", { enumerable: true, get: function () { return environmentContextModifier_1.EnvironmentContextModifier; } });
|
|
@@ -22,12 +22,16 @@ var loopDetectionModifier_1 = require("../postInferenceProcessors/loopDetectionM
|
|
|
22
22
|
Object.defineProperty(exports, "LoopDetectionModifier", { enumerable: true, get: function () { return loopDetectionModifier_1.LoopDetectionModifier; } });
|
|
23
23
|
var toolInjectionModifier_1 = require("./toolInjectionModifier");
|
|
24
24
|
Object.defineProperty(exports, "ToolInjectionModifier", { enumerable: true, get: function () { return toolInjectionModifier_1.ToolInjectionModifier; } });
|
|
25
|
+
var toolGroupContextModifier_1 = require("./toolGroupContextModifier");
|
|
26
|
+
Object.defineProperty(exports, "ToolGroupContextModifier", { enumerable: true, get: function () { return toolGroupContextModifier_1.ToolGroupContextModifier; } });
|
|
25
27
|
var toolManifestPromptModifier_1 = require("./toolManifestPromptModifier");
|
|
26
28
|
Object.defineProperty(exports, "ToolManifestPromptModifier", { enumerable: true, get: function () { return toolManifestPromptModifier_1.ToolManifestPromptModifier; } });
|
|
27
29
|
var chatRecordingModifier_1 = require("./chatRecordingModifier");
|
|
28
30
|
Object.defineProperty(exports, "ChatRecordingModifier", { enumerable: true, get: function () { return chatRecordingModifier_1.ChatRecordingModifier; } });
|
|
29
31
|
var chatHistoryMessageModifier_1 = require("./chatHistoryMessageModifier");
|
|
30
32
|
Object.defineProperty(exports, "ChatHistoryMessageModifier", { enumerable: true, get: function () { return chatHistoryMessageModifier_1.ChatHistoryMessageModifier; } });
|
|
33
|
+
var agentEventQueueModifier_1 = require("./agentEventQueueModifier");
|
|
34
|
+
Object.defineProperty(exports, "AgentEventQueueModifier", { enumerable: true, get: function () { return agentEventQueueModifier_1.AgentEventQueueModifier; } });
|
|
31
35
|
var contextAssemblyModifier_1 = require("./contextAssemblyModifier");
|
|
32
36
|
Object.defineProperty(exports, "ContextAssemblyModifier", { enumerable: true, get: function () { return contextAssemblyModifier_1.ContextAssemblyModifier; } });
|
|
33
37
|
var contextAssemblyModifier_2 = require("./contextAssemblyModifier");
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ProcessedMessage } from '@codebolt/types/agent';
|
|
2
|
+
import type { FlatUserMessage } from '@codebolt/types/sdk';
|
|
3
|
+
import type { RuntimeCatalogGroup, ToolSourceType } from '@codebolt/types/sdk';
|
|
4
|
+
import { BaseMessageModifier } from '../base';
|
|
5
|
+
export interface ToolGroupContextOptions {
|
|
6
|
+
location?: 'SystemMessage' | 'InsidePrompt';
|
|
7
|
+
groups?: RuntimeCatalogGroup[];
|
|
8
|
+
loadGroups?: () => Promise<RuntimeCatalogGroup[]>;
|
|
9
|
+
includeToolGroups?: boolean;
|
|
10
|
+
includeResourceGroups?: boolean;
|
|
11
|
+
includeCounts?: boolean;
|
|
12
|
+
includeSourceLabels?: boolean;
|
|
13
|
+
allowedGroupIds?: string[];
|
|
14
|
+
excludedGroupIds?: string[];
|
|
15
|
+
allowedSourceTypes?: ToolSourceType[];
|
|
16
|
+
maxGroups?: number;
|
|
17
|
+
maxCharacters?: number;
|
|
18
|
+
}
|
|
19
|
+
export declare class ToolGroupContextModifier extends BaseMessageModifier {
|
|
20
|
+
private readonly options;
|
|
21
|
+
constructor(options?: ToolGroupContextOptions);
|
|
22
|
+
modify(_originalRequest: FlatUserMessage, createdMessage: ProcessedMessage): Promise<ProcessedMessage>;
|
|
23
|
+
private resolveGroups;
|
|
24
|
+
private loadRuntimeGroups;
|
|
25
|
+
private formatGroups;
|
|
26
|
+
private withMetadata;
|
|
27
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
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.ToolGroupContextModifier = void 0;
|
|
7
|
+
const base_1 = require("../base");
|
|
8
|
+
const promptContext_1 = require("../../unified/base/promptContext");
|
|
9
|
+
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
10
|
+
class ToolGroupContextModifier extends base_1.BaseMessageModifier {
|
|
11
|
+
constructor(options = {}) {
|
|
12
|
+
super();
|
|
13
|
+
this.options = options;
|
|
14
|
+
}
|
|
15
|
+
async modify(_originalRequest, createdMessage) {
|
|
16
|
+
const groups = await this.resolveGroups();
|
|
17
|
+
if (groups.length === 0) {
|
|
18
|
+
return createdMessage;
|
|
19
|
+
}
|
|
20
|
+
const context = this.formatGroups(groups);
|
|
21
|
+
if (!context) {
|
|
22
|
+
return createdMessage;
|
|
23
|
+
}
|
|
24
|
+
if (this.options.location === 'InsidePrompt') {
|
|
25
|
+
const updatedMessage = (0, promptContext_1.updateCurrentUserMessage)(createdMessage, (message) => ({
|
|
26
|
+
...message,
|
|
27
|
+
content: typeof message.content === 'string'
|
|
28
|
+
? `${message.content}\n\n${context}`
|
|
29
|
+
: [
|
|
30
|
+
...(Array.isArray(message.content)
|
|
31
|
+
? message.content
|
|
32
|
+
: [{ type: 'text', text: String(message.content) }]),
|
|
33
|
+
{ type: 'text', text: context },
|
|
34
|
+
],
|
|
35
|
+
}));
|
|
36
|
+
return this.withMetadata(updatedMessage, groups);
|
|
37
|
+
}
|
|
38
|
+
const groupMessage = { role: 'system', content: context };
|
|
39
|
+
return this.withMetadata((0, promptContext_1.appendSystemContextMessage)(createdMessage, groupMessage), groups);
|
|
40
|
+
}
|
|
41
|
+
async resolveGroups() {
|
|
42
|
+
const availableGroups = this.options.loadGroups
|
|
43
|
+
? await this.options.loadGroups()
|
|
44
|
+
: this.options.groups || await this.loadRuntimeGroups();
|
|
45
|
+
const allowedIds = this.options.allowedGroupIds
|
|
46
|
+
? new Set(this.options.allowedGroupIds)
|
|
47
|
+
: undefined;
|
|
48
|
+
const excludedIds = new Set(this.options.excludedGroupIds || []);
|
|
49
|
+
const allowedSourceTypes = this.options.allowedSourceTypes
|
|
50
|
+
? new Set(this.options.allowedSourceTypes)
|
|
51
|
+
: undefined;
|
|
52
|
+
const filteredGroups = availableGroups
|
|
53
|
+
.filter((group) => this.options.includeToolGroups !== false || group.kind !== 'tool-group')
|
|
54
|
+
.filter((group) => this.options.includeResourceGroups !== false || group.kind !== 'resource-group')
|
|
55
|
+
.filter((group) => !allowedIds || allowedIds.has(group.id) || allowedIds.has(group.kind === 'tool-group' ? group.groupId : group.resourceType))
|
|
56
|
+
.filter((group) => !excludedIds.has(group.id))
|
|
57
|
+
.filter((group) => group.kind !== 'tool-group' || !allowedSourceTypes || allowedSourceTypes.has(group.sourceType))
|
|
58
|
+
.filter((group) => group.kind !== 'tool-group' || group.toolCount > 0)
|
|
59
|
+
.sort((left, right) => (right.priority || 0) - (left.priority || 0) ||
|
|
60
|
+
left.displayName.localeCompare(right.displayName));
|
|
61
|
+
return this.options.maxGroups === undefined
|
|
62
|
+
? filteredGroups
|
|
63
|
+
: filteredGroups.slice(0, Math.max(0, this.options.maxGroups));
|
|
64
|
+
}
|
|
65
|
+
async loadRuntimeGroups() {
|
|
66
|
+
var _a;
|
|
67
|
+
const toolsApi = codeboltjs_1.default.tools;
|
|
68
|
+
if (!(toolsApi === null || toolsApi === void 0 ? void 0 : toolsApi.listToolGroups)) {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
const response = await toolsApi.listToolGroups();
|
|
72
|
+
return Array.isArray((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.groups) ? response.data.groups : [];
|
|
73
|
+
}
|
|
74
|
+
formatGroups(groups) {
|
|
75
|
+
const toolGroups = groups.filter((group) => group.kind === 'tool-group');
|
|
76
|
+
const resourceGroups = groups.filter((group) => group.kind === 'resource-group');
|
|
77
|
+
const sections = ['Available capabilities:'];
|
|
78
|
+
if (toolGroups.length > 0) {
|
|
79
|
+
sections.push('Tool groups:', ...toolGroups.map((group) => {
|
|
80
|
+
if (group.kind !== 'tool-group')
|
|
81
|
+
return '';
|
|
82
|
+
const count = this.options.includeCounts === false ? '' : ` (${group.toolCount})`;
|
|
83
|
+
const source = this.options.includeSourceLabels ? ` [${group.sourceType}]` : '';
|
|
84
|
+
return `- ${group.displayName}${count}${source}: ${group.description}`;
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
if (resourceGroups.length > 0) {
|
|
88
|
+
sections.push('Resource groups:', ...resourceGroups.map((group) => `- ${group.displayName}: ${group.description}`));
|
|
89
|
+
}
|
|
90
|
+
const content = sections.filter(Boolean).join('\n');
|
|
91
|
+
const maxCharacters = this.options.maxCharacters;
|
|
92
|
+
if (maxCharacters === undefined) {
|
|
93
|
+
return content;
|
|
94
|
+
}
|
|
95
|
+
return content.length <= maxCharacters
|
|
96
|
+
? content
|
|
97
|
+
: `${content.slice(0, Math.max(0, maxCharacters - 1)).trimEnd()}…`;
|
|
98
|
+
}
|
|
99
|
+
withMetadata(message, groups) {
|
|
100
|
+
return {
|
|
101
|
+
...message,
|
|
102
|
+
metadata: {
|
|
103
|
+
...message.metadata,
|
|
104
|
+
toolGroupsInjected: true,
|
|
105
|
+
toolGroupCount: groups.length,
|
|
106
|
+
injectedToolGroupIds: groups.map((group) => group.id),
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
exports.ToolGroupContextModifier = ToolGroupContextModifier;
|
|
@@ -77,13 +77,11 @@ class ToolInjectionModifier extends base_1.BaseMessageModifier {
|
|
|
77
77
|
role: 'system',
|
|
78
78
|
content: `Available Tools:\n${toolsInfo}`
|
|
79
79
|
};
|
|
80
|
+
const updatedMessage = (0, promptContext_1.appendSystemContextMessage)(createdMessage, toolsMessage);
|
|
80
81
|
return {
|
|
81
|
-
|
|
82
|
-
...createdMessage.message,
|
|
83
|
-
input: [toolsMessage, ...createdMessage.message.input]
|
|
84
|
-
},
|
|
82
|
+
...updatedMessage,
|
|
85
83
|
metadata: {
|
|
86
|
-
...
|
|
84
|
+
...updatedMessage.metadata,
|
|
87
85
|
toolsInjected: true,
|
|
88
86
|
toolsLocation: 'SystemMessage',
|
|
89
87
|
toolsCount: tools.length
|
package/dist/processor-pieces/postToolCallProcessors/agentEventQueuePostToolCallProcessor.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { PostToolCallProcessor, PostToolCallProcessorInput, PostToolCallProcessorOutput } from '@codebolt/types/agent';
|
|
2
|
+
import { type AgentEventQueueProcessorOptions } from '../utils/agentEventQueuePrompt';
|
|
3
|
+
export declare class AgentEventQueuePostToolCallProcessor implements PostToolCallProcessor {
|
|
4
|
+
private readonly options;
|
|
5
|
+
constructor(options?: AgentEventQueueProcessorOptions);
|
|
6
|
+
modify(input: PostToolCallProcessorInput): Promise<PostToolCallProcessorOutput>;
|
|
7
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
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.AgentEventQueuePostToolCallProcessor = void 0;
|
|
7
|
+
const codeboltjs_1 = __importDefault(require("@codebolt/codeboltjs"));
|
|
8
|
+
const agentEventQueuePrompt_1 = require("../utils/agentEventQueuePrompt");
|
|
9
|
+
class AgentEventQueuePostToolCallProcessor {
|
|
10
|
+
constructor(options = {}) {
|
|
11
|
+
this.options = options;
|
|
12
|
+
}
|
|
13
|
+
async modify(input) {
|
|
14
|
+
const pendingEvents = await codeboltjs_1.default.agentEventQueue.getPendingEvents();
|
|
15
|
+
return {
|
|
16
|
+
nextPrompt: (0, agentEventQueuePrompt_1.injectAgentQueueEventsIntoPrompt)(input.nextPrompt, pendingEvents, this.options),
|
|
17
|
+
shouldExit: false,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.AgentEventQueuePostToolCallProcessor = AgentEventQueuePostToolCallProcessor;
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
export { ShellProcessorModifier } from './shellProcessorModifier';
|
|
2
|
+
export { AgentEventQueuePostToolCallProcessor } from './agentEventQueuePostToolCallProcessor';
|
|
2
3
|
export { ConversationCompactorModifier, type ConversationCompactorOptions, type CompressionMetadata, CompressionStatus } from './conversationCompactorModifier';
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.CompressionStatus = exports.ConversationCompactorModifier = exports.ShellProcessorModifier = void 0;
|
|
3
|
+
exports.CompressionStatus = exports.ConversationCompactorModifier = exports.AgentEventQueuePostToolCallProcessor = exports.ShellProcessorModifier = void 0;
|
|
4
4
|
var shellProcessorModifier_1 = require("./shellProcessorModifier");
|
|
5
5
|
Object.defineProperty(exports, "ShellProcessorModifier", { enumerable: true, get: function () { return shellProcessorModifier_1.ShellProcessorModifier; } });
|
|
6
|
+
var agentEventQueuePostToolCallProcessor_1 = require("./agentEventQueuePostToolCallProcessor");
|
|
7
|
+
Object.defineProperty(exports, "AgentEventQueuePostToolCallProcessor", { enumerable: true, get: function () { return agentEventQueuePostToolCallProcessor_1.AgentEventQueuePostToolCallProcessor; } });
|
|
6
8
|
var conversationCompactorModifier_1 = require("./conversationCompactorModifier");
|
|
7
9
|
Object.defineProperty(exports, "ConversationCompactorModifier", { enumerable: true, get: function () { return conversationCompactorModifier_1.ConversationCompactorModifier; } });
|
|
8
10
|
Object.defineProperty(exports, "CompressionStatus", { enumerable: true, get: function () { return conversationCompactorModifier_1.CompressionStatus; } });
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ProcessedMessage } from '@codebolt/types/agent';
|
|
2
|
+
import type { MessageObject } from '@codebolt/types/sdk';
|
|
3
|
+
export interface AgentEventQueueProcessorOptions {
|
|
4
|
+
enableLogging?: boolean;
|
|
5
|
+
}
|
|
6
|
+
interface AgentEventMessageLike {
|
|
7
|
+
eventId?: string;
|
|
8
|
+
id?: string;
|
|
9
|
+
type?: string;
|
|
10
|
+
eventType?: string;
|
|
11
|
+
data?: Record<string, unknown>;
|
|
12
|
+
payload?: Record<string, unknown>;
|
|
13
|
+
metadata?: Record<string, unknown>;
|
|
14
|
+
target?: {
|
|
15
|
+
threadId?: string;
|
|
16
|
+
};
|
|
17
|
+
threadId?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function injectAgentQueueEventsIntoPrompt(prompt: ProcessedMessage, events: AgentEventMessageLike[], options?: AgentEventQueueProcessorOptions): ProcessedMessage;
|
|
20
|
+
export declare function formatAgentQueueEventAsMessage(event: AgentEventMessageLike): MessageObject;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.injectAgentQueueEventsIntoPrompt = injectAgentQueueEventsIntoPrompt;
|
|
4
|
+
exports.formatAgentQueueEventAsMessage = formatAgentQueueEventAsMessage;
|
|
5
|
+
const promptContext_1 = require("../../unified/base/promptContext");
|
|
6
|
+
const FAILURE_STATUSES = new Set([
|
|
7
|
+
'failed',
|
|
8
|
+
'failure',
|
|
9
|
+
'error',
|
|
10
|
+
'errored',
|
|
11
|
+
'stopped',
|
|
12
|
+
'cancelled',
|
|
13
|
+
'canceled',
|
|
14
|
+
'crashed',
|
|
15
|
+
'timeout',
|
|
16
|
+
'timed_out',
|
|
17
|
+
]);
|
|
18
|
+
function injectAgentQueueEventsIntoPrompt(prompt, events, options = {}) {
|
|
19
|
+
if (options.enableLogging && events.length > 0) {
|
|
20
|
+
console.log(`[AgentEventQueue] injecting ${events.length} event(s)`);
|
|
21
|
+
}
|
|
22
|
+
return events.reduce((updatedPrompt, event) => (0, promptContext_1.appendTranscriptMessage)(updatedPrompt, formatAgentQueueEventAsMessage(event)), prompt);
|
|
23
|
+
}
|
|
24
|
+
function formatAgentQueueEventAsMessage(event) {
|
|
25
|
+
const eventType = event.type || event.eventType || 'unknown';
|
|
26
|
+
const eventData = event.data || event.payload || {};
|
|
27
|
+
switch (eventType) {
|
|
28
|
+
case 'steering':
|
|
29
|
+
return createUserMessage(`<steering_message>
|
|
30
|
+
<instruction>${formatInstruction(eventData)}</instruction>
|
|
31
|
+
<context>The user has sent a steering message while the agent is working. Review the instruction and adjust the current approach accordingly. Prioritize this instruction for the next actions.</context>
|
|
32
|
+
</steering_message>`);
|
|
33
|
+
case 'threadCompletion':
|
|
34
|
+
return formatThreadCompletionEvent(eventData);
|
|
35
|
+
case 'backgroundCommandCompletion':
|
|
36
|
+
return formatBackgroundCommandCompletionEvent(eventData);
|
|
37
|
+
case 'forceStopCleanup':
|
|
38
|
+
return createUserMessage(`<force_stop_cleanup>
|
|
39
|
+
${safeStringify(eventData)}
|
|
40
|
+
</force_stop_cleanup>`);
|
|
41
|
+
case 'agentMessage':
|
|
42
|
+
return createUserMessage(`<agent_event>
|
|
43
|
+
<source>${formatSource(event)}</source>
|
|
44
|
+
<content>${formatContent(eventData)}</content>
|
|
45
|
+
</agent_event>`);
|
|
46
|
+
case 'mailNotification':
|
|
47
|
+
return formatMailNotificationEvent(eventData);
|
|
48
|
+
case 'calendarUpdate':
|
|
49
|
+
case 'taskUpdate':
|
|
50
|
+
case 'systemNotification':
|
|
51
|
+
case 'custom':
|
|
52
|
+
return createUserMessage(`<agent_event>
|
|
53
|
+
<type>${eventType}</type>
|
|
54
|
+
<source>${formatSource(event)}</source>
|
|
55
|
+
<content>${safeStringify(eventData)}</content>
|
|
56
|
+
</agent_event>`);
|
|
57
|
+
default:
|
|
58
|
+
return createUserMessage(`<agent_event>
|
|
59
|
+
<type>${eventType}</type>
|
|
60
|
+
<source>${formatSource(event)}</source>
|
|
61
|
+
<content>${safeStringify(eventData)}</content>
|
|
62
|
+
<metadata>${safeStringify(event.metadata || {})}</metadata>
|
|
63
|
+
</agent_event>`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function formatThreadCompletionEvent(eventData) {
|
|
67
|
+
const failureReason = getEventFailureReason(eventData);
|
|
68
|
+
if (failureReason) {
|
|
69
|
+
return createUserMessage(`<thread_failure_event>
|
|
70
|
+
<context>This is a Codebolt application event. A background child thread failed, stopped, or returned an error-shaped result. Treat this as a failed child task, report it to the parent workflow, and decide whether to retry, continue with remaining work, or stop based on the user's objective.</context>
|
|
71
|
+
<reason>${failureReason}</reason>
|
|
72
|
+
<event>${safeStringify(eventData)}</event>
|
|
73
|
+
</thread_failure_event>`);
|
|
74
|
+
}
|
|
75
|
+
return createUserMessage(`<thread_completion_event>
|
|
76
|
+
<context>This is an application event from Codebolt, not user text and not assistant output. Use it to update background-thread state. If this completes the current batch, continue with the next required work and use thread tools for any next batch.</context>
|
|
77
|
+
<event>${safeStringify(eventData)}</event>
|
|
78
|
+
</thread_completion_event>`);
|
|
79
|
+
}
|
|
80
|
+
function formatBackgroundCommandCompletionEvent(eventData) {
|
|
81
|
+
const failureReason = getEventFailureReason(eventData);
|
|
82
|
+
if (failureReason) {
|
|
83
|
+
return createUserMessage(`<background_command_failure_event>
|
|
84
|
+
<context>This is a Codebolt application event. A background command failed, stopped, or returned an error-shaped result. Treat this as a failed background task and surface the error in the current workflow.</context>
|
|
85
|
+
<reason>${failureReason}</reason>
|
|
86
|
+
<event>${safeStringify(eventData)}</event>
|
|
87
|
+
</background_command_failure_event>`);
|
|
88
|
+
}
|
|
89
|
+
return createUserMessage(`<background_command_completion_event>
|
|
90
|
+
<context>This is an application event from Codebolt, not user text and not assistant output. Use it to update background-command state and continue the current task.</context>
|
|
91
|
+
<event>${safeStringify(eventData)}</event>
|
|
92
|
+
</background_command_completion_event>`);
|
|
93
|
+
}
|
|
94
|
+
function formatMailNotificationEvent(eventData) {
|
|
95
|
+
const messageId = String(eventData['messageId'] ||
|
|
96
|
+
getNestedValue(eventData, ['toolInput', 'messageId']) ||
|
|
97
|
+
'unknown');
|
|
98
|
+
const mailMessage = typeof eventData['message'] === 'string'
|
|
99
|
+
? eventData['message']
|
|
100
|
+
: typeof eventData['body'] === 'string'
|
|
101
|
+
? eventData['body']
|
|
102
|
+
: '';
|
|
103
|
+
const contentLines = [
|
|
104
|
+
`You have received a mail notification. To get the mail details, call the mail_get_message tool with parameter: { "messageId": "${messageId}" }. If mail_get_message is not in your available tools, use tool search to find it.`,
|
|
105
|
+
];
|
|
106
|
+
if (mailMessage.trim()) {
|
|
107
|
+
contentLines.push('', 'Message:', mailMessage);
|
|
108
|
+
}
|
|
109
|
+
return createUserMessage(contentLines.join('\n'));
|
|
110
|
+
}
|
|
111
|
+
function createUserMessage(content) {
|
|
112
|
+
return {
|
|
113
|
+
role: 'user',
|
|
114
|
+
content,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function getEventFailureReason(eventData) {
|
|
118
|
+
if (eventData['error']) {
|
|
119
|
+
return typeof eventData['error'] === 'string'
|
|
120
|
+
? eventData['error']
|
|
121
|
+
: safeStringify(eventData['error']);
|
|
122
|
+
}
|
|
123
|
+
const status = typeof eventData['status'] === 'string'
|
|
124
|
+
? eventData['status'].toLowerCase()
|
|
125
|
+
: '';
|
|
126
|
+
if (FAILURE_STATUSES.has(status)) {
|
|
127
|
+
return `Event status is ${eventData['status']}`;
|
|
128
|
+
}
|
|
129
|
+
const messageObject = parseJsonObject(eventData['message']);
|
|
130
|
+
const outputObject = parseJsonObject(eventData['output']);
|
|
131
|
+
const nestedError = (messageObject === null || messageObject === void 0 ? void 0 : messageObject['error']) || (outputObject === null || outputObject === void 0 ? void 0 : outputObject['error']);
|
|
132
|
+
if (nestedError) {
|
|
133
|
+
return typeof nestedError === 'string'
|
|
134
|
+
? nestedError
|
|
135
|
+
: safeStringify(nestedError);
|
|
136
|
+
}
|
|
137
|
+
const nestedStatus = String((messageObject === null || messageObject === void 0 ? void 0 : messageObject['status']) || (outputObject === null || outputObject === void 0 ? void 0 : outputObject['status']) || '').toLowerCase();
|
|
138
|
+
if (FAILURE_STATUSES.has(nestedStatus)) {
|
|
139
|
+
return `Nested result status is ${(messageObject === null || messageObject === void 0 ? void 0 : messageObject['status']) || (outputObject === null || outputObject === void 0 ? void 0 : outputObject['status'])}`;
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
function parseJsonObject(value) {
|
|
144
|
+
if (typeof value !== 'string') {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
const parsed = JSON.parse(value);
|
|
149
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
150
|
+
? parsed
|
|
151
|
+
: null;
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function getNestedValue(source, path) {
|
|
158
|
+
let currentValue = source;
|
|
159
|
+
for (const segment of path) {
|
|
160
|
+
if (!currentValue || typeof currentValue !== 'object' || Array.isArray(currentValue)) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
currentValue = currentValue[segment];
|
|
164
|
+
}
|
|
165
|
+
return currentValue;
|
|
166
|
+
}
|
|
167
|
+
function formatInstruction(eventData) {
|
|
168
|
+
return typeof eventData['instruction'] === 'string'
|
|
169
|
+
? eventData['instruction']
|
|
170
|
+
: safeStringify(eventData);
|
|
171
|
+
}
|
|
172
|
+
function formatSource(event) {
|
|
173
|
+
var _a, _b;
|
|
174
|
+
const source = ((_a = event.metadata) === null || _a === void 0 ? void 0 : _a['sourceAgentId']) || ((_b = event.metadata) === null || _b === void 0 ? void 0 : _b['source']);
|
|
175
|
+
return typeof source === 'string' && source.length > 0 ? source : 'system';
|
|
176
|
+
}
|
|
177
|
+
function formatContent(eventData) {
|
|
178
|
+
return typeof eventData['content'] === 'string'
|
|
179
|
+
? eventData['content']
|
|
180
|
+
: safeStringify(eventData);
|
|
181
|
+
}
|
|
182
|
+
function safeStringify(value) {
|
|
183
|
+
try {
|
|
184
|
+
return JSON.stringify(value, null, 2);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
return `[Unserializable event: ${error instanceof Error ? error.message : String(error)}]`;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
export type RecipientAddress = `subagent:${string}` | `threadagent:${string}` | `newagent:${string}`;
|
|
2
|
+
export type RecipientKind = 'subagent' | 'threadagent' | 'newagent';
|
|
3
|
+
export interface RecipientSnapshot {
|
|
4
|
+
agentId?: string;
|
|
5
|
+
agentInstanceId?: string;
|
|
6
|
+
threadId?: string;
|
|
7
|
+
agentName?: string;
|
|
8
|
+
threadName?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface Recipient {
|
|
11
|
+
address: RecipientAddress;
|
|
12
|
+
label?: string;
|
|
13
|
+
snapshot?: RecipientSnapshot;
|
|
14
|
+
}
|
|
15
|
+
export interface RecipientOption extends Recipient {
|
|
16
|
+
kind: RecipientKind;
|
|
17
|
+
available: boolean;
|
|
18
|
+
description?: string;
|
|
19
|
+
}
|
|
20
|
+
export type AutomationRunStatus = 'running' | 'success' | 'failed' | 'skipped';
|
|
21
|
+
export type AutomationActionType = 'notify' | 'sendMessage' | 'runAgent' | 'runActionBlock' | 'runCommand';
|
|
22
|
+
export interface ScheduleDefinition {
|
|
23
|
+
type: 'once' | 'interval' | 'cron';
|
|
24
|
+
startAt?: string;
|
|
25
|
+
intervalMinutes?: number;
|
|
26
|
+
cronExpression?: string;
|
|
27
|
+
timezone?: string;
|
|
28
|
+
endAt?: string;
|
|
29
|
+
}
|
|
30
|
+
export type AutomationTrigger = {
|
|
31
|
+
type: 'manual';
|
|
32
|
+
} | {
|
|
33
|
+
type: 'schedule';
|
|
34
|
+
schedule: ScheduleDefinition;
|
|
35
|
+
} | {
|
|
36
|
+
type: 'event';
|
|
37
|
+
eventType: string;
|
|
38
|
+
filter?: Record<string, unknown>;
|
|
39
|
+
};
|
|
40
|
+
export interface AutomationAction {
|
|
41
|
+
type: AutomationActionType;
|
|
42
|
+
recipient?: Recipient;
|
|
43
|
+
payload: Record<string, unknown>;
|
|
44
|
+
}
|
|
45
|
+
export interface AutomationCalendarOptions {
|
|
46
|
+
show: boolean;
|
|
47
|
+
title?: string;
|
|
48
|
+
durationMinutes?: number;
|
|
49
|
+
color?: string;
|
|
50
|
+
}
|
|
51
|
+
export interface Automation {
|
|
52
|
+
id: string;
|
|
53
|
+
name: string;
|
|
54
|
+
description?: string;
|
|
55
|
+
enabled: boolean;
|
|
56
|
+
trigger: AutomationTrigger;
|
|
57
|
+
action: AutomationAction;
|
|
58
|
+
calendar?: AutomationCalendarOptions;
|
|
59
|
+
nextRunAt?: string;
|
|
60
|
+
lastRunAt?: string;
|
|
61
|
+
lastRunStatus?: Exclude<AutomationRunStatus, 'running'>;
|
|
62
|
+
createdAt: string;
|
|
63
|
+
updatedAt: string;
|
|
64
|
+
}
|
|
65
|
+
export interface AutomationRun {
|
|
66
|
+
id: string;
|
|
67
|
+
automationId: string;
|
|
68
|
+
scheduledFor?: string;
|
|
69
|
+
startedAt: string;
|
|
70
|
+
completedAt?: string;
|
|
71
|
+
status: AutomationRunStatus;
|
|
72
|
+
recipient?: Recipient;
|
|
73
|
+
error?: string;
|
|
74
|
+
output?: unknown;
|
|
75
|
+
triggerContext?: Record<string, unknown>;
|
|
76
|
+
}
|
|
@@ -2,6 +2,12 @@ import { AgentConfig, AgentInterface, MessageModifier, PostInferenceProcessor, P
|
|
|
2
2
|
import { FlatUserMessage } from "@codebolt/types/sdk";
|
|
3
3
|
import { LoopDetectionService } from "../services/LoopDetectionService";
|
|
4
4
|
import type { CompactionOrchestratorOptions } from "../services/compaction/types";
|
|
5
|
+
import type { AgentEventQueueProcessorOptions } from "../../processor-pieces/utils/agentEventQueuePrompt";
|
|
6
|
+
export interface AgentEventQueueOptions extends AgentEventQueueProcessorOptions {
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
injectOnMessage?: boolean;
|
|
9
|
+
injectAfterToolCall?: boolean;
|
|
10
|
+
}
|
|
5
11
|
export interface AgentOptions extends AgentConfig {
|
|
6
12
|
context?: ProcessedMessage;
|
|
7
13
|
allowedTools?: string[];
|
|
@@ -16,6 +22,7 @@ export interface AgentOptions extends AgentConfig {
|
|
|
16
22
|
postInferenceProcessors?: PostInferenceProcessor[];
|
|
17
23
|
preToolCallProcessors?: PreToolCallProcessor[];
|
|
18
24
|
postToolCallProcessors?: PostToolCallProcessor[];
|
|
25
|
+
eventQueue?: boolean | AgentEventQueueOptions;
|
|
19
26
|
}
|
|
20
27
|
export interface AgentRunResult {
|
|
21
28
|
success: boolean;
|
|
@@ -38,6 +45,7 @@ export interface AgentRunState {
|
|
|
38
45
|
export interface AgentRunOptions {
|
|
39
46
|
state?: AgentRunState;
|
|
40
47
|
context?: ProcessedMessage;
|
|
48
|
+
contextoverride_id?: string;
|
|
41
49
|
}
|
|
42
50
|
export interface CreateAgentOptions extends AgentOptions {
|
|
43
51
|
systemPrompt?: string;
|
|
@@ -60,6 +68,8 @@ export declare class Agent implements AgentInterface {
|
|
|
60
68
|
private readonly localToolSchemas;
|
|
61
69
|
private readonly localToolsByExecutionName;
|
|
62
70
|
private readonly runtimeToolSetId;
|
|
71
|
+
private readonly localToolGroups;
|
|
72
|
+
private readonly localToolGroupAssignments;
|
|
63
73
|
constructor(config: AgentOptions);
|
|
64
74
|
run(message: string | FlatUserMessage, options?: ProcessedMessage | AgentRunOptions): Promise<AgentRunResult>;
|
|
65
75
|
private registerRuntimeToolsForSearch;
|
|
@@ -67,16 +77,29 @@ export declare class Agent implements AgentInterface {
|
|
|
67
77
|
processMessage(message: string | FlatUserMessage, options?: ProcessedMessage | AgentRunOptions): Promise<AgentRunResult>;
|
|
68
78
|
execute(reqMessage: FlatUserMessage): Promise<{
|
|
69
79
|
success: boolean;
|
|
70
|
-
result:
|
|
80
|
+
result: unknown;
|
|
71
81
|
error?: string;
|
|
72
82
|
}>;
|
|
83
|
+
start(): void;
|
|
73
84
|
getConfig(): AgentOptions;
|
|
74
85
|
getMessageModifiers(): MessageModifier[];
|
|
75
86
|
getPreInferenceProcessors(): PreInferenceProcessor[];
|
|
76
87
|
getPostInferenceProcessors(): PostInferenceProcessor[];
|
|
77
88
|
getPreToolCallProcessors(): PreToolCallProcessor[];
|
|
78
89
|
getPostToolCallProcessors(): PostToolCallProcessor[];
|
|
79
|
-
private
|
|
90
|
+
private resolveExplicitRunContext;
|
|
91
|
+
private resolveContextOverride;
|
|
92
|
+
private getContextOverrideId;
|
|
93
|
+
private savedContextToProcessedMessage;
|
|
94
|
+
private extractSavedContextMessages;
|
|
95
|
+
private extractSavedCompactedMessages;
|
|
96
|
+
private extractLatestSavedLlmRequestMessages;
|
|
97
|
+
private normalizeSavedLlmInputItem;
|
|
98
|
+
private previewItemToMessage;
|
|
99
|
+
private isSavedContextInputMessage;
|
|
100
|
+
private createSavedContextBoundaryMessage;
|
|
101
|
+
private formatSavedContextForPrompt;
|
|
102
|
+
private stringifyForPrompt;
|
|
80
103
|
private getResumeMessageModifiers;
|
|
81
104
|
private normalizeLLMRole;
|
|
82
105
|
private isProcessedMessage;
|
|
@@ -45,7 +45,8 @@ function createDefaultMessageModifiers(systemPrompt, allowedTools) {
|
|
|
45
45
|
enableChatHistory: true,
|
|
46
46
|
includeSystemMessages: false,
|
|
47
47
|
}),
|
|
48
|
-
new processor_pieces_1.
|
|
48
|
+
new processor_pieces_1.CapabilityContextModifier(),
|
|
49
|
+
new processor_pieces_1.EnvironmentContextModifier({ enableFullContext: false }),
|
|
49
50
|
new processor_pieces_1.DirectoryContextModifier(),
|
|
50
51
|
new processor_pieces_1.IdeContextModifier({
|
|
51
52
|
includeActiveFile: true,
|
|
@@ -58,6 +59,7 @@ function createDefaultMessageModifiers(systemPrompt, allowedTools) {
|
|
|
58
59
|
includeToolDescriptions: true,
|
|
59
60
|
...(allowedTools ? { allowedTools } : {})
|
|
60
61
|
}),
|
|
62
|
+
new processor_pieces_1.ToolGroupContextModifier(),
|
|
61
63
|
new processor_pieces_1.AtFileProcessorModifier({ enableRecursiveSearch: true })
|
|
62
64
|
];
|
|
63
65
|
}
|
|
@@ -73,6 +75,24 @@ function createDefaultPreToolCallProcessors() {
|
|
|
73
75
|
function createDefaultPostToolCallProcessors() {
|
|
74
76
|
return [];
|
|
75
77
|
}
|
|
78
|
+
function normalizeAgentEventQueueOptions(eventQueue, enableLogging) {
|
|
79
|
+
var _a, _b, _c, _d;
|
|
80
|
+
if (typeof eventQueue === 'boolean') {
|
|
81
|
+
return {
|
|
82
|
+
enabled: eventQueue,
|
|
83
|
+
injectOnMessage: eventQueue,
|
|
84
|
+
injectAfterToolCall: eventQueue,
|
|
85
|
+
enableLogging,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const enabled = (_a = eventQueue === null || eventQueue === void 0 ? void 0 : eventQueue.enabled) !== null && _a !== void 0 ? _a : true;
|
|
89
|
+
return {
|
|
90
|
+
enabled,
|
|
91
|
+
injectOnMessage: (_b = eventQueue === null || eventQueue === void 0 ? void 0 : eventQueue.injectOnMessage) !== null && _b !== void 0 ? _b : enabled,
|
|
92
|
+
injectAfterToolCall: (_c = eventQueue === null || eventQueue === void 0 ? void 0 : eventQueue.injectAfterToolCall) !== null && _c !== void 0 ? _c : enabled,
|
|
93
|
+
enableLogging: (_d = eventQueue === null || eventQueue === void 0 ? void 0 : eventQueue.enableLogging) !== null && _d !== void 0 ? _d : enableLogging,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
76
96
|
function createDefaultUserMessage(message) {
|
|
77
97
|
const timestamp = Date.now();
|
|
78
98
|
return {
|
|
@@ -104,41 +124,66 @@ class Agent {
|
|
|
104
124
|
const localToolRegistry = (0, agentToolLoader_1.createAgentLocalToolRegistry)(config.tools || []);
|
|
105
125
|
const includeDefaultModifiers = (_b = (_a = config.includeDefaultModifiers) !== null && _a !== void 0 ? _a : config.defaultProcessors) !== null && _b !== void 0 ? _b : true;
|
|
106
126
|
const includeDefaultProcessors = (_d = (_c = config.includeDefaultProcessors) !== null && _c !== void 0 ? _c : config.defaultProcessors) !== null && _d !== void 0 ? _d : true;
|
|
127
|
+
const enableLogging = config.enableLogging !== false;
|
|
128
|
+
const eventQueueOptions = normalizeAgentEventQueueOptions(config.eventQueue, enableLogging);
|
|
107
129
|
const customMessageModifiers = collectProcessors((_e = config.processors) === null || _e === void 0 ? void 0 : _e.messageModifiers, config.messageModifiers);
|
|
108
130
|
const defaultMessageModifiers = includeDefaultModifiers
|
|
109
131
|
? createDefaultMessageModifiers(config.instructions || DEFAULT_SYSTEM_PROMPT, config.allowedTools)
|
|
110
132
|
: [];
|
|
111
133
|
this.config = { ...config };
|
|
112
|
-
this.enableLogging =
|
|
134
|
+
this.enableLogging = enableLogging;
|
|
113
135
|
this.baseSystemPrompt = config.instructions || DEFAULT_SYSTEM_PROMPT;
|
|
114
136
|
this.context = config.context;
|
|
115
137
|
this.allowedTools = config.allowedTools;
|
|
116
138
|
this.llmRole = this.normalizeLLMRole(config.llmRole);
|
|
117
|
-
this.messageModifiers = mergeProcessors(defaultMessageModifiers,
|
|
139
|
+
this.messageModifiers = mergeProcessors(defaultMessageModifiers, [
|
|
140
|
+
...customMessageModifiers,
|
|
141
|
+
...(eventQueueOptions.enabled && eventQueueOptions.injectOnMessage
|
|
142
|
+
? [new processor_pieces_1.AgentEventQueueModifier(eventQueueOptions)]
|
|
143
|
+
: []),
|
|
144
|
+
]);
|
|
118
145
|
this.preInferenceProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPreInferenceProcessors() : [], collectProcessors((_f = config.processors) === null || _f === void 0 ? void 0 : _f.preInferenceProcessors, config.preInferenceProcessors));
|
|
119
146
|
this.postInferenceProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPostInferenceProcessors() : [], collectProcessors((_g = config.processors) === null || _g === void 0 ? void 0 : _g.postInferenceProcessors, config.postInferenceProcessors));
|
|
120
147
|
this.preToolCallProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPreToolCallProcessors() : [], collectProcessors((_h = config.processors) === null || _h === void 0 ? void 0 : _h.preToolCallProcessors, config.preToolCallProcessors));
|
|
121
|
-
|
|
148
|
+
const customPostToolCallProcessors = collectProcessors((_j = config.processors) === null || _j === void 0 ? void 0 : _j.postToolCallProcessors, config.postToolCallProcessors);
|
|
149
|
+
this.postToolCallProcessors = mergeProcessors(includeDefaultProcessors ? createDefaultPostToolCallProcessors() : [], [
|
|
150
|
+
...customPostToolCallProcessors,
|
|
151
|
+
...(eventQueueOptions.enabled && eventQueueOptions.injectAfterToolCall
|
|
152
|
+
? [new processor_pieces_1.AgentEventQueuePostToolCallProcessor(eventQueueOptions)]
|
|
153
|
+
: []),
|
|
154
|
+
]);
|
|
122
155
|
const compactionLLMRole = (_l = this.normalizeLLMRole((_k = config.compaction) === null || _k === void 0 ? void 0 : _k.llmRole)) !== null && _l !== void 0 ? _l : this.llmRole;
|
|
123
156
|
this.compactionOrchestrator = new compactionOrchestrator_1.CompactionOrchestrator({
|
|
124
157
|
...config.compaction,
|
|
125
158
|
...(compactionLLMRole ? { llmRole: compactionLLMRole } : {}),
|
|
126
159
|
});
|
|
127
160
|
this.loopDetectionService = config.loopDetectionService;
|
|
128
|
-
this.maxTurns = (_o = (_m = config.maxTurns) !== null && _m !== void 0 ? _m : config.maxIterations) !== null && _o !== void 0 ? _o :
|
|
161
|
+
this.maxTurns = (_o = (_m = config.maxTurns) !== null && _m !== void 0 ? _m : config.maxIterations) !== null && _o !== void 0 ? _o : 0;
|
|
129
162
|
this.localToolSchemas = localToolRegistry.schemas;
|
|
130
163
|
this.localToolsByExecutionName = localToolRegistry.byExecutionName;
|
|
164
|
+
this.localToolGroups = config.toolGroups;
|
|
165
|
+
this.localToolGroupAssignments = Object.fromEntries((config.tools || []).flatMap((tool) => {
|
|
166
|
+
var _a;
|
|
167
|
+
if (!tool.groupId)
|
|
168
|
+
return [];
|
|
169
|
+
const toolName = (_a = tool.toOpenAITool().function) === null || _a === void 0 ? void 0 : _a.name;
|
|
170
|
+
return toolName ? [[toolName, tool.groupId]] : [];
|
|
171
|
+
}));
|
|
131
172
|
this.runtimeToolSetId = `agent-${(0, crypto_1.randomUUID)()}`;
|
|
132
173
|
}
|
|
133
174
|
async run(message, options) {
|
|
134
|
-
var _a, _b;
|
|
175
|
+
var _a, _b, _c;
|
|
135
176
|
try {
|
|
136
177
|
await this.registerRuntimeToolsForSearch();
|
|
137
178
|
const reqMessage = typeof message === 'string'
|
|
138
179
|
? createDefaultUserMessage(message)
|
|
139
180
|
: message;
|
|
140
181
|
let prompt;
|
|
141
|
-
const
|
|
182
|
+
const explicitContext = this.resolveExplicitRunContext(options);
|
|
183
|
+
const contextOverride = explicitContext
|
|
184
|
+
? undefined
|
|
185
|
+
: await this.resolveContextOverride(reqMessage, options);
|
|
186
|
+
const contextToUse = (_a = explicitContext !== null && explicitContext !== void 0 ? explicitContext : contextOverride) !== null && _a !== void 0 ? _a : this.context;
|
|
142
187
|
if (contextToUse) {
|
|
143
188
|
const promptGenerator = new base_1.InitialPromptGenerator({
|
|
144
189
|
processors: this.getResumeMessageModifiers(),
|
|
@@ -162,7 +207,7 @@ class Agent {
|
|
|
162
207
|
const toolResults = [];
|
|
163
208
|
while (!completed) {
|
|
164
209
|
turnNumber += 1;
|
|
165
|
-
if (turnNumber > this.maxTurns) {
|
|
210
|
+
if (this.maxTurns > 0 && turnNumber > this.maxTurns) {
|
|
166
211
|
throw new Error(`Agent exceeded the maximum turn limit of ${this.maxTurns}.`);
|
|
167
212
|
}
|
|
168
213
|
this.compactionOrchestrator.resetForTurn();
|
|
@@ -177,7 +222,7 @@ class Agent {
|
|
|
177
222
|
while (!stepResult) {
|
|
178
223
|
try {
|
|
179
224
|
const nextStepResult = await agentStep.executeStep(reqMessage, prompt);
|
|
180
|
-
this.compactionOrchestrator.updateModelTokenLimit((
|
|
225
|
+
this.compactionOrchestrator.updateModelTokenLimit((_b = nextStepResult.rawLLMResponse) === null || _b === void 0 ? void 0 : _b.tokenLimit);
|
|
181
226
|
const recoverableResponseError = this.getRecoverableResponseError(nextStepResult.rawLLMResponse);
|
|
182
227
|
if (!recoverableResponseError) {
|
|
183
228
|
stepResult = nextStepResult;
|
|
@@ -217,7 +262,7 @@ class Agent {
|
|
|
217
262
|
completed = executionResult.completed;
|
|
218
263
|
prompt = executionResult.nextMessage;
|
|
219
264
|
finalMessage = executionResult.finalMessage;
|
|
220
|
-
toolResults.push(...((
|
|
265
|
+
toolResults.push(...((_c = executionResult.toolResults) !== null && _c !== void 0 ? _c : []));
|
|
221
266
|
}
|
|
222
267
|
const state = { prompt };
|
|
223
268
|
return {
|
|
@@ -253,7 +298,13 @@ class Agent {
|
|
|
253
298
|
return;
|
|
254
299
|
}
|
|
255
300
|
try {
|
|
256
|
-
await ((_b = (_a = codeboltjs_1.default.searchableAssets) === null || _a === void 0 ? void 0 : _a.registerRuntimeTools) === null || _b === void 0 ? void 0 : _b.call(_a, this.runtimeToolSetId, this.localToolSchemas
|
|
301
|
+
await ((_b = (_a = codeboltjs_1.default.searchableAssets) === null || _a === void 0 ? void 0 : _a.registerRuntimeTools) === null || _b === void 0 ? void 0 : _b.call(_a, this.runtimeToolSetId, this.localToolSchemas, {
|
|
302
|
+
displayName: this.config.name || 'Current Agent Tools',
|
|
303
|
+
description: `Custom tools available to ${this.config.name || 'the current agent'}.`,
|
|
304
|
+
sourceType: 'agent-local',
|
|
305
|
+
groups: this.localToolGroups,
|
|
306
|
+
toolGroupAssignments: this.localToolGroupAssignments,
|
|
307
|
+
}));
|
|
257
308
|
}
|
|
258
309
|
catch (error) {
|
|
259
310
|
if (this.enableLogging) {
|
|
@@ -281,6 +332,34 @@ class Agent {
|
|
|
281
332
|
async execute(reqMessage) {
|
|
282
333
|
return this.run(reqMessage);
|
|
283
334
|
}
|
|
335
|
+
start() {
|
|
336
|
+
codeboltjs_1.default.onMessage(async (reqMessage) => {
|
|
337
|
+
var _a, _b;
|
|
338
|
+
if (this.enableLogging) {
|
|
339
|
+
console.log(`[Agent] Started message ${(_a = reqMessage.messageId) !== null && _a !== void 0 ? _a : 'unknown'}`);
|
|
340
|
+
}
|
|
341
|
+
try {
|
|
342
|
+
const executionResult = await this.processMessage(reqMessage);
|
|
343
|
+
if (!executionResult.success) {
|
|
344
|
+
return JSON.stringify({
|
|
345
|
+
error: executionResult.error || 'Agent failed to process the message.',
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
if (this.enableLogging) {
|
|
349
|
+
console.log(`[Agent] Finished message ${(_b = reqMessage.messageId) !== null && _b !== void 0 ? _b : 'unknown'}`);
|
|
350
|
+
}
|
|
351
|
+
return executionResult.finalMessage;
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
if (this.enableLogging) {
|
|
355
|
+
console.error('[Agent] Message handler failed:', error);
|
|
356
|
+
}
|
|
357
|
+
return JSON.stringify({
|
|
358
|
+
error: error instanceof Error ? error.message : 'Unknown agent message handler error',
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
}
|
|
284
363
|
getConfig() {
|
|
285
364
|
return { ...this.config };
|
|
286
365
|
}
|
|
@@ -299,15 +378,225 @@ class Agent {
|
|
|
299
378
|
getPostToolCallProcessors() {
|
|
300
379
|
return [...this.postToolCallProcessors];
|
|
301
380
|
}
|
|
302
|
-
|
|
303
|
-
var _a, _b
|
|
381
|
+
resolveExplicitRunContext(options) {
|
|
382
|
+
var _a, _b;
|
|
304
383
|
if (!options) {
|
|
305
|
-
return
|
|
384
|
+
return undefined;
|
|
306
385
|
}
|
|
307
386
|
if (this.isProcessedMessage(options)) {
|
|
308
387
|
return options;
|
|
309
388
|
}
|
|
310
|
-
return (
|
|
389
|
+
return (_b = (_a = options.state) === null || _a === void 0 ? void 0 : _a.prompt) !== null && _b !== void 0 ? _b : options.context;
|
|
390
|
+
}
|
|
391
|
+
async resolveContextOverride(reqMessage, options) {
|
|
392
|
+
const contextId = this.getContextOverrideId(reqMessage, options);
|
|
393
|
+
if (!contextId) {
|
|
394
|
+
return undefined;
|
|
395
|
+
}
|
|
396
|
+
if (!/^id_[A-Za-z0-9_-]+$/.test(contextId)) {
|
|
397
|
+
throw new Error(`Invalid contextoverride_id: ${contextId}`);
|
|
398
|
+
}
|
|
399
|
+
const getSavedThreadContext = codeboltjs_1.default.thread.getSavedThreadContext;
|
|
400
|
+
if (!getSavedThreadContext) {
|
|
401
|
+
throw new Error('Saved context getter is not available in the CodeBolt thread client');
|
|
402
|
+
}
|
|
403
|
+
const response = await getSavedThreadContext({ contextId });
|
|
404
|
+
if ((response === null || response === void 0 ? void 0 : response.success) === false || !(response === null || response === void 0 ? void 0 : response.savedContext)) {
|
|
405
|
+
throw new Error((response === null || response === void 0 ? void 0 : response.error) || `Saved context not found: ${contextId}`);
|
|
406
|
+
}
|
|
407
|
+
return this.savedContextToProcessedMessage(response.savedContext, contextId, reqMessage.threadId);
|
|
408
|
+
}
|
|
409
|
+
getContextOverrideId(reqMessage, options) {
|
|
410
|
+
const optionValue = options && !this.isProcessedMessage(options)
|
|
411
|
+
? options.contextoverride_id
|
|
412
|
+
: undefined;
|
|
413
|
+
const messageValue = reqMessage.contextoverride_id;
|
|
414
|
+
const envValue = process.env['contextoverride_id'] || process.env['CONTEXTOVERRIDE_ID'];
|
|
415
|
+
const value = optionValue || messageValue || envValue;
|
|
416
|
+
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
417
|
+
}
|
|
418
|
+
savedContextToProcessedMessage(savedContext, contextId, targetThreadId) {
|
|
419
|
+
const runningContext = (savedContext === null || savedContext === void 0 ? void 0 : savedContext.runningContext) || {};
|
|
420
|
+
const savedMessages = this.extractSavedContextMessages(runningContext);
|
|
421
|
+
const input = savedMessages.length > 0
|
|
422
|
+
? [
|
|
423
|
+
...savedMessages,
|
|
424
|
+
this.createSavedContextBoundaryMessage(savedContext),
|
|
425
|
+
]
|
|
426
|
+
: [
|
|
427
|
+
{
|
|
428
|
+
role: 'user',
|
|
429
|
+
content: this.formatSavedContextForPrompt(savedContext),
|
|
430
|
+
},
|
|
431
|
+
];
|
|
432
|
+
return {
|
|
433
|
+
message: {
|
|
434
|
+
formatVersion: 'codebolt.llm.v2',
|
|
435
|
+
input,
|
|
436
|
+
tools: [],
|
|
437
|
+
},
|
|
438
|
+
metadata: {
|
|
439
|
+
timestamp: new Date().toISOString(),
|
|
440
|
+
threadId: targetThreadId,
|
|
441
|
+
contextoverride_id: contextId,
|
|
442
|
+
savedContextId: contextId,
|
|
443
|
+
savedContextSourceThreadId: savedContext === null || savedContext === void 0 ? void 0 : savedContext.sourceThreadId,
|
|
444
|
+
savedContextCreatedAt: savedContext === null || savedContext === void 0 ? void 0 : savedContext.createdAt,
|
|
445
|
+
},
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
extractSavedContextMessages(runningContext) {
|
|
449
|
+
const fullLlmRequestMessages = this.extractLatestSavedLlmRequestMessages(runningContext === null || runningContext === void 0 ? void 0 : runningContext.messages, {
|
|
450
|
+
requireFullInput: true,
|
|
451
|
+
});
|
|
452
|
+
if (fullLlmRequestMessages.length > 0) {
|
|
453
|
+
return fullLlmRequestMessages;
|
|
454
|
+
}
|
|
455
|
+
const compactedMessages = this.extractSavedCompactedMessages(runningContext === null || runningContext === void 0 ? void 0 : runningContext.compactedContext);
|
|
456
|
+
if (compactedMessages.length > 0) {
|
|
457
|
+
return compactedMessages;
|
|
458
|
+
}
|
|
459
|
+
return this.extractLatestSavedLlmRequestMessages(runningContext === null || runningContext === void 0 ? void 0 : runningContext.messages, {
|
|
460
|
+
requireFullInput: false,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
extractSavedCompactedMessages(compactedContext) {
|
|
464
|
+
var _a;
|
|
465
|
+
const data = typeof compactedContext === 'object' && compactedContext !== null
|
|
466
|
+
? compactedContext.data
|
|
467
|
+
: undefined;
|
|
468
|
+
const messages = typeof data === 'object' && data !== null
|
|
469
|
+
? ((_a = data.input) !== null && _a !== void 0 ? _a : data.messages)
|
|
470
|
+
: undefined;
|
|
471
|
+
if (!Array.isArray(messages)) {
|
|
472
|
+
return [];
|
|
473
|
+
}
|
|
474
|
+
return messages
|
|
475
|
+
.filter((message) => this.isServerCompactedMessage(message))
|
|
476
|
+
.map((message) => ({ ...message }));
|
|
477
|
+
}
|
|
478
|
+
extractLatestSavedLlmRequestMessages(messages, options) {
|
|
479
|
+
if (!Array.isArray(messages)) {
|
|
480
|
+
return [];
|
|
481
|
+
}
|
|
482
|
+
const latestRequest = [...messages]
|
|
483
|
+
.reverse()
|
|
484
|
+
.find((message) => (message === null || message === void 0 ? void 0 : message.type) === 'llm_request');
|
|
485
|
+
if (!latestRequest || typeof latestRequest !== 'object') {
|
|
486
|
+
return [];
|
|
487
|
+
}
|
|
488
|
+
const request = latestRequest;
|
|
489
|
+
const fullInput = Array.isArray(request.input)
|
|
490
|
+
? request.input
|
|
491
|
+
: Array.isArray(request.messages)
|
|
492
|
+
? request.messages
|
|
493
|
+
: undefined;
|
|
494
|
+
if (options.requireFullInput && !fullInput) {
|
|
495
|
+
return [];
|
|
496
|
+
}
|
|
497
|
+
const sourceMessages = fullInput
|
|
498
|
+
? fullInput.map((message) => this.normalizeSavedLlmInputItem(message))
|
|
499
|
+
: Array.isArray(request.inputPreviewItems)
|
|
500
|
+
? request.inputPreviewItems.map((item) => this.previewItemToMessage(item))
|
|
501
|
+
: [];
|
|
502
|
+
return sourceMessages
|
|
503
|
+
.filter((message) => !!message && this.isSavedContextInputMessage(message))
|
|
504
|
+
.filter((message) => !(0, promptContext_1.isGeneratedUserContextMessage)(message))
|
|
505
|
+
.map((message) => ({ ...message }));
|
|
506
|
+
}
|
|
507
|
+
normalizeSavedLlmInputItem(item) {
|
|
508
|
+
if (!item || typeof item !== 'object') {
|
|
509
|
+
return null;
|
|
510
|
+
}
|
|
511
|
+
return { ...item };
|
|
512
|
+
}
|
|
513
|
+
previewItemToMessage(item) {
|
|
514
|
+
if (!item || typeof item !== 'object') {
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
const preview = item;
|
|
518
|
+
const type = typeof preview.type === 'string' ? preview.type : undefined;
|
|
519
|
+
const role = typeof preview.role === 'string' ? preview.role : undefined;
|
|
520
|
+
const content = typeof preview.contentPreview === 'string' ? preview.contentPreview : undefined;
|
|
521
|
+
const callId = typeof preview.call_id === 'string'
|
|
522
|
+
? preview.call_id
|
|
523
|
+
: typeof preview.id === 'string'
|
|
524
|
+
? preview.id
|
|
525
|
+
: undefined;
|
|
526
|
+
if (type === 'function_call') {
|
|
527
|
+
return {
|
|
528
|
+
type,
|
|
529
|
+
name: typeof preview.name === 'string' ? preview.name : undefined,
|
|
530
|
+
call_id: callId,
|
|
531
|
+
arguments: content || '',
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
if (type === 'function_call_output' || type === 'tool_search_output') {
|
|
535
|
+
return {
|
|
536
|
+
type,
|
|
537
|
+
call_id: callId,
|
|
538
|
+
output: content || '',
|
|
539
|
+
status: 'completed',
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
if (role && content !== undefined) {
|
|
543
|
+
return {
|
|
544
|
+
...(type ? { type } : {}),
|
|
545
|
+
role,
|
|
546
|
+
content,
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
if (type && content !== undefined) {
|
|
550
|
+
return {
|
|
551
|
+
type,
|
|
552
|
+
call_id: callId,
|
|
553
|
+
output: content,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
return null;
|
|
557
|
+
}
|
|
558
|
+
isSavedContextInputMessage(message) {
|
|
559
|
+
if (typeof message.role === 'string' && message.content !== undefined) {
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
return typeof message.type === 'string' && (message.type === 'function_call' ||
|
|
563
|
+
message.type === 'function_call_output' ||
|
|
564
|
+
message.type === 'tool_search_output');
|
|
565
|
+
}
|
|
566
|
+
createSavedContextBoundaryMessage(savedContext) {
|
|
567
|
+
const contextId = (savedContext === null || savedContext === void 0 ? void 0 : savedContext.id) || '';
|
|
568
|
+
const sourceThreadId = (savedContext === null || savedContext === void 0 ? void 0 : savedContext.sourceThreadId) || '';
|
|
569
|
+
return {
|
|
570
|
+
role: 'user',
|
|
571
|
+
content: [
|
|
572
|
+
`--- End of saved context ${contextId} ---`,
|
|
573
|
+
'',
|
|
574
|
+
`The above messages were loaded from saved context ${contextId}${sourceThreadId ? ` for source thread ${sourceThreadId}` : ''}.`,
|
|
575
|
+
'Some entries may be reconstructed from saved LLM request previews if full input messages were not available.',
|
|
576
|
+
'Continue from that context and respond to the current user message.',
|
|
577
|
+
].join('\n'),
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
formatSavedContextForPrompt(savedContext) {
|
|
581
|
+
var _a;
|
|
582
|
+
const runningContext = (savedContext === null || savedContext === void 0 ? void 0 : savedContext.runningContext) || {};
|
|
583
|
+
const parts = [
|
|
584
|
+
`<saved-context id="${(savedContext === null || savedContext === void 0 ? void 0 : savedContext.id) || ''}" sourceThreadId="${(savedContext === null || savedContext === void 0 ? void 0 : savedContext.sourceThreadId) || ''}">`,
|
|
585
|
+
(savedContext === null || savedContext === void 0 ? void 0 : savedContext.title) ? `Title: ${savedContext.title}` : '',
|
|
586
|
+
(runningContext === null || runningContext === void 0 ? void 0 : runningContext.summary) ? `Summary:\n${runningContext.summary}` : '',
|
|
587
|
+
((_a = runningContext === null || runningContext === void 0 ? void 0 : runningContext.compactedContext) === null || _a === void 0 ? void 0 : _a.content) ? `Compacted Context:\n${runningContext.compactedContext.content}` : '',
|
|
588
|
+
`Running Context Messages:\n${this.stringifyForPrompt(Array.isArray(runningContext === null || runningContext === void 0 ? void 0 : runningContext.messages) ? runningContext.messages.slice(-20) : [])}`,
|
|
589
|
+
'</saved-context>',
|
|
590
|
+
].filter(Boolean);
|
|
591
|
+
return parts.join('\n\n');
|
|
592
|
+
}
|
|
593
|
+
stringifyForPrompt(value) {
|
|
594
|
+
try {
|
|
595
|
+
return JSON.stringify(value, null, 2);
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
return String(value);
|
|
599
|
+
}
|
|
311
600
|
}
|
|
312
601
|
getResumeMessageModifiers() {
|
|
313
602
|
return this.messageModifiers.filter((modifier) => { var _a; return ((_a = modifier.constructor) === null || _a === void 0 ? void 0 : _a.name) !== 'ChatHistoryMessageModifier'; });
|
|
@@ -67,7 +67,7 @@ class AgentStep {
|
|
|
67
67
|
}
|
|
68
68
|
async generateResponse(messageForLLM) {
|
|
69
69
|
var _a, _b, _c, _d, _e;
|
|
70
|
-
console.log('[AgentStep] llm.inference payload:', messageForLLM);
|
|
70
|
+
// console.log('[AgentStep] llm.inference payload:', messageForLLM);
|
|
71
71
|
const response = await codeboltjs_1.default.llm.inference(messageForLLM);
|
|
72
72
|
const completion = this.extractCompletion(response);
|
|
73
73
|
if (!completion) {
|
|
@@ -34,6 +34,20 @@ function cloneMessage(message) {
|
|
|
34
34
|
function cloneMessages(messages) {
|
|
35
35
|
return messages.map((message) => cloneMessage(message));
|
|
36
36
|
}
|
|
37
|
+
function legacyPromptMessages(prompt) {
|
|
38
|
+
const messages = prompt.message.messages;
|
|
39
|
+
if (!Array.isArray(messages)) {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
return cloneMessages(messages.filter((message) => (!!message &&
|
|
43
|
+
typeof message === 'object' &&
|
|
44
|
+
typeof message.role === 'string' &&
|
|
45
|
+
Object.prototype.hasOwnProperty.call(message, 'content'))));
|
|
46
|
+
}
|
|
47
|
+
function stripChatStyleFields(message) {
|
|
48
|
+
const { messages: _messages, functions: _functions, max_tokens: _maxTokens, choices: _choices, tool_calls: _toolCalls, ...rest } = message;
|
|
49
|
+
return rest;
|
|
50
|
+
}
|
|
37
51
|
function textFromContent(content) {
|
|
38
52
|
if (typeof content === 'string') {
|
|
39
53
|
return content;
|
|
@@ -155,7 +169,10 @@ function flattenRuntimeMessages(runtimeContext) {
|
|
|
155
169
|
}
|
|
156
170
|
function inferRuntimeContext(prompt) {
|
|
157
171
|
var _a;
|
|
158
|
-
const messages =
|
|
172
|
+
const messages = [
|
|
173
|
+
...((_a = prompt.message.input) !== null && _a !== void 0 ? _a : []),
|
|
174
|
+
...legacyPromptMessages(prompt),
|
|
175
|
+
];
|
|
159
176
|
const systemMessages = messages.filter((message) => message.role === 'system');
|
|
160
177
|
const transcriptMessages = messages.filter((message) => message.role !== 'system' && !isGeneratedUserContextMessage(message));
|
|
161
178
|
let systemPrompt;
|
|
@@ -204,10 +221,11 @@ function ensureRuntimePromptContext(prompt) {
|
|
|
204
221
|
return (_a = getRuntimePromptContext(prompt)) !== null && _a !== void 0 ? _a : inferRuntimeContext(prompt);
|
|
205
222
|
}
|
|
206
223
|
function withRuntimePromptContext(prompt, runtimeContext) {
|
|
224
|
+
const baseMessage = stripChatStyleFields(prompt.message);
|
|
207
225
|
return {
|
|
208
226
|
...prompt,
|
|
209
227
|
message: {
|
|
210
|
-
...
|
|
228
|
+
...baseMessage,
|
|
211
229
|
formatVersion: 'codebolt.llm.v2',
|
|
212
230
|
input: flattenRuntimeMessages(runtimeContext),
|
|
213
231
|
},
|
|
@@ -240,6 +258,7 @@ function reconcileRuntimePromptContext(prompt) {
|
|
|
240
258
|
runtimeContext.userContextMessages.length;
|
|
241
259
|
const normalizedTranscriptStartIndex = Math.min(transcriptStartIndex, flattenedMessages.length);
|
|
242
260
|
const candidateTranscriptMessages = cloneMessages(flattenedMessages.slice(normalizedTranscriptStartIndex));
|
|
261
|
+
candidateTranscriptMessages.push(...legacyPromptMessages(prompt));
|
|
243
262
|
const possibleCurrentUserContextMessageIndex = runtimeContext.currentUserMessageIndex;
|
|
244
263
|
const possibleCurrentUserContextMessage = possibleCurrentUserContextMessageIndex === undefined
|
|
245
264
|
? undefined
|
|
@@ -383,8 +402,9 @@ function updateCurrentUserMessage(prompt, update) {
|
|
|
383
402
|
}
|
|
384
403
|
function buildInferenceParams(prompt) {
|
|
385
404
|
const runtimeContext = ensureRuntimePromptContext(prompt);
|
|
405
|
+
const baseMessage = stripChatStyleFields(prompt.message);
|
|
386
406
|
return {
|
|
387
|
-
...
|
|
407
|
+
...baseMessage,
|
|
388
408
|
formatVersion: 'codebolt.llm.v2',
|
|
389
409
|
input: flattenRuntimeMessages(runtimeContext),
|
|
390
410
|
};
|
|
@@ -25,7 +25,7 @@ export declare class ResponseExecutor implements AgentResponseExecutor {
|
|
|
25
25
|
private isMessageObject;
|
|
26
26
|
private getMessagesAddedAfterInference;
|
|
27
27
|
private executeTools;
|
|
28
|
-
private
|
|
28
|
+
private sendAssistantMessageToChat;
|
|
29
29
|
private getPendingAsyncTasks;
|
|
30
30
|
private extractCompletionMessage;
|
|
31
31
|
private formatCompletionValue;
|
|
@@ -347,7 +347,7 @@ class ResponseExecutor {
|
|
|
347
347
|
const lastMessageContent = this.extractLastMessageContent(llmResponse);
|
|
348
348
|
const toolCalls = this.getToolCalls(llmResponse);
|
|
349
349
|
if (toolCalls.length === 0) {
|
|
350
|
-
await this.
|
|
350
|
+
await this.sendAssistantMessageToChat(lastMessageContent);
|
|
351
351
|
return {
|
|
352
352
|
toolResults: [],
|
|
353
353
|
followUpMessages: [],
|
|
@@ -359,6 +359,9 @@ class ResponseExecutor {
|
|
|
359
359
|
const parsedToolCalls = toolCalls.map((tool) => this.parseToolCall(tool));
|
|
360
360
|
const completionToolCalls = parsedToolCalls.filter((toolCall) => toolCall.toolName.includes('attempt_completion'));
|
|
361
361
|
const executionToolCalls = parsedToolCalls.filter((toolCall) => !toolCall.toolName.includes('attempt_completion'));
|
|
362
|
+
if (executionToolCalls.length > 0) {
|
|
363
|
+
await this.sendAssistantMessageToChat(lastMessageContent);
|
|
364
|
+
}
|
|
362
365
|
if (this.loopDetectionService) {
|
|
363
366
|
for (const toolCall of executionToolCalls) {
|
|
364
367
|
const loopDetected = this.loopDetectionService.checkToolCallLoop(toolCall.toolName, toolCall.toolInput);
|
|
@@ -398,7 +401,7 @@ class ResponseExecutor {
|
|
|
398
401
|
const completionArguments = completionToolCall.toolInput;
|
|
399
402
|
const [, completionResult] = await this.executeTool(completionToolCall.toolName, completionArguments, input);
|
|
400
403
|
this.finalMessage = (_a = this.extractCompletionMessage(completionArguments)) !== null && _a !== void 0 ? _a : lastMessageContent;
|
|
401
|
-
await this.
|
|
404
|
+
await this.sendAssistantMessageToChat(this.finalMessage);
|
|
402
405
|
const parsedCompletionResult = this.parseToolResult(completionToolCall.toolUseId, completionResult === '' ? 'The user is satisfied with the result.' : completionResult);
|
|
403
406
|
toolResults.push(parsedCompletionResult);
|
|
404
407
|
}
|
|
@@ -411,7 +414,7 @@ class ResponseExecutor {
|
|
|
411
414
|
hadToolCalls: true,
|
|
412
415
|
};
|
|
413
416
|
}
|
|
414
|
-
async
|
|
417
|
+
async sendAssistantMessageToChat(message) {
|
|
415
418
|
if (!message || message.trim().length === 0) {
|
|
416
419
|
return;
|
|
417
420
|
}
|
|
@@ -419,7 +422,7 @@ class ResponseExecutor {
|
|
|
419
422
|
await Promise.resolve(codeboltjs_1.default.chat.sendMessage(message));
|
|
420
423
|
}
|
|
421
424
|
catch (error) {
|
|
422
|
-
console.error('[ResponseExecutor] Failed to send
|
|
425
|
+
console.error('[ResponseExecutor] Failed to send assistant chat message:', error);
|
|
423
426
|
}
|
|
424
427
|
}
|
|
425
428
|
async getPendingAsyncTasks() {
|
|
@@ -496,7 +499,7 @@ class ResponseExecutor {
|
|
|
496
499
|
resultTuple = [false, 'tool result is successful'];
|
|
497
500
|
}
|
|
498
501
|
else {
|
|
499
|
-
resultTuple = await this.executeTool(toolCall.toolName, toolCall.toolInput, input);
|
|
502
|
+
resultTuple = await this.executeTool(toolCall.toolName, toolCall.toolInput, input, toolCall.toolUseId);
|
|
500
503
|
}
|
|
501
504
|
const [didUserReject, result] = resultTuple;
|
|
502
505
|
const parsedResult = this.parseToolResult(toolCall.toolUseId, result);
|
|
@@ -521,11 +524,18 @@ class ResponseExecutor {
|
|
|
521
524
|
};
|
|
522
525
|
}
|
|
523
526
|
}
|
|
524
|
-
async executeTool(toolName, toolInput, input) {
|
|
527
|
+
async executeTool(toolName, toolInput, input, toolUseId) {
|
|
525
528
|
var _a, _b;
|
|
526
529
|
const executionToolName = (0, agentToolLoader_1.resolveToolExecutionName)(toolName);
|
|
527
530
|
const localTool = this.localToolsByExecutionName.get(executionToolName);
|
|
528
531
|
if (localTool) {
|
|
532
|
+
const localToolUseId = toolUseId || `${executionToolName}-${Date.now()}`;
|
|
533
|
+
codeboltjs_1.default.chat.sendLocalToolExecutionUpdate({
|
|
534
|
+
toolUseId: localToolUseId,
|
|
535
|
+
toolName: executionToolName,
|
|
536
|
+
params: toolInput,
|
|
537
|
+
state: 'EXECUTING',
|
|
538
|
+
});
|
|
529
539
|
const localResult = await localTool.execute(toolInput, {
|
|
530
540
|
initialUserMessage: input.initialUserMessage,
|
|
531
541
|
llmMessageSent: input.actualMessageSentToLLM,
|
|
@@ -533,6 +543,13 @@ class ResponseExecutor {
|
|
|
533
543
|
nextMessage: input.nextMessage,
|
|
534
544
|
toolName: executionToolName,
|
|
535
545
|
});
|
|
546
|
+
codeboltjs_1.default.chat.sendLocalToolExecutionUpdate({
|
|
547
|
+
toolUseId: localToolUseId,
|
|
548
|
+
toolName: executionToolName,
|
|
549
|
+
params: toolInput,
|
|
550
|
+
state: localResult.success ? 'EXECUTION_SUCCESS' : 'EXECUTION_ERROR',
|
|
551
|
+
result: localResult.success ? localResult.result : localResult.error,
|
|
552
|
+
});
|
|
536
553
|
if (!localResult.success) {
|
|
537
554
|
return [false, localResult.error || `Local tool "${executionToolName}" failed.`];
|
|
538
555
|
}
|
|
@@ -540,7 +557,7 @@ class ResponseExecutor {
|
|
|
540
557
|
}
|
|
541
558
|
const toolGateway = codeboltjs_1.default.tools;
|
|
542
559
|
if (typeof (toolGateway === null || toolGateway === void 0 ? void 0 : toolGateway.execute) === 'function') {
|
|
543
|
-
const response = await toolGateway.execute(executionToolName, toolInput);
|
|
560
|
+
const response = await toolGateway.execute(executionToolName, toolInput, toolUseId ? { toolUseId } : {});
|
|
544
561
|
const data = (_b = response.data) !== null && _b !== void 0 ? _b : response.result;
|
|
545
562
|
if (Array.isArray(data) && data.length >= 2) {
|
|
546
563
|
const [didUserReject, content] = data;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codebolt/agent",
|
|
3
|
-
"version": "6.1.
|
|
3
|
+
"version": "6.1.26",
|
|
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",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"build": "tsc",
|
|
14
14
|
"clean": "rm -rf dist",
|
|
15
15
|
"dev": "tsc --watch",
|
|
16
|
-
"test": "
|
|
16
|
+
"test": "npm run build && node --test tests/*.test.js",
|
|
17
17
|
"lint": "eslint src/**/*.ts && tsc --noEmit",
|
|
18
18
|
"lint:test": "npm run lint",
|
|
19
19
|
"docs": "node script/gen-docusaurus-agent-types.js",
|