@backendkit-labs/agent-core 0.37.2 → 0.38.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 (68) hide show
  1. package/README.md +132 -43
  2. package/dist/delegation/DelegationBus.d.ts +8 -1
  3. package/dist/delegation/DelegationBus.d.ts.map +1 -1
  4. package/dist/delegation/DelegationBus.js +2 -1
  5. package/dist/delegation/DelegationBus.js.map +1 -1
  6. package/dist/engine/AgentEngine.d.ts +108 -3
  7. package/dist/engine/AgentEngine.d.ts.map +1 -1
  8. package/dist/engine/AgentEngine.js +463 -43
  9. package/dist/engine/AgentEngine.js.map +1 -1
  10. package/dist/engine/createBaseEngine.d.ts +28 -0
  11. package/dist/engine/createBaseEngine.d.ts.map +1 -1
  12. package/dist/engine/createBaseEngine.js +7 -0
  13. package/dist/engine/createBaseEngine.js.map +1 -1
  14. package/dist/engine/package-install.d.ts +7 -0
  15. package/dist/engine/package-install.d.ts.map +1 -1
  16. package/dist/engine/package-install.js +17 -0
  17. package/dist/engine/package-install.js.map +1 -1
  18. package/dist/governance/approval-store.d.ts +32 -0
  19. package/dist/governance/approval-store.d.ts.map +1 -0
  20. package/dist/governance/approval-store.js +129 -0
  21. package/dist/governance/approval-store.js.map +1 -0
  22. package/dist/governance/approval.d.ts +35 -0
  23. package/dist/governance/approval.d.ts.map +1 -0
  24. package/dist/governance/approval.js +65 -0
  25. package/dist/governance/approval.js.map +1 -0
  26. package/dist/governance/approvers.d.ts +24 -0
  27. package/dist/governance/approvers.d.ts.map +1 -0
  28. package/dist/governance/approvers.js +69 -0
  29. package/dist/governance/approvers.js.map +1 -0
  30. package/dist/governance/audit.d.ts +101 -0
  31. package/dist/governance/audit.d.ts.map +1 -0
  32. package/dist/governance/audit.js +178 -0
  33. package/dist/governance/audit.js.map +1 -0
  34. package/dist/governance/hooks.d.ts +60 -0
  35. package/dist/governance/hooks.d.ts.map +1 -0
  36. package/dist/governance/hooks.js +26 -0
  37. package/dist/governance/hooks.js.map +1 -0
  38. package/dist/governance/policy.d.ts +28 -0
  39. package/dist/governance/policy.d.ts.map +1 -0
  40. package/dist/governance/policy.js +101 -0
  41. package/dist/governance/policy.js.map +1 -0
  42. package/dist/governance/types.d.ts +162 -0
  43. package/dist/governance/types.d.ts.map +1 -0
  44. package/dist/governance/types.js +3 -0
  45. package/dist/governance/types.js.map +1 -0
  46. package/dist/index.d.ts +11 -0
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +28 -2
  49. package/dist/index.js.map +1 -1
  50. package/dist/mcp/tool-server-http.d.ts +2 -6
  51. package/dist/mcp/tool-server-http.d.ts.map +1 -1
  52. package/dist/mcp/tool-server-http.js +4 -20
  53. package/dist/mcp/tool-server-http.js.map +1 -1
  54. package/dist/mcp/tool-server.d.ts +18 -4
  55. package/dist/mcp/tool-server.d.ts.map +1 -1
  56. package/dist/mcp/tool-server.js +110 -22
  57. package/dist/mcp/tool-server.js.map +1 -1
  58. package/dist/shared/utils/canonical-json.d.ts +12 -0
  59. package/dist/shared/utils/canonical-json.d.ts.map +1 -0
  60. package/dist/shared/utils/canonical-json.js +29 -0
  61. package/dist/shared/utils/canonical-json.js.map +1 -0
  62. package/dist/shared/utils/loopback.d.ts +10 -0
  63. package/dist/shared/utils/loopback.d.ts.map +1 -0
  64. package/dist/shared/utils/loopback.js +25 -0
  65. package/dist/shared/utils/loopback.js.map +1 -0
  66. package/dist/types/index.d.ts +10 -0
  67. package/dist/types/index.d.ts.map +1 -1
  68. package/package.json +1 -1
@@ -9,6 +9,13 @@ const secrets_1 = require("./secrets");
9
9
  const contextOverflow_1 = require("./contextOverflow");
10
10
  const GuardrailRunner_1 = require("../guardrails/GuardrailRunner");
11
11
  const MCPRegistrar_1 = require("./MCPRegistrar");
12
+ const node_crypto_1 = require("node:crypto");
13
+ const audit_1 = require("../governance/audit");
14
+ const policy_1 = require("../governance/policy");
15
+ const approval_1 = require("../governance/approval");
16
+ const package_install_1 = require("./package-install");
17
+ const hooks_1 = require("../governance/hooks");
18
+ const canonical_json_1 = require("../shared/utils/canonical-json");
12
19
  const DelegationBus_1 = require("../delegation/DelegationBus");
13
20
  const SessionMemory_1 = require("../memory/SessionMemory");
14
21
  const activator_1 = require("../skills/activator");
@@ -30,6 +37,9 @@ const ASK_AGENT_TOOL = {
30
37
  },
31
38
  required: ['agent_id', 'question'],
32
39
  },
40
+ // Delegating changes nothing by itself: what the delegate does is decided and audited call by call. So the
41
+ // default policy lets delegation through; an explicit policy still sees it (tool name 'ask_agent').
42
+ readOnly: true,
33
43
  execute: async () => '',
34
44
  };
35
45
  const generateObject_1 = require("../structured/generateObject");
