@agent-custody/receipts 0.6.17 → 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/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
- if (!o.mail)
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}.`, "",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.6.17",
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",