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