@backendkit-labs/agent-core 0.40.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 (86) hide show
  1. package/README.md +56 -0
  2. package/dist/agent-memory/ProceduralMemory.d.ts +3 -0
  3. package/dist/agent-memory/ProceduralMemory.d.ts.map +1 -1
  4. package/dist/agent-memory/ProceduralMemory.js +3 -0
  5. package/dist/agent-memory/ProceduralMemory.js.map +1 -1
  6. package/dist/engine/AgentEngine.d.ts +22 -2
  7. package/dist/engine/AgentEngine.d.ts.map +1 -1
  8. package/dist/engine/AgentEngine.js +92 -48
  9. package/dist/engine/AgentEngine.js.map +1 -1
  10. package/dist/engine/createBaseEngine.d.ts +13 -0
  11. package/dist/engine/createBaseEngine.d.ts.map +1 -1
  12. package/dist/engine/createBaseEngine.js +41 -7
  13. package/dist/engine/createBaseEngine.js.map +1 -1
  14. package/dist/engine/error-code.d.ts +7 -0
  15. package/dist/engine/error-code.d.ts.map +1 -0
  16. package/dist/engine/error-code.js +23 -0
  17. package/dist/engine/error-code.js.map +1 -0
  18. package/dist/engine/run-recorder.d.ts +13 -0
  19. package/dist/engine/run-recorder.d.ts.map +1 -0
  20. package/dist/engine/run-recorder.js +49 -0
  21. package/dist/engine/run-recorder.js.map +1 -0
  22. package/dist/governance/approval-store.d.ts +12 -0
  23. package/dist/governance/approval-store.d.ts.map +1 -1
  24. package/dist/governance/approval-store.js +37 -1
  25. package/dist/governance/approval-store.js.map +1 -1
  26. package/dist/governance/types.d.ts +6 -0
  27. package/dist/governance/types.d.ts.map +1 -1
  28. package/dist/index.d.ts +6 -3
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +17 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/learning/index.d.ts +16 -0
  33. package/dist/learning/index.d.ts.map +1 -0
  34. package/dist/learning/index.js +560 -0
  35. package/dist/learning/index.js.map +1 -0
  36. package/dist/learning/signal.d.ts +51 -0
  37. package/dist/learning/signal.d.ts.map +1 -0
  38. package/dist/learning/signal.js +136 -0
  39. package/dist/learning/signal.js.map +1 -0
  40. package/dist/learning/stores.d.ts +32 -0
  41. package/dist/learning/stores.d.ts.map +1 -0
  42. package/dist/learning/stores.js +91 -0
  43. package/dist/learning/stores.js.map +1 -0
  44. package/dist/learning/types.d.ts +345 -0
  45. package/dist/learning/types.d.ts.map +1 -0
  46. package/dist/learning/types.js +3 -0
  47. package/dist/learning/types.js.map +1 -0
  48. package/dist/learning/units.d.ts +46 -0
  49. package/dist/learning/units.d.ts.map +1 -0
  50. package/dist/learning/units.js +137 -0
  51. package/dist/learning/units.js.map +1 -0
  52. package/dist/reflection/domain-registry.d.ts +3 -0
  53. package/dist/reflection/domain-registry.d.ts.map +1 -1
  54. package/dist/reflection/domain-registry.js +3 -0
  55. package/dist/reflection/domain-registry.js.map +1 -1
  56. package/dist/reflection/failure-catalog.d.ts +3 -0
  57. package/dist/reflection/failure-catalog.d.ts.map +1 -1
  58. package/dist/reflection/failure-catalog.js +3 -0
  59. package/dist/reflection/failure-catalog.js.map +1 -1
  60. package/dist/reflection/pattern-detector.d.ts +3 -0
  61. package/dist/reflection/pattern-detector.d.ts.map +1 -1
  62. package/dist/reflection/pattern-detector.js +3 -0
  63. package/dist/reflection/pattern-detector.js.map +1 -1
  64. package/dist/reflection/policy-promoter.d.ts +3 -0
  65. package/dist/reflection/policy-promoter.d.ts.map +1 -1
  66. package/dist/reflection/policy-promoter.js +3 -0
  67. package/dist/reflection/policy-promoter.js.map +1 -1
  68. package/dist/reflection/reflection-engine.d.ts +3 -0
  69. package/dist/reflection/reflection-engine.d.ts.map +1 -1
  70. package/dist/reflection/reflection-engine.js +3 -0
  71. package/dist/reflection/reflection-engine.js.map +1 -1
  72. package/dist/tools/defineTool.d.ts +4 -1
  73. package/dist/tools/defineTool.d.ts.map +1 -1
  74. package/dist/tools/defineTool.js +5 -2
  75. package/dist/tools/defineTool.js.map +1 -1
  76. package/dist/tools/services.d.ts +13 -0
  77. package/dist/tools/services.d.ts.map +1 -1
  78. package/dist/tools/services.js +12 -0
  79. package/dist/tools/services.js.map +1 -1
  80. package/dist/tools/tool-error.d.ts +19 -0
  81. package/dist/tools/tool-error.d.ts.map +1 -0
  82. package/dist/tools/tool-error.js +33 -0
  83. package/dist/tools/tool-error.js.map +1 -0
  84. package/dist/types/index.d.ts +39 -0
  85. package/dist/types/index.d.ts.map +1 -1
  86. package/package.json +89 -89
