@agent-custody/receipts 0.6.13 → 0.6.15
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 +3 -1
- package/dist/cli.js +17 -2
- package/dist/index.d.ts +1 -1
- package/dist/portal.d.ts +22 -0
- package/dist/portal.js +199 -45
- package/dist/sdk/openclaw.d.ts +50 -0
- package/dist/sdk/openclaw.js +52 -0
- package/docs/sdk.md +29 -0
- package/docs/tutorials.md +1 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ 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, 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, 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
|
|
|
@@ -107,6 +107,8 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
|
|
|
107
107
|
| OpenAI Agents SDK (JS) | SDK | `wrapTools` | `observeRunner` | a real `Runner` with a scripted model |
|
|
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
|
+
| OpenClaw | SDK | `registerOpenClaw` / `openclawHooks`: `before_tool_call` deny | `after_tool_call` | OpenClaw's documented hook contract, in the plugin's process |
|
|
111
|
+
| 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 |
|
|
110
112
|
| anything else | SDK | `issuer.wrap(name, fn)` | `issuer.record` | plain functions |
|
|
111
113
|
| 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 |
|
|
112
114
|
| Go, Java, Rust, any language with HTTP | sidecar | decide then record | record | [examples/languages](examples/languages), each run against a live sidecar |
|
package/dist/cli.js
CHANGED
|
@@ -267,9 +267,24 @@ async function main(argv) {
|
|
|
267
267
|
return 0;
|
|
268
268
|
}
|
|
269
269
|
case "portal": {
|
|
270
|
-
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" }, "trust-proxy": { type: "boolean", default: false } } });
|
|
270
|
+
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
271
|
if (!values["db-env"] || !values["secret-env"] || !values["public-url"])
|
|
272
272
|
throw new Error("portal needs --db-env, --secret-env, and --public-url");
|
|
273
|
+
let oauth;
|
|
274
|
+
for (const p of ["github", "google"]) {
|
|
275
|
+
const id = values[`${p}-client-id`];
|
|
276
|
+
const env = values[`${p}-secret-env`];
|
|
277
|
+
if (!id && !env)
|
|
278
|
+
continue;
|
|
279
|
+
if (!id || !env)
|
|
280
|
+
throw new Error(`${p} sign-in needs both --${p}-client-id and --${p}-secret-env`);
|
|
281
|
+
const clientSecret = process.env[env];
|
|
282
|
+
if (!clientSecret)
|
|
283
|
+
throw new Error(`portal: environment variable ${env} is not set`);
|
|
284
|
+
if (!values["portal-url"])
|
|
285
|
+
throw new Error("provider sign-in needs --portal-url, the callback is built from it");
|
|
286
|
+
oauth = { ...(oauth ?? {}), [p]: { clientId: id, clientSecret } };
|
|
287
|
+
}
|
|
273
288
|
let mail;
|
|
274
289
|
if (values["mail-key-env"] || values["mail-from"]) {
|
|
275
290
|
if (!values["mail-key-env"] || !values["mail-from"])
|
|
@@ -301,7 +316,7 @@ async function main(argv) {
|
|
|
301
316
|
catch {
|
|
302
317
|
// the log may not be reachable from here at start; the sheet then omits the keyid
|
|
303
318
|
}
|
|
304
|
-
const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
|
|
319
|
+
const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), ...(oauth ? { oauth } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
|
|
305
320
|
console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
|
|
306
321
|
await new Promise((resolve) => process.once("SIGINT", resolve));
|
|
307
322
|
await running.close();
|
package/dist/index.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ 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
8
|
export { PortalStore, portalHandler, readSession, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
|
|
9
|
-
export type { MailOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
|
|
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";
|
|
12
12
|
export type { ExportOptions, ExportResult } from "./log-export.ts";
|
package/dist/portal.d.ts
CHANGED
|
@@ -18,6 +18,18 @@ export interface MailOptions {
|
|
|
18
18
|
url?: string;
|
|
19
19
|
fetch?: typeof fetch;
|
|
20
20
|
}
|
|
21
|
+
/** Sign in through GitHub or Google: the OAuth web flow over fetch, no library. The callback is `<portalUrl>auth/<provider>/callback`. */
|
|
22
|
+
export interface OAuthOptions {
|
|
23
|
+
github?: {
|
|
24
|
+
clientId: string;
|
|
25
|
+
clientSecret: string;
|
|
26
|
+
};
|
|
27
|
+
google?: {
|
|
28
|
+
clientId: string;
|
|
29
|
+
clientSecret: string;
|
|
30
|
+
};
|
|
31
|
+
fetch?: typeof fetch;
|
|
32
|
+
}
|
|
21
33
|
export interface PortalOptions {
|
|
22
34
|
tenancy: PostgresTenancy;
|
|
23
35
|
/** the Postgres client the tenancy uses; the portal's own tables live beside the log's */
|
|
@@ -33,6 +45,7 @@ export interface PortalOptions {
|
|
|
33
45
|
portalUrl?: string;
|
|
34
46
|
stripe?: StripeOptions;
|
|
35
47
|
mail?: MailOptions;
|
|
48
|
+
oauth?: OAuthOptions;
|
|
36
49
|
/** key throttles by X-Forwarded-For; only behind a proxy you run. Also marks cookies Secure. */
|
|
37
50
|
trustProxy?: boolean;
|
|
38
51
|
/** table prefix; default portal_ */
|
|
@@ -62,6 +75,15 @@ export declare class PortalStore {
|
|
|
62
75
|
static hashPassword(password: string): string;
|
|
63
76
|
static checkPassword(password: string, stored: string): boolean;
|
|
64
77
|
createUser(email: string, password: string, profile?: Profile): Promise<PortalUser>;
|
|
78
|
+
userByEmail(email: string): Promise<PortalUser | null>;
|
|
79
|
+
/** the account's profile, for the onboarding screen and the operator's note */
|
|
80
|
+
profile(userId: string): Promise<Profile>;
|
|
81
|
+
updateProfile(userId: string, profile: Profile): Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
|
|
84
|
+
* now on), else a new account with a random password nobody knows. The provider's email must be verified.
|
|
85
|
+
*/
|
|
86
|
+
findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
|
|
65
87
|
authenticate(email: string, password: string): Promise<PortalUser | null>;
|
|
66
88
|
user(id: string): Promise<PortalUser | null>;
|
|
67
89
|
addMember(userId: string, tenantId: string): Promise<void>;
|
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
|
+
// a provider identity linked to an account: GitHub or Google's stable subject, and the verified email it gave
|
|
43
|
+
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))`);
|
|
42
44
|
})();
|
|
43
45
|
}
|
|
44
46
|
return this.ready;
|
|
@@ -63,6 +65,42 @@ export class PortalStore {
|
|
|
63
65
|
throw new Error("an account with this email already exists");
|
|
64
66
|
return { id, email, createdAt: new Date(rows[0].created_at).toISOString() };
|
|
65
67
|
}
|
|
68
|
+
async userByEmail(email) {
|
|
69
|
+
await this.init();
|
|
70
|
+
const rows = (await this.client.query(`SELECT id, email, created_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
|
|
71
|
+
const r = rows[0];
|
|
72
|
+
return r ? { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString() } : null;
|
|
73
|
+
}
|
|
74
|
+
/** the account's profile, for the onboarding screen and the operator's note */
|
|
75
|
+
async profile(userId) {
|
|
76
|
+
await this.init();
|
|
77
|
+
const rows = (await this.client.query(`SELECT name, company, role, phone, telegram FROM ${this.p}users WHERE id = $1`, [userId])).rows;
|
|
78
|
+
const r = rows[0] ?? {};
|
|
79
|
+
const str = (v) => (v == null ? null : String(v));
|
|
80
|
+
return { name: str(r.name), company: str(r.company), role: str(r.role), phone: str(r.phone), telegram: str(r.telegram) };
|
|
81
|
+
}
|
|
82
|
+
async updateProfile(userId, profile) {
|
|
83
|
+
await this.init();
|
|
84
|
+
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]);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
|
|
88
|
+
* now on), else a new account with a random password nobody knows. The provider's email must be verified.
|
|
89
|
+
*/
|
|
90
|
+
async findOrCreateOAuthUser(provider, subject, email) {
|
|
91
|
+
await this.init();
|
|
92
|
+
const linked = (await this.client.query(`SELECT user_id FROM ${this.p}identities WHERE provider = $1 AND subject = $2`, [provider, subject])).rows;
|
|
93
|
+
if (linked[0]) {
|
|
94
|
+
const u = await this.user(linked[0].user_id);
|
|
95
|
+
if (u)
|
|
96
|
+
return u;
|
|
97
|
+
}
|
|
98
|
+
let user = await this.userByEmail(email);
|
|
99
|
+
if (!user)
|
|
100
|
+
user = await this.createUser(email, randomBytes(32).toString("hex"));
|
|
101
|
+
await this.client.query(`INSERT INTO ${this.p}identities (provider, subject, user_id, email) VALUES ($1, $2, $3, $4) ON CONFLICT (provider, subject) DO UPDATE SET user_id = EXCLUDED.user_id, email = EXCLUDED.email`, [provider, subject, user.id, email]);
|
|
102
|
+
return user;
|
|
103
|
+
}
|
|
66
104
|
async authenticate(email, password) {
|
|
67
105
|
await this.init();
|
|
68
106
|
const rows = (await this.client.query(`SELECT id, email, password_hash, created_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
|
|
@@ -247,7 +285,8 @@ export function portalHandler(o) {
|
|
|
247
285
|
}
|
|
248
286
|
if (req.method === "GET" && url.pathname === "/") {
|
|
249
287
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-frame-options": "DENY", "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'" });
|
|
250
|
-
|
|
288
|
+
const providers = JSON.stringify(["github", "google"].filter((p) => !!o.oauth?.[p]));
|
|
289
|
+
return void res.end(PORTAL_PAGE.replace("__LOG_BASE__", base.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c])).replace("__PROVIDERS__", providers));
|
|
251
290
|
}
|
|
252
291
|
// ---- Stripe's webhook: the only caller that is not a browser with a session ----
|
|
253
292
|
if (req.method === "POST" && url.pathname === "/stripe/webhook") {
|
|
@@ -279,47 +318,132 @@ export function portalHandler(o) {
|
|
|
279
318
|
}
|
|
280
319
|
return json(200, { received: true });
|
|
281
320
|
}
|
|
282
|
-
//
|
|
283
|
-
|
|
284
|
-
const b = await jsonBody();
|
|
285
|
-
const email = String(b.email ?? "").trim().toLowerCase();
|
|
286
|
-
const password = String(b.password ?? "");
|
|
321
|
+
// What the tenant setup needs, checked before anything is created: a mistyped form leaves nothing behind.
|
|
322
|
+
const parseOnboarding = async (b) => {
|
|
287
323
|
const tenant = String(b.tenant ?? "").trim().toLowerCase();
|
|
288
|
-
if (!EMAIL.test(email))
|
|
289
|
-
return json(400, { error: "a valid email address is needed" });
|
|
290
|
-
if (password.length < 10)
|
|
291
|
-
return json(400, { error: "the password needs at least ten characters" });
|
|
292
324
|
if (!TENANT_ID.test(tenant) || RESERVED.has(tenant))
|
|
293
|
-
return
|
|
325
|
+
return { status: 400, body: { error: "the tenant id is the name in your log's URL: three to forty lowercase letters, digits, or hyphens, and not a reserved word" } };
|
|
294
326
|
const text = (k, max) => String(b[k] ?? "").trim().slice(0, max);
|
|
295
327
|
const profile = { name: text("name", 120), company: text("company", 160), role: text("role", 120) || null, phone: text("phone", 40) || null, telegram: text("telegram", 40).replace(/^@/, "") || null };
|
|
296
328
|
if (!profile.name)
|
|
297
|
-
return
|
|
329
|
+
return { status: 400, body: { error: "your name is needed, so we know who to write to" } };
|
|
298
330
|
if (!profile.company)
|
|
299
|
-
return
|
|
331
|
+
return { status: 400, body: { error: "the company or organisation the tenant is for is needed" } };
|
|
300
332
|
if (profile.telegram && !/^[A-Za-z0-9_]{5,32}$/.test(profile.telegram))
|
|
301
|
-
return
|
|
333
|
+
return { status: 400, body: { error: "a Telegram username is five to thirty-two letters, digits, or underscores, with or without the @" } };
|
|
302
334
|
if (profile.phone && !/^[+0-9 ()./-]{6,40}$/.test(profile.phone))
|
|
303
|
-
return
|
|
335
|
+
return { status: 400, body: { error: "a phone number is digits, with an optional + and spaces" } };
|
|
304
336
|
if (await o.tenancy.tenant(tenant))
|
|
305
|
-
return
|
|
337
|
+
return { status: 409, body: { error: "that tenant id is taken" } };
|
|
338
|
+
return { tenant, profile };
|
|
339
|
+
};
|
|
340
|
+
const onboard = async (user, parsed) => {
|
|
341
|
+
const { tenant, profile } = parsed;
|
|
342
|
+
if (await store.tenantOf(user.id))
|
|
343
|
+
return { status: 409, body: { error: "this account already has a tenant" } };
|
|
344
|
+
await store.updateProfile(user.id, profile);
|
|
345
|
+
const t = await o.tenancy.addTenant(tenant, tenant, `portal:${user.email}`);
|
|
346
|
+
await store.addMember(user.id, tenant);
|
|
347
|
+
const minted = await o.tenancy.addToken(tenant, "first key", `portal:${user.email}`);
|
|
348
|
+
log(`agent-custody portal: ${user.email} registered tenant ${tenant}`);
|
|
349
|
+
void welcomeMail(user.email, profile.name, t.id, t.logId);
|
|
350
|
+
void notifyMail({ ...profile, email: user.email, tenant: t.id });
|
|
351
|
+
return { status: 200, body: { tenant: t.id, logId: t.logId, plan: t.plan, token: minted.token, tokenHash: minted.tokenHash.slice(0, 12), welcome: sheet(t.id, t.logId), setup: setupFor(t.id, t.logId), exportCommand: exportCommand(t.id) } };
|
|
352
|
+
};
|
|
353
|
+
if (req.method === "POST" && url.pathname === "/api/register") {
|
|
354
|
+
const b = await jsonBody();
|
|
355
|
+
const email = String(b.email ?? "").trim().toLowerCase();
|
|
356
|
+
const password = String(b.password ?? "");
|
|
357
|
+
if (!EMAIL.test(email))
|
|
358
|
+
return json(400, { error: "a valid email address is needed" });
|
|
359
|
+
if (password.length < 10)
|
|
360
|
+
return json(400, { error: "the password needs at least ten characters" });
|
|
361
|
+
const oneStep = "tenant" in b || "company" in b || "name" in b;
|
|
362
|
+
let parsed = null;
|
|
363
|
+
if (oneStep) {
|
|
364
|
+
const p = await parseOnboarding(b);
|
|
365
|
+
if ("status" in p)
|
|
366
|
+
return json(p.status, p.body);
|
|
367
|
+
parsed = p;
|
|
368
|
+
}
|
|
306
369
|
// throttled once the request is well formed: a mistyped form costs nothing, five real registrations from one address, then one every ten minutes
|
|
307
370
|
if (!registrations.take(`reg:${addr}`))
|
|
308
371
|
return json(429, { error: "too many registrations from this address; try again later" });
|
|
309
372
|
let user;
|
|
310
373
|
try {
|
|
311
|
-
user = await store.createUser(email, password
|
|
374
|
+
user = await store.createUser(email, password);
|
|
312
375
|
}
|
|
313
376
|
catch (e) {
|
|
314
377
|
return json(409, { error: e instanceof Error ? e.message : String(e) });
|
|
315
378
|
}
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
return json(
|
|
379
|
+
const cookie = { "set-cookie": setCookie(signSession(o.secret, user.id)) };
|
|
380
|
+
if (!parsed) {
|
|
381
|
+
log(`agent-custody portal: ${email} created an account`);
|
|
382
|
+
return json(200, { email, tenant: null }, cookie);
|
|
383
|
+
}
|
|
384
|
+
const r = await onboard(user, parsed);
|
|
385
|
+
return json(r.status, r.body, cookie);
|
|
386
|
+
}
|
|
387
|
+
// ---- sign in through a provider: the OAuth web flow, state in a short-lived signed cookie ----
|
|
388
|
+
const provider = /^\/auth\/(github|google)(\/callback)?$/.exec(url.pathname);
|
|
389
|
+
if (req.method === "GET" && provider && o.oauth?.[provider[1]]) {
|
|
390
|
+
const name = provider[1];
|
|
391
|
+
const conf = o.oauth[name];
|
|
392
|
+
const redirectUri = `${portalBase}auth/${name}/callback`;
|
|
393
|
+
const stateCookie = (value) => `custody_oauth=${value ?? ""}; Path=/auth; HttpOnly; SameSite=Lax${o.trustProxy ? "; Secure" : ""}; Max-Age=${value ? 600 : 0}`;
|
|
394
|
+
if (!provider[2]) {
|
|
395
|
+
const state = signSession(o.secret, `oauth:${name}:${randomBytes(16).toString("hex")}`, 600_000);
|
|
396
|
+
const authorize = name === "github"
|
|
397
|
+
? `https://github.com/login/oauth/authorize?${new URLSearchParams({ client_id: conf.clientId, redirect_uri: redirectUri, scope: "user:email", state })}`
|
|
398
|
+
: `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({ client_id: conf.clientId, redirect_uri: redirectUri, response_type: "code", scope: "openid email", state, prompt: "select_account" })}`;
|
|
399
|
+
res.writeHead(302, { location: authorize, "set-cookie": stateCookie(state), "cache-control": "no-store" });
|
|
400
|
+
return void res.end();
|
|
401
|
+
}
|
|
402
|
+
const state = url.searchParams.get("state") ?? "";
|
|
403
|
+
const code = url.searchParams.get("code") ?? "";
|
|
404
|
+
const expected = cookies.custody_oauth;
|
|
405
|
+
const stateUser = readSession(o.secret, state);
|
|
406
|
+
if (!code || !state || state !== expected || !stateUser?.startsWith(`oauth:${name}:`))
|
|
407
|
+
return json(400, { error: "the sign-in did not start here, or took too long; go back and try again" }, { "set-cookie": stateCookie(null) });
|
|
408
|
+
const f = o.oauth.fetch ?? fetch;
|
|
409
|
+
let subject = "";
|
|
410
|
+
let email = "";
|
|
411
|
+
try {
|
|
412
|
+
if (name === "github") {
|
|
413
|
+
const tok = (await (await f("https://github.com/login/oauth/access_token", { method: "POST", headers: { accept: "application/json", "content-type": "application/json" }, body: JSON.stringify({ client_id: conf.clientId, client_secret: conf.clientSecret, code, redirect_uri: redirectUri }), signal: AbortSignal.timeout(10_000) })).json());
|
|
414
|
+
if (!tok.access_token)
|
|
415
|
+
throw new Error(tok.error ?? "no access token");
|
|
416
|
+
const gh = { authorization: `Bearer ${tok.access_token}`, accept: "application/vnd.github+json", "user-agent": "agent-custody-portal" };
|
|
417
|
+
const me = (await (await f("https://api.github.com/user", { headers: gh, signal: AbortSignal.timeout(10_000) })).json());
|
|
418
|
+
const emails = (await (await f("https://api.github.com/user/emails", { headers: gh, signal: AbortSignal.timeout(10_000) })).json());
|
|
419
|
+
const primary = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified);
|
|
420
|
+
if (me.id === undefined || !primary)
|
|
421
|
+
throw new Error("GitHub gave no verified email; add one to your GitHub account or use email and password");
|
|
422
|
+
subject = String(me.id);
|
|
423
|
+
email = primary.email.toLowerCase();
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
const tok = (await (await f("https://oauth2.googleapis.com/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: conf.clientId, client_secret: conf.clientSecret, code, redirect_uri: redirectUri, grant_type: "authorization_code" }), signal: AbortSignal.timeout(10_000) })).json());
|
|
427
|
+
if (!tok.id_token)
|
|
428
|
+
throw new Error(tok.error ?? "no id token");
|
|
429
|
+
// the id token came straight from Google's token endpoint over TLS in this exchange, so its claims are read without a second signature check
|
|
430
|
+
const claims = JSON.parse(Buffer.from(tok.id_token.split(".")[1] ?? "", "base64url").toString());
|
|
431
|
+
if (!claims.sub || !claims.email || claims.email_verified !== true)
|
|
432
|
+
throw new Error("Google gave no verified email");
|
|
433
|
+
subject = claims.sub;
|
|
434
|
+
email = claims.email.toLowerCase();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
catch (e) {
|
|
438
|
+
log(`agent-custody portal: ${name} sign-in failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
439
|
+
return json(502, { error: `${name === "github" ? "GitHub" : "Google"} sign-in failed: ${e instanceof Error ? e.message : String(e)}` }, { "set-cookie": stateCookie(null) });
|
|
440
|
+
}
|
|
441
|
+
const user = await store.findOrCreateOAuthUser(name, subject, email);
|
|
442
|
+
log(`agent-custody portal: ${email} signed in with ${name}`);
|
|
443
|
+
// A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
|
|
444
|
+
// would not carry it. The page's own navigation to / does.
|
|
445
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "set-cookie": [setCookie(signSession(o.secret, user.id)), stateCookie(null)], "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" });
|
|
446
|
+
return void res.end(`<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/"><title>Signed in</title><p style="font:15px system-ui;padding:2rem">Signed in as ${email.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c])}. <a href="/">Continue</a>.</p>`);
|
|
323
447
|
}
|
|
324
448
|
if (req.method === "POST" && url.pathname === "/api/login") {
|
|
325
449
|
if (!loginFailures.take(`login:${addr}`))
|
|
@@ -338,14 +462,23 @@ export function portalHandler(o) {
|
|
|
338
462
|
const user = userId ? await store.user(userId) : null;
|
|
339
463
|
if (!user)
|
|
340
464
|
return json(401, { error: "sign in first" });
|
|
465
|
+
if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
|
|
466
|
+
return json(415, { error: "expected a JSON body" });
|
|
341
467
|
const tenantId = await store.tenantOf(user.id);
|
|
468
|
+
if (req.method === "GET" && url.pathname === "/api/me" && !tenantId)
|
|
469
|
+
return json(200, { email: user.email, tenant: null, profile: await store.profile(user.id), billing: !!o.stripe });
|
|
470
|
+
if (req.method === "POST" && url.pathname === "/api/onboard") {
|
|
471
|
+
const p = await parseOnboarding(await jsonBody());
|
|
472
|
+
if ("status" in p)
|
|
473
|
+
return json(p.status, p.body);
|
|
474
|
+
const r = await onboard(user, p);
|
|
475
|
+
return json(r.status, r.body);
|
|
476
|
+
}
|
|
342
477
|
if (!tenantId)
|
|
343
|
-
return json(409, { error: "this account has no tenant" });
|
|
478
|
+
return json(409, { error: "this account has no tenant yet; finish setting it up" });
|
|
344
479
|
const tenant = await o.tenancy.tenant(tenantId);
|
|
345
480
|
if (!tenant)
|
|
346
481
|
return json(409, { error: "the tenant no longer exists" });
|
|
347
|
-
if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
|
|
348
|
-
return json(415, { error: "expected a JSON body" });
|
|
349
482
|
if (req.method === "GET" && url.pathname === "/api/me") {
|
|
350
483
|
const q = await o.tenancy.quota(tenantId);
|
|
351
484
|
return json(200, { email: user.email, tenant: tenantId, logId: tenant.logId, plan: q.plan, used: q.used, quota: q.quota, disabled: !!tenant.disabledAt, billing: !!o.stripe });
|
|
@@ -509,6 +642,8 @@ const PORTAL_PAGE = `<!doctype html>
|
|
|
509
642
|
button.link { background: none; border: 0; padding: 0; color: var(--accent); text-decoration: underline; }
|
|
510
643
|
.auth { max-width: 26rem; margin: 4rem auto; }
|
|
511
644
|
.auth.wide { max-width: 44rem; }
|
|
645
|
+
.providers { display: grid; gap: .5rem; margin: 0 0 1rem; } .providers a { display: block; text-align: center; padding: .55rem .9rem; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); color: var(--ink); text-decoration: none; font-weight: 600; }
|
|
646
|
+
.providers a:hover { border-color: var(--accent); } .or { text-align: center; color: var(--ink2); font-size: .82rem; margin: 0 0 .8rem; }
|
|
512
647
|
.step { display: grid; grid-template-columns: 2rem 1fr; gap: .2rem .8rem; padding: 1rem 0; border-top: 1px solid var(--line); }
|
|
513
648
|
.step .n { font: 700 .85rem/1.6 var(--mono); color: var(--accent); }
|
|
514
649
|
.step h3 { margin: 0 0 .3rem; font-size: 1rem; } .step p { margin: 0 0 .5rem; color: var(--ink2); font-size: .92rem; }
|
|
@@ -525,25 +660,32 @@ const PORTAL_PAGE = `<!doctype html>
|
|
|
525
660
|
<div class="top"><a class="brand" href="https://agent-custody.dev/"><svg viewBox="0 0 64 64" aria-hidden="true"><rect width="64" height="64" rx="14"/><path d="M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z" fill="#fff"/><path d="M25 20h14M25 27h14" stroke="var(--accent)" stroke-width="2.6" stroke-linecap="round"/><path d="M25 37.5l5 4.5 9.5-10" fill="none" stroke="var(--accent)" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/></svg>agent-custody</a><span id="tenantTag" class="pill" hidden></span><span id="planTag" class="pill" hidden></span><span class="links"><a href="https://agent-custody.dev/guide/getting-started">Guide</a><a href="https://docs.agent-custody.dev/reference/">Docs</a><a href="https://agent-custody.dev/verify">Verify a receipt</a></span><span class="who" id="who"></span><button class="theme" id="themeToggle" type="button">Dark mode</button></div>
|
|
526
661
|
<section id="auth" class="auth" hidden>
|
|
527
662
|
<h1 id="authTitle">Sign in</h1>
|
|
663
|
+
<div id="providers" class="providers" hidden></div>
|
|
528
664
|
<form id="authForm">
|
|
529
|
-
<div id="regFields" hidden>
|
|
530
|
-
<label>Your name<input id="name" autocomplete="name" maxlength="120"></label>
|
|
531
|
-
<label>Company or organisation<input id="company" autocomplete="organization" maxlength="160"></label>
|
|
532
|
-
<label>Your role <span class="opt">optional</span><input id="role" autocomplete="organization-title" maxlength="120" placeholder="Head of Platform"></label>
|
|
533
|
-
</div>
|
|
534
665
|
<label>Work email<input id="email" type="email" autocomplete="email" required></label>
|
|
535
|
-
<div id="regFields2" hidden>
|
|
536
|
-
<label>Phone <span class="opt">optional</span><input id="phone" type="tel" autocomplete="tel" maxlength="40" placeholder="+44 20 …"></label>
|
|
537
|
-
<label>Telegram username <span class="opt">optional</span><input id="telegram" maxlength="40" placeholder="@yourname"><span class="hint">Your handle in Telegram, under Settings, if you would rather we reach you there than by email.</span></label>
|
|
538
|
-
</div>
|
|
539
666
|
<label>Password<input id="password" type="password" autocomplete="current-password" minlength="10" required></label>
|
|
540
|
-
<label id="tenantField" hidden>Tenant id<input id="tenant" placeholder="acme" pattern="[a-z0-9][a-z0-9-]{1,38}[a-z0-9]"><span class="hint">A short name for your organisation, filled in from the company name; change it if you like. It becomes the path of your log, which your gateway config and your auditors will use: <code id="tenantPreview">__LOG_BASE__t/<tenant>/</code></span></label>
|
|
541
667
|
<button id="authGo" type="submit">Sign in</button>
|
|
542
668
|
<p class="msg" id="authMsg"></p>
|
|
543
669
|
</form>
|
|
544
|
-
<p class="muted"
|
|
670
|
+
<p class="muted" id="authNote" hidden>Next you name your organisation and get your tenant and its first key. Two minutes.</p>
|
|
671
|
+
<p class="muted"><button class="link" id="authSwap" type="button">Create an account instead</button></p>
|
|
545
672
|
<p class="muted">The free plan is ten thousand appends a month, no card. Your gateway sends only hashes; nothing you log here can be read by us.</p>
|
|
546
673
|
</section>
|
|
674
|
+
<section id="onboard" class="auth" hidden>
|
|
675
|
+
<h1>Set up your tenant</h1>
|
|
676
|
+
<p class="muted">Signed in as <b id="onboardWho"></b>. A tenant is your own log on this service, with its own keys and its own path.</p>
|
|
677
|
+
<form id="onboardForm">
|
|
678
|
+
<label>Your name<input id="name" autocomplete="name" maxlength="120" required></label>
|
|
679
|
+
<label>Company or organisation<input id="company" autocomplete="organization" maxlength="160" required></label>
|
|
680
|
+
<label>Tenant id<input id="tenant" placeholder="acme" pattern="[a-z0-9][a-z0-9-]{1,38}[a-z0-9]" required><span class="hint">A short name for your organisation, filled in from the company name; change it if you like. It becomes the path of your log, which your gateway config and your auditors will use: <code id="tenantPreview">__LOG_BASE__t/<tenant>/</code></span></label>
|
|
681
|
+
<label>Your role <span class="opt">optional</span><input id="role" autocomplete="organization-title" maxlength="120" placeholder="Head of Platform"></label>
|
|
682
|
+
<label>Phone <span class="opt">optional</span><input id="phone" type="tel" autocomplete="tel" maxlength="40" placeholder="+44 20 …"></label>
|
|
683
|
+
<label>Telegram username <span class="opt">optional</span><input id="telegram" maxlength="40" placeholder="@yourname"><span class="hint">Your handle in Telegram, under Settings, if you would rather we reach you there than by email.</span></label>
|
|
684
|
+
<button type="submit">Create tenant</button>
|
|
685
|
+
<p class="msg" id="onboardMsg"></p>
|
|
686
|
+
</form>
|
|
687
|
+
<p class="muted"><a href="#" id="signoutOnboard">Sign out</a></p>
|
|
688
|
+
</section>
|
|
547
689
|
<section id="welcome" class="auth wide" hidden>
|
|
548
690
|
<h1>Your tenant is ready</h1>
|
|
549
691
|
<p class="muted">Three steps to your first receipt in this log. Everything here is under <b>Setup</b> in the dashboard whenever you need it again.</p>
|
|
@@ -632,7 +774,9 @@ const PORTAL_PAGE = `<!doctype html>
|
|
|
632
774
|
const fmt = (n) => Number(n).toLocaleString();
|
|
633
775
|
const ago = (iso) => { const m = Math.round((Date.now() - Date.parse(iso)) / 60000); return m < 60 ? m + " min ago" : m < 1440 ? Math.round(m / 60) + " h ago" : Math.round(m / 1440) + " d ago"; };
|
|
634
776
|
let registering = false;
|
|
635
|
-
const show = (id) => { for (const s of ["auth", "welcome", "app"]) $(s).hidden = s !== id; };
|
|
777
|
+
const show = (id) => { for (const s of ["auth", "onboard", "welcome", "app"]) $(s).hidden = s !== id; };
|
|
778
|
+
const PROVIDERS = __PROVIDERS__;
|
|
779
|
+
if (PROVIDERS.length) { $("providers").innerHTML = PROVIDERS.map((p) => "<a href='/auth/" + p + "'>Continue with " + (p === "github" ? "GitHub" : "Google") + "</a>").join("") + "<p class=or>or with email</p>"; $("providers").hidden = false; }
|
|
636
780
|
const view = (name) => {
|
|
637
781
|
for (const p of document.querySelectorAll("[data-pane]")) p.hidden = p.dataset.pane !== name;
|
|
638
782
|
for (const a of document.querySelectorAll("nav a[data-view]")) a.classList.toggle("on", a.dataset.view === name);
|
|
@@ -644,16 +788,22 @@ const PORTAL_PAGE = `<!doctype html>
|
|
|
644
788
|
const previewTenant = () => { $("tenantPreview").textContent = LOG_BASE + "t/" + ($("tenant").value || "<tenant>") + "/"; };
|
|
645
789
|
$("company").oninput = () => { if (!tenantEdited) { $("tenant").value = slug($("company").value); previewTenant(); } };
|
|
646
790
|
$("tenant").oninput = () => { tenantEdited = $("tenant").value !== ""; previewTenant(); };
|
|
647
|
-
$("authSwap").onclick = () => { registering = !registering; $("authTitle").textContent = registering ? "Create
|
|
791
|
+
$("authSwap").onclick = () => { registering = !registering; $("authTitle").textContent = registering ? "Create an account" : "Sign in"; $("authGo").textContent = registering ? "Create account" : "Sign in"; $("authNote").hidden = !registering; $("password").autocomplete = registering ? "new-password" : "current-password"; $("authSwap").textContent = registering ? "I already have an account" : "Create an account instead"; };
|
|
648
792
|
$("authForm").onsubmit = async (e) => {
|
|
649
793
|
e.preventDefault(); $("authMsg").className = "msg"; $("authMsg").textContent = "";
|
|
650
794
|
try {
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
$("firstToken").textContent = r.token; renderSetup($("firstSetup"), r.setup, true); show("welcome");
|
|
654
|
-
} else { await api("POST", "/api/login", { email: $("email").value, password: $("password").value }); await enter(); }
|
|
795
|
+
await api("POST", registering ? "/api/register" : "/api/login", { email: $("email").value, password: $("password").value });
|
|
796
|
+
await enter();
|
|
655
797
|
} catch (err) { $("authMsg").className = "msg err"; $("authMsg").textContent = err.message; }
|
|
656
798
|
};
|
|
799
|
+
$("onboardForm").onsubmit = async (e) => {
|
|
800
|
+
e.preventDefault(); $("onboardMsg").className = "msg"; $("onboardMsg").textContent = "";
|
|
801
|
+
try {
|
|
802
|
+
const r = await api("POST", "/api/onboard", { tenant: $("tenant").value, name: $("name").value, company: $("company").value, role: $("role").value, phone: $("phone").value, telegram: $("telegram").value });
|
|
803
|
+
$("firstToken").textContent = r.token; renderSetup($("firstSetup"), r.setup, true); show("welcome");
|
|
804
|
+
} catch (err) { $("onboardMsg").className = "msg err"; $("onboardMsg").textContent = err.message; }
|
|
805
|
+
};
|
|
806
|
+
$("signoutOnboard").onclick = async (e) => { e.preventDefault(); await api("POST", "/api/logout", {}); location.hash = ""; show("auth"); };
|
|
657
807
|
$("copyFirst").onclick = () => navigator.clipboard.writeText($("firstToken").textContent);
|
|
658
808
|
// Light or dark by choice, kept in this browser; unset, the page follows the system. The button says where it is going.
|
|
659
809
|
const themeNow = () => document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
|
|
@@ -703,7 +853,11 @@ const PORTAL_PAGE = `<!doctype html>
|
|
|
703
853
|
};
|
|
704
854
|
const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); };
|
|
705
855
|
const enter = async () => {
|
|
706
|
-
try {
|
|
856
|
+
try {
|
|
857
|
+
const me = await api("GET", "/api/me");
|
|
858
|
+
if (me.tenant === null) { $("onboardWho").textContent = me.email; if (me.profile) { for (const k of ["name", "company", "role", "phone", "telegram"]) if (me.profile[k]) $(k).value = me.profile[k]; } previewTenant(); show("onboard"); return; }
|
|
859
|
+
$("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview");
|
|
860
|
+
}
|
|
707
861
|
catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); } else { show("app"); $("who").textContent = err.message; } }
|
|
708
862
|
};
|
|
709
863
|
const sha256hex = async (text) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type SdkIssuer } from "./index.ts";
|
|
2
|
+
/** What OpenClaw passes as the hook context (PluginHookToolContext), the fields this adapter reads. */
|
|
3
|
+
export interface OpenClawToolContext {
|
|
4
|
+
agentId?: string;
|
|
5
|
+
sessionKey?: string;
|
|
6
|
+
sessionId?: string;
|
|
7
|
+
runId?: string;
|
|
8
|
+
toolName?: string;
|
|
9
|
+
toolCallId?: string;
|
|
10
|
+
[k: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
/** PluginHookBeforeToolCallEvent */
|
|
13
|
+
export interface OpenClawBeforeToolCallEvent {
|
|
14
|
+
toolName: string;
|
|
15
|
+
params: Record<string, unknown>;
|
|
16
|
+
runId?: string;
|
|
17
|
+
toolCallId?: string;
|
|
18
|
+
[k: string]: unknown;
|
|
19
|
+
}
|
|
20
|
+
/** PluginHookAfterToolCallEvent */
|
|
21
|
+
export interface OpenClawAfterToolCallEvent {
|
|
22
|
+
toolName: string;
|
|
23
|
+
params: Record<string, unknown>;
|
|
24
|
+
runId?: string;
|
|
25
|
+
toolCallId?: string;
|
|
26
|
+
result?: unknown;
|
|
27
|
+
error?: string;
|
|
28
|
+
durationMs?: number;
|
|
29
|
+
[k: string]: unknown;
|
|
30
|
+
}
|
|
31
|
+
/** The part of PluginHookBeforeToolCallResult this adapter produces. */
|
|
32
|
+
export interface OpenClawBeforeToolCallResult {
|
|
33
|
+
block: true;
|
|
34
|
+
blockReason: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The two handlers. `before_tool_call` evaluates the policy: on deny it issues a denial receipt and blocks with the
|
|
38
|
+
* reason and the receipt id, which OpenClaw shows the model as the tool's result; on allow, or with no policy, it
|
|
39
|
+
* returns nothing, so OpenClaw's own approvals and other plugins still apply. It never auto-approves. If the receipt
|
|
40
|
+
* cannot be issued (the log refused it) the call is blocked too: nothing runs without evidence. `after_tool_call`
|
|
41
|
+
* issues the receipt for the completed or failed call; a refused leaf is thrown, which OpenClaw logs.
|
|
42
|
+
*/
|
|
43
|
+
export declare function openclawHooks(issuer: SdkIssuer): {
|
|
44
|
+
before_tool_call: (event: OpenClawBeforeToolCallEvent, ctx?: OpenClawToolContext) => Promise<OpenClawBeforeToolCallResult | undefined>;
|
|
45
|
+
after_tool_call: (event: OpenClawAfterToolCallEvent, ctx?: OpenClawToolContext) => Promise<void>;
|
|
46
|
+
};
|
|
47
|
+
/** Registers both hooks on a plugin api (`api.on(name, handler)`), for a plugin's `register(api)`. */
|
|
48
|
+
export declare function registerOpenClaw(api: {
|
|
49
|
+
on: (name: string, handler: (event: any, ctx?: any) => unknown) => unknown;
|
|
50
|
+
}, issuer: SdkIssuer): void;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Adapter for OpenClaw plugin hooks. OpenClaw runs plugins in the agent's own process and offers two tool hooks:
|
|
2
|
+
// `before_tool_call`, which may block a call with a reason the model sees, and `after_tool_call`, which carries the
|
|
3
|
+
// result or the error. Both are awaited. This file mirrors OpenClaw's typed hook contract (src/plugins/hook-types.ts)
|
|
4
|
+
// loosely, on purpose, so it does not depend on the openclaw package; a plugin entry wires it with `api.on`.
|
|
5
|
+
//
|
|
6
|
+
// import { definePluginEntry } from "openclaw/plugin-sdk/plugin-sdk";
|
|
7
|
+
// import { createSdkIssuer, loadSdkConfig } from "@agent-custody/receipts";
|
|
8
|
+
// import { registerOpenClaw } from "@agent-custody/receipts/sdk/openclaw";
|
|
9
|
+
// export default definePluginEntry({ id: "agent-custody", name: "agent-custody", description: "A receipt for every tool call",
|
|
10
|
+
// register(api) { registerOpenClaw(api, createSdkIssuer(loadSdkConfig(process.env.AGENT_CUSTODY_CONFIG!))); } });
|
|
11
|
+
import { receiptIdOf } from "./index.js";
|
|
12
|
+
function toEvent(event, ctx) {
|
|
13
|
+
const raw = event.params;
|
|
14
|
+
const args = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : { input: raw ?? null };
|
|
15
|
+
return { tool: event.toolName, args, session: { id: ctx?.sessionId ?? ctx?.sessionKey ?? null, toolUseId: event.toolCallId ?? ctx?.toolCallId ?? null } };
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The two handlers. `before_tool_call` evaluates the policy: on deny it issues a denial receipt and blocks with the
|
|
19
|
+
* reason and the receipt id, which OpenClaw shows the model as the tool's result; on allow, or with no policy, it
|
|
20
|
+
* returns nothing, so OpenClaw's own approvals and other plugins still apply. It never auto-approves. If the receipt
|
|
21
|
+
* cannot be issued (the log refused it) the call is blocked too: nothing runs without evidence. `after_tool_call`
|
|
22
|
+
* issues the receipt for the completed or failed call; a refused leaf is thrown, which OpenClaw logs.
|
|
23
|
+
*/
|
|
24
|
+
export function openclawHooks(issuer) {
|
|
25
|
+
return {
|
|
26
|
+
before_tool_call: async (event, ctx) => {
|
|
27
|
+
const ev = toEvent(event, ctx);
|
|
28
|
+
const policy = issuer.decide(ev);
|
|
29
|
+
if (!policy || policy.decision !== "deny")
|
|
30
|
+
return undefined;
|
|
31
|
+
const reason = [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched";
|
|
32
|
+
try {
|
|
33
|
+
const bundle = await issuer.record(ev, { status: "denied", reason }, policy);
|
|
34
|
+
return { block: true, blockReason: `agent-custody: ${reason} (receipt ${receiptIdOf(bundle)})` };
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
return { block: true, blockReason: `agent-custody: ${reason}; the denial receipt could not be issued (${e instanceof Error ? e.message : String(e)})` };
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
after_tool_call: async (event, ctx) => {
|
|
41
|
+
const ev = toEvent(event, ctx);
|
|
42
|
+
const outcome = event.error !== undefined ? { status: "failed", result: event.error } : { status: "executed", result: event.result ?? null };
|
|
43
|
+
await issuer.record(ev, outcome, issuer.decide(ev));
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Registers both hooks on a plugin api (`api.on(name, handler)`), for a plugin's `register(api)`. */
|
|
48
|
+
export function registerOpenClaw(api, issuer) {
|
|
49
|
+
const hooks = openclawHooks(issuer);
|
|
50
|
+
api.on("before_tool_call", hooks.before_tool_call);
|
|
51
|
+
api.on("after_tool_call", hooks.after_tool_call);
|
|
52
|
+
}
|
package/docs/sdk.md
CHANGED
|
@@ -130,6 +130,35 @@ const refund = tool(issuer.wrap("stripe.refund", fn), { name: "stripe.refund", s
|
|
|
130
130
|
|
|
131
131
|
LangChain callbacks cannot block a tool, so the handler evaluates no policy; it records what happened, including the `tool_call_id` when one is present, and unwraps `ToolMessage` outputs. For enforcement wrap the function at construction. Do not do both on one tool or it will be recorded twice.
|
|
132
132
|
|
|
133
|
+
## OpenClaw
|
|
134
|
+
|
|
135
|
+
[src/sdk/openclaw.ts](../src/sdk/openclaw.ts). OpenClaw runs plugins in the agent's process and awaits two tool hooks: `before_tool_call`, which can block a call with a reason the model sees, and `after_tool_call`, which carries the result or the error. A plugin is three files: `package.json` with `"openclaw": { "extensions": ["./index.ts"] }`, `openclaw.plugin.json`, and the entry:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-sdk";
|
|
139
|
+
import { createSdkIssuer, loadSdkConfig } from "@agent-custody/receipts";
|
|
140
|
+
import { registerOpenClaw } from "@agent-custody/receipts/sdk/openclaw";
|
|
141
|
+
|
|
142
|
+
export default definePluginEntry({
|
|
143
|
+
id: "agent-custody",
|
|
144
|
+
name: "agent-custody",
|
|
145
|
+
description: "A signed receipt for every tool call; a policy can deny one before it runs",
|
|
146
|
+
register(api) {
|
|
147
|
+
registerOpenClaw(api, createSdkIssuer(loadSdkConfig(process.env.AGENT_CUSTODY_CONFIG ?? "./sdk.json")));
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
```json
|
|
153
|
+
{ "id": "agent-custody", "name": "agent-custody", "activation": { "onStartup": true }, "configSchema": { "type": "object", "additionalProperties": false } }
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
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.
|
|
157
|
+
|
|
158
|
+
## Hermes Agent
|
|
159
|
+
|
|
160
|
+
[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.
|
|
161
|
+
|
|
133
162
|
## Any other framework: wrap the function
|
|
134
163
|
|
|
135
164
|
Every agent framework ends up calling a function. Wrap it.
|
package/docs/tutorials.md
CHANGED
|
@@ -30,6 +30,7 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
|
|
|
30
30
|
| 18 | OpenTelemetry export | [18-opentelemetry.ts](../examples/18-opentelemetry.ts) | a stand-in OTLP collector, `otel` in the config, one span per receipt with the receipt id as trace id, the collector going away and the next receipt still issued | `src/otel.ts`, `src/issue.ts` |
|
|
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
|
+
| 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` |
|
|
33
34
|
|
|
34
35
|
## How policies are defined, in one paragraph
|
|
35
36
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-custody/receipts",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.15",
|
|
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",
|
|
@@ -41,6 +41,10 @@
|
|
|
41
41
|
"types": "./dist/sdk/langchain.d.ts",
|
|
42
42
|
"default": "./dist/sdk/langchain.js"
|
|
43
43
|
},
|
|
44
|
+
"./sdk/openclaw": {
|
|
45
|
+
"types": "./dist/sdk/openclaw.d.ts",
|
|
46
|
+
"default": "./dist/sdk/openclaw.js"
|
|
47
|
+
},
|
|
44
48
|
"./cli": {
|
|
45
49
|
"types": "./dist/cli.d.ts",
|
|
46
50
|
"default": "./dist/cli.js"
|