@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
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FileApprovalStore = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
6
+ const promises_1 = require("node:fs/promises");
7
+ const node_path_1 = require("node:path");
8
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
9
+ /**
10
+ * Durable approvals in a directory (SPEC-0014 §6, option A). Three files per request:
11
+ *
12
+ * - `<id>.request.json` — the request, written once.
13
+ * - `<id>.outcome.json` — the decision, written once: a second decision for the same id fails.
14
+ * - `<id>.executed` — the approved action ran, written once: `markExecuted` answers true exactly once.
15
+ *
16
+ * Each file is written to a temporary name and then published with a hard link, which fails if the target exists.
17
+ * That makes every step atomic and exclusive without locks, also across processes sharing the directory, and a
18
+ * crash never leaves a half-written file under the final name. Tool definitions are stored as data (their facts
19
+ * and parameters); whoever resumes the call looks the tool up again by name.
20
+ */
21
+ class FileApprovalStore {
22
+ dir;
23
+ ready;
24
+ constructor(dir) {
25
+ this.dir = dir;
26
+ }
27
+ async put(req) {
28
+ await this.publish(req.id, 'request.json', JSON.stringify(req), `approval "${req.id}" already exists`);
29
+ }
30
+ async get(id) {
31
+ this.checkId(id);
32
+ const request = await this.readJson(this.file(id, 'request.json'));
33
+ if (!request)
34
+ return undefined;
35
+ const outcome = await this.readJson(this.file(id, 'outcome.json'));
36
+ const executedAt = await (0, promises_1.readFile)(this.file(id, 'executed'), 'utf8').catch(() => undefined);
37
+ const status = executedAt !== undefined ? 'executed'
38
+ : !outcome ? 'pending'
39
+ : outcome.decision === 'approve' ? 'approved' : 'rejected';
40
+ return { ...request, status, ...(outcome ? { outcome } : {}), ...(executedAt ? { executedAt } : {}) };
41
+ }
42
+ async resolve(id, outcome) {
43
+ this.checkId(id);
44
+ if (!(0, node_fs_1.existsSync)(this.file(id, 'request.json')))
45
+ throw new Error(`approval "${id}" does not exist`);
46
+ await this.publish(id, 'outcome.json', JSON.stringify(outcome), `approval "${id}" was already decided`);
47
+ return (await this.get(id));
48
+ }
49
+ async markExecuted(id) {
50
+ const item = await this.get(id);
51
+ if (!item)
52
+ throw new Error(`approval "${id}" does not exist`);
53
+ if (item.status === 'executed')
54
+ return false;
55
+ if (item.status !== 'approved')
56
+ throw new Error(`approval "${id}" is ${item.status}, not approved`);
57
+ try {
58
+ await this.publish(id, 'executed', new Date().toISOString(), '');
59
+ return true;
60
+ }
61
+ catch (err) {
62
+ if (err.alreadyExists)
63
+ return false;
64
+ throw err;
65
+ }
66
+ }
67
+ async list(filter = {}) {
68
+ let names;
69
+ try {
70
+ names = await (0, promises_1.readdir)(this.dir);
71
+ }
72
+ catch {
73
+ return [];
74
+ }
75
+ const out = [];
76
+ for (const name of names) {
77
+ if (!name.endsWith('.request.json'))
78
+ continue;
79
+ const item = await this.get(name.slice(0, -'.request.json'.length));
80
+ if (!item)
81
+ continue;
82
+ if (filter.status && item.status !== filter.status)
83
+ continue;
84
+ if (filter.agentId && item.principal.agentId !== filter.agentId)
85
+ continue;
86
+ out.push(item);
87
+ }
88
+ return out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
89
+ }
90
+ // ── internals ────────────────────────────────────────────────────────────
91
+ checkId(id) {
92
+ if (!ID.test(id))
93
+ throw new Error(`invalid approval id "${id}"`);
94
+ }
95
+ file(id, suffix) {
96
+ return (0, node_path_1.join)(this.dir, `${id}.${suffix}`);
97
+ }
98
+ async readJson(path) {
99
+ try {
100
+ return JSON.parse(await (0, promises_1.readFile)(path, 'utf8'));
101
+ }
102
+ catch {
103
+ return undefined;
104
+ }
105
+ }
106
+ /** Write to a unique temporary file, then hard-link it under the final name (fails if it exists). */
107
+ async publish(id, suffix, content, existsMessage) {
108
+ this.checkId(id);
109
+ this.ready ??= (0, promises_1.mkdir)(this.dir, { recursive: true });
110
+ await this.ready;
111
+ const target = this.file(id, suffix);
112
+ const tmp = (0, node_path_1.join)(this.dir, `.${id}.${suffix}.${process.pid}.${(0, node_crypto_1.randomBytes)(6).toString('hex')}.tmp`);
113
+ await (0, promises_1.writeFile)(tmp, content, { flag: 'wx' });
114
+ try {
115
+ await (0, promises_1.link)(tmp, target);
116
+ }
117
+ catch (err) {
118
+ if (err.code === 'EEXIST') {
119
+ throw Object.assign(new Error(existsMessage), { alreadyExists: true });
120
+ }
121
+ throw err;
122
+ }
123
+ finally {
124
+ await (0, promises_1.unlink)(tmp).catch(() => undefined);
125
+ }
126
+ }
127
+ }
128
+ exports.FileApprovalStore = FileApprovalStore;
129
+ //# sourceMappingURL=approval-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-store.js","sourceRoot":"","sources":["../../src/governance/approval-store.ts"],"names":[],"mappings":";;;AAAA,6CAA0C;AAC1C,qCAAqC;AACrC,+CAAqF;AACrF,yCAAiC;AAGjC,MAAM,EAAE,GAAG,mCAAmC,CAAC;AAE/C;;;;;;;;;;;GAWG;AACH,MAAa,iBAAiB;IAGG;IAFrB,KAAK,CAAoB;IAEjC,YAA6B,GAAW;QAAX,QAAG,GAAH,GAAG,CAAQ;IAAG,CAAC;IAE5C,KAAK,CAAC,GAAG,CAAC,GAAoB;QAC1B,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,cAAc,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,aAAa,GAAG,CAAC,EAAE,kBAAkB,CAAC,CAAC;IAC3G,CAAC;IAED,K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equest, Approver, ApproverKind, ApproverRef, Principal } from './types';
3
+ /**
4
+ * Checks an approver's answer against the rules of SPEC-0014 §6.2 before the engine accepts it. Returns the reason
5
+ * it is not valid, or undefined when it is. An invalid approval is treated as a rejection.
6
+ *
7
+ * 1. The approver's kind is one the decision accepts.
8
+ * 2. Nobody approves their own request: not the agent that asked, nor any agent in its delegation chain.
9
+ * 3. An agent approves only what it could do itself (`canAgentAct`, evaluated by the engine with that agent as
10
+ * principal over the same call).
11
+ *
12
+ * Rule 4 (every approval audited with its approver in full) is the engine's job when it writes the event.
13
+ */
14
+ export declare function approvalProblem(outcome: ApprovalOutcome, request: {
15
+ principal: Principal;
16
+ accepts?: ApproverKind[];
17
+ }, canAgentAct: (approver: ApproverRef) => Promise<boolean>): Promise<string | undefined>;
18
+ /** The legacy callback (`onToolApproval`) seen as an `Approver`; see {@link approverFromCallback}. */
19
+ export interface CallbackApprover extends Approver {
20
+ /** Stop asking for the rest of the session (what 'approve_all' does). Destructive calls still ask. */
21
+ disable(): void;
22
+ enable(): void;
23
+ }
24
+ /**
25
+ * Adapts `onToolApproval(toolName, agentId, argsPreview)` to the `Approver` contract. Its answers count as a
26
+ * person's (`kind: 'human'`). 'approve_all' stops asking for the rest of the session, except for destructive
27
+ * tools: an irreversible action is never approved in bulk (SPEC-0014 §4).
28
+ *
29
+ * @deprecated Pass an `Approver` instead. Kept so that existing `onToolApproval` callers work in the new path.
30
+ */
31
+ export declare function approverFromCallback(onToolApproval: (toolName: string, agentId: string, argsPreview: string) => Promise<ToolApprovalDecision>, opts?: {
32
+ id?: string;
33
+ onAsk?: (req: ApprovalRequest, preview: string) => void;
34
+ }): CallbackApprover;
35
+ //# sourceMappingURL=approval.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval.d.ts","sourceRoot":"","sources":["../../src/governance/approval.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,KAAK,EACR,eAAe,EAAE,eAAe,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,EACnF,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;GAUG;AACH,wBAAsB,eAAe,CACjC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE;IAAE,SAAS,EAAE,SAAS,CAAC;IAAC,OAAO,CAAC,EAAE,YAAY,EAAE,CAAA;CAAE,EAC3D,WAAW,EAAE,CAAC,QAAQ,EAAE,WAAW,KAAK,OAAO,CAAC,OAAO,CAAC,GACzD,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAgB7B;AAED,sGAAsG;AACtG,MAAM,WAAW,gBAAiB,SAAQ,QAAQ;IAC9C,sGAAsG;IACtG,OAAO,IAAI,IAAI,CAAC;IAChB,MAAM,IAAI,IAAI,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAChC,cAAc,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,oBAAoB,CAAC,EACzG,IAAI,GAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;CAAO,GACpF,gBAAgB,CAsBlB"}
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.approvalProblem = approvalProblem;
4
+ exports.approverFromCallback = approverFromCallback;
5
+ /**
6
+ * Checks an approver's answer against the rules of SPEC-0014 §6.2 before the engine accepts it. Returns the reason
7
+ * it is not valid, or undefined when it is. An invalid approval is treated as a rejection.
8
+ *
9
+ * 1. The approver's kind is one the decision accepts.
10
+ * 2. Nobody approves their own request: not the agent that asked, nor any agent in its delegation chain.
11
+ * 3. An agent approves only what it could do itself (`canAgentAct`, evaluated by the engine with that agent as
12
+ * principal over the same call).
13
+ *
14
+ * Rule 4 (every approval audited with its approver in full) is the engine's job when it writes the event.
15
+ */
16
+ async function approvalProblem(outcome, request, canAgentAct) {
17
+ const by = outcome.by;
18
+ if (!by || typeof by.id !== 'string' || !by.id || !['human', 'agent', 'service'].includes(by.kind)) {
19
+ return 'the approval does not say who approved it';
20
+ }
21
+ if (request.accepts && !request.accepts.includes(by.kind)) {
22
+ return `this action needs approval by ${request.accepts.join(' or ')}, not by ${by.kind} "${by.id}"`;
23
+ }
24
+ const { principal } = request;
25
+ if (by.kind !== 'human' && (by.id === principal.agentId || principal.chain.includes(by.id))) {
26
+ return `"${by.id}" cannot approve a request of its own delegation chain`;
27
+ }
28
+ if (by.kind === 'agent' && !(await canAgentAct(by))) {
29
+ return `agent "${by.id}" cannot approve an action it is not allowed to perform itself`;
30
+ }
31
+ return undefined;
32
+ }
33
+ /**
34
+ * Adapts `onToolApproval(toolName, agentId, argsPreview)` to the `Approver` contract. Its answers count as a
35
+ * person's (`kind: 'human'`). 'approve_all' stops asking for the rest of the session, except for destructive
36
+ * tools: an irreversible action is never approved in bulk (SPEC-0014 §4).
37
+ *
38
+ * @deprecated Pass an `Approver` instead. Kept so that existing `onToolApproval` callers work in the new path.
39
+ */
40
+ function approverFromCallback(onToolApproval, opts = {}) {
41
+ const ref = { kind: 'human', id: opts.id ?? 'operator' };
42
+ let approveAll = false;
43
+ return {
44
+ ref,
45
+ disable: () => { approveAll = true; },
46
+ enable: () => { approveAll = false; },
47
+ async request(req) {
48
+ const at = () => new Date().toISOString();
49
+ const subject = req.subject;
50
+ const call = subject.kind === 'tool_call' && 'call' in subject ? subject.call : undefined;
51
+ // "Approve all" never covers what only a person may approve (destructive tools, package installs...).
52
+ const humanOnly = !!call?.tool.destructive || (req.accepts?.length === 1 && req.accepts[0] === 'human');
53
+ if (approveAll && !humanOnly)
54
+ return { decision: 'approve', by: ref, reason: 'approve all (session)', at: at() };
55
+ const name = call ? call.tool.name : subject.kind;
56
+ const preview = (call ? JSON.stringify(call.args) : JSON.stringify(subject)).slice(0, 200);
57
+ opts.onAsk?.(req, preview);
58
+ const decision = await onToolApproval(name, req.principal.agentId, preview);
59
+ if (decision === 'approve_all')
60
+ approveAll = true;
61
+ return { decision: decision === 'reject' ? 'reject' : 'approve', by: ref, at: at() };
62
+ },
63
+ };
64
+ }
65
+ //# sourceMappingURL=approval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval.js","sourceRoot":"","sources":["../../src/governance/approval.ts"],"names":[],"mappings":";;AAgBA,0CAoBC;AAgBD,oDAyBC;AAxED;;;;;;;;;;GAUG;AACI,KAAK,UAAU,eAAe,CACjC,OAAwB,EACxB,OAA2D,EAC3D,WAAwD;IAExD,MAAM,EAAE,GAAG,OAAO,CAAC,EAAE,CAAC;IACtB,IAAI,CAAC,EAAE,IAAI,OAAO,EAAE,CAAC,EAAE,KAAK,QAAQ,IAAI,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACjG,OAAO,2CAA2C,CAAC;IACvD,CAAC;IACD,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACxD,OAAO,iCAAiC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE,GAAG,CAAC;IACzG,CAAC;IACD,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAC9B,IAAI,EAAE,CAAC,IAAI,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,EAAE,KAAK,SAAS,CAAC,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;QAC1F,OAAO,IAAI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AE,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,uBAAuB,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;YACjH,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;YAClD,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;YAC3F,IAAI,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YAC3B,MAAM,QAAQ,GAAG,MAAM,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC5E,IAAI,QAAQ,KAAK,aAAa;gBAAE,UAAU,GAAG,IAAI,CAAC;YAClD,OAAO,EAAE,QAAQ,EAAE,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;QACzF,CAAC;KACJ,CAAC;AACN,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ import type { ApprovalRequest, Approver } from './types';
3
+ /** A short, human-readable description of what is being approved. */
4
+ export declare function describeApproval(req: ApprovalRequest): string;
5
+ /**
6
+ * Another agent as approver (SPEC-0014 §6.2): the request is put to it as a question and its answer must start
7
+ * with APPROVE or REJECT. Its answer counts as `kind: 'agent'`, so the engine checks that it may approve: not for
8
+ * actions that accept only people, not for its own delegation chain, and only for what it could do itself.
9
+ *
10
+ * `consult` is how to ask it, typically `(id, q) => engine.consultAgent(id, q)`.
11
+ */
12
+ export declare function agentApprover(consult: (agentId: string, question: string) => Promise<string>, agentId: string, opts?: {
13
+ chain?: string[];
14
+ }): Approver;
15
+ /**
16
+ * A person at a terminal as approver: prints the request and reads y/n. Anything but y/yes rejects.
17
+ * Pass `input`/`output` streams to use something other than stdin/stdout.
18
+ */
19
+ export declare function consoleApprover(opts?: {
20
+ id?: string;
21
+ input?: Readable;
22
+ output?: Writable;
23
+ }): Approver;
24
+ //# sourceMappingURL=approvers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approvers.d.ts","sourceRoot":"","sources":["../../src/governance/approvers.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAmB,eAAe,EAAE,QAAQ,EAAe,MAAM,SAAS,CAAC;AAEvF,qEAAqE;AACrE,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,eAAe,GAAG,MAAM,CAS7D;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CACzB,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,EAC/D,OAAO,EAAE,MAAM,EACf,IAAI,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CAAO,GAChC,QAAQ,CAcV;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,GAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,QAAQ,CAAC;IAAC,MAAM,CAAC,EAAE,QAAQ,CAAA;CAAO,GAAG,QAAQ,CAezG"}
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.describeApproval = describeApproval;
4
+ exports.agentApprover = agentApprover;
5
+ exports.consoleApprover = consoleApprover;
6
+ const node_os_1 = require("node:os");
7
+ const promises_1 = require("node:readline/promises");
8
+ /** A short, human-readable description of what is being approved. */
9
+ function describeApproval(req) {
10
+ const s = req.subject;
11
+ const what = s.kind === 'tool_call' && 'call' in s
12
+ ? `call tool "${s.call.tool.name}" with ${JSON.stringify(s.call.args)}`
13
+ : s.kind === 'workflow_step' && 'step' in s ? `run step "${s.step}" of workflow "${s.workflow}"`
14
+ : s.kind === 'rule_proposal' && 'evidence' in s ? `adopt a learned rule (${s.evidence})`
15
+ : 'summary' in s ? s.summary : s.kind;
16
+ const chain = req.principal.chain.join(' → ');
17
+ return `Agent "${req.principal.agentId}" (${chain}) wants to ${what}. Reason it needs approval: ${req.reason}.`;
18
+ }
19
+ /**
20
+ * Another agent as approver (SPEC-0014 §6.2): the request is put to it as a question and its answer must start
21
+ * with APPROVE or REJECT. Its answer counts as `kind: 'agent'`, so the engine checks that it may approve: not for
22
+ * actions that accept only people, not for its own delegation chain, and only for what it could do itself.
23
+ *
24
+ * `consult` is how to ask it, typically `(id, q) => engine.consultAgent(id, q)`.
25
+ */
26
+ function agentApprover(consult, agentId, opts = {}) {
27
+ const ref = { kind: 'agent', id: agentId, chain: opts.chain ?? [agentId] };
28
+ return {
29
+ ref,
30
+ async request(req) {
31
+ const question = `${describeApproval(req)}\n\n` +
32
+ 'You are asked to approve or reject this action. Answer with APPROVE or REJECT as the first word, ' +
33
+ 'followed by one sentence explaining why. Do not perform the action yourself.';
34
+ const answer = (await consult(agentId, question)).trim();
35
+ const decision = /^\W*approve\b/i.test(answer) ? 'approve' : 'reject';
36
+ return { decision, by: ref, reason: answer.slice(0, 500), at: new Date().toISOString() };
37
+ },
38
+ };
39
+ }
40
+ /**
41
+ * A person at a terminal as approver: prints the request and reads y/n. Anything but y/yes rejects.
42
+ * Pass `input`/`output` streams to use something other than stdin/stdout.
43
+ */
44
+ function consoleApprover(opts = {}) {
45
+ const ref = { kind: 'human', id: opts.id ?? safeUserName() };
46
+ return {
47
+ ref,
48
+ async request(req) {
49
+ const rl = (0, promises_1.createInterface)({ input: opts.input ?? process.stdin, output: opts.output ?? process.stdout, terminal: false });
50
+ try {
51
+ const answer = (await rl.question(`\n${describeApproval(req)}\nApprove? [y/N] `)).trim().toLowerCase();
52
+ const decision = answer === 'y' || answer === 'yes' ? 'approve' : 'reject';
53
+ return { decision, by: ref, at: new Date().toISOString() };
54
+ }
55
+ finally {
56
+ rl.close();
57
+ }
58
+ },
59
+ };
60
+ }
61
+ function safeUserName() {
62
+ try {
63
+ return (0, node_os_1.userInfo)().username || 'operator';
64
+ }
65
+ catch {
66
+ return 'operator';
67
+ }
68
+ }
69
+ //# sourceMappingURL=approvers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approvers.js","sourceRoot":"","sources":["../../src/governance/approvers.ts"],"names":[],"mappings":";;AAMA,4CASC;AASD,sCAkBC;AAMD,0CAeC;AA/DD,qCAAmC;AACnC,qDAAyD;AAIzD,qEAAqE;AACrE,SAAgB,gBAAgB,CAAC,GAAoB;IACjD,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC;IACtB,MAAM,IAAI,GAAG,CAAC,CAAC,IAAI,KAAK,WAAW,IAAI,MAAM,IAAI,CAAC;QAC9C,CAAC,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,UAAU,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;QACvE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,eAAe,IAAI,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,IAAI,kBAAkB,CAAC,CAAC,QAAQ,GAAG;YAChG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,eAAe,IAAI,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,yBAAyB,CAAC,CAAC,QAAQ,GAAG;gBACxF,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC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ACH,KAAK,CAAC,OAAO,CAAC,GAAoB;YAC9B,MAAM,EAAE,GAAG,IAAA,0BAAe,EAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;YAC3H,IAAI,CAAC;gBACD,MAAM,MAAM,GAAG,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,KAAK,gBAAgB,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;gBACvG,MAAM,QAAQ,GAAG,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC;gBAC3E,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;YAC/D,CAAC;oBAAS,CAAC;gBACP,EAAE,CAAC,KAAK,EAAE,CAAC;YACf,CAAC;QACL,CAAC;KACJ,CAAC;AACN,CAAC;AAED,SAAS,YAAY;IACjB,IAAI,CAAC;QAAC,OAAO,IAAA,kBAAQ,GAAE,CAAC,QAAQ,IAAI,UAAU,CAAC;IAAC,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,UAAU,CAAC;IAAC,CAAC;AAClF,CAAC"}
@@ -0,0 +1,101 @@
1
+ import type { AuditEvent, AuditSink } from './types';
2
+ /** Keeps events in memory, in write order. For tests and for in-process inspection. */
3
+ export declare class MemoryAuditSink implements AuditSink {
4
+ readonly events: AuditEvent[];
5
+ write(event: AuditEvent): void;
6
+ }
7
+ /** One JSON line per event, appended to `path` (directory created on first write). No integrity guarantee. */
8
+ export declare class NdjsonAuditSink implements AuditSink {
9
+ private readonly path;
10
+ private ready?;
11
+ constructor(path: string);
12
+ write(event: AuditEvent): Promise<void>;
13
+ }
14
+ /** `prevHash` of the first entry. */
15
+ export declare const GENESIS_HASH: string;
16
+ /**
17
+ * One line of a chained log. `hash` covers `seq`, `prevHash` and the event, so changing, dropping or reordering any
18
+ * line breaks the chain. Same scheme as Steward's governance log.
19
+ */
20
+ export interface ChainedAuditEntry {
21
+ seq: number;
22
+ prevHash: string;
23
+ hash: string;
24
+ event: AuditEvent;
25
+ /** HMAC-SHA256 of `hash` with the sink's secret, when it has one. */
26
+ mac?: string;
27
+ }
28
+ export type ChainVerification = {
29
+ ok: true;
30
+ entries: number;
31
+ head: string;
32
+ } | {
33
+ ok: false;
34
+ entries: number;
35
+ brokenAt: number;
36
+ reason: string;
37
+ };
38
+ export type SegmentVerification = {
39
+ ok: true;
40
+ count: number;
41
+ last: {
42
+ seq: number;
43
+ hash: string;
44
+ };
45
+ } | {
46
+ ok: false;
47
+ at: number;
48
+ reason: string;
49
+ };
50
+ /**
51
+ * Checks a chained log from its first line. A missing file is an empty, valid log. With `secret`, every entry
52
+ * must also carry a valid MAC: a log rewritten by someone without the secret, every hash recomputed, does not pass.
53
+ */
54
+ export declare function verifyAuditChain(filePath: string, options?: {
55
+ secret?: string | Uint8Array;
56
+ }): ChainVerification;
57
+ /**
58
+ * Checks entries that continue a chain from a known point (`after`: the seq and hash of the entry before the first;
59
+ * `{ seq: 0, hash: GENESIS_HASH }` for a new chain). How a receiver that keeps the head of a log accepts a batch.
60
+ */
61
+ export declare function verifyAuditSegment(entries: readonly ChainedAuditEntry[], after: {
62
+ seq: number;
63
+ hash: string;
64
+ }): SegmentVerification;
65
+ /**
66
+ * Append-only audit log where every entry carries the hash of the previous one, so editing, deleting or reordering
67
+ * past entries is detectable with {@link verifyAuditChain}.
68
+ *
69
+ * - Someone who can rewrite the whole file can recompute every hash. Pass a `secret` (kept away from that file's
70
+ * writers) to add a MAC per entry, and/or store `head` somewhere the writer cannot reach.
71
+ * - One writer per file: two processes appending to the same file would fork the chain.
72
+ * - Writing is synchronous and fsync'd, and errors are thrown: a record that cannot be written is not lost silently.
73
+ * - Opening a file whose chain is already broken throws: a tampered log is not extended.
74
+ */
75
+ export declare class HashChainAuditSink implements AuditSink {
76
+ private readonly filePath;
77
+ private readonly options;
78
+ private seq;
79
+ private prevHash;
80
+ constructor(filePath: string, options?: {
81
+ secret?: string | Uint8Array;
82
+ });
83
+ /** Hash of the last entry. Store it elsewhere to anchor the log. */
84
+ get head(): string;
85
+ /** Number of entries: the `seq` of the last one. */
86
+ get count(): number;
87
+ write(event: AuditEvent): void;
88
+ }
89
+ /**
90
+ * Fans one event out to several sinks, one event at a time in call order (a hash chain needs a stable order, and
91
+ * parallel tool calls finish in any order). A failing sink does not stop the others; the failure is reported.
92
+ */
93
+ export declare class AuditDispatcher {
94
+ private readonly onError;
95
+ private readonly sinks;
96
+ private queue;
97
+ constructor(sinks: AuditSink | AuditSink[] | undefined, onError: (err: unknown, sink: AuditSink) => void);
98
+ get enabled(): boolean;
99
+ write(event: AuditEvent): Promise<void>;
100
+ }
101
+ //# sourceMappingURL=audit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.d.ts","sourceRoot":"","sources":["../../src/governance/audit.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAErD,uFAAuF;AACvF,qBAAa,eAAgB,YAAW,SAAS;IAC7C,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,CAAM;IACnC,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;CACjC;AAED,8GAA8G;AAC9G,qBAAa,eAAgB,YAAW,SAAS;IAEjC,OAAO,CAAC,QAAQ,CAAC,IAAI;IADjC,OAAO,CAAC,KAAK,CAAC,CAAmB;gBACJ,IAAI,EAAE,MAAM;IACnC,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;CAKhD;AAID,qCAAqC;AACrC,eAA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,QAAQ;IAAU,OAAO,CAAC,QAAQ,CAAC,OAAO;IAHvE,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,QAAQ,CAAS;gBAEI,QAAQ,EAAE,MAAM,EAAmB,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,MAAM,GAAG,UAAU,CAAA;KAAO;IAU9G,oEAAoE;IACpE,IAAI,IAAI,IAAI,MAAM,CAA0B;IAE5C,oDAAoD;IACpD,IAAI,KAAK,IAAI,MAAM,CAAqB;IAExC,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI;CAYjC;AAED;;;GAGG;AACH,qBAAa,eAAe;IAIgC,OAAO,CAAC,QAAQ,CAAC,OAAO;IAHhF,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAc;IACpC,OAAO,CAAC,KAAK,CAAoC;gBAErC,KAAK,EAAE,SAAS,GAAG,SAAS,EAAE,GAAG,SAAS,EAAmB,OAAO,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,KAAK,IAAI;IAIzH,IAAI,OAAO,IAAI,OAAO,CAAkC;IAExD,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;CAW1C"}
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuditDispatcher = exports.HashChainAuditSink = exports.GENESIS_HASH = exports.NdjsonAuditSink = exports.MemoryAuditSink = void 0;
4
+ exports.verifyAuditChain = verifyAuditChain;
5
+ exports.verifyAuditSegment = verifyAuditSegment;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const promises_1 = require("node:fs/promises");
8
+ const node_fs_1 = require("node:fs");
9
+ const node_path_1 = require("node:path");
10
+ const canonical_json_1 = require("../shared/utils/canonical-json");
11
+ /** Keeps events in memory, in write order. For tests and for in-process inspection. */
12
+ class MemoryAuditSink {
13
+ events = [];
14
+ write(event) { this.events.push(event); }
15
+ }
16
+ exports.MemoryAuditSink = MemoryAuditSink;
17
+ /** One JSON line per event, appended to `path` (directory created on first write). No integrity guarantee. */
18
+ class NdjsonAuditSink {
19
+ path;
20
+ ready;
21
+ constructor(path) {
22
+ this.path = path;
23
+ }
24
+ async write(event) {
25
+ this.ready ??= (0, promises_1.mkdir)((0, node_path_1.dirname)(this.path), { recursive: true });
26
+ await this.ready;
27
+ await (0, promises_1.appendFile)(this.path, `${JSON.stringify(event)}\n`);
28
+ }
29
+ }
30
+ exports.NdjsonAuditSink = NdjsonAuditSink;
31
+ // ── Hash chain ────────────────────────────────────────────────────────────────
32
+ /** `prevHash` of the first entry. */
33
+ exports.GENESIS_HASH = '0'.repeat(64);
34
+ const entryHash = (seq, prevHash, event) => (0, node_crypto_1.createHash)('sha256').update(`${seq}\n${prevHash}\n${(0, canonical_json_1.canonicalJson)(event)}`).digest('hex');
35
+ const macOf = (secret, hash) => (0, node_crypto_1.createHmac)('sha256', secret).update(`audit:${hash}`).digest('hex');
36
+ function macMatches(secret, hash, mac) {
37
+ if (typeof mac !== 'string')
38
+ return false;
39
+ const expected = Buffer.from(macOf(secret, hash), 'hex');
40
+ const given = Buffer.from(mac, 'hex');
41
+ return given.length === expected.length && (0, node_crypto_1.timingSafeEqual)(given, expected);
42
+ }
43
+ /**
44
+ * Checks a chained log from its first line. A missing file is an empty, valid log. With `secret`, every entry
45
+ * must also carry a valid MAC: a log rewritten by someone without the secret, every hash recomputed, does not pass.
46
+ */
47
+ function verifyAuditChain(filePath, options = {}) {
48
+ if (!(0, node_fs_1.existsSync)(filePath))
49
+ return { ok: true, entries: 0, head: exports.GENESIS_HASH };
50
+ const lines = (0, node_fs_1.readFileSync)(filePath, 'utf8').split('\n').filter(l => l.length > 0);
51
+ let prev = exports.GENESIS_HASH;
52
+ for (let i = 0; i < lines.length; i++) {
53
+ const seq = i + 1;
54
+ let entry;
55
+ try {
56
+ entry = JSON.parse(lines[i]);
57
+ }
58
+ catch {
59
+ return { ok: false, entries: i, brokenAt: seq, reason: 'line is not valid JSON' };
60
+ }
61
+ if (entry.seq !== seq)
62
+ return { ok: false, entries: i, brokenAt: seq, reason: `expected seq ${seq}, found ${String(entry.seq)} (a line was removed, added or reordered)` };
63
+ if (entry.prevHash !== prev)
64
+ return { ok: false, entries: i, brokenAt: seq, reason: 'prevHash does not match the previous entry' };
65
+ if (entry.hash !== entryHash(seq, entry.prevHash, entry.event))
66
+ return { ok: false, entries: i, brokenAt: seq, reason: 'hash does not match the content (the entry was modified)' };
67
+ if (options.secret && !macMatches(options.secret, entry.hash, entry.mac)) {
68
+ return { ok: false, entries: i, brokenAt: seq, reason: 'the entry carries no valid MAC for this secret' };
69
+ }
70
+ prev = entry.hash;
71
+ }
72
+ return { ok: true, entries: lines.length, head: prev };
73
+ }
74
+ /**
75
+ * Checks entries that continue a chain from a known point (`after`: the seq and hash of the entry before the first;
76
+ * `{ seq: 0, hash: GENESIS_HASH }` for a new chain). How a receiver that keeps the head of a log accepts a batch.
77
+ */
78
+ function verifyAuditSegment(entries, after) {
79
+ let prev = after.hash;
80
+ let seq = after.seq;
81
+ for (const entry of entries) {
82
+ seq += 1;
83
+ if (!entry || typeof entry !== 'object' || typeof entry.hash !== 'string' || typeof entry.prevHash !== 'string' || !entry.event) {
84
+ return { ok: false, at: seq, reason: 'not an audit entry' };
85
+ }
86
+ if (entry.seq !== seq)
87
+ return { ok: false, at: seq, reason: `expected seq ${seq}, found ${String(entry.seq)}` };
88
+ if (entry.prevHash !== prev)
89
+ return { ok: false, at: seq, reason: 'prevHash does not match the previous entry' };
90
+ if (entry.hash !== entryHash(seq, entry.prevHash, entry.event))
91
+ return { ok: false, at: seq, reason: 'hash does not match the content' };
92
+ prev = entry.hash;
93
+ }
94
+ return { ok: true, count: entries.length, last: { seq, hash: prev } };
95
+ }
96
+ /**
97
+ * Append-only audit log where every entry carries the hash of the previous one, so editing, deleting or reordering
98
+ * past entries is detectable with {@link verifyAuditChain}.
99
+ *
100
+ * - Someone who can rewrite the whole file can recompute every hash. Pass a `secret` (kept away from that file's
101
+ * writers) to add a MAC per entry, and/or store `head` somewhere the writer cannot reach.
102
+ * - One writer per file: two processes appending to the same file would fork the chain.
103
+ * - Writing is synchronous and fsync'd, and errors are thrown: a record that cannot be written is not lost silently.
104
+ * - Opening a file whose chain is already broken throws: a tampered log is not extended.
105
+ */
106
+ class HashChainAuditSink {
107
+ filePath;
108
+ options;
109
+ seq;
110
+ prevHash;
111
+ constructor(filePath, options = {}) {
112
+ this.filePath = filePath;
113
+ this.options = options;
114
+ const check = verifyAuditChain(filePath, options);
115
+ if (!check.ok) {
116
+ throw new Error(`Audit log ${filePath} is not intact at entry ${check.brokenAt}: ${check.reason}. Refusing to append to it.`);
117
+ }
118
+ this.seq = check.entries;
119
+ this.prevHash = check.head;
120
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(filePath), { recursive: true });
121
+ }
122
+ /** Hash of the last entry. Store it elsewhere to anchor the log. */
123
+ get head() { return this.prevHash; }
124
+ /** Number of entries: the `seq` of the last one. */
125
+ get count() { return this.seq; }
126
+ write(event) {
127
+ const seq = this.seq + 1;
128
+ const hash = entryHash(seq, this.prevHash, event);
129
+ const entry = {
130
+ seq, prevHash: this.prevHash, hash, event,
131
+ ...(this.options.secret ? { mac: macOf(this.options.secret, hash) } : {}),
132
+ };
133
+ const fd = (0, node_fs_1.openSync)(this.filePath, 'a');
134
+ try {
135
+ (0, node_fs_1.writeSync)(fd, `${JSON.stringify(entry)}\n`);
136
+ (0, node_fs_1.fsyncSync)(fd);
137
+ }
138
+ finally {
139
+ (0, node_fs_1.closeSync)(fd);
140
+ }
141
+ this.seq = seq;
142
+ this.prevHash = hash;
143
+ }
144
+ }
145
+ exports.HashChainAuditSink = HashChainAuditSink;
146
+ /**
147
+ * Fans one event out to several sinks, one event at a time in call order (a hash chain needs a stable order, and
148
+ * parallel tool calls finish in any order). A failing sink does not stop the others; the failure is reported.
149
+ */
150
+ class AuditDispatcher {
151
+ onError;
152
+ sinks;
153
+ queue = Promise.resolve();
154
+ constructor(sinks, onError) {
155
+ this.onError = onError;
156
+ this.sinks = sinks === undefined ? [] : Array.isArray(sinks) ? sinks : [sinks];
157
+ }
158
+ get enabled() { return this.sinks.length > 0; }
159
+ write(event) {
160
+ if (!this.enabled)
161
+ return Promise.resolve();
162
+ const run = async () => {
163
+ for (const sink of this.sinks) {
164
+ try {
165
+ await sink.write(event);
166
+ }
167
+ catch (err) {
168
+ this.onError(err, sink);
169
+ }
170
+ }
171
+ };
172
+ const next = this.queue.then(run);
173
+ this.queue = next.catch(() => undefined);
174
+ return next;
175
+ }
176
+ }
177
+ exports.AuditDispatcher = AuditDispatcher;
178
+ //# sourceMappingURL=audit.js.map