@backendkit-labs/agent-core 0.37.2 → 0.39.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 (102) 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 +109 -25
  7. package/dist/engine/AgentEngine.d.ts.map +1 -1
  8. package/dist/engine/AgentEngine.js +467 -139
  9. package/dist/engine/AgentEngine.js.map +1 -1
  10. package/dist/engine/ApprovalGate.d.ts +4 -3
  11. package/dist/engine/ApprovalGate.d.ts.map +1 -1
  12. package/dist/engine/ApprovalGate.js +9 -13
  13. package/dist/engine/ApprovalGate.js.map +1 -1
  14. package/dist/engine/MCPRegistrar.js +1 -1
  15. package/dist/engine/MCPRegistrar.js.map +1 -1
  16. package/dist/engine/coding-pipeline-hooks.d.ts +28 -0
  17. package/dist/engine/coding-pipeline-hooks.d.ts.map +1 -0
  18. package/dist/engine/coding-pipeline-hooks.js +91 -0
  19. package/dist/engine/coding-pipeline-hooks.js.map +1 -0
  20. package/dist/engine/createBaseEngine.d.ts +32 -25
  21. package/dist/engine/createBaseEngine.d.ts.map +1 -1
  22. package/dist/engine/createBaseEngine.js +8 -6
  23. package/dist/engine/createBaseEngine.js.map +1 -1
  24. package/dist/engine/package-install.d.ts +7 -0
  25. package/dist/engine/package-install.d.ts.map +1 -1
  26. package/dist/engine/package-install.js +17 -0
  27. package/dist/engine/package-install.js.map +1 -1
  28. package/dist/engine/qa-orchestrator.d.ts +11 -12
  29. package/dist/engine/qa-orchestrator.d.ts.map +1 -1
  30. package/dist/engine/qa-orchestrator.js +13 -16
  31. package/dist/engine/qa-orchestrator.js.map +1 -1
  32. package/dist/governance/approval-store.d.ts +32 -0
  33. package/dist/governance/approval-store.d.ts.map +1 -0
  34. package/dist/governance/approval-store.js +129 -0
  35. package/dist/governance/approval-store.js.map +1 -0
  36. package/dist/governance/approval.d.ts +35 -0
  37. package/dist/governance/approval.d.ts.map +1 -0
  38. package/dist/governance/approval.js +65 -0
  39. package/dist/governance/approval.js.map +1 -0
  40. package/dist/governance/approvers.d.ts +24 -0
  41. package/dist/governance/approvers.d.ts.map +1 -0
  42. package/dist/governance/approvers.js +69 -0
  43. package/dist/governance/approvers.js.map +1 -0
  44. package/dist/governance/audit.d.ts +101 -0
  45. package/dist/governance/audit.d.ts.map +1 -0
  46. package/dist/governance/audit.js +178 -0
  47. package/dist/governance/audit.js.map +1 -0
  48. package/dist/governance/hooks.d.ts +62 -0
  49. package/dist/governance/hooks.d.ts.map +1 -0
  50. package/dist/governance/hooks.js +26 -0
  51. package/dist/governance/hooks.js.map +1 -0
  52. package/dist/governance/policy.d.ts +33 -0
  53. package/dist/governance/policy.d.ts.map +1 -0
  54. package/dist/governance/policy.js +115 -0
  55. package/dist/governance/policy.js.map +1 -0
  56. package/dist/governance/types.d.ts +162 -0
  57. package/dist/governance/types.d.ts.map +1 -0
  58. package/dist/governance/types.js +3 -0
  59. package/dist/governance/types.js.map +1 -0
  60. package/dist/index.d.ts +18 -12
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +53 -16
  63. package/dist/index.js.map +1 -1
  64. package/dist/mcp/tool-server-http.d.ts +2 -6
  65. package/dist/mcp/tool-server-http.d.ts.map +1 -1
  66. package/dist/mcp/tool-server-http.js +4 -20
  67. package/dist/mcp/tool-server-http.js.map +1 -1
  68. package/dist/mcp/tool-server.d.ts +18 -4
  69. package/dist/mcp/tool-server.d.ts.map +1 -1
  70. package/dist/mcp/tool-server.js +110 -22
  71. package/dist/mcp/tool-server.js.map +1 -1
  72. package/dist/reflection/index.d.ts +0 -7
  73. package/dist/reflection/index.d.ts.map +1 -1
  74. package/dist/reflection/index.js +1 -16
  75. package/dist/reflection/index.js.map +1 -1
  76. package/dist/sandbox/types.d.ts +2 -2
  77. package/dist/sandbox/types.d.ts.map +1 -1
  78. package/dist/shared/llm/chat-client.d.ts +16 -0
  79. package/dist/shared/llm/chat-client.d.ts.map +1 -0
  80. package/dist/shared/llm/chat-client.js +27 -0
  81. package/dist/shared/llm/chat-client.js.map +1 -0
  82. package/dist/shared/llm/resilient-client.d.ts +1 -1
  83. package/dist/shared/llm/resilient-client.d.ts.map +1 -1
  84. package/dist/shared/utils/canonical-json.d.ts +12 -0
  85. package/dist/shared/utils/canonical-json.d.ts.map +1 -0
  86. package/dist/shared/utils/canonical-json.js +29 -0
  87. package/dist/shared/utils/canonical-json.js.map +1 -0
  88. package/dist/shared/utils/loopback.d.ts +10 -0
  89. package/dist/shared/utils/loopback.d.ts.map +1 -0
  90. package/dist/shared/utils/loopback.js +25 -0
  91. package/dist/shared/utils/loopback.js.map +1 -0
  92. package/dist/tools/defineTool.d.ts +2 -0
  93. package/dist/tools/defineTool.d.ts.map +1 -1
  94. package/dist/tools/defineTool.js +1 -0
  95. package/dist/tools/defineTool.js.map +1 -1
  96. package/dist/tools/services.d.ts +7 -0
  97. package/dist/tools/services.d.ts.map +1 -0
  98. package/dist/tools/services.js +11 -0
  99. package/dist/tools/services.js.map +1 -0
  100. package/dist/types/index.d.ts +24 -38
  101. package/dist/types/index.d.ts.map +1 -1
  102. package/package.json +89 -93
@@ -9,12 +9,17 @@ 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 hooks_1 = require("../governance/hooks");
17
+ const canonical_json_1 = require("../shared/utils/canonical-json");
12
18
  const DelegationBus_1 = require("../delegation/DelegationBus");
13
19
  const SessionMemory_1 = require("../memory/SessionMemory");
14
20
  const activator_1 = require("../skills/activator");
15
21
  const WorkflowRunner_1 = require("../workflow/WorkflowRunner");
16
22
  const IterationManager_1 = require("./IterationManager");
17
- const qa_orchestrator_1 = require("./qa-orchestrator");
18
23
  const MAX_INPUT_BYTES = 100_000; // Fix #17: 100 KB hard cap on user input
