@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.
- package/README.md +26 -0
- package/dist/engine/AgentEngine.d.ts +22 -2
- package/dist/engine/AgentEngine.d.ts.map +1 -1
- package/dist/engine/AgentEngine.js +92 -48
- package/dist/engine/AgentEngine.js.map +1 -1
- package/dist/engine/createBaseEngine.d.ts +2 -0
- package/dist/engine/createBaseEngine.d.ts.map +1 -1
- package/dist/engine/createBaseEngine.js +21 -4
- package/dist/engine/createBaseEngine.js.map +1 -1
- package/dist/engine/error-code.d.ts +7 -0
- package/dist/engine/error-code.d.ts.map +1 -0
- package/dist/engine/error-code.js +23 -0
- package/dist/engine/error-code.js.map +1 -0
- package/dist/engine/run-recorder.d.ts +13 -0
- package/dist/engine/run-recorder.d.ts.map +1 -0
- package/dist/engine/run-recorder.js +49 -0
- package/dist/engine/run-recorder.js.map +1 -0
- package/dist/governance/types.d.ts +6 -0
- package/dist/governance/types.d.ts.map +1 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -3
- package/dist/index.js.map +1 -1
- package/dist/learning/index.d.ts +2 -1
- package/dist/learning/index.d.ts.map +1 -1
- package/dist/learning/index.js +270 -56
- package/dist/learning/index.js.map +1 -1
- package/dist/learning/signal.d.ts +51 -0
- package/dist/learning/signal.d.ts.map +1 -0
- package/dist/learning/signal.js +136 -0
- package/dist/learning/signal.js.map +1 -0
- package/dist/learning/types.d.ts +143 -1
- package/dist/learning/types.d.ts.map +1 -1
- package/dist/learning/units.d.ts +46 -0
- package/dist/learning/units.d.ts.map +1 -0
- package/dist/learning/units.js +137 -0
- package/dist/learning/units.js.map +1 -0
- package/dist/tools/defineTool.d.ts +4 -1
- package/dist/tools/defineTool.d.ts.map +1 -1
- package/dist/tools/defineTool.js +5 -2
- package/dist/tools/defineTool.js.map +1 -1
- package/dist/tools/services.d.ts +13 -0
- package/dist/tools/services.d.ts.map +1 -1
- package/dist/tools/services.js +12 -0
- package/dist/tools/services.js.map +1 -1
- package/dist/tools/tool-error.d.ts +19 -0
- package/dist/tools/tool-error.d.ts.map +1 -0
- package/dist/tools/tool-error.js +33 -0
- package/dist/tools/tool-error.js.map +1 -0
- package/dist/types/index.d.ts +39 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +89 -89
package/README.md
CHANGED
|
@@ -1132,6 +1132,15 @@ await learning.retire(id); // withdraw an appro
|
|
|
1132
1132
|
```
|
|
1133
1133
|
|
|
1134
1134
|
- **What the `learning` option wires.** Every failed, timed-out, denied or blocked tool call becomes an experience. The lessons of each agent, sanitized and capped, join its system prompt. The rules a person approved (`{ tool, effect: 'ask' | 'deny' }`) are enforced only when the engine is on the policy path (`policy`, `approver` or `approvals` is set): `learning` alone never changes how the engine asks for approval. `learning.sink`, `learning.hooks` and `learning.policy` remain available to wire by hand.
|
|
1135
|
+
- **What makes a pattern.** The same failure (tool, kind and, when the tool's error has one, its code: `ECONNRESET` and `ERP_PERIOD_CLOSED` are different patterns) seen `threshold` times **inside the window** (`window: { days: 30 }`). Correct calls are counted, not stored, so a tool with many calls also needs the failures to be a share of them (`rate`, default 5% from 20 calls): 3 failures in 1000 calls are noise, 3 in 5 are not. The share is that of the **subject**: to judge a context on its own, put it in the subject (`breakout/trend_flat` and `breakout/trend_up` are judged separately; `breakout` judges both together). The share decides when a pattern **enters**; once in, it stays while its failures stay in the window, so a lesson that works (and fills its subject with correct calls) does not remove itself. `rate: false` counts failures only. `learning.flush()` writes the counters now; they are also written after each turn.
|
|
1136
|
+
- **Lessons come in units.** The lessons of an agent are grouped by tool (`### post_invoice`), with `general` first; inside a unit, what a person taught goes before what was learned, and `lessons.maxPerUnit` caps the learned ones. `lessons.maxPerUnit` and `lessons.maxLessons` keep the learned lessons that happen most. The text is cut by dropping whole entries from the end, learned ones first and what a person taught only when nothing learned is left, so the same lessons always give the same system prompt.
|
|
1137
|
+
- **The advice comes from whoever knows the domain.** A tool declares what to do about each error code: `defineTool({ ..., errorHints: { ERP_PERIOD_CLOSED: 'The period is closed: post it in the next open one.', '*': 'Check the invoice first.' } })`. When that error repeats, the lesson says it. It is only about the errors the tool raises: for the failures the engine sees by itself (a denial, a timeout, a result that was too large) it says one fixed sentence (`ENGINE_HINTS`). Nothing generic is invented for the rest: the lesson states the fact.
|
|
1138
|
+
- **A unit a person can write and review in git.** `await learning.exportUnit('post_invoice')` gives markdown with a front matter, the `## Taught` lessons (the part an import reads) and the `## Learned` ones (generated: ignored on import). `await learning.importUnit(md, by)` teaches the taught ones; the file is imported whole or not at all, importing it twice changes nothing (a lesson that did not change keeps its place and its first author), and `{ replace: true }` forgets the ones that left the file. **The front matter decides which tenant gets the lessons**: a product with tenants passes `{ tenantId }` to say it itself. `learning.units()` lists the units.
|
|
1139
|
+
- **Everything in a directory.** `createLearning({ dir })` keeps the experiences, counters, proposals, rules and taught lessons under one directory (`experiences.json`, `counters.json`, `proposals/`, `rules.json`, `lessons.json`); a store you pass replaces its file. Without `dir` nothing touches the disk.
|
|
1140
|
+
- **Report what happened in one line.** `await learning.trackOutcome({ agentId, domain, subject, ok, context?, kind?, detail? })` counts a success against its subject or records a failure. A success without a subject is refused: it would never be counted.
|
|
1141
|
+
- **Circumstances in the pattern.** `context` ('trend_flat', 'before_close') makes the same subject be judged apart: the share of failures is measured against the calls *in that context*. Without a context nothing changes.
|
|
1142
|
+
- **Simulated time.** `createLearning({ now, stamp: 'clock' })` makes the experiences from the audit sink, `record` and the counters use the clock `now`, so a simulation or a backtest runs in simulated time with the window, the counters and the experiences in agreement. The default is the time of the event, as always.
|
|
1143
|
+
- **Tools enforce the rules a person approved** without owning a store: `const guards = await learnedRules(ctx, isMyGuard)`. `createBaseEngine({ learning })` gives the tools a read-only view of the rules of the engine's tenant under `LEARNED_RULES_SERVICE`, never the `Learning` object (it could approve).
|
|
1135
1144
|
- **Teach it something specific.** A lesson a person writes does not wait for three failures: `await learning.teach({ text: 'Totals are rounded to 2 decimals.', tools: ['post_invoice'] }, { kind: 'human', id: 'ana' })`. It joins the prompt as `Taught lessons`, before the learned ones, sanitized and capped, inside its tenant. `agentId` limits it to one agent, `tools` to agents that have one of those tools in the turn, and it is at most 500 characters. `learning.taught()` lists them and `learning.forget(id)` withdraws one. For knowledge that never changes, `AGENT.md` or `instructionSources` do the same without learning.
|
|
1136
1145
|
- **A rule by hand.** `learning.addRule({ rule: { tool: 'post_invoice', effect: 'deny' }, reason: 'ERP freeze' }, by)` validates the rule, attributes it to a person and stores it next to the ones that came from proposals.
|
|
1137
1146
|
- **Only a person.** Teaching and adding a rule need the same author as approving one (`approverKinds`, default a human): an agent cannot teach itself.
|
|
@@ -1144,6 +1153,23 @@ await learning.retire(id); // withdraw an appro
|
|
|
1144
1153
|
|
|
1145
1154
|
---
|
|
1146
1155
|
|
|
1156
|
+
## What `engine.run` returns
|
|
1157
|
+
|
|
1158
|
+
```typescript
|
|
1159
|
+
const r = await engine.run('Session 7');
|
|
1160
|
+
r.text; // what the agent said after its last tool call
|
|
1161
|
+
r.toolCalls; // [{ name, agentId, success, errorCode?, outcome?, preview? }], delegates included
|
|
1162
|
+
r.errors; // the messages of the error events of the turn
|
|
1163
|
+
r.aborted; // the turn was aborted (engine.abort(), a budget)
|
|
1164
|
+
r.budgetExceeded;
|
|
1165
|
+
r.systemPrompts; // the prompt of each model call: only with `emitSystemPrompt: true` (a system prompt can carry secrets)
|
|
1166
|
+
engine.budgetExceeded; // sticky: the cost budget was reached at some point
|
|
1167
|
+
```
|
|
1168
|
+
|
|
1169
|
+
Every tool that fails with a `ToolError(code, message)` (or `ToolArgumentError`) shows its `code` in `toolCalls`, in the audit event and in the `tool_result` event (`error_code`).
|
|
1170
|
+
|
|
1171
|
+
---
|
|
1172
|
+
|
|
1147
1173
|
## Sources of agents, skills and instructions
|
|
1148
1174
|
|
|
1149
1175
|
The engine reads no file by itself. Where its agents, skills and instruction layers come from is declared with sources, and an engine built without them touches no disk:
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type EngineHooks } from '../governance/hooks';
|
|
2
2
|
import type { ApprovalStore, Approver, AuditSink, Identity, ToolPolicy } from '../governance/types';
|
|
3
|
-
import type { EngineOptions, SessionMemoryData } from '../types';
|
|
3
|
+
import type { EngineOptions, RunResult, SessionMemoryData } from '../types';
|
|
4
|
+
import type { BudgetUsage } from '../observability/types';
|
|
4
5
|
import type { Transport } from '../transport/Transport';
|
|
5
6
|
import type { AgentRegistry } from './AgentRegistry';
|
|
6
7
|
import type { ToolRegistry } from './ToolRegistry';
|
|
@@ -124,6 +125,12 @@ export interface AgentEngineOptions extends EngineOptions {
|
|
|
124
125
|
* next system prompt reflects the switched project without an engine restart.
|
|
125
126
|
*/
|
|
126
127
|
projectContextLoader?: (cwd: string) => Promise<string | undefined>;
|
|
128
|
+
/**
|
|
129
|
+
* Emit a `system_prompt` event with the system prompt of every model call. It is how you check what the agent really saw
|
|
130
|
+
* (the lessons and the memory that reached it). Off by default: a system prompt can carry secrets, and the event goes to
|
|
131
|
+
* every transport.
|
|
132
|
+
*/
|
|
133
|
+
emitSystemPrompt?: boolean;
|
|
127
134
|
}
|
|
128
135
|
import type { ZodType } from 'zod';
|
|
129
136
|
export declare class AgentEngine {
|
|
@@ -169,6 +176,10 @@ export declare class AgentEngine {
|
|
|
169
176
|
private memoryContextBlock;
|
|
170
177
|
/** Serializes concurrent run() calls — shared mutable state is not reentrant-safe. */
|
|
171
178
|
private runMutex;
|
|
179
|
+
/** What the engine emits to: the transport of the caller, with the events of the current run also collected. */
|
|
180
|
+
private readonly transport;
|
|
181
|
+
private recorder?;
|
|
182
|
+
private budgetHit;
|
|
172
183
|
constructor(opts: AgentEngineOptions);
|
|
173
184
|
/**
|
|
174
185
|
* Asks the agent's provider for an object matching `schema` (validated with zod, one corrective
|
|
@@ -225,7 +236,14 @@ export declare class AgentEngine {
|
|
|
225
236
|
*/
|
|
226
237
|
callLLM(prompt: string): Promise<string>;
|
|
227
238
|
private getProviderForProfile;
|
|
228
|
-
run(input: string): Promise<
|
|
239
|
+
run(input: string): Promise<RunResult>;
|
|
240
|
+
/** The cost budget was exceeded at some point (`observability.costTracker.budget`). It stays true. */
|
|
241
|
+
get budgetExceeded(): boolean;
|
|
242
|
+
/**
|
|
243
|
+
* Called by the engine's own budget wiring (`createBaseEngine`): remembers it for `engine.budgetExceeded` and the result of the
|
|
244
|
+
* run. It tells the transport only when `announce` (the `budget_exceeded` event has always been tied to `abortOnBudget`).
|
|
245
|
+
*/
|
|
246
|
+
reportBudgetExceeded(usage: BudgetUsage, announce?: boolean): void;
|
|
229
247
|
private _run;
|
|
230
248
|
/** Sections the `systemPrompt` hooks add for `profile`. */
|
|
231
249
|
private hookPromptSections;
|
|
@@ -284,6 +302,8 @@ export declare class AgentEngine {
|
|
|
284
302
|
switchAgent(agentId: string): void;
|
|
285
303
|
private getCurrentProfile;
|
|
286
304
|
private buildAgentRoster;
|
|
305
|
+
/** Opt-in (`emitSystemPrompt`): a system prompt can carry secrets and reaches every transport. */
|
|
306
|
+
private emitSystemPrompt;
|
|
287
307
|
private buildSystemPrompt;
|
|
288
308
|
private resolvesDelegateTo;
|
|
289
309
|
private getToolsForAgent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentEngine.d.ts","sourceRoot":"","sources":["../../src/engine/AgentEngine.ts"],"names":[],"mappings":"AAaA,OAAO,EAA2D,KAAK,WAAW,EAAmB,MAAM,qBAAqB,CAAC;AACjI,OAAO,KAAK,EAER,aAAa,EACb,QAAQ,EAMR,SAAS,EACT,QAAQ,EAIR,UAAU,EACb,MAAM,qBAAqB,CAAC;AAO7B,OAAO,KAAK,EAER,aAAa,EAIb,iBAAiB,EAGpB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,E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AAS,CAA8B;IAEjG;;;;OAIG;IACH,OAAO,CAAC,UAAU;IAuBlB,8GAA8G;IAC9G,OAAO,CAAC,cAAc;IAOtB;;;OAGG;IACH,OAAO,CAAC,qBAAqB;IAsB7B;;;;;OAKG;YACW,eAAe;IAoI7B,wFAAwF;IACxF,OAAO,CAAC,SAAS,CAAuC;IACxD,OAAO,CAAC,SAAS;IAMjB,uGAAuG;YACzF,YAAY;IAc1B,OAAO,CAAC,oBAAoB;IAS5B;;;;OAIG;YACW,cAAc;YAsCd,UAAU;IAoDxB;;;OAGG;YACW,eAAe;YAQf,UAAU;IAkExB;;;;;;;;OAQG;IACH,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAI7C;;;OAGG;IACH,mBAAmB,IAAI,IAAI;IAE3B,8DAA8D;IAC9D,kBAAkB,IAAI,IAAI;IAG1B,qGAAqG;IACrG,OAAO,CAAC,YAAY;IASpB;;;;OAIG;YACW,WAAW;IAgCzB,OAAO,CAAC,YAAY;CA4CvB"}
|
|
@@ -20,6 +20,8 @@ const SessionMemory_1 = require("../memory/SessionMemory");
|
|
|
20
20
|
const activator_1 = require("../skills/activator");
|
|
21
21
|
const WorkflowRunner_1 = require("../workflow/WorkflowRunner");
|
|
22
22
|
const IterationManager_1 = require("./IterationManager");
|
|
23
|
+
const error_code_1 = require("./error-code");
|
|
24
|
+
const run_recorder_1 = require("./run-recorder");
|
|
23
25
|
const MAX_INPUT_BYTES = 100_000; // Fix #17: 100 KB hard cap on user input
|
|
24
26
|
const ASK_AGENT_TOOL = {
|
|
25
27
|
name: 'ask_agent',
|
|
@@ -100,8 +102,17 @@ class AgentEngine {
|
|
|
100
102
|
memoryContextBlock = '';
|
|
101
103
|
/** Serializes concurrent run() calls — shared mutable state is not reentrant-safe. */
|
|
102
104
|
runMutex = Promise.resolve();
|
|
105
|
+
/** What the engine emits to: the transport of the caller, with the events of the current run also collected. */
|
|
106
|
+
transport;
|
|
107
|
+
recorder;
|
|
108
|
+
budgetHit = false;
|
|
103
109
|
constructor(opts) {
|
|
104
110
|
this.opts = opts;
|
|
111
|
+
this.transport = {
|
|
112
|
+
emit: (event) => { this.recorder?.push(event); opts.transport.emit(event); },
|
|
113
|
+
onInput: (cb) => opts.transport.onInput(cb),
|
|
114
|
+
close: () => opts.transport.close(),
|
|
115
|
+
};
|
|
105
116
|
this.memory = opts.sessionMemory ?? new SessionMemory_1.SessionMemory();
|
|
106
117
|
this.currentAgentId = opts.defaultAgentId;
|
|
107
118
|
this.allSkills = opts.skills ?? [];
|
|
@@ -115,12 +126,12 @@ class AgentEngine {
|
|
|
115
126
|
this.contextManager = new ContextManager_1.ContextManager(opts.context, {
|
|
116
127
|
history: this.history,
|
|
117
128
|
summarize: (transcript, previous) => this.summarizeForContext(transcript, previous),
|
|
118
|
-
emit: (event) => this.
|
|
129
|
+
emit: (event) => this.transport.emit(event),
|
|
119
130
|
});
|
|
120
131
|
}
|
|
121
132
|
this.auditLogger = new AuditLogger_1.AuditLogger(opts.auditLog);
|
|
122
133
|
// A sink that fails must not change what the agent already did, but it must not fail silently either.
|
|
123
|
-
this.audit = new audit_1.AuditDispatcher(opts.audit, (err) => this.
|
|
134
|
+
this.audit = new audit_1.AuditDispatcher(opts.audit, (err) => this.transport.emit({
|
|
124
135
|
type: 'system', level: 'warn',
|
|
125
136
|
text: `[audit] a sink failed to record a tool call: ${err instanceof Error ? err.message : String(err)}`,
|
|
126
137
|
}));
|
|
@@ -149,11 +160,11 @@ class AgentEngine {
|
|
|
149
160
|
mcpManager: opts.mcpManager,
|
|
150
161
|
tools: opts.tools,
|
|
151
162
|
agents: opts.agents,
|
|
152
|
-
transport:
|
|
163
|
+
transport: this.transport,
|
|
153
164
|
});
|
|
154
165
|
this.approvalGate = new ApprovalGate_1.ApprovalGate({
|
|
155
166
|
onToolApproval: opts.onToolApproval,
|
|
156
|
-
transport:
|
|
167
|
+
transport: this.transport,
|
|
157
168
|
});
|
|
158
169
|
this.iterationManager = new IterationManager_1.IterationManager({
|
|
159
170
|
mode: opts.iterationMode ?? 'interactive',
|
|
@@ -165,7 +176,7 @@ class AgentEngine {
|
|
|
165
176
|
maxParallel: opts.maxParallelAgents ?? 6,
|
|
166
177
|
maxDepth: opts.maxDelegationDepth,
|
|
167
178
|
agents: opts.agents,
|
|
168
|
-
transport:
|
|
179
|
+
transport: this.transport,
|
|
169
180
|
runAgent: (id, question, context, depth, buf, chain) => this.runAgentInternal(id, question, context, depth, buf, chain),
|
|
170
181
|
});
|
|
171
182
|
}
|
|
@@ -186,7 +197,7 @@ class AgentEngine {
|
|
|
186
197
|
name: opts.name,
|
|
187
198
|
model: profile.model,
|
|
188
199
|
onMetrics: (inputTokens, outputTokens, usage) => {
|
|
189
|
-
this.
|
|
200
|
+
this.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
|
|
190
201
|
agentId, provider: profile.provider ?? this.opts.defaultProvider,
|
|
191
202
|
model: profile.model ?? provider.modelId, purpose: 'structured_output', startedAt: attemptStart,
|
|
192
203
|
}));
|
|
@@ -309,35 +320,55 @@ class AgentEngine {
|
|
|
309
320
|
const prev = this.runMutex;
|
|
310
321
|
this.runMutex = prev.then(() => slot);
|
|
311
322
|
await prev;
|
|
323
|
+
// One collector per turn, set once the turn owns the engine: every exit of `_run` (blocked input, a route to an agent,
|
|
324
|
+
// an abort, an error) ends here, and the events of delegates are part of the turn.
|
|
325
|
+
const recorder = new run_recorder_1.RunRecorder();
|
|
326
|
+
this.recorder = recorder;
|
|
312
327
|
try {
|
|
313
328
|
await this._run(input);
|
|
314
329
|
}
|
|
315
330
|
finally {
|
|
331
|
+
this.recorder = undefined;
|
|
316
332
|
release();
|
|
317
333
|
}
|
|
334
|
+
return recorder.result(this.aborted);
|
|
335
|
+
}
|
|
336
|
+
/** The cost budget was exceeded at some point (`observability.costTracker.budget`). It stays true. */
|
|
337
|
+
get budgetExceeded() {
|
|
338
|
+
return this.budgetHit;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Called by the engine's own budget wiring (`createBaseEngine`): remembers it for `engine.budgetExceeded` and the result of the
|
|
342
|
+
* run. It tells the transport only when `announce` (the `budget_exceeded` event has always been tied to `abortOnBudget`).
|
|
343
|
+
*/
|
|
344
|
+
reportBudgetExceeded(usage, announce = true) {
|
|
345
|
+
this.budgetHit = true;
|
|
346
|
+
this.recorder?.markBudgetExceeded();
|
|
347
|
+
if (announce)
|
|
348
|
+
this.transport.emit({ type: 'budget_exceeded', usage });
|
|
318
349
|
}
|
|
319
350
|
async _run(input) {
|
|
320
351
|
if (this.pendingContextLoad)
|
|
321
352
|
await this.pendingContextLoad;
|
|
322
353
|
this.aborted = false;
|
|
323
|
-
this.
|
|
354
|
+
this.transport.emit({ type: 'ready' });
|
|
324
355
|
// Fix #17: reject inputs that exceed the hard cap to prevent prompt injection via huge payloads
|
|
325
356
|
if (Buffer.byteLength(input, 'utf-8') > MAX_INPUT_BYTES) {
|
|
326
|
-
this.
|
|
357
|
+
this.transport.emit({
|
|
327
358
|
type: 'error',
|
|
328
359
|
message: `Input too large (${Buffer.byteLength(input, 'utf-8').toLocaleString()} bytes). Maximum is ${MAX_INPUT_BYTES.toLocaleString()} bytes.`,
|
|
329
360
|
});
|
|
330
|
-
this.
|
|
361
|
+
this.transport.emit({ type: 'done' });
|
|
331
362
|
return;
|
|
332
363
|
}
|
|
333
364
|
if (this.guardrails?.has('input')) {
|
|
334
365
|
const checked = await this.guard('input', input, this.currentAgentId);
|
|
335
366
|
if (checked.blocked) {
|
|
336
|
-
this.
|
|
367
|
+
this.transport.emit({
|
|
337
368
|
type: 'error',
|
|
338
369
|
message: `Input blocked by guardrail "${checked.blocked.guardrail}": ${checked.blocked.reason}`,
|
|
339
370
|
});
|
|
340
|
-
this.
|
|
371
|
+
this.transport.emit({ type: 'done' });
|
|
341
372
|
return;
|
|
342
373
|
}
|
|
343
374
|
input = checked.content;
|
|
@@ -360,22 +391,22 @@ class AgentEngine {
|
|
|
360
391
|
throw new Error(`MCP route matched agent "${mcpRoute.agentId}", but it is not registered ` +
|
|
361
392
|
`and no current agent profile is available.`);
|
|
362
393
|
}
|
|
363
|
-
this.
|
|
394
|
+
this.transport.emit({
|
|
364
395
|
type: 'block_start',
|
|
365
396
|
agent_id: mcpRoute.agentId,
|
|
366
397
|
agent_name: mcpProfile.name ?? mcpRoute.agentId,
|
|
367
398
|
agent_icon: mcpProfile.icon ?? '◎',
|
|
368
399
|
});
|
|
369
400
|
const result = await this.executeToolCall({ name: toolName, args: JSON.stringify({ [firstParam]: input }) }, mcpProfile);
|
|
370
|
-
this.
|
|
371
|
-
this.
|
|
372
|
-
this.
|
|
401
|
+
this.transport.emit({ type: 'token', content: result, agent_id: mcpRoute.agentId });
|
|
402
|
+
this.transport.emit({ type: 'block_end', status: 'ok', agent_id: mcpRoute.agentId });
|
|
403
|
+
this.transport.emit({ type: 'done' });
|
|
373
404
|
return;
|
|
374
405
|
}
|
|
375
406
|
}
|
|
376
407
|
// Agent trigger fallback: route to the agent's LLM session
|
|
377
408
|
await this.runAgentInternal(mcpRoute.agentId, input);
|
|
378
|
-
this.
|
|
409
|
+
this.transport.emit({ type: 'done' });
|
|
379
410
|
return;
|
|
380
411
|
}
|
|
381
412
|
// Pre-compute memory context block for this input
|
|
@@ -408,7 +439,7 @@ class AgentEngine {
|
|
|
408
439
|
state: new Map(),
|
|
409
440
|
signal: this.runController.signal,
|
|
410
441
|
hasAgent: (id) => this.opts.agents.has(id),
|
|
411
|
-
emit: (event) => this.
|
|
442
|
+
emit: (event) => this.transport.emit(event),
|
|
412
443
|
};
|
|
413
444
|
try {
|
|
414
445
|
await (0, hooks_1.runHooks)(this.hooks, 'beforeRun', h => h.beforeRun(this.runCtx));
|
|
@@ -422,7 +453,7 @@ class AgentEngine {
|
|
|
422
453
|
this.runCtx = undefined;
|
|
423
454
|
this.runController = undefined;
|
|
424
455
|
}
|
|
425
|
-
this.
|
|
456
|
+
this.transport.emit({ type: 'done' });
|
|
426
457
|
}
|
|
427
458
|
/** Sections the `systemPrompt` hooks add for `profile`. */
|
|
428
459
|
async hookPromptSections(profile) {
|
|
@@ -454,7 +485,7 @@ class AgentEngine {
|
|
|
454
485
|
toolHookContext(principal) {
|
|
455
486
|
return this.runCtx
|
|
456
487
|
? { ...this.runCtx, principal }
|
|
457
|
-
: { principal, input: '', state: new Map(), signal: new AbortController().signal, hasAgent: (id) => this.opts.agents.has(id), emit: (e) => this.
|
|
488
|
+
: { principal, input: '', state: new Map(), signal: new AbortController().signal, hasAgent: (id) => this.opts.agents.has(id), emit: (e) => this.transport.emit(e) };
|
|
458
489
|
}
|
|
459
490
|
async runWorkflow(defOrBuilder, opts = {}) {
|
|
460
491
|
if (this.pendingContextLoad)
|
|
@@ -465,7 +496,7 @@ class AgentEngine {
|
|
|
465
496
|
const runner = new WorkflowRunner_1.WorkflowRunner(def, {
|
|
466
497
|
...opts,
|
|
467
498
|
runAgent: (agentId, input, context) => this.runAgentInternal(agentId, input, context, 0),
|
|
468
|
-
transport: this.
|
|
499
|
+
transport: this.transport,
|
|
469
500
|
});
|
|
470
501
|
return runner.run();
|
|
471
502
|
}
|
|
@@ -558,7 +589,7 @@ class AgentEngine {
|
|
|
558
589
|
});
|
|
559
590
|
const replaced = replacement?.(outcome);
|
|
560
591
|
outcome.events.forEach((info, i) => {
|
|
561
|
-
this.
|
|
592
|
+
this.transport.emit({
|
|
562
593
|
type: 'guardrail',
|
|
563
594
|
name: info.name, phase: info.phase, action: info.action, reason: info.reason,
|
|
564
595
|
agent_id: info.agentId,
|
|
@@ -601,7 +632,7 @@ class AgentEngine {
|
|
|
601
632
|
try {
|
|
602
633
|
const report = await this.contextManager.compact();
|
|
603
634
|
if (report && report.summarizedMessages + report.droppedMessages + report.truncatedToolResults > 0) {
|
|
604
|
-
this.
|
|
635
|
+
this.transport.emit({
|
|
605
636
|
type: 'system', level: 'info',
|
|
606
637
|
text: `[Context] ~${report.tokensBefore} → ~${report.tokensAfter} tokens ` +
|
|
607
638
|
`(truncated ${report.truncatedToolResults} tool results, summarized ${report.summarizedMessages}, dropped ${report.droppedMessages} messages)`,
|
|
@@ -610,7 +641,7 @@ class AgentEngine {
|
|
|
610
641
|
}
|
|
611
642
|
catch (err) {
|
|
612
643
|
// Compaction is best-effort: a bug here must never stop the agent.
|
|
613
|
-
this.
|
|
644
|
+
this.transport.emit({ type: 'system', level: 'warn', text: `[Context] Compaction failed: ${err instanceof Error ? err.message : String(err)}` });
|
|
614
645
|
}
|
|
615
646
|
}
|
|
616
647
|
this.trimHistory();
|
|
@@ -643,7 +674,7 @@ class AgentEngine {
|
|
|
643
674
|
}
|
|
644
675
|
if (!report || report.tokensAfter >= report.tokensBefore)
|
|
645
676
|
return false;
|
|
646
|
-
this.
|
|
677
|
+
this.transport.emit({
|
|
647
678
|
type: 'system', level: 'info',
|
|
648
679
|
text: `[Context] Provider reported context overflow: compacted ~${report.tokensBefore} → ~${report.tokensAfter} tokens, ` +
|
|
649
680
|
`budget now ~${cm.effectiveMaxTokens} tokens. Retrying.`,
|
|
@@ -665,7 +696,7 @@ class AgentEngine {
|
|
|
665
696
|
onDone: (msg) => resolve(msg.content ?? chunks.join('')),
|
|
666
697
|
onError: reject,
|
|
667
698
|
onMetrics: (inputTokens, outputTokens, usage) => {
|
|
668
|
-
this.
|
|
699
|
+
this.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
|
|
669
700
|
provider: cfg?.provider ?? this.opts.defaultProvider,
|
|
670
701
|
model: cfg?.model ?? provider.modelId, purpose: 'context_summary', startedAt,
|
|
671
702
|
}));
|
|
@@ -682,7 +713,7 @@ class AgentEngine {
|
|
|
682
713
|
return;
|
|
683
714
|
const dropped = this.history.trim(max);
|
|
684
715
|
if (dropped > 0) {
|
|
685
|
-
this.
|
|
716
|
+
this.transport.emit({
|
|
686
717
|
type: 'system',
|
|
687
718
|
level: 'warn',
|
|
688
719
|
text: `[ContextWindow] Dropped ${dropped} messages — history capped at ${max} (maxContextMessages)`,
|
|
@@ -711,7 +742,7 @@ class AgentEngine {
|
|
|
711
742
|
}
|
|
712
743
|
}
|
|
713
744
|
catch (err) {
|
|
714
|
-
this.
|
|
745
|
+
this.transport.emit({
|
|
715
746
|
type: 'system', level: 'warn',
|
|
716
747
|
text: `[AgentDiscovery] Failed to load agents: ${err.message}`,
|
|
717
748
|
});
|
|
@@ -746,6 +777,11 @@ class AgentEngine {
|
|
|
746
777
|
}
|
|
747
778
|
return parts.join('\n');
|
|
748
779
|
}
|
|
780
|
+
/** Opt-in (`emitSystemPrompt`): a system prompt can carry secrets and reaches every transport. */
|
|
781
|
+
emitSystemPrompt(agentId, text) {
|
|
782
|
+
if (this.opts.emitSystemPrompt)
|
|
783
|
+
this.transport.emit({ type: 'system_prompt', agent_id: agentId, text });
|
|
784
|
+
}
|
|
749
785
|
buildSystemPrompt(profile, hookSections = []) {
|
|
750
786
|
const isOrchestrator = profile.id === this.opts.defaultAgentId;
|
|
751
787
|
const parts = [profile.systemPrompt];
|
|
@@ -810,7 +846,7 @@ class AgentEngine {
|
|
|
810
846
|
const iterManager = this.iterationManager;
|
|
811
847
|
let overflowRetries = 0;
|
|
812
848
|
let hookContinues = 0;
|
|
813
|
-
this.
|
|
849
|
+
this.transport.emit({
|
|
814
850
|
type: 'block_start',
|
|
815
851
|
agent_id: profile.id,
|
|
816
852
|
agent_name: profile.name,
|
|
@@ -828,6 +864,7 @@ class AgentEngine {
|
|
|
828
864
|
role: 'system',
|
|
829
865
|
content: this.buildSystemPrompt(currentProfile, await this.hookPromptSections(currentProfile)),
|
|
830
866
|
};
|
|
867
|
+
this.emitSystemPrompt(currentProfile.id, systemMsg.content ?? '');
|
|
831
868
|
const tools = this.getToolsForAgent(currentProfile);
|
|
832
869
|
const safeHistory = this.history.sanitized();
|
|
833
870
|
if (this.contextManager) {
|
|
@@ -854,10 +891,10 @@ class AgentEngine {
|
|
|
854
891
|
if (holdOutput)
|
|
855
892
|
heldTokens.push(delta);
|
|
856
893
|
else
|
|
857
|
-
this.
|
|
894
|
+
this.transport.emit({ type: 'token', content: delta, agent_id: currentProfile.id });
|
|
858
895
|
},
|
|
859
896
|
onToolCall: (name, args, id) => {
|
|
860
|
-
this.
|
|
897
|
+
this.transport.emit({ type: 'tool_call', name, args_preview: args.slice(0, 200) });
|
|
861
898
|
if (name === 'ask_agent') {
|
|
862
899
|
try {
|
|
863
900
|
const parsed = JSON.parse(args);
|
|
@@ -880,12 +917,12 @@ class AgentEngine {
|
|
|
880
917
|
overflowError = err;
|
|
881
918
|
return;
|
|
882
919
|
}
|
|
883
|
-
this.
|
|
920
|
+
this.transport.emit({ type: 'error', message: err.message });
|
|
884
921
|
},
|
|
885
922
|
onMetrics: (inputTokens, outputTokens, usage) => {
|
|
886
923
|
// Anthropic reports cached tokens apart from input_tokens; the request still carried them.
|
|
887
924
|
this.contextManager?.observeUsage(inputTokens + (usage?.cacheReadTokens ?? 0) + (usage?.cacheWriteTokens ?? 0), this.lastRequestEstimate);
|
|
888
|
-
this.
|
|
925
|
+
this.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
|
|
889
926
|
agentId: currentProfile.id,
|
|
890
927
|
provider: currentProfile.provider ?? this.opts.defaultProvider,
|
|
891
928
|
model: currentProfile.model ?? chatProvider.modelId,
|
|
@@ -903,7 +940,7 @@ class AgentEngine {
|
|
|
903
940
|
overflowRetries++;
|
|
904
941
|
continue;
|
|
905
942
|
}
|
|
906
|
-
this.
|
|
943
|
+
this.transport.emit({ type: 'error', message: overflowError.message });
|
|
907
944
|
break;
|
|
908
945
|
}
|
|
909
946
|
if (!finalMessage)
|
|
@@ -915,7 +952,7 @@ class AgentEngine {
|
|
|
915
952
|
if (holdOutput) {
|
|
916
953
|
const shown = guardedOut.touched ? guardedOut.text : heldTokens.join('');
|
|
917
954
|
if (shown)
|
|
918
|
-
this.
|
|
955
|
+
this.transport.emit({ type: 'token', content: shown, agent_id: currentProfile.id });
|
|
919
956
|
}
|
|
920
957
|
this.history.push(finalMessage);
|
|
921
958
|
const toolResults = [];
|
|
@@ -928,7 +965,7 @@ class AgentEngine {
|
|
|
928
965
|
for (const call of selfCalls) {
|
|
929
966
|
const startedAt = Date.now();
|
|
930
967
|
const msg = `Self-delegation blocked: agent "${currentProfile.id}" cannot delegate to itself. Execute the task directly.`;
|
|
931
|
-
this.
|
|
968
|
+
this.transport.emit({ type: 'tool_result', name: 'ask_agent', agent_id: currentProfile.id, success: false, preview: msg });
|
|
932
969
|
toolResults.push({ role: 'tool', tool_call_id: call.id, content: msg });
|
|
933
970
|
await this.recordAudit({
|
|
934
971
|
startedAt, agentId: currentProfile.id, tool: 'ask_agent', rawArgs: delegationArgs(call),
|
|
@@ -949,7 +986,7 @@ class AgentEngine {
|
|
|
949
986
|
allowedCalls.push(call);
|
|
950
987
|
continue;
|
|
951
988
|
}
|
|
952
|
-
this.
|
|
989
|
+
this.transport.emit({ type: 'tool_result', name: 'ask_agent', agent_id: currentProfile.id, success: false, preview: verdict.message.slice(0, 120) });
|
|
953
990
|
toolResults.push({ role: 'tool', tool_call_id: call.id, content: verdict.message });
|
|
954
991
|
await this.recordAudit({
|
|
955
992
|
startedAt, agentId: currentProfile.id, chain: callerChain, tool: 'ask_agent',
|
|
@@ -973,7 +1010,7 @@ class AgentEngine {
|
|
|
973
1010
|
const call = validCalls[i];
|
|
974
1011
|
const result = results[i];
|
|
975
1012
|
const content = result.error ? `Error: ${result.error}` : result.content;
|
|
976
|
-
this.
|
|
1013
|
+
this.transport.emit({ type: 'tool_result', name: 'ask_agent', agent_id: currentProfile.id, success: !result.error, preview: content.slice(0, 120) });
|
|
977
1014
|
toolResults.push({ role: 'tool', tool_call_id: call.id, content });
|
|
978
1015
|
await this.recordAudit({
|
|
979
1016
|
startedAt, agentId: currentProfile.id, chain: callerChain, tool: 'ask_agent', rawArgs: delegationArgs(call),
|
|
@@ -1010,7 +1047,7 @@ class AgentEngine {
|
|
|
1010
1047
|
const results = await Promise.all(wave.map((call, i) => this.executeToolCall(call, currentProfile, 0, e => buffers[i].push(e), () => this.history.redactToolCallArgs(call.id))));
|
|
1011
1048
|
wave.forEach((call, i) => {
|
|
1012
1049
|
for (const e of buffers[i])
|
|
1013
|
-
this.
|
|
1050
|
+
this.transport.emit(e);
|
|
1014
1051
|
toolResults.push({ role: 'tool', tool_call_id: call.id, content: results[i] });
|
|
1015
1052
|
});
|
|
1016
1053
|
}
|
|
@@ -1022,7 +1059,7 @@ class AgentEngine {
|
|
|
1022
1059
|
break;
|
|
1023
1060
|
const cap = this.opts.maxHookContinues ?? hooks_1.DEFAULT_MAX_HOOK_CONTINUES;
|
|
1024
1061
|
if (hookContinues >= cap) {
|
|
1025
|
-
this.
|
|
1062
|
+
this.transport.emit({ type: 'system', level: 'warn', text: `[hooks] afterTurn asked for more than ${cap} extra passes; stopping` });
|
|
1026
1063
|
break;
|
|
1027
1064
|
}
|
|
1028
1065
|
hookContinues++;
|
|
@@ -1038,7 +1075,7 @@ class AgentEngine {
|
|
|
1038
1075
|
}
|
|
1039
1076
|
this.history.pushAll(toolResults);
|
|
1040
1077
|
}
|
|
1041
|
-
this.
|
|
1078
|
+
this.transport.emit({ type: 'block_end', status: 'ok', agent_id: profile.id });
|
|
1042
1079
|
}
|
|
1043
1080
|
async runAgentInternal(agentId, question, context, depth = 0, outputBuffer, chain) {
|
|
1044
1081
|
const profile = this.opts.agents.get(agentId);
|
|
@@ -1063,8 +1100,10 @@ class AgentEngine {
|
|
|
1063
1100
|
historySlice = [];
|
|
1064
1101
|
historySlice = (0, HistoryManager_1.sanitizeMessages)(historySlice);
|
|
1065
1102
|
}
|
|
1103
|
+
const systemText = this.buildSystemPrompt(profile, await this.hookPromptSections(profile));
|
|
1104
|
+
this.emitSystemPrompt(profile.id, systemText);
|
|
1066
1105
|
const messages = [
|
|
1067
|
-
{ role: 'system', content:
|
|
1106
|
+
{ role: 'system', content: systemText },
|
|
1068
1107
|
...historySlice,
|
|
1069
1108
|
{ role: 'user', content: context ? `${question}\n\nContext:\n${context}` : question },
|
|
1070
1109
|
];
|
|
@@ -1081,7 +1120,7 @@ class AgentEngine {
|
|
|
1081
1120
|
if (outputBuffer)
|
|
1082
1121
|
outputBuffer.push(event);
|
|
1083
1122
|
else
|
|
1084
|
-
this.
|
|
1123
|
+
this.transport.emit(event);
|
|
1085
1124
|
};
|
|
1086
1125
|
emit({ type: 'block_start', agent_id: profile.id, agent_name: profile.name, agent_icon: profile.icon });
|
|
1087
1126
|
// A sub-agent runs on a local message list that nothing used to bound or recover: a long tool loop
|
|
@@ -1248,7 +1287,7 @@ class AgentEngine {
|
|
|
1248
1287
|
...(d.mode ? { mode: d.mode } : {}), ...(d.network ? { network: d.network } : {}),
|
|
1249
1288
|
...(d.backend ? { backend: d.backend } : {}), ...(d.reason ? { reason: d.reason } : {}),
|
|
1250
1289
|
});
|
|
1251
|
-
this.
|
|
1290
|
+
this.transport.emit({
|
|
1252
1291
|
type: 'sandbox', outcome: d.outcome, tool: d.tool, agent_id: d.agentId,
|
|
1253
1292
|
...(d.mode ? { mode: d.mode } : {}), ...(d.network ? { network: d.network } : {}),
|
|
1254
1293
|
...(d.backend ? { backend: d.backend } : {}), ...(d.reason ? { reason: d.reason } : {}),
|
|
@@ -1272,13 +1311,14 @@ class AgentEngine {
|
|
|
1272
1311
|
chain,
|
|
1273
1312
|
/** Set only by `runApproved`: this exact call was approved and stored (resubmission, SPEC-0014 §6). */
|
|
1274
1313
|
approved) {
|
|
1275
|
-
const emitEvent = emit ?? ((e) => this.
|
|
1314
|
+
const emitEvent = emit ?? ((e) => this.transport.emit(e));
|
|
1276
1315
|
const callStart = Date.now();
|
|
1277
1316
|
const toolDef = this.opts.tools.get(call.name);
|
|
1278
1317
|
const principal = this.principalFor(profile.id, chain);
|
|
1279
1318
|
let result;
|
|
1280
1319
|
let success;
|
|
1281
1320
|
let outcome;
|
|
1321
|
+
let errorCode;
|
|
1282
1322
|
let sandboxRefusal;
|
|
1283
1323
|
// What the single audit event of this call records (SPEC-0014 F1).
|
|
1284
1324
|
let decision = 'allow';
|
|
@@ -1352,7 +1392,7 @@ class AgentEngine {
|
|
|
1352
1392
|
const hookCtx = toolHooks ? this.toolHookContext(principal) : undefined;
|
|
1353
1393
|
if (hookCall && hookCtx)
|
|
1354
1394
|
await (0, hooks_1.runHooks)(this.hooks, 'beforeTool', h => h.beforeTool(hookCtx, hookCall));
|
|
1355
|
-
({ result, success, outcome } = await this.runToolDef(effective, toolDef, profile.id, depth, sandboxDecisions, principal, verdict.mode === 'dry_run'));
|
|
1395
|
+
({ result, success, outcome, errorCode } = await this.runToolDef(effective, toolDef, profile.id, depth, sandboxDecisions, principal, verdict.mode === 'dry_run'));
|
|
1356
1396
|
if (this.guardrails?.has('tool_result')) {
|
|
1357
1397
|
const checked = await this.guard('tool_result', result, profile.id, call.name);
|
|
1358
1398
|
result = checked.blocked
|
|
@@ -1377,6 +1417,7 @@ class AgentEngine {
|
|
|
1377
1417
|
decision,
|
|
1378
1418
|
reason,
|
|
1379
1419
|
outcome: ran ? (outcome ?? (success ? 'ok' : 'error')) : undefined,
|
|
1420
|
+
...(errorCode ? { errorCode } : {}),
|
|
1380
1421
|
approval,
|
|
1381
1422
|
sandbox: sandboxDecisions,
|
|
1382
1423
|
meta: toolDef?.meta,
|
|
@@ -1388,6 +1429,7 @@ class AgentEngine {
|
|
|
1388
1429
|
type: 'tool_result', name: call.name, success, preview: cleanPreview.slice(0, 120),
|
|
1389
1430
|
agent_id: profile.id, started_at: callStart, duration_ms: Date.now() - callStart,
|
|
1390
1431
|
...(outcome ? { outcome } : {}),
|
|
1432
|
+
...(errorCode ? { error_code: errorCode } : {}),
|
|
1391
1433
|
});
|
|
1392
1434
|
return result;
|
|
1393
1435
|
}
|
|
@@ -1462,7 +1504,7 @@ class AgentEngine {
|
|
|
1462
1504
|
createdAt: new Date().toISOString(),
|
|
1463
1505
|
};
|
|
1464
1506
|
if (this.approver) {
|
|
1465
|
-
this.
|
|
1507
|
+
this.transport.emit({
|
|
1466
1508
|
type: 'tool_approval_request', tool_name: name, agent_id: principal.agentId,
|
|
1467
1509
|
args_preview: JSON.stringify(call.args).slice(0, 200),
|
|
1468
1510
|
});
|
|
@@ -1535,7 +1577,8 @@ class AgentEngine {
|
|
|
1535
1577
|
return { result: await toolDef.execute(args, ctx), success: true };
|
|
1536
1578
|
}
|
|
1537
1579
|
catch (err) {
|
|
1538
|
-
|
|
1580
|
+
const errorCode = (0, error_code_1.errorCodeOf)(err);
|
|
1581
|
+
return { result: `Error: ${err instanceof Error ? err.message : String(err)}`, success: false, ...(errorCode ? { errorCode } : {}) };
|
|
1539
1582
|
}
|
|
1540
1583
|
})();
|
|
1541
1584
|
// A result that arrives after we gave up on the call is dropped, never an unhandled rejection.
|
|
@@ -1626,6 +1669,7 @@ class AgentEngine {
|
|
|
1626
1669
|
decision: c.decision,
|
|
1627
1670
|
...(c.reason !== undefined ? { reason: c.reason } : {}),
|
|
1628
1671
|
...(c.outcome !== undefined ? { outcome: c.outcome } : {}),
|
|
1672
|
+
...(c.errorCode ? { errorCode: c.errorCode } : {}),
|
|
1629
1673
|
durationMs: Date.now() - c.startedAt,
|
|
1630
1674
|
...(c.approval ? { approval: c.approval } : {}),
|
|
1631
1675
|
...(c.sandbox && c.sandbox.length > 0 ? { sandbox: c.sandbox } : {}),
|
|
@@ -1656,7 +1700,7 @@ class AgentEngine {
|
|
|
1656
1700
|
return result.content;
|
|
1657
1701
|
},
|
|
1658
1702
|
emitCompacting: (phase, label) => {
|
|
1659
|
-
this.
|
|
1703
|
+
this.transport.emit({ type: 'compacting', phase, label });
|
|
1660
1704
|
},
|
|
1661
1705
|
llmCall: async (prompt) => {
|
|
1662
1706
|
const profile = this.opts.agents.get(id);
|