@hogsend/engine 0.33.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.
@@ -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);