@@ -60,6 +70,19 @@ class AgentEngine {
60
70
  /** Uncalibrated token estimate of the last request sent by runLoop, to calibrate against real usage. */
61
71
  lastRequestEstimate = 0;
62
72
  auditLogger;
73
+ audit;
74
+ /** Policy path (SPEC-0014 F2) instead of the legacy ApprovalGate: on when policy, approver or approvals is set. */
75
+ governed;
76
+ policies;
77
+ approver;
78
+ /** Set when the approver is the adapted onToolApproval callback, so disable/enableToolApproval reach it. */
79
+ callbackApprover;
80
+ hooks;
81
+ /** Context shared by the hooks of the turn in progress; undefined between turns. */
82
+ runCtx;
83
+ runController;
84
+ /** Last final answer of the model in the current turn (for afterRun). */
85
+ lastAnswer = '';
63
86
  currentAgentId;
64
87
  aborted = false;
65
88
  abortController = null;
@@ -98,6 +121,32 @@ class AgentEngine {
98
121
  });
99
122
  }
100
123
  this.auditLogger = new AuditLogger_1.AuditLogger(opts.auditLog);
124
+ // A sink that fails must not change what the agent already did, but it must not fail silently either.
125
+ this.audit = new audit_1.AuditDispatcher(opts.audit, (err) => this.opts.transport.emit({
126
+ type: 'system', level: 'warn',
127
+ text: `[audit] a sink failed to record a tool call: ${err instanceof Error ? err.message : String(err)}`,
128
+ }));
129
+ this.hooks = opts.hooks ?? [];
130
+ this.governed = !!(opts.policy || opts.approver || opts.approvals);
131
+ if (this.governed) {
132
+ const someoneToAsk = !!(opts.approver || opts.approvals || opts.onToolApproval);
133
+ const configured = opts.policy ? (Array.isArray(opts.policy) ? opts.policy : [opts.policy]) : [];
134
+ // Package installs always ask a person; it moves to the coding vertical with SPEC-0015 F3.
135
+ this.policies = [
136
+ ...(configured.length > 0 ? configured : someoneToAsk ? [policy_1.defaultToolPolicy] : []),
137
+ package_install_1.packageInstallPolicy,
138
+ ];
139
+ if (opts.approver) {
140
+ this.approver = opts.approver;
141
+ }
142
+ else if (opts.onToolApproval) {
143
+ this.callbackApprover = (0, approval_1.approverFromCallback)(opts.onToolApproval);
144
+ this.approver = this.callbackApprover;
145
+ }
146
+ }
147
+ else {
148
+ this.policies = [];
149
+ }
101
150
  this.mcpRegistrar = new MCPRegistrar_1.MCPRegistrar({
102
151
  mcpManager: opts.mcpManager,
103
152
  tools: opts.tools,
@@ -119,7 +168,7 @@ class AgentEngine {
119
168
  maxDepth: opts.maxDelegationDepth,
120
169
  agents: opts.agents,
121
170
  transport: opts.transport,
122
- runAgent: (id, question, context, depth, buf) => this.runAgentInternal(id, question, context, depth, buf),
171
+ runAgent: (id, question, context, depth, buf, chain) => this.runAgentInternal(id, question, context, depth, buf, chain),
123
172
  });
124
173
  }
125
174
  /**
@@ -366,11 +415,62 @@ class AgentEngine {
366
415
  this.opts.transport.emit({ type: 'system', level: 'warn', text: `[Orchestrator] failed (${reason}); running without classification or gates` });
367
416
  }
368
417
  }
369
- this.history.push({ role: 'user', content: input });
370
- await this.runLoop(profile, orchestrationResult);
371
- this.saveHistory();
418
+ // Hooks of this turn share one context (SPEC-0014 F3). A throwing hook fails the turn.
419
+ this.runController = new AbortController();
420
+ this.lastAnswer = '';
421
+ this.runCtx = {
422
+ principal: this.principalFor(profile.id),
423
+ input,
424
+ state: new Map(),
425
+ signal: this.runController.signal,
426
+ emit: (event) => this.opts.transport.emit(event),
427
+ };
428
+ try {
429
+ await (0, hooks_1.runHooks)(this.hooks, 'beforeRun', h => h.beforeRun(this.runCtx));
430
+ this.history.push({ role: 'user', content: input });
431
+ await this.runLoop(profile, orchestrationResult);
432
+ this.saveHistory();
433
+ const finished = this.runCtx;
434
+ await (0, hooks_1.runHooks)(this.hooks, 'afterRun', h => h.afterRun(finished, { text: this.lastAnswer }));
435
+ }
436
+ finally {
437
+ this.runCtx = undefined;
438
+ this.runController = undefined;
439
+ }
372
440
  this.opts.transport.emit({ type: 'done' });
373
441
  }
442
+ /** Sections the `systemPrompt` hooks add for `profile`. */
443
+ async hookPromptSections(profile) {
444
+ if (!this.runCtx || !this.hooks.some(h => h.systemPrompt))
445
+ return [];
446
+ const ctx = this.runCtx;
447
+ const sections = await (0, hooks_1.runHooks)(this.hooks, 'systemPrompt', h => h.systemPrompt(ctx, profile));
448
+ return sections.filter((s) => typeof s === 'string' && s.trim().length > 0);
449
+ }
450
+ /** The first `afterTurn` hook that asks to continue wins; the rest still run (they may only observe). */
451
+ async afterTurnHooks(profile, text) {
452
+ if (!this.runCtx || !this.hooks.some(h => h.afterTurn))
453
+ return undefined;
454
+ const ctx = this.runCtx;
455
+ const answers = await (0, hooks_1.runHooks)(this.hooks, 'afterTurn', h => h.afterTurn(ctx, { text, profile }));
456
+ return answers.find((a) => !!a && a.action === 'continue');
457
+ }
458
+ /** Arguments the model produced, as an object (anything else becomes `{}`). */
459
+ parseArgs(raw) {
460
+ try {
461
+ const parsed = JSON.parse(raw);
462
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
463
+ }
464
+ catch {
465
+ return {};
466
+ }
467
+ }
468
+ /** Context for a tool hook: the turn's context with the principal of the agent that makes the call. */
469
+ toolHookContext(principal) {
470
+ return this.runCtx
471
+ ? { ...this.runCtx, principal }
472
+ : { principal, input: '', state: new Map(), signal: new AbortController().signal, emit: (e) => this.opts.transport.emit(e) };
473
+ }
374
474
  async runWorkflow(defOrBuilder, opts = {}) {
375
475
  if (this.pendingContextLoad)
376
476
  await this.pendingContextLoad;
@@ -384,8 +484,51 @@ class AgentEngine {
384
484
  });
