@backendkit-labs/agent-core 0.41.0 → 0.42.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.
Files changed (52) hide show
  1. package/README.md +26 -0
  2. package/dist/engine/AgentEngine.d.ts +22 -2
  3. package/dist/engine/AgentEngine.d.ts.map +1 -1
  4. package/dist/engine/AgentEngine.js +92 -48
  5. package/dist/engine/AgentEngine.js.map +1 -1
  6. package/dist/engine/createBaseEngine.d.ts +2 -0
  7. package/dist/engine/createBaseEngine.d.ts.map +1 -1
  8. package/dist/engine/createBaseEngine.js +21 -4
  9. package/dist/engine/createBaseEngine.js.map +1 -1
  10. package/dist/engine/error-code.d.ts +7 -0
  11. package/dist/engine/error-code.d.ts.map +1 -0
  12. package/dist/engine/error-code.js +23 -0
  13. package/dist/engine/error-code.js.map +1 -0
  14. package/dist/engine/run-recorder.d.ts +13 -0
  15. package/dist/engine/run-recorder.d.ts.map +1 -0
  16. package/dist/engine/run-recorder.js +49 -0
  17. package/dist/engine/run-recorder.js.map +1 -0
  18. package/dist/governance/types.d.ts +6 -0
  19. package/dist/governance/types.d.ts.map +1 -1
  20. package/dist/index.d.ts +5 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +9 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/learning/index.d.ts +2 -1
  25. package/dist/learning/index.d.ts.map +1 -1
  26. package/dist/learning/index.js +270 -56
  27. package/dist/learning/index.js.map +1 -1
  28. package/dist/learning/signal.d.ts +51 -0
  29. package/dist/learning/signal.d.ts.map +1 -0
  30. package/dist/learning/signal.js +136 -0
  31. package/dist/learning/signal.js.map +1 -0
  32. package/dist/learning/types.d.ts +143 -1
  33. package/dist/learning/types.d.ts.map +1 -1
  34. package/dist/learning/units.d.ts +46 -0
  35. package/dist/learning/units.d.ts.map +1 -0
  36. package/dist/learning/units.js +137 -0
  37. package/dist/learning/units.js.map +1 -0
  38. package/dist/tools/defineTool.d.ts +4 -1
  39. package/dist/tools/defineTool.d.ts.map +1 -1
  40. package/dist/tools/defineTool.js +5 -2
  41. package/dist/tools/defineTool.js.map +1 -1
  42. package/dist/tools/services.d.ts +13 -0
  43. package/dist/tools/services.d.ts.map +1 -1
  44. package/dist/tools/services.js +12 -0
  45. package/dist/tools/services.js.map +1 -1
  46. package/dist/tools/tool-error.d.ts +19 -0
  47. package/dist/tools/tool-error.d.ts.map +1 -0
  48. package/dist/tools/tool-error.js +33 -0
  49. package/dist/tools/tool-error.js.map +1 -0
  50. package/dist/types/index.d.ts +39 -0
  51. package/dist/types/index.d.ts.map +1 -1
  52. package/package.json +89 -89
