@backendkit-labs/agent-core 0.27.1 → 0.29.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 +1262 -1168
- package/dist/engine/AgentEngine.d.ts +25 -0
- package/dist/engine/AgentEngine.d.ts.map +1 -1
- package/dist/engine/AgentEngine.js +365 -27
- package/dist/engine/AgentEngine.js.map +1 -1
- package/dist/engine/ContextManager.d.ts +106 -0
- package/dist/engine/ContextManager.d.ts.map +1 -0
- package/dist/engine/ContextManager.js +257 -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/contextOverflow.d.ts +7 -0
- package/dist/engine/contextOverflow.d.ts.map +1 -0
- package/dist/engine/contextOverflow.js +40 -0
- package/dist/engine/contextOverflow.js.map +1 -0
- package/dist/engine/createBaseEngine.d.ts +43 -0
- package/dist/engine/createBaseEngine.d.ts.map +1 -1
- package/dist/engine/createBaseEngine.js +13 -0
- package/dist/engine/createBaseEngine.js.map +1 -1
- package/dist/engine/secrets.d.ts +9 -0
- package/dist/engine/secrets.d.ts.map +1 -0
- package/dist/engine/secrets.js +24 -0
- package/dist/engine/secrets.js.map +1 -0
- 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 +9 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +28 -4
- package/dist/index.js.map +1 -1
- package/dist/jobs/JobRegistry.d.ts +53 -0
- package/dist/jobs/JobRegistry.d.ts.map +1 -0
- package/dist/jobs/JobRegistry.js +121 -0
- package/dist/jobs/JobRegistry.js.map +1 -0
- package/dist/jobs/tools.d.ts +5 -0
- package/dist/jobs/tools.d.ts.map +1 -0
- package/dist/jobs/tools.js +51 -0
- package/dist/jobs/tools.js.map +1 -0
- package/dist/mcp/MCPClientManager.js +2 -2
- package/dist/mcp/MCPClientManager.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 +2 -0
- package/dist/observability/ObservabilityManager.d.ts.map +1 -1
- package/dist/observability/ObservabilityManager.js +45 -0
- 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/tools/defineTool.d.ts +2 -0
- package/dist/tools/defineTool.d.ts.map +1 -1
- package/dist/tools/defineTool.js +1 -0
- package/dist/tools/defineTool.js.map +1 -1
- package/dist/types/index.d.ts +97 -6
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +87 -87
|
@@ -97,10 +97,16 @@ export declare class AgentEngine {
|
|
|
97
97
|
private readonly bus;
|
|
98
98
|
private readonly skillActivator;
|
|
99
99
|
private readonly history;
|
|
100
|
+
private readonly contextManager?;
|
|
101
|
+
private readonly guardrails?;
|
|
102
|
+
/** Uncalibrated token estimate of the last request sent by runLoop, to calibrate against real usage. */
|
|
103
|
+
private lastRequestEstimate;
|
|
100
104
|
private readonly auditLogger;
|
|
101
105
|
private currentAgentId;
|
|
102
106
|
private aborted;
|
|
103
107
|
private abortController;
|
|
108
|
+
/** One controller per tool call in flight (main agent and sub-agents); see `runToolDef`. */
|
|
109
|
+
private readonly toolControllers;
|
|
104
110
|
private allSkills;
|
|
105
111
|
private iterationManager;
|
|
106
112
|
private activeSkillAddition;
|
|
@@ -180,6 +186,25 @@ export declare class AgentEngine {
|
|
|
180
186
|
/** Delete persisted history file and reset in-memory conversation. */
|
|
181
187
|
clearHistory(): void;
|
|
182
188
|
private saveHistory;
|
|
189
|
+
/**
|
|
190
|
+
* Runs the guardrails of `phase` over `content`, reports what happened (transport event + audit log)
|
|
191
|
+
* and returns the outcome. `replacement` lets output checks attach the corrected text to the event.
|
|
192
|
+
*/
|
|
193
|
+
private guard;
|
|
194
|
+
/** Checks a model answer. Returns the (possibly corrected) message and the text to show. */
|
|
195
|
+
private guardOutput;
|
|
196
|
+
private blockedText;
|
|
197
|
+
/** Token-aware compaction first (when configured), then the message-count cap. */
|
|
198
|
+
private prepareContext;
|
|
199
|
+
/** Tells the model about background jobs that ended since the last iteration, once each. */
|
|
200
|
+
private announceFinishedJobs;
|
|
201
|
+
/**
|
|
202
|
+
* The provider said the request did not fit: shrink the budget and force a compaction.
|
|
203
|
+
* True when the history got smaller, so repeating the call can succeed.
|
|
204
|
+
*/
|
|
205
|
+
private recoverFromOverflow;
|
|
206
|
+
/** One summarization call, billed through `metrics` events like any other LLM call. */
|
|
207
|
+
private summarizeForContext;
|
|
183
208
|
private trimHistory;
|
|
184
209
|
private ensureAgentsLoaded;
|
|
185
210
|
private _loadAgentsOnce;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentEngine.d.ts","sourceRoot":"","sources":["../../src/engine/AgentEng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O,CAAC,mBAAmB;IA4B3B,OAAO,CAAC,WAAW;YAaL,kBAAkB;YASlB,eAAe;IAkB7B,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAKlC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,gBAAgB;IAuBxB,OAAO,CAAC,iBAAiB;IAwBzB;;;;OAIG;IACH,OAAO,CAAC,uBAAuB;IAoC/B,OAAO,CAAC,kBAAkB;IAU1B,OAAO,CAAC,gBAAgB;IAexB;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;YASd,OAAO;YAuOP,gBAAgB;IAqH9B;;;;OAIG;YACW,eAAe;IA2E7B,wFAAwF;IACxF,OAAO,CAAC,SAAS,CAAuC;IACxD,OAAO,CAAC,eAAe;YAMT,UAAU;IA4DxB;;;;;;;;OAQG;IACH,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAI7C,wEAAwE;IACxE,mBAAmB,IAAI,IAAI;IAE3B,8DAA8D;IAC9D,kBAAkB,IAAI,IAAI;IAG1B,OAAO,CAAC,YAAY;CA2CvB"}
|
|
@@ -4,6 +4,10 @@ exports.AgentEngine = void 0;
|
|
|
4
4
|
const ApprovalGate_1 = require("./ApprovalGate");
|
|
5
5
|
const AuditLogger_1 = require("./AuditLogger");
|
|
6
6
|
const HistoryManager_1 = require("./HistoryManager");
|
|
7
|
+
const ContextManager_1 = require("./ContextManager");
|
|
8
|
+
const secrets_1 = require("./secrets");
|
|
9
|
+
const contextOverflow_1 = require("./contextOverflow");
|
|
10
|
+
const GuardrailRunner_1 = require("../guardrails/GuardrailRunner");
|
|
7
11
|
const MCPRegistrar_1 = require("./MCPRegistrar");
|
|
8
12
|
const DelegationBus_1 = require("../delegation/DelegationBus");
|
|
9
13
|
const SessionMemory_1 = require("../memory/SessionMemory");
|
|
@@ -29,12 +33,18 @@ const ASK_AGENT_TOOL = {
|
|
|
29
33
|
execute: async () => '',
|
|
30
34
|
};
|
|
31
35
|
const generateObject_1 = require("../structured/generateObject");
|
|
36
|
+
const MAX_OVERFLOW_RETRIES = 2;
|
|
32
37
|
/** `metrics` event; cache fields are included only when the provider reported them. */
|
|
33
|
-
function metricsEvent(inputTokens, outputTokens, usage) {
|
|
38
|
+
function metricsEvent(inputTokens, outputTokens, usage, extra) {
|
|
34
39
|
return {
|
|
35
40
|
type: 'metrics',
|
|
36
41
|
input_tokens: inputTokens,
|
|
37
42
|
output_tokens: outputTokens,
|
|
43
|
+
...(extra?.agentId ? { agent_id: extra.agentId } : {}),
|
|
44
|
+
...(extra?.provider ? { provider: extra.provider } : {}),
|
|
45
|
+
...(extra?.model ? { model: extra.model } : {}),
|
|
46
|
+
...(extra?.purpose ? { purpose: extra.purpose } : {}),
|
|
47
|
+
...(extra?.startedAt !== undefined ? { started_at: extra.startedAt, duration_ms: Math.max(0, Date.now() - extra.startedAt) } : {}),
|
|
38
48
|
...(usage?.cacheReadTokens !== undefined ? { cache_read_tokens: usage.cacheReadTokens } : {}),
|
|
39
49
|
...(usage?.cacheWriteTokens !== undefined ? { cache_write_tokens: usage.cacheWriteTokens } : {}),
|
|
40
50
|
};
|
|
@@ -45,10 +55,16 @@ class AgentEngine {
|
|
|
45
55
|
bus;
|
|
46
56
|
skillActivator = new activator_1.SkillActivator();
|
|
47
57
|
history;
|
|
58
|
+
contextManager;
|
|
59
|
+
guardrails;
|
|
60
|
+
/** Uncalibrated token estimate of the last request sent by runLoop, to calibrate against real usage. */
|
|
61
|
+
lastRequestEstimate = 0;
|
|
48
62
|
auditLogger;
|
|
49
63
|
currentAgentId;
|
|
50
64
|
aborted = false;
|
|
51
65
|
abortController = null;
|
|
66
|
+
/** One controller per tool call in flight (main agent and sub-agents); see `runToolDef`. */
|
|
67
|
+
toolControllers = new Set();
|
|
52
68
|
allSkills;
|
|
53
69
|
iterationManager;
|
|
54
70
|
activeSkillAddition = '';
|
|
@@ -70,6 +86,15 @@ class AgentEngine {
|
|
|
70
86
|
historyPath: opts.historyPath,
|
|
71
87
|
maxContextMessages: opts.maxContextMessages,
|
|
72
88
|
});
|
|
89
|
+
if (opts.guardrails?.length)
|
|
90
|
+
this.guardrails = new GuardrailRunner_1.GuardrailRunner(opts.guardrails);
|
|
91
|
+
if (opts.context) {
|
|
92
|
+
this.contextManager = new ContextManager_1.ContextManager(opts.context, {
|
|
93
|
+
history: this.history,
|
|
94
|
+
summarize: (transcript, previous) => this.summarizeForContext(transcript, previous),
|
|
95
|
+
emit: (event) => this.opts.transport.emit(event),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
73
98
|
this.auditLogger = new AuditLogger_1.AuditLogger(opts.auditLog);
|
|
74
99
|
this.mcpRegistrar = new MCPRegistrar_1.MCPRegistrar({
|
|
75
100
|
mcpManager: opts.mcpManager,
|
|
@@ -104,12 +129,18 @@ class AgentEngine {
|
|
|
104
129
|
const profile = this.opts.agents.get(agentId);
|
|
105
130
|
if (!profile)
|
|
106
131
|
throw new Error(`Agent "${agentId}" not registered`);
|
|
107
|
-
|
|
132
|
+
const provider = this.getProviderForProfile(profile);
|
|
133
|
+
let attemptStart = Date.now();
|
|
134
|
+
return (0, generateObject_1.generateObject)(provider, prompt, schema, {
|
|
108
135
|
retries: opts.retries,
|
|
109
136
|
name: opts.name,
|
|
110
137
|
model: profile.model,
|
|
111
138
|
onMetrics: (inputTokens, outputTokens, usage) => {
|
|
112
|
-
this.opts.transport.emit(metricsEvent(inputTokens, outputTokens, usage
|
|
139
|
+
this.opts.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
|
|
140
|
+
agentId, provider: profile.provider ?? this.opts.defaultProvider,
|
|
141
|
+
model: profile.model ?? provider.modelId, purpose: 'structured_output', startedAt: attemptStart,
|
|
142
|
+
}));
|
|
143
|
+
attemptStart = Date.now();
|
|
113
144
|
},
|
|
114
145
|
});
|
|
115
146
|
}
|
|
@@ -248,6 +279,18 @@ class AgentEngine {
|
|
|
248
279
|
this.opts.transport.emit({ type: 'done' });
|
|
249
280
|
return;
|
|
250
281
|
}
|
|
282
|
+
if (this.guardrails?.has('input')) {
|
|
283
|
+
const checked = await this.guard('input', input, this.currentAgentId);
|
|
284
|
+
if (checked.blocked) {
|
|
285
|
+
this.opts.transport.emit({
|
|
286
|
+
type: 'error',
|
|
287
|
+
message: `Input blocked by guardrail "${checked.blocked.guardrail}": ${checked.blocked.reason}`,
|
|
288
|
+
});
|
|
289
|
+
this.opts.transport.emit({ type: 'done' });
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
input = checked.content;
|
|
293
|
+
}
|
|
251
294
|
await this.mcpRegistrar.ensureInitialized();
|
|
252
295
|
await this.ensureAgentsLoaded();
|
|
253
296
|
// Direct MCP routing: bypass general when input matches a configured trigger
|
|
@@ -330,8 +373,13 @@ class AgentEngine {
|
|
|
330
373
|
}
|
|
331
374
|
abort() {
|
|
332
375
|
this.aborted = true;
|
|
376
|
+
void this.opts.jobs?.cancelAll();
|
|
333
377
|
this.abortController?.abort();
|
|
334
378
|
this.abortController = null;
|
|
379
|
+
// Tools already running get their signal too; each one winds down (or is given up on after
|
|
380
|
+
// the grace period) and the model is told the call was aborted.
|
|
381
|
+
for (const controller of [...this.toolControllers])
|
|
382
|
+
controller.abort('aborted');
|
|
335
383
|
}
|
|
336
384
|
/** Change the iteration mode at runtime — takes effect on the next run(). */
|
|
337
385
|
setIterationMode(mode) {
|
|
@@ -348,6 +396,141 @@ class AgentEngine {
|
|
|
348
396
|
saveHistory() {
|
|
349
397
|
this.history.save();
|
|
350
398
|
}
|
|
399
|
+
/**
|
|
400
|
+
* Runs the guardrails of `phase` over `content`, reports what happened (transport event + audit log)
|
|
401
|
+
* and returns the outcome. `replacement` lets output checks attach the corrected text to the event.
|
|
402
|
+
*/
|
|
403
|
+
async guard(phase, content, agentId, toolName, replacement) {
|
|
404
|
+
if (!this.guardrails?.has(phase))
|
|
405
|
+
return { content, changed: false, events: [] };
|
|
406
|
+
const sessionId = this.opts.sessionId ?? 'default';
|
|
407
|
+
const resolved = await Promise.all(this.opts.agents.getAll().map(async (a) => [a.id, await (0, secrets_1.resolveSecrets)(a, this.opts.secretResolver)]));
|
|
408
|
+
const secrets = resolved.find(([id]) => id === agentId)?.[1];
|
|
409
|
+
const secretValues = resolved.flatMap(([, r]) => Object.values(r));
|
|
410
|
+
const outcome = await this.guardrails.run({
|
|
411
|
+
phase, agentId, sessionId, content,
|
|
412
|
+
...(toolName ? { toolName } : {}),
|
|
413
|
+
...(secrets && Object.keys(secrets).length ? { secrets } : {}),
|
|
414
|
+
secretValues,
|
|
415
|
+
});
|
|
416
|
+
const replaced = replacement?.(outcome);
|
|
417
|
+
outcome.events.forEach((info, i) => {
|
|
418
|
+
this.opts.transport.emit({
|
|
419
|
+
type: 'guardrail',
|
|
420
|
+
name: info.name, phase: info.phase, action: info.action, reason: info.reason,
|
|
421
|
+
agent_id: info.agentId,
|
|
422
|
+
...(info.tool ? { tool: info.tool } : {}),
|
|
423
|
+
...(info.dryRun ? { dry_run: true } : {}),
|
|
424
|
+
...(replaced !== undefined && !info.dryRun && i === outcome.events.length - 1 ? { replacement: replaced } : {}),
|
|
425
|
+
});
|
|
426
|
+
void this.auditLogger.log({
|
|
427
|
+
agentId: info.agentId,
|
|
428
|
+
tool: `guardrail:${info.phase}:${info.name}`,
|
|
429
|
+
inputPreview: `${info.action}${info.dryRun ? ' (dry-run)' : ''}: ${info.reason}`,
|
|
430
|
+
success: info.action === 'redact',
|
|
431
|
+
durationMs: 0,
|
|
432
|
+
sessionId,
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
return outcome;
|
|
436
|
+
}
|
|
437
|
+
/** Checks a model answer. Returns the (possibly corrected) message and the text to show. */
|
|
438
|
+
async guardOutput(message, agentId) {
|
|
439
|
+
const original = message.content ?? '';
|
|
440
|
+
if (!original || !this.guardrails?.has('output'))
|
|
441
|
+
return { message, text: original, touched: false };
|
|
442
|
+
const buffered = this.opts.guardrailOutputMode === 'buffer';
|
|
443
|
+
const outcome = await this.guard('output', original, agentId, undefined, buffered ? undefined : (o) => o.blocked ? this.blockedText(o) : (o.changed ? o.content : undefined));
|
|
444
|
+
if (outcome.blocked) {
|
|
445
|
+
const text = this.blockedText(outcome);
|
|
446
|
+
return { message: { ...message, content: text }, text, touched: true };
|
|
447
|
+
}
|
|
448
|
+
if (outcome.changed)
|
|
449
|
+
return { message: { ...message, content: outcome.content }, text: outcome.content, touched: true };
|
|
450
|
+
return { message, text: original, touched: false };
|
|
451
|
+
}
|
|
452
|
+
blockedText(outcome) {
|
|
453
|
+
return `[Response withheld by guardrail "${outcome.blocked?.guardrail}": ${outcome.blocked?.reason}]`;
|
|
454
|
+
}
|
|
455
|
+
/** Token-aware compaction first (when configured), then the message-count cap. */
|
|
456
|
+
async prepareContext() {
|
|
457
|
+
if (this.contextManager) {
|
|
458
|
+
try {
|
|
459
|
+
const report = await this.contextManager.compact();
|
|
460
|
+
if (report && report.summarizedMessages + report.droppedMessages + report.truncatedToolResults > 0) {
|
|
461
|
+
this.opts.transport.emit({
|
|
462
|
+
type: 'system', level: 'info',
|
|
463
|
+
text: `[Context] ~${report.tokensBefore} → ~${report.tokensAfter} tokens ` +
|
|
464
|
+
`(truncated ${report.truncatedToolResults} tool results, summarized ${report.summarizedMessages}, dropped ${report.droppedMessages} messages)`,
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
catch (err) {
|
|
469
|
+
// Compaction is best-effort: a bug here must never stop the agent.
|
|
470
|
+
this.opts.transport.emit({ type: 'system', level: 'warn', text: `[Context] Compaction failed: ${err instanceof Error ? err.message : String(err)}` });
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
this.trimHistory();
|
|
474
|
+
}
|
|
475
|
+
/** Tells the model about background jobs that ended since the last iteration, once each. */
|
|
476
|
+
announceFinishedJobs(agentId) {
|
|
477
|
+
const finished = this.opts.jobs?.drainFinished(agentId) ?? [];
|
|
478
|
+
for (const job of finished) {
|
|
479
|
+
this.history.push({
|
|
480
|
+
role: 'user',
|
|
481
|
+
content: `[Background job ${job.id} finished (${job.status}). Use job_output to read it.]`,
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* The provider said the request did not fit: shrink the budget and force a compaction.
|
|
487
|
+
* True when the history got smaller, so repeating the call can succeed.
|
|
488
|
+
*/
|
|
489
|
+
async recoverFromOverflow() {
|
|
490
|
+
const cm = this.contextManager;
|
|
491
|
+
if (!cm)
|
|
492
|
+
return false;
|
|
493
|
+
cm.noteOverflow();
|
|
494
|
+
let report;
|
|
495
|
+
try {
|
|
496
|
+
report = await cm.compact({ force: true, targetRatio: 0.5 });
|
|
497
|
+
}
|
|
498
|
+
catch {
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
if (!report || report.tokensAfter >= report.tokensBefore)
|
|
502
|
+
return false;
|
|
503
|
+
this.opts.transport.emit({
|
|
504
|
+
type: 'system', level: 'info',
|
|
505
|
+
text: `[Context] Provider reported context overflow: compacted ~${report.tokensBefore} → ~${report.tokensAfter} tokens, ` +
|
|
506
|
+
`budget now ~${cm.effectiveMaxTokens} tokens. Retrying.`,
|
|
507
|
+
});
|
|
508
|
+
return true;
|
|
509
|
+
}
|
|
510
|
+
/** One summarization call, billed through `metrics` events like any other LLM call. */
|
|
511
|
+
summarizeForContext(transcript, previousSummary) {
|
|
512
|
+
const cfg = this.opts.context?.summarizer;
|
|
513
|
+
const provider = this.opts.providers.resolve(cfg?.provider, this.opts.defaultProvider);
|
|
514
|
+
const startedAt = Date.now();
|
|
515
|
+
return new Promise((resolve, reject) => {
|
|
516
|
+
const chunks = [];
|
|
517
|
+
Promise.resolve(provider.chat([
|
|
518
|
+
{ role: 'system', content: ContextManager_1.SUMMARY_SYSTEM_PROMPT },
|
|
519
|
+
{ role: 'user', content: (0, ContextManager_1.buildSummaryPrompt)(transcript, previousSummary) },
|
|
520
|
+
], [], {
|
|
521
|
+
onChunk: (delta) => { chunks.push(delta); },
|
|
522
|
+
onDone: (msg) => resolve(msg.content ?? chunks.join('')),
|
|
523
|
+
onError: reject,
|
|
524
|
+
onMetrics: (inputTokens, outputTokens, usage) => {
|
|
525
|
+
this.opts.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
|
|
526
|
+
provider: cfg?.provider ?? this.opts.defaultProvider,
|
|
527
|
+
model: cfg?.model ?? provider.modelId, purpose: 'context_summary', startedAt,
|
|
528
|
+
}));
|
|
529
|
+
},
|
|
530
|
+
...(cfg?.model ? { model: cfg.model } : {}),
|
|
531
|
+
})).catch(reject);
|
|
532
|
+
});
|
|
533
|
+
}
|
|
351
534
|
trimHistory() {
|
|
352
535
|
const max = this.opts.maxContextMessages;
|
|
353
536
|
if (!max)
|
|
@@ -520,6 +703,7 @@ class AgentEngine {
|
|
|
520
703
|
let currentProfile = profile;
|
|
521
704
|
this.iterationManager.reset();
|
|
522
705
|
const iterManager = this.iterationManager;
|
|
706
|
+
let overflowRetries = 0;
|
|
523
707
|
this.opts.transport.emit({
|
|
524
708
|
type: 'block_start',
|
|
525
709
|
agent_id: profile.id,
|
|
@@ -532,20 +716,36 @@ class AgentEngine {
|
|
|
532
716
|
const shouldContinue = await iterManager.advance();
|
|
533
717
|
if (!shouldContinue)
|
|
534
718
|
break;
|
|
535
|
-
this.
|
|
719
|
+
this.announceFinishedJobs(currentProfile.id);
|
|
720
|
+
await this.prepareContext();
|
|
536
721
|
const systemMsg = { role: 'system', content: this.buildSystemPrompt(currentProfile, orchestrationResult) };
|
|
537
722
|
const tools = this.getToolsForAgent(currentProfile);
|
|
538
723
|
const safeHistory = this.history.sanitized();
|
|
724
|
+
if (this.contextManager) {
|
|
725
|
+
this.lastRequestEstimate =
|
|
726
|
+
this.contextManager.estimateText(systemMsg.content ?? '') +
|
|
727
|
+
this.contextManager.estimateText(JSON.stringify(tools.map(t => [t.name, t.description, t.parameters]))) +
|
|
728
|
+
this.contextManager.estimateRaw(safeHistory);
|
|
729
|
+
}
|
|
539
730
|
let streamBuffer = '';
|
|
731
|
+
// `buffer` mode: hold tokens until the output guardrails have seen the whole answer.
|
|
732
|
+
const holdOutput = !!this.guardrails?.has('output') && this.opts.guardrailOutputMode === 'buffer';
|
|
733
|
+
const heldTokens = [];
|
|
540
734
|
const askAgentCalls = [];
|
|
541
735
|
const otherCalls = [];
|
|
542
736
|
let finalMessage = null;
|
|
737
|
+
let overflowError = null;
|
|
543
738
|
this.abortController = new AbortController();
|
|
544
739
|
const signal = this.abortController.signal;
|
|
545
|
-
|
|
740
|
+
const chatProvider = this.getProviderForProfile(currentProfile);
|
|
741
|
+
const llmStartedAt = Date.now();
|
|
742
|
+
await chatProvider.chat([systemMsg, ...safeHistory], tools, {
|
|
546
743
|
onChunk: (delta) => {
|
|
547
744
|
streamBuffer += delta;
|
|
548
|
-
|
|
745
|
+
if (holdOutput)
|
|
746
|
+
heldTokens.push(delta);
|
|
747
|
+
else
|
|
748
|
+
this.opts.transport.emit({ type: 'token', content: delta, agent_id: currentProfile.id });
|
|
549
749
|
},
|
|
550
750
|
onToolCall: (name, args, id) => {
|
|
551
751
|
this.opts.transport.emit({ type: 'tool_call', name, args_preview: args.slice(0, 200) });
|
|
@@ -564,11 +764,24 @@ class AgentEngine {
|
|
|
564
764
|
},
|
|
565
765
|
onDone: (msg) => { finalMessage = msg; },
|
|
566
766
|
onError: (err) => {
|
|
567
|
-
if (
|
|
568
|
-
|
|
767
|
+
if (this.aborted)
|
|
768
|
+
return;
|
|
769
|
+
// Held back: the loop below may recover by compacting and retrying.
|
|
770
|
+
if (this.contextManager && this.opts.context?.overflowRetry !== false && (0, contextOverflow_1.isContextOverflowError)(err)) {
|
|
771
|
+
overflowError = err;
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
this.opts.transport.emit({ type: 'error', message: err.message });
|
|
569
775
|
},
|
|
570
776
|
onMetrics: (inputTokens, outputTokens, usage) => {
|
|
571
|
-
|
|
777
|
+
// Anthropic reports cached tokens apart from input_tokens; the request still carried them.
|
|
778
|
+
this.contextManager?.observeUsage(inputTokens + (usage?.cacheReadTokens ?? 0) + (usage?.cacheWriteTokens ?? 0), this.lastRequestEstimate);
|
|
779
|
+
this.opts.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
|
|
780
|
+
agentId: currentProfile.id,
|
|
781
|
+
provider: currentProfile.provider ?? this.opts.defaultProvider,
|
|
782
|
+
model: currentProfile.model ?? chatProvider.modelId,
|
|
783
|
+
startedAt: llmStartedAt,
|
|
784
|
+
}));
|
|
572
785
|
},
|
|
573
786
|
signal,
|
|
574
787
|
model: currentProfile.model,
|
|
@@ -576,8 +789,25 @@ class AgentEngine {
|
|
|
576
789
|
this.abortController = null;
|
|
577
790
|
if (this.aborted)
|
|
578
791
|
break;
|
|
792
|
+
if (!finalMessage && overflowError) {
|
|
793
|
+
if (overflowRetries < MAX_OVERFLOW_RETRIES && await this.recoverFromOverflow()) {
|
|
794
|
+
overflowRetries++;
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
this.opts.transport.emit({ type: 'error', message: overflowError.message });
|
|
798
|
+
break;
|
|
799
|
+
}
|
|
579
800
|
if (!finalMessage)
|
|
580
801
|
break;
|
|
802
|
+
const guardedOut = await this.guardOutput(finalMessage, currentProfile.id);
|
|
803
|
+
finalMessage = guardedOut.message;
|
|
804
|
+
if (guardedOut.touched)
|
|
805
|
+
streamBuffer = guardedOut.text;
|
|
806
|
+
if (holdOutput) {
|
|
807
|
+
const shown = guardedOut.touched ? guardedOut.text : heldTokens.join('');
|
|
808
|
+
if (shown)
|
|
809
|
+
this.opts.transport.emit({ type: 'token', content: shown, agent_id: currentProfile.id });
|
|
810
|
+
}
|
|
581
811
|
this.history.push(finalMessage);
|
|
582
812
|
const toolResults = [];
|
|
583
813
|
// ── ask_agent: parallel if 2+ calls ──────────────────────────────
|
|
@@ -626,13 +856,13 @@ class AgentEngine {
|
|
|
626
856
|
for (let i = 0; i < wave.length; i++)
|
|
627
857
|
iterManager.recordToolCall();
|
|
628
858
|
if (wave.length === 1) {
|
|
629
|
-
const result = await this.executeToolCall(first, currentProfile, 0);
|
|
859
|
+
const result = await this.executeToolCall(first, currentProfile, 0, undefined, () => this.history.redactToolCallArgs(first.id));
|
|
630
860
|
toolResults.push({ role: 'tool', tool_call_id: first.id, content: result });
|
|
631
861
|
continue;
|
|
632
862
|
}
|
|
633
863
|
// Parallel wave: events buffered per call, flushed in call order.
|
|
634
864
|
const buffers = wave.map(() => []);
|
|
635
|
-
const results = await Promise.all(wave.map((call, i) => this.executeToolCall(call, currentProfile, 0, e => buffers[i].push(e))));
|
|
865
|
+
const results = await Promise.all(wave.map((call, i) => this.executeToolCall(call, currentProfile, 0, e => buffers[i].push(e), () => this.history.redactToolCallArgs(call.id))));
|
|
636
866
|
wave.forEach((call, i) => {
|
|
637
867
|
for (const e of buffers[i])
|
|
638
868
|
this.opts.transport.emit(e);
|
|
@@ -725,12 +955,18 @@ class AgentEngine {
|
|
|
725
955
|
while (iter < maxIter && !this.aborted) {
|
|
726
956
|
iter++;
|
|
727
957
|
let streamContent = '';
|
|
958
|
+
const holdOutput = !!this.guardrails?.has('output') && this.opts.guardrailOutputMode === 'buffer';
|
|
959
|
+
const heldTokens = [];
|
|
728
960
|
const toolCalls = [];
|
|
729
961
|
let finalMessage = null;
|
|
730
|
-
|
|
962
|
+
const chatProvider = this.getProviderForProfile(profile);
|
|
963
|
+
const llmStartedAt = Date.now();
|
|
964
|
+
await chatProvider.chat(messages, this.getToolsForAgent(profile), {
|
|
731
965
|
onChunk: (delta) => {
|
|
732
966
|
streamContent += delta;
|
|
733
|
-
if (
|
|
967
|
+
if (holdOutput)
|
|
968
|
+
heldTokens.push(delta);
|
|
969
|
+
else if (!profile.suppressDefaultOutput) {
|
|
734
970
|
emit({ type: 'token', content: delta, agent_id: profile.id });
|
|
735
971
|
}
|
|
736
972
|
},
|
|
@@ -745,12 +981,26 @@ class AgentEngine {
|
|
|
745
981
|
onMetrics: (inputTokens, outputTokens, usage) => {
|
|
746
982
|
totalInputTokens += inputTokens;
|
|
747
983
|
totalOutputTokens += outputTokens;
|
|
748
|
-
emit(metricsEvent(inputTokens, outputTokens, usage
|
|
984
|
+
emit(metricsEvent(inputTokens, outputTokens, usage, {
|
|
985
|
+
agentId: profile.id,
|
|
986
|
+
provider: profile.provider ?? this.opts.defaultProvider,
|
|
987
|
+
model: profile.model ?? chatProvider.modelId,
|
|
988
|
+
startedAt: llmStartedAt,
|
|
989
|
+
}));
|
|
749
990
|
},
|
|
750
991
|
model: profile.model,
|
|
751
992
|
});
|
|
752
993
|
if (!finalMessage)
|
|
753
994
|
break;
|
|
995
|
+
const guardedOut = await this.guardOutput(finalMessage, profile.id);
|
|
996
|
+
finalMessage = guardedOut.message;
|
|
997
|
+
if (guardedOut.touched)
|
|
998
|
+
streamContent = guardedOut.text;
|
|
999
|
+
if (holdOutput && !profile.suppressDefaultOutput) {
|
|
1000
|
+
const shown = guardedOut.touched ? guardedOut.text : heldTokens.join('');
|
|
1001
|
+
if (shown)
|
|
1002
|
+
emit({ type: 'token', content: shown, agent_id: profile.id });
|
|
1003
|
+
}
|
|
754
1004
|
if (streamContent)
|
|
755
1005
|
finalContent = streamContent;
|
|
756
1006
|
messages.push(finalMessage);
|
|
@@ -758,7 +1008,14 @@ class AgentEngine {
|
|
|
758
1008
|
break;
|
|
759
1009
|
const toolResults = [];
|
|
760
1010
|
for (const call of toolCalls) {
|
|
761
|
-
const result = await this.executeToolCall(call, profile, depth, emit)
|
|
1011
|
+
const result = await this.executeToolCall(call, profile, depth, emit, () => {
|
|
1012
|
+
// Sub-agent history is the local `messages` array: blank the refused arguments there too.
|
|
1013
|
+
for (const m of messages) {
|
|
1014
|
+
const tc = m.role === 'assistant' ? m.tool_calls?.find(c => c.id === call.id) : undefined;
|
|
1015
|
+
if (tc)
|
|
1016
|
+
tc.function = { ...tc.function, arguments: '{"redacted":"blocked by guardrail"}' };
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
762
1019
|
toolResults.push({ role: 'tool', tool_call_id: call.id, content: result });
|
|
763
1020
|
}
|
|
764
1021
|
messages.push(...toolResults);
|
|
@@ -771,12 +1028,15 @@ class AgentEngine {
|
|
|
771
1028
|
* runAgentInternal (sub-agents via ask_agent).
|
|
772
1029
|
* Handles: allowedTools authorization → onToolApproval gate → execute → audit → transport.
|
|
773
1030
|
*/
|
|
774
|
-
async executeToolCall(call, profile, depth = 0, emit
|
|
1031
|
+
async executeToolCall(call, profile, depth = 0, emit,
|
|
1032
|
+
/** Called when a guardrail refused the arguments, so the caller can scrub them from its history. */
|
|
1033
|
+
onArgsRefused) {
|
|
775
1034
|
const emitEvent = emit ?? ((e) => this.opts.transport.emit(e));
|
|
776
1035
|
const callStart = Date.now();
|
|
777
1036
|
const toolDef = this.opts.tools.get(call.name);
|
|
778
1037
|
let result;
|
|
779
1038
|
let success;
|
|
1039
|
+
let outcome;
|
|
780
1040
|
if (!toolDef) {
|
|
781
1041
|
result = `Tool "${call.name}" not found`;
|
|
782
1042
|
success = false;
|
|
@@ -788,20 +1048,56 @@ class AgentEngine {
|
|
|
788
1048
|
success = false;
|
|
789
1049
|
}
|
|
790
1050
|
else {
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
1051
|
+
// Guardrails on the arguments run before approval: nobody is asked to approve a blocked call.
|
|
1052
|
+
let effective = call;
|
|
1053
|
+
let withheld;
|
|
1054
|
+
if (this.guardrails?.has('tool_call')) {
|
|
1055
|
+
const checked = await this.guard('tool_call', call.args, profile.id, call.name);
|
|
1056
|
+
if (checked.blocked) {
|
|
1057
|
+
withheld = `Tool call "${call.name}" blocked by guardrail "${checked.blocked.guardrail}": ${checked.blocked.reason}`;
|
|
1058
|
+
}
|
|
1059
|
+
else if (checked.changed) {
|
|
1060
|
+
try {
|
|
1061
|
+
JSON.parse(checked.content);
|
|
1062
|
+
effective = { name: call.name, args: checked.content };
|
|
1063
|
+
}
|
|
1064
|
+
catch {
|
|
1065
|
+
withheld = `Tool call "${call.name}" blocked by guardrails: redaction left the arguments invalid`;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
if (withheld) {
|
|
1070
|
+
result = withheld;
|
|
794
1071
|
success = false;
|
|
1072
|
+
onArgsRefused?.();
|
|
795
1073
|
}
|
|
796
1074
|
else {
|
|
797
|
-
|
|
1075
|
+
const gateDecision = await this.checkGateSerial(effective, profile.id);
|
|
1076
|
+
if (gateDecision === 'rejected') {
|
|
1077
|
+
result = `Tool call "${call.name}" was rejected by the user.`;
|
|
1078
|
+
success = false;
|
|
1079
|
+
}
|
|
1080
|
+
else {
|
|
1081
|
+
({ result, success, outcome } = await this.runToolDef(effective, toolDef, profile.id, depth));
|
|
1082
|
+
if (this.guardrails?.has('tool_result')) {
|
|
1083
|
+
const checked = await this.guard('tool_result', result, profile.id, call.name);
|
|
1084
|
+
result = checked.blocked
|
|
1085
|
+
? `[Tool result withheld by guardrail "${checked.blocked.guardrail}": ${checked.blocked.reason}]`
|
|
1086
|
+
: checked.content;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
798
1089
|
}
|
|
1090
|
+
call = effective;
|
|
799
1091
|
}
|
|
800
1092
|
await this.auditLogger.log({ agentId: profile.id, tool: call.name, inputPreview: call.args, success, durationMs: Date.now() - callStart, sessionId: this.opts.sessionId });
|
|
801
1093
|
// Strip ANSI before slicing to avoid partial escape sequences in the preview
|
|
802
1094
|
// eslint-disable-next-line no-control-regex
|
|
803
1095
|
const cleanPreview = result.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
|
|
804
|
-
emitEvent({
|
|
1096
|
+
emitEvent({
|
|
1097
|
+
type: 'tool_result', name: call.name, success, preview: cleanPreview.slice(0, 120),
|
|
1098
|
+
agent_id: profile.id, started_at: callStart, duration_ms: Date.now() - callStart,
|
|
1099
|
+
...(outcome ? { outcome } : {}),
|
|
1100
|
+
});
|
|
805
1101
|
return result;
|
|
806
1102
|
}
|
|
807
1103
|
/** Approval checks never overlap and run in call order, even inside a parallel wave. */
|
|
@@ -812,13 +1108,56 @@ class AgentEngine {
|
|
|
812
1108
|
return next;
|
|
813
1109
|
}
|
|
814
1110
|
async runToolDef(call, toolDef, agentId, depth = 0) {
|
|
815
|
-
const
|
|
1111
|
+
const controller = new AbortController();
|
|
1112
|
+
this.toolControllers.add(controller);
|
|
1113
|
+
const secrets = await (0, secrets_1.resolveSecrets)(this.opts.agents.get(agentId), this.opts.secretResolver);
|
|
1114
|
+
const ctx = {
|
|
1115
|
+
...this.buildContext(agentId, depth),
|
|
1116
|
+
...(Object.keys(secrets).length ? { secrets } : {}),
|
|
1117
|
+
...(this.opts.jobs ? { jobs: this.opts.jobs } : {}),
|
|
1118
|
+
signal: controller.signal,
|
|
1119
|
+
};
|
|
1120
|
+
const timeoutMs = toolDef.timeoutMs ?? this.opts.toolTimeoutMs;
|
|
1121
|
+
const graceMs = this.opts.toolTimeoutGraceMs ?? 2000;
|
|
1122
|
+
let timer;
|
|
1123
|
+
let graceTimer;
|
|
1124
|
+
const execution = (async () => {
|
|
1125
|
+
try {
|
|
1126
|
+
const args = JSON.parse(call.args);
|
|
1127
|
+
return { result: await toolDef.execute(args, ctx), success: true };
|
|
1128
|
+
}
|
|
1129
|
+
catch (err) {
|
|
1130
|
+
return { result: `Error: ${err instanceof Error ? err.message : String(err)}`, success: false };
|
|
1131
|
+
}
|
|
1132
|
+
})();
|
|
1133
|
+
// A result that arrives after we gave up on the call is dropped, never an unhandled rejection.
|
|
1134
|
+
execution.catch(() => undefined);
|
|
1135
|
+
// Resolves with the reason as soon as the call is aborted or its time limit passes.
|
|
1136
|
+
const interrupted = new Promise((resolve) => {
|
|
1137
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
1138
|
+
timer = setTimeout(() => { controller.abort('timeout'); resolve('timeout'); }, timeoutMs);
|
|
1139
|
+
}
|
|
1140
|
+
controller.signal.addEventListener('abort', () => {
|
|
1141
|
+
resolve(controller.signal.reason === 'timeout' ? 'timeout' : 'aborted');
|
|
1142
|
+
}, { once: true });
|
|
1143
|
+
});
|
|
816
1144
|
try {
|
|
817
|
-
const
|
|
818
|
-
|
|
1145
|
+
const first = await Promise.race([execution, interrupted]);
|
|
1146
|
+
if (first !== 'timeout' && first !== 'aborted')
|
|
1147
|
+
return first;
|
|
1148
|
+
// Interrupted: give the tool a moment to react to the signal, then answer either way.
|
|
1149
|
+
await Promise.race([
|
|
1150
|
+
execution,
|
|
1151
|
+
new Promise((resolve) => { graceTimer = setTimeout(resolve, graceMs); }),
|
|
1152
|
+
]);
|
|
1153
|
+
return first === 'timeout'
|
|
1154
|
+
? { result: `Error: TOOL_TIMEOUT: tool "${call.name}" exceeded ${timeoutMs}ms`, success: false, outcome: 'timeout' }
|
|
1155
|
+
: { result: `Error: aborted: tool "${call.name}" was cancelled`, success: false, outcome: 'aborted' };
|
|
819
1156
|
}
|
|
820
|
-
|
|
821
|
-
|
|
1157
|
+
finally {
|
|
1158
|
+
clearTimeout(timer);
|
|
1159
|
+
clearTimeout(graceTimer);
|
|
1160
|
+
this.toolControllers.delete(controller);
|
|
822
1161
|
}
|
|
823
1162
|
}
|
|
824
1163
|
/**
|
|
@@ -854,7 +1193,6 @@ class AgentEngine {
|
|
|
854
1193
|
advancedMemory: this.opts.memorySystem,
|
|
855
1194
|
...(additionalRoots.length ? { additionalRoots } : {}),
|
|
856
1195
|
...(profile?.blockedCommands?.length ? { blockedCommands: profile.blockedCommands } : {}),
|
|
857
|
-
...(profile?.secrets && Object.keys(profile.secrets).length ? { secrets: profile.secrets } : {}),
|
|
858
1196
|
askAgent: async (agentId, question, context) => {
|
|
859
1197
|
const result = await this.bus.runSingle({ agentId, question, context, fromAgentId: id, depth: depth + 1 });
|
|
860
1198
|
return result.content;
|