385
485
  return runner.run();
386
486
  }
487
+ /**
488
+ * Runs a tool call that was stored as pending and has since been approved (SPEC-0014 §6, resubmission).
489
+ *
490
+ * - At most once: the store marks it executed atomically before it runs; a second call throws.
491
+ * - Everything is checked again (allowedTools, sandbox, guardrails, policies); the stored approval only
492
+ * satisfies an `ask`, and only if its approver is one that ask accepts. An approval that turns out not to be
493
+ * valid is consumed and audited as `deny`.
494
+ * - The result is returned to the caller (e.g. Hermes or a UI); it is not added to the conversation.
495
+ */
496
+ async runApproved(approvalId) {
497
+ const store = this.opts.approvals;
498
+ if (!store)
499
+ throw new Error('runApproved needs an approvals store');
500
+ await this.mcpRegistrar.ensureInitialized();
501
+ await this.ensureAgentsLoaded();
502
+ const item = await store.get(approvalId);
503
+ if (!item)
504
+ throw new Error(`approval "${approvalId}" does not exist`);
505
+ if (item.status === 'executed')
506
+ throw new Error(`approval "${approvalId}" was already executed`);
507
+ if (item.status !== 'approved' || !item.outcome)
508
+ throw new Error(`approval "${approvalId}" is ${item.status}, not approved`);
509
+ const subject = item.subject;
510
+ if (subject.kind !== 'tool_call' || !('call' in subject)) {
511
+ throw new Error(`approval "${approvalId}" is a ${subject.kind}; only tool calls are resumed by the engine`);
512
+ }
513
+ const profile = this.opts.agents.get(item.principal.agentId);
514
+ if (!profile)
515
+ throw new Error(`agent "${item.principal.agentId}" of approval "${approvalId}" is not registered`);
516
+ if (!(await store.markExecuted(approvalId)))
517
+ throw new Error(`approval "${approvalId}" was already executed`);
518
+ return this.executeToolCall({ name: subject.call.tool.name, args: JSON.stringify(subject.call.args) }, profile, 0, undefined, undefined, item.principal.chain, { by: item.outcome.by, approvalId });
519
+ }
520
+ /**
521
+ * Puts one question to an agent outside the conversation and returns its answer (its tool calls are governed
522
+ * like any other). Used by `agentApprover` to let a supervising agent approve or reject requests.
523
+ */
524
+ async consultAgent(agentId, question) {
525
+ await this.ensureAgentsLoaded();
526
+ const result = await this.runAgentInternal(agentId, question, undefined, 0, undefined, [agentId]);
527
+ return result.content;
528
+ }
387
529
  abort() {
388
530
  this.aborted = true;
531
+ this.runController?.abort('aborted');
389
532
  void this.opts.jobs?.cancelAll();
390
533
  this.abortController?.abort();
391
534
  this.abortController = null;
@@ -618,7 +761,7 @@ class AgentEngine {
618
761
  }
619
762
  return parts.join('\n');
620
763
  }
