@agent-custody/receipts 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,269 @@
1
+ # agent-custody
2
+
3
+ Chain of custody for AI agents: signed, independently verifiable receipts for every tool call.
4
+
5
+ Two producers, one receipt format, one verifier.
6
+
7
+ - **The gateway** is an MCP proxy between an agent and the systems it can affect. For every tool call, allowed or denied, it checks a delegation grant signed by the human principal, gathers the facts the policy needs by calling upstream itself, evaluates a Cedar policy that fails closed, forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
8
+ - **The SDK** is an interceptor inside the agent's own process, hooked into the framework's tool-call callbacks: Claude Code, the Claude Agent SDK, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, or any function you wrap. It reaches everything the gateway cannot see and issues the same receipts, labelled as self-reported.
9
+
10
+ Anyone holding the public keys can verify a receipt offline. The agent is not trusted. The layer around it is, and the receipt says exactly how far that trust extends, starting with who issued it.
11
+
12
+ - [Tutorials](docs/tutorials.md): twelve runnable examples, one per aspect of the code, all executed by the test suite
13
+ - [Usage guide](docs/usage.md): gateway setup, wiring into Claude Desktop, Claude Code, or your own agent loop
14
+ - [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK and LangChain, and wrapping tool functions in anything else
15
+ - [Writing policies](docs/policies.md): how a tool call becomes a Cedar request, with tested examples
16
+ - [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
17
+
18
+ ## Getting started
19
+
20
+ ```bash
21
+ npm install @agent-custody/receipts # or bun add, pnpm add
22
+ ```
23
+
24
+ Not on npm yet: the `@agent-custody` scope is still to be claimed. Until then, build from a clone and install the tarball:
25
+
26
+ ```bash
27
+ bun install && bun run build # at the repository root
28
+ cd packages/receipts && bun pm pack # writes agent-custody-receipts-0.1.0.tgz here
29
+ npm install /path/to/agent-custody/packages/receipts/agent-custody-receipts-0.1.0.tgz # in your project
30
+ ```
31
+
32
+ Record receipts from inside your own agent, no gateway needed. Generate a signing key, point a config at it, wrap the functions the agent calls:
33
+
34
+ ```bash
35
+ npx agent-custody keygen --dir keys --name app
36
+ ```
37
+
38
+ ```json
39
+ { "agentId": "billing-bot", "identity": { "keyFile": "keys/app.key" }, "receiptsDir": "receipts", "logFile": "log.jsonl" }
40
+ ```
41
+
42
+ ```ts
43
+ import { createSdkIssuer, loadSdkConfig, loadPublicKey, verifyBundle } from "@agent-custody/receipts";
44
+
45
+ const issuer = createSdkIssuer(loadSdkConfig("./sdk.json"));
46
+ const refund = issuer.wrap("stripe.refund", async (args: { amount: number }) => stripe.refund(args));
47
+ await refund({ amount: 5000 }); // one signed receipt in receipts/, one leaf in log.jsonl
48
+
49
+ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
50
+ verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
51
+ ```
52
+
53
+ Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK and LangChain, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx agent-custody gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md).
54
+
55
+ ## How it fits together
56
+
57
+ ```mermaid
58
+ flowchart LR
59
+ P["Principal<br/>(human or org, holds a signing key)"]
60
+ A["Agent host<br/>Claude Desktop, Claude Code,<br/>LangGraph, custom loop"]
61
+ S["SDK interceptor<br/>inside the agent process:<br/>hooks or wrapped tools"]
62
+ G["agent-custody gateway<br/>scope check → fact lookups → Cedar policy"]
63
+ U["Upstream MCP server<br/>Stripe, database, GitHub, ..."]
64
+ R[("receipt bundles<br/>receipts/*.json")]
65
+ L[("Merkle log<br/>log.jsonl")]
66
+ V["Verifier<br/>auditor, counterparty, CI job"]
67
+ O["Observability<br/>OTel, LangSmith, Arize"]
68
+
69
+ P -- "signed delegation grant" --> G
70
+ A -- "MCP tools/call" --> G
71
+ G -- "only on allow" --> U
72
+ U -- "result" --> G
73
+ G -- "result + receipt id, or denial + receipt id" --> A
74
+ G -- "signed receipt (issuer: gateway)" --> R
75
+ G -- "leaf hash" --> L
76
+ A -. "in-process tool calls" .-> S
77
+ S -- "signed receipt (issuer: sdk)" --> R
78
+ S -- "leaf hash" --> L
79
+ R --> V
80
+ L -. "copy of the log (optional)" .-> V
81
+ P -. "public key" .-> V
82
+ G -. "public key" .-> V
83
+ A -. "traces (unchanged)" .-> O
84
+ ```
85
+
86
+ Three parties hold keys. The **principal** signs a grant saying which agent may use which tools until when. The **issuer**, gateway or SDK, signs every receipt and every tree head. The **verifier** holds only public keys and needs no access to the issuer, the agent, or the upstream system.
87
+
88
+ ## Two producers, one receipt
89
+
90
+ | | gateway | SDK |
91
+ | --- | --- | --- |
92
+ | where it runs | separate process between agent and tools | inside the agent's process |
93
+ | what it sees | MCP tool calls | whatever the framework's hooks expose |
94
+ | enforcement | yes, denied calls never reach upstream | only where a hook can block |
95
+ | provenance of its fields | `attested` and `observed` | `claimed`, all of them |
96
+ | what a verifier learns | the agent could not skip or forge this | the agent's process reported this and it has not changed since |
97
+ | install | one line in the host's MCP config | a hook entry or a wrapped function |
98
+
99
+ Every receipt names its issuer, and the verifier prints what that issuer kind is worth before anything else. A dashboard full of `sdk` rows is the reason to route the consequential calls through the gateway.
100
+
101
+ ### Supported hosts and frameworks
102
+
103
+ | host or framework | producer | enforce + record | record only | tested against |
104
+ | --- | --- | --- | --- | --- |
105
+ | any MCP host: Claude Desktop, Claude Code, Cursor, custom | gateway | yes | | a real MCP client and upstream over stdio |
106
+ | Claude Code | SDK | `hook` command, PreToolUse deny | PostToolUse | the documented hook contract, via stdin |
107
+ | Claude Agent SDK | SDK | `claudeAgentHooks` | same | the same handler |
108
+ | OpenAI Agents SDK (JS) | SDK | `wrapTools` | `observeRunner` | a real `Runner` with a scripted model |
109
+ | Vercel AI SDK | SDK | `wrapTools` | | a real `generateText` loop over the SDK's mock model |
110
+ | LangChain / LangGraph (JS) | SDK | `tool(issuer.wrap(fn))` | `ReceiptCallbackHandler` | real `StructuredTool` invocations |
111
+ | anything else | SDK | `issuer.wrap(name, fn)` | `issuer.record` | plain functions |
112
+
113
+ The framework packages are optional peer dependencies. Each adapter imports only from its own package.
114
+
115
+ ## One tool call, end to end
116
+
117
+ ```mermaid
118
+ sequenceDiagram
119
+ participant Agent
120
+ participant Gateway
121
+ participant Upstream as Upstream MCP server
122
+ participant Log as Merkle log
123
+
124
+ Agent->>Gateway: tools/call stripe.refund {customer_id, amount}
125
+ Gateway->>Gateway: tool in signed grant's scopes?
126
+ Gateway->>Upstream: tools/call customer.lookup {customer_id}
127
+ Upstream-->>Gateway: {verified: true}
128
+ Note over Gateway: facts.customer = that result, labelled "observed"
129
+ Gateway->>Gateway: Cedar: permit if amount ≤ limit and facts.customer.verified
130
+ alt allow
131
+ Gateway->>Upstream: tools/call stripe.refund {customer_id, amount}
132
+ Upstream-->>Gateway: {refund_id, status}
133
+ else deny
134
+ Note over Gateway: no upstream call is made
135
+ end
136
+ Gateway->>Gateway: build in-toto statement, sign (DSSE, Ed25519)
137
+ Gateway->>Log: append canonical envelope
138
+ Log-->>Gateway: leaf index, inclusion proof, root
139
+ Gateway->>Gateway: sign tree head, write bundle to receipts/
140
+ Gateway-->>Agent: result or denial, _meta["agent-custody/receipt"] = id
141
+ ```
142
+
143
+ Denied calls get receipts too. "The agent tried to pay out funds and was refused" is evidence worth keeping.
144
+
145
+ ## Anatomy of a receipt bundle
146
+
147
+ ```mermaid
148
+ flowchart TB
149
+ B["receipt bundle (one JSON file)"]
150
+ B --> E["envelope: DSSE, signed by gateway key"]
151
+ B --> T["treeHead: DSSE, signed by gateway key<br/>{treeSize, rootHash, timestamp}"]
152
+ B --> I["inclusion: {leafIndex, treeSize, hashes[]}"]
153
+ E --> S["in-toto Statement v1"]
154
+ S --> SU["subject: tool-call:&lt;tool&gt;:&lt;id&gt;<br/>digest = sha256(args)"]
155
+ S --> PR["predicate"]
156
+ PR --> P0["issuer: gateway or sdk, keyid, framework"]
157
+ PR --> P1["principal, agent, delegation<br/><b>attested</b>: signed by principal key (gateway)"]
158
+ PR --> P2["tool, facts, policy decision, execution<br/><b>observed</b>: gateway obtained it (gateway)"]
159
+ PR --> P3["args, model id, session<br/><b>claimed</b>: agent-supplied, unchecked (both)<br/>every field, when issued by the sdk"]
160
+ ```
161
+
162
+ Every field carries a provenance label. This is the design decision that matters most, and it is what a verifier reads back.
163
+
164
+ | provenance | meaning | today's examples |
165
+ | --- | --- | --- |
166
+ | `attested` | signed by a key other than the issuer's | principal id, agent id, the delegation grant (gateway receipts) |
167
+ | `observed` | the issuer obtained it deterministically, outside the agent's control | upstream tool results, fact lookups, the policy decision, execution status (gateway receipts) |
168
+ | `claimed` | originated from the agent, the model, or the agent's own process, no independent check | tool arguments, the model id, session ids, and every field of an SDK receipt |
169
+
170
+ ## Quick start
171
+
172
+ ```bash
173
+ bun install # from the repository root, once for the workspace
174
+ cd packages/receipts
175
+ node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
176
+ node examples/01-keys-and-signing.ts # first of twelve step-by-step examples, see docs/tutorials.md
177
+ bun run test # this package; `bun run test` at the root runs every package
178
+ ```
179
+
180
+ Everything runs on plain Node 22 or later. No build step, no `npx`, no `tsx` needed on the command line.
181
+
182
+ The demo leaves everything in `demo-out/`, including receipts from both producers. Verify a receipt by hand:
183
+
184
+ ```bash
185
+ node src/cli.ts verify demo-out/receipts/<id>.json \
186
+ --issuer-key demo-out/keys/gateway.pub \
187
+ --principal-key demo-out/keys/principal.pub \
188
+ --log demo-out/log.jsonl
189
+ ```
190
+
191
+ Exit code 0 means every check passed. See [docs/verification.md](docs/verification.md) for what the report means.
192
+
193
+ To issue receipts from your own agent code, without a gateway:
194
+
195
+ ```ts
196
+ import { loadSdkConfig } from "./src/config.ts";
197
+ import { createSdkIssuer } from "./src/sdk/index.ts";
198
+
199
+ const issuer = createSdkIssuer(loadSdkConfig("./sdk.json"));
200
+ const refund = issuer.wrap("stripe.refund", async (args: { amount: number }) => stripe.refund(args));
201
+ ```
202
+
203
+ [docs/sdk.md](docs/sdk.md) has the config file and the per-framework adapters.
204
+
205
+ ## What a receipt proves, and what it does not
206
+
207
+ | claim | verifier | adversary | mechanism | status |
208
+ | --- | --- | --- | --- | --- |
209
+ | receipt was not altered after issue | anyone | later editor | DSSE signature over canonical JSON | done |
210
+ | receipt was issued in sequence, none removed | auditor with a log copy | operator rewriting history | Merkle inclusion proof + recomputed root | done |
211
+ | the principal really delegated this scope to this agent | anyone with the principal's key | operator, agent | grant signed by principal key, checked for scope and validity window | done |
212
+ | the policy decision was made against this exact policy | anyone | operator swapping policies | sha256 of policy text in the receipt | done |
213
+ | facts the policy relied on were not asserted by the agent | anyone reading the receipt | agent | facts fetched by the gateway, recorded with their own digests, labelled `observed` | done |
214
+ | the upstream system actually executed the action | third party | operator | needs the upstream's own signed response embedded verbatim | **not done**, depends on the tool provider |
215
+ | the operator itself cannot mint a false receipt | regulator, counterparty | operator | needs a TEE-hosted signer or a federated log | **not done** |
216
+ | which model produced the call | anyone | operator | no hosted provider signs model identity | **not possible today**, labelled `claimed` |
217
+ | an SDK receipt reflects what the tool really did | anyone | agent's own process | none; the SDK shares a process with the agent | **by design not claimed**; issuer kind `sdk` says so |
218
+
219
+ If a vendor tells you their receipts prove more than the first five rows, ask them which key signed it.
220
+
221
+ ## Layout
222
+
223
+ ```
224
+ src/config.ts gateway and SDK config schemas, path resolution
225
+ src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
226
+ src/log.ts Merkle log: append, root, inclusion proof, verify, JSONL persistence
227
+ src/policy.ts Cedar evaluation wrapper, fail-closed
228
+ src/delegation.ts signed delegation grants
229
+ src/receipt.ts receipt statement types and provenance labels
230
+ src/issue.ts sign, log, and write a receipt; shared by both producers
231
+ src/gateway.ts the MCP proxy: scope check, facts, policy, forward, receipt
232
+ src/sdk/index.ts the interceptor: policy decision, record, wrap(tool fn)
233
+ src/sdk/claude.ts Claude Code command hook and Claude Agent SDK in-process hooks
234
+ src/sdk/openai-agents.ts, vercel-ai.ts, langchain.ts framework adapters, tested against the real packages
235
+ src/verify.ts offline verification and the human-readable report
236
+ src/cli.ts keygen, grant, gateway, hook, verify
237
+ src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
238
+ tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
239
+ scripts/ fake Stripe upstream, fixture builders for gateway and SDK, demo
240
+ examples/ twelve runnable tutorials, one per aspect; each is run by the test suite
241
+ test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
242
+ adapter tests against the real packages, and a test that runs every policy in docs/policies.md
243
+ docs/ tutorials, usage (gateway), sdk, policies, verification
244
+ ```
245
+
246
+ ## Plan
247
+
248
+ The design is two producers feeding one verifier. The SDK is the top of the funnel: cheap to install, wide reach, honest about being self-reported. The gateway is what a security or compliance owner mandates for consequential actions. Both exist; the work is widening each.
249
+
250
+ **Done**
251
+
252
+ - Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
253
+ - Receipt schema carries the issuer kind, so a verifier reads gateway versus SDK before anything else.
254
+ - SDK core: policy decision, record, and a generic `wrap(tool, fn)` for any framework whose tools are functions.
255
+ - Claude Code command hook for PreToolUse, PostToolUse, and PostToolUseFailure, with blocking on deny.
256
+ - Claude Agent SDK in-process hooks over the same handler.
257
+ - Framework adapters, each tested against the real package with a scripted model and no network: OpenAI Agents SDK (`wrapTools` enforces, `observeRunner` records from lifecycle events), Vercel AI SDK (`wrapTools` over a real `generateText` loop), LangChain (`ReceiptCallbackHandler` records, `issuer.wrap` enforces).
258
+
259
+ **Next, in the order it pays off**
260
+
261
+ 1. OpenTelemetry export: emit each receipt as a span with the receipt id and issuer kind as attributes, so existing collectors and dashboards carry them without a new pipeline.
262
+ 2. Embed upstream signed responses (Stripe webhook signatures, GitHub delivery signatures) so gateway execution can move from `observed` to `attested`.
263
+ 3. Consistency proofs between tree heads, so an auditor can check that a later log extends an earlier copy.
264
+ 4. An HTTP transport for the gateway, with the grant presented per connection, for a shared deployment rather than one process per agent session.
265
+ 5. Delegation chains for sub-agents.
266
+ 6. Receiver-attested receipts for agent-to-agent calls.
267
+ 7. A TEE-hosted signer, then SD-JWT redaction, then ZK proofs of policy compliance. Not before.
268
+
269
+ A Python SDK follows the same shape once the TypeScript adapters have settled.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
+ import { loadConfig, loadSdkConfig } from "./config.js";
5
+ import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
6
+ import { createDelegation } from "./delegation.js";
7
+ import { createGateway, serveStdio } from "./gateway.js";
8
+ import { createSdkIssuer } from "./sdk/index.js";
9
+ import { handleHookEvent } from "./sdk/claude.js";
10
+ import { formatReport, verifyBundle } from "./verify.js";
11
+ const USAGE = `agent-custody <command>
12
+
13
+ keygen --dir <dir> --name <name>
14
+ grant --key <principal.key> --principal <id> --agent <id> --scopes <a,b> [--ttl-hours 24] --out <file>
15
+ gateway --config <gateway.json>
16
+ hook [--config <sdk.json>] Claude Code hook command; reads the event on stdin (or AGENT_CUSTODY_CONFIG)
17
+ verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--log <log.jsonl>] [--json]
18
+ `;
19
+ async function main(argv) {
20
+ const [cmd, ...rest] = argv;
21
+ switch (cmd) {
22
+ case "keygen": {
23
+ const { values } = parseArgs({ args: rest, options: { dir: { type: "string" }, name: { type: "string" } } });
24
+ if (!values.dir || !values.name)
25
+ throw new Error("keygen needs --dir and --name");
26
+ const kp = generateKeyPair();
27
+ const files = writeKeyPair(kp, values.dir, values.name);
28
+ console.log(`keyid ${kp.keyid}\nprivate ${files.keyFile}\npublic ${files.pubFile}`);
29
+ return 0;
30
+ }
31
+ case "grant": {
32
+ const { values } = parseArgs({
33
+ args: rest,
34
+ options: {
35
+ key: { type: "string" },
36
+ principal: { type: "string" },
37
+ agent: { type: "string" },
38
+ scopes: { type: "string" },
39
+ "ttl-hours": { type: "string", default: "24" },
40
+ out: { type: "string" },
41
+ },
42
+ });
43
+ if (!values.key || !values.principal || !values.agent || !values.scopes || !values.out)
44
+ throw new Error("grant needs --key --principal --agent --scopes --out");
45
+ const now = Date.now();
46
+ const env = createDelegation(loadPrivateKey(values.key), {
47
+ version: "0.1",
48
+ principal: values.principal,
49
+ agent: values.agent,
50
+ scopes: values.scopes.split(",").map((s) => s.trim()).filter(Boolean),
51
+ issuedAt: new Date(now).toISOString(),
52
+ expiresAt: new Date(now + Number(values["ttl-hours"]) * 3600_000).toISOString(),
53
+ });
54
+ writeFileSync(values.out, JSON.stringify(env, null, 2));
55
+ console.log(`wrote ${values.out}`);
56
+ return 0;
57
+ }
58
+ case "gateway": {
59
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
60
+ if (!values.config)
61
+ throw new Error("gateway needs --config");
62
+ const gw = await createGateway(loadConfig(values.config));
63
+ console.error(`agent-custody gateway: agent=${gw.agentId} principal=${gw.delegation.principal} scopes=[${gw.delegation.scopes.join(", ")}]`);
64
+ await serveStdio(gw);
65
+ await gw.close();
66
+ return 0;
67
+ }
68
+ case "hook": {
69
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
70
+ const configPath = values.config ?? process.env.AGENT_CUSTODY_CONFIG;
71
+ if (!configPath)
72
+ throw new Error("hook needs --config or AGENT_CUSTODY_CONFIG");
73
+ const input = JSON.parse(readFileSync(0, "utf8"));
74
+ const out = handleHookEvent(createSdkIssuer(loadSdkConfig(configPath)), input);
75
+ console.log(JSON.stringify(out));
76
+ return 0;
77
+ }
78
+ case "verify": {
79
+ const { values, positionals } = parseArgs({
80
+ args: rest,
81
+ allowPositionals: true,
82
+ options: {
83
+ "issuer-key": { type: "string", multiple: true },
84
+ "gateway-key": { type: "string", multiple: true },
85
+ "principal-key": { type: "string", multiple: true },
86
+ log: { type: "string" },
87
+ json: { type: "boolean", default: false },
88
+ },
89
+ });
90
+ const file = positionals[0];
91
+ const issuerKeyFiles = [...(values["issuer-key"] ?? []), ...(values["gateway-key"] ?? [])];
92
+ if (!file || issuerKeyFiles.length === 0)
93
+ throw new Error("verify needs <bundle> --issuer-key (alias --gateway-key)");
94
+ const bundle = JSON.parse(readFileSync(file, "utf8"));
95
+ const result = verifyBundle(bundle, {
96
+ issuerKeys: issuerKeyFiles.map(loadPublicKey),
97
+ principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
98
+ ...(values.log ? { logFile: values.log } : {}),
99
+ });
100
+ console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
101
+ return result.ok ? 0 : 1;
102
+ }
103
+ default:
104
+ console.error(USAGE);
105
+ return cmd === undefined || cmd === "--help" || cmd === "-h" ? 0 : 2;
106
+ }
107
+ }
108
+ main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
109
+ console.error(`error: ${e instanceof Error ? e.message : e}`);
110
+ process.exit(1);
111
+ });
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ declare const FactSchema: z.ZodObject<{
3
+ name: z.ZodString;
4
+ tool: z.ZodString;
5
+ args: z.ZodRecord<z.ZodString, z.ZodString>;
6
+ forTools: z.ZodArray<z.ZodString>;
7
+ }, z.core.$strip>;
8
+ export declare const GatewayConfigSchema: z.ZodObject<{
9
+ identity: z.ZodObject<{
10
+ keyFile: z.ZodString;
11
+ }, z.core.$strip>;
12
+ upstream: z.ZodObject<{
13
+ command: z.ZodString;
14
+ args: z.ZodDefault<z.ZodArray<z.ZodString>>;
15
+ env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
16
+ }, z.core.$strip>;
17
+ grantFile: z.ZodString;
18
+ trustedPrincipalKeys: z.ZodArray<z.ZodString>;
19
+ policyFile: z.ZodString;
20
+ facts: z.ZodDefault<z.ZodArray<z.ZodObject<{
21
+ name: z.ZodString;
22
+ tool: z.ZodString;
23
+ args: z.ZodRecord<z.ZodString, z.ZodString>;
24
+ forTools: z.ZodArray<z.ZodString>;
25
+ }, z.core.$strip>>>;
26
+ receiptsDir: z.ZodString;
27
+ logFile: z.ZodString;
28
+ }, z.core.$strip>;
29
+ export type GatewayConfig = z.infer<typeof GatewayConfigSchema>;
30
+ export type FactConfig = z.infer<typeof FactSchema>;
31
+ /** Loads a config file and resolves every path relative to the file's directory. */
32
+ export declare function loadConfig(path: string): GatewayConfig;
33
+ export declare const SdkConfigSchema: z.ZodObject<{
34
+ agentId: z.ZodString;
35
+ principalId: z.ZodOptional<z.ZodString>;
36
+ identity: z.ZodObject<{
37
+ keyFile: z.ZodString;
38
+ }, z.core.$strip>;
39
+ policyFile: z.ZodOptional<z.ZodString>;
40
+ receiptsDir: z.ZodString;
41
+ logFile: z.ZodString;
42
+ framework: z.ZodOptional<z.ZodString>;
43
+ }, z.core.$strip>;
44
+ export type SdkConfig = z.infer<typeof SdkConfigSchema>;
45
+ export declare function loadSdkConfig(path: string): SdkConfig;
46
+ export {};