@backendkit-labs/agent-core 0.21.0 → 0.22.1
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 +1031 -164
- package/dist/engine/MCPRegistrar.d.ts +1 -0
- package/dist/engine/MCPRegistrar.d.ts.map +1 -1
- package/dist/engine/MCPRegistrar.js +8 -0
- package/dist/engine/MCPRegistrar.js.map +1 -1
- package/dist/mcp/MCPClientManager.d.ts +8 -0
- package/dist/mcp/MCPClientManager.d.ts.map +1 -1
- package/dist/mcp/MCPClientManager.js +24 -1
- package/dist/mcp/MCPClientManager.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,263 +1,1130 @@
|
|
|
1
1
|
# @backendkit-labs/agent-core
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
See the [subsystem matrix](../../README.md#backendkit-labsagent-core-subsystem-matrix) for per-subsystem status (`qa`, `reflection`, `agent-memory`, `observability`, `triggers` are **experimental** and frozen during the pilot).
|
|
3
|
+
The foundation engine for the BackendKit Labs agent framework. Provides everything needed to build, run, and compose AI agents: typed tool definitions, provider adapters, session memory, MCP client, workflow orchestration, and advanced multi-layer memory.
|
|
5
4
|
|
|
6
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/@backendkit-labs/agent-core)
|
|
6
|
+
|
|
7
|
+
## Table of contents
|
|
8
|
+
|
|
9
|
+
- [Installation](#installation)
|
|
10
|
+
- [Quick start](#quick-start)
|
|
11
|
+
- [defineTool — typed tools with Zod](#definetool--typed-tools-with-zod)
|
|
12
|
+
- [AgentEngine — the execution core](#agentengine--the-execution-core)
|
|
13
|
+
- [createBaseEngine — high-level factory](#createbaseengine--high-level-factory)
|
|
14
|
+
- [Providers](#providers)
|
|
15
|
+
- [Transports](#transports)
|
|
16
|
+
- [SessionMemory](#sessionmemory)
|
|
17
|
+
- [MCP client](#mcp-client)
|
|
18
|
+
- [Workflow engine](#workflow-engine)
|
|
19
|
+
- [Advanced memory system](#advanced-memory-system)
|
|
20
|
+
- [Observability](#observability)
|
|
21
|
+
- [Skills and slash commands](#skills-and-slash-commands)
|
|
22
|
+
- [Checkpoints](#checkpoints)
|
|
23
|
+
- [Workspaces](#workspaces)
|
|
24
|
+
- [Autonomous agents and triggers](#autonomous-agents-and-triggers)
|
|
25
|
+
- [Delegation bus](#delegation-bus)
|
|
26
|
+
- [Type reference](#type-reference)
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
7
31
|
|
|
8
32
|
```bash
|
|
9
33
|
npm install @backendkit-labs/agent-core
|
|
10
34
|
```
|
|
11
35
|
|
|
36
|
+
Requires Node.js ≥ 18 and TypeScript ≥ 5.0.
|
|
37
|
+
|
|
12
38
|
---
|
|
13
39
|
|
|
14
40
|
## Quick start
|
|
15
41
|
|
|
16
|
-
|
|
17
|
-
import { createBaseEngine } from '@backendkit-labs/agent-core';
|
|
18
|
-
import { AnthropicProvider } from '@backendkit-labs/agent-coding';
|
|
42
|
+
The fastest path to a running agent:
|
|
19
43
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
44
|
+
```typescript
|
|
45
|
+
import {
|
|
46
|
+
AgentEngine,
|
|
47
|
+
AgentRegistry,
|
|
48
|
+
ToolRegistry,
|
|
49
|
+
ProviderRegistry,
|
|
50
|
+
defineTool,
|
|
51
|
+
z,
|
|
52
|
+
StdoutTransport,
|
|
53
|
+
} from '@backendkit-labs/agent-core';
|
|
54
|
+
|
|
55
|
+
// 1. Define a tool
|
|
56
|
+
const weatherTool = defineTool({
|
|
57
|
+
name: 'get_weather',
|
|
58
|
+
description: 'Returns current weather for a city',
|
|
59
|
+
input: z.object({
|
|
60
|
+
city: z.string().describe('City name'),
|
|
61
|
+
}),
|
|
62
|
+
execute: async ({ city }) => `Weather in ${city}: sunny, 22°C`,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// 2. Register tools and agents
|
|
66
|
+
const tools = new ToolRegistry();
|
|
67
|
+
tools.register(weatherTool);
|
|
68
|
+
|
|
69
|
+
const agents = new AgentRegistry();
|
|
70
|
+
agents.register({
|
|
71
|
+
id: 'general',
|
|
72
|
+
name: 'General Assistant',
|
|
73
|
+
systemPrompt: 'You are a helpful assistant. Use available tools when relevant.',
|
|
74
|
+
tools: ['get_weather'],
|
|
31
75
|
});
|
|
32
76
|
|
|
33
|
-
|
|
77
|
+
// 3. Register an LLM provider
|
|
78
|
+
const providers = new ProviderRegistry();
|
|
79
|
+
providers.register('my-provider', myLLMProvider);
|
|
80
|
+
|
|
81
|
+
// 4. Run
|
|
82
|
+
const engine = new AgentEngine({
|
|
83
|
+
model: { provider: 'my-provider', id: 'gpt-4o' },
|
|
84
|
+
agents,
|
|
85
|
+
tools,
|
|
86
|
+
providers,
|
|
87
|
+
defaultProvider: 'my-provider',
|
|
88
|
+
defaultAgentId: 'general',
|
|
89
|
+
transport: new StdoutTransport(),
|
|
90
|
+
maxIterations: 10,
|
|
91
|
+
iterationMode: 'auto',
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
await engine.run("What's the weather in London?");
|
|
34
95
|
```
|
|
35
96
|
|
|
36
|
-
|
|
97
|
+
---
|
|
37
98
|
|
|
38
|
-
|
|
39
|
-
|
|
99
|
+
## defineTool — typed tools with Zod
|
|
100
|
+
|
|
101
|
+
`defineTool` wraps a function with a Zod input schema. The engine validates inputs before calling `execute`, and the TypeScript types flow through automatically.
|
|
102
|
+
|
|
103
|
+
### Basic tool
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
import { defineTool, z } from '@backendkit-labs/agent-core';
|
|
107
|
+
|
|
108
|
+
const greetTool = defineTool({
|
|
109
|
+
name: 'greet',
|
|
110
|
+
description: 'Greet a user by name',
|
|
111
|
+
input: z.object({ name: z.string() }),
|
|
112
|
+
execute: async ({ name }) => `Hello, ${name}!`,
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Optional parameters and defaults
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
const searchTool = defineTool({
|
|
120
|
+
name: 'search_products',
|
|
121
|
+
description: 'Search the product catalog',
|
|
122
|
+
input: z.object({
|
|
123
|
+
query: z.string().describe('Search term'),
|
|
124
|
+
category: z.string().optional().describe('Filter by category'),
|
|
125
|
+
limit: z.number().min(1).max(50).default(10),
|
|
126
|
+
sort: z.enum(['price_asc', 'price_desc', 'relevance']).default('relevance'),
|
|
127
|
+
}),
|
|
128
|
+
execute: async ({ query, category, limit, sort }) => {
|
|
129
|
+
const results = await db.products.search({ query, category, limit, sort });
|
|
130
|
+
return results.map(p => `${p.name} — $${p.price}`).join('\n');
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Structured / nested input
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
const createOrderTool = defineTool({
|
|
139
|
+
name: 'create_order',
|
|
140
|
+
description: 'Create a new customer order',
|
|
141
|
+
input: z.object({
|
|
142
|
+
customer: z.object({
|
|
143
|
+
id: z.string(),
|
|
144
|
+
email: z.string().email(),
|
|
145
|
+
}),
|
|
146
|
+
items: z.array(z.object({
|
|
147
|
+
productId: z.string(),
|
|
148
|
+
qty: z.number().int().positive(),
|
|
149
|
+
})).min(1),
|
|
150
|
+
shippingAddress: z.string(),
|
|
151
|
+
notes: z.string().optional(),
|
|
152
|
+
}),
|
|
153
|
+
execute: async ({ customer, items, shippingAddress, notes }) => {
|
|
154
|
+
const order = await orders.create({ customer, items, shippingAddress, notes });
|
|
155
|
+
return `Order ${order.id} created for ${items.length} item(s).`;
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Returning JSON
|
|
161
|
+
|
|
162
|
+
Return a JSON string so the LLM can reason about structured data:
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
const analyzeCodeTool = defineTool({
|
|
166
|
+
name: 'analyze_code',
|
|
167
|
+
description: 'Analyze code and return structured issues',
|
|
168
|
+
input: z.object({
|
|
169
|
+
code: z.string(),
|
|
170
|
+
language: z.string(),
|
|
171
|
+
}),
|
|
172
|
+
execute: async ({ code, language }) => {
|
|
173
|
+
const issues = await analyzer.run(code, language);
|
|
174
|
+
return JSON.stringify({
|
|
175
|
+
issueCount: issues.length,
|
|
176
|
+
critical: issues.filter(i => i.severity === 'critical'),
|
|
177
|
+
warnings: issues.filter(i => i.severity === 'warning'),
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Tool that throws (error signaling)
|
|
184
|
+
|
|
185
|
+
When a tool throws, the engine catches the error and tells the LLM, which can retry with corrected arguments or apologize to the user:
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
const lookupUserTool = defineTool({
|
|
189
|
+
name: 'lookup_user',
|
|
190
|
+
description: 'Look up a user by email',
|
|
191
|
+
input: z.object({ email: z.string().email() }),
|
|
192
|
+
execute: async ({ email }) => {
|
|
193
|
+
const user = await db.users.findByEmail(email);
|
|
194
|
+
if (!user) throw new Error(`No user found with email ${email}`);
|
|
195
|
+
return JSON.stringify(user);
|
|
196
|
+
},
|
|
197
|
+
});
|
|
40
198
|
```
|
|
41
199
|
|
|
42
200
|
---
|
|
43
201
|
|
|
44
|
-
##
|
|
202
|
+
## AgentEngine — the execution core
|
|
203
|
+
|
|
204
|
+
`AgentEngine` is the stateful agent runner. It owns the conversation loop, tool dispatch, multi-agent delegation, and iteration control.
|
|
205
|
+
|
|
206
|
+
### Constructor options
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
new AgentEngine({
|
|
210
|
+
// Required
|
|
211
|
+
model: { provider: 'openai', id: 'gpt-4o' },
|
|
212
|
+
agents,
|
|
213
|
+
tools,
|
|
214
|
+
providers,
|
|
215
|
+
defaultProvider: 'openai',
|
|
216
|
+
defaultAgentId: 'general',
|
|
217
|
+
|
|
218
|
+
// I/O
|
|
219
|
+
transport: new StdoutTransport(),
|
|
220
|
+
sessionId: 'session-xyz',
|
|
221
|
+
|
|
222
|
+
// Iteration control
|
|
223
|
+
maxIterations: 50,
|
|
224
|
+
iterationMode: 'auto', // 'auto' | 'manual' | 'step-by-step' | 'interactive'
|
|
225
|
+
|
|
226
|
+
// Memory
|
|
227
|
+
sessionMemory: mySessionMemory,
|
|
228
|
+
memorySystem: myMemorySystem,
|
|
229
|
+
historyPath: '/path/to/history.json',
|
|
230
|
+
|
|
231
|
+
// MCP servers (connected lazily on first run)
|
|
232
|
+
mcpServers: [
|
|
233
|
+
{ name: 'github', command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] }
|
|
234
|
+
],
|
|
235
|
+
|
|
236
|
+
// Observability
|
|
237
|
+
observability: obsManager,
|
|
238
|
+
auditLog: '/path/to/audit.ndjson',
|
|
239
|
+
|
|
240
|
+
// Context injected into the system prompt
|
|
241
|
+
projectContext: 'You are working in project X...',
|
|
242
|
+
})
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Running the engine
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
// Basic run — returns when done
|
|
249
|
+
const result = await engine.run('Summarize the README.md file');
|
|
250
|
+
console.log(result.final); // final assistant response
|
|
251
|
+
|
|
252
|
+
// Run with a specific agent
|
|
253
|
+
const result = await engine.run('Review this code for security issues', {
|
|
254
|
+
agentId: 'security-reviewer',
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// Stream events to a UI
|
|
258
|
+
const events: AgentEvent[] = [];
|
|
259
|
+
await engine.run('Analyze the database schema', {
|
|
260
|
+
onEvent: (event) => {
|
|
261
|
+
if (event.type === 'chunk') process.stdout.write(event.content);
|
|
262
|
+
events.push(event);
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### Iteration modes
|
|
268
|
+
|
|
269
|
+
| Mode | Behavior |
|
|
270
|
+
|------|----------|
|
|
271
|
+
| `'auto'` | Runs until complete or `maxIterations` reached |
|
|
272
|
+
| `'manual'` | Pauses before write/execute tool calls, calls `onToolApproval` |
|
|
273
|
+
| `'step-by-step'` | Calls `onStep` after every iteration; return `false` to stop |
|
|
274
|
+
| `'interactive'` | Calls `onIterationLimit` when cap is reached; return `true` to continue |
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
// Manual approval — user approves destructive tool calls
|
|
278
|
+
const engine = new AgentEngine({
|
|
279
|
+
...opts,
|
|
280
|
+
iterationMode: 'manual',
|
|
281
|
+
onToolApproval: async (toolName, agentId, argsPreview) => {
|
|
282
|
+
console.log(`[${agentId}] → ${toolName}:`, argsPreview);
|
|
283
|
+
const answer = await prompt('Approve? (y/n/all) ');
|
|
284
|
+
if (answer === 'y') return 'approve';
|
|
285
|
+
if (answer === 'all') return 'approve_all';
|
|
286
|
+
return 'reject';
|
|
287
|
+
},
|
|
288
|
+
});
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
```typescript
|
|
292
|
+
// Step-by-step — inspect each iteration
|
|
293
|
+
const engine = new AgentEngine({
|
|
294
|
+
...opts,
|
|
295
|
+
iterationMode: 'step-by-step',
|
|
296
|
+
onStep: async (stats) => {
|
|
297
|
+
console.log(`Iteration ${stats.count}/${stats.max} — agent: ${stats.agentId}`);
|
|
298
|
+
return true; // false to stop
|
|
299
|
+
},
|
|
300
|
+
});
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
### Multi-turn sessions
|
|
45
304
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
305
|
+
The engine retains conversation history between `run()` calls on the same instance:
|
|
306
|
+
|
|
307
|
+
```typescript
|
|
308
|
+
await engine.run('My name is Alice.');
|
|
309
|
+
await engine.run("What's my name?"); // → "Your name is Alice."
|
|
310
|
+
```
|
|
51
311
|
|
|
52
312
|
---
|
|
53
313
|
|
|
54
|
-
##
|
|
314
|
+
## createBaseEngine — high-level factory
|
|
55
315
|
|
|
56
|
-
|
|
316
|
+
`createBaseEngine` assembles all internals from a flat options object so you don't have to instantiate registries manually.
|
|
57
317
|
|
|
58
|
-
```
|
|
318
|
+
```typescript
|
|
59
319
|
import { createBaseEngine } from '@backendkit-labs/agent-core';
|
|
60
320
|
|
|
61
321
|
const engine = createBaseEngine({
|
|
62
|
-
providers: {
|
|
63
|
-
defaultProvider: '
|
|
64
|
-
agents:
|
|
65
|
-
tools:
|
|
66
|
-
defaultAgent: '
|
|
67
|
-
|
|
322
|
+
providers: { openai: myOpenAIProvider },
|
|
323
|
+
defaultProvider: 'openai',
|
|
324
|
+
agents: myAgentList, // AgentProfile[]
|
|
325
|
+
tools: myToolList, // ToolDefinition[]
|
|
326
|
+
defaultAgent: 'general',
|
|
327
|
+
transport: new StdoutTransport(),
|
|
328
|
+
maxIterations: 100,
|
|
329
|
+
workingDir: process.cwd(),
|
|
68
330
|
});
|
|
69
331
|
|
|
70
|
-
await engine.run('
|
|
71
|
-
engine.abort(); // cancel in-flight request
|
|
72
|
-
engine.updateWorkingDir('/new/path'); // live workspace switch
|
|
73
|
-
engine.reloadSkills(); // reload YAML skills from disk
|
|
332
|
+
await engine.run('Hello!');
|
|
74
333
|
```
|
|
75
334
|
|
|
76
|
-
###
|
|
335
|
+
### With MCP servers and orchestration
|
|
77
336
|
|
|
78
|
-
```
|
|
79
|
-
|
|
337
|
+
```typescript
|
|
338
|
+
const engine = createBaseEngine({
|
|
339
|
+
providers: { anthropic: myAnthropicProvider },
|
|
340
|
+
defaultProvider: 'anthropic',
|
|
341
|
+
agents: myAgents,
|
|
342
|
+
tools: myTools,
|
|
343
|
+
defaultAgent: 'general',
|
|
344
|
+
mcpServers: [
|
|
345
|
+
{
|
|
346
|
+
name: 'github',
|
|
347
|
+
command: 'npx',
|
|
348
|
+
args: ['-y', '@modelcontextprotocol/server-github'],
|
|
349
|
+
env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN! },
|
|
350
|
+
},
|
|
351
|
+
{
|
|
352
|
+
name: 'postgres',
|
|
353
|
+
command: 'npx',
|
|
354
|
+
args: ['-y', '@modelcontextprotocol/server-postgres', process.env.DATABASE_URL!],
|
|
355
|
+
},
|
|
356
|
+
],
|
|
357
|
+
orchestration: true, // enables intent detection + domain routing + QA review
|
|
358
|
+
});
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
---
|
|
362
|
+
|
|
363
|
+
## Providers
|
|
364
|
+
|
|
365
|
+
Providers wrap LLM APIs and implement the `LLMProvider` interface. `ProviderRegistry` holds named providers that the engine selects per-agent.
|
|
80
366
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
367
|
+
```typescript
|
|
368
|
+
import { ProviderRegistry } from '@backendkit-labs/agent-core';
|
|
369
|
+
|
|
370
|
+
const providers = new ProviderRegistry();
|
|
371
|
+
|
|
372
|
+
// Register multiple providers — engine selects per-agent or falls back to defaultProvider
|
|
373
|
+
providers.register('openai', openAIProvider);
|
|
374
|
+
providers.register('anthropic', anthropicProvider);
|
|
375
|
+
providers.register('local', ollamaProvider);
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
### Custom LLM provider
|
|
379
|
+
|
|
380
|
+
Implement `LLMProvider` to add any API:
|
|
381
|
+
|
|
382
|
+
```typescript
|
|
383
|
+
import type { LLMProvider, LLMMessage, LLMStreamCallbacks, ToolDefinition } from '@backendkit-labs/agent-core';
|
|
384
|
+
|
|
385
|
+
class MyProvider implements LLMProvider {
|
|
386
|
+
async chat(
|
|
387
|
+
messages: LLMMessage[],
|
|
388
|
+
tools: ToolDefinition[],
|
|
389
|
+
callbacks: LLMStreamCallbacks,
|
|
390
|
+
): Promise<void> {
|
|
391
|
+
const stream = await myAPI.stream({ messages, tools });
|
|
392
|
+
for await (const chunk of stream) {
|
|
393
|
+
if (chunk.type === 'text') callbacks.onChunk(chunk.text);
|
|
394
|
+
if (chunk.type === 'tool_use') callbacks.onToolCall({ id: chunk.id, name: chunk.name, arguments: chunk.input });
|
|
395
|
+
}
|
|
396
|
+
callbacks.onDone();
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
providers.register('my-api', new MyProvider());
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
---
|
|
404
|
+
|
|
405
|
+
## Transports
|
|
406
|
+
|
|
407
|
+
Transports receive `AgentEvent` objects and deliver them to consumers.
|
|
408
|
+
|
|
409
|
+
### StdoutTransport
|
|
410
|
+
|
|
411
|
+
Prints events as formatted text — good for CLI tools:
|
|
412
|
+
|
|
413
|
+
```typescript
|
|
414
|
+
import { StdoutTransport } from '@backendkit-labs/agent-core';
|
|
415
|
+
const engine = new AgentEngine({ ...opts, transport: new StdoutTransport() });
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
### CallbackTransport
|
|
419
|
+
|
|
420
|
+
Routes events to your own function — use this for server integrations or streaming UIs:
|
|
421
|
+
|
|
422
|
+
```typescript
|
|
423
|
+
import { CallbackTransport } from '@backendkit-labs/agent-core';
|
|
424
|
+
|
|
425
|
+
const transport = new CallbackTransport((event) => {
|
|
426
|
+
switch (event.type) {
|
|
427
|
+
case 'chunk': process.stdout.write(event.content); break;
|
|
428
|
+
case 'tool_call': console.log(`[tool] ${event.name}`); break;
|
|
429
|
+
case 'agent_switch': console.log(`→ ${event.to}`); break;
|
|
430
|
+
case 'done': console.log('\n[done]'); break;
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
### AgentEvent types
|
|
436
|
+
|
|
437
|
+
| Type | Key fields | Description |
|
|
438
|
+
|------|-----------|-------------|
|
|
439
|
+
| `'chunk'` | `content: string` | Incremental LLM token |
|
|
440
|
+
| `'tool_call'` | `name, args, result` | Tool called and returned |
|
|
441
|
+
| `'agent_switch'` | `from, to` | Multi-agent delegation |
|
|
442
|
+
| `'iteration'` | `count, max` | Iteration counter |
|
|
443
|
+
| `'done'` | `final: string` | Run completed |
|
|
444
|
+
| `'error'` | `message: string` | Recoverable error |
|
|
445
|
+
|
|
446
|
+
---
|
|
447
|
+
|
|
448
|
+
## SessionMemory
|
|
449
|
+
|
|
450
|
+
`SessionMemory` stores conversation messages for the current session. `AgentEngine` manages it automatically; use it directly for custom initialization or testing.
|
|
451
|
+
|
|
452
|
+
```typescript
|
|
453
|
+
import { SessionMemory } from '@backendkit-labs/agent-core';
|
|
454
|
+
|
|
455
|
+
const memory = new SessionMemory();
|
|
456
|
+
|
|
457
|
+
// Seed with prior context
|
|
458
|
+
memory.addMessage({ role: 'user', content: 'My name is Alice.' });
|
|
459
|
+
memory.addMessage({ role: 'assistant', content: 'Nice to meet you, Alice!' });
|
|
460
|
+
|
|
461
|
+
const engine = new AgentEngine({ ...opts, sessionMemory: memory });
|
|
462
|
+
|
|
463
|
+
await engine.run("What's my name?"); // → "Your name is Alice."
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
---
|
|
467
|
+
|
|
468
|
+
## MCP client
|
|
469
|
+
|
|
470
|
+
`MCPClientManager` connects to external MCP (Model Context Protocol) servers, discovers their tools, and makes them available to the engine. Supports stdio, Streamable HTTP, and SSE transports.
|
|
471
|
+
|
|
472
|
+
### Stdio (most common)
|
|
473
|
+
|
|
474
|
+
```typescript
|
|
475
|
+
import { MCPClientManager } from '@backendkit-labs/agent-core';
|
|
476
|
+
|
|
477
|
+
const mcp = new MCPClientManager();
|
|
478
|
+
|
|
479
|
+
await mcp.connectStdio({
|
|
480
|
+
name: 'filesystem',
|
|
481
|
+
command: 'npx',
|
|
482
|
+
args: ['-y', '@modelcontextprotocol/server-filesystem', '/workspace'],
|
|
483
|
+
env: {},
|
|
484
|
+
});
|
|
485
|
+
|
|
486
|
+
const tools = mcp.getTools(); // ToolDefinition[] — discovered from the server
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
### HTTP transport
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
await mcp.connectStreamableHTTP({
|
|
493
|
+
name: 'remote-server',
|
|
494
|
+
baseUrl: 'https://mcp.example.com',
|
|
495
|
+
apiKey: process.env.MCP_API_KEY,
|
|
496
|
+
});
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
### SSE transport (legacy servers)
|
|
500
|
+
|
|
501
|
+
```typescript
|
|
502
|
+
await mcp.connectSSE({
|
|
503
|
+
name: 'legacy-server',
|
|
504
|
+
url: 'http://localhost:8080/sse',
|
|
505
|
+
});
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
### Multiple servers via engine options
|
|
509
|
+
|
|
510
|
+
Passing `mcpServers` to `createBaseEngine` or `AgentEngine` is the recommended path — the engine manages the lifecycle, retries, and disconnect detection:
|
|
511
|
+
|
|
512
|
+
```typescript
|
|
513
|
+
const engine = createBaseEngine({
|
|
514
|
+
...opts,
|
|
515
|
+
mcpServers: [
|
|
516
|
+
{ name: 'github', command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'], env: { GITHUB_TOKEN: '...' } },
|
|
517
|
+
{ name: 'slack', command: 'npx', args: ['-y', '@modelcontextprotocol/server-slack'], env: { SLACK_TOKEN: '...' } },
|
|
518
|
+
{ name: 'postgres', command: 'npx', args: ['-y', '@modelcontextprotocol/server-postgres'], env: { DATABASE_URL: '...' } },
|
|
88
519
|
],
|
|
89
520
|
});
|
|
521
|
+
```
|
|
90
522
|
|
|
91
|
-
|
|
92
|
-
|
|
523
|
+
### Disconnect detection (health monitoring)
|
|
524
|
+
|
|
525
|
+
The client detects server crashes via `client.onclose` and marks them `'failed'`, preventing stale `'connected'` state:
|
|
526
|
+
|
|
527
|
+
```typescript
|
|
528
|
+
// The engine's MCPRegistrar wires this automatically.
|
|
529
|
+
// For manual use:
|
|
530
|
+
mcp.setDisconnectHandler((serverName) => {
|
|
531
|
+
console.warn(`MCP server "${serverName}" disconnected`);
|
|
532
|
+
// Re-attempt connection on next engine.run() call
|
|
533
|
+
});
|
|
93
534
|
```
|
|
94
535
|
|
|
95
|
-
|
|
536
|
+
---
|
|
96
537
|
|
|
97
|
-
|
|
98
|
-
import { defineTool, z } from '@backendkit-labs/agent-core';
|
|
538
|
+
## Workflow engine
|
|
99
539
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
540
|
+
Build declarative multi-agent workflows with `WorkflowBuilder`. Steps can run sequentially, in parallel, or conditionally.
|
|
541
|
+
|
|
542
|
+
### Sequential workflow
|
|
543
|
+
|
|
544
|
+
```typescript
|
|
545
|
+
import { workflow, agent } from '@backendkit-labs/agent-core';
|
|
546
|
+
|
|
547
|
+
const reviewPipeline = workflow('code-review')
|
|
548
|
+
.step('fetch', agent('general', 'List all TypeScript files in src/'))
|
|
549
|
+
.step('analyze', agent('security-reviewer', 'Review the files for security issues'))
|
|
550
|
+
.step('report', agent('general', 'Summarize the findings into a report'));
|
|
551
|
+
|
|
552
|
+
const result = await engine.runWorkflow(reviewPipeline);
|
|
553
|
+
console.log(result.steps.report.output);
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
### Context passing between steps
|
|
557
|
+
|
|
558
|
+
Steps reference previous outputs with `{{stepName.output}}`:
|
|
559
|
+
|
|
560
|
+
```typescript
|
|
561
|
+
const dataPipeline = workflow('etl')
|
|
562
|
+
.step('ingest', agent('data-agent', 'Read /data/sales.csv'))
|
|
563
|
+
.step('transform', agent('data-agent', 'Clean {{ingest.output}}: fix nulls, normalize dates'))
|
|
564
|
+
.step('analyze', agent('analyst', 'Find the top 5 trends in: {{transform.output}}'));
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
### Parallel steps
|
|
568
|
+
|
|
569
|
+
```typescript
|
|
570
|
+
const auditWorkflow = workflow('full-audit')
|
|
571
|
+
.parallel([
|
|
572
|
+
agent('frontend-agent', 'Audit React components for accessibility'),
|
|
573
|
+
agent('backend-agent', 'Audit API endpoints for security'),
|
|
574
|
+
agent('database-agent', 'Audit database schema for missing indexes'),
|
|
575
|
+
])
|
|
576
|
+
.step('merge', agent('general', 'Synthesize all three audit reports'));
|
|
577
|
+
```
|
|
578
|
+
|
|
579
|
+
### Conditional steps
|
|
580
|
+
|
|
581
|
+
```typescript
|
|
582
|
+
const smartReview = workflow('smart-review')
|
|
583
|
+
.step('classify', agent('general', 'Classify this PR: feature, bug fix, or refactor. Reply with just the type.'))
|
|
584
|
+
.when('{{classify.output}} includes "bug"',
|
|
585
|
+
agent('qa-engineer', 'Focus on regression risk and edge cases')
|
|
586
|
+
)
|
|
587
|
+
.otherwise(
|
|
588
|
+
agent('general', 'Perform a standard code quality review')
|
|
589
|
+
);
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
### WorkflowRunner (direct usage)
|
|
593
|
+
|
|
594
|
+
```typescript
|
|
595
|
+
import { WorkflowRunner } from '@backendkit-labs/agent-core';
|
|
596
|
+
|
|
597
|
+
const runner = new WorkflowRunner(engine);
|
|
598
|
+
const result = await runner.run(myWorkflow, {
|
|
599
|
+
initialContext: { projectName: 'my-app', version: '2.0' },
|
|
600
|
+
onStepStart: (name) => console.log(`▶ ${name}`),
|
|
601
|
+
onStepDone: (name, out) => console.log(`✓ ${name}: ${out.slice(0, 80)}`),
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
// result.steps — Map<stepName, { output, durationMs }>
|
|
605
|
+
// result.total — total wall time in ms
|
|
606
|
+
// result.failed — boolean
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
---
|
|
610
|
+
|
|
611
|
+
## Advanced memory system
|
|
612
|
+
|
|
613
|
+
Beyond session history, agents can use a three-layer persistent memory. Each layer is independently configurable and backed by a pluggable store.
|
|
614
|
+
|
|
615
|
+
| Layer | Purpose | Use case |
|
|
616
|
+
|-------|---------|---------|
|
|
617
|
+
| `EpisodicMemory` | What happened — events and interactions | "Last week we refactored auth" |
|
|
618
|
+
| `SemanticMemory` | What is known — facts and domain knowledge | "Alice owns the auth module" |
|
|
619
|
+
| `ProceduralMemory` | How to do it — step-by-step patterns | "Deploy: build → push → apply" |
|
|
620
|
+
|
|
621
|
+
### Creating a full memory system
|
|
622
|
+
|
|
623
|
+
```typescript
|
|
624
|
+
import { createMemorySystem } from '@backendkit-labs/agent-core';
|
|
625
|
+
|
|
626
|
+
const memory = createMemorySystem({
|
|
627
|
+
episodic: {
|
|
628
|
+
provider: 'json',
|
|
629
|
+
path: '~/.bk-agent/projects/my-project/memory/episodes.json',
|
|
630
|
+
},
|
|
631
|
+
semantic: {
|
|
632
|
+
provider: 'json',
|
|
633
|
+
path: '~/.bk-agent/projects/my-project/memory/knowledge.json',
|
|
108
634
|
},
|
|
635
|
+
procedural: {
|
|
636
|
+
provider: 'json',
|
|
637
|
+
path: '~/.bk-agent/projects/my-project/memory/patterns.json',
|
|
638
|
+
},
|
|
639
|
+
retention: {
|
|
640
|
+
maxEpisodes: 500,
|
|
641
|
+
summarizeAfter: 50,
|
|
642
|
+
// Optional: compress old episodes with an LLM summary
|
|
643
|
+
summarizeFn: async (episodes) => {
|
|
644
|
+
const list = episodes.map((e, i) => `${i + 1}. ${e.content}`).join('\n');
|
|
645
|
+
return await llm.summarize(list);
|
|
646
|
+
},
|
|
647
|
+
},
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
// Pass to engine
|
|
651
|
+
const engine = new AgentEngine({ ...opts, memorySystem: memory });
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
### Using each layer directly
|
|
655
|
+
|
|
656
|
+
```typescript
|
|
657
|
+
const { episodic, semantic, procedural } = memory;
|
|
658
|
+
|
|
659
|
+
// --- Episodic ---
|
|
660
|
+
await episodic.add({
|
|
661
|
+
content: 'User asked to refactor the auth module',
|
|
662
|
+
tags: ['refactor', 'auth'],
|
|
663
|
+
timestamp: Date.now(),
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
const recentAuth = await episodic.search('auth', { limit: 5 });
|
|
667
|
+
// [{ id, content, tags, timestamp }, ...]
|
|
668
|
+
|
|
669
|
+
// --- Semantic ---
|
|
670
|
+
await semantic.add({
|
|
671
|
+
key: 'auth-module-owner',
|
|
672
|
+
value: 'Alice (Backend Team)',
|
|
673
|
+
tags: ['ownership', 'auth'],
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
const owner = await semantic.get('auth-module-owner');
|
|
677
|
+
// 'Alice (Backend Team)'
|
|
678
|
+
|
|
679
|
+
const authKnowledge = await semantic.search('auth', { limit: 10 });
|
|
680
|
+
|
|
681
|
+
// --- Procedural ---
|
|
682
|
+
await procedural.add({
|
|
683
|
+
name: 'deploy-to-staging',
|
|
684
|
+
steps: ['npm run build', 'docker build .', 'kubectl apply -f k8s/staging/'],
|
|
685
|
+
tags: ['deployment'],
|
|
109
686
|
});
|
|
687
|
+
|
|
688
|
+
const deploySteps = await procedural.get('deploy-to-staging');
|
|
689
|
+
```
|
|
690
|
+
|
|
691
|
+
### In-memory store (testing)
|
|
692
|
+
|
|
693
|
+
```typescript
|
|
694
|
+
import { InMemoryStore, EpisodicMemory } from '@backendkit-labs/agent-core';
|
|
695
|
+
|
|
696
|
+
const episodic = new EpisodicMemory(new InMemoryStore());
|
|
697
|
+
await episodic.add({ content: 'test event', tags: [], timestamp: Date.now() });
|
|
698
|
+
```
|
|
699
|
+
|
|
700
|
+
### JSON file store (production)
|
|
701
|
+
|
|
702
|
+
```typescript
|
|
703
|
+
import { JsonFileStore, SemanticMemory } from '@backendkit-labs/agent-core';
|
|
704
|
+
|
|
705
|
+
const semantic = new SemanticMemory(new JsonFileStore('/app/data/knowledge.json'));
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
### Memory tools (agents writing their own memory)
|
|
709
|
+
|
|
710
|
+
`buildMemoryTools()` creates tool definitions that let agents read and write all three memory layers:
|
|
711
|
+
|
|
712
|
+
```typescript
|
|
713
|
+
import { buildMemoryTools } from '@backendkit-labs/agent-core';
|
|
714
|
+
|
|
715
|
+
const memTools = buildMemoryTools(memory);
|
|
716
|
+
// Returns: remember_episode, recall_episodes, store_knowledge, recall_knowledge,
|
|
717
|
+
// store_pattern, recall_pattern
|
|
718
|
+
|
|
719
|
+
memTools.forEach(t => tools.register(t));
|
|
110
720
|
```
|
|
111
721
|
|
|
112
|
-
|
|
722
|
+
---
|
|
723
|
+
|
|
724
|
+
## Observability
|
|
725
|
+
|
|
726
|
+
`ObservabilityManager` ties together cost tracking, metrics collection, and distributed tracing.
|
|
727
|
+
|
|
728
|
+
### Enable observability on the engine
|
|
729
|
+
|
|
730
|
+
```typescript
|
|
731
|
+
import { ObservabilityManager } from '@backendkit-labs/agent-core';
|
|
732
|
+
|
|
733
|
+
const obs = new ObservabilityManager({
|
|
734
|
+
costTracking: true,
|
|
735
|
+
metricsEnabled: true,
|
|
736
|
+
tracing: true,
|
|
737
|
+
});
|
|
738
|
+
|
|
739
|
+
const engine = new AgentEngine({ ...opts, observability: obs });
|
|
740
|
+
```
|
|
741
|
+
|
|
742
|
+
### Cost tracking
|
|
743
|
+
|
|
744
|
+
```typescript
|
|
745
|
+
import { CostTracker, MODEL_PRICING } from '@backendkit-labs/agent-core';
|
|
746
|
+
|
|
747
|
+
const tracker = new CostTracker();
|
|
748
|
+
|
|
749
|
+
// MODEL_PRICING[model] = { input: $/1M tokens, output: $/1M tokens }
|
|
750
|
+
console.log(MODEL_PRICING['gpt-4o']); // { input: 2.50, output: 10.00 }
|
|
751
|
+
console.log(MODEL_PRICING['claude-sonnet-4-6']); // { input: 3.00, output: 15.00 }
|
|
752
|
+
|
|
753
|
+
tracker.record({ model: 'gpt-4o', inputTokens: 1500, outputTokens: 200 });
|
|
754
|
+
|
|
755
|
+
console.log(`Cost: $${tracker.getTotalCostUSD().toFixed(6)}`); // $0.005750
|
|
756
|
+
```
|
|
757
|
+
|
|
758
|
+
### Metrics snapshot
|
|
759
|
+
|
|
760
|
+
```typescript
|
|
761
|
+
import { MetricsCollector } from '@backendkit-labs/agent-core';
|
|
762
|
+
|
|
763
|
+
const metrics = new MetricsCollector();
|
|
764
|
+
|
|
765
|
+
// After some runs:
|
|
766
|
+
const snap = metrics.getSnapshot();
|
|
767
|
+
// {
|
|
768
|
+
// sessionsActive: 3,
|
|
769
|
+
// runsTotal: 47,
|
|
770
|
+
// runsSucceeded: 44,
|
|
771
|
+
// runsFailed: 3,
|
|
772
|
+
// avgDurationMs: 1823,
|
|
773
|
+
// }
|
|
774
|
+
```
|
|
775
|
+
|
|
776
|
+
### Custom span exporter
|
|
777
|
+
|
|
778
|
+
Export traces to Jaeger, Honeycomb, Datadog, or any OpenTelemetry backend:
|
|
779
|
+
|
|
780
|
+
```typescript
|
|
781
|
+
import { Tracer } from '@backendkit-labs/agent-core';
|
|
782
|
+
|
|
783
|
+
const tracer = new Tracer({
|
|
784
|
+
onSpan: (span) => {
|
|
785
|
+
honeycomb.sendEvent({
|
|
786
|
+
'span.name': span.name,
|
|
787
|
+
'duration_ms': span.durationMs,
|
|
788
|
+
'agent.id': span.agentId,
|
|
789
|
+
'tool.calls': span.toolCallCount,
|
|
790
|
+
});
|
|
791
|
+
},
|
|
792
|
+
});
|
|
793
|
+
```
|
|
113
794
|
|
|
114
|
-
|
|
115
|
-
|
|
795
|
+
### Audit log (NDJSON)
|
|
796
|
+
|
|
797
|
+
Every tool call can be logged to a newline-delimited JSON file:
|
|
798
|
+
|
|
799
|
+
```typescript
|
|
800
|
+
const engine = new AgentEngine({
|
|
801
|
+
...opts,
|
|
802
|
+
auditLog: '/var/log/agent-audit.ndjson',
|
|
803
|
+
// Each line: { ts, agentId, toolName, args, result, durationMs }
|
|
804
|
+
});
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
---
|
|
808
|
+
|
|
809
|
+
## Skills and slash commands
|
|
810
|
+
|
|
811
|
+
Skills are reusable prompt snippets that augment agent behavior. Slash commands let users invoke agent features directly.
|
|
812
|
+
|
|
813
|
+
### Loading built-in skills
|
|
814
|
+
|
|
815
|
+
```typescript
|
|
816
|
+
import { SkillLoader, createSkillManager } from '@backendkit-labs/agent-core';
|
|
116
817
|
|
|
117
818
|
const manager = createSkillManager('my-app');
|
|
118
|
-
|
|
819
|
+
|
|
820
|
+
// Install a skill pack from GitHub
|
|
821
|
+
await manager.install({
|
|
822
|
+
source: 'github:backendkit-labs/skills#main',
|
|
823
|
+
pack: 'backend',
|
|
824
|
+
});
|
|
825
|
+
|
|
826
|
+
const installed = manager.listInstalled();
|
|
827
|
+
// [{ id, name, pack, version }, ...]
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
### Inline skill definition
|
|
831
|
+
|
|
832
|
+
```typescript
|
|
833
|
+
import { SkillRegistry, SkillActivator } from '@backendkit-labs/agent-core';
|
|
834
|
+
|
|
835
|
+
const registry = new SkillRegistry();
|
|
836
|
+
|
|
837
|
+
registry.register({
|
|
838
|
+
id: 'pr-review',
|
|
839
|
+
name: 'PR Review',
|
|
840
|
+
description: 'Perform a thorough pull request review',
|
|
841
|
+
prompt: `
|
|
842
|
+
Review this pull request with the following criteria:
|
|
843
|
+
1. Correctness — does the code do what the PR description claims?
|
|
844
|
+
2. Security — any new attack surface?
|
|
845
|
+
3. Performance — any obvious regressions?
|
|
846
|
+
4. Tests — are changes covered?
|
|
847
|
+
Output a concise review with LGTM or CHANGES REQUESTED at the end.
|
|
848
|
+
`,
|
|
849
|
+
tags: ['github', 'review'],
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
const activator = new SkillActivator(registry);
|
|
853
|
+
const systemContext = activator.buildContext(['pr-review']);
|
|
854
|
+
// Returns the skill prompt injected into the system context
|
|
119
855
|
```
|
|
120
856
|
|
|
121
857
|
### Slash commands
|
|
122
858
|
|
|
123
|
-
|
|
859
|
+
Built-in commands: `/help`, `/clear`, `/status`, `/skills`, `/agents`, `/workspace`, `/checkpoint`.
|
|
860
|
+
|
|
861
|
+
```typescript
|
|
124
862
|
import { SlashCommandRegistry, registerBuiltinCommands } from '@backendkit-labs/agent-core';
|
|
125
863
|
|
|
126
|
-
const
|
|
127
|
-
registerBuiltinCommands(
|
|
864
|
+
const cmds = new SlashCommandRegistry();
|
|
865
|
+
registerBuiltinCommands(cmds);
|
|
128
866
|
|
|
129
|
-
|
|
130
|
-
|
|
867
|
+
// Custom command
|
|
868
|
+
cmds.register({
|
|
869
|
+
name: 'deploy',
|
|
870
|
+
description: 'Trigger a deployment to an environment',
|
|
871
|
+
handler: async (ctx) => {
|
|
872
|
+
const env = ctx.args[0] ?? 'staging';
|
|
873
|
+
await ci.triggerDeploy(env);
|
|
874
|
+
return `Deployment to ${env} triggered. Watch: https://ci.company.com/jobs/latest`;
|
|
875
|
+
},
|
|
131
876
|
});
|
|
877
|
+
|
|
878
|
+
// Handle user input
|
|
879
|
+
const input = '/deploy production';
|
|
880
|
+
if (input.startsWith('/')) {
|
|
881
|
+
const response = await cmds.handle(input, agentContext);
|
|
882
|
+
console.log(response);
|
|
883
|
+
}
|
|
132
884
|
```
|
|
133
885
|
|
|
134
|
-
|
|
886
|
+
---
|
|
135
887
|
|
|
136
|
-
|
|
137
|
-
|---------|-------------|
|
|
138
|
-
| `/help` | List available commands |
|
|
139
|
-
| `/agents` | List agents or switch active agent |
|
|
140
|
-
| `/skills` | Manage skill packs — install, create, generate, update, uninstall |
|
|
141
|
-
| `/workspace` | Manage multi-project workspaces — create, add, switch, remove |
|
|
142
|
-
| `/plugin` | Manage MCP agent plugins — list, add, remove |
|
|
143
|
-
| `/status` | Show current agent and model |
|
|
144
|
-
| `/iteration` | Change iteration mode (interactive / auto / step-by-step) |
|
|
145
|
-
| `/checkpoint` | Create, list, or load session checkpoints |
|
|
888
|
+
## Checkpoints
|
|
146
889
|
|
|
147
|
-
|
|
890
|
+
Save and restore session state for recovery and branching.
|
|
148
891
|
|
|
149
|
-
|
|
892
|
+
### Save a checkpoint
|
|
150
893
|
|
|
151
|
-
|
|
894
|
+
```typescript
|
|
895
|
+
import { createCheckpoint, listCheckpoints, readCheckpoint } from '@backendkit-labs/agent-core';
|
|
152
896
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
/
|
|
158
|
-
|
|
897
|
+
// After a successful milestone
|
|
898
|
+
await createCheckpoint({
|
|
899
|
+
sessionId: 'session-abc',
|
|
900
|
+
messages: engine.getMessages(),
|
|
901
|
+
projectDir: '/app/.bk-agent/projects/my-project',
|
|
902
|
+
description: 'After auth module refactor — all tests pass',
|
|
903
|
+
});
|
|
159
904
|
```
|
|
160
905
|
|
|
161
|
-
|
|
906
|
+
### List and restore
|
|
162
907
|
|
|
163
|
-
```
|
|
164
|
-
//
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
}
|
|
177
|
-
]
|
|
178
|
-
}
|
|
908
|
+
```typescript
|
|
909
|
+
// List all checkpoints
|
|
910
|
+
const summaries = await listCheckpoints('/app/.bk-agent/projects/my-project');
|
|
911
|
+
// [{ id, timestamp, description, messageCount }, ...]
|
|
912
|
+
|
|
913
|
+
// Restore a specific checkpoint
|
|
914
|
+
const checkpoint = await readCheckpoint(summaries[0].id, '/app/.bk-agent/projects/my-project');
|
|
915
|
+
|
|
916
|
+
const restoredMemory = new SessionMemory();
|
|
917
|
+
restoredMemory.loadMessages(checkpoint.messages);
|
|
918
|
+
|
|
919
|
+
const engine = new AgentEngine({ ...opts, sessionMemory: restoredMemory });
|
|
920
|
+
await engine.run('Continue from where we left off');
|
|
179
921
|
```
|
|
180
922
|
|
|
181
|
-
|
|
923
|
+
### Compact a long session
|
|
924
|
+
|
|
925
|
+
```typescript
|
|
926
|
+
import { compactSession } from '@backendkit-labs/agent-core';
|
|
927
|
+
|
|
928
|
+
// Compress a 200-message conversation to a short summary
|
|
929
|
+
const compacted = await compactSession(
|
|
930
|
+
engine.getMessages(),
|
|
931
|
+
async (messages) => await llm.summarize(messages),
|
|
932
|
+
);
|
|
933
|
+
|
|
934
|
+
// Replace memory with compacted version to reduce context size
|
|
935
|
+
engine.replaceMessages(compacted);
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
---
|
|
939
|
+
|
|
940
|
+
## Workspaces
|
|
941
|
+
|
|
942
|
+
Manage multiple projects and let agents switch context between them.
|
|
943
|
+
|
|
944
|
+
```typescript
|
|
945
|
+
import {
|
|
946
|
+
loadWorkspaces, createWorkspace, addProject,
|
|
947
|
+
setActiveProject, buildWorkspaceContext,
|
|
948
|
+
} from '@backendkit-labs/agent-core';
|
|
949
|
+
|
|
950
|
+
// One-time setup
|
|
951
|
+
const config = await loadWorkspaces('my-app');
|
|
952
|
+
await createWorkspace('my-app', 'work');
|
|
182
953
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
appName: 'my-app', // reads/writes ~/.my-app/config.json
|
|
954
|
+
await addProject('my-app', 'work', {
|
|
955
|
+
name: 'api-server',
|
|
956
|
+
path: '/home/user/projects/api-server',
|
|
187
957
|
});
|
|
958
|
+
|
|
959
|
+
await addProject('my-app', 'work', {
|
|
960
|
+
name: 'frontend',
|
|
961
|
+
path: '/home/user/projects/frontend',
|
|
962
|
+
});
|
|
963
|
+
|
|
964
|
+
// Switch active project
|
|
965
|
+
await setActiveProject('my-app', 'work', 'frontend');
|
|
966
|
+
|
|
967
|
+
// Build context string injected into the engine's system prompt
|
|
968
|
+
const ctx = buildWorkspaceContext(await loadWorkspaces('my-app'));
|
|
969
|
+
// "Active project: frontend (/home/user/projects/frontend)\nWorkspace: work\n..."
|
|
188
970
|
```
|
|
189
971
|
|
|
190
972
|
---
|
|
191
973
|
|
|
192
|
-
##
|
|
974
|
+
## Autonomous agents and triggers
|
|
193
975
|
|
|
194
|
-
|
|
976
|
+
Create fire-and-forget agents that run on schedules or in response to events.
|
|
195
977
|
|
|
196
|
-
###
|
|
978
|
+
### Scheduled agent (cron)
|
|
197
979
|
|
|
198
|
-
|
|
980
|
+
```typescript
|
|
981
|
+
import { createAutonomousAgent } from '@backendkit-labs/agent-core';
|
|
199
982
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
model: 'deepseek-chat', // fallback for agents with no model override
|
|
207
|
-
}),
|
|
208
|
-
},
|
|
209
|
-
defaultProvider: 'default',
|
|
210
|
-
agents: [
|
|
211
|
-
{ id: 'orchestrator', model: 'deepseek-reasoner', ... }, // smart — routing decisions
|
|
212
|
-
{ id: 'coder', model: 'deepseek-chat', ... }, // fast — bulk tool calls
|
|
213
|
-
{ id: 'data-analyst', model: 'deepseek-chat', ... }, // fast — tool calls
|
|
214
|
-
],
|
|
983
|
+
const standupAgent = createAutonomousAgent({
|
|
984
|
+
engine: myEngine,
|
|
985
|
+
schedule: '0 9 * * 1-5', // cron: weekdays at 9 AM
|
|
986
|
+
buildPrompt: () => 'Generate a daily standup summary from recent git commits and open PRs.',
|
|
987
|
+
onResult: (output) => slack.postMessage('#standup', output),
|
|
988
|
+
onError: (err) => logger.error('[standup-agent]', err),
|
|
215
989
|
});
|
|
990
|
+
|
|
991
|
+
await standupAgent.start();
|
|
992
|
+
// Stops the cron job
|
|
993
|
+
await standupAgent.stop();
|
|
216
994
|
```
|
|
217
995
|
|
|
218
|
-
###
|
|
996
|
+
### Event-driven agent
|
|
219
997
|
|
|
220
|
-
|
|
998
|
+
```typescript
|
|
999
|
+
import { EventBus } from '@backendkit-labs/agent-core';
|
|
221
1000
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
1001
|
+
const eventBus = new EventBus();
|
|
1002
|
+
|
|
1003
|
+
// Subscribe to an event
|
|
1004
|
+
eventBus.on('deployment.failed', async (payload) => {
|
|
1005
|
+
const analysis = await engine.run(
|
|
1006
|
+
`Investigate this deployment failure:\n${JSON.stringify(payload, null, 2)}`
|
|
1007
|
+
);
|
|
1008
|
+
await pagerduty.alert({ summary: analysis.final });
|
|
1009
|
+
});
|
|
1010
|
+
|
|
1011
|
+
// Publish from your CI/CD system
|
|
1012
|
+
await eventBus.emit('deployment.failed', {
|
|
1013
|
+
service: 'payment-api',
|
|
1014
|
+
version: '2.1.4',
|
|
1015
|
+
errorLog: lastError,
|
|
235
1016
|
});
|
|
236
1017
|
```
|
|
237
1018
|
|
|
238
|
-
|
|
1019
|
+
### TriggerManager (low-level)
|
|
1020
|
+
|
|
1021
|
+
```typescript
|
|
1022
|
+
import { TriggerManager } from '@backendkit-labs/agent-core';
|
|
1023
|
+
|
|
1024
|
+
const triggers = new TriggerManager();
|
|
1025
|
+
|
|
1026
|
+
// Cron trigger
|
|
1027
|
+
triggers.addSchedule({
|
|
1028
|
+
id: 'daily-report',
|
|
1029
|
+
schedule: '0 8 * * *',
|
|
1030
|
+
handler: async () => engine.run('Generate daily report'),
|
|
1031
|
+
});
|
|
1032
|
+
|
|
1033
|
+
// Webhook trigger
|
|
1034
|
+
triggers.addWebhook({
|
|
1035
|
+
id: 'github-pr',
|
|
1036
|
+
path: '/webhooks/github',
|
|
1037
|
+
handler: async (body) => engine.run(`Review PR: ${body.pull_request.title}`),
|
|
1038
|
+
});
|
|
239
1039
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
| `provider` | Which LLM backend (`ProviderRegistry`) | `defaultProvider` |
|
|
243
|
-
| `model` | Which model within that backend | Provider's configured default |
|
|
1040
|
+
await triggers.start();
|
|
1041
|
+
```
|
|
244
1042
|
|
|
245
1043
|
---
|
|
246
1044
|
|
|
247
|
-
##
|
|
1045
|
+
## Delegation bus
|
|
1046
|
+
|
|
1047
|
+
`DelegationBus` enables multi-agent collaboration — orchestrators delegate sub-tasks to specialized agents and collect results.
|
|
1048
|
+
|
|
1049
|
+
```typescript
|
|
1050
|
+
import { DelegationBus } from '@backendkit-labs/agent-core';
|
|
1051
|
+
|
|
1052
|
+
const bus = new DelegationBus();
|
|
248
1053
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
1054
|
+
// Register specialized agents
|
|
1055
|
+
bus.register('security-agent', async (req) => ({
|
|
1056
|
+
output: (await securityEngine.run(req.prompt)).final,
|
|
1057
|
+
agentId: 'security-agent',
|
|
1058
|
+
}));
|
|
1059
|
+
|
|
1060
|
+
bus.register('data-agent', async (req) => ({
|
|
1061
|
+
output: (await dataEngine.run(req.prompt)).final,
|
|
1062
|
+
agentId: 'data-agent',
|
|
1063
|
+
}));
|
|
1064
|
+
|
|
1065
|
+
// Delegate from orchestrator
|
|
1066
|
+
const secResult = await bus.delegate({
|
|
1067
|
+
targetAgentId: 'security-agent',
|
|
1068
|
+
prompt: 'Audit this SQL query for injection risks: SELECT * FROM users WHERE id=' + input,
|
|
1069
|
+
context: currentMessages,
|
|
1070
|
+
});
|
|
1071
|
+
|
|
1072
|
+
console.log(secResult.output);
|
|
257
1073
|
```
|
|
258
1074
|
|
|
259
1075
|
---
|
|
260
1076
|
|
|
261
|
-
##
|
|
1077
|
+
## Type reference
|
|
1078
|
+
|
|
1079
|
+
Key types exported from `@backendkit-labs/agent-core`:
|
|
262
1080
|
|
|
263
|
-
|
|
1081
|
+
```typescript
|
|
1082
|
+
// Engine
|
|
1083
|
+
AgentEngineOptions // Full constructor options
|
|
1084
|
+
BaseEngineOptions // Options for createBaseEngine
|
|
1085
|
+
|
|
1086
|
+
// Agents
|
|
1087
|
+
AgentProfile // { id, name, systemPrompt, tools, provider? }
|
|
1088
|
+
|
|
1089
|
+
// Tools
|
|
1090
|
+
ToolDefinition // { name, description, inputSchema, execute }
|
|
1091
|
+
TypedToolOptions // Options for defineTool
|
|
1092
|
+
ExecutionContext // Runtime context passed to tool.execute
|
|
1093
|
+
|
|
1094
|
+
// LLM
|
|
1095
|
+
LLMProvider // Interface for LLM adapters
|
|
1096
|
+
LLMMessage // { role, content }
|
|
1097
|
+
LLMToolCall // { id, name, arguments }
|
|
1098
|
+
LLMStreamCallbacks // { onChunk, onToolCall, onDone, onError }
|
|
1099
|
+
ModelConfig // { provider, id }
|
|
1100
|
+
|
|
1101
|
+
// Memory
|
|
1102
|
+
SessionMemoryData // Serialized session memory
|
|
1103
|
+
MemorySystemConfig // createMemorySystem options
|
|
1104
|
+
MemoryStoreBackend // 'json' | 'memory'
|
|
1105
|
+
Episode // Episodic memory entry
|
|
1106
|
+
Knowledge // Semantic memory entry
|
|
1107
|
+
Pattern // Procedural memory entry
|
|
1108
|
+
|
|
1109
|
+
// MCP
|
|
1110
|
+
MCPServerConfig // { name, command, args, env?, baseUrl?, url? }
|
|
1111
|
+
|
|
1112
|
+
// Workflows
|
|
1113
|
+
WorkflowDef // Compiled workflow definition
|
|
1114
|
+
WorkflowResult // { steps, total, failed }
|
|
1115
|
+
WorkflowRunOptions // WorkflowRunner.run() options
|
|
1116
|
+
|
|
1117
|
+
// Iteration
|
|
1118
|
+
IterationMode // 'auto' | 'manual' | 'step-by-step' | 'interactive'
|
|
1119
|
+
IterationStats // { count, max, agentId }
|
|
1120
|
+
ToolApprovalDecision // 'approve' | 'approve_all' | 'reject'
|
|
1121
|
+
|
|
1122
|
+
// Observability
|
|
1123
|
+
ObservabilityConfig // { costTracking, metricsEnabled, tracing }
|
|
1124
|
+
MetricsSnapshot // Current counters snapshot
|
|
1125
|
+
Span // Tracing span
|
|
1126
|
+
SpanExporter // Interface for custom exporters
|
|
1127
|
+
|
|
1128
|
+
// Events
|
|
1129
|
+
AgentEvent // Union of all transport event types
|
|
1130
|
+
```
|