@hogsend/engine 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.34.0",
3
+ "version": "0.35.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,8 +28,10 @@
28
28
  "@hatchet-dev/typescript-sdk": "^1.22.3",
29
29
  "@hono/node-server": "^2.0.4",
30
30
  "@hono/zod-openapi": "^1.4.0",
31
+ "@openrouter/ai-sdk-provider": "^2.9.1",
31
32
  "@scalar/hono-api-reference": "^0.10.19",
32
33
  "@t3-oss/env-core": "^0.13.11",
34
+ "ai": "^6.0.209",
33
35
  "better-auth": "^1.6.11",
34
36
  "drizzle-orm": "^0.45.2",
35
37
  "hono": "^4.12.22",
@@ -40,14 +42,14 @@
40
42
  "svix": "^1.95.1",
41
43
  "winston": "^3.19.0",
42
44
  "zod": "^4.4.3",
43
- "@hogsend/core": "^0.34.0",
44
- "@hogsend/db": "^0.34.0",
45
- "@hogsend/email": "^0.34.0",
46
- "@hogsend/plugin-posthog": "^0.34.0",
47
- "@hogsend/plugin-resend": "^0.34.0"
45
+ "@hogsend/core": "^0.35.0",
46
+ "@hogsend/db": "^0.35.0",
47
+ "@hogsend/email": "^0.35.0",
48
+ "@hogsend/plugin-posthog": "^0.35.0",
49
+ "@hogsend/plugin-resend": "^0.35.0"
48
50
  },
49
51
  "optionalDependencies": {
50
- "@hogsend/plugin-postmark": "^0.34.0"
52
+ "@hogsend/plugin-postmark": "^0.35.0"
51
53
  },
