@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.
- package/package.json +9 -7
- package/src/container.ts +23 -1
- package/src/env.ts +24 -0
- package/src/index.ts +8 -0
- package/src/lib/agent/config.ts +19 -0
- package/src/lib/agent/proposals.ts +210 -0
- package/src/lib/agent/provider.ts +18 -0
- package/src/lib/agent/risk.ts +71 -0
- package/src/lib/agent/system-prompt.ts +30 -0
- package/src/lib/agent/tools.ts +465 -0
- package/src/lib/analytics-singleton.ts +18 -1
- package/src/lib/connector-actions.ts +19 -3
- package/src/lib/ingestion.ts +62 -2
- package/src/lib/tracking-events.ts +6 -3
- package/src/routes/admin/agent.ts +402 -0
- package/src/routes/admin/index.ts +2 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hogsend/engine",
|
|
3
|
-
"version": "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.
|
|
44
|
-
"@hogsend/db": "^0.
|
|
45
|
-
"@hogsend/email": "^0.
|
|
46
|
-
"@hogsend/plugin-posthog": "^0.
|
|
47
|
-
"@hogsend/plugin-resend": "^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.
|
|
52
|
+
"@hogsend/plugin-postmark": "^0.35.0"
|
|
51
53
|
},
|
|
52
54
|
"devDependencies": {
|
|
53
55
|
"@types/node": "^22.15.3",
|
package/src/container.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { HatchetClient } from "@hatchet-dev/typescript-sdk/v1/index.js";
|
|
2
2
|
import type {
|
|
3
|
+
AnalyticsEventMirrorConfig,
|
|
3
4
|
AnalyticsProvider,
|
|
4
5
|
EmailProvider,
|
|
5
6
|
PostHogService,
|
|
@@ -47,7 +48,10 @@ import {
|
|
|
47
48
|
} from "./lib/analytics-adapter.js";
|
|
48
49
|
import { AnalyticsProviderRegistry } from "./lib/analytics-provider-registry.js";
|
|
49
50
|
import { analyticsProvidersFromEnv } from "./lib/analytics-providers-from-env.js";
|
|
50
|
-
import {
|
|
51
|
+
import {
|
|
52
|
+
setAnalytics,
|
|
53
|
+
setAnalyticsEventMirror,
|
|
54
|
+
} from "./lib/analytics-singleton.js";
|
|
51
55
|
import { type Auth, createAuth } from "./lib/auth.js";
|
|
52
56
|
import {
|
|
53
57
|
createDomainStatusService,
|
|
@@ -271,6 +275,7 @@ export interface HogsendClientOptions {
|
|
|
271
275
|
provider?: AnalyticsProvider;
|
|
272
276
|
providers?: AnalyticsProvider[];
|
|
273
277
|
defaultProvider?: string;
|
|
278
|
+
eventMirror?: AnalyticsEventMirrorConfig;
|
|
274
279
|
};
|
|
275
280
|
/**
|
|
276
281
|
* Code-defined outbound DESTINATIONS (Phase 3). Each is a
|
|
@@ -588,6 +593,7 @@ export function createHogsendClient(
|
|
|
588
593
|
provider?: AnalyticsProvider;
|
|
589
594
|
providers?: AnalyticsProvider[];
|
|
590
595
|
defaultProvider?: string;
|
|
596
|
+
eventMirror?: AnalyticsEventMirrorConfig;
|
|
591
597
|
})
|
|
592
598
|
: undefined;
|
|
593
599
|
|
|
@@ -647,6 +653,22 @@ export function createHogsendClient(
|
|
|
647
653
|
// undefined (no provider configured) — the reads stay no-ops.
|
|
648
654
|
setAnalytics(analytics);
|
|
649
655
|
|
|
656
|
+
// Event mirror (operator policy): resolve the ingest→analytics capture config
|
|
657
|
+
// once and install it on the same singleton seam as `analytics`, so
|
|
658
|
+
// `ingestEvent` mirrors events into the active provider on EVERY ingest path
|
|
659
|
+
// (not just the routes that thread `analytics`). Off by default. The env flag
|
|
660
|
+
// is an explicit OVERRIDE in both directions when set ("true"/"false"); unset
|
|
661
|
+
// ⇒ the code option wins. Allow/deny stay code-only (env is not list config).
|
|
662
|
+
const eventMirror: AnalyticsEventMirrorConfig = {
|
|
663
|
+
enabled:
|
|
664
|
+
env.ANALYTICS_EVENT_MIRROR != null
|
|
665
|
+
? env.ANALYTICS_EVENT_MIRROR === "true"
|
|
666
|
+
: (analyticsGroup?.eventMirror?.enabled ?? false),
|
|
667
|
+
allow: analyticsGroup?.eventMirror?.allow,
|
|
668
|
+
deny: analyticsGroup?.eventMirror?.deny,
|
|
669
|
+
};
|
|
670
|
+
setAnalyticsEventMirror(eventMirror);
|
|
671
|
+
|
|
650
672
|
// Identity-attach helper (§7): bound to THIS container's db + resolved
|
|
651
673
|
// analytics provider so a contact-merge outside the `/v1/events` ingest path
|
|
652
674
|
// (Discord `/link`) propagates the analytics merge through the same engine
|
package/src/env.ts
CHANGED
|
@@ -149,6 +149,13 @@ export const env = createEnv({
|
|
|
149
149
|
// Selects the ACTIVE analytics provider id out of the registry (env
|
|
150
150
|
// presets + consumer-registered providers). Mirrors EMAIL_PROVIDER.
|
|
151
151
|
ANALYTICS_PROVIDER: z.string().min(1).default("posthog"),
|
|
152
|
+
// Override for the ingest→analytics event mirror (capture every ingested
|
|
153
|
+
// event into the active analytics provider, keyed to the resolved contact).
|
|
154
|
+
// The code option `analytics.eventMirror.enabled` is the default; this env,
|
|
155
|
+
// when set, OVERRIDES it in both directions. Enum (not z.coerce.boolean) so
|
|
156
|
+
// an explicit "false" actually disables (coerce.boolean treats "false" as
|
|
157
|
+
// true). Unset ⇒ the code option wins. Allow/deny lists stay code-only.
|
|
158
|
+
ANALYTICS_EVENT_MIRROR: z.enum(["true", "false"]).optional(),
|
|
152
159
|
POSTHOG_WEBHOOK_SECRET: z.string().min(1).optional(),
|
|
153
160
|
// When true AND POSTHOG_API_KEY is set, the engine idempotently auto-seeds
|
|
154
161
|
// ONE kind="posthog" webhook endpoint subscribed to the email funnel so the
|
|
@@ -229,6 +236,23 @@ export const env = createEnv({
|
|
|
229
236
|
// path can never be turned off by misconfiguration. Set this to add the
|
|
230
237
|
// segment/slack presets (credentials still live per-endpoint in `config`).
|
|
231
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),
|
|
232
256
|
},
|
|
233
257
|
runtimeEnv: process.env,
|
|
234
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
|
+
}
|