19
24
  const ASK_AGENT_TOOL = {
20
25
  name: 'ask_agent',
@@ -30,6 +35,9 @@ const ASK_AGENT_TOOL = {
30
35
  },
31
36
  required: ['agent_id', 'question'],
32
37
  },
38
+ // Delegating changes nothing by itself: what the delegate does is decided and audited call by call. So the
39
+ // default policy lets delegation through; an explicit policy still sees it (tool name 'ask_agent').
40
+ readOnly: true,
33
41
  execute: async () => '',
34
42
  };
35
43
  const generateObject_1 = require("../structured/generateObject");
@@ -60,6 +68,19 @@ class AgentEngine {
60
68
  /** Uncalibrated token estimate of the last request sent by runLoop, to calibrate against real usage. */
61
69
  lastRequestEstimate = 0;
62
70
  auditLogger;
71
+ audit;
72
+ /** Policy path (SPEC-0014 F2) instead of the legacy ApprovalGate: on when policy, approver or approvals is set. */
73
+ governed;
74
+ policies;
75
+ approver;
76
+ /** Set when the approver is the adapted onToolApproval callback, so disable/enableToolApproval reach it. */
77
+ callbackApprover;
78
+ hooks;
79
+ /** Context shared by the hooks of the turn in progress; undefined between turns. */
80
+ runCtx;
81
+ runController;
82
+ /** Last final answer of the model in the current turn (for afterRun). */
83
+ lastAnswer = '';
63
84
  currentAgentId;
64
85
  aborted = false;
65
86
  abortController = null;
@@ -98,6 +119,32 @@ class AgentEngine {
98
119
  });
99
120
  }
100
121
  this.auditLogger = new AuditLogger_1.AuditLogger(opts.auditLog);
122
+ // 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({
124
+ type: 'system', level: 'warn',
125
+ text: `[audit] a sink failed to record a tool call: ${err instanceof Error ? err.message : String(err)}`,
126
+ }));
127
+ this.hooks = opts.hooks ?? [];
128
+ this.governed = !!(opts.policy || opts.approver || opts.approvals);
129
+ if (this.governed) {
130
+ const someoneToAsk = !!(opts.approver || opts.approvals || opts.onToolApproval);
131
+ const configured = opts.policy ? (Array.isArray(opts.policy) ? opts.policy : [opts.policy]) : [];
132
+ // What a tool declares with `alwaysAsk` always asks a person, whatever the configured policy says.
133
+ this.policies = [
134
+ ...(configured.length > 0 ? configured : someoneToAsk ? [policy_1.defaultToolPolicy] : []),
135
+ policy_1.declaredAskPolicy,
136
+ ];
137
+ if (opts.approver) {
138
+ this.approver = opts.approver;
139
+ }
140
+ else if (opts.onToolApproval) {
141
+ this.callbackApprover = (0, approval_1.approverFromCallback)(opts.onToolApproval);
142
+ this.approver = this.callbackApprover;
143
+ }
144
+ }
145
+ else {
146
+ this.policies = [];
147
+ }
101
148
  this.mcpRegistrar = new MCPRegistrar_1.MCPRegistrar({
102
149
  mcpManager: opts.mcpManager,
103
150
  tools: opts.tools,
@@ -119,7 +166,7 @@ class AgentEngine {
119
166
  maxDepth: opts.maxDelegationDepth,
120
167
  agents: opts.agents,
121
168
  transport: opts.transport,
122
- runAgent: (id, question, context, depth, buf) => this.runAgentInternal(id, question, context, depth, buf),
169
+ runAgent: (id, question, context, depth, buf, chain) => this.runAgentInternal(id, question, context, depth, buf, chain),
123
170
  });
124
171
  }
125
172
  /**
@@ -352,25 +399,63 @@ class AgentEngine {
352
399
  const profile = this.getCurrentProfile();
353
400
  if (!profile)
354
401
  throw new Error(`Default agent "${this.currentAgentId}" not registered`);
355
- // Orquestar la tarea para obtener clasificacion, risk scoring y gates requeridos
356
- let orchestrationResult;
357
- if (this.opts.orchestrator) {
358
- try {
359
- orchestrationResult = await this.opts.orchestrator.orchestrate(input);
360
- }
361
- catch (err) {
362
- const reason = err instanceof Error ? err.message : String(err);
363
- if ((this.opts.orchestratorFailureMode ?? 'closed') === 'closed') {
364
- throw new Error(`Orchestrator failed; refusing to run without its gates: ${reason}`);
365
- }
366
- this.opts.transport.emit({ type: 'system', level: 'warn', text: `[Orchestrator] failed (${reason}); running without classification or gates` });
367
- }
402
+ // Hooks of this turn share one context (SPEC-0014 F3). A throwing hook fails the turn.
403
+ this.runController = new AbortController();
404
+ this.lastAnswer = '';
405
+ this.runCtx = {
406
+ principal: this.principalFor(profile.id),
407
+ input,
408
+ state: new Map(),
409
+ signal: this.runController.signal,
410
+ hasAgent: (id) => this.opts.agents.has(id),
411
+ emit: (event) => this.opts.transport.emit(event),
412
+ };
413
+ try {
414
+ await (0, hooks_1.runHooks)(this.hooks, 'beforeRun', h => h.beforeRun(this.runCtx));
415
+ this.history.push({ role: 'user', content: input });
416
+ await this.runLoop(profile);
417
+ this.saveHistory();
418
+ const finished = this.runCtx;
419
+ await (0, hooks_1.runHooks)(this.hooks, 'afterRun', h => h.afterRun(finished, { text: this.lastAnswer }));
420
+ }
421
+ finally {
422
+ this.runCtx = undefined;
423
+ this.runController = undefined;
368
424
  }
369
- this.history.push({ role: 'user', content: input });
370
- await this.runLoop(profile, orchestrationResult);
371
- this.saveHistory();
372
425
  this.opts.transport.emit({ type: 'done' });
373
426
  }
427
+ /** Sections the `systemPrompt` hooks add for `profile`. */
428
+ async hookPromptSections(profile) {
429
+ if (!this.runCtx || !this.hooks.some(h => h.systemPrompt))
430
+ return [];
431
+ const ctx = this.runCtx;
432
+ const sections = await (0, hooks_1.runHooks)(this.hooks, 'systemPrompt', h => h.systemPrompt(ctx, profile));
433
+ return sections.filter((s) => typeof s === 'string' && s.trim().length > 0);
434
+ }
435
+ /** The first `afterTurn` hook that asks to continue wins; the rest still run (they may only observe). */
436
+ async afterTurnHooks(profile, text) {
437
+ if (!this.runCtx || !this.hooks.some(h => h.afterTurn))
438
+ return undefined;
439
+ const ctx = this.runCtx;
440
+ const answers = await (0, hooks_1.runHooks)(this.hooks, 'afterTurn', h => h.afterTurn(ctx, { text, profile }));
441
+ return answers.find((a) => !!a && a.action === 'continue');
442
+ }
443
+ /** Arguments the model produced, as an object (anything else becomes `{}`). */
444
+ parseArgs(raw) {
445
+ try {
446
+ const parsed = JSON.parse(raw);
447
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
448
+ }
449
+ catch {
450
+ return {};
451
+ }
452
+ }
453
+ /** Context for a tool hook: the turn's context with the principal of the agent that makes the call. */
454
+ toolHookContext(principal) {
455
+ return this.runCtx
456
+ ? { ...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) };
458
+ }
374
459
  async runWorkflow(defOrBuilder, opts = {}) {
375
460
  if (this.pendingContextLoad)
376
461
  await this.pendingContextLoad;
@@ -384,8 +469,51 @@ class AgentEngine {
384
469
  });
385
470
  return runner.run();
386
471
  }
472
+ /**
473
+ * Runs a tool call that was stored as pending and has since been approved (SPEC-0014 §6, resubmission).
474
+ *
475
+ * - At most once: the store marks it executed atomically before it runs; a second call throws.
476
+ * - Everything is checked again (allowedTools, sandbox, guardrails, policies); the stored approval only
477
+ * satisfies an `ask`, and only if its approver is one that ask accepts. An approval that turns out not to be
478
+ * valid is consumed and audited as `deny`.
479
+ * - The result is returned to the caller (e.g. Hermes or a UI); it is not added to the conversation.
480
+ */
481
+ async runApproved(approvalId) {
482
+ const store = this.opts.approvals;
483
+ if (!store)
484
+ throw new Error('runApproved needs an approvals store');
485
+ await this.mcpRegistrar.ensureInitialized();
486
+ await this.ensureAgentsLoaded();
487
+ const item = await store.get(approvalId);
488
+ if (!item)
489
+ throw new Error(`approval "${approvalId}" does not exist`);
490
+ if (item.status === 'executed')
491
+ throw new Error(`approval "${approvalId}" was already executed`);
492
+ if (item.status !== 'approved' || !item.outcome)
493
+ throw new Error(`approval "${approvalId}" is ${item.status}, not approved`);
494
+ const subject = item.subject;
495
+ if (subject.kind !== 'tool_call' || !('call' in subject)) {
496
+ throw new Error(`approval "${approvalId}" is a ${subject.kind}; only tool calls are resumed by the engine`);
497
+ }
498
+ const profile = this.opts.agents.get(item.principal.agentId);
499
+ if (!profile)
500
+ throw new Error(`agent "${item.principal.agentId}" of approval "${approvalId}" is not registered`);
501
+ if (!(await store.markExecuted(approvalId)))
502
+ throw new Error(`approval "${approvalId}" was already executed`);
503
+ 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 });
504
+ }
505
+ /**
506
+ * Puts one question to an agent outside the conversation and returns its answer (its tool calls are governed
507
+ * like any other). Used by `agentApprover` to let a supervising agent approve or reject requests.
508
+ */
509
+ async consultAgent(agentId, question) {
510
+ await this.ensureAgentsLoaded();
511
+ const result = await this.runAgentInternal(agentId, question, undefined, 0, undefined, [agentId]);
512
+ return result.content;
513
+ }
387
514
  abort() {
388
515
  this.aborted = true;
516
+ this.runController?.abort('aborted');
389
517
  void this.opts.jobs?.cancelAll();
390
518
  this.abortController?.abort();
391
519
  this.abortController = null;
@@ -618,64 +746,24 @@ class AgentEngine {
618
746
  }
619
747
  return parts.join('\n');
620
748
  }
621
- buildSystemPrompt(profile, orchestrationResult) {
749
+ buildSystemPrompt(profile, hookSections = []) {
622
750
  const isOrchestrator = profile.id === this.opts.defaultAgentId;
623
751
  const parts = [profile.systemPrompt];
624
752
  if (isOrchestrator)
625
753
  parts.push(this.buildAgentRoster(profile.id));
626
754
  if (this.opts.workingDir) {
627
755
  parts.push(`## Working Directory\n` +
628
- `\`${this.opts.workingDir}\`\n\n` +
629
- `ALWAYS use RELATIVE paths with tools (e.g. \`src/index.ts\`, \`package.json\`). ` +
630
- `NEVER invent absolute paths like \`/workspace/...\` or \`/home/...\`.`);
756
+ `\`${this.opts.workingDir}\``);
631
757
  }
632
758
  if (this.opts.projectContext)
633
759
  parts.push(this.opts.projectContext);
634
- // Per-agent session notes (tool quirks, learnings routed by LearningRouter)
635
- const agentNotes = this.opts.store?.getAgentNotes?.(profile.id);
636
- if (agentNotes)
637
- parts.push(`## Agent Session Notes\n${agentNotes}`);
638
760
  if (this.memoryContextBlock)
639
761
  parts.push(this.memoryContextBlock);
640
762
  if (this.activeSkillAddition)
641
763
  parts.push(this.activeSkillAddition);
642
- if (isOrchestrator && orchestrationResult) {
643
- parts.push(this.buildOrchestrationBrief(orchestrationResult));
644
- }
764
+ parts.push(...hookSections);
645
765
  return parts.join('\n\n');
646
766
  }
647
- /**
648
- * Converts an OrchestrationResult into a system-prompt section that tells the
649
- * default agent which specialists to use, in what order, and what gates apply.
650
- * This closes the gap between the deterministic policy layer and the LLM layer.
651
- */
652
- buildOrchestrationBrief(result) {
653
- const { task, selectedAgents, agentPipeline, requiredGates } = result;
654
- const lines = ['## Orchestrator Analysis — Current Task'];
655
- const domains = task.domains.length > 0 ? task.domains.join(', ') : 'general';
656
- lines.push(`**Intent:** ${task.actionType} | **Risk:** ${task.riskLevel} | **Domains:** ${domains}`);
657
- // Only surface non-trivial agent selections (skip sole-fallback case)
658
- const nonFallback = selectedAgents.filter(a => !(a.agentId === 'general' && a.score <= 50));
659
- if (nonFallback.length > 0) {
660
- lines.push('\n**Recommended agents for this task (highest priority first):**');
661
- for (const a of nonFallback) {
662
- lines.push(`- ${a.agentId} — ${a.reason}`);
663
- }
664
- lines.push('\nWhen delegating via ask_agent, prioritize the agents listed above. ' +
665
- 'Do not delegate to unlisted agents unless the task explicitly requires it.');
666
- }
667
- if (agentPipeline && agentPipeline.length > 0) {
668
- lines.push('\n**Suggested execution pipeline (respect this order):**');
669
- agentPipeline.forEach((phase, i) => {
670
- lines.push(`${i + 1}. [${phase.phase}] ${phase.agentId} — ${phase.purpose}`);
671
- });
672
- }
673
- if (requiredGates.length > 0) {
674
- lines.push(`\n**Required gates before commit:** ${requiredGates.join(', ')}`);
675
- lines.push('Ensure each gate is satisfied before considering the task complete.');
676
- }
677
- return lines.join('\n');
678
- }
679
767
  resolvesDelegateTo(profile) {
680
768
  if (!profile.delegatesTo || profile.delegatesTo.length === 0)
681
769
  return [];
@@ -716,11 +804,12 @@ class AgentEngine {
716
804
  parts.push(`## Orchestrator Analysis\n${trimmed}`);
717
805
  return parts.join('\n\n');
718
806
  }
719
- async runLoop(profile, orchestrationResult) {
807
+ async runLoop(profile) {
720
808
  let currentProfile = profile;
721
809
  this.iterationManager.reset();
722
810
  const iterManager = this.iterationManager;
723
811
  let overflowRetries = 0;
812
+ let hookContinues = 0;
724
813
  this.opts.transport.emit({
725
814
  type: 'block_start',
726
815
  agent_id: profile.id,
@@ -735,7 +824,10 @@ class AgentEngine {
735
824
  break;
736
825
  this.announceFinishedJobs(currentProfile.id);
737
826
  await this.prepareContext();
738
- const systemMsg = { role: 'system', content: this.buildSystemPrompt(currentProfile, orchestrationResult) };
827
+ const systemMsg = {
828
+ role: 'system',
829
+ content: this.buildSystemPrompt(currentProfile, await this.hookPromptSections(currentProfile)),
830
+ };
739
831
  const tools = this.getToolsForAgent(currentProfile);
740
832
  const safeHistory = this.history.sanitized();
741
833
  if (this.contextManager) {
@@ -831,17 +923,48 @@ class AgentEngine {
831
923
  if (askAgentCalls.length > 0) {
832
924
  const validCalls = askAgentCalls.filter(c => c.agentId !== currentProfile.id);
833
925
  const selfCalls = askAgentCalls.filter(c => c.agentId === currentProfile.id);
926
+ // Delegations are audited like any tool call: one event each (SPEC-0014 F1).
927
+ const delegationArgs = (c) => ({ agent_id: c.agentId, question: c.question, ...(c.context !== undefined ? { context: c.context } : {}) });
834
928
  for (const call of selfCalls) {
929
+ const startedAt = Date.now();
835
930
  const msg = `Self-delegation blocked: agent "${currentProfile.id}" cannot delegate to itself. Execute the task directly.`;
836
931
  this.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: false, preview: msg });
837
932
  toolResults.push({ role: 'tool', tool_call_id: call.id, content: msg });
933
+ await this.recordAudit({
934
+ startedAt, agentId: currentProfile.id, tool: 'ask_agent', rawArgs: delegationArgs(call),
935
+ decision: 'not_allowed', reason: 'self-delegation',
936
+ });
838
937
  }
938
+ // In the policy path a delegation is a call like any other: the policies may deny it or ask first.
939
+ const callerChain = this.principalFor(currentProfile.id).chain;
940
+ const allowedCalls = [];
941
+ for (const call of validCalls) {
942
+ if (!this.governed) {
943
+ allowedCalls.push(call);
944
+ continue;
945
+ }
946
+ const startedAt = Date.now();
947
+ const verdict = await this.decideGoverned(ASK_AGENT_TOOL, JSON.stringify(delegationArgs(call)), this.principalFor(currentProfile.id, callerChain), []);
948
+ if (verdict.run) {
949
+ allowedCalls.push(call);
950
+ continue;
951
+ }
952
+ this.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: false, preview: verdict.message.slice(0, 120) });
953
+ toolResults.push({ role: 'tool', tool_call_id: call.id, content: verdict.message });
954
+ await this.recordAudit({
955
+ startedAt, agentId: currentProfile.id, chain: callerChain, tool: 'ask_agent',
956
+ rawArgs: delegationArgs(call), decision: verdict.decision, reason: verdict.reason,
957
+ });
958
+ }
959
+ validCalls.splice(0, validCalls.length, ...allowedCalls);
839
960
  if (validCalls.length > 0) {
961
+ const startedAt = Date.now();
840
962
  const requests = validCalls.map(c => ({
841
963
  agentId: c.agentId,
842
964
  question: c.question,
843
965
  context: this.buildSubAgentContext(c.context, streamBuffer),
844
966
  fromAgentId: currentProfile.id,
967
+ chain: callerChain,
845
968
  }));
846
969
  const results = validCalls.length >= 2
847
970
  ? await this.bus.runParallel(requests)
@@ -852,6 +975,11 @@ class AgentEngine {
852
975
  const content = result.error ? `Error: ${result.error}` : result.content;
853
976
  this.opts.transport.emit({ type: 'tool_result', name: 'ask_agent', success: !result.error, preview: content.slice(0, 120) });
854
977
  toolResults.push({ role: 'tool', tool_call_id: call.id, content });
978
+ await this.recordAudit({
979
+ startedAt, agentId: currentProfile.id, chain: callerChain, tool: 'ask_agent', rawArgs: delegationArgs(call),
980
+ decision: 'allow', ...(result.error ? { reason: result.error } : {}),
981
+ outcome: result.error ? 'error' : 'ok',
982
+ });
855
983
  }
856
984
  }
857
985
  }
@@ -886,51 +1014,38 @@ class AgentEngine {
886
1014
  toolResults.push({ role: 'tool', tool_call_id: call.id, content: results[i] });
887
1015
  });
888
1016
  }
889
- // ── QA orchestration: runs when response is final (no tool calls) ─
890
- if (toolResults.length === 0 && this.opts.orchestrator && this.opts.qaService && orchestrationResult) {
891
- const qaAgentId = this.opts.agents.has('qa-engineer') ? 'qa-engineer' : undefined;
892
- const qaCtx = {
893
- clean: streamBuffer,
894
- orchestrationResult,
895
- orchestrator: this.opts.orchestrator,
896
- qaService: this.opts.qaService,
897
- allAgents: this.opts.agents.getAll(),
898
- messages: this.history.getAll(),
899
- effectiveAgentId: currentProfile.id,
900
- defaultAgentId: this.opts.defaultAgentId,
901
- qaAgentId,
902
- noQA: this.opts.noQA,
903
- onQAReview: this.opts.onQAReview,
904
- setEffectiveAgent: (agentId) => {
905
- const p = this.opts.agents.get(agentId);
906
- if (p)
907
- currentProfile = p;
908
- },
909
- };
910
- await (0, qa_orchestrator_1.advanceRequiredGates)(qaCtx);
911
- const qaProfile = (0, qa_orchestrator_1.activateQaEngineerIfNeeded)(qaCtx);
912
- if (qaProfile) {
913
- currentProfile = qaProfile;
914
- continue; // re-enter loop as qa-engineer
915
- }
916
- if (qaAgentId && currentProfile.id === qaAgentId) {
917
- await (0, qa_orchestrator_1.processQaEngineerResponse)(qaCtx);
918
- currentProfile = profile; // reset to original agent
1017
+ if (toolResults.length === 0) {
1018
+ // The model answered without tools: afterTurn hooks may force another pass (SPEC-0014 F3).
1019
+ this.lastAnswer = streamBuffer;
1020
+ const next = await this.afterTurnHooks(currentProfile, streamBuffer);
1021
+ if (!next)
1022
+ break;
1023
+ const cap = this.opts.maxHookContinues ?? hooks_1.DEFAULT_MAX_HOOK_CONTINUES;
1024
+ if (hookContinues >= cap) {
1025
+ this.opts.transport.emit({ type: 'system', level: 'warn', text: `[hooks] afterTurn asked for more than ${cap} extra passes; stopping` });
1026
+ break;
919
1027
  }
920
- else {
921
- await (0, qa_orchestrator_1.processInlineQaReview)(qaCtx);
1028
+ hookContinues++;
1029
+ if (next.agentId) {
1030
+ const nextProfile = this.opts.agents.get(next.agentId);
1031
+ if (!nextProfile)
1032
+ throw new Error(`afterTurn hook asked to continue as unknown agent "${next.agentId}"`);
1033
+ currentProfile = nextProfile;
922
1034
  }
1035
+ if (next.message)
1036
+ this.history.push({ role: 'user', content: next.message });
1037
+ continue;
923
1038
  }
924
- if (toolResults.length === 0)
925
- break;
926
1039
  this.history.pushAll(toolResults);
927
1040
  }
928
1041
  this.opts.transport.emit({ type: 'block_end', status: 'ok', agent_id: profile.id });
929
1042
  }
930
- async runAgentInternal(agentId, question, context, depth = 0, outputBuffer) {
1043
+ async runAgentInternal(agentId, question, context, depth = 0, outputBuffer, chain) {
931
1044
  const profile = this.opts.agents.get(agentId);
932
1045
  if (!profile)
933
1046
  throw new Error(`Agent "${agentId}" not registered`);
1047
+ // Delegation chain of this sub-agent, oldest first (SPEC-0014 principal).
1048
+ const agentChain = chain && chain.length > 0 ? chain : [agentId];
934
1049
  const start = Date.now();
935
1050
  // Inject recent history from the orchestrator's conversation so specialists
936
1051
  // can see previously gathered data (file reads, command outputs, etc.)
@@ -949,7 +1064,7 @@ class AgentEngine {
949
1064
  historySlice = (0, HistoryManager_1.sanitizeMessages)(historySlice);
950
1065
  }
951
1066
  const messages = [
952
- { role: 'system', content: this.buildSystemPrompt(profile) },
1067
+ { role: 'system', content: this.buildSystemPrompt(profile, await this.hookPromptSections(profile)) },
953
1068
  ...historySlice,
954
1069
  { role: 'user', content: context ? `${question}\n\nContext:\n${context}` : question },
955
1070
  ];
@@ -1077,7 +1192,7 @@ class AgentEngine {
1077
1192
  if (tc)
1078
1193
  tc.function = { ...tc.function, arguments: '{"redacted":"blocked by guardrail"}' };
1079
1194
  }
1080
- });
1195
+ }, agentChain);
1081
1196
  toolResults.push({ role: 'tool', tool_call_id: call.id, content: result });
1082
1197
  }
1083
1198
  messages.push(...toolResults);
@@ -1092,14 +1207,14 @@ class AgentEngine {
1092
1207
  * outcome is reported on THIS engine's transport and audit log. A runner shared by several engines therefore
1093
1208
  * never leaks one engine's decisions to another.
1094
1209
  */
1095
- sandboxFor(agentId) {
1210
+ sandboxFor(agentId, collect) {
1096
1211
  const real = this.opts.sandbox;
1097
1212
  return Object.assign(Object.create(real), {
1098
1213
  run: async (caller, req) => {
1099
1214
  const out = await real.run(caller, req);
1100
1215
  this.reportSandboxDecision(out.ok
1101
1216
  ? { 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 });
1217
+ : { outcome: out.code, tool: req.tool, agentId, mode: out.mode, network: out.network, backend: out.backend, reason: out.reason }, collect);
1103
1218
  return out;
1104
1219
  },
1105
1220
  ...(real.authorizePath ? {
@@ -1107,23 +1222,32 @@ class AgentEngine {
1107
1222
  const verdict = real.authorizePath(caller, req);
1108
1223
  // Allowed reads are not reported (every file read would be an event); denials and writes are.
1109
1224
  if (!verdict.ok)
1110
- this.reportSandboxDecision({ outcome: verdict.code, tool: req.tool, agentId, reason: verdict.reason });
1225
+ this.reportSandboxDecision({ outcome: verdict.code, tool: req.tool, agentId, reason: verdict.reason }, collect);
1111
1226
  else if (req.access === 'write')
1112
- this.reportSandboxDecision({ outcome: 'allowed', tool: req.tool, agentId });
1227
+ this.reportSandboxDecision({ outcome: 'allowed', tool: req.tool, agentId }, collect);
1113
1228
  return verdict;
1114
1229
  },
1115
1230
  } : {}),
1116
1231
  });
1117
1232
  }
1118
1233
  /** The message for the model when the sandbox policy refuses `tool` for `agentId`; undefined when allowed. */
1119
- sandboxRefusal(tool, agentId) {
1234
+ sandboxRefusal(tool, agentId, collect) {
1120
1235
  const verdict = this.opts.sandbox?.authorizeTool?.({ agentId, sessionId: this.opts.sessionId ?? 'default' }, tool);
1121
1236
  if (!verdict || verdict.ok)
1122
1237
  return undefined;
1123
- this.reportSandboxDecision({ outcome: verdict.code, tool, agentId, reason: verdict.reason });
1238
+ this.reportSandboxDecision({ outcome: verdict.code, tool, agentId, reason: verdict.reason }, collect);
1124
1239
  return `Tool call "${tool}" refused by the sandbox policy (${verdict.code}): ${verdict.reason}`;
1125
1240
  }
1126
- reportSandboxDecision(d) {
1241
+ /**
1242
+ * Reports a sandbox decision on the transport and the legacy audit log, and, when `collect` is given, adds it to
1243
+ * the decisions the single `AuditEvent` of the current tool call will carry.
1244
+ */
1245
+ reportSandboxDecision(d, collect) {
1246
+ collect?.push({
1247
+ outcome: d.outcome,
1248
+ ...(d.mode ? { mode: d.mode } : {}), ...(d.network ? { network: d.network } : {}),
1249
+ ...(d.backend ? { backend: d.backend } : {}), ...(d.reason ? { reason: d.reason } : {}),
1250
+ });
1127
1251
  this.opts.transport.emit({
1128
1252
  type: 'sandbox', outcome: d.outcome, tool: d.tool, agent_id: d.agentId,
1129
1253
  ...(d.mode ? { mode: d.mode } : {}), ...(d.network ? { network: d.network } : {}),
@@ -1138,21 +1262,34 @@ class AgentEngine {
1138
1262
  /**
1139
1263
  * Unified tool execution used by both runLoop (primary agent) and
1140
1264
  * runAgentInternal (sub-agents via ask_agent).
1141
- * Handles: allowedTools authorization → onToolApproval gate → execute → audit → transport.
1265
+ * Handles: allowedTools → sandbox refusal → argument guardrails → policy/approval (or the legacy gate)
1266
+ * → execute → result guardrails → audit → transport.
1142
1267
  */
1143
1268
  async executeToolCall(call, profile, depth = 0, emit,
1144
1269
  /** Called when a guardrail refused the arguments, so the caller can scrub them from its history. */
1145
- onArgsRefused) {
1270
+ onArgsRefused,
1271
+ /** Delegation chain of `profile`, oldest first. Default `[profile.id]`. */
1272
+ chain,
1273
+ /** Set only by `runApproved`: this exact call was approved and stored (resubmission, SPEC-0014 §6). */
1274
+ approved) {
1146
1275
  const emitEvent = emit ?? ((e) => this.opts.transport.emit(e));
1147
1276
  const callStart = Date.now();
1148
1277
  const toolDef = this.opts.tools.get(call.name);
1278
+ const principal = this.principalFor(profile.id, chain);
1149
1279
  let result;
1150
1280
  let success;
1151
1281
  let outcome;
1152
1282
  let sandboxRefusal;
1283
+ // What the single audit event of this call records (SPEC-0014 F1).
1284
+ let decision = 'allow';
1285
+ let reason;
1286
+ let ran = false;
1287
+ let approval;
1288
+ const sandboxDecisions = [];
1153
1289
  if (!toolDef) {
1154
1290
  result = `Tool "${call.name}" not found`;
1155
1291
  success = false;
1292
+ decision = 'not_found';
1156
1293
  }
1157
1294
  else if (!profile.allowedTools.includes(call.name) &&
1158
1295
  !(this.opts.allowUnlistedTools && profile.allowedTools.length === 0 && !(profile.delegatesTo && profile.delegatesTo.length > 0))) {
@@ -1161,11 +1298,15 @@ class AgentEngine {
1161
1298
  ? `Use ask_agent to delegate to a specialist.`
1162
1299
  : `Add it to the agent's allowedTools if it should be able to use it.`);
1163
1300
  success = false;
1301
+ decision = 'not_allowed';
1302
+ reason = `not in the allowedTools of agent "${profile.id}"`;
1164
1303
  }
1165
- else if ((sandboxRefusal = this.sandboxRefusal(call.name, profile.id)) !== undefined) {
1304
+ else if ((sandboxRefusal = this.sandboxRefusal(call.name, profile.id, sandboxDecisions)) !== undefined) {
1166
1305
  // The policy refuses this tool outright (e.g. a writer while read-only). Nobody is asked and nothing runs.
1167
1306
  result = sandboxRefusal;
1168
1307
  success = false;
1308
+ decision = 'sandbox_denied';
1309
+ reason = sandboxDecisions[sandboxDecisions.length - 1]?.reason;
1169
1310
  }
1170
1311
  else {
1171
1312
  // Guardrails on the arguments run before approval: nobody is asked to approve a blocked call.
@@ -1189,33 +1330,57 @@ class AgentEngine {
1189
1330
  if (withheld) {
1190
1331
  result = withheld;
1191
1332
  success = false;
1333
+ decision = 'guardrail_blocked';
1334
+ reason = withheld;
1192
1335
  onArgsRefused?.();
1193
1336
  }
1194
1337
  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.`;
1338
+ const verdict = this.governed
1339
+ ? await this.decideGoverned(toolDef, effective.args, principal, sandboxDecisions, approved)
1340
+ : await this.decideLegacy(effective, profile.id, sandboxDecisions);
1341
+ if (!verdict.run) {
1342
+ result = verdict.message;
1204
1343
  success = false;
1344
+ decision = verdict.decision;
1345
+ reason = verdict.reason;
1205
1346
  }
1206
1347
  else {
1207
- ({ result, success, outcome } = await this.runToolDef(effective, toolDef, profile.id, depth));
1348
+ ran = true;
1349
+ approval = verdict.approval;
1350
+ const toolHooks = this.hooks.some(h => h.beforeTool || h.afterTool);
1351
+ const hookCall = toolHooks ? { tool: toolDef, args: this.parseArgs(effective.args) } : undefined;
1352
+ const hookCtx = toolHooks ? this.toolHookContext(principal) : undefined;
1353
+ if (hookCall && hookCtx)
1354
+ 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'));
1208
1356
  if (this.guardrails?.has('tool_result')) {
1209
1357
  const checked = await this.guard('tool_result', result, profile.id, call.name);
1210
1358
  result = checked.blocked
1211
1359
  ? `[Tool result withheld by guardrail "${checked.blocked.guardrail}": ${checked.blocked.reason}]`
1212
1360
  : checked.content;
1213
1361
  }
1362
+ if (hookCall && hookCtx) {
1363
+ const finalResult = { text: result, success };
1364
+ await (0, hooks_1.runHooks)(this.hooks, 'afterTool', h => h.afterTool(hookCtx, hookCall, finalResult));
1365
+ }
1214
1366
  }
1215
1367
  }
1216
1368
  call = effective;
1217
1369
  }
1218
1370
  await this.auditLogger.log({ agentId: profile.id, tool: call.name, inputPreview: call.args, success, durationMs: Date.now() - callStart, sessionId: this.opts.sessionId });
1371
+ await this.recordAudit({
1372
+ startedAt: callStart,
1373
+ agentId: profile.id,
1374
+ chain: principal.chain,
1375
+ tool: call.name,
1376
+ rawArgs: call.args,
1377
+ decision,
1378
+ reason,
1379
+ outcome: ran ? (outcome ?? (success ? 'ok' : 'error')) : undefined,
1380
+ approval,
1381
+ sandbox: sandboxDecisions,
1382
+ meta: toolDef?.meta,
1383
+ });
1219
1384
  // Strip ANSI before slicing to avoid partial escape sequences in the preview
1220
1385
  // eslint-disable-next-line no-control-regex
1221
1386
  const cleanPreview = result.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
@@ -1228,23 +1393,136 @@ class AgentEngine {
1228
1393
  }
1229
1394
  /** Approval checks never overlap and run in call order, even inside a parallel wave. */
1230
1395
  gateQueue = Promise.resolve();
1231
- checkGateSerial(call, agentId) {
1396
+ serialize(work) {
1397
+ const next = this.gateQueue.then(work);
1398
+ this.gateQueue = next.catch(() => undefined);
1399
+ return next;
1400
+ }
1401
+ /** The legacy gate (onToolApproval + the built-in list of tools that ask), unchanged, as a verdict. */
1402
+ async decideLegacy(call, agentId, sandboxDecisions) {
1232
1403
  const sandboxAsk = this.opts.sandbox?.approvalFor
1233
1404
  ? this.opts.sandbox.approvalFor({ agentId, sessionId: this.opts.sessionId ?? 'default' }, call.name)
1234
1405
  : undefined;
1235
- const next = this.gateQueue.then(() => this.approvalGate.check(call, agentId, sandboxAsk));
1236
- this.gateQueue = next.catch(() => undefined);
1237
- return next;
1406
+ const gate = await this.serialize(() => this.approvalGate.check(call, agentId, sandboxAsk, this.opts.tools.get(call.name)));
1407
+ if (gate === 'rejected') {
1408
+ return { run: false, decision: 'deny', reason: 'rejected by the approver', message: `Tool call "${call.name}" was rejected by the user.` };
1409
+ }
1410
+ if (gate === 'no-approver')
1411
+ return this.noApproverForSandbox(call.name, agentId, sandboxDecisions);
1412
+ return { run: true };
1413
+ }
1414
+ noApproverForSandbox(tool, agentId, sandboxDecisions) {
1415
+ const reason = `tool "${tool}" needs approval under the sandbox policy and no approver is configured`;
1416
+ this.reportSandboxDecision({ outcome: 'SANDBOX_DENIED', tool, agentId, reason }, sandboxDecisions);
1417
+ return {
1418
+ run: false, decision: 'sandbox_denied', reason,
1419
+ message: `Tool call "${tool}" refused (SANDBOX_DENIED): needs approval under the sandbox policy and no approver is configured.`,
1420
+ };
1421
+ }
1422
+ /**
1423
+ * The policy path (SPEC-0014 §2, F2): the policies decide on the arguments that would really run (after the
1424
+ * guardrails), a sandbox that wants approval adds an `ask`, and an `ask` goes to the approver in call order or,
1425
+ * when nobody answers now, to the durable store.
1426
+ */
1427
+ async decideGoverned(tool, rawArgs, principal, sandboxDecisions, approved) {
1428
+ // `approved` is never taken from what the model sent: only `runApproved`, which holds a stored approval, sets it.
1429
+ const call = { tool, args: this.parseArgs(rawArgs), ...(approved ? { approved } : {}) };
1430
+ const sandboxAsk = this.opts.sandbox?.approvalFor?.({ agentId: principal.agentId, sessionId: principal.sessionId }, tool.name) === 'ask';
1431
+ let d = await (0, policy_1.evaluatePolicies)(this.policies, principal, call);
1432
+ if (sandboxAsk)
1433
+ d = (0, policy_1.combineDecisions)([d, { effect: 'ask', reason: 'the sandbox policy requires approval' }]);
1434
+ if (d.effect === 'deny') {
1435
+ return { run: false, decision: 'deny', reason: d.reason, message: `Tool call "${tool.name}" denied by policy: ${d.reason}` };
1436
+ }
1437
+ if (d.effect === 'allow') {
1438
+ if (d.mode === 'sandboxed' && !this.opts.sandbox) {
1439
+ const reason = 'the policy requires a sandbox and none is configured';
1440
+ return { run: false, decision: 'deny', reason, message: `Tool call "${tool.name}" denied by policy: ${reason}` };
1441
+ }
1442
+ return { run: true, ...(d.mode ? { mode: d.mode } : {}), ...(approved ? { approval: { id: approved.approvalId, by: approved.by } } : {}) };
1443
+ }
1444
+ const ask = d;
1445
+ if (approved) {
1446
+ // A stored approval satisfies the ask, but only if its approver is one this ask accepts (§6.2).
1447
+ 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));
1448
+ if (problem) {
1449
+ const reason = `invalid approval: ${problem}`;
1450
+ return { run: false, decision: 'deny', reason, message: `Tool call "${tool.name}" not run: ${reason}` };
1451
+ }
1452
+ return { run: true, approval: { id: approved.approvalId, by: approved.by } };
1453
+ }
1454
+ return this.serialize(() => this.resolveAsk(principal, call, ask, sandboxAsk, sandboxDecisions));
1455
+ }
1456
+ async resolveAsk(principal, call, d, sandboxAsk, sandboxDecisions) {
1457
+ const name = call.tool.name;
1458
+ const request = {
1459
+ id: (0, node_crypto_1.randomUUID)(), principal, subject: { kind: 'tool_call', call }, reason: d.reason,
1460
+ ...(d.approver ? { approver: d.approver } : {}),
1461
+ ...(d.accepts ? { accepts: d.accepts } : {}),
1462
+ createdAt: new Date().toISOString(),
1463
+ };
1464
+ if (this.approver) {
1465
+ this.opts.transport.emit({
1466
+ type: 'tool_approval_request', tool_name: name, agent_id: principal.agentId,
1467
+ args_preview: JSON.stringify(call.args).slice(0, 200),
1468
+ });
1469
+ let answer;
1470
+ try {
1471
+ answer = await this.approver.request(request);
1472
+ }
1473
+ catch (err) {
1474
+ const reason = `the approver failed: ${err instanceof Error ? err.message : String(err)}`;
1475
+ return { run: false, decision: 'deny', reason, message: `Tool call "${name}" not run: ${reason}` };
1476
+ }
1477
+ if (answer.decision !== 'approve') {
1478
+ return {
1479
+ run: false, decision: 'deny', reason: answer.reason ?? 'rejected by the approver',
1480
+ message: `Tool call "${name}" was rejected by the approver.`,
1481
+ };
1482
+ }
1483
+ const problem = await (0, approval_1.approvalProblem)(answer, request, (by) => this.agentCanPerform(by, call));
1484
+ if (problem) {
1485
+ const reason = `invalid approval: ${problem}`;
1486
+ return { run: false, decision: 'deny', reason, message: `Tool call "${name}" not run: ${reason}` };
1487
+ }
1488
+ return { run: true, approval: { id: request.id, by: answer.by } };
1489
+ }
1490
+ if (this.opts.approvals) {
1491
+ await this.opts.approvals.put(request);
1492
+ return {
1493
+ run: false, decision: 'ask', reason: d.reason,
1494
+ message: `Tool call "${name}" needs approval (${d.reason}) and is pending as request ${request.id}. ` +
1495
+ 'It has NOT run; it will run once someone approves it.',
1496
+ };
1497
+ }
1498
+ if (sandboxAsk)
1499
+ return this.noApproverForSandbox(name, principal.agentId, sandboxDecisions);
1500
+ const reason = `needs approval (${d.reason}) and no approver is configured`;
1501
+ return { run: false, decision: 'deny', reason, message: `Tool call "${name}" refused: ${reason}.` };
1238
1502
  }
1239
- async runToolDef(call, toolDef, agentId, depth = 0) {
1503
+ /**
1504
+ * Rule 3 of SPEC-0014 §6.2: an agent approves only what it could do itself. It must be registered, have the
1505
+ * tool in its allowedTools, and the policies must allow the same call with that agent as principal.
1506
+ */
1507
+ async agentCanPerform(by, call) {
1508
+ const approverProfile = this.opts.agents.get(by.id);
1509
+ if (!approverProfile)
1510
+ return false;
1511
+ if (!approverProfile.allowedTools.includes(call.tool.name))
1512
+ return false;
1513
+ const d = await (0, policy_1.evaluatePolicies)(this.policies, this.principalFor(by.id, by.chain ?? [by.id]), { tool: call.tool, args: call.args });
1514
+ return (0, policy_1.agentCouldPerform)(d);
1515
+ }
1516
+ async runToolDef(call, toolDef, agentId, depth = 0, sandboxDecisions, principal, dryRun = false) {
1240
1517
  const controller = new AbortController();
1241
1518
  this.toolControllers.add(controller);
1242
1519
  const secrets = await (0, secrets_1.resolveSecrets)(this.opts.agents.get(agentId), this.opts.secretResolver);
1243
1520
  const ctx = {
1244
- ...this.buildContext(agentId, depth),
1521
+ ...this.buildContext(agentId, depth, principal?.chain),
1522
+ ...(dryRun ? { dryRun: true } : {}),
1245
1523
  ...(Object.keys(secrets).length ? { secrets } : {}),
1246
1524
  ...(this.opts.jobs ? { jobs: this.opts.jobs } : {}),
1247
- ...(this.opts.sandbox ? { sandbox: this.sandboxFor(agentId) } : {}),
1525
+ ...(this.opts.sandbox ? { sandbox: this.sandboxFor(agentId, sandboxDecisions) } : {}),
1248
1526
  signal: controller.signal,
1249
1527
  };
1250
1528
  const timeoutMs = toolDef.timeoutMs ?? this.opts.toolTimeoutMs;
@@ -1302,29 +1580,79 @@ class AgentEngine {
1302
1580
  unregisterMCPServer(serverName) {
1303
1581
  this.mcpRegistrar.unregisterServer(serverName);
1304
1582
  }
1305
- /** Disable approval gate for the rest of this session (approve_all). */
1306
- disableToolApproval() { this.approvalGate.disable(); }
1583
+ /**
1584
+ * Disable approval for the rest of this session (approve_all). In the policy path it affects only the adapted
1585
+ * onToolApproval callback, and never covers what only a person may approve (destructive tools, package installs).
1586
+ */
1587
+ disableToolApproval() { this.approvalGate.disable(); this.callbackApprover?.disable(); }
1307
1588
  /** Re-enable approval gate (e.g. after /iteration manual). */
1308
- enableToolApproval() { this.approvalGate.enable(); }
1309
- buildContext(agentId, depth = 0) {
1589
+ enableToolApproval() { this.approvalGate.enable(); this.callbackApprover?.enable(); }
1590
+ /** The principal of a call: this engine's identity, the executing agent and its delegation chain. */
1591
+ principalFor(agentId, chain) {
1592
+ return {
1593
+ ...this.opts.identity,
1594
+ agentId,
1595
+ sessionId: this.opts.sessionId ?? 'default',
1596
+ chain: chain && chain.length > 0 ? chain : [agentId],
1597
+ };
1598
+ }
1599
+ /**
1600
+ * Writes the single `AuditEvent` of a tool call (or delegation). Arguments only as a hash: the raw JSON string
1601
+ * the model produced is parsed when it can be (so equal arguments hash equal whatever their key order) and
1602
+ * hashed as text when it cannot.
1603
+ */
1604
+ async recordAudit(c) {
1605
+ if (!this.audit.enabled)
1606
+ return;
1607
+ let args = c.rawArgs;
1608
+ if (typeof c.rawArgs === 'string') {
1609
+ try {
1610
+ args = JSON.parse(c.rawArgs);
1611
+ }
1612
+ catch {
1613
+ args = c.rawArgs;
1614
+ }
1615
+ }
1616
+ const p = this.principalFor(c.agentId, c.chain);
1617
+ const event = {
1618
+ at: new Date(c.startedAt).toISOString(),
1619
+ principal: {
1620
+ agentId: p.agentId, sessionId: p.sessionId, chain: p.chain,
1621
+ ...(p.tenantId !== undefined ? { tenantId: p.tenantId } : {}),
1622
+ ...(p.userId !== undefined ? { userId: p.userId } : {}),
1623
+ },
1624
+ tool: c.tool,
1625
+ argsHash: (0, canonical_json_1.hashArgs)(args),
1626
+ decision: c.decision,
1627
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
1628
+ ...(c.outcome !== undefined ? { outcome: c.outcome } : {}),
1629
+ durationMs: Date.now() - c.startedAt,
1630
+ ...(c.approval ? { approval: c.approval } : {}),
1631
+ ...(c.sandbox && c.sandbox.length > 0 ? { sandbox: c.sandbox } : {}),
1632
+ ...(c.meta ? { meta: c.meta } : {}),
1633
+ };
1634
+ await this.audit.write(event);
1635
+ }
1636
+ buildContext(agentId, depth = 0, chain) {
1310
1637
  const id = agentId ?? this.currentAgentId;
1638
+ const principal = this.principalFor(id, chain);
1311
1639
  const profile = this.opts.agents.get(id);
1312
- const storeRoot = this.opts.store?.projectDir;
1313
- const additionalRoots = [
1314
- ...(this.opts.additionalRoots ?? []),
1315
- ...(storeRoot ? [storeRoot] : []),
1316
- ];
1640
+ const additionalRoots = this.opts.additionalRoots ?? [];
1641
+ const serviceSource = this.opts.services;
1642
+ const serviceMap = serviceSource
1643
+ ? new Map(Object.entries(typeof serviceSource === 'function' ? serviceSource(profile) : serviceSource))
1644
+ : undefined;
1317
1645
  return {
1318
1646
  agentId: id,
1319
1647
  sessionId: this.opts.sessionId ?? 'default',
1648
+ principal,
1320
1649
  workingDir: this.opts.workingDir,
1321
1650
  memory: this.memory,
1322
- store: this.opts.store,
1651
+ ...(serviceMap ? { services: serviceMap } : {}),
1323
1652
  advancedMemory: this.opts.memorySystem,
1324
1653
  ...(additionalRoots.length ? { additionalRoots } : {}),
1325
- ...(profile?.blockedCommands?.length ? { blockedCommands: profile.blockedCommands } : {}),
1326
1654
  askAgent: async (agentId, question, context) => {
1327
- const result = await this.bus.runSingle({ agentId, question, context, fromAgentId: id, depth: depth + 1 });
1655
+ const result = await this.bus.runSingle({ agentId, question, context, fromAgentId: id, depth: depth + 1, chain: principal.chain });
1328
1656
  return result.content;
1329
1657
  },
1330
1658
  emitCompacting: (phase, label) => {