@chatbotkit/agent 1.29.0 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,13 +11,13 @@ Build autonomous AI agents that can use custom tools and execute complex tasks w
11
11
 
12
12
  ## Why ChatBotKit?
13
13
 
14
- **Build lighter, future-proof AI agents.** When you build with ChatBotKit, the heavy lifting happens on our servers—not in your application. This architectural advantage delivers:
14
+ **Build lighter, future-proof AI agents.** When you build with ChatBotKit, the heavy lifting happens on our servers-not in your application. This architectural advantage delivers:
15
15
 
16
16
  - ðŸŠķ **Lightweight Agents**: Your agents stay lean because complex AI processing, model orchestration, and tool execution happen server-side. Less code in your app means faster load times and simpler maintenance.
17
17
 
18
18
  - ðŸ›Ąïļ **Robust & Streamlined**: Server-side processing provides a more reliable experience with built-in error handling, automatic retries, and consistent behavior across all platforms.
19
19
 
20
- - 🔄 **Backward & Forward Compatible**: As AI technology evolves—new models, new capabilities, new paradigms—your agents automatically benefit. No code changes required on your end.
20
+ - 🔄 **Backward & Forward Compatible**: As AI technology evolves-new models, new capabilities, new paradigms-your agents automatically benefit. No code changes required on your end.
21
21
 
22
22
  - ðŸ”Ū **Future-Proof**: Agents you build today will remain capable tomorrow. When we add support for new AI models or capabilities, your existing agents gain those powers without any updates to your codebase.
23
23
 
@@ -197,7 +197,7 @@ The `execute` mode provides system tools for task management:
197
197
  Load skills from local directories and pass them as a feature to the agent. Skills are defined using `SKILL.md` files with front matter containing name and description.
198
198
 
