@agent-custody/receipts 0.6.16 → 0.6.18
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/README.md +4 -3
- package/dist/cli.js +15 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/portal.d.ts +50 -0
- package/dist/portal.js +83 -13
- package/dist/sdk/deepseek-harness.d.ts +69 -0
- package/dist/sdk/deepseek-harness.js +74 -0
- package/docs/sdk.md +17 -0
- package/docs/tutorials.md +1 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -5,14 +5,14 @@ Chain of custody for AI agents: a signed receipt for every tool call, checkable
|
|
|
5
5
|
Two producers, one receipt format, one verifier.
|
|
6
6
|
|
|
7
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, OpenClaw, Hermes, LangChain, or any function you wrap. It reaches everything the gateway cannot see and issues the same receipts, labelled as self-reported.
|
|
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, OpenClaw, DeepSeek Harness, Hermes, LangChain, or any function you wrap. It reaches everything the gateway cannot see and issues the same receipts, labelled as self-reported.
|
|
9
9
|
|
|
10
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
11
|
|
|
12
12
|
- [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
|
|
13
13
|
- [Tutorials](docs/tutorials.md): twenty runnable examples, one per aspect of the code, all executed by the test suite
|
|
14
14
|
- [Usage guide](docs/usage.md): gateway setup, wiring into Claude Desktop, Claude Code, or your own agent loop
|
|
15
|
-
- [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK, LangChain and
|
|
15
|
+
- [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK, LangChain, OpenClaw and DeepSeek Harness, a Hermes Agent plugin through the Python package, and wrapping tool functions in anything else
|
|
16
16
|
- [Writing policies](docs/policies.md): how a tool call becomes a Cedar request, with tested examples
|
|
17
17
|
- [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
|
|
18
18
|
- [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, the EU AI Act, and UK GDPR, with what none of them claims
|
|
@@ -47,7 +47,7 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
|
|
|
47
47
|
verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
-
Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw and Hermes, 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). The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
|
|
50
|
+
Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness and Hermes, 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). The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
|
|
51
51
|
|
|
52
52
|
## How it fits together
|
|
53
53
|
|
|
@@ -108,6 +108,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
|
|
|
108
108
|
| Vercel AI SDK | SDK | `wrapTools` | | a real `generateText` loop over the SDK's mock model |
|
|
109
109
|
| LangChain / LangGraph (JS) | SDK | `tool(issuer.wrap(fn))` | `ReceiptCallbackHandler` | real `StructuredTool` invocations |
|
|
110
110
|
| OpenClaw | SDK | `registerOpenClaw` / `openclawHooks`: `before_tool_call` deny | `after_tool_call` | OpenClaw's documented hook contract, in the plugin's process |
|
|
111
|
+
| DeepSeek Harness | SDK | the module is the plugin: `tools/pre-execute` deny | `tools/post-execute` | the harness's tool waterfall types, driven as the harness drives them |
|
|
111
112
|
| Hermes Agent | sidecar + [Python package](../python/README.md) | `agent_custody.hermes`: `pre_tool_call` block | `post_tool_call` | the documented hook contract, against a live sidecar |
|
|
112
113
|
| anything else | SDK | `issuer.wrap(name, fn)` | `issuer.record` | plain functions |
|
|
113
114
|
| Python: LangChain, OpenAI Agents SDK, CrewAI, Claude Agent SDK | sidecar + [Python package](../python/README.md) | `wrap_tools` (OpenAI Agents, CrewAI), `claude_hook` PreToolUse deny, `client.wrap` | `ReceiptCallbackHandler` | the real Python packages, receipts checked by this verifier |
|
package/dist/cli.js
CHANGED
|
@@ -14,7 +14,7 @@ import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.
|
|
|
14
14
|
import { fetchWitnessKeys, Witness } from "./witness.js";
|
|
15
15
|
import { checkLog, formatLogCheck } from "./log-check.js";
|
|
16
16
|
import { serveHttp } from "./gateway-http.js";
|
|
17
|
-
import { PortalStore, servePortal } from "./portal.js";
|
|
17
|
+
import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
|
|
18
18
|
import { exportLog, formatExport } from "./log-export.js";
|
|
19
19
|
import { CheckpointPublisher, fileResolver } from "./log-sink.js";
|
|
20
20
|
import { createRequire } from "node:module";
|
|
@@ -79,6 +79,8 @@ const USAGE = `agent-custody <command>
|
|
|
79
79
|
[--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]
|
|
80
80
|
the tenant portal: register, first key, usage against plan, keys, billing, export
|
|
81
81
|
log-admin --db-env NAME import --file <log.jsonl> [--tenant default] copies a file log into the database as hashes
|
|
82
|
+
portal-followup --db-env NAME --mail-key-env NAME --mail-from <address> [--mail-notify <address>] [--portal-url <url>] [--dry-run]
|
|
83
|
+
the founder's note to registrations an hour to a week old that have not had it; hourly from cron
|
|
82
84
|
audit --older <bundle.json> --newer <bundle.json> (--log <log.jsonl> | --log-url <url>) [--issuer-key <pub>] [--log-key <pub>] [--log-id <id>] [--witness-key <pub> | --witness-url <url>] [--json]
|
|
83
85
|
with --log-url the log's published keys are fetched and pinned by keyid; with a witness key or
|
|
84
86
|
URL the newer head must also carry the witness's countersignature
|
|
@@ -266,6 +268,18 @@ async function main(argv) {
|
|
|
266
268
|
await running.close();
|
|
267
269
|
return 0;
|
|
268
270
|
}
|
|
271
|
+
case "portal-followup": {
|
|
272
|
+
// The founder's note to every registration between an hour and a week old that has not had it; run hourly from cron.
|
|
273
|
+
const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "portal-url": { type: "string", default: "https://app.agent-custody.dev/" }, "dry-run": { type: "boolean", default: false } } });
|
|
274
|
+
if (!values["db-env"] || !values["mail-key-env"] || !values["mail-from"])
|
|
275
|
+
throw new Error("portal-followup needs --db-env, --mail-key-env, and --mail-from");
|
|
276
|
+
const apiKey = process.env[values["mail-key-env"]];
|
|
277
|
+
if (!apiKey)
|
|
278
|
+
throw new Error(`portal-followup: environment variable ${values["mail-key-env"]} is not set`);
|
|
279
|
+
const r = await sendFollowUps(new PortalStore(openPostgres(values["db-env"])), { apiKey, from: values["mail-from"], ...(values["mail-notify"] ? { notify: values["mail-notify"] } : {}) }, { portalUrl: values["portal-url"], dryRun: values["dry-run"] });
|
|
280
|
+
console.log(`${values["dry-run"] ? "would send" : "sent"} ${r.sent.length}, skipped ${r.skipped.length} (operator's own), failed ${r.failed.length}${r.sent.length ? `: ${r.sent.join(", ")}` : ""}`);
|
|
281
|
+
return r.failed.length ? 1 : 0;
|
|
282
|
+
}
|
|
269
283
|
case "portal": {
|
|
270
284
|
const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "github-client-id": { type: "string" }, "github-secret-env": { type: "string" }, "google-client-id": { type: "string" }, "google-secret-env": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
|
|
271
285
|
if (!values["db-env"] || !values["secret-env"] || !values["public-url"])
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export { buildRequest, restUpstream } from "./rest.ts";
|
|
|
5
5
|
export { openExporter, otlpExporter, spanFor } from "./otel.ts";
|
|
6
6
|
export { hecEvent, splunkExporter } from "./splunk.ts";
|
|
7
7
|
export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
|
|
8
|
-
export { PortalStore, portalHandler, readSession, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
|
|
8
|
+
export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
|
|
9
9
|
export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
|
|
10
10
|
export type { HttpGatewayOptions, RunningHttpGateway } from "./gateway-http.ts";
|
|
11
11
|
export { exportLog, formatExport } from "./log-export.ts";
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ export { buildRequest, restUpstream } from "./rest.js";
|
|
|
4
4
|
export { openExporter, otlpExporter, spanFor } from "./otel.js";
|
|
5
5
|
export { hecEvent, splunkExporter } from "./splunk.js";
|
|
6
6
|
export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
|
|
7
|
-
export { PortalStore, portalHandler, readSession, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.js";
|
|
7
|
+
export { deliverMail, founderNote, PortalStore, portalHandler, readSession, sendFollowUps, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.js";
|
|
8
8
|
export { exportLog, formatExport } from "./log-export.js";
|
|
9
9
|
export { fileBackend, importLogFile, PostgresLog, PostgresTenancy, RateLimiter } from "./log-store.js";
|
|
10
10
|
export { PLAN_QUOTAS, PLANS } from "./log-store.js";
|
package/dist/portal.d.ts
CHANGED
|
@@ -78,6 +78,20 @@ export declare class PortalStore {
|
|
|
78
78
|
userByEmail(email: string): Promise<PortalUser | null>;
|
|
79
79
|
/** the account's profile, for the onboarding screen and the operator's note */
|
|
80
80
|
profile(userId: string): Promise<Profile>;
|
|
81
|
+
/** Accounts with a tenant, a name, and no founder's note yet, registered inside the window: the hourly job's work list. */
|
|
82
|
+
pendingFollowUps(o: {
|
|
83
|
+
now: Date;
|
|
84
|
+
minAgeMs: number;
|
|
85
|
+
maxAgeMs: number;
|
|
86
|
+
}): Promise<{
|
|
87
|
+
id: string;
|
|
88
|
+
email: string;
|
|
89
|
+
name: string;
|
|
90
|
+
company: string | null;
|
|
91
|
+
tenantId: string;
|
|
92
|
+
createdAt: string;
|
|
93
|
+
}[]>;
|
|
94
|
+
markFollowedUp(userId: string, at?: Date): Promise<void>;
|
|
81
95
|
updateProfile(userId: string, profile: Profile): Promise<void>;
|
|
82
96
|
/**
|
|
83
97
|
* The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
|
|
@@ -117,6 +131,42 @@ export interface RunningPortal {
|
|
|
117
131
|
url: string;
|
|
118
132
|
close(): Promise<void>;
|
|
119
133
|
}
|
|
134
|
+
/** One message through the provider. Best effort: a refusal or a failure is reported through `log`, never thrown. Returns whether it was accepted. */
|
|
135
|
+
export declare function deliverMail(mail: MailOptions, m: {
|
|
136
|
+
to: string;
|
|
137
|
+
subject: string;
|
|
138
|
+
text: string;
|
|
139
|
+
}, log?: (message: string) => void): Promise<boolean>;
|
|
140
|
+
/**
|
|
141
|
+
* The founder's note, sent about an hour after a registration by `sendFollowUps`, once. Written to get the first
|
|
142
|
+
* receipt appended: it asks which stack they are on, offers to do the integration, and says to start in observe mode.
|
|
143
|
+
*/
|
|
144
|
+
export declare function founderNote(o: {
|
|
145
|
+
name: string;
|
|
146
|
+
tenant: string;
|
|
147
|
+
company: string | null;
|
|
148
|
+
portalUrl: string;
|
|
149
|
+
from: string;
|
|
150
|
+
}): {
|
|
151
|
+
subject: string;
|
|
152
|
+
text: string;
|
|
153
|
+
};
|
|
154
|
+
/**
|
|
155
|
+
* Sends the founder's note to every account registered between an hour and a week ago that has not had it, and
|
|
156
|
+
* marks each one. Accounts on the operator's own mail domains are marked without a message. Idempotent: run it hourly.
|
|
157
|
+
*/
|
|
158
|
+
export declare function sendFollowUps(store: PortalStore, mail: MailOptions, o?: {
|
|
159
|
+
portalUrl: string;
|
|
160
|
+
now?: Date;
|
|
161
|
+
minAgeMs?: number;
|
|
162
|
+
maxAgeMs?: number;
|
|
163
|
+
dryRun?: boolean;
|
|
164
|
+
log?: (message: string) => void;
|
|
165
|
+
}): Promise<{
|
|
166
|
+
sent: string[];
|
|
167
|
+
skipped: string[];
|
|
168
|
+
failed: string[];
|
|
169
|
+
}>;
|
|
120
170
|
export declare function portalHandler(o: PortalOptions): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
121
171
|
export declare function servePortal(o: PortalOptions, opts: {
|
|
122
172
|
port: number;
|
package/dist/portal.js
CHANGED
|
@@ -39,6 +39,8 @@ export class PortalStore {
|
|
|
39
39
|
// who the account belongs to: added after the first tenants registered, so the columns are optional
|
|
40
40
|
for (const c of PROFILE_COLUMNS)
|
|
41
41
|
await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS ${c} TEXT`);
|
|
42
|
+
// when the founder's note went out, so it goes once
|
|
43
|
+
await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS followed_up_at TIMESTAMPTZ`);
|
|
42
44
|
// a provider identity linked to an account: GitHub or Google's stable subject, and the verified email it gave
|
|
43
45
|
await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}identities (provider TEXT NOT NULL, subject TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES ${p}users(id), email TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (provider, subject))`);
|
|
44
46
|
})();
|
|
@@ -79,6 +81,17 @@ export class PortalStore {
|
|
|
79
81
|
const str = (v) => (v == null ? null : String(v));
|
|
80
82
|
return { name: str(r.name), company: str(r.company), role: str(r.role), phone: str(r.phone), telegram: str(r.telegram) };
|
|
81
83
|
}
|
|
84
|
+
/** Accounts with a tenant, a name, and no founder's note yet, registered inside the window: the hourly job's work list. */
|
|
85
|
+
async pendingFollowUps(o) {
|
|
86
|
+
await this.init();
|
|
87
|
+
const rows = (await this.client.query(`SELECT u.id, u.email, u.name, u.company, m.tenant_id, u.created_at FROM ${this.p}users u JOIN ${this.p}members m ON m.user_id = u.id
|
|
88
|
+
WHERE u.followed_up_at IS NULL AND u.name IS NOT NULL AND u.created_at <= $1 AND u.created_at >= $2 ORDER BY u.created_at`, [new Date(o.now.getTime() - o.minAgeMs).toISOString(), new Date(o.now.getTime() - o.maxAgeMs).toISOString()])).rows;
|
|
89
|
+
return rows.map((r) => ({ id: String(r.id), email: String(r.email), name: String(r.name), company: r.company == null ? null : String(r.company), tenantId: String(r.tenant_id), createdAt: new Date(r.created_at).toISOString() }));
|
|
90
|
+
}
|
|
91
|
+
async markFollowedUp(userId, at = new Date()) {
|
|
92
|
+
await this.init();
|
|
93
|
+
await this.client.query(`UPDATE ${this.p}users SET followed_up_at = $2 WHERE id = $1`, [userId, at.toISOString()]);
|
|
94
|
+
}
|
|
82
95
|
async updateProfile(userId, profile) {
|
|
83
96
|
await this.init();
|
|
84
97
|
await this.client.query(`UPDATE ${this.p}users SET name = $2, company = $3, role = $4, phone = $5, telegram = $6 WHERE id = $1`, [userId, profile.name ?? null, profile.company ?? null, profile.role ?? null, profile.phone ?? null, profile.telegram ?? null]);
|
|
@@ -202,6 +215,74 @@ export function verifyStripeSignature(header, rawBody, secret, now = Date.now(),
|
|
|
202
215
|
const TENANT_ID = /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
|
|
203
216
|
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
204
217
|
const RESERVED = new Set(["default", "admin", "api", "www", "log", "checkpoints", "app", "portal", "stripe", "health", "t"]);
|
|
218
|
+
/** One message through the provider. Best effort: a refusal or a failure is reported through `log`, never thrown. Returns whether it was accepted. */
|
|
219
|
+
export async function deliverMail(mail, m, log = console.error) {
|
|
220
|
+
const f = mail.fetch ?? fetch;
|
|
221
|
+
try {
|
|
222
|
+
const r = await f(mail.url ?? "https://api.resend.com/emails", { method: "POST", headers: { authorization: `Bearer ${mail.apiKey}`, "content-type": "application/json" }, body: JSON.stringify({ from: mail.from, to: [m.to], subject: m.subject, text: m.text }), signal: AbortSignal.timeout(10_000) });
|
|
223
|
+
if (r.ok)
|
|
224
|
+
return true;
|
|
225
|
+
log(`agent-custody portal: mail to ${m.to} refused: ${r.status} ${(await r.text()).slice(0, 200)}`);
|
|
226
|
+
}
|
|
227
|
+
catch (e) {
|
|
228
|
+
log(`agent-custody portal: mail to ${m.to} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
229
|
+
}
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* The founder's note, sent about an hour after a registration by `sendFollowUps`, once. Written to get the first
|
|
234
|
+
* receipt appended: it asks which stack they are on, offers to do the integration, and says to start in observe mode.
|
|
235
|
+
*/
|
|
236
|
+
export function founderNote(o) {
|
|
237
|
+
const first = o.name.trim().split(/\s+/)[0] || o.name;
|
|
238
|
+
const signer = o.from.replace(/^.*<|>.*$/g, "");
|
|
239
|
+
return {
|
|
240
|
+
subject: "Welcome to agent-custody, and one question",
|
|
241
|
+
text: [
|
|
242
|
+
`Hi ${first},`, "",
|
|
243
|
+
`Thanks for registering ${o.tenant} on agent-custody. I am Partha, the founder; you will get me, not a queue.`, "",
|
|
244
|
+
"One question so I can help rather than guess: which stack are your agents on, and what do they touch? Claude Code, the OpenAI Agents SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes, plain Python, or an MCP host. If you tell me, I will send the exact config for it, and if it is quicker, I will do the integration with you on a call: twenty minutes gets a first receipt into your log and verified in the browser.", "",
|
|
245
|
+
'Two things worth knowing from the start. Run it in observe mode first, "mode": "observe" in the config: nothing is blocked, and each receipt records what the policy would have denied, so you tune the policy against real traffic before turning it on. And the log only ever receives a hash per receipt; the receipts stay on your machines.', "",
|
|
246
|
+
`You are on the free plan, ten thousand appends a month, no card. If you hit that, tell me and I move you up while we talk. The setup sheet is under Setup in the dashboard whenever you need it: ${o.portalUrl}`, "",
|
|
247
|
+
`What are you building${o.company ? ` at ${o.company}` : ""}? I would like to know what you want the receipts to prove, and to whom.`, "",
|
|
248
|
+
"Partha", `agent-custody.dev · ${signer}`,
|
|
249
|
+
].join("\n"),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Sends the founder's note to every account registered between an hour and a week ago that has not had it, and
|
|
254
|
+
* marks each one. Accounts on the operator's own mail domains are marked without a message. Idempotent: run it hourly.
|
|
255
|
+
*/
|
|
256
|
+
export async function sendFollowUps(store, mail, o = { portalUrl: "https://app.agent-custody.dev/" }) {
|
|
257
|
+
const log = o.log ?? console.error;
|
|
258
|
+
const now = o.now ?? new Date();
|
|
259
|
+
const own = new Set([mail.from, mail.notify ?? ""].map((a) => a.replace(/^.*<|>.*$/g, "").split("@")[1]?.toLowerCase()).filter(Boolean));
|
|
260
|
+
const sent = [];
|
|
261
|
+
const skipped = [];
|
|
262
|
+
const failed = [];
|
|
263
|
+
for (const u of await store.pendingFollowUps({ now, minAgeMs: o.minAgeMs ?? 3_600_000, maxAgeMs: o.maxAgeMs ?? 7 * 86_400_000 })) {
|
|
264
|
+
if (own.has(u.email.split("@")[1]?.toLowerCase() ?? "")) {
|
|
265
|
+
if (!o.dryRun)
|
|
266
|
+
await store.markFollowedUp(u.id, now);
|
|
267
|
+
skipped.push(u.email);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const note = founderNote({ name: u.name, tenant: u.tenantId, company: u.company, portalUrl: o.portalUrl, from: mail.from });
|
|
271
|
+
if (o.dryRun) {
|
|
272
|
+
sent.push(u.email);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (await deliverMail(mail, { to: u.email, ...note }, log)) {
|
|
276
|
+
await store.markFollowedUp(u.id, now);
|
|
277
|
+
sent.push(u.email);
|
|
278
|
+
log(`agent-custody portal: founder's note sent to ${u.email} for tenant ${u.tenantId}`);
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
failed.push(u.email); // left pending; the next run tries again
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { sent, skipped, failed };
|
|
285
|
+
}
|
|
205
286
|
export function portalHandler(o) {
|
|
206
287
|
const store = new PortalStore(o.client, o.prefix);
|
|
207
288
|
const heads = postgresCheckpoints(o.client);
|
|
@@ -213,19 +294,8 @@ export function portalHandler(o) {
|
|
|
213
294
|
const sheet = (tenant, logId) => welcomeSheet({ tenant, logId, publicUrl: base, ...(o.checkpointsUrl ? { checkpointsUrl: o.checkpointsUrl } : {}), ...(o.keyid ? { keyid: o.keyid } : {}) });
|
|
214
295
|
const portalBase = (o.portalUrl ?? "http://localhost/").replace(/\/?$/, "/");
|
|
215
296
|
// Mail is best effort and off the request path: a provider outage is logged, never a failed registration.
|
|
216
|
-
const send = async (m) => {
|
|
217
|
-
|
|
218
|
-
return;
|
|
219
|
-
const f = o.mail.fetch ?? fetch;
|
|
220
|
-
try {
|
|
221
|
-
const r = await f(o.mail.url ?? "https://api.resend.com/emails", { method: "POST", headers: { authorization: `Bearer ${o.mail.apiKey}`, "content-type": "application/json" }, body: JSON.stringify({ from: o.mail.from, to: [m.to], subject: m.subject, text: m.text }), signal: AbortSignal.timeout(10_000) });
|
|
222
|
-
if (!r.ok)
|
|
223
|
-
log(`agent-custody portal: mail to ${m.to} refused: ${r.status} ${(await r.text()).slice(0, 200)}`);
|
|
224
|
-
}
|
|
225
|
-
catch (e) {
|
|
226
|
-
log(`agent-custody portal: mail to ${m.to} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
227
|
-
}
|
|
228
|
-
};
|
|
297
|
+
const send = async (m) => { if (o.mail)
|
|
298
|
+
await deliverMail(o.mail, m, log); };
|
|
229
299
|
const welcomeMail = (to, name, tenant, logId) => send({ to, subject: `Your agent-custody log "${tenant}" is ready`, text: [
|
|
230
300
|
`Hello ${name},`, "",
|
|
231
301
|
`Your tenant "${tenant}" is live on the hosted log. Your API key was shown once when you registered and is not in this email; if it is gone, mint another under API keys at ${portalBase}.`, "",
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type SdkIssuer } from "./index.ts";
|
|
3
|
+
/** The fields of the harness's ToolExecution this adapter reads. */
|
|
4
|
+
export interface DshToolExecution {
|
|
5
|
+
name: string;
|
|
6
|
+
arguments?: unknown;
|
|
7
|
+
callId?: string;
|
|
8
|
+
agent?: {
|
|
9
|
+
session?: {
|
|
10
|
+
header?: {
|
|
11
|
+
id?: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
} | undefined;
|
|
15
|
+
[k: string]: unknown;
|
|
16
|
+
}
|
|
17
|
+
/** ToolExecutionResult: success carries `content` blocks and a `value`; failure carries `error`. */
|
|
18
|
+
export interface DshToolExecutionResult {
|
|
19
|
+
isError: boolean;
|
|
20
|
+
content?: unknown[];
|
|
21
|
+
value?: unknown;
|
|
22
|
+
error?: unknown;
|
|
23
|
+
[k: string]: unknown;
|
|
24
|
+
}
|
|
25
|
+
export type DshPreToolDecision = {
|
|
26
|
+
kind: "allow";
|
|
27
|
+
} | {
|
|
28
|
+
kind: "deny";
|
|
29
|
+
reason: string;
|
|
30
|
+
} | {
|
|
31
|
+
kind: "cancel";
|
|
32
|
+
} | {
|
|
33
|
+
kind: "ask";
|
|
34
|
+
reason?: string;
|
|
35
|
+
};
|
|
36
|
+
export type DshPostToolDecision = {
|
|
37
|
+
kind: "accept";
|
|
38
|
+
[k: string]: unknown;
|
|
39
|
+
} | {
|
|
40
|
+
kind: "block";
|
|
41
|
+
feedback: unknown[];
|
|
42
|
+
[k: string]: unknown;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* The two handlers. `preExecute` evaluates the policy: on an enforced deny it issues the denial receipt and returns
|
|
46
|
+
* `{ kind: "deny" }` with the reason and the receipt id, which the model sees; otherwise it delegates with `next()`,
|
|
47
|
+
* so the harness's own approvals and other plugins still apply. It never returns `allow` itself. If the denial
|
|
48
|
+
* receipt cannot be issued the call is denied all the same. `postExecute` issues the receipt for the executed or
|
|
49
|
+
* failed call and delegates; a refused leaf is thrown, which the harness reports.
|
|
50
|
+
*/
|
|
51
|
+
export declare function deepseekHarnessHooks(issuer: SdkIssuer): {
|
|
52
|
+
preExecute: (exec: DshToolExecution, next: () => Promise<DshPreToolDecision>) => Promise<DshPreToolDecision>;
|
|
53
|
+
postExecute: (exec: DshToolExecution, result: DshToolExecutionResult, next: () => Promise<DshPostToolDecision>) => Promise<DshPostToolDecision>;
|
|
54
|
+
};
|
|
55
|
+
/** Registers both handlers on a Cordis context (`ctx.on(event, handler)`), for a plugin's `apply(ctx)`. */
|
|
56
|
+
export declare function registerDeepSeekHarness(ctx: {
|
|
57
|
+
on: (event: string, handler: (...args: any[]) => unknown) => unknown;
|
|
58
|
+
}, issuer: SdkIssuer): void;
|
|
59
|
+
export declare const name = "agent-custody";
|
|
60
|
+
/** the tool runtime must be up before the two events exist */
|
|
61
|
+
export declare const inject: string[];
|
|
62
|
+
/** Cordis validates the plugin's settings with this (zod implements Standard Schema): the SDK config file, else AGENT_CUSTODY_CONFIG. */
|
|
63
|
+
export declare const Config: z.ZodObject<{
|
|
64
|
+
config: z.ZodOptional<z.ZodString>;
|
|
65
|
+
}, z.core.$strip>;
|
|
66
|
+
export type Config = z.infer<typeof Config>;
|
|
67
|
+
export declare function apply(ctx: {
|
|
68
|
+
on: (event: string, handler: (...args: any[]) => unknown) => unknown;
|
|
69
|
+
}, config?: Config): void;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Adapter for DeepSeek Harness (dsh), where everything is a plugin. The harness runs two awaited waterfalls around
|
|
2
|
+
// every tool call: `tools/pre-execute`, whose handler returns `{ kind: "allow" }`, `{ kind: "deny", reason }` (the
|
|
3
|
+
// reason reaches the model), or delegates with `next()`; and `tools/post-execute`, which sees the result. This module
|
|
4
|
+
// is itself a harness plugin: it exports `name`, `inject`, `Config`, and `apply`, so it is listed by its package path
|
|
5
|
+
// with the SDK config as its only setting.
|
|
6
|
+
//
|
|
7
|
+
// # cordis.yml (an overlay; `dsh web --patch ./cordis.yml`), or the plugin list the dsh CLI manages
|
|
8
|
+
// - insert:
|
|
9
|
+
// - id: agent-custody
|
|
10
|
+
// name: "@agent-custody/receipts/sdk/deepseek-harness"
|
|
11
|
+
// config:
|
|
12
|
+
// config: /abs/path/sdk.json
|
|
13
|
+
//
|
|
14
|
+
// Typed loosely from the harness's `packages/core/tools/src/index.ts` on purpose, so this package does not depend on
|
|
15
|
+
// `@deepseek-ai/dsh-tools`; `deepseekHarnessHooks(issuer)` gives the two handlers for a plugin that registers them
|
|
16
|
+
// itself. The harness also ships `@deepseek-ai/dsh-hooks-claude-code`, which runs a Claude Code hooks.json: the
|
|
17
|
+
// `agent-custody hook` command works through it unchanged, one process per call. This plugin is the in-process path.
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
import { loadSdkConfig } from "../config.js";
|
|
20
|
+
import { createSdkIssuer, denies, receiptIdOf } from "./index.js";
|
|
21
|
+
function toEvent(exec) {
|
|
22
|
+
const raw = exec.arguments;
|
|
23
|
+
const args = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : { input: raw ?? null };
|
|
24
|
+
return { tool: exec.name, args, session: { id: exec.agent?.session?.header?.id ?? null, toolUseId: exec.callId ?? null } };
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The two handlers. `preExecute` evaluates the policy: on an enforced deny it issues the denial receipt and returns
|
|
28
|
+
* `{ kind: "deny" }` with the reason and the receipt id, which the model sees; otherwise it delegates with `next()`,
|
|
29
|
+
* so the harness's own approvals and other plugins still apply. It never returns `allow` itself. If the denial
|
|
30
|
+
* receipt cannot be issued the call is denied all the same. `postExecute` issues the receipt for the executed or
|
|
31
|
+
* failed call and delegates; a refused leaf is thrown, which the harness reports.
|
|
32
|
+
*/
|
|
33
|
+
export function deepseekHarnessHooks(issuer) {
|
|
34
|
+
return {
|
|
35
|
+
preExecute: async (exec, next) => {
|
|
36
|
+
const ev = toEvent(exec);
|
|
37
|
+
const policy = issuer.decide(ev);
|
|
38
|
+
if (!denies(policy))
|
|
39
|
+
return next();
|
|
40
|
+
const reason = [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched";
|
|
41
|
+
try {
|
|
42
|
+
const bundle = await issuer.record(ev, { status: "denied", reason }, policy);
|
|
43
|
+
return { kind: "deny", reason: `agent-custody: ${reason} (receipt ${receiptIdOf(bundle)})` };
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
return { kind: "deny", reason: `agent-custody: ${reason}; the denial receipt could not be issued (${e instanceof Error ? e.message : String(e)})` };
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
postExecute: async (exec, result, next) => {
|
|
50
|
+
const ev = toEvent(exec);
|
|
51
|
+
const outcome = result.isError ? { status: "failed", result: result.error ?? result.content ?? null } : { status: "executed", result: result.content ?? result.value ?? null };
|
|
52
|
+
await issuer.record(ev, outcome, issuer.decide(ev));
|
|
53
|
+
return next();
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Registers both handlers on a Cordis context (`ctx.on(event, handler)`), for a plugin's `apply(ctx)`. */
|
|
58
|
+
export function registerDeepSeekHarness(ctx, issuer) {
|
|
59
|
+
const hooks = deepseekHarnessHooks(issuer);
|
|
60
|
+
ctx.on("tools/pre-execute", hooks.preExecute);
|
|
61
|
+
ctx.on("tools/post-execute", hooks.postExecute);
|
|
62
|
+
}
|
|
63
|
+
// ---- the module as a plugin ----
|
|
64
|
+
export const name = "agent-custody";
|
|
65
|
+
/** the tool runtime must be up before the two events exist */
|
|
66
|
+
export const inject = ["tools"];
|
|
67
|
+
/** Cordis validates the plugin's settings with this (zod implements Standard Schema): the SDK config file, else AGENT_CUSTODY_CONFIG. */
|
|
68
|
+
export const Config = z.object({ config: z.string().optional() });
|
|
69
|
+
export function apply(ctx, config = {}) {
|
|
70
|
+
const path = config.config ?? process.env.AGENT_CUSTODY_CONFIG;
|
|
71
|
+
if (!path)
|
|
72
|
+
throw new Error("agent-custody: set `config` in the plugin's settings to the SDK config file, or AGENT_CUSTODY_CONFIG in the environment");
|
|
73
|
+
registerDeepSeekHarness(ctx, createSdkIssuer(loadSdkConfig(path)));
|
|
74
|
+
}
|
package/docs/sdk.md
CHANGED
|
@@ -157,6 +157,23 @@ export default definePluginEntry({
|
|
|
157
157
|
|
|
158
158
|
Then `openclaw plugins install --link ./agent-custody-plugin && openclaw plugins enable agent-custody`. `before_tool_call` evaluates the policy: on deny it issues a denial receipt and returns `{ block: true, blockReason: "agent-custody: … (receipt <id>)" }`; on allow, or with no policy, it returns nothing, so OpenClaw's own approvals and other plugins still apply. It never auto-approves, and if the denial receipt cannot be issued the call is blocked all the same. `after_tool_call` issues the receipt for the executed or failed call, with OpenClaw's `sessionId` and `toolCallId` as the receipt's session. `openclawHooks(issuer)` returns the two handlers for a plugin that registers them itself. Typed loosely on purpose, mirroring OpenClaw's `hook-types.ts`, so the package does not depend on `openclaw`; exercised against that contract in [example 21](../examples/21-openclaw.ts) and the test.
|
|
159
159
|
|
|
160
|
+
## DeepSeek Harness
|
|
161
|
+
|
|
162
|
+
[src/sdk/deepseek-harness.ts](../src/sdk/deepseek-harness.ts). DeepSeek Harness (dsh) is Node, everything in it is a plugin, and it runs two awaited waterfalls around every tool call: `tools/pre-execute`, whose handler returns `{ kind: "deny", reason }` (the reason reaches the model) or delegates with `next()`, and `tools/post-execute`, which sees the result. This module is a harness plugin itself: it exports `name`, `inject`, `Config`, and `apply`, so it is listed by its package path with the SDK config file as its one setting:
|
|
163
|
+
|
|
164
|
+
```yaml
|
|
165
|
+
# cordis.yml overlay (dsh web --patch ./cordis.yml), or the plugin list the dsh CLI manages
|
|
166
|
+
- insert:
|
|
167
|
+
- id: agent-custody
|
|
168
|
+
name: "@agent-custody/receipts/sdk/deepseek-harness"
|
|
169
|
+
config:
|
|
170
|
+
config: /abs/path/sdk.json
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`AGENT_CUSTODY_CONFIG` in the environment works instead of the setting. `tools/pre-execute` evaluates the policy: on an enforced deny it issues the denial receipt and denies with `agent-custody: … (receipt <id>)`; otherwise it delegates, so the harness's own approvals and other plugins still apply, and it never decides `allow` itself. `tools/post-execute` records the executed or failed call with the harness's session and call ids and delegates. `deepseekHarnessHooks(issuer)` returns the two handlers, `registerDeepSeekHarness(ctx, issuer)` registers them, for a plugin of your own. Typed loosely from the harness's `packages/core/tools/src/index.ts`, no dependency on `@deepseek-ai/dsh-tools`; driven with the harness's event shapes in [example 22](../examples/22-deepseek-harness.ts) and the test.
|
|
174
|
+
|
|
175
|
+
The harness also ships `@deepseek-ai/dsh-hooks-claude-code`, a bridge that runs a Claude Code `hooks.json` on the same seams. The [`agent-custody hook`](#claude-code) command works through it unchanged, one process per call; this plugin is the in-process path.
|
|
176
|
+
|
|
160
177
|
## Hermes Agent
|
|
161
178
|
|
|
162
179
|
[packages/python/agent_custody/hermes.py](../../python/agent_custody/hermes.py), through the sidecar like every Python adapter. Hermes runs Python plugins in the agent's process and fires `pre_tool_call(tool_name, args, task_id, **kwargs)`, which may return `{"action": "block", "message": …}`, and `post_tool_call(tool_name, args, result, task_id, duration_ms, **kwargs)`. The plugin is the directory [packages/python/hermes-plugin](../../python/hermes-plugin/): a `plugin.yaml` declaring both hooks and a `sidecar_url` setting, and an `__init__.py` that is one line, `from agent_custody.hermes import register`. Copy it to `~/.hermes/plugins/agent-custody/`, `pip install agent-custody`, start the sidecar, `hermes plugins enable agent-custody`. A denied call is blocked before it runs with the receipt id in the message; an allowed one gets no action, so Hermes's own guardrails and approvals still apply; every completed call is recorded with the Hermes `task_id` as the receipt's session. `hermes_hooks(client)` returns the two callables; `register_hermes(ctx, client)` registers them on a plugin context.
|
package/docs/tutorials.md
CHANGED
|
@@ -31,6 +31,7 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
|
|
|
31
31
|
| 19 | Splunk export | [19-splunk.ts](../examples/19-splunk.ts) | a stand-in HTTP Event Collector, `splunk` in the config with the token from the environment, one event per receipt with the receipt id and log position as fields, the collector going away and the next receipt still issued | `src/splunk.ts`, `src/otel.ts` |
|
|
32
32
|
| 20 | one gateway for many agents, over HTTP | [20-http-gateway.ts](../examples/20-http-gateway.ts) | a gateway host served over Streamable HTTP, two agents connecting with their own grants and seeing their own tools, receipts naming the right agent, a refusal by grant, and a stranger's grant getting no session | `src/gateway-http.ts`, `src/gateway.ts` |
|
|
33
33
|
| 21 | OpenClaw plugin hooks | [21-openclaw.ts](../examples/21-openclaw.ts) | the two hooks driven with OpenClaw's event shapes: an allowed call gets no result, a denied one is blocked with the receipt id, executed and failed calls are recorded, every receipt verifies | `src/sdk/openclaw.ts` |
|
|
34
|
+
| 22 | DeepSeek Harness plugin | [22-deepseek-harness.ts](../examples/22-deepseek-harness.ts) | the module as a plugin, applied by a stand-in context; pre-execute delegating an allowed call and denying one with the receipt id; post-execute recording executed and failed calls; every receipt verifying with the harness's session and call ids | `src/sdk/deepseek-harness.ts` |
|
|
34
35
|
|
|
35
36
|
## How policies are defined, in one paragraph
|
|
36
37
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-custody/receipts",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.18",
|
|
4
4
|
"mcpName": "io.github.svayatta/agent-custody",
|
|
5
5
|
"description": "Chain of custody for AI agents: signed, independently verifiable receipts for tool calls. MCP gateway + Cedar policy + Merkle transparency log",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -45,6 +45,10 @@
|
|
|
45
45
|
"types": "./dist/sdk/openclaw.d.ts",
|
|
46
46
|
"default": "./dist/sdk/openclaw.js"
|
|
47
47
|
},
|
|
48
|
+
"./sdk/deepseek-harness": {
|
|
49
|
+
"types": "./dist/sdk/deepseek-harness.d.ts",
|
|
50
|
+
"default": "./dist/sdk/deepseek-harness.js"
|
|
51
|
+
},
|
|
48
52
|
"./cli": {
|
|
49
53
|
"types": "./dist/cli.d.ts",
|
|
50
54
|
"default": "./dist/cli.js"
|