621
- buildSystemPrompt(profile, orchestrationResult) {
764
+ buildSystemPrompt(profile, orchestrationResult, hookSections = []) {
622
765
  const isOrchestrator = profile.id === this.opts.defaultAgentId;
623
766
  const parts = [profile.systemPrompt];
624
767
  if (isOrchestrator)
@@ -642,6 +785,7 @@ class AgentEngine {
642
785
  if (isOrchestrator && orchestrationResult) {
643
786
  parts.push(this.buildOrchestrationBrief(orchestrationResult));
644
787
  }
788
+ parts.push(...hookSections);
645
789
  return parts.join('\n\n');
646
790
  }
647
791
  /**
@@ -721,6 +865,7 @@ class AgentEngine {
721
865
  this.iterationManager.reset();
722
866
  const iterManager = this.iterationManager;
723
867
  let overflowRetries = 0;
868
+ let hookContinues = 0;
724
869
  this.opts.transport.emit({
725
870
  type: 'block_start',
726
871
  agent_id: profile.id,
@@ -735,7 +880,10 @@ class AgentEngine {
735
880
  break;
736
881
  this.announceFinishedJobs(currentProfile.id);
737
882
  await this.prepareContext();
738
- const systemMsg = { role: 'system', content: this.buildSystemPrompt(currentProfile, orchestrationResult) };
883
+ const systemMsg = {
884
+ role: 'system',
885
+ content: this.buildSystemPrompt(currentProfile, orchestrationResult, await this.hookPromptSections(currentProfile)),
886
+ };
739
887
  const tools = this.getToolsForAgent(currentProfile);
740
888
  const safeHistory = this.history.sanitized();
741
889
  if (this.contextManager) {
@@ -831,17 +979,48 @@ class AgentEngine {
831
979
  if (askAgentCalls.length > 0) {
832
980
  const validCalls = askAgentCalls.filter(c => c.agentId !== currentProfile.id);
833
981
  const selfCalls = askAgentCalls.filter(c => c.agentId === currentProfile.id);
982
+ // Delegations are audited like any tool call: one event each (SPEC-0014 F1).
983
+ const delegationArgs = (c) => ({ agent_id: c.agentId, question: c.question, ...(c.context !== undefined ? { context: c.context } : {}) });
834
984
  for (const call of selfCalls) {
985
+ const startedAt = Date.now();
835
986
  const msg = `Self-delegation blocked: agent "${currentProfile.id}" cannot delegate to itself. Execute the task directly.`;
836
987
  this.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: false, preview: msg });
837
988
  toolResults.push({ role: 'tool', tool_call_id: call.id, content: msg });
989
+ await this.recordAudit({
990
+ startedAt, agentId: currentProfile.id, tool: 'ask_agent', rawArgs: delegationArgs(call),
991
+ decision: 'not_allowed', reason: 'self-delegation',
992
+ });
838
993
  }
994
+ // In the policy path a delegation is a call like any other: the policies may deny it or ask first.
995
+ const callerChain = this.principalFor(currentProfile.id).chain;
996
+ const allowedCalls = [];
997
+ for (const call of validCalls) {
998
+ if (!this.governed) {
999
+ allowedCalls.push(call);
1000
+ continue;
1001
+ }
1002
+ const startedAt = Date.now();
1003
+ const verdict = await this.decideGoverned(ASK_AGENT_TOOL, JSON.stringify(delegationArgs(call)), this.principalFor(currentProfile.id, callerChain), []);
1004
+ if (verdict.run) {
1005
+ allowedCalls.push(call);
1006
+ continue;
1007
+ }
1008
+ this.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: false, preview: verdict.message.slice(0, 120) });
1009
+ toolResults.push({ role: 'tool', tool_call_id: call.id, content: verdict.message });
1010
+ await this.recordAudit({
1011
+ startedAt, agentId: currentProfile.id, chain: callerChain, tool: 'ask_agent',
1012
+ rawArgs: delegationArgs(call), decision: verdict.decision, reason: verdict.reason,
1013
+ });
1014
+ }
1015
+ validCalls.splice(0, validCalls.length, ...allowedCalls);
839
1016
  if (validCalls.length > 0) {
1017
+ const startedAt = Date.now();
840
1018
  const requests = validCalls.map(c => ({
841
1019
  agentId: c.agentId,
842
1020
  question: c.question,
843
1021
  context: this.buildSubAgentContext(c.context, streamBuffer),
844
1022
  fromAgentId: currentProfile.id,
1023
+ chain: callerChain,
845
1024
  }));
846
1025
  const results = validCalls.length >= 2
847
1026
  ? await this.bus.runParallel(requests)
@@ -852,6 +1031,11 @@ class AgentEngine {
852
1031
  const content = result.error ? `Error: ${result.error}` : result.content;
853
1032
  this.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: !result.error, preview: content.slice(0, 120) });
854
1033
  toolResults.push({ role: 'tool', tool_call_id: call.id, content });
1034
+ await this.recordAudit({
1035
+ startedAt, agentId: currentProfile.id, chain: callerChain, tool: 'ask_agent', rawArgs: delegationArgs(call),
1036
+ decision: 'allow', ...(result.error ? { reason: result.error } : {}),
1037
+ outcome: result.error ? 'error' : 'ok',
1038
+ });
855
1039
  }
856
1040
  }
857
1041
  }
@@ -921,16 +1105,38 @@ class AgentEngine {
921
1105
  await (0, qa_orchestrator_1.processInlineQaReview)(qaCtx);
922
1106
  }
923
1107
  }
924
- if (toolResults.length === 0)
925
- break;
1108
+ if (toolResults.length === 0) {
1109
+ // The model answered without tools: afterTurn hooks may force another pass (SPEC-0014 F3).
1110
+ this.lastAnswer = streamBuffer;
1111
+ const next = await this.afterTurnHooks(currentProfile, streamBuffer);
1112
+ if (!next)
1113
+ break;
1114
+ const cap = this.opts.maxHookContinues ?? hooks_1.DEFAULT_MAX_HOOK_CONTINUES;
1115
+ if (hookContinues >= cap) {
1116
+ this.opts.transport.emit({ type: 'system', level: 'warn', text: `[hooks] afterTurn asked for more than ${cap} extra passes; stopping` });
1117
+ break;
1118
+ }
1119
+ hookContinues++;
1120
+ if (next.agentId) {
1121
+ const nextProfile = this.opts.agents.get(next.agentId);
1122
+ if (!nextProfile)
1123
+ throw new Error(`afterTurn hook asked to continue as unknown agent "${next.agentId}"`);
1124
+ currentProfile = nextProfile;
1125
+ }
1126
+ if (next.message)
1127
+ this.history.push({ role: 'user', content: next.message });
1128
+ continue;
1129
+ }
926
1130
  this.history.pushAll(toolResults);
927
1131
  }
928
1132
  this.opts.transport.emit({ type: 'block_end', status: 'ok', agent_id: profile.id });
929
1133
  }
930
- async runAgentInternal(agentId, question, context, depth = 0, outputBuffer) {
1134
+ async runAgentInternal(agentId, question, context, depth = 0, outputBuffer, chain) {
931
1135
  const profile = this.opts.agents.get(agentId);
932
1136
  if (!profile)
933
1137
  throw new Error(`Agent "${agentId}" not registered`);
1138
+ // Delegation chain of this sub-agent, oldest first (SPEC-0014 principal).
1139
+ const agentChain = chain && chain.length > 0 ? chain : [agentId];
934
1140
  const start = Date.now();
935
1141
  // Inject recent history from the orchestrator's conversation so specialists
936
1142
  // can see previously gathered data (file reads, command outputs, etc.)
@@ -949,7 +1155,7 @@ class AgentEngine {
949
1155
  historySlice = (0, HistoryManager_1.sanitizeMessages)(historySlice);
950
1156
  }
951
1157
  const messages = [
952
- { role: 'system', content: this.buildSystemPrompt(profile) },
1158
+ { role: 'system', content: this.buildSystemPrompt(profile, undefined, await this.hookPromptSections(profile)) },
953
1159
  ...historySlice,
954
1160
  { role: 'user', content: context ? `${question}\n\nContext:\n${context}` : question },
955
1161
  ];
@@ -1077,7 +1283,7 @@ class AgentEngine {
1077
1283
  if (tc)
1078
1284
  tc.function = { ...tc.function, arguments: '{"redacted":"blocked by guardrail"}' };
1079
1285
  }
1080
- });
1286
+ }, agentChain);
1081
1287
  toolResults.push({ role: 'tool', tool_call_id: call.id, content: result });
1082
1288
  }
1083
1289
  messages.push(...toolResults);
@@ -1092,14 +1298,14 @@ class AgentEngine {
1092
1298
  * outcome is reported on THIS engine's transport and audit log. A runner shared by several engines therefore
1093
1299
  * never leaks one engine's decisions to another.
1094
1300
  */
1095
- sandboxFor(agentId) {
1301
+ sandboxFor(agentId, collect) {
1096
1302
  const real = this.opts.sandbox;
1097
1303
  return Object.assign(Object.create(real), {
1098
1304
  run: async (caller, req) => {
1099
1305
  const out = await real.run(caller, req);
1100
1306
  this.reportSandboxDecision(out.ok
1101
1307
  ? { outcome: 'allowed', tool: req.tool, agentId, mode: out.mode, network: out.network, backend: out.backend }
1102
- : { outcome: out.code, tool: req.tool, agentId, mode: out.mode, network: out.network, backend: out.backend, reason: out.reason });
1308
+ : { outcome: out.code, tool: req.tool, agentId, mode: out.mode, network: out.network, backend: out.backend, reason: out.reason }, collect);
1103
1309
  return out;
1104
1310
  },
1105
1311
  ...(real.authorizePath ? {
@@ -1107,23 +1313,32 @@ class AgentEngine {
1107
1313
  const verdict = real.authorizePath(caller, req);
1108
1314
  // Allowed reads are not reported (every file read would be an event); denials and writes are.
1109
1315
  if (!verdict.ok)
1110
- this.reportSandboxDecision({ outcome: verdict.code, tool: req.tool, agentId, reason: verdict.reason });
1316
+ this.reportSandboxDecision({ outcome: verdict.code, tool: req.tool, agentId, reason: verdict.reason }, collect);
1111
1317
  else if (req.access === 'write')
1112
- this.reportSandboxDecision({ outcome: 'allowed', tool: req.tool, agentId });
1318
+ this.reportSandboxDecision({ outcome: 'allowed', tool: req.tool, agentId }, collect);
1113
1319
  return verdict;
1114
1320
  },
1115
1321
  } : {}),
1116
1322
  });
1117
1323
  }
1118
1324
  /** The message for the model when the sandbox policy refuses `tool` for `agentId`; undefined when allowed. */
1119
- sandboxRefusal(tool, agentId) {
1325
+ sandboxRefusal(tool, agentId, collect) {
1120
1326
  const verdict = this.opts.sandbox?.authorizeTool?.({ agentId, sessionId: this.opts.sessionId ?? 'default' }, tool);
1121
1327
  if (!verdict || verdict.ok)
1122
1328
  return undefined;
1123
- this.reportSandboxDecision({ outcome: verdict.code, tool, agentId, reason: verdict.reason });
1329
+ this.reportSandboxDecision({ outcome: verdict.code, tool, agentId, reason: verdict.reason }, collect);
1124
1330
  return `Tool call "${tool}" refused by the sandbox policy (${verdict.code}): ${verdict.reason}`;
1125
1331
  }
1126
- reportSandboxDecision(d) {
1332
+ /**
1333
+ * Reports a sandbox decision on the transport and the legacy audit log, and, when `collect` is given, adds it to
1334
+ * the decisions the single `AuditEvent` of the current tool call will carry.
1335
+ */
1336
+ reportSandboxDecision(d, collect) {
1337
+ collect?.push({
1338
+ outcome: d.outcome,
1339
+ ...(d.mode ? { mode: d.mode } : {}), ...(d.network ? { network: d.network } : {}),
1340
+ ...(d.backend ? { backend: d.backend } : {}), ...(d.reason ? { reason: d.reason } : {}),
1341
+ });
1127
1342
  this.opts.transport.emit({
1128
1343
  type: 'sandbox', outcome: d.outcome, tool: d.tool, agent_id: d.agentId,
1129
1344
  ...(d.mode ? { mode: d.mode } : {}), ...(d.network ? { network: d.network } : {}),
@@ -1138,21 +1353,34 @@ class AgentEngine {
1138
1353
  /**
1139
1354
  * Unified tool execution used by both runLoop (primary agent) and
1140
1355
  * runAgentInternal (sub-agents via ask_agent).
1141
- * Handles: allowedTools authorization → onToolApproval gate → execute → audit → transport.
1356
+ * Handles: allowedTools → sandbox refusal → argument guardrails → policy/approval (or the legacy gate)
1357
+ * → execute → result guardrails → audit → transport.
1142
1358
  */
1143
1359
  async executeToolCall(call, profile, depth = 0, emit,
1144
1360
  /** Called when a guardrail refused the arguments, so the caller can scrub them from its history. */
1145
- onArgsRefused) {
1361
+ onArgsRefused,
1362
+ /** Delegation chain of `profile`, oldest first. Default `[profile.id]`. */
1363
+ chain,
1364
+ /** Set only by `runApproved`: this exact call was approved and stored (resubmission, SPEC-0014 §6). */
1365
+ approved) {
1146
1366
  const emitEvent = emit ?? ((e) => this.opts.transport.emit(e));
1147
1367
  const callStart = Date.now();
1148
1368
  const toolDef = this.opts.tools.get(call.name);
1369
+ const principal = this.principalFor(profile.id, chain);
1149
1370
  let result;
1150
1371
  let success;
1151
1372
  let outcome;
1152
1373
  let sandboxRefusal;
1374
+ // What the single audit event of this call records (SPEC-0014 F1).
1375
+ let decision = 'allow';
1376
+ let reason;
1377
+ let ran = false;
1378
+ let approval;
1379
+ const sandboxDecisions = [];
1153
1380
  if (!toolDef) {
1154
1381
  result = `Tool "${call.name}" not found`;
1155
1382
  success = false;
1383
+ decision = 'not_found';
1156
1384
  }
1157
1385
  else if (!profile.allowedTools.includes(call.name) &&
1158
1386
  !(this.opts.allowUnlistedTools && profile.allowedTools.length === 0 && !(profile.delegatesTo && profile.delegatesTo.length > 0))) {
@@ -1161,11 +1389,15 @@ class AgentEngine {
1161
1389
  ? `Use ask_agent to delegate to a specialist.`
1162
1390
  : `Add it to the agent's allowedTools if it should be able to use it.`);
1163
1391
  success = false;
1392
+ decision = 'not_allowed';
1393
+ reason = `not in the allowedTools of agent "${profile.id}"`;
1164
1394
  }
1165
- else if ((sandboxRefusal = this.sandboxRefusal(call.name, profile.id)) !== undefined) {
1395
+ else if ((sandboxRefusal = this.sandboxRefusal(call.name, profile.id, sandboxDecisions)) !== undefined) {
1166
1396
  // The policy refuses this tool outright (e.g. a writer while read-only). Nobody is asked and nothing runs.
1167
1397
  result = sandboxRefusal;
1168
1398
  success = false;
1399
+ decision = 'sandbox_denied';
1400
+ reason = sandboxDecisions[sandboxDecisions.length - 1]?.reason;
1169
1401
  }
1170
1402
  else {
1171
1403
  // Guardrails on the arguments run before approval: nobody is asked to approve a blocked call.
@@ -1189,33 +1421,57 @@ class AgentEngine {
1189
1421
  if (withheld) {
1190
1422
  result = withheld;
1191
1423
  success = false;
1424
+ decision = 'guardrail_blocked';
1425
+ reason = withheld;
1192
1426
  onArgsRefused?.();
1193
1427
  }
1194
1428
  else {
1195
- const gateDecision = await this.checkGateSerial(effective, profile.id);
1196
- if (gateDecision === 'rejected') {
1197
- result = `Tool call "${call.name}" was rejected by the user.`;
1198
- success = false;
1199
- }
1200
- else if (gateDecision === 'no-approver') {
1201
- const reason = `tool "${call.name}" needs approval under the sandbox policy and no approver is configured`;
1202
- this.reportSandboxDecision({ outcome: 'SANDBOX_DENIED', tool: call.name, agentId: profile.id, reason });
1203
- result = `Tool call "${call.name}" refused (SANDBOX_DENIED): needs approval under the sandbox policy and no approver is configured.`;
1429
+ const verdict = this.governed
1430
+ ? await this.decideGoverned(toolDef, effective.args, principal, sandboxDecisions, approved)
1431
+ : await this.decideLegacy(effective, profile.id, sandboxDecisions);
1432
+ if (!verdict.run) {
1433
+ result = verdict.message;
1204
1434
  success = false;
1435
+ decision = verdict.decision;
1436
+ reason = verdict.reason;
1205
1437
  }
1206
1438
  else {
1207
- ({ result, success, outcome } = await this.runToolDef(effective, toolDef, profile.id, depth));
1439
+ ran = true;
1440
+ approval = verdict.approval;
1441
+ const toolHooks = this.hooks.some(h => h.beforeTool || h.afterTool);
1442
+ const hookCall = toolHooks ? { tool: toolDef, args: this.parseArgs(effective.args) } : undefined;
1443
+ const hookCtx = toolHooks ? this.toolHookContext(principal) : undefined;
1444
+ if (hookCall && hookCtx)
1445
+ await (0, hooks_1.runHooks)(this.hooks, 'beforeTool', h => h.beforeTool(hookCtx, hookCall));
1446
+ ({ result, success, outcome } = await this.runToolDef(effective, toolDef, profile.id, depth, sandboxDecisions, principal, verdict.mode === 'dry_run'));
1208
1447
  if (this.guardrails?.has('tool_result')) {
1209
1448
  const checked = await this.guard('tool_result', result, profile.id, call.name);
1210
1449
  result = checked.blocked
1211
1450
  ? `[Tool result withheld by guardrail "${checked.blocked.guardrail}": ${checked.blocked.reason}]`
1212
1451
  : checked.content;
1213
1452
  }
1453
+ if (hookCall && hookCtx) {
1454
+ const finalResult = { text: result, success };
1455
+ await (0, hooks_1.runHooks)(this.hooks, 'afterTool', h => h.afterTool(hookCtx, hookCall, finalResult));
1456
+ }
1214
1457
  }
1215
1458
  }
1216
1459
  call = effective;
1217
1460
  }
1218
1461
  await this.auditLogger.log({ agentId: profile.id, tool: call.name, inputPreview: call.args, success, durationMs: Date.now() - callStart, sessionId: this.opts.sessionId });
1462
+ await this.recordAudit({
1463
+ startedAt: callStart,
1464
+ agentId: profile.id,
1465
+ chain: principal.chain,
1466
+ tool: call.name,
1467
+ rawArgs: call.args,
1468
+ decision,
1469
+ reason,
1470
+ outcome: ran ? (outcome ?? (success ? 'ok' : 'error')) : undefined,
1471
+ approval,
1472
+ sandbox: sandboxDecisions,
1473
+ meta: toolDef?.meta,
1474
+ });
1219
1475
  // Strip ANSI before slicing to avoid partial escape sequences in the preview
1220
1476
  // eslint-disable-next-line no-control-regex
1221
1477
  const cleanPreview = result.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
@@ -1228,23 +1484,136 @@ class AgentEngine {
1228
1484
  }
1229
1485
  /** Approval checks never overlap and run in call order, even inside a parallel wave. */
1230
1486
  gateQueue = Promise.resolve();
1231
- checkGateSerial(call, agentId) {
1487
+ serialize(work) {
1488
+ const next = this.gateQueue.then(work);
1489
+ this.gateQueue = next.catch(() => undefined);
1490
+ return next;
1491
+ }
1492
+ /** The legacy gate (onToolApproval + the built-in list of tools that ask), unchanged, as a verdict. */
1493
+ async decideLegacy(call, agentId, sandboxDecisions) {
1232
1494
  const sandboxAsk = this.opts.sandbox?.approvalFor
1233
1495
  ? this.opts.sandbox.approvalFor({ agentId, sessionId: this.opts.sessionId ?? 'default' }, call.name)
1234
1496
  : undefined;
1235
- const next = this.gateQueue.then(() => this.approvalGate.check(call, agentId, sandboxAsk));
1236
- this.gateQueue = next.catch(() => undefined);
1237
- return next;
1497
+ const gate = await this.serialize(() => this.approvalGate.check(call, agentId, sandboxAsk));
1498
+ if (gate === 'rejected') {
1499
+ return { run: false, decision: 'deny', reason: 'rejected by the approver', message: `Tool call "${call.name}" was rejected by the user.` };
1500
+ }
1501
+ if (gate === 'no-approver')
1502
+ return this.noApproverForSandbox(call.name, agentId, sandboxDecisions);
1503
+ return { run: true };
1504
+ }
1505
+ noApproverForSandbox(tool, agentId, sandboxDecisions) {
1506
+ const reason = `tool "${tool}" needs approval under the sandbox policy and no approver is configured`;
1507
+ this.reportSandboxDecision({ outcome: 'SANDBOX_DENIED', tool, agentId, reason }, sandboxDecisions);
1508
+ return {
1509
+ run: false, decision: 'sandbox_denied', reason,
1510
+ message: `Tool call "${tool}" refused (SANDBOX_DENIED): needs approval under the sandbox policy and no approver is configured.`,
1511
+ };
1238
1512
  }
1239
- async runToolDef(call, toolDef, agentId, depth = 0) {
1513
+ /**
1514
+ * The policy path (SPEC-0014 §2, F2): the policies decide on the arguments that would really run (after the
1515
+ * guardrails), a sandbox that wants approval adds an `ask`, and an `ask` goes to the approver in call order or,
1516
+ * when nobody answers now, to the durable store.
1517
+ */
1518
+ async decideGoverned(tool, rawArgs, principal, sandboxDecisions, approved) {
1519
+ // `approved` is never taken from what the model sent: only `runApproved`, which holds a stored approval, sets it.
1520
+ const call = { tool, args: this.parseArgs(rawArgs), ...(approved ? { approved } : {}) };
1521
+ const sandboxAsk = this.opts.sandbox?.approvalFor?.({ agentId: principal.agentId, sessionId: principal.sessionId }, tool.name) === 'ask';
1522
+ let d = await (0, policy_1.evaluatePolicies)(this.policies, principal, call);
1523
+ if (sandboxAsk)
1524
+ d = (0, policy_1.combineDecisions)([d, { effect: 'ask', reason: 'the sandbox policy requires approval' }]);
1525
+ if (d.effect === 'deny') {
1526
+ return { run: false, decision: 'deny', reason: d.reason, message: `Tool call "${tool.name}" denied by policy: ${d.reason}` };
1527
+ }
1528
+ if (d.effect === 'allow') {
1529
+ if (d.mode === 'sandboxed' && !this.opts.sandbox) {
1530
+ const reason = 'the policy requires a sandbox and none is configured';
1531
+ return { run: false, decision: 'deny', reason, message: `Tool call "${tool.name}" denied by policy: ${reason}` };
1532
+ }
1533
+ return { run: true, ...(d.mode ? { mode: d.mode } : {}), ...(approved ? { approval: { id: approved.approvalId, by: approved.by } } : {}) };
1534
+ }
1535
+ const ask = d;
1536
+ if (approved) {
1537
+ // A stored approval satisfies the ask, but only if its approver is one this ask accepts (§6.2).
1538
+ const problem = await (0, approval_1.approvalProblem)({ decision: 'approve', by: approved.by, at: new Date().toISOString() }, { principal, ...(ask.accepts ? { accepts: ask.accepts } : {}) }, (by) => this.agentCanPerform(by, call));
1539
+ if (problem) {
1540
+ const reason = `invalid approval: ${problem}`;
1541
+ return { run: false, decision: 'deny', reason, message: `Tool call "${tool.name}" not run: ${reason}` };
1542
+ }
1543
+ return { run: true, approval: { id: approved.approvalId, by: approved.by } };
1544
+ }
1545
+ return this.serialize(() => this.resolveAsk(principal, call, ask, sandboxAsk, sandboxDecisions));
1546
+ }
1547
+ async resolveAsk(principal, call, d, sandboxAsk, sandboxDecisions) {
1548
+ const name = call.tool.name;
1549
+ const request = {
1550
+ id: (0, node_crypto_1.randomUUID)(), principal, subject: { kind: 'tool_call', call }, reason: d.reason,
1551
+ ...(d.approver ? { approver: d.approver } : {}),
1552
+ ...(d.accepts ? { accepts: d.accepts } : {}),
1553
+ createdAt: new Date().toISOString(),
1554
+ };
1555
+ if (this.approver) {
1556
+ this.opts.transport.emit({
1557
+ type: 'tool_approval_request', tool_name: name, agent_id: principal.agentId,
1558
+ args_preview: JSON.stringify(call.args).slice(0, 200),
1559
+ });
1560
+ let answer;
1561
+ try {
1562
+ answer = await this.approver.request(request);
1563
+ }
1564
+ catch (err) {
1565
+ const reason = `the approver failed: ${err instanceof Error ? err.message : String(err)}`;
1566
+ return { run: false, decision: 'deny', reason, message: `Tool call "${name}" not run: ${reason}` };
1567
+ }
1568
+ if (answer.decision !== 'approve') {
1569
+ return {
1570
+ run: false, decision: 'deny', reason: answer.reason ?? 'rejected by the approver',
1571
+ message: `Tool call "${name}" was rejected by the approver.`,
1572
+ };
1573
+ }
1574
+ const problem = await (0, approval_1.approvalProblem)(answer, request, (by) => this.agentCanPerform(by, call));
1575
+ if (problem) {
1576
+ const reason = `invalid approval: ${problem}`;
1577
+ return { run: false, decision: 'deny', reason, message: `Tool call "${name}" not run: ${reason}` };
1578
+ }
1579
+ return { run: true, approval: { id: request.id, by: answer.by } };
1580
+ }
1581
+ if (this.opts.approvals) {
1582
+ await this.opts.approvals.put(request);
1583
+ return {
1584
+ run: false, decision: 'ask', reason: d.reason,
1585
+ message: `Tool call "${name}" needs approval (${d.reason}) and is pending as request ${request.id}. ` +
1586
+ 'It has NOT run; it will run once someone approves it.',
1587
+ };
1588
+ }
1589
+ if (sandboxAsk)
1590
+ return this.noApproverForSandbox(name, principal.agentId, sandboxDecisions);
1591
+ const reason = `needs approval (${d.reason}) and no approver is configured`;
1592
+ return { run: false, decision: 'deny', reason, message: `Tool call "${name}" refused: ${reason}.` };
1593
+ }
1594
+ /**
1595
+ * Rule 3 of SPEC-0014 §6.2: an agent approves only what it could do itself. It must be registered, have the
1596
+ * tool in its allowedTools, and the policies must allow the same call with that agent as principal.
1597
+ */
1598
+ async agentCanPerform(by, call) {
1599
+ const approverProfile = this.opts.agents.get(by.id);
1600
+ if (!approverProfile)
1601
+ return false;
1602
+ if (!approverProfile.allowedTools.includes(call.tool.name))
1603
+ return false;
1604
+ const d = await (0, policy_1.evaluatePolicies)(this.policies, this.principalFor(by.id, by.chain ?? [by.id]), { tool: call.tool, args: call.args });
1605
+ return (0, policy_1.agentCouldPerform)(d);
1606
+ }
1607
+ async runToolDef(call, toolDef, agentId, depth = 0, sandboxDecisions, principal, dryRun = false) {
1240
1608
  const controller = new AbortController();
1241
1609
  this.toolControllers.add(controller);
1242
1610
  const secrets = await (0, secrets_1.resolveSecrets)(this.opts.agents.get(agentId), this.opts.secretResolver);
1243
1611
  const ctx = {
1244
- ...this.buildContext(agentId, depth),
1612
+ ...this.buildContext(agentId, depth, principal?.chain),
1613
+ ...(dryRun ? { dryRun: true } : {}),
1245
1614
  ...(Object.keys(secrets).length ? { secrets } : {}),
1246
1615
  ...(this.opts.jobs ? { jobs: this.opts.jobs } : {}),
1247
- ...(this.opts.sandbox ? { sandbox: this.sandboxFor(agentId) } : {}),
1616
+ ...(this.opts.sandbox ? { sandbox: this.sandboxFor(agentId, sandboxDecisions) } : {}),
1248
1617
  signal: controller.signal,
1249
1618
  };
1250
1619
  const timeoutMs = toolDef.timeoutMs ?? this.opts.toolTimeoutMs;
@@ -1302,12 +1671,62 @@ class AgentEngine {
1302
1671
  unregisterMCPServer(serverName) {
1303
1672
  this.mcpRegistrar.unregisterServer(serverName);
1304
1673
  }
1305
- /** Disable approval gate for the rest of this session (approve_all). */
1306
- disableToolApproval() { this.approvalGate.disable(); }
1674
+ /**
1675
+ * Disable approval for the rest of this session (approve_all). In the policy path it affects only the adapted
1676
+ * onToolApproval callback, and never covers what only a person may approve (destructive tools, package installs).
1677
+ */
1678
+ disableToolApproval() { this.approvalGate.disable(); this.callbackApprover?.disable(); }
1307
1679
  /** Re-enable approval gate (e.g. after /iteration manual). */
1308
- enableToolApproval() { this.approvalGate.enable(); }
1309
- buildContext(agentId, depth = 0) {
1680
+ enableToolApproval() { this.approvalGate.enable(); this.callbackApprover?.enable(); }
1681
+ /** The principal of a call: this engine's identity, the executing agent and its delegation chain. */
1682
+ principalFor(agentId, chain) {
1683
+ return {
1684
+ ...this.opts.identity,
1685
+ agentId,
1686
+ sessionId: this.opts.sessionId ?? 'default',
1687
+ chain: chain && chain.length > 0 ? chain : [agentId],
1688
+ };
1689
+ }
1690
+ /**
1691
+ * Writes the single `AuditEvent` of a tool call (or delegation). Arguments only as a hash: the raw JSON string
1692
+ * the model produced is parsed when it can be (so equal arguments hash equal whatever their key order) and
1693
+ * hashed as text when it cannot.
1694
+ */
1695
+ async recordAudit(c) {
1696
+ if (!this.audit.enabled)
1697
+ return;
1698
+ let args = c.rawArgs;
1699
+ if (typeof c.rawArgs === 'string') {
1700
+ try {
1701
+ args = JSON.parse(c.rawArgs);
1702
+ }
1703
+ catch {
1704
+ args = c.rawArgs;
1705
+ }
1706
+ }
1707
+ const p = this.principalFor(c.agentId, c.chain);
1708
+ const event = {
1709
+ at: new Date(c.startedAt).toISOString(),
1710
+ principal: {
1711
+ agentId: p.agentId, sessionId: p.sessionId, chain: p.chain,
1712
+ ...(p.tenantId !== undefined ? { tenantId: p.tenantId } : {}),
1713
+ ...(p.userId !== undefined ? { userId: p.userId } : {}),
1714
+ },
1715
+ tool: c.tool,
1716
+ argsHash: (0, canonical_json_1.hashArgs)(args),
1717
+ decision: c.decision,
1718
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
1719
+ ...(c.outcome !== undefined ? { outcome: c.outcome } : {}),
1720
+ durationMs: Date.now() - c.startedAt,
1721
+ ...(c.approval ? { approval: c.approval } : {}),
1722
+ ...(c.sandbox && c.sandbox.length > 0 ? { sandbox: c.sandbox } : {}),
1723
+ ...(c.meta ? { meta: c.meta } : {}),
1724
+ };
1725
+ await this.audit.write(event);
1726
+ }
1727
+ buildContext(agentId, depth = 0, chain) {
1310
1728
  const id = agentId ?? this.currentAgentId;
1729
+ const principal = this.principalFor(id, chain);
1311
1730
  const profile = this.opts.agents.get(id);
1312
1731
  const storeRoot = this.opts.store?.projectDir;
1313
1732
  const additionalRoots = [
@@ -1317,6 +1736,7 @@ class AgentEngine {
1317
1736
  return {
1318
1737
  agentId: id,
1319
1738
  sessionId: this.opts.sessionId ?? 'default',
1739
+ principal,
1320
1740
  workingDir: this.opts.workingDir,
1321
1741
  memory: this.memory,
1322
1742
  store: this.opts.store,
@@ -1324,7 +1744,7 @@ class AgentEngine {
1324
1744
  ...(additionalRoots.length ? { additionalRoots } : {}),
1325
1745
  ...(profile?.blockedCommands?.length ? { blockedCommands: profile.blockedCommands } : {}),
1326
1746
  askAgent: async (agentId, question, context) => {
1327
- const result = await this.bus.runSingle({ agentId, question, context, fromAgentId: id, depth: depth + 1 });
1747
+ const result = await this.bus.runSingle({ agentId, question, context, fromAgentId: id, depth: depth + 1, chain: principal.chain });
1328
1748
  return result.content;
1329
1749
  },
1330
1750
  emitCompacting: (phase, label) => {