52
54
  "devDependencies": {
53
55
  "@types/node": "^22.15.3",
package/src/env.ts CHANGED
@@ -236,6 +236,23 @@ export const env = createEnv({
236
236
  // path can never be turned off by misconfiguration. Set this to add the
237
237
  // segment/slack presets (credentials still live per-endpoint in `config`).
238
238
  ENABLED_DESTINATION_PRESETS: z.string().optional(),
239
+ // --- Studio co-working agent (GLM-5.2 via OpenRouter) ---
240
+ // The agent route (`/v1/admin/agent/*`) is FAIL-CLOSED on this key: with no
241
+ // OPENROUTER_API_KEY the `/config` probe reports `enabled:false` and `/chat`
242
+ // 503s, so the Studio panel renders a calm "agent not configured" state and
243
+ // never ships the key to the browser. Get one at openrouter.ai/keys.
244
+ OPENROUTER_API_KEY: z.string().min(1).optional(),
245
+ // The OpenRouter model id the agent runs on. Default is GLM-5.2 (z-ai), a
246
+ // 1M-context agentic-coding model well-suited to tool use; swap freely
247
+ // (e.g. z-ai/glm-4.6 as a battle-tested fallback) without code changes.
248
+ AGENT_MODEL: z.string().min(1).default("z-ai/glm-5.2"),
249
+ // Master switch. Enum (not z.coerce.boolean) so an explicit "false" disables.
250
+ // EFFECTIVE-enabled also requires OPENROUTER_API_KEY, so this defaults "true"
251
+ // yet stays zero-cost-off until a key is set.
252
+ AGENT_ENABLED: z.enum(["true", "false"]).default("true"),
253
+ // Hard cap on the agent's tool-use loop per chat turn (GLM-5.2 handles long
254
+ // multi-step loops; this bounds runaway cost). Read in routes/admin/agent.ts.
255
+ AGENT_MAX_STEPS: z.coerce.number().int().positive().default(24),
239
256
  },
240
257
  runtimeEnv: process.env,
241
258
  emptyStringAsUndefined: true,
package/src/index.ts CHANGED
@@ -204,6 +204,14 @@ export {
204
204
  getJourneyRegistrySingleton,
205
205
  setJourneyRegistry,
206
206
  } from "./journeys/registry-singleton.js";
207
+ // --- Studio co-working agent (HITL proposal chokepoint) ---
208
+ export {
209
+ InvalidProposalError,
210
+ mintProposal,
211
+ type ProposalPayload,
212
+ type VerifiedProposal,
213
+ verifyAndBurnProposal,
214
+ } from "./lib/agent/proposals.js";
207
215
  // --- Analytics provider registry (the analytics sibling) ---
208
216
  export {
209
217
  type IdentityMergeReason,
@@ -0,0 +1,19 @@
1
+ import type { HogsendClient } from "../../container.js";
2
+
3
+ /**
4
+ * Resolved availability of the Studio co-working agent. FAIL-CLOSED on the key:
5
+ * the route family is only "enabled" when the master switch is on AND an
6
+ * OpenRouter key is present, so the browser-facing `/config` probe reports
7
+ * `enabled:false` (and `/chat` 503s) until the operator sets the secret —
8
+ * the key itself never leaves the server.
9
+ */
10
+ export interface AgentConfig {
11
+ enabled: boolean;
12
+ model: string;
13
+ }
14
+
15
+ export function agentConfig(env: HogsendClient["env"]): AgentConfig {
16
+ const enabled =
17
+ env.AGENT_ENABLED === "true" && Boolean(env.OPENROUTER_API_KEY);
18
+ return { enabled, model: env.AGENT_MODEL };
19
+ }
@@ -0,0 +1,210 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createHash,
5
+ randomBytes,
6
+ randomUUID,
7
+ } from "node:crypto";
8
+ import { getRedis } from "../redis.js";
9
+ import { baseTier, type Tier } from "./risk.js";
10
+
11
+ /**
12
+ * HITL proposal token. A write tool mints one and returns it WITHOUT performing
13
+ * the side effect; the operator clicks confirm and POST /v1/admin/agent/confirm
14
+ * verifies+burns it and runs the real write — the ONLY place a write executes.
15
+ *
16
+ * ENCRYPTED (AES-256-GCM keyed off BETTER_AUTH_SECRET): the token rides in
17
+ * browser memory and the confirm POST; the GCM tag covers integrity so a
18
+ * tampered token fails decryption. The ARGS are NOT in the token — only
19
+ * `proposalId` is. The args are stored server-side in Redis keyed by that id, so
20
+ * (a) the token stays small, (b) args can't be swapped onto another tool's
21
+ * token, and (c) the single-use burn is one atomic Redis op on the id.
22
+ */
23
+ const TTL_SECONDS = 10 * 60; // 10-minute confirm window — Redis TTL === token exp
24
+ const IV_LENGTH = 12;
25
+ const TAG_LENGTH = 16;
26
+ const REDIS_PREFIX = "hogsend:agent:proposal:";
27
+
28
+ export interface ProposalPayload {
29
+ proposalId: string;
30
+ tool: string;
31
+ tier: Tier;
32
+ /** The operator who minted it. Confirm asserts this === the confirming actor. */
33
+ actorEmail: string;
34
+ /** Optional chat session id for correlation/audit. */
35
+ sessionId?: string;
36
+ exp: number;
37
+ }
38
+
39
+ /** The verified proposal the confirm route acts on: token claims + burned args. */
40
+ export interface VerifiedProposal extends ProposalPayload {
41
+ args: Record<string, unknown>;
42
+ }
43
+
44
+ export class InvalidProposalError extends Error {
45
+ /** `redis_unavailable` ⇒ retryable infra error (confirm route maps to 503);
46
+ * otherwise a terminal token problem (burned/expired/bad ⇒ 410). */
47
+ constructor(
48
+ message: string,
49
+ public readonly code?: "redis_unavailable",
50
+ ) {
51
+ super(message);
52
+ this.name = "InvalidProposalError";
53
+ }
54
+ }
55
+
56
+ function deriveKey(secret: string): Buffer {
57
+ return createHash("sha256").update(secret).digest();
58
+ }
59
+
60
+ function redisKey(proposalId: string): string {
61
+ return `${REDIS_PREFIX}${proposalId}`;
62
+ }
63
+
64
+ /**
65
+ * Mint a proposal: stash the args in Redis under a fresh id (SET NX EX, 10 min),
66
+ * then return an encrypted token carrying the id + tool + tier + actor. The
67
+ * caller (a write tool's execute) returns `{ status: "needs_confirmation", token,
68
+ * proposalId, ... }` and does NOT perform the side effect.
69
+ */
70
+ export async function mintProposal(opts: {
71
+ secret: string;
72
+ tool: string;
73
+ args: Record<string, unknown>;
74
+ tier?: Tier;
75
+ actorEmail: string;
76
+ sessionId?: string;
77
+ }): Promise<{ proposalId: string; token: string; expiresAt: string }> {
78
+ const proposalId = randomUUID();
79
+ const tier = opts.tier ?? baseTier(opts.tool);
80
+ const exp = Math.floor(Date.now() / 1000) + TTL_SECONDS;
81
+
82
+ // Store the args server-side, NX so a (cosmically unlikely) uuid collision can
83
+ // never overwrite a live proposal's args.
84
+ const redis = getRedis();
85
+ let ok: string | null;
86
+ try {
87
+ ok = await redis.set(
88
+ redisKey(proposalId),
89
+ JSON.stringify({ tool: opts.tool, args: opts.args }),
90
+ "EX",
91
+ TTL_SECONDS,
92
+ "NX",
93
+ );
94
+ } catch {
95
+ throw new InvalidProposalError("Redis unavailable", "redis_unavailable");
96
+ }
97
+ if (ok !== "OK") {
98
+ throw new InvalidProposalError("Failed to persist proposal args");
99
+ }
100
+
101
+ const payload: ProposalPayload = {
102
+ proposalId,
103
+ tool: opts.tool,
104
+ tier,
105
+ actorEmail: opts.actorEmail,
106
+ sessionId: opts.sessionId,
107
+ exp,
108
+ };
109
+
110
+ const iv = randomBytes(IV_LENGTH);
111
+ const cipher = createCipheriv("aes-256-gcm", deriveKey(opts.secret), iv);
112
+ const ciphertext = Buffer.concat([
113
+ cipher.update(JSON.stringify(payload), "utf-8"),
114
+ cipher.final(),
115
+ ]);
116
+ const token = Buffer.concat([iv, ciphertext, cipher.getAuthTag()]).toString(
117
+ "base64url",
118
+ );
119
+
120
+ return { proposalId, token, expiresAt: new Date(exp * 1000).toISOString() };
121
+ }
122
+
123
+ // Atomic single-use burn: read the args then delete in one round-trip. Returns
124
+ // the JSON string or nil — a second confirm finds nil (already burned/expired).
125
+ const BURN_LUA =
126
+ "local v = redis.call('GET', KEYS[1]); if v then redis.call('DEL', KEYS[1]) end; return v";
127
+
128
+ /**
129
+ * Verify a proposal token AND burn its args atomically (single-use). Throws
130
+ * {@link InvalidProposalError} on: malformed/tampered token (GCM failure),
131
+ * expired token, or a burned/expired Redis entry (replay). On success the args
132
+ * are gone from Redis — a second call with the same token throws "already used".
133
+ * Also asserts the burned args' `tool` matches the token's `tool` (defence in
134
+ * depth against a swapped id).
135
+ */
136
+ export async function verifyAndBurnProposal(opts: {
137
+ token: string;
138
+ secret: string;
139
+ }): Promise<VerifiedProposal> {
140
+ let raw: Buffer;
141
+ try {
142
+ raw = Buffer.from(opts.token, "base64url");
143
+ } catch {
144
+ throw new InvalidProposalError("Malformed proposal token");
145
+ }
146
+ if (raw.length <= IV_LENGTH + TAG_LENGTH) {
147
+ throw new InvalidProposalError("Malformed proposal token");
148
+ }
149
+
150
+ const iv = raw.subarray(0, IV_LENGTH);
151
+ const ciphertext = raw.subarray(IV_LENGTH, raw.length - TAG_LENGTH);
152
+ const tag = raw.subarray(raw.length - TAG_LENGTH);
153
+
154
+ let payload: ProposalPayload;
155
+ try {
156
+ const decipher = createDecipheriv(
157
+ "aes-256-gcm",
158
+ deriveKey(opts.secret),
159
+ iv,
160
+ );
161
+ decipher.setAuthTag(tag);
162
+ const plaintext = Buffer.concat([
163
+ decipher.update(ciphertext),
164
+ decipher.final(),
165
+ ]).toString("utf-8");
166
+ payload = JSON.parse(plaintext);
167
+ } catch {
168
+ throw new InvalidProposalError("Bad proposal token");
169
+ }
170
+
171
+ if (
172
+ typeof payload.proposalId !== "string" ||
173
+ typeof payload.tool !== "string" ||
174
+ typeof payload.actorEmail !== "string" ||
175
+ typeof payload.exp !== "number"
176
+ ) {
177
+ throw new InvalidProposalError("Invalid proposal payload");
178
+ }
179
+ if (payload.exp < Math.floor(Date.now() / 1000)) {
180
+ throw new InvalidProposalError("Proposal expired");
181
+ }
182
+
183
+ // Single-use burn. If Redis is unreachable this throws a retryable error →
184
+ // fail-closed (no write proceeds without a successful burn), but the confirm
185
+ // route can distinguish it (503) from a genuinely spent token (410).
186
+ const redis = getRedis();
187
+ let stored: string | null;
188
+ try {
189
+ stored = (await redis.eval(BURN_LUA, 1, redisKey(payload.proposalId))) as
190
+ | string
191
+ | null;
192
+ } catch {
193
+ throw new InvalidProposalError("Redis unavailable", "redis_unavailable");
194
+ }
195
+ if (!stored) {
196
+ throw new InvalidProposalError("Proposal already used or expired");
197
+ }
198
+
199
+ let parsed: { tool: string; args: Record<string, unknown> };
200
+ try {
201
+ parsed = JSON.parse(stored);
202
+ } catch {
203
+ throw new InvalidProposalError("Corrupt proposal args");
204
+ }
205
+ if (parsed.tool !== payload.tool) {
206
+ throw new InvalidProposalError("Proposal tool mismatch");
207
+ }
208
+
209
+ return { ...payload, args: parsed.args ?? {} };
210
+ }
@@ -0,0 +1,18 @@
1
+ import { createOpenRouter } from "@openrouter/ai-sdk-provider";
2
+ import type { LanguageModel } from "ai";
3
+ import type { HogsendClient } from "../../container.js";
4
+
5
+ /**
6
+ * The language model the agent runs on, built from env (OpenRouter + AGENT_MODEL,
7
+ * default GLM-5.2). Throws when the key is absent — callers gate on
8
+ * {@link agentConfig} first, so this only fires on a misconfiguration.
9
+ */
10
+ export function getAgentModel(env: HogsendClient["env"]): LanguageModel {
11
+ if (!env.OPENROUTER_API_KEY) {
12
+ throw new Error(
13
+ "OPENROUTER_API_KEY is not set — the agent is not configured",
14
+ );
15
+ }
16
+ const openrouter = createOpenRouter({ apiKey: env.OPENROUTER_API_KEY });
17
+ return openrouter(env.AGENT_MODEL);
18
+ }
@@ -0,0 +1,71 @@
1
+ import type { TestModeState } from "../domain-status.js";
2
+
3
+ /**
4
+ * The risk tier of an agent tool. Drives the confirm-card severity in Studio AND
5
+ * (advisory) the system prompt's per-tool caution. The HITL chokepoint is
6
+ * UNCONDITIONAL regardless of tier — tier is presentation/observability metadata,
7
+ * not the gate. `read` tools auto-run (no proposal); every non-`read` tier mints
8
+ * a proposal and is performed ONLY by POST /v1/admin/agent/confirm.
9
+ */
10
+ export type Tier = "read" | "write_safe" | "write_external" | "destructive";
11
+
12
+ /**
13
+ * Static per-tool tier registry. Unknown tool ⇒ treated as `destructive`
14
+ * (fail-closed: an unregistered write must get the loudest confirm). Keep this
15
+ * in sync with the tools in `buildAgentTools` — a new write tool missing here
16
+ * still works but gets the most cautious confirm. (If the tool set grows past
17
+ * ~15, fold the tier into each tool definition + a confirm-handler registry.)
18
+ */
19
+ const TIER_REGISTRY: Record<string, Tier> = {
20
+ // reads — auto-run
21
+ list_journeys: "read",
22
+ list_buckets: "read",
23
+ overview_stats: "read",
24
+ query_events: "read",
25
+ find_contacts: "read",
26
+ get_contact: "read",
27
+ get_contact_timeline: "read",
28
+ list_sends: "read",
29
+ build_audience: "read",
30
+ // writes — mint a proposal
31
+ upsert_contact: "write_safe",
32
+ update_contact: "write_safe",
33
+ subscribe_list: "write_safe",
34
+ unsubscribe_list: "write_safe",
35
+ enroll_in_journey: "write_external",
36
+ fire_event: "write_external",
37
+ send_transactional_email: "write_external",
38
+ send_campaign: "write_external",
39
+ delete_contact: "destructive",
40
+ };
41
+
42
+ export function baseTier(tool: string): Tier {
43
+ return TIER_REGISTRY[tool] ?? "destructive";
44
+ }
45
+
46
+ export function isReadTool(tool: string): boolean {
47
+ return baseTier(tool) === "read";
48
+ }
49
+
50
+ /**
51
+ * The tier AS IT APPLIES RIGHT NOW, given live test-mode. When test mode is
52
+ * active every send is redirected to the test inbox and never reaches a real
53
+ * recipient, so the two SEND tools relax from `write_external` to `write_safe`
54
+ * for the confirm-card severity. `fire_event` is NOT relaxed — firing an event
55
+ * still triggers journeys/buckets (an internal side effect test-mode doesn't
56
+ * mute). `destructive` is never relaxed. Computed off the SYNC cache
57
+ * (`domainStatus.testModeCached()`), so it never awaits.
58
+ */
59
+ export function effectiveTier(
60
+ tool: string,
61
+ opts: { testMode: TestModeState },
62
+ ): Tier {
63
+ const base = baseTier(tool);
64
+ if (
65
+ opts.testMode.active &&
66
+ (tool === "send_transactional_email" || tool === "send_campaign")
67
+ ) {
68
+ return "write_safe";
69
+ }
70
+ return base;
71
+ }
@@ -0,0 +1,30 @@
1
+ import type { HogsendClient } from "../../container.js";
2
+
3
+ /**
4
+ * The agent's system prompt, assembled per request from the live instance so it
5
+ * knows what journeys/buckets exist and that Hogsend is code-first. Phase 0 is
6
+ * read-only; the authoring + write guidance arrives with those tiers.
7
+ */
8
+ export async function buildAgentSystemPrompt(
9
+ container: HogsendClient,
10
+ ): Promise<string> {
11
+ const journeys = container.registry.getAll();
12
+ const buckets = container.bucketRegistry.getAll();
13
+
14
+ return [
15
+ "You are the Hogsend Studio co-working agent — an expert operator embedded in a self-hosted lifecycle-email instance (PostHog events in, Resend email out).",
16
+ "You help the operator understand and run this instance: investigate contacts and events, inspect journeys (email sequences) and buckets (real-time segments), and explain what is happening.",
17
+ "",
18
+ "How to work:",
19
+ "- Use the read tools to ground every answer in real data. Never invent ids, counts, or events — look them up.",
20
+ "- Be concise and concrete. Prefer a short answer plus the specific ids/numbers you found.",
21
+ "- Hogsend is CODE-FIRST: journeys, buckets, and email templates are TypeScript/React in the repo. You currently have READ-ONLY tools; you cannot yet change anything. If asked to create or modify, say so plainly and describe what you would do.",
22
+ "",
23
+ `This instance has ${journeys.length} journey(s): ${
24
+ journeys.map((j) => j.id).join(", ") || "(none)"
25
+ }.`,
26
+ `And ${buckets.length} bucket(s): ${
27
+ buckets.map((b) => b.id).join(", ") || "(none)"
28
+ }.`,
29
+ ].join("\n");
30
+ }
@@ -0,0 +1,465 @@
1
+ import { criteriaBuilder, days, evaluateCondition } from "@hogsend/core";
2
+ import {
3
+ contacts,
4
+ emailPreferences,
5
+ emailSends,
6
+ journeyStates,
7
+ userEvents,
8
+ } from "@hogsend/db";
9
+ import { tool } from "ai";
10
+ import { and, count, desc, eq, inArray, isNull } from "drizzle-orm";
11
+ import { z } from "zod";
12
+ import type { HogsendClient } from "../../container.js";
13
+ import {
14
+ contactKey,
15
+ contactSearchFilter,
16
+ resolveContact,
17
+ } from "../contacts.js";
18
+ import { mintProposal } from "./proposals.js";
19
+ import { effectiveTier } from "./risk.js";
20
+
21
+ /**
22
+ * The agent's tool set. READ tools auto-run (in-process against the container,
23
+ * the same query the corresponding admin route runs). WRITE tools are MINT-ONLY:
24
+ * their execute() builds a human summary, mints a single-use proposal token, and
25
+ * returns `{ status: "needs_confirmation", ... }` — they NEVER perform the side
26
+ * effect. The real write happens only in POST /v1/admin/agent/confirm.
27
+ */
28
+ export function buildAgentTools({
29
+ container,
30
+ actorEmail,
31
+ sessionId,
32
+ }: {
33
+ container: HogsendClient;
34
+ actorEmail: string;
35
+ sessionId?: string;
36
+ }) {
37
+ const { db, env, registry, bucketRegistry, domainStatus } = container;
38
+
39
+ /**
40
+ * Shared body for every write tool. NEVER performs the write. The recorded
41
+ * tier is the EFFECTIVE tier at mint time (test-mode-aware) so the confirm
42
+ * route can detect a test-mode change between propose and confirm. The args
43
+ * are stored server-side in Redis and deliberately NOT returned to the browser.
44
+ */
45
+ const mintWrite = async (
46
+ toolName: string,
47
+ args: Record<string, unknown>,
48
+ summary: string,
49
+ ) => {
50
+ const tier = effectiveTier(toolName, {
51
+ testMode: domainStatus.testModeCached(),
52
+ });
53
+ const { proposalId, token, expiresAt } = await mintProposal({
54
+ secret: env.BETTER_AUTH_SECRET,
55
+ tool: toolName,
56
+ args,
57
+ tier,
58
+ actorEmail,
59
+ sessionId,
60
+ });
61
+ return {
62
+ status: "needs_confirmation" as const,
63
+ proposalId,
64
+ token,
65
+ tool: toolName,
66
+ summary,
67
+ tier,
68
+ expiresAt,
69
+ };
70
+ };
71
+
72
+ return {
73
+ // ---- READ TOOLS (auto-run) ----------------------------------------------
74
+ list_journeys: tool({
75
+ description:
76
+ "List the journeys (lifecycle email sequences) registered in this Hogsend instance: id, name, whether enabled, and the event that triggers each.",
77
+ inputSchema: z.object({}),
78
+ execute: async () =>
79
+ registry.getAll().map((j) => ({
80
+ id: j.id,
81
+ name: j.name,
82
+ enabled: j.enabled,
83
+ trigger: j.trigger?.event,
84
+ })),
85
+ }),
86
+
87
+ list_buckets: tool({
88
+ description:
89
+ "List the buckets (real-time segments) registered in this instance: id and name.",
90
+ inputSchema: z.object({}),
91
+ execute: async () =>
92
+ bucketRegistry.getAll().map((b) => ({ id: b.id, name: b.name })),
93
+ }),
94
+
95
+ overview_stats: tool({
96
+ description:
97
+ "High-level instance stats: total (non-deleted) contacts and the count of active/waiting journey enrollments right now.",
98
+ inputSchema: z.object({}),
99
+ execute: async () => {
100
+ const [totalContacts, activeJourneyEnrollments] = await Promise.all([
101
+ db
102
+ .select({ c: count() })
103
+ .from(contacts)
104
+ .where(isNull(contacts.deletedAt))
105
+ .then((r) => r[0]?.c ?? 0),
106
+ db
107
+ .select({ c: count() })
108
+ .from(journeyStates)
109
+ .where(
110
+ and(
111
+ inArray(journeyStates.status, ["active", "waiting"]),
112
+ isNull(journeyStates.deletedAt),
113
+ ),
114
+ )
115
+ .then((r) => r[0]?.c ?? 0),
116
+ ]);
117
+ return { totalContacts, activeJourneyEnrollments };
118
+ },
119
+ }),
120
+
121
+ query_events: tool({
122
+ description:
123
+ "List recently ingested events, most recent first. Optionally filter by exact event name (e.g. 'checkout.completed'). Use this to investigate what users have done.",
124
+ inputSchema: z.object({
125
+ event: z.string().optional().describe("exact event name to filter by"),
126
+ limit: z.number().int().min(1).max(100).default(20),
127
+ }),
128
+ execute: async ({ event, limit }) => {
129
+ const where = event ? eq(userEvents.event, event) : undefined;
130
+ return db
131
+ .select({
132
+ event: userEvents.event,
133
+ userId: userEvents.userId,
134
+ source: userEvents.source,
135
+ occurredAt: userEvents.occurredAt,
136
+ })
137
+ .from(userEvents)
138
+ .where(where)
139
+ .orderBy(desc(userEvents.occurredAt))
140
+ .limit(limit);
141
+ },
142
+ }),
143
+
144
+ find_contacts: tool({
145
+ description:
146
+ "Search contacts by email / external id / anonymous id / discord id (substring match). Returns up to `limit` non-deleted contacts, most recently seen first.",
147
+ inputSchema: z.object({
148
+ search: z.string().min(1),
149
+ limit: z.number().int().min(1).max(50).default(10),
150
+ }),
151
+ execute: async ({ search, limit }) =>
152
+ db
153
+ .select({
154
+ id: contacts.id,
155
+ email: contacts.email,
156
+ externalId: contacts.externalId,
157
+ lastSeenAt: contacts.lastSeenAt,
158
+ })
159
+ .from(contacts)
160
+ .where(and(contactSearchFilter(search), isNull(contacts.deletedAt)))
161
+ .orderBy(desc(contacts.lastSeenAt))
162
+ .limit(limit),
163
+ }),
164
+
165
+ get_contact: tool({
166
+ description:
167
+ "Fetch a single contact (by uuid or external id) plus its email preferences.",
168
+ inputSchema: z.object({ id: z.string().min(1) }),
169
+ execute: async ({ id }) => {
170
+ const contact = await resolveContact({ db, id });
171
+ if (!contact) return { error: `No contact for "${id}"` };
172
+ const prefs = await db
173
+ .select()
174
+ .from(emailPreferences)
175
+ .where(eq(emailPreferences.userId, contact.externalId ?? contact.id))
176
+ .limit(1);
177
+ return { contact, preferences: prefs[0] ?? null };
178
+ },
179
+ }),
180
+
181
+ get_contact_timeline: tool({
182
+ description:
183
+ "A contact's recent activity: events and journey enrollments. Pass the contact uuid or external id.",
184
+ inputSchema: z.object({
185
+ id: z.string().min(1),
186
+ limit: z.number().int().min(1).max(50).default(20),
187
+ }),
188
+ execute: async ({ id, limit }) => {
189
+ const contact = await resolveContact({ db, id });
190
+ if (!contact) return { error: `No contact for "${id}"` };
191
+ const key = contactKey(contact);
192
+ const [events, journeys] = await Promise.all([
193
+ db
194
+ .select({
195
+ event: userEvents.event,
196
+ source: userEvents.source,
197
+ occurredAt: userEvents.occurredAt,
198
+ })
199
+ .from(userEvents)
200
+ .where(eq(userEvents.userId, key))
201
+ .orderBy(desc(userEvents.occurredAt))
202
+ .limit(limit),
203
+ db
204
+ .select({
205
+ journeyId: journeyStates.journeyId,
206
+ status: journeyStates.status,
207
+ createdAt: journeyStates.createdAt,
208
+ })
209
+ .from(journeyStates)
210
+ .where(
211
+ and(
212
+ eq(journeyStates.userId, key),
213
+ isNull(journeyStates.deletedAt),
214
+ ),
215
+ )
216
+ .orderBy(desc(journeyStates.createdAt))
217
+ .limit(limit),
218
+ ]);
219
+ return { contactKey: key, events, journeys };
220
+ },
221
+ }),
222
+
223
+ list_sends: tool({
224
+ description:
225
+ "List recent email sends, most recent first: template, recipient, status, and timestamps.",
226
+ inputSchema: z.object({
227
+ limit: z.number().int().min(1).max(50).default(20),
228
+ }),
229
+ execute: async ({ limit }) =>
230
+ db
231
+ .select({
232
+ id: emailSends.id,
233
+ templateKey: emailSends.templateKey,
234
+ to: emailSends.toEmail,
235
+ status: emailSends.status,
236
+ sentAt: emailSends.sentAt,
237
+ openedAt: emailSends.openedAt,
238
+ clickedAt: emailSends.clickedAt,
239
+ })
240
+ .from(emailSends)
241
+ .orderBy(desc(emailSends.createdAt))
242
+ .limit(limit),
243
+ }),
244
+
245
+ build_audience: tool({
246
+ description:
247
+ "Count contacts matching an ad-hoc criterion (a property comparison OR an event-occurred-within-window check). Returns the matched count and a sample of contact ids. Read-only — does NOT create a bucket or campaign. Scans up to 5000 contacts.",
248
+ inputSchema: z.object({
249
+ kind: z.enum(["property", "event"]),
250
+ property: z.string().optional(),
251
+ op: z
252
+ .enum(["eq", "neq", "gt", "gte", "lt", "lte", "contains", "exists"])
253
+ .optional(),
254
+ value: z.union([z.string(), z.number(), z.boolean()]).optional(),
255
+ event: z.string().optional(),
256
+ withinDays: z.number().int().min(1).max(365).optional(),
257
+ }),
258
+ execute: async (input) => {
259
+ const condition =
260
+ input.kind === "event"
261
+ ? criteriaBuilder
262
+ .event(input.event ?? "")
263
+ .within(days(input.withinDays ?? 7))
264
+ .exists()
265
+ : (() => {
266
+ const m = criteriaBuilder.prop(input.property ?? "");
267
+ switch (input.op) {
268
+ case "exists":
269
+ return m.exists();
270
+ case "neq":
271
+ return m.neq(input.value ?? "");
272
+ case "gt":
273
+ return m.gt(Number(input.value));
274
+ case "gte":
275
+ return m.gte(Number(input.value));
276
+ case "lt":
277
+ return m.lt(Number(input.value));
278
+ case "lte":
279
+ return m.lte(Number(input.value));
280
+ case "contains":
281
+ return m.contains(input.value ?? "");
282
+ default:
283
+ return m.eq(input.value ?? "");
284
+ }
285
+ })();
286
+
287
+ const all = await db
288
+ .select()
289
+ .from(contacts)
290
+ .where(isNull(contacts.deletedAt))
291
+ .limit(5000);
292
+ const matched: string[] = [];
293
+ for (const c of all) {
294
+ const ok = await evaluateCondition({
295
+ condition,
296
+ ctx: {
297
+ db,
298
+ userId: contactKey(c),
299
+ journeyContext: (c.properties ?? {}) as Record<string, unknown>,
300
+ },
301
+ });
302
+ if (ok) matched.push(c.id);
303
+ }
304
+ return {
305
+ count: matched.length,
306
+ sample: matched.slice(0, 10),
307
+ capped: all.length === 5000,
308
+ };
309
+ },
310
+ }),
311
+
312
+ // ---- WRITE TOOLS (mint-only — NO side effect here) -----------------------
313
+ fire_event: tool({
314
+ description:
315
+ "Fire an event for a contact through the full ingest pipeline (triggers journeys/buckets). REQUIRES operator confirmation — returns a proposal, does not fire.",
316
+ inputSchema: z.object({
317
+ event: z.string().min(1),
318
+ userId: z.string().optional(),
319
+ userEmail: z.string().email().optional(),
320
+ eventProperties: z.record(z.string(), z.unknown()).default({}),
321
+ }),
322
+ execute: async (args) =>
323
+ mintWrite(
324
+ "fire_event",
325
+ args,
326
+ `Fire event "${args.event}" for ${args.userEmail ?? args.userId ?? "(no recipient)"}`,
327
+ ),
328
+ }),
329
+
330
+ send_transactional_email: tool({
331
+ description:
332
+ "Send one transactional email from a registered template to one recipient. REQUIRES confirmation — returns a proposal, does not send.",
333
+ inputSchema: z.object({
334
+ template: z.string().min(1),
335
+ to: z.string().email(),
336
+ props: z.record(z.string(), z.unknown()).default({}),
337
+ subject: z.string().optional(),
338
+ userId: z.string().optional(),
339
+ }),
340
+ execute: async (args) =>
341
+ mintWrite(
342
+ "send_transactional_email",
343
+ args,
344
+ `Send "${args.template}" to ${args.to}`,
345
+ ),
346
+ }),
347
+
348
+ send_campaign: tool({
349
+ description:
350
+ "Broadcast a template to every subscribed member of a list OR every active member of a bucket. REQUIRES confirmation — returns a proposal, does not send.",
351
+ inputSchema: z
352
+ .object({
353
+ name: z.string().optional(),
354
+ list: z.string().optional(),
355
+ bucket: z.string().optional(),
356
+ template: z.string().min(1),
357
+ props: z.record(z.string(), z.unknown()).default({}),
358
+ subject: z.string().optional(),
359
+ from: z.string().optional(),
360
+ })
361
+ .refine((b) => (b.list ? 1 : 0) + (b.bucket ? 1 : 0) === 1, {
362
+ message: "Exactly one of `list` or `bucket` is required",
363
+ }),
364
+ execute: async (args) =>
365
+ mintWrite(
366
+ "send_campaign",
367
+ args,
368
+ `Broadcast "${args.template}" to ${args.list ? `list ${args.list}` : `bucket ${args.bucket}`}`,
369
+ ),
370
+ }),
371
+
372
+ enroll_in_journey: tool({
373
+ description:
374
+ "Manually enroll a contact in a journey by firing its trigger event. REQUIRES confirmation.",
375
+ inputSchema: z.object({
376
+ journeyId: z.string().min(1),
377
+ userId: z.string().optional(),
378
+ userEmail: z.string().email().optional(),
379
+ properties: z.record(z.string(), z.unknown()).default({}),
380
+ }),
381
+ execute: async (args) =>
382
+ mintWrite(
383
+ "enroll_in_journey",
384
+ args,
385
+ `Enroll ${args.userEmail ?? args.userId ?? "(no recipient)"} in journey ${args.journeyId}`,
386
+ ),
387
+ }),
388
+
389
+ subscribe_list: tool({
390
+ description:
391
+ "Subscribe a contact to an email list (opt-in). REQUIRES confirmation.",
392
+ inputSchema: z.object({
393
+ list: z.string().min(1),
394
+ userId: z.string().optional(),
395
+ email: z.string().email().optional(),
396
+ }),
397
+ execute: async (args) =>
398
+ mintWrite(
399
+ "subscribe_list",
400
+ args,
401
+ `Subscribe ${args.email ?? args.userId} to list ${args.list}`,
402
+ ),
403
+ }),
404
+
405
+ unsubscribe_list: tool({
406
+ description:
407
+ "Unsubscribe a contact from an email list (opt-out). REQUIRES confirmation.",
408
+ inputSchema: z.object({
409
+ list: z.string().min(1),
410
+ userId: z.string().optional(),
411
+ email: z.string().email().optional(),
412
+ }),
413
+ execute: async (args) =>
414
+ mintWrite(
415
+ "unsubscribe_list",
416
+ args,
417
+ `Unsubscribe ${args.email ?? args.userId} from list ${args.list}`,
418
+ ),
419
+ }),
420
+
421
+ upsert_contact: tool({
422
+ description:
423
+ "Create or update a contact by email / external id, optionally setting properties. REQUIRES confirmation.",
424
+ inputSchema: z.object({
425
+ userId: z.string().optional(),
426
+ email: z.string().email().optional(),
427
+ anonymousId: z.string().optional(),
428
+ properties: z.record(z.string(), z.unknown()).default({}),
429
+ }),
430
+ execute: async (args) =>
431
+ mintWrite(
432
+ "upsert_contact",
433
+ args,
434
+ `Upsert contact ${args.email ?? args.userId ?? args.anonymousId}`,
435
+ ),
436
+ }),
437
+
438
+ update_contact: tool({
439
+ description:
440
+ "Update an existing contact's email and/or properties (by uuid or external id). REQUIRES confirmation.",
441
+ inputSchema: z.object({
442
+ id: z.string().min(1),
443
+ email: z.string().email().optional(),
444
+ properties: z.record(z.string(), z.unknown()).default({}),
445
+ }),
446
+ execute: async (args) =>
447
+ mintWrite("update_contact", args, `Update contact ${args.id}`),
448
+ }),
449
+
450
+ delete_contact: tool({
451
+ description:
452
+ "Soft-delete a contact (sets deletedAt). DESTRUCTIVE — requires confirmation.",
453
+ inputSchema: z.object({
454
+ email: z.string().email().optional(),
455
+ userId: z.string().optional(),
456
+ }),
457
+ execute: async (args) =>
458
+ mintWrite(
459
+ "delete_contact",
460
+ args,
461
+ `Delete contact ${args.email ?? args.userId}`,
462
+ ),
463
+ }),
464
+ };
465
+ }
@@ -0,0 +1,402 @@
1
+ import { createHash } from "node:crypto";
2
+ import { auditLogs, campaigns } from "@hogsend/db";
3
+ import { getTemplateNames } from "@hogsend/email";
4
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
5
+ import {
6
+ convertToModelMessages,
7
+ stepCountIs,
8
+ streamText,
9
+ type UIMessage,
10
+ } from "ai";
11
+ import { eq } from "drizzle-orm";
12
+ import type { AppEnv } from "../../app.js";
13
+ import { agentConfig } from "../../lib/agent/config.js";
14
+ import {
15
+ InvalidProposalError,
16
+ type VerifiedProposal,
17
+ verifyAndBurnProposal,
18
+ } from "../../lib/agent/proposals.js";
19
+ import { getAgentModel } from "../../lib/agent/provider.js";
20
+ import { effectiveTier } from "../../lib/agent/risk.js";
21
+ import { buildAgentSystemPrompt } from "../../lib/agent/system-prompt.js";
22
+ import { buildAgentTools } from "../../lib/agent/tools.js";
23
+ import {
24
+ resolveContact,
25
+ resolveOrCreateContact,
26
+ softDeleteContact,
27
+ } from "../../lib/contacts.js";
28
+ import { ingestEvent } from "../../lib/ingestion.js";
29
+ import { applyListMembership } from "../../lib/preferences.js";
30
+ import { sendCampaignTask } from "../../workflows/send-campaign.js";
31
+
32
+ const configRoute = createRoute({
33
+ method: "get",
34
+ path: "/config",
35
+ tags: ["Admin — Agent"],
36
+ summary: "Studio co-working agent availability + active model",
37
+ responses: {
38
+ 200: {
39
+ content: {
40
+ "application/json": {
41
+ schema: z.object({
42
+ enabled: z
43
+ .boolean()
44
+ .describe(
45
+ "true only when AGENT_ENABLED and an OpenRouter key are set",
46
+ ),
47
+ model: z
48
+ .string()
49
+ .describe("the OpenRouter model id the agent runs on"),
50
+ }),
51
+ },
52
+ },
53
+ description: "Whether the agent is configured, and which model it uses",
54
+ },
55
+ },
56
+ });
57
+
58
+ export const agentRouter = new OpenAPIHono<AppEnv>();
59
+
60
+ agentRouter.openapi(configRoute, (c) => {
61
+ const { env } = c.get("container");
62
+ const cfg = agentConfig(env);
63
+ return c.json({ enabled: cfg.enabled, model: cfg.model }, 200);
64
+ });
65
+
66
+ /**
67
+ * Streaming chat. NOT an `.openapi()` route — `@hono/zod-openapi` can't model a
68
+ * non-JSON UI-message stream body — so it's a plain POST that returns the AI
69
+ * SDK's stream Response directly. Mounted under `adminRouter`, so it already
70
+ * inherits requireAdmin + rateLimit + auditMiddleware. The browser sends the
71
+ * Better Auth session cookie; the OpenRouter key never leaves the server.
72
+ */
73
+ agentRouter.post("/chat", async (c) => {
74
+ const container = c.get("container");
75
+ const cfg = agentConfig(container.env);
76
+ if (!cfg.enabled) {
77
+ return c.json({ error: "agent_unconfigured" }, 503);
78
+ }
79
+
80
+ const body = await c.req.json<{ messages?: UIMessage[] }>();
81
+ const messages = body.messages ?? [];
82
+
83
+ // The proposing operator — stamped into every minted write proposal so the
84
+ // confirm route can bind execution to the same actor. MUST match the actor
85
+ // resolution in /confirm exactly (key id, not the non-unique key name).
86
+ const user = c.get("user") as { email?: string } | null;
87
+ const apiKey = c.get("apiKey") as { id?: string; name?: string } | undefined;
88
+ const actorEmail = user?.email ?? apiKey?.id ?? apiKey?.name ?? "unknown";
89
+
90
+ const result = streamText({
91
+ model: getAgentModel(container.env),
92
+ system: await buildAgentSystemPrompt(container),
93
+ messages: await convertToModelMessages(messages),
94
+ tools: buildAgentTools({ container, actorEmail }),
95
+ stopWhen: stepCountIs(container.env.AGENT_MAX_STEPS),
96
+ });
97
+
98
+ return result.toUIMessageStreamResponse();
99
+ });
100
+
101
+ /**
102
+ * The HITL chokepoint — the ONLY place an agent write executes. A write tool's
103
+ * `execute` merely mints a single-use proposal token; the operator clicks
104
+ * confirm in Studio and the browser POSTs `{ token }` here. We verify+burn the
105
+ * token (single-use, 10-min TTL), assert the confirming actor matches the
106
+ * minting actor, re-derive the tier from CURRENT test-mode, dispatch to the real
107
+ * backing fn (idempotency-key = proposalId), and write an explicit audit row.
108
+ */
109
+ agentRouter.post("/confirm", async (c) => {
110
+ const container = c.get("container");
111
+ const {
112
+ db,
113
+ env,
114
+ registry,
115
+ bucketRegistry,
116
+ listRegistry,
117
+ hatchet,
118
+ logger,
119
+ emailService,
120
+ domainStatus,
121
+ analytics,
122
+ templates,
123
+ } = container;
124
+
125
+ if (!agentConfig(env).enabled) {
126
+ return c.json({ error: "agent_unconfigured" }, 503);
127
+ }
128
+
129
+ const user = c.get("user") as { email?: string } | null;
130
+ const apiKey = c.get("apiKey") as { id?: string; name?: string } | undefined;
131
+ const actor = user?.email ?? apiKey?.id ?? apiKey?.name ?? "unknown";
132
+
133
+ const { token } = await c.req.json<{ token?: string }>();
134
+ if (!token) return c.json({ error: "token required" }, 400);
135
+
136
+ let proposal: VerifiedProposal;
137
+ try {
138
+ proposal = await verifyAndBurnProposal({
139
+ token,
140
+ secret: env.BETTER_AUTH_SECRET,
141
+ });
142
+ } catch (err) {
143
+ if (err instanceof InvalidProposalError) {
144
+ // Redis blip ⇒ retryable (503); otherwise a spent/expired/bad token (410).
145
+ return c.json(
146
+ { error: err.message },
147
+ err.code === "redis_unavailable" ? 503 : 410,
148
+ );
149
+ }
150
+ throw err;
151
+ }
152
+
153
+ if (proposal.actorEmail !== actor) {
154
+ return c.json({ error: "Proposal actor mismatch" }, 403);
155
+ }
156
+
157
+ // Re-derive the effective tier from CURRENT test-mode. If it changed since the
158
+ // proposal was minted (e.g. the domain got verified mid-session), reject — the
159
+ // operator approved a risk level that no longer holds; they must re-mint.
160
+ const tier = effectiveTier(proposal.tool, {
161
+ testMode: domainStatus.testModeCached(),
162
+ });
163
+ if (tier !== proposal.tier) {
164
+ return c.json(
165
+ {
166
+ error:
167
+ "Risk level changed since this action was proposed (test-mode may have changed). Re-issue the action to confirm.",
168
+ },
169
+ 409,
170
+ );
171
+ }
172
+
173
+ const args = proposal.args;
174
+ const idem = proposal.proposalId;
175
+ let result: unknown;
176
+
177
+ try {
178
+ switch (proposal.tool) {
179
+ case "fire_event":
180
+ result = await ingestEvent({
181
+ db,
182
+ registry,
183
+ hatchet,
184
+ logger,
185
+ analytics,
186
+ event: {
187
+ event: String(args.event),
188
+ userId: args.userId as string | undefined,
189
+ userEmail: args.userEmail as string | undefined,
190
+ eventProperties: (args.eventProperties ?? {}) as Record<
191
+ string,
192
+ unknown
193
+ >,
194
+ idempotencyKey: idem,
195
+ source: "agent",
196
+ },
197
+ });
198
+ break;
199
+
200
+ case "enroll_in_journey": {
201
+ const meta = registry.get(String(args.journeyId));
202
+ if (!meta) return c.json({ error: "Journey not found" }, 404);
203
+ result = await ingestEvent({
204
+ db,
205
+ registry,
206
+ hatchet,
207
+ logger,
208
+ analytics,
209
+ event: {
210
+ event: meta.trigger.event,
211
+ userId: args.userId as string | undefined,
212
+ userEmail: args.userEmail as string | undefined,
213
+ eventProperties: (args.properties ?? {}) as Record<string, unknown>,
214
+ idempotencyKey: idem,
215
+ source: "agent",
216
+ },
217
+ });
218
+ break;
219
+ }
220
+
221
+ case "send_transactional_email": {
222
+ if (!getTemplateNames(templates).includes(args.template as never)) {
223
+ return c.json({ error: `Unknown template: ${args.template}` }, 400);
224
+ }
225
+ result = await emailService.send({
226
+ template: args.template as never,
227
+ props: (args.props ?? {}) as never,
228
+ to: String(args.to),
229
+ userEmail: String(args.to),
230
+ subject: args.subject as string | undefined,
231
+ userId: args.userId as string | undefined,
232
+ idempotencyKey: idem,
233
+ });
234
+ break;
235
+ }
236
+
237
+ case "send_campaign": {
238
+ if (!getTemplateNames(templates).includes(args.template as never)) {
239
+ return c.json({ error: `Unknown template: ${args.template}` }, 400);
240
+ }
241
+ const audienceKind = args.list ? "list" : "bucket";
242
+ const audienceId = String(args.list ?? args.bucket);
243
+ // Reject a non-existent audience up front — otherwise the durable task
244
+ // resolves zero recipients and the campaign silently "sends" to no one.
245
+ const audienceExists =
246
+ audienceKind === "bucket"
247
+ ? bucketRegistry.has(audienceId)
248
+ : listRegistry.has(audienceId);
249
+ if (!audienceExists) {
250
+ return c.json(
251
+ { error: `Unknown ${audienceKind}: ${audienceId}` },
252
+ 404,
253
+ );
254
+ }
255
+ const inserted = await db
256
+ .insert(campaigns)
257
+ .values({
258
+ name:
259
+ (args.name as string) ??
260
+ `Agent campaign to ${audienceKind} ${audienceId}`,
261
+ status: "queued",
262
+ audienceKind,
263
+ audienceId,
264
+ templateKey: String(args.template) as never,
265
+ props: (args.props ?? {}) as Record<string, unknown>,
266
+ fromEmail: (args.from as string) ?? null,
267
+ subject: (args.subject as string) ?? null,
268
+ idempotencyKey: idem,
269
+ })
270
+ .onConflictDoNothing({ target: campaigns.idempotencyKey })
271
+ .returning({ id: campaigns.id });
272
+ const campaignId =
273
+ inserted[0]?.id ??
274
+ (
275
+ await db
276
+ .select({ id: campaigns.id })
277
+ .from(campaigns)
278
+ .where(eq(campaigns.idempotencyKey, idem))
279
+ .limit(1)
280
+ )[0]?.id;
281
+ if (!campaignId) throw new Error("Failed to create campaign");
282
+ await sendCampaignTask.run({ campaignId });
283
+ result = { campaignId, status: "queued" };
284
+ break;
285
+ }
286
+
287
+ case "subscribe_list":
288
+ case "unsubscribe_list": {
289
+ const subscribed = proposal.tool === "subscribe_list";
290
+ if (!args.email && !args.userId) {
291
+ return c.json(
292
+ { error: "subscribe/unsubscribe requires an email or userId" },
293
+ 400,
294
+ );
295
+ }
296
+ await resolveOrCreateContact({
297
+ db,
298
+ userId: args.userId as string | undefined,
299
+ email: args.email as string | undefined,
300
+ });
301
+ try {
302
+ await applyListMembership({
303
+ db,
304
+ userId: args.userId as string | undefined,
305
+ email: args.email as string | undefined,
306
+ lists: { [String(args.list)]: subscribed },
307
+ });
308
+ } catch (e) {
309
+ // List membership keys on email; a contact with no resolvable email is
310
+ // an operator input problem (400), not a server fault (500).
311
+ return c.json(
312
+ {
313
+ error:
314
+ e instanceof Error ? e.message : "Cannot set list membership",
315
+ },
316
+ 400,
317
+ );
318
+ }
319
+ result = { list: String(args.list), subscribed };
320
+ break;
321
+ }
322
+
323
+ case "upsert_contact":
324
+ result = await resolveOrCreateContact({
325
+ db,
326
+ userId: args.userId as string | undefined,
327
+ email: args.email as string | undefined,
328
+ anonymousId: args.anonymousId as string | undefined,
329
+ contactProperties: (args.properties ?? {}) as Record<string, unknown>,
330
+ });
331
+ break;
332
+
333
+ case "update_contact": {
334
+ const current = await resolveContact({ db, id: String(args.id) });
335
+ if (!current) return c.json({ error: "Contact not found" }, 404);
336
+ result = await resolveOrCreateContact({
337
+ db,
338
+ userId: current.externalId ?? undefined,
339
+ email: (args.email as string) ?? current.email ?? undefined,
340
+ anonymousId: current.anonymousId ?? undefined,
341
+ contactProperties: (args.properties ?? {}) as Record<string, unknown>,
342
+ });
343
+ break;
344
+ }
345
+
346
+ case "delete_contact":
347
+ result = await softDeleteContact({
348
+ db,
349
+ email: args.email as string | undefined,
350
+ userId: args.userId as string | undefined,
351
+ });
352
+ break;
353
+
354
+ default:
355
+ return c.json({ error: `Unknown tool: ${proposal.tool}` }, 400);
356
+ }
357
+ } catch (err) {
358
+ logger.warn("agent confirm: write failed", {
359
+ tool: proposal.tool,
360
+ proposalId: proposal.proposalId,
361
+ error: err instanceof Error ? err.message : String(err),
362
+ });
363
+ return c.json(
364
+ { ok: false, error: err instanceof Error ? err.message : String(err) },
365
+ 500,
366
+ );
367
+ }
368
+
369
+ // Explicit audit row. Args are stored as a DIGEST (data minimization — never
370
+ // raw PII), with field names + count for forensics. Awaited so `ok:true`
371
+ // truthfully means the write AND its audit both landed.
372
+ const argsHash = createHash("sha256")
373
+ .update(JSON.stringify(args))
374
+ .digest("hex");
375
+ await db
376
+ .insert(auditLogs)
377
+ .values({
378
+ actor: `agent:${actor}`,
379
+ action: `agent.confirm.${proposal.tool}`,
380
+ resource: "agent",
381
+ resourceId: proposal.proposalId,
382
+ detail: {
383
+ tool: proposal.tool,
384
+ tier,
385
+ mintedTier: proposal.tier,
386
+ sessionId: proposal.sessionId,
387
+ argsHash,
388
+ argCount: Object.keys(args).length,
389
+ fieldNames: Object.keys(args),
390
+ result,
391
+ },
392
+ ipAddress:
393
+ c.req.header("x-forwarded-for") ?? c.req.header("x-real-ip") ?? null,
394
+ })
395
+ .catch((e: unknown) =>
396
+ logger.warn("agent confirm audit write failed", {
397
+ error: e instanceof Error ? e.message : String(e),
398
+ }),
399
+ );
400
+
401
+ return c.json({ ok: true, result }, 200);
402
+ });
@@ -3,6 +3,7 @@ import type { AppEnv } from "../../app.js";
3
3
  import { auditMiddleware } from "../../middleware/audit.js";
4
4
  import { rateLimit } from "../../middleware/rate-limit.js";
5
5
  import { requireAdmin } from "../../middleware/require-admin.js";
6
+ import { agentRouter } from "./agent.js";
6
7
  import { alertsRouter } from "./alerts.js";
7
8
  import { analyticsAdminRouter } from "./analytics.js";
8
9
  import { apiKeysRouter } from "./api-keys.js";
@@ -56,3 +57,4 @@ adminRouter.route("/alerts", alertsRouter);
56
57
  adminRouter.route("/dlq", dlqRouter);
57
58
  adminRouter.route("/domain", domainRouter);
58
59
  adminRouter.route("/readiness", readinessRouter);
60
+ adminRouter.route("/agent", agentRouter);