199
199
  ```javascript
200
- import { execute, loadSkills, createSkillsFeature } from '@chatbotkit/agent'
200
+ import { createSkillsFeature, execute, loadSkills } from '@chatbotkit/agent'
201
201
  import { ChatBotKit } from '@chatbotkit/sdk'
202
202
 
203
203
  const client = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_TOKEN })
@@ -1,308 +1,47 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.complete = complete;
4
- exports.execute = execute;
5
- const zod_1 = require("zod");
6
- const zod_to_json_schema_1 = require("zod-to-json-schema");
7
- async function* complete(options) {
8
- const { client, tools, abortSignal, ...request } = options;
9
- const channelToTool = new Map();
10
- const functions = tools
11
- ? Object.entries(tools).map(([name, tool]) => {
12
- const randomSuffix = Math.random().toString(36).substring(2, 15);
13
- const channel = `${name}_${randomSuffix}`.padEnd(16, '0');
14
- channelToTool.set(channel, { name, tool });
15
- if (!tool.input) {
16
- return {
17
- name,
18
- description: tool.description,
19
- parameters: ({
20
- type: 'object',
21
- properties: {},
22
- }),
23
- result: {
24
- channel,
25
- },
26
- };
27
- }
28
- const schema = ((0, zod_to_json_schema_1.zodToJsonSchema)(tool.input, { target: 'openApi3' }));
29
- const parameters = {
30
- type: 'object',
31
- properties: schema.properties || {},
32
- ...(schema.required && schema.required.length > 0
33
- ? { required: schema.required }
34
- : {}),
35
- };
36
- return {
37
- name,
38
- description: tool.description,
39
- parameters: (parameters),
40
- result: {
41
- channel,
42
- },
43
- };
44
- })
45
- : undefined;
46
- const stream = client.conversation
47
- .complete(null, {
48
- ...request,
49
- functions,
50
- limits: {
51
- iterations: 1,
52
- },
53
- })
54
- .stream({ abortSignal });
55
- const toolEventQueue = [];
56
- const runningToolPromises = [];
57
- const executeToolAsync = async (channel, name, tool, args) => {
58
- try {
59
- let parsedArgs = args;
60
- if (tool.input) {
61
- const parseResult = tool.input.safeParse(args);
62
- if (!parseResult.success) {
63
- const errorMsg = `Invalid arguments: ${parseResult.error.message}`;
64
- toolEventQueue.push({
65
- type: 'toolCallError',
66
- data: { name, error: errorMsg },
67
- });
68
- await client.channel.publish(String(channel), {
69
- message: { error: errorMsg },
70
- });
71
- return;
72
- }
73
- parsedArgs = parseResult.data;
74
- }
75
- const result = await tool.handler(parsedArgs);
76
- toolEventQueue.push({
77
- type: 'toolCallEnd',
78
- data: { name, result },
79
- });
80
- await client.channel.publish(String(channel), {
81
- message: { data: result },
82
- });
83
- }
84
- catch (error) {
85
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
86
- toolEventQueue.push({
87
- type: 'toolCallError',
88
- data: { name, error: errorMessage },
89
- });
90
- await client.channel.publish(String(channel), {
91
- message: { error: errorMessage },
92
- });
93
- }
94
- };
95
- for await (const event of stream) {
96
- if (abortSignal?.aborted) {
97
- break;
98
- }
99
- while (toolEventQueue.length > 0) {
100
- const toolEvent = toolEventQueue.shift();
101
- if (toolEvent) {
102
- yield toolEvent;
103
- }
104
- }
105
- if (event.type === 'waitForChannelMessageBegin' &&
106
- event.data &&
107
- 'channel' in event.data &&
108
- 'function' in event.data) {
109
- const channel = (event.data.channel);
110
- const args = (event.data.function).args;
111
- const toolInfo = channelToTool.get(String(channel));
112
- if (toolInfo) {
113
- const { name, tool } = toolInfo;
114
- yield {
115
- type: 'toolCallStart',
116
- data: {
117
- name,
118
- args,
119
- },
120
- };
121
- const toolPromise = executeToolAsync(channel, name, tool, args);
122
- runningToolPromises.push(toolPromise);
123
- }
124
- }
125
- yield event;
6
+ exports.loadAgent = loadAgent;
7
+ const promises_1 = require("fs/promises");
8
+ const js_yaml_1 = __importDefault(require("js-yaml"));
9
+ const path_1 = require("path");
10
+ function parseAgentFile(content) {
11
+ const frontMatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)/;
12
+ const match = content.match(frontMatterRegex);
13
+ if (!match) {
14
+ return { frontMatter: {}, body: content.trim() };
126
15
  }
127
- while (toolEventQueue.length > 0) {
128
- const toolEvent = toolEventQueue.shift();
129
- if (toolEvent) {
130
- yield toolEvent;
16
+ let frontMatter = ({});
17
+ try {
18
+ const parsed = js_yaml_1.default.load(match[1]);
19
+ if (typeof parsed === 'object' && parsed !== null) {
20
+ frontMatter = (parsed);
131
21
  }
132
22
  }
133
- if (runningToolPromises.length > 0) {
134
- await Promise.allSettled(runningToolPromises);
135
- while (toolEventQueue.length > 0) {
136
- const toolEvent = toolEventQueue.shift();
137
- if (toolEvent) {
138
- yield toolEvent;
139
- }
140
- }
23
+ catch {
141
24
  }
25
+ return { frontMatter, body: match[2].trim() };
142
26
  }
143
- async function* execute(options) {
144
- const { client, tools = {}, maxIterations = 100, abortSignal, ...request } = options;
145
- const messages = request.messages || [];
146
- let exitResult = null;
147
- let internalAbort = null;
148
- const systemTools = {
149
- plan: {
150
- description: 'Create or update a plan for approaching the task. Break down the task into clear, actionable steps. Use this at the start and whenever you need to revise your approach.',
151
- input: zod_1.z.object({
152
- steps: zod_1.z
153
- .array(zod_1.z.string())
154
- .describe('Array of step descriptions in order of execution'),
155
- rationale: zod_1.z
156
- .string()
157
- .optional()
158
- .describe('Brief explanation of the plan approach'),
159
- }),
160
- handler: async (input) => {
161
- return {
162
- success: true,
163
- message: `Plan created with ${input.steps.length} steps${input.rationale ? ': ' + input.rationale : ''}`,
164
- };
165
- },
166
- },
167
- progress: {
168
- description: 'Update progress on the current task. Use this to track completed steps, report current status, and identify blockers.',
169
- input: zod_1.z.object({
170
- completed: zod_1.z
171
- .array(zod_1.z.string())
172
- .optional()
173
- .describe('Steps that have been completed'),
174
- current: zod_1.z.string().optional().describe('Current step being worked on'),
175
- blockers: zod_1.z
176
- .array(zod_1.z.string())
177
- .optional()
178
- .describe('Any issues preventing progress'),
179
- nextSteps: zod_1.z
180
- .array(zod_1.z.string())
181
- .optional()
182
- .describe('Next actions to take'),
183
- }),
184
- handler: async (input) => {
185
- return {
186
- success: true,
187
- message: 'Progress updated',
188
- ...input,
189
- };
190
- },
191
- },
192
- exit: {
193
- description: 'Exit the task execution with a status code and optional message. Status code 0 indicates success, non-zero indicates failure. Use this when all the tasks are complete or cannot proceed.',
194
- input: zod_1.z.object({
195
- code: zod_1.z
196
- .number()
197
- .int()
198
- .min(0)
199
- .max(255)
200
- .describe('Exit status code (0 = success, non-zero = failure)'),
201
- message: zod_1.z
202
- .string()
203
- .optional()
204
- .describe('Optional message explaining the exit reason'),
205
- }),
206
- handler: async (input) => {
207
- exitResult = { code: input.code, message: input.message };
208
- return {
209
- success: true,
210
- message: `Task exiting with code ${input.code}${input.message ? ': ' + input.message : ''}`,
211
- };
212
- },
213
- },
214
- abort: {
215
- description: 'Immediately abort the current task. Use this when the user explicitly asks you to stop, cancel, or abort what you are doing. Set hard to true to kill running processes immediately.',
216
- input: zod_1.z.object({
217
- reason: zod_1.z.string().optional().describe('Brief reason for aborting'),
218
- hard: zod_1.z
219
- .boolean()
220
- .optional()
221
- .describe('If true, immediately kill running processes. If false (default), finish the current operation gracefully.'),
222
- }),
223
- handler: async (input) => {
224
- const reason = input.reason || 'aborted by user request';
225
- exitResult = { code: 1, message: reason };
226
- if (input.hard && internalAbort) {
227
- internalAbort.abort(reason);
228
- }
229
- return {
230
- success: true,
231
- message: `Task aborted: ${reason}`,
232
- };
233
- },
234
- },
235
- };
236
- const allTools = { ...tools, ...systemTools };
237
- const systemInstruction = `
238
- ${options.extensions?.backstory || ''}
239
-
240
- # Task Execution Guidelines
241
-
242
- The goal is to complete the assigned task efficiently and effectively. Follow these guidelines:
243
-
244
- 1. **Plan First**: Use the 'plan' function to create a clear strategy before starting work
245
- 2. **Track Progress**: Regularly use the 'progress' function to update status and identify issues
246
- 3. **Use Tools**: Leverage available tools to accomplish each step of your plan
247
- 4. **Exit When Done**: Call the 'exit' function with code 0 when successful, or non-zero code if unable to complete
248
- 5. **Abort**: If the user asks you to stop, cancel, or abort, call the 'abort' function immediately. Use hard=true if processes are running that need to be killed right away.
249
- 6. **Be Autonomous**: Work through the task systematically without waiting for additional input
250
- 7. **Be Responsive**: If the user sends a new message while you are working, acknowledge it briefly and adjust your approach if needed. Always prioritize user input over your current plan.
251
- `.trim();
252
- let iteration = 0;
253
- while (iteration < maxIterations && exitResult === null) {
254
- if (abortSignal?.aborted) {
255
- exitResult = {
256
- code: 1,
257
- message: 'Task execution aborted',
258
- };
259
- break;
260
- }
261
- iteration++;
262
- yield { type: 'iteration', data: { iteration } };
263
- let lastEndReason = null;
264
- internalAbort = new AbortController();
265
- if (abortSignal?.aborted) {
266
- internalAbort.abort(abortSignal.reason);
267
- }
268
- else if (abortSignal) {
269
- const capturedAbort = internalAbort;
270
- abortSignal.addEventListener('abort', () => capturedAbort.abort(abortSignal.reason), { once: true });
271
- }
272
- const iterSignal = internalAbort.signal;
273
- for await (const event of complete({
274
- ...request,
275
- client,
276
- messages,
277
- tools: allTools,
278
- abortSignal: iterSignal,
279
- extensions: {
280
- ...options.extensions,
281
- backstory: systemInstruction,
282
- },
283
- })) {
284
- if (event.type === 'message') {
285
- messages.push(event.data);
286
- }
287
- if (event.type === 'result') {
288
- if (event.data.end.reason) {
289
- lastEndReason = event.data.end.reason;
290
- }
291
- }
292
- yield event;
293
- }
294
- if (exitResult) {
295
- break;
296
- }
297
- if (lastEndReason === 'stop') {
298
- break;
299
- }
300
- }
301
- if (exitResult === null) {
302
- exitResult = {
303
- code: 1,
304
- message: `Task did not complete within ${maxIterations} iterations`,
305
- };
306
- }
307
- yield { type: 'exit', data: exitResult };
27
+ async function loadAgent(filePath) {
28
+ const resolvedPath = (0, path_1.resolve)(process.cwd(), filePath);
29
+ const content = await (0, promises_1.readFile)(resolvedPath, 'utf-8');
30
+ const { frontMatter, body } = parseAgentFile(content);
31
+ const name = typeof frontMatter.name === 'string' ? frontMatter.name : undefined;
32
+ const description = typeof frontMatter.description === 'string'
33
+ ? frontMatter.description
34
+ : undefined;
35
+ const model = typeof frontMatter.model === 'string' ? frontMatter.model : undefined;
36
+ const botId = typeof frontMatter.botId === 'string' ? frontMatter.botId : undefined;
37
+ const skillsetId = typeof frontMatter.skillsetId === 'string'
38
+ ? frontMatter.skillsetId
39
+ : undefined;
40
+ const datasetId = typeof frontMatter.datasetId === 'string'
41
+ ? frontMatter.datasetId
42
+ : undefined;
43
+ const frontMatterBackstory = typeof frontMatter.backstory === 'string' ? frontMatter.backstory : '';
44
+ const backstoryParts = [frontMatterBackstory, body].filter(Boolean);
45
+ const backstory = backstoryParts.length > 0 ? backstoryParts.join('\n\n') : undefined;
46
+ return { name, description, backstory, model, botId, skillsetId, datasetId };
308
47
  }
@@ -1,56 +1,10 @@
1
- export function complete(options: Omit<ConversationCompleteRequest, "functions" | "limits"> & {
2
- client: ChatBotKit;
3
- tools?: Tools;
4
- abortSignal?: AbortSignal;
5
- }): AsyncGenerator<ConversationCompleteStreamType | ToolCallStartEvent | ToolCallEndEvent | ToolCallErrorEvent, void, unknown>;
6
- export function execute(options: Omit<ConversationCompleteRequest, "functions" | "limits"> & {
7
- client: ChatBotKit;
8
- tools?: Tools;
9
- maxIterations?: number;
10
- abortSignal?: AbortSignal;
11
- }): AsyncGenerator<ConversationCompleteStreamType | ToolCallStartEvent | ToolCallEndEvent | ToolCallErrorEvent | IterationEvent | ExitEvent, void, unknown>;
12
- export type ZodObject = import("zod").ZodObject<any>;
13
- export type ChatBotKit = import("@chatbotkit/sdk").ChatBotKit;
14
- export type ConversationCompleteRequest = any;
15
- export type ConversationCompleteStreamType = any;
16
- export type ToolDefinition<T extends ZodObject> = {
17
- description: string;
18
- input?: T;
19
- handler: (input: any) => Promise<any>;
20
- };
21
- export type Tools = Record<string, ToolDefinition<ZodObject>>;
22
- export type ExitResult = {
23
- code: number;
24
- message?: string;
25
- };
26
- export type ToolCallStartEvent = {
27
- type: "toolCallStart";
28
- data: {
29
- name: string;
30
- args: any;
31
- };
32
- };
33
- export type ToolCallEndEvent = {
34
- type: "toolCallEnd";
35
- data: {
36
- name: string;
37
- result: any;
38
- };
39
- };
40
- export type ToolCallErrorEvent = {
41
- type: "toolCallError";
42
- data: {
43
- name: string;
44
- error: string;
45
- };
46
- };
47
- export type IterationEvent = {
48
- type: "iteration";
49
- data: {
50
- iteration: number;
51
- };
52
- };
53
- export type ExitEvent = {
54
- type: "exit";
55
- data: ExitResult;
1
+ export function loadAgent(filePath: string): Promise<AgentDefinition>;
2
+ export type AgentDefinition = {
3
+ name?: string;
4
+ description?: string;
5
+ backstory?: string;
6
+ model?: string;
7
+ botId?: string;
8
+ skillsetId?: string;
9
+ datasetId?: string;
56
10
  };