@@ -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.opts.transport.emit(event),
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.opts.transport.emit({
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: opts.transport,
163
+ transport: this.transport,
153
164
  });
154
165
  this.approvalGate = new ApprovalGate_1.ApprovalGate({
155
166
  onToolApproval: opts.onToolApproval,
156
- transport: opts.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: opts.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.opts.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
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.opts.transport.emit({ type: 'ready' });
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.opts.transport.emit({
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.opts.transport.emit({ type: 'done' });
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.opts.transport.emit({
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.opts.transport.emit({ type: 'done' });
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.opts.transport.emit({
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.opts.transport.emit({ type: 'token', content: result, agent_id: mcpRoute.agentId });
371
- this.opts.transport.emit({ type: 'block_end', status: 'ok', agent_id: mcpRoute.agentId });
372
- this.opts.transport.emit({ type: 'done' });
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.opts.transport.emit({ type: 'done' });
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.opts.transport.emit(event),
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.opts.transport.emit({ type: 'done' });
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.opts.transport.emit(e) };
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.opts.transport,
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.opts.transport.emit({
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.opts.transport.emit({
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.opts.transport.emit({ type: 'system', level: 'warn', text: `[Context] Compaction failed: ${err instanceof Error ? err.message : String(err)}` });
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.opts.transport.emit({
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.opts.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
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.opts.transport.emit({
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.opts.transport.emit({
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.opts.transport.emit({
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.opts.transport.emit({ type: 'token', content: delta, agent_id: currentProfile.id });
894
+ this.transport.emit({ type: 'token', content: delta, agent_id: currentProfile.id });
858
895
  },
859
896
  onToolCall: (name, args, id) => {
860
- this.opts.transport.emit({ type: 'tool_call', name, args_preview: args.slice(0, 200) });
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.opts.transport.emit({ type: 'error', message: err.message });
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.opts.transport.emit(metricsEvent(inputTokens, outputTokens, usage, {
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.opts.transport.emit({ type: 'error', message: overflowError.message });
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.opts.transport.emit({ type: 'token', content: shown, agent_id: currentProfile.id });
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.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: false, preview: msg });
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.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: false, preview: verdict.message.slice(0, 120) });
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.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: !result.error, preview: content.slice(0, 120) });
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.opts.transport.emit(e);
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.opts.transport.emit({ type: 'system', level: 'warn', text: `[hooks] afterTurn asked for more than ${cap} extra passes; stopping` });
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.opts.transport.emit({ type: 'block_end', status: 'ok', agent_id: profile.id });
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: this.buildSystemPrompt(profile, await this.hookPromptSections(profile)) },
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.opts.transport.emit(event);
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.opts.transport.emit({
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.opts.transport.emit(e));
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.opts.transport.emit({
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
- return { result: `Error: ${err instanceof Error ? err.message : String(err)}`, success: false };
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.opts.transport.emit({ type: 'compacting', phase, label });
1703
+ this.transport.emit({ type: 'compacting', phase, label });
1660
1704
  },
1661
1705
  llmCall: async (prompt) => {
1662
1706
  const profile = this.opts.agents.get(id);