@@ -0,0 +1,51 @@
1
+ import type { MemoryStoreBackend } from '../agent-memory/types';
2
+ /** Failures that make a pattern only count if they are a big enough share of the calls (SPEC-0019 D2). */
3
+ export interface RateOptions {
4
+ /** Share of the calls of a subject that failed with this pattern. Default 0.05. */
5
+ minFailureRate: number;
6
+ /** Below this many calls in the window the share means nothing, and only the count decides. Default 20. */
7
+ minCalls: number;
8
+ }
9
+ export declare const DEFAULT_RATE: RateOptions;
10
+ /**
11
+ * The successes, counted instead of stored (SPEC-0019 D1). A healthy agent makes thousands of correct calls, and one
12
+ * experience each would push the failures out of the bounded store. A bucket is one day of one agent and subject, kept
13
+ * in memory and written to its store at most every few seconds.
14
+ */
15
+ export declare class SuccessCounters {
16
+ private readonly store;
17
+ private readonly buckets;
18
+ private loaded;
19
+ private dirty;
20
+ private timer?;
21
+ constructor(store: MemoryStoreBackend);
22
+ /** One more correct call. */
23
+ add(at: string, agentId: string, tenantId: string | undefined, domain: string, subject: string, context?: string): void;
24
+ /** Correct calls of a subject (and context: those counted without one are another bucket) since `sinceDay`, of one agent or of all. */
25
+ since(sinceDay: string, tenantId: string | undefined, domain: string, subject: string, agentId?: string, context?: string): number;
26
+ /** Writes what changed and drops the days before `keepFromDay`. */
27
+ flush(keepFromDay?: string): Promise<void>;
28
+ private load;
29
+ }
30
+ /**
31
+ * The patterns that already passed the rate (SPEC-0019, found by the trading bench). The rate decides when a pattern
32
+ * ENTERS: once it is in, it stays while its failures stay in the window, however many correct calls pile up. Otherwise a
33
+ * lesson that works would remove itself: the bot obeys it, its correct calls dilute the failure share, the lesson leaves
34
+ * and the mistake comes back. A record is the key and the last day the pattern was seen; it expires after the window.
35
+ */
36
+ export declare class QualifiedPatterns {
37
+ private readonly store;
38
+ private readonly days;
39
+ private loaded;
40
+ constructor(store: MemoryStoreBackend);
41
+ /** Did the pattern pass the rate, and was it seen since `sinceDay`? */
42
+ has(key: string, sinceDay: string): boolean;
43
+ /** The pattern is in (it passed the rate, or it stayed): remember the day. */
44
+ confirm(key: string, day: string): void;
45
+ /** The pattern has fewer failures than it needs: it leaves, and has to pass the rate again to come back. */
46
+ drop(key: string): void;
47
+ /** Forgets what was not seen since `keepFromDay`. */
48
+ prune(keepFromDay: string): void;
49
+ private load;
50
+ }
51
+ //# sourceMappingURL=signal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal.d.ts","sourceRoot":"","sources":["../../src/learning/signal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAEhE,0GAA0G;AAC1G,MAAM,WAAW,WAAW;IACxB,mFAAmF;IACnF,cAAc,EAAE,MAAM,CAAC;IACvB,2GAA2G;IAC3G,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,YAAY,EAAE,WAAoD,CAAC;AAiBhF;;;;GAIG;AACH,qBAAa,eAAe;IAMZ,OAAO,CAAC,QAAQ,CAAC,KAAK;IALlC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IACrD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,KAAK,CAAC,CAAgC;gBAEjB,KAAK,EAAE,kBAAkB;IAEtD,6BAA6B;IAC7B,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAcvH,uIAAuI;IACvI,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM;IAWlI,mEAAmE;IAC7D,KAAK,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAahD,OAAO,CAAC,IAAI;CASf;AAED;;;;;GAKG;AACH,qBAAa,iBAAiB;IAId,OAAO,CAAC,QAAQ,CAAC,KAAK;IAHlC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,OAAO,CAAC,MAAM,CAAS;gBAEM,KAAK,EAAE,kBAAkB;IAEtD,uEAAuE;IACvE,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO;IAM3C,8EAA8E;IAC9E,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI;IAOvC,4GAA4G;IAC5G,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAMvB,qDAAqD;IACrD,KAAK,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI;IAKhC,OAAO,CAAC,IAAI;CAOf"}
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QualifiedPatterns = exports.SuccessCounters = exports.DEFAULT_RATE = void 0;
4
+ exports.DEFAULT_RATE = { minFailureRate: 0.05, minCalls: 20 };
5
+ const FLUSH_MS = 5000;
6
+ /**
7
+ * The successes, counted instead of stored (SPEC-0019 D1). A healthy agent makes thousands of correct calls, and one
8
+ * experience each would push the failures out of the bounded store. A bucket is one day of one agent and subject, kept
9
+ * in memory and written to its store at most every few seconds.
10
+ */
11
+ class SuccessCounters {
12
+ store;
13
+ buckets = new Map();
14
+ loaded = false;
15
+ dirty = false;
16
+ timer;
17
+ constructor(store) {
18
+ this.store = store;
19
+ }
20
+ /** One more correct call. */
21
+ add(at, agentId, tenantId, domain, subject, context) {
22
+ this.load();
23
+ const day = at.slice(0, 10);
24
+ const id = [day, tenantId ?? '', agentId, domain, subject, ...(context ? [context] : [])].join('\u0000');
25
+ const bucket = this.buckets.get(id);
26
+ if (bucket)
27
+ bucket.n++;
28
+ else
29
+ this.buckets.set(id, { id, day, ...(tenantId ? { tenantId } : {}), agentId, domain, subject, ...(context ? { context } : {}), n: 1 });
30
+ this.dirty = true;
31
+ if (!this.timer) {
32
+ this.timer = setTimeout(() => { this.timer = undefined; void this.flush(); }, FLUSH_MS);
33
+ this.timer.unref?.();
34
+ }
35
+ }
36
+ /** Correct calls of a subject (and context: those counted without one are another bucket) since `sinceDay`, of one agent or of all. */
37
+ since(sinceDay, tenantId, domain, subject, agentId, context) {
38
+ this.load();
39
+ let total = 0;
40
+ for (const b of this.buckets.values()) {
41
+ if (b.day >= sinceDay && b.tenantId === tenantId && b.domain === domain && b.subject === subject && b.context === context && (!agentId || b.agentId === agentId)) {
42
+ total += b.n;
43
+ }
44
+ }
45
+ return total;
46
+ }
47
+ /** Writes what changed and drops the days before `keepFromDay`. */
48
+ async flush(keepFromDay) {
49
+ if (this.timer) {
50
+ clearTimeout(this.timer);
51
+ this.timer = undefined;
52
+ }
53
+ this.load();
54
+ const stale = keepFromDay ? [...this.buckets.values()].filter(b => b.day < keepFromDay) : [];
55
+ for (const b of stale)
56
+ this.buckets.delete(b.id);
57
+ if (stale.length) {
58
+ this.store.deleteByIds(stale.map(b => b.id));
59
+ this.dirty = true;
60
+ }
61
+ if (!this.dirty)
62
+ return;
63
+ this.dirty = false;
64
+ const records = [...this.buckets.values()].map(b => ({ ...b, createdAt: `${b.day}T00:00:00.000Z`, kind: 'ok-bucket' }));
65
+ if (this.store.upsertMany)
66
+ this.store.upsertMany(records);
67
+ else
68
+ for (const r of records)
69
+ this.store.upsert(r.id, r);
70
+ }
71
+ load() {
72
+ if (this.loaded)
73
+ return;
74
+ this.loaded = true;
75
+ for (const r of this.store.getAll()) {
76
+ if (r.kind !== 'ok-bucket')
77
+ continue;
78
+ const { createdAt: _createdAt, kind: _kind, ...bucket } = r;
79
+ this.buckets.set(bucket.id, bucket);
80
+ }
81
+ }
82
+ }
83
+ exports.SuccessCounters = SuccessCounters;
84
+ /**
85
+ * The patterns that already passed the rate (SPEC-0019, found by the trading bench). The rate decides when a pattern
86
+ * ENTERS: once it is in, it stays while its failures stay in the window, however many correct calls pile up. Otherwise a
87
+ * lesson that works would remove itself: the bot obeys it, its correct calls dilute the failure share, the lesson leaves
88
+ * and the mistake comes back. A record is the key and the last day the pattern was seen; it expires after the window.
89
+ */
90
+ class QualifiedPatterns {
91
+ store;
92
+ days = new Map();
93
+ loaded = false;
94
+ constructor(store) {
95
+ this.store = store;
96
+ }
97
+ /** Did the pattern pass the rate, and was it seen since `sinceDay`? */
98
+ has(key, sinceDay) {
99
+ this.load();
100
+ const day = this.days.get(key);
101
+ return day !== undefined && day >= sinceDay;
102
+ }
103
+ /** The pattern is in (it passed the rate, or it stayed): remember the day. */
104
+ confirm(key, day) {
105
+ this.load();
106
+ if (this.days.get(key) === day)
107
+ return;
108
+ this.days.set(key, day);
109
+ this.store.upsert(`q|${key}`, { id: `q|${key}`, createdAt: `${day}T00:00:00.000Z`, kind: 'qualified', key, day });
110
+ }
111
+ /** The pattern has fewer failures than it needs: it leaves, and has to pass the rate again to come back. */
112
+ drop(key) {
113
+ this.load();
114
+ if (!this.days.delete(key))
115
+ return;
116
+ this.store.deleteByIds([`q|${key}`]);
117
+ }
118
+ /** Forgets what was not seen since `keepFromDay`. */
119
+ prune(keepFromDay) {
120
+ this.load();
121
+ for (const [key, day] of [...this.days])
122
+ if (day < keepFromDay)
123
+ this.drop(key);
124
+ }
125
+ load() {
126
+ if (this.loaded)
127
+ return;
128
+ this.loaded = true;
129
+ for (const r of this.store.getAll()) {
130
+ if (r.kind === 'qualified' && typeof r.key === 'string' && typeof r.day === 'string')
131
+ this.days.set(r.key, r.day);
132
+ }
133
+ }
134
+ }
135
+ exports.QualifiedPatterns = QualifiedPatterns;
136
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal.js","sourceRoot":"","sources":["../../src/learning/signal.ts"],"names":[],"mappings":";;;AAUa,QAAA,YAAY,GAAgB,EAAE,cAAc,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC;AAehF,MAAM,QAAQ,GAAG,IAAI,CAAC;AAEtB;;;;GAIG;AACH,MAAa,eAAe;IAMK;IALZ,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC7C,MAAM,GAAG,KAAK,CAAC;IACf,KAAK,GAAG,KAAK,CAAC;IACd,KAAK,CAAiC;IAE9C,YAA6B,KAAyB;QAAzB,UAAK,GAAL,KAAK,CAAoB;IAAG,CAAC;IAE1D,6BAA6B;IAC7B,GAAG,CAAC,EAAU,EAAE,OAAe,EAAE,QAA4B,EAAE,MAAc,EAAE,OAAe,EAAE,OAAgB;QAC5G,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,MAAM,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC5B,MAAM,EAAE,GAAG,CAAC,GAAG,EAAE,QAAQ,IAAI,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACzG,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE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AC,GAAG,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;QACtH,CAAC;IACL,CAAC;CACJ;AAzCD,8CAyCC"}
@@ -15,8 +15,24 @@ export interface Experience {
15
15
  tenantId?: string;
16
16
  /** Area of the experience: 'tool', 'policy', 'commit'... */
17
17
  domain: string;
18
- /** What it is about: a tool name, a workflow step. Patterns group by domain + kind + subject. */
18
+ /**
19
+ * What it is about: a tool name, a workflow step. Patterns group by domain + kind + subject + fingerprint, and the share of
20
+ * failures (`rate`) is measured against the calls of the SUBJECT. To judge a context on its own, put the context in the
21
+ * subject: `breakout/trend_flat` and `breakout/trend_up` are judged separately, `breakout` judges both together.
22
+ */
19
23
  subject?: string;
24
+ /**
25
+ * The circumstances of the experience, as one label: `trend_flat`, `before_close`. Patterns of the same subject but another
26
+ * context are different patterns, and the share of failures is measured against the calls of the subject IN THAT CONTEXT:
27
+ * `breakout` in `trend_up` and in `trend_flat` are judged apart without making up a subject for each. Without it, nothing
28
+ * changes: the keys, the proposals and the lessons are the ones there always were.
29
+ */
30
+ context?: string;
31
+ /**
32
+ * What tells apart failures of the same kind and subject that have different causes: for a tool, the code or class
33
+ * of its error (`ECONNRESET`, `ERP_PERIOD_CLOSED`). Without it, they are one pattern.
34
+ */
35
+ fingerprint?: string;
20
36
  /** What was being attempted. */
21
37
  situation: string;
22
38
  /** What was done (a tool and a hash of its arguments, a step). */
@@ -40,6 +56,8 @@ export interface LearnedPattern {
40
56
  domain: string;
41
57
  kind: string;
42
58
  subject?: string;
59
+ context?: string;
60
+ fingerprint?: string;
43
61
  count: number;
44
62
  firstSeen: string;
45
63
  lastSeen: string;
@@ -79,6 +97,8 @@ export interface TaughtLesson {
79
97
  tenantId?: string;
80
98
  /** Only an agent that has at least one of these tools in the turn gets it. */
81
99
  tools?: string[];
100
+ /** The unit it belongs to in the prompt: a tool name, or `general`. Default: the first of `tools`, else `general`. */
101
+ unit?: string;
82
102
  /** Who taught it. */
83
103
  by: ApproverRef;
84
104
  /** ISO time. */
@@ -90,6 +110,14 @@ export interface LessonStore {
90
110
  /** Removes a lesson; false when it did not exist. */
91
111
  remove(id: string): Promise<boolean>;
92
112
  }
113
+ /** A unit of lessons: the knowledge of one tool (or of nothing in particular) that the agents carry in their prompt. */
114
+ export interface LessonUnitInfo {
115
+ name: string;
116
+ tenantId?: string;
117
+ taught: number;
118
+ /** Lessons learned from patterns, for the agents of the tenant. */
119
+ learned: number;
120
+ }
93
121
  /** What `teach` takes. */
94
122
  export interface TeachInput {
95
123
  /** What the agent should know, in a sentence or two. Sanitized and capped when it joins the prompt. */
@@ -97,6 +125,44 @@ export interface TeachInput {
97
125
  agentId?: string;
98
126
  tenantId?: string;
99
127
  tools?: string[];
128
+ unit?: string;
129
+ /** Teaching the same `id` again replaces the lesson. Letters, digits, `_` and `-`. */
130
+ id?: string;
131
+ }
132
+ /**
133
+ * What a tool may see of the rules a person approved: a read-only view of one tenant's rules. It has no way to approve, teach
134
+ * or add anything, on purpose: whoever holds the `Learning` object itself could claim to be a person.
135
+ */
136
+ export interface LearnedRulesView {
137
+ /** Every approved rule of the tenant. */
138
+ list(): Promise<ApprovedRule[]>;
139
+ /** The approved rules of the tenant that satisfy `guard`, typed: how a tool picks out the rules of its own kind. */
140
+ where<T>(guard: (rule: unknown) => rule is T): Promise<Array<{
141
+ id: string;
142
+ rule: T;
143
+ approvedAt: string;
144
+ approvedBy: ApproverRef;
145
+ }>>;
146
+ }
147
+ /** What `trackOutcome` takes: something that happened to an agent, good or bad, in a line. */
148
+ export interface OutcomeInput {
149
+ agentId: string;
150
+ tenantId?: string;
151
+ domain: string;
152
+ /** What it is about. Required: it is what a success is counted against. */
153
+ subject: string;
154
+ /** The circumstances (see `Experience.context`): successes and failures are compared within the same one. */
155
+ context?: string;
156
+ ok: boolean;
157
+ /** The kind of failure (ignored when `ok`). Default `failure`. */
158
+ kind?: string;
159
+ severity?: Severity;
160
+ /** The advice, for a failure: it ends up in the lesson. */
161
+ detail?: string;
162
+ situation?: string;
163
+ action?: string;
164
+ meta?: Record<string, unknown>;
165
+ at?: string;
100
166
  }
101
167
  /** What `addRule` takes: a rule a person writes, without waiting for a pattern. */
102
168
  export interface AddRuleInput {
@@ -112,6 +178,12 @@ export interface ToolRule {
112
178
  reason: string;
113
179
  }
114
180
  export interface LearningOptions {
181
+ /**
182
+ * Keep everything under this directory, with the file names `agent-coding` has always used: `experiences.json`, `counters.json`,
183
+ * `proposals/`, `rules.json` and `lessons.json`. A store passed explicitly replaces its file. Without `dir` (and without the
184
+ * stores) nothing touches the disk.
185
+ */
186
+ dir?: string;
115
187
  /** Where the experiences are kept. Default: in memory, so an engine without configuration touches no file. */
116
188
  store?: MemoryStoreBackend;
117
189
  /** Where the proposed rules wait for a decision. Default: in memory. */
@@ -120,6 +192,35 @@ export interface LearningOptions {
120
192
  rules?: RuleStore;
121
193
  /** Repetitions that make a pattern: it becomes a lesson and a proposed rule. Default 3. */
122
194
  threshold?: number;
195
+ /**
196
+ * How far back a failure counts, in days. An older one is ignored by patterns, lessons and proposals (it stays in the
197
+ * store until the cap drops it). Default 30.
198
+ */
199
+ window?: {
200
+ days: number;
201
+ };
202
+ /**
203
+ * A pattern of a tool that has many correct calls also needs to be a big enough share of its calls: three failures among
204
+ * a thousand calls is noise. Default `{ minFailureRate: 0.05, minCalls: 20 }`; `false` counts failures only. With fewer
205
+ * than `minCalls` calls in the window, or for subjects whose successes are not counted, only the count decides.
206
+ * The share is that of the subject (see `Experience.subject`). It decides when a pattern ENTERS: once in, it stays while its
207
+ * failures stay in the window, so a lesson that works (and fills the subject with correct calls) does not remove itself.
208
+ */
209
+ rate?: {
210
+ minFailureRate: number;
211
+ minCalls: number;
212
+ } | false;
213
+ /** Where the daily counters of correct calls live. Default: in memory. */
214
+ counters?: MemoryStoreBackend;
215
+ /** The clock. Default: the system's. It decides what is inside the window. */
216
+ now?: () => Date;
217
+ /**
218
+ * Whose time an experience carries. `'event'` (default): the one of the audit event (the real clock of the engine) or the
219
+ * real time of the call to `record`. `'clock'`: the one of `now`, for the experiences from the audit sink AND for `record`,
220
+ * and for the day of the counters. It is how a simulation or a backtest runs in simulated time: with `now` driving a
221
+ * simulated clock, the window, the counters and the experiences all agree.
222
+ */
223
+ stamp?: 'event' | 'clock';
123
224
  /**
124
225
  * Repetitions that make a pattern, per kind of experience (it gets the latest of the group). Overrides `threshold`:
125
226
  * for example, a critical failure may need one, and a minor one three.
@@ -127,9 +228,11 @@ export interface LearningOptions {
127
228
  thresholdFor?: (experience: Experience) => number;
128
229
  /** Most experiences kept; the oldest are dropped. Default 1000. */
129
230
  maxExperiences?: number;
231
+ /** `maxChars` of the whole text, `maxLessons` learned lessons in total, `maxPerUnit` learned lessons of one unit (default 3). */
130
232
  lessons?: {
131
233
  maxChars?: number;
132
234
  maxLessons?: number;
235
+ maxPerUnit?: number;
133
236
  };
134
237
  /**
135
238
  * What rule a pattern proposes. Return `undefined` for none (the pattern stays a lesson). Default: for a tool
@@ -157,6 +260,11 @@ export interface Learning {
157
260
  readonly rules: RuleStore;
158
261
  /** Records an experience of a vertical: a QA verdict, user feedback... */
159
262
  record(input: ExperienceInput): Promise<Experience>;
263
+ /**
264
+ * The short way to `record` what happened to an agent: `{ ok: true }` counts a success against the subject, `{ ok: false }`
265
+ * records a failure. A success without a subject is refused, because it would never be counted.
266
+ */
267
+ trackOutcome(input: OutcomeInput): Promise<Experience>;
160
268
  /** Without `tenantId` in the filter, every tenant's are returned (an operator's view). */
161
269
  experiences(filter?: {
162
270
  agentId?: string;
@@ -199,5 +307,39 @@ export interface Learning {
199
307
  reject(id: string, by: ApproverRef, reason?: string): Promise<void>;
200
308
  /** Withdraws an approved rule. */
201
309
  retire(ruleId: string): Promise<boolean>;
310
+ /**
311
+ * A read-only view of the approved rules of a tenant (or of no tenant). `createBaseEngine` hands it to the tools of an engine that
312
+ * has `learning`, under `LEARNED_RULES_SERVICE`; read it with `learnedRules(ctx, guard)`.
313
+ */
314
+ rulesView(tenantId?: string): LearnedRulesView;
315
+ /**
316
+ * What the author of a tool knows about its errors, by the code of the error (`*` for any): a learned lesson about that
317
+ * code says it instead of a generic sentence. `createBaseEngine` registers the `errorHints` of the tools it gets.
318
+ */
319
+ registerHints(tool: string, hints: Record<string, string>): void;
320
+ /** The units the agents have lessons for: a tool, or `general`. */
321
+ units(filter?: {
322
+ tenantId?: string;
323
+ }): Promise<LessonUnitInfo[]>;
324
+ /**
325
+ * One unit as markdown a person can write and review in git: a front matter, the lessons taught (the part that an
326
+ * import reads) and the lessons learned (generated, ignored on import).
327
+ */
328
+ exportUnit(unit: string, scope?: {
329
+ tenantId?: string;
330
+ agentId?: string;
331
+ }): Promise<string>;
332
+ /**
333
+ * Reads the `## Taught` lessons of a unit's markdown and teaches them, with an id that depends on their text, so
334
+ * importing the same file twice changes nothing. With `replace`, the taught lessons of that unit that are not in the
335
+ * file are forgotten. Only whoever `approverKinds` allows. The file is imported whole or not at all. **The front matter
336
+ * decides which tenant gets the lessons**; a product with tenants passes `tenantId` to say it itself and ignore the file's.
337
+ */
338
+ importUnit(markdown: string, by: ApproverRef, options?: {
339
+ replace?: boolean;
340
+ tenantId?: string;
341
+ }): Promise<TaughtLesson[]>;
342
+ /** Writes the counters of correct calls now (they are written every few seconds, and at most once the engine stops). */
343
+ flush(): Promise<void>;
202
344
  }
203
345
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/learning/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC3H,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAEhE,MAAM,MAAM,QAAQ,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAC;AAE9D,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AS,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAAC;IAC/C;;;OAGG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IACjE,mEAAmE;IACnE,KAAK,CAAC,MAAM,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAAC;IACjE;;;OAGG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC3F;;;;;OAKG;IACH,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC;IAC3H,wHAAwH;IACxH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B"}
@@ -0,0 +1,46 @@
1
+ /** A lesson that belongs to no tool in particular. */
2
+ export declare const GENERAL_UNIT = "general";
3
+ /**
4
+ * What the engine itself knows about how a call failed, whatever the domain: said once, the same for every agent. The
5
+ * advice that depends on the domain comes from whoever knows it (`ToolDefinition.errorHints`, `teach`).
6
+ */
7
+ export declare const ENGINE_HINTS: Record<string, string>;
8
+ /** What the engine knows of an error code that any tool can raise. */
9
+ export declare const ENGINE_ERROR_CODES: Record<string, string>;
10
+ export interface UnitEntry {
11
+ source: 'taught' | 'learned';
12
+ /** Already one line, without the leading dash. */
13
+ text: string;
14
+ }
15
+ export interface UnitGroup {
16
+ name: string;
17
+ entries: UnitEntry[];
18
+ }
19
+ /** Units first `general`, then by name; inside a unit what a person taught goes before what was learned. */
20
+ export declare function groupEntries(items: Array<{
21
+ unit: string;
22
+ source: UnitEntry['source'];
23
+ text: string;
24
+ order: string;
25
+ }>): UnitGroup[];
26
+ /**
27
+ * The text of the units, cut to `maxChars` by dropping whole entries from the end, never in the middle of one: the same
28
+ * units always give the same text, so the system prompt stays cacheable. What was learned goes first; a lesson a person
29
+ * taught is only dropped when nothing learned is left.
30
+ */
31
+ export declare function fitUnits(groups: UnitGroup[], maxChars: number): string | undefined;
32
+ export interface UnitDocument {
33
+ unit: string;
34
+ tools: string[];
35
+ agentId?: string;
36
+ tenantId?: string;
37
+ /** The lessons of the `## Taught` section: the only part an import reads. */
38
+ taught: string[];
39
+ /** The `## Learned` section: regenerated on export, ignored on import. */
40
+ learned: string[];
41
+ }
42
+ export declare function unitToMarkdown(doc: UnitDocument): string;
43
+ export declare function unitFromMarkdown(markdown: string): UnitDocument;
44
+ /** The same lesson in the same unit has the same id, so importing a file twice changes nothing. */
45
+ export declare function lessonIdFor(unit: string, tenantId: string | undefined, agentId: string | undefined, text: string): string;
46
+ //# sourceMappingURL=units.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"units.d.ts","sourceRoot":"","sources":["../../src/learning/units.ts"],"names":[],"mappings":"AAGA,sDAAsD;AACtD,eAAO,MAAM,YAAY,YAAY,CAAC;AAEtC;;;GAGG;AACH,eAAO,MAAM,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAQ/C,CAAC;AAEF,sEAAsE;AACtE,eAAO,MAAM,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAErD,CAAC;AAEF,MAAM,WAAW,SAAS;IACtB,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC7B,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,SAAS;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,SAAS,EAAE,CAAC;CACxB;AAED,4GAA4G;AAC5G,wBAAgB,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,SAAS,CAAC,QAAQ,CAAC,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,SAAS,EAAE,CAalI;AAKD;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAelF;AAID,MAAM,WAAW,YAAY;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6EAA6E;IAC7E,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,0EAA0E;IAC1E,OAAO,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAIxD;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,YAAY,CAkB/D;AAED,mGAAmG;AACnG,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAEzH"}
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ENGINE_ERROR_CODES = exports.ENGINE_HINTS = exports.GENERAL_UNIT = void 0;
37
+ exports.groupEntries = groupEntries;
38
+ exports.fitUnits = fitUnits;
39
+ exports.unitToMarkdown = unitToMarkdown;
40
+ exports.unitFromMarkdown = unitFromMarkdown;
41
+ exports.lessonIdFor = lessonIdFor;
42
+ const node_crypto_1 = require("node:crypto");
43
+ const yaml = __importStar(require("yaml"));
44
+ /** A lesson that belongs to no tool in particular. */
45
+ exports.GENERAL_UNIT = 'general';
46
+ /**
47
+ * What the engine itself knows about how a call failed, whatever the domain: said once, the same for every agent. The
48
+ * advice that depends on the domain comes from whoever knows it (`ToolDefinition.errorHints`, `teach`).
49
+ */
50
+ exports.ENGINE_HINTS = {
51
+ policy_denied: 'A policy denied this call: do not repeat it unchanged; ask for approval or choose another way.',
52
+ guardrail_blocked: 'A guardrail blocked this call: change what you send instead of retrying it.',
53
+ sandbox_denied: 'The sandbox denied this call: it is outside what this agent may touch.',
54
+ tool_timeout: 'This call timed out: try a smaller request instead of repeating the same one.',
55
+ tool_too_large: 'The result was too large: narrow the request.',
56
+ tool_not_found: 'This tool does not exist: use only the tools you were given.',
57
+ tool_not_allowed: 'This agent may not use this tool: use only the tools you were given.',
58
+ };
59
+ /** What the engine knows of an error code that any tool can raise. */
60
+ exports.ENGINE_ERROR_CODES = {
61
+ INVALID_ARGUMENTS: 'The arguments did not match the schema of the tool: read the schema and send every required field with the right type.',
62
+ };
63
+ /** Units first `general`, then by name; inside a unit what a person taught goes before what was learned. */
64
+ function groupEntries(items) {
65
+ const byUnit = new Map();
66
+ for (const item of items) {
67
+ const list = byUnit.get(item.unit);
68
+ if (list)
69
+ list.push(item);
70
+ else
71
+ byUnit.set(item.unit, [item]);
72
+ }
73
+ const names = [...byUnit.keys()].sort((a, b) => (a === exports.GENERAL_UNIT ? -1 : b === exports.GENERAL_UNIT ? 1 : a.localeCompare(b)));
74
+ return names.map(name => {
75
+ const list = byUnit.get(name);
76
+ const taught = list.filter(i => i.source === 'taught').sort((a, b) => a.order.localeCompare(b.order));
77
+ const learned = list.filter(i => i.source === 'learned').sort((a, b) => a.order.localeCompare(b.order));
78
+ return { name, entries: [...taught, ...learned].map(i => ({ source: i.source, text: i.text })) };
79
+ });
80
+ }
81
+ const render = (groups) => groups.map(g => `### ${g.name}\n${g.entries.map(e => `- ${e.text}`).join('\n')}`).join('\n\n');
82
+ /**
83
+ * The text of the units, cut to `maxChars` by dropping whole entries from the end, never in the middle of one: the same
84
+ * units always give the same text, so the system prompt stays cacheable. What was learned goes first; a lesson a person
85
+ * taught is only dropped when nothing learned is left.
86
+ */
87
+ function fitUnits(groups, maxChars) {
88
+ let live = groups.map(g => ({ ...g, entries: [...g.entries] })).filter(g => g.entries.length);
89
+ const dropLast = (source) => {
90
+ for (let g = live.length - 1; g >= 0; g--) {
91
+ for (let e = live[g].entries.length - 1; e >= 0; e--) {
92
+ if (live[g].entries[e].source === source) {
93
+ live[g].entries.splice(e, 1);
94
+ return true;
95
+ }
96
+ }
97
+ }
98
+ return false;
99
+ };
100
+ while (live.length && render(live).length > maxChars) {
101
+ if (!dropLast('learned') && !dropLast('taught'))
102
+ break;
103
+ live = live.filter(g => g.entries.length);
104
+ }
105
+ return live.length ? render(live) : undefined;
106
+ }
107
+ function unitToMarkdown(doc) {
108
+ const front = { unit: doc.unit, ...(doc.tools.length ? { tools: doc.tools } : {}), ...(doc.agentId ? { agent: doc.agentId } : {}), ...(doc.tenantId ? { tenant: doc.tenantId } : {}) };
109
+ const bullets = (list) => list.length ? list.map(t => `- ${t}`).join('\n') : '_none_';
110
+ return `---\n${yaml.stringify(front).trimEnd()}\n---\n\n## Taught\n\n${bullets(doc.taught)}\n\n## Learned (generated: regenerated on export and ignored on import)\n\n${bullets(doc.learned)}\n`;
111
+ }
112
+ function unitFromMarkdown(markdown) {
113
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(markdown.trim());
114
+ if (!m)
115
+ throw new Error('A unit starts with a front matter between --- lines');
116
+ const front = (yaml.parse(m[1]) ?? {});
117
+ if (typeof front.unit !== 'string' || !front.unit.trim())
118
+ throw new Error('A unit needs a `unit` name in its front matter');
119
+ const str = (v) => typeof v === 'string' && v.trim() ? v.trim() : undefined;
120
+ const tools = Array.isArray(front.tools) ? front.tools.filter((t) => typeof t === 'string' && !!t) : [];
121
+ const sections = m[2].split(/^## /m).slice(1);
122
+ const taughtSection = sections.find(s => /^Taught\b/i.test(s));
123
+ const taught = (taughtSection ?? '').split(/\r?\n/).slice(1)
124
+ .map(l => /^\s*[-*]\s+(.*\S)\s*$/.exec(l)?.[1])
125
+ .filter((t) => !!t);
126
+ return {
127
+ unit: front.unit.trim(), tools,
128
+ ...(str(front.agent) ? { agentId: str(front.agent) } : {}),
129
+ ...(str(front.tenant) ? { tenantId: str(front.tenant) } : {}),
130
+ taught, learned: [],
131
+ };
132
+ }
133
+ /** The same lesson in the same unit has the same id, so importing a file twice changes nothing. */
134
+ function lessonIdFor(unit, tenantId, agentId, text) {
135
+ return `lesson-${(0, node_crypto_1.createHash)('sha256').update([unit, tenantId ?? '', agentId ?? '', text].join('\u0000')).digest('hex').slice(0, 16)}`;
136
+ }
137
+ //# sourceMappingURL=units.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"units.js","sourceRoot":"","sources":["../../src/learning/units.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,oCAaC;AAUD,4BAeC;AAeD,wCAIC;AAED,4CAkBC;AAGD,kCAEC;AAvHD,6CAAyC;AACzC,2CAA6B;AAE7B,sDAAsD;AACzC,QAAA,YAAY,GAAG,SAAS,CAAC;AAEtC;;;GAGG;AACU,QAAA,YAAY,GAA2B;IAChD,aAAa,EAAE,gGAAgG;IAC/G,iBAAiB,EAAE,6EAA6E;IAChG,cAAc,EAAE,wEAAwE;IACxF,YAAY,EAAE,+EAA+E;IAC7F,cAAc,EAAE,+CAA+C;IAC/D,cAAc,EAAE,8DAA8D;IAC9E,gBAAgB,EAAE,sEAAsE;CAC3F,CAAC;AAEF,sEAAsE;AACzD,QAAA,kBAAkB,GAA2B;IACtD,iBAAiB,EAAE,wHAAwH;CAC9I,CAAC;AAaF,4GAA4G;AAC5G,SAAgB,YAAY,CAAC,KAAwF;IACjH,MAAM,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC/C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;;YAAM,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;IAClE,CAAC;IACD,MAAM,KAAK,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAA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