@backendkit-labs/agent-core 0.37.1 → 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 (87) hide show
  1. package/README.md +219 -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 +21 -2
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +49 -3
  49. package/dist/index.js.map +1 -1
  50. package/dist/mcp/MCPClientManager.d.ts.map +1 -1
  51. package/dist/mcp/MCPClientManager.js +20 -1
  52. package/dist/mcp/MCPClientManager.js.map +1 -1
  53. package/dist/mcp/index.d.ts +6 -0
  54. package/dist/mcp/index.d.ts.map +1 -1
  55. package/dist/mcp/index.js +15 -1
  56. package/dist/mcp/index.js.map +1 -1
  57. package/dist/mcp/tool-server-cli.d.ts +48 -0
  58. package/dist/mcp/tool-server-cli.d.ts.map +1 -0
  59. package/dist/mcp/tool-server-cli.js +106 -0
  60. package/dist/mcp/tool-server-cli.js.map +1 -0
  61. package/dist/mcp/tool-server-http.d.ts +37 -0
  62. package/dist/mcp/tool-server-http.d.ts.map +1 -0
  63. package/dist/mcp/tool-server-http.js +117 -0
  64. package/dist/mcp/tool-server-http.js.map +1 -0
  65. package/dist/mcp/tool-server.d.ts +104 -0
  66. package/dist/mcp/tool-server.d.ts.map +1 -0
  67. package/dist/mcp/tool-server.js +312 -0
  68. package/dist/mcp/tool-server.js.map +1 -0
  69. package/dist/shared/utils/canonical-json.d.ts +12 -0
  70. package/dist/shared/utils/canonical-json.d.ts.map +1 -0
  71. package/dist/shared/utils/canonical-json.js +29 -0
  72. package/dist/shared/utils/canonical-json.js.map +1 -0
  73. package/dist/shared/utils/loopback.d.ts +10 -0
  74. package/dist/shared/utils/loopback.d.ts.map +1 -0
  75. package/dist/shared/utils/loopback.js +25 -0
  76. package/dist/shared/utils/loopback.js.map +1 -0
  77. package/dist/tools/createToolContext.d.ts +15 -0
  78. package/dist/tools/createToolContext.d.ts.map +1 -0
  79. package/dist/tools/createToolContext.js +34 -0
  80. package/dist/tools/createToolContext.js.map +1 -0
  81. package/dist/tools/defineTool.d.ts +43 -7
  82. package/dist/tools/defineTool.d.ts.map +1 -1
  83. package/dist/tools/defineTool.js +68 -10
  84. package/dist/tools/defineTool.js.map +1 -1
  85. package/dist/types/index.d.ts +32 -0
  86. package/dist/types/index.d.ts.map +1 -1
  87. package/package.json +1 -1
package/README.md CHANGED
@@ -4,8 +4,6 @@ The foundation engine for the BackendKit Labs agent framework. Provides everythi
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@backendkit-labs/agent-core)](https://www.npmjs.com/package/@backendkit-labs/agent-core)
6
6
 
7
- > **Status: `core`** — Required by the enterprise use case. Breaking changes go through full review before merging.
8
-
9
7
  ## Table of contents
10
8
 
11
9
  - [Installation](#installation)
@@ -19,6 +17,7 @@ The foundation engine for the BackendKit Labs agent framework. Provides everythi
19
17
  - [Transports](#transports)
20
18
  - [SessionMemory](#sessionmemory)
21
19
  - [MCP client](#mcp-client)
20
+ - [MCP tool server (tools without a model)](#mcp-tool-server-tools-without-a-model)
22
21
  - [Workflow engine](#workflow-engine)
23
22
  - [Advanced memory system](#advanced-memory-system)
24
23
  - [Observability](#observability)
@@ -201,6 +200,52 @@ const lookupUserTool = defineTool({
201
200
  });
202
201
  ```
203
202
 
203
+ ### Declared facts: readOnly, destructive, meta
204
+
205
+ A tool can say what it does so the engine and MCP clients can treat it accordingly. The fields are optional and absent unless declared, so existing tools are unaffected.
206
+
207
+ ```typescript
208
+ const balancesTool = defineTool({
209
+ name: 'balances_at',
210
+ title: 'Balances at date',
211
+ description: 'Account balances at the end of a day',
212
+ readOnly: true, // implies concurrencySafe; MCP readOnlyHint
213
+ idempotent: true, // MCP idempotentHint
214
+ meta: { autonomyLevel: 0, erpOperation: 'query' }, // MCP _meta, for governance clients
215
+ input: z.object({ date: z.string() }),
216
+ execute: async ({ date }) => JSON.stringify(await ledger.balances(date)),
217
+ });
218
+
219
+ const payTool = defineTool({
220
+ name: 'pay_invoice',
221
+ description: 'Pay an approved invoice',
222
+ destructive: true, // MCP destructiveHint; a direct MCP server must authorize every call
223
+ input: z.object({ invoiceId: z.string(), approvalId: z.string() }),
224
+ execute: async (args) => JSON.stringify(await treasury.pay(args)),
225
+ });
226
+ ```
227
+
228
+ | Field | Meaning | MCP |
229
+ |---|---|---|
230
+ | `title` | Human-readable name | `title` |
231
+ | `readOnly` | Mutates nothing. Implies `concurrencySafe`; cannot be combined with `destructive`. | `readOnlyHint` |
232
+ | `destructive` | A write that cannot be undone from the outside. Cannot be `concurrencySafe`. | `destructiveHint` |
233
+ | `idempotent` | Same arguments again, no additional effect | `idempotentHint` |
234
+ | `openWorld` | Talks to entities outside the system | `openWorldHint` |
235
+ | `meta` | Free-form, never read by the engine | `_meta` |
236
+
237
+ Contradictions throw `ToolDefinitionError` at definition time, not at call time. For a hand-written `ToolDefinition`, call `validateToolDefinition(tool)` yourself; the MCP tool server does. When the **client** side consumes an MCP server (`MCPClientManager`), these facts are copied from the server's annotations only with `trustAnnotations: true`: what a server says about its tools is a claim.
238
+
239
+ ### Running a tool outside an engine
240
+
241
+ `createToolContext()` builds the `ExecutionContext` a tool expects, with in-memory session memory and an `askAgent` that rejects. Use it in tests, scripts, cron jobs or anywhere there is no `AgentEngine`:
242
+
243
+ ```typescript
244
+ import { createToolContext } from '@backendkit-labs/agent-core';
245
+
246
+ const out = await balancesTool.execute({ date: '2026-10-31' }, createToolContext({ workingDir: process.cwd() }));
247
+ ```
248
+
204
249
  ---
205
250
 
206
251
  ## AgentEngine — the execution core
@@ -239,7 +284,7 @@ new AgentEngine({
239
284
 
240
285
  // Observability
241
286
  observability: obsManager,
242
- auditLog: '/path/to/audit.ndjson',
287
+ audit: new NdjsonAuditSink('/path/to/audit.ndjson'), // one AuditEvent per tool call (see Observability → Audit)
243
288
 
244
289
  // Context injected into the system prompt
245
290
  projectContext: 'You are working in project X...',
@@ -276,7 +321,7 @@ await engine.run('Analyze the database schema', {
276
321
  | `'step-by-step'` | Calls `onStep` after every iteration; return `false` to stop |
277
322
  | `'interactive'` | Calls `onIterationLimit` when cap is reached; return `true` to continue. Without that callback the run stops at the cap |
278
323
 
279
- Tool approval is independent of the mode: whenever `onToolApproval` is set, the engine asks before `write_file`, `edit_file`, `run_command` and package installs.
324
+ Tool approval is independent of the mode: whenever `onToolApproval` is set, the engine asks before `write_file`, `edit_file`, `run_command` and package installs. That is the legacy gate, and it is what coding agents should keep using for now. For approval decided by what tools declare (`readOnly`, `destructive`), by a policy, or by another agent or a service, see [Policy and approval](#policy-and-approval-per-call).
280
325
 
281
326
  ```typescript
282
327
  // Approval — user approves destructive tool calls
@@ -428,7 +473,7 @@ stored history is corrected and a `guardrail` event carries the `replacement` fo
428
473
  until the answer is checked: nothing unchecked is ever shown, but there is no streaming.
429
474
 
430
475
  Every redaction, block and error emits a `{ type: 'guardrail', name, phase, action, reason, ... }` event, is written to the
431
- `auditLog` as `guardrail:<phase>:<name>`, and is counted in `MetricsSnapshot.guardrails`.
476
+ legacy `auditLog` as `guardrail:<phase>:<name>`, and is counted in `MetricsSnapshot.guardrails`.
432
477
 
433
478
  ---
434
479
 
@@ -563,43 +608,29 @@ await engine.run("What's my name?"); // → "Your name is Alice."
563
608
 
564
609
  ## MCP client
565
610
 
566
- `MCPClientManager` connects to external MCP (Model Context Protocol) servers, discovers their tools, and makes them available to the engine. Supports stdio, Streamable HTTP, and SSE transports.
611
+ `MCPClientManager` connects to external MCP (Model Context Protocol) servers, discovers their tools, and makes them available to the engine. One `MCPServerConfig` per server decides the transport:
567
612
 
568
- ### Stdio (most common)
613
+ - `command` (+ `args`, `env`) — a local subprocess over stdio.
614
+ - `url` (+ `headers`) — a remote server over Streamable HTTP, falling back to SSE when the server answers 4xx; force one with `remoteTransport: 'streamable-http' | 'sse'`.
615
+ - When both are set, `url` wins.
616
+
617
+ ### Standalone
569
618
 
570
619
  ```typescript
571
620
  import { MCPClientManager } from '@backendkit-labs/agent-core';
572
621
 
573
- const mcp = new MCPClientManager();
622
+ const mcp = new MCPClientManager([
623
+ { name: 'filesystem', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/workspace'] },
624
+ { name: 'remote', url: 'https://mcp.example.com/v1', headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` } },
625
+ ]);
574
626
 
575
- await mcp.connectStdio({
576
- name: 'filesystem',
577
- command: 'npx',
578
- args: ['-y', '@modelcontextprotocol/server-filesystem', '/workspace'],
579
- env: {},
580
- });
581
-
582
- const tools = mcp.getTools(); // ToolDefinition[] — discovered from the server
583
- ```
584
-
585
- ### HTTP transport
586
-
587
- ```typescript
588
- await mcp.connectStreamableHTTP({
589
- name: 'remote-server',
590
- baseUrl: 'https://mcp.example.com',
591
- apiKey: process.env.MCP_API_KEY,
592
- });
627
+ await mcp.initialize(); // connects every configured server
628
+ const tools = mcp.getTools(); // ToolDefinition[], named mcp__{server}__{tool}
629
+ mcp.isConnected('remote'); // per-server status
630
+ await mcp.disconnect();
593
631
  ```
594
632
 
595
- ### SSE transport (legacy servers)
596
-
597
- ```typescript
598
- await mcp.connectSSE({
599
- name: 'legacy-server',
600
- url: 'http://localhost:8080/sse',
601
- });
602
- ```
633
+ Other useful fields: `timeoutMs` (per tool call, default 30 s), `connectTimeoutMs`, `trustAnnotations` (believe the server's `readOnlyHint` and `_meta`; off by default), `mode: 'tools' | 'agent'` and `assignTo` (which agents get the tools).
603
634
 
604
635
  ### Multiple servers via engine options
605
636
 
@@ -625,12 +656,52 @@ The client detects server crashes via `client.onclose` and marks them `'failed'`
625
656
  // For manual use:
626
657
  mcp.setDisconnectHandler((serverName) => {
627
658
  console.warn(`MCP server "${serverName}" disconnected`);
628
- // Re-attempt connection on next engine.run() call
629
659
  });
660
+ await mcp.reconnectFailed(); // retry the servers marked 'failed'
630
661
  ```
631
662
 
632
663
  ---
633
664
 
665
+ ## MCP tool server (tools without a model)
666
+
667
+ `createToolServer` exposes `ToolDefinition`s as MCP tools that run **directly**: the arguments the client sends are the arguments `execute` receives, with no language model in between. Use it for anything a caller already knows how to ask for (a balance at a date, post this draft, run this check), where a model would only add latency, cost and the chance of a rewritten amount. For requests that need interpretation, `AgentMCPServer` in `@backendkit-labs/mcp-server` turns each call into a prompt for an engine. Both can coexist, and a prompt tool may itself call direct tools.
668
+
669
+ Each call gets: validation against the tool's schema before anything runs (the SDK answers invalid arguments with `isError` and a `-32602` message), an optional `authorize` gate, an `ExecutionContext` whose `signal` aborts on client cancellation or `timeoutMs`, an output cap, and an `audit` record. Tools from `defineTool` are registered with their own Zod schema, so what the client validates against is exactly what `execute` validates against; a hand-written `ToolDefinition` goes through `z.fromJSONSchema`, which fails loudly on constructs it cannot express.
670
+
671
+ ```typescript
672
+ import { createToolServer, startToolServerHttp, runToolServer } from '@backendkit-labs/agent-core';
673
+ // also available from '@backendkit-labs/agent-core/mcp'
674
+
675
+ const options = {
676
+ name: 'ledger',
677
+ version: '1.0.0',
678
+ tools: [balancesTool, payTool],
679
+ // Required because payTool is destructive: a direct tool skips the engine's allowedTools, gates and budget.
680
+ authorize: async ({ tool, args, sessionId }) =>
681
+ !tool.destructive || approvals.isValid(args.approvalId as string),
682
+ audit: record => fs.appendFile('tool-calls.ndjson', JSON.stringify(record) + '\n'),
683
+ context: { workingDir: process.cwd() }, // or a function that builds the whole context per call
684
+ maxOutputChars: 1_048_576, // default
685
+ };
686
+
687
+ // 1. Any transport: one McpServer with the tools registered.
688
+ const server = createToolServer(options);
689
+ await server.connect(new StdioServerTransport());
690
+
691
+ // 2. Streamable HTTP, stateless: one server and transport per request, bearer required, loopback-only by default.
692
+ const running = await startToolServerHttp(options, { port: 3100, authToken: process.env.LEDGER_TOKEN });
693
+ // running.url → http://127.0.0.1:3100/mcp
694
+
695
+ // 3. The usual command line: stdio by default, `--http --port 3100 --host 0.0.0.0 --token <t>`, `--help`.
696
+ await runToolServer(options, { bin: 'ledger-mcp', tokenEnv: 'LEDGER_TOKEN' });
697
+ ```
698
+
699
+ **Error contract.** `isError: true` means the call did not run to completion: denied by `authorize`, timed out, threw (message only, no stack), or returned more than `maxOutputChars`. Whatever the tool *returned* is payload, even a JSON `{ ok: false }` that encodes a business failure. The `audit` hook receives one record per call, including denied and failed ones, with a SHA-256 of the arguments rather than the arguments themselves; if the hook throws, the failure goes to stderr and the result does not change (the tool has already run).
700
+
701
+ **HTTP guards.** Without `authToken` the server refuses to listen anywhere but loopback. Bound to loopback, requests whose `Host` or `Origin` is not loopback get 403 (DNS rebinding, cross-site POST). Only `POST <path>` is served: a stateless server has no SSE stream to open and no session to delete. Bodies above `maxBodyBytes` (1 MiB) get 413.
702
+
703
+ ---
704
+
634
705
  ## Workflow engine
635
706
 
636
707
  Build declarative multi-agent workflows with `WorkflowBuilder`. Steps can run sequentially, in parallel, or conditionally.
@@ -733,7 +804,7 @@ const memory = createMemorySystem({
733
804
  path: '~/.bk-agent/projects/my-project/memory/patterns.json',
734
805
  },
735
806
  retention: {
736
- maxEpisodes: 500, // prunes by relevance score when exceeded (v0.22.3+)
807
+ maxEpisodes: 500, // prunes by relevance score when exceeded
737
808
  summarizeAfter: 50,
738
809
  // Optional: compress old episodes with an LLM summary
739
810
  summarizeFn: async (episodes) => {
@@ -784,7 +855,7 @@ await procedural.add({
784
855
  const deploySteps = await procedural.get('deploy-to-staging');
785
856
  ```
786
857
 
787
- ### Forgetting curve (v0.22.3+)
858
+ ### Forgetting curve
788
859
 
789
860
  When `maxEpisodes` is set and the limit is exceeded, `EpisodicMemory` prunes by **relevance score** rather than raw age:
790
861
 
@@ -830,7 +901,7 @@ interface MemoryStoreBackend {
830
901
  upsert(id: string, record: StoredRecord): void;
831
902
  getAll(): StoredRecord[];
832
903
  deleteOldest(keepNewest: number): void;
833
- deleteByIds(ids: string[]): void; // v0.22.3+: used by relevance-based pruning
904
+ deleteByIds(ids: string[]): void; // used by relevance-based pruning
834
905
  count(): number;
835
906
  }
836
907
  ```
@@ -924,18 +995,123 @@ const tracer = new Tracer({
924
995
  });
925
996
  ```
926
997
 
927
- ### Audit log (NDJSON)
998
+ ### Audit (one event per tool call)
928
999
 
929
- Every tool call can be logged to a newline-delimited JSON file:
1000
+ Give the engine one or more `AuditSink`s and it records **exactly one `AuditEvent` per tool call**, whether it ran or was refused (not found, not in `allowedTools`, blocked by a guardrail or the sandbox, rejected by the approver), plus one per `ask_agent` delegation. Arguments are recorded only as a SHA-256 of their canonical JSON, never in clear.
930
1001
 
931
1002
  ```typescript
932
- const engine = new AgentEngine({
1003
+ import { createBaseEngine, HashChainAuditSink, NdjsonAuditSink, verifyAuditChain } from '@backendkit-labs/agent-core';
1004
+
1005
+ const engine = createBaseEngine({
933
1006
  ...opts,
934
- auditLog: '/var/log/agent-audit.ndjson',
935
- // Each line: { ts, agentId, toolName, args, result, durationMs }
1007
+ identity: { tenantId: 'acme', userId: 'u-42', roles: ['treasury'] }, // part of every event's principal
1008
+ audit: [
1009
+ new NdjsonAuditSink('/var/log/agent/events.ndjson'), // plain, one JSON line per event
1010
+ new HashChainAuditSink('/var/log/agent/chain.log', { secret: process.env.AUDIT_KEY }), // tamper-evident
1011
+ ],
936
1012
  });
1013
+
1014
+ // Later, or on another host:
1015
+ verifyAuditChain('/var/log/agent/chain.log', { secret: process.env.AUDIT_KEY });
1016
+ // → { ok: true, entries, head } or { ok: false, brokenAt, reason }
937
1017
  ```
938
1018
 
1019
+ An event carries `at`, `principal` (agent, session, delegation chain, tenant, user), `tool`, `argsHash`, `decision` (`allow`, `deny`, `ask`, `not_found`, `not_allowed`, `sandbox_denied`, `guardrail_blocked`), `outcome` when it ran (`ok`, `error`, `timeout`, `aborted`), `durationMs`, the sandbox decisions taken during the call and the tool's `meta`. Sinks receive events one at a time in call order; a failing sink is reported on the transport (`system` warning) and never changes the result. `HashChainAuditSink` links every entry to the previous one, so editing, removing or reordering entries is detected; with a `secret` a log rewritten by someone without it does not verify either. It refuses to extend a log that is already broken.
1020
+
1021
+ `auditLog: '/path.ndjson'` (the older option) still works unchanged but is deprecated: it writes up to 200 characters of the arguments in clear. It will be removed in 0.40.
1022
+
1023
+ ### Policy and approval (per call)
1024
+
1025
+ A `ToolPolicy` decides every tool call and every `ask_agent` delegation: `allow`, `deny` or `ask`. It sees the principal (agent, delegation chain, tenant, user, roles) and the call (the tool with its declared facts, the arguments after guardrails). An `ask` goes to the `approver` (a person, another agent, a service), or is stored as pending in `approvals` when nobody answers now.
1026
+
1027
+ ```typescript
1028
+ import { createBaseEngine, type ToolPolicy, type Approver } from '@backendkit-labs/agent-core';
1029
+
1030
+ const treasuryRules: ToolPolicy = {
1031
+ decide(principal, call) {
1032
+ if (call.tool.name === 'pay_invoice' && (call.args.amount as number) > 10_000) {
1033
+ return { effect: 'ask', reason: 'payment above 10k', accepts: ['human'] };
1034
+ }
1035
+ if (!principal.roles?.includes('treasury') && !call.tool.readOnly) {
1036
+ return { effect: 'deny', reason: 'only treasury writes' };
1037
+ }
1038
+ return { effect: 'allow' };
1039
+ },
1040
+ };
1041
+
1042
+ const engine = createBaseEngine({
1043
+ ...opts,
1044
+ identity: { tenantId: 'acme', userId: 'u-42', roles: ['treasury'] },
1045
+ policy: treasuryRules, // several combine: deny > ask > allow; a throwing policy denies
1046
+ approver: myApprover, // { ref, request(req) → { decision, by: { kind, id }, at } }
1047
+ audit: new HashChainAuditSink('audit.log'),
1048
+ });
1049
+ ```
1050
+
1051
+ - **Without `policy`**, but with someone to ask, `defaultToolPolicy` applies. Tools declared `readOnly` run. Tools declared `destructive` always ask a person. Anything else asks.
1052
+ - **Approvals are validated before they count:**
1053
+ - the approver's kind must be accepted;
1054
+ - nobody approves their own request or one from their delegation chain;
1055
+ - an agent approves only what it could do itself.
1056
+
1057
+ Every approval is audited with who gave it.
1058
+ - **`allow` can carry a mode.** `mode: 'dry_run'` runs the tool with `ctx.dryRun = true`. `mode: 'sandboxed'` requires a configured sandbox.
1059
+ - **Opt-in.** Setting `policy`, `approver` or `approvals` switches to this path. Without them, `onToolApproval` behaves exactly as before. With them, `onToolApproval` is adapted as the approver: "approve all" never covers destructive tools or package installs.
1060
+
1061
+ ### Durable approvals
1062
+
1063
+ If nobody can answer an `ask` right now, give the engine an `approvals` store. The call is stored as pending, the model is told it did not run, and whoever decides later runs it with `runApproved`.
1064
+
1065
+ ```typescript
1066
+ import { createBaseEngine, FileApprovalStore, agentApprover, consoleApprover } from '@backendkit-labs/agent-core';
1067
+
1068
+ const approvals = new FileApprovalStore('/var/lib/agent/approvals');
1069
+ const engine = createBaseEngine({ ...opts, approvals });
1070
+
1071
+ await engine.run('pay the October invoices'); // asks become pending requests
1072
+
1073
+ // Later, maybe in another process (a UI, Hermes, a CLI):
1074
+ const [req] = await approvals.list({ status: 'pending' });
1075
+ await approvals.resolve(req.id, { decision: 'approve', by: { kind: 'human', id: 'ana' }, at: new Date().toISOString() });
1076
+ const result = await engine.runApproved(req.id); // runs once; a second call throws
1077
+
1078
+ // Approvers that answer right away:
1079
+ createBaseEngine({ ...opts, approver: consoleApprover() }); // a person at the terminal
1080
+ createBaseEngine({ ...opts, approver: agentApprover((id, q) => engine.consultAgent(id, q), 'supervisor') }); // another agent
1081
+ ```
1082
+
1083
+ - **One decision and one execution per request.** `FileApprovalStore` allows exactly one decision and one execution per request, even across processes that share the directory.
1084
+ - **Everything is checked again.** `runApproved` repeats every check. A stored approval only satisfies an `ask` whose `accepts` admits the approver: an approval from an agent never covers a destructive tool.
1085
+ - **An invalid approval is spent.** If the approval turns out not to be valid, it is consumed and audited as `deny`.
1086
+
1087
+ ### Lifecycle hooks
1088
+
1089
+ Hooks let a vertical plug into a turn without new engine options. Every hook of one turn shares a `RunContext`: the principal, the input, a `state` map and an abort `signal`.
1090
+
1091
+ ```typescript
1092
+ import { createBaseEngine, type EngineHooks } from '@backendkit-labs/agent-core';
1093
+
1094
+ const review: EngineHooks = {
1095
+ name: 'review',
1096
+ beforeRun: (ctx) => ctx.state.set('task', classify(ctx.input)),
1097
+ systemPrompt: (ctx, profile) => profile.id === 'general' ? `## Task\n${describe(ctx.state.get('task'))}` : undefined,
1098
+ afterTurn: (ctx, turn) => !ctx.state.get('reviewed') && turn.profile.id === 'general'
1099
+ ? { action: 'continue', agentId: 'reviewer', message: 'Review the answer above.' } // another pass, as another agent
1100
+ : undefined,
1101
+ beforeTool: (ctx, call) => metrics.start(call.tool.name),
1102
+ afterTool: (ctx, call, result) => metrics.end(call.tool.name, result.success),
1103
+ afterRun: (ctx, result) => store.save(ctx.state.get('task'), result.text),
1104
+ };
1105
+
1106
+ const engine = createBaseEngine({ ...opts, hooks: [review], maxHookContinues: 3 });
1107
+ ```
1108
+
1109
+ - **Order.** Hooks run in registration order.
1110
+ - **`systemPrompt`** adds sections to the active agent and to delegates.
1111
+ - **`afterTurn`** runs when the model answers without asking for tools. The first hook that asks to `continue` wins. The number of extra passes is capped by `maxHookContinues` (default 5) and by `maxIterations`.
1112
+ - **`beforeTool` / `afterTool`** wrap only the calls the policy allowed.
1113
+ - **Errors.** A hook that throws fails the turn, and the error names the hook and the point.
1114
+
939
1115
  ---
940
1116
 
941
1117
  ## Skills and slash commands
@@ -14,6 +14,11 @@ export interface DelegationRequest {
14
14
  * slots are occupied by agents that are themselves waiting for nested delegations.
15
15
  */
16
16
  depth?: number;
17
+ /**
18
+ * Delegation chain of the agent that asks, oldest first (SPEC-0014 principal). The delegate's chain is this
19
+ * plus its own id. When absent, `[fromAgentId]` is assumed.
20
+ */
21
+ chain?: string[];
17
22
  }
18
23
  export interface DelegationResult {
19
24
  agentId: string;
@@ -31,7 +36,9 @@ export interface DelegationBusOptions {
31
36
  maxDepth?: number;
32
37
  agents: AgentRegistry;
33
38
  transport: Transport;
34
- runAgent(agentId: string, question: string, context?: string, depth?: number, outputBuffer?: AgentEvent[]): Promise<DelegationResult>;
39
+ runAgent(agentId: string, question: string, context?: string, depth?: number, outputBuffer?: AgentEvent[],
40
+ /** Chain of the delegate itself: the caller's chain plus the delegate's id. */
41
+ chain?: string[]): Promise<DelegationResult>;
35
42
  }
36
43
  export declare class DelegationBus {
37
44
  private readonly opts;
@@ -1 +1 @@
1
- {"version":3,"file":"DelegationBus.d.ts","sourceRoot":"","sources":["../../src/delegation/DelegationBus.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAExD,MAAM,WAAW,iBAAiB;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,oFAAoF;IACpF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,2FAA2F;AAC3F,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,MAAM,WAAW,oBAAoB;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,2GAA2G;IAC3G,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,aAAa,CAAC;IACtB,SAAS,EAAE,SAAS,CAAC;IACrB,QAAQ,CACJ,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,MAAM,EAChB,KAAK,CAAC,EAAE,MAAM,EACd,YAAY,CAAC,EAAE,UAAU,EAAE,GAC5B,OAAO,CA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ClB;AAED,2FAA2F;AAC3F,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,MAAM,WAAW,oBAAoB;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,2GAA2G;IAC3G,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,aAAa,CAAC;IACtB,SAAS,EAAE,SAAS,CAAC;IACrB,QAAQ,CACJ,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,MAAM,EAChB,KAAK,CAAC,EAAE,MAAM,EACd,YAAY,CAAC,EAAE,UAAU,EAAE;IAC3B,+EAA+E;IAC/E,KAAK,CAAC,EAAE,MAAM,EAAE,GACjB,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAChC;AAED,qBAAa,aAAa;IASV,OAAO,CAAC,QAAQ,CAAC,IAAI;IARjC;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA+B;gBAE5B,IAAI,EAAE,oBAAoB;IAIvD,OAAO,CAAC,WAAW;IAenB;;;;;;;OAOG;IACG,WAAW,CAAC,QAAQ,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAgBvE,SAAS,CAAC,OAAO,EAAE,iBAAiB,EAAE,YAAY,CAAC,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC;IA0DnG,kBAAkB;CAGrB"}
@@ -86,7 +86,8 @@ class DelegationBus {
86
86
  to_name: profile.name,
87
87
  to_icon: profile.icon,
88
88
  });
89
- return this.opts.runAgent(request.agentId, request.question, request.context, depth, outputBuffer);
89
+ const callerChain = request.chain ?? (request.fromAgentId ? [request.fromAgentId] : []);
90
+ return this.opts.runAgent(request.agentId, request.question, request.context, depth, outputBuffer, [...callerChain, request.agentId]);
90
91
  };
91
92
  try {
92
93
  return await this.bulkheadFor(depth).execute(execute);
@@ -1 +1 @@
1
- {"version":3,"file":"DelegationBus.js","sourceRoot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+ import { type EngineHooks } from '../governance/hooks';
2
+ import type { ApprovalStore, Approver, AuditSink, Identity, ToolPolicy } from '../governance/types';
1
3
  import type { EngineOptions, SessionMemoryData } from '../types';
2
4
  import type { Transport } from '../transport/Transport';
3
5
  import type { AgentRegistry } from './AgentRegistry';
@@ -91,8 +93,44 @@ export interface AgentEngineOptions extends EngineOptions {
91
93
  * Path to an append-only NDJSON file for tool call audit records.
92
94
  * Each executed tool call is appended as one JSON line with: ts, session, agent, tool, inputPreview, success, durationMs.
93
95
  * Directory is created automatically. Optional — no audit file written when absent.
96
+ * @deprecated Writes up to 200 characters of the arguments in clear. Use `audit` (an `AuditSink`, e.g.
97
+ * `new NdjsonAuditSink(path)` or `new HashChainAuditSink(path)`), whose events carry only a hash of the
98
+ * arguments. Kept unchanged, same file format, until 0.40.
94
99
  */
95
100
  auditLog?: string;
101
+ /**
102
+ * Where every tool call (and every `ask_agent` delegation) is recorded, accepted or refused: exactly one
103
+ * `AuditEvent` per call, arguments as a SHA-256 only. Several sinks receive the same events in the same order.
104
+ */
105
+ audit?: AuditSink | AuditSink[];
106
+ /** Who this engine acts for (tenant, user, roles...). Becomes part of the `Principal` of every call. */
107
+ identity?: Identity;
108
+ /**
109
+ * Decides every tool call and delegation (allow, deny, ask) after allowedTools, the sandbox and the argument
110
+ * guardrails. Several policies combine: deny wins, then ask, then allow. When absent but there is someone to
111
+ * ask (`approver`, `approvals` or `onToolApproval`), `defaultToolPolicy` applies: readOnly runs, everything else
112
+ * asks, destructive asks a person. Setting any of `policy`, `approver` or `approvals` switches the engine to this
113
+ * path; with none of them the legacy `onToolApproval` gate keeps working exactly as before.
114
+ */
115
+ policy?: ToolPolicy | ToolPolicy[];
116
+ /**
117
+ * Who answers an `ask` right away: a person through a UI, a supervising agent, a service such as Hermes. Its
118
+ * answers are checked (accepted kind, no self-approval, an agent approves only what it can do) and audited.
119
+ * Without it, `onToolApproval` is adapted as the approver.
120
+ */
121
+ approver?: Approver;
122
+ /**
123
+ * Durable approvals: when nobody answers right away, an `ask` is stored here as pending and the model is told
124
+ * the call did not run (resubmission, SPEC-0014 §6).
125
+ */
126
+ approvals?: ApprovalStore;
127
+ /**
128
+ * Lifecycle hooks (SPEC-0014 §3): before/after a turn, system prompt sections, after the model's final answer
129
+ * (may force another pass), before/after each tool call. Run in registration order; a throwing hook fails the turn.
130
+ */
131
+ hooks?: EngineHooks[];
132
+ /** Most extra passes `afterTurn` hooks may force in one turn. Default 5. */
133
+ maxHookContinues?: number;
96
134
  /**
97
135
  * Called by updateWorkingDir after the workingDir changes (e.g. /workspace switch).
98
136
  * Should return the new projectContext string built from the new cwd
@@ -114,6 +152,19 @@ export declare class AgentEngine {
114
152
  /** Uncalibrated token estimate of the last request sent by runLoop, to calibrate against real usage. */
115
153
  private lastRequestEstimate;
116
154
  private readonly auditLogger;
155
+ private readonly audit;
156
+ /** Policy path (SPEC-0014 F2) instead of the legacy ApprovalGate: on when policy, approver or approvals is set. */
157
+ private readonly governed;
158
+ private readonly policies;
159
+ private readonly approver?;
160
+ /** Set when the approver is the adapted onToolApproval callback, so disable/enableToolApproval reach it. */
161
+ private readonly callbackApprover?;
162
+ private readonly hooks;
163
+ /** Context shared by the hooks of the turn in progress; undefined between turns. */
164
+ private runCtx?;
165
+ private runController?;
166
+ /** Last final answer of the model in the current turn (for afterRun). */
167
+ private lastAnswer;
117
168
  private currentAgentId;
118
169
  private aborted;
119
170
  private abortController;
@@ -191,7 +242,30 @@ export declare class AgentEngine {
191
242
  private getProviderForProfile;
192
243
  run(input: string): Promise<void>;
193
244
  private _run;
245
+ /** Sections the `systemPrompt` hooks add for `profile`. */
246
+ private hookPromptSections;
247
+ /** The first `afterTurn` hook that asks to continue wins; the rest still run (they may only observe). */
248
+ private afterTurnHooks;
249
+ /** Arguments the model produced, as an object (anything else becomes `{}`). */
250
+ private parseArgs;
251
+ /** Context for a tool hook: the turn's context with the principal of the agent that makes the call. */
252
+ private toolHookContext;
194
253
  runWorkflow(defOrBuilder: WorkflowDef | WorkflowBuilder, opts?: WorkflowRunOptions): Promise<WorkflowResult>;
254
+ /**
255
+ * Runs a tool call that was stored as pending and has since been approved (SPEC-0014 §6, resubmission).
256
+ *
257
+ * - At most once: the store marks it executed atomically before it runs; a second call throws.
258
+ * - Everything is checked again (allowedTools, sandbox, guardrails, policies); the stored approval only
259
+ * satisfies an `ask`, and only if its approver is one that ask accepts. An approval that turns out not to be
260
+ * valid is consumed and audited as `deny`.
261
+ * - The result is returned to the caller (e.g. Hermes or a UI); it is not added to the conversation.
262
+ */
263
+ runApproved(approvalId: string): Promise<string>;
264
+ /**
265
+ * Puts one question to an agent outside the conversation and returns its answer (its tool calls are governed
266
+ * like any other). Used by `agentApprover` to let a supervising agent approve or reject requests.
267
+ */
268
+ consultAgent(agentId: string, question: string): Promise<string>;
195
269
  abort(): void;
196
270
  /** Change the iteration mode at runtime — takes effect on the next run(). */
197
271
  setIterationMode(mode: IterationMode): void;
@@ -252,16 +326,36 @@ export declare class AgentEngine {
252
326
  private sandboxFor;
253
327
  /** The message for the model when the sandbox policy refuses `tool` for `agentId`; undefined when allowed. */
254
328
  private sandboxRefusal;
329
+ /**
330
+ * Reports a sandbox decision on the transport and the legacy audit log, and, when `collect` is given, adds it to
331
+ * the decisions the single `AuditEvent` of the current tool call will carry.
332
+ */
255
333
  private reportSandboxDecision;
256
334
  /**
257
335
  * Unified tool execution used by both runLoop (primary agent) and
258
336
  * runAgentInternal (sub-agents via ask_agent).
259
- * Handles: allowedTools authorization → onToolApproval gate → execute → audit → transport.
337
+ * Handles: allowedTools → sandbox refusal → argument guardrails → policy/approval (or the legacy gate)
338
+ * → execute → result guardrails → audit → transport.
260
339
  */
261
340
  private executeToolCall;
262
341
  /** Approval checks never overlap and run in call order, even inside a parallel wave. */
263
342
  private gateQueue;
264
- private checkGateSerial;
343
+ private serialize;
344
+ /** The legacy gate (onToolApproval + the built-in list of tools that ask), unchanged, as a verdict. */
345
+ private decideLegacy;
346
+ private noApproverForSandbox;
347
+ /**
348
+ * The policy path (SPEC-0014 §2, F2): the policies decide on the arguments that would really run (after the
349
+ * guardrails), a sandbox that wants approval adds an `ask`, and an `ask` goes to the approver in call order or,
350
+ * when nobody answers now, to the durable store.
351
+ */
352
+ private decideGoverned;
353
+ private resolveAsk;
354
+ /**
355
+ * Rule 3 of SPEC-0014 §6.2: an agent approves only what it could do itself. It must be registered, have the
356
+ * tool in its allowedTools, and the policies must allow the same call with that agent as principal.
357
+ */
358
+ private agentCanPerform;
265
359
  private runToolDef;
266
360
  /**
267
361
  * Disconnects an MCP server at runtime — reverts all tool assignments and
@@ -273,10 +367,21 @@ export declare class AgentEngine {
273
367
  * For mode='tools' servers, agents fall back to shell commands automatically.
274
368
  */
275
369
  unregisterMCPServer(serverName: string): void;
276
- /** Disable approval gate for the rest of this session (approve_all). */
370
+ /**
371
+ * Disable approval for the rest of this session (approve_all). In the policy path it affects only the adapted
372
+ * onToolApproval callback, and never covers what only a person may approve (destructive tools, package installs).
373
+ */
277
374
  disableToolApproval(): void;
278
375
  /** Re-enable approval gate (e.g. after /iteration manual). */
279
376
  enableToolApproval(): void;
377
+ /** The principal of a call: this engine's identity, the executing agent and its delegation chain. */
378
+ private principalFor;
379
+ /**
380
+ * Writes the single `AuditEvent` of a tool call (or delegation). Arguments only as a hash: the raw JSON string
381
+ * the model produced is parsed when it can be (so equal arguments hash equal whatever their key order) and
382
+ * hashed as text when it cannot.
383
+ */
384
+ private recordAudit;
280
385
  private buildContext;
281
386
  }
282
387
  //# sourceMappingURL=AgentEngine.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AgentEngine.d.ts","sourceRoot":"","sources":["../../src/engine/AgentEngine.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAER,aAAa,EAIb,iBAAiB,EAGpB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC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