Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
feat(api): implement Context.dev key verification and enhance capabilities handling
Lewis Carhart5ca4eae98716
diff --git a/.env.example b/.env.exampleindex a643dd52..db20f549 100644--- a/.env.example+++ b/.env.example@@ -59,12 +59,15 @@ GOOGLE_CLIENT_SECRET=""# secret; the agent verifies it and learns *which rep* is asking. Set the same# value for both processes. openssl rand -base64 32#-# It also authorises the API's dispatch poke, which is what makes a new-# company's logo appear as it is added instead of on the next minute's tick.+# It also authorises two calls the API makes to the agent: the dispatch poke,+# which is what makes a new company's logo appear as it is added instead of on+# the next minute's tick, and the check that a Context API key is real before+# it is saved.#-# Leave it unset and the Agent tab reports that it is not configured, and the-# poke is skipped rather than sent unauthenticated. Nothing else changes: the-# agent still runs on its own schedule.+# Leave it unset and the Agent tab reports that it is not configured, the poke+# is skipped rather than sent unauthenticated, and a Context key is saved+# without being checked. Nothing else changes: the agent still runs on its own+# schedule.# AGENT_BRIDGE_SECRET=""# PORT="3001"@@ -84,10 +87,6 @@ GOOGLE_CLIENT_SECRET=""# https://rapidapi.com/linkdapi/api/linkdapi-best-unofficial-linkedin-api# RAPIDAPI_KEY=""-# Context.dev — company logos, industry and socials from a domain.-# https://context.dev-# CONTEXT_DEV_API_KEY=""-# GitHub — raises the rate limit when matching contacts to GitHub profiles.# Any classic token with no scopes will do.# GITHUB_TOKEN=""diff --git a/README.md b/README.mdindex c69b809c..65023907 100644--- a/README.md+++ b/README.md@@ -1,3 +1,8 @@+<p align="center">+ <a href="https://link.context.dev/crm"><img alt="Context" height="18" align="middle" src="./docs/images/context.png"></a>+ <a href="https://link.context.dev/crm"><strong>Powered by Context</strong></a>+</p>+<h1 align="center">CRM</h1><p align="center">@@ -132,9 +137,17 @@ failed call at a time, and it prints the list at startup:```[agent] on LinkedIn (RAPIDAPI_KEY)[agent] off Web research (PERPLEXITY_API_KEY)-[agent] off Company brand data (CONTEXT_DEV_API_KEY)+[agent] off Company brand data (Settings → General)```+**Company brand data is [Context](https://link.context.dev/crm)** — the logo, the+colours, the industry and the real name behind a domain, which is the difference+between an account that arrives as itself and one that arrives as a grey square with+its initials in it. It is the one key that is asked for rather than configured: it+lives in a row, the onboarding asks for it, and **Settings → General** changes it+afterwards, because a self-hoster's admin cannot redeploy to set an environment+variable.+**The sandbox has no network and no database.** Turning it on is what gives the modela shell — the difference between a tool-caller and something that can keep a dossier,diff this month's profile against last month's, and grep a thread for a signature@@ -277,7 +290,6 @@ short version:| `API_URL` / `APP_URL` | Where the two halves are served. Only needed off localhost. || `PERPLEXITY_API_KEY` | Lets the agent search the open web, with citations. || `RAPIDAPI_KEY` | Lets the agent read LinkedIn profiles for identity. |-| `CONTEXT_DEV_API_KEY` | Company logo, industry and socials from a domain. || `AGENT_BRIDGE_SECRET` | Lets a rep talk to the agent from a contact's **Agent** tab. || `REDIS_URL` | A shared cache. Without it, per-instance and in-memory. || `CRON_SECRET` | Guards the Gmail/Calendar sync route. Required to use it. |diff --git a/apps/agent/agent/agent.ts b/apps/agent/agent/agent.tsindex 0f179305..c6ce8583 100644--- a/apps/agent/agent/agent.ts+++ b/apps/agent/agent/agent.ts@@ -2,14 +2,10 @@ import "@crm/env/load";import { DEFAULT_AGENT_MODEL } from "@crm/db/settings";import { defineAgent, defineDynamic } from "eve";-import { capabilities } from "./lib/capabilities";+import { logCapabilities } from "./lib/capabilities";import { selectedModel } from "./lib/model";-for (const capability of capabilities()) {- console.log(- `[agent] ${capability.enabled ? "on " : "off"} ${capability.label} (${capability.env})`,- );-}+void logCapabilities();export default defineAgent({model: defineDynamic({diff --git a/apps/agent/agent/channels/crm.ts b/apps/agent/agent/channels/crm.tsindex 90eba837..44d686ac 100644--- a/apps/agent/agent/channels/crm.ts+++ b/apps/agent/agent/channels/crm.ts@@ -1,5 +1,6 @@import { EnrichmentStatus } from "@crm/db";import { defineChannel, POST } from "eve/channels";+import { verifyKey } from "../lib/context-dev";import { brief, drainAll, taskAuth } from "../lib/dispatch";import { settle } from "../lib/enrichment";import { completeTask, taskSubject } from "../lib/tasks";@@ -45,6 +46,28 @@ export default defineChannel({return new Response(null, { status: 202 });}),++ POST("/internal/crm/verify-key", async (request) => {+ if (!authorised(request)) {+ return new Response("Unauthorized", { status: 401 });+ }++ const body = (await request.json().catch(() => null)) as {+ apiKey?: unknown;+ } | null;++ const apiKey =+ typeof body?.apiKey === "string" ? body.apiKey.trim() : null;++ if (!apiKey) {+ return Response.json(+ { outcome: "invalid", reason: "No API key was sent." },+ { status: 400 },+ );+ }++ return Response.json(await verifyKey(apiKey));+ }),],events: {diff --git a/apps/agent/agent/lib/brand.ts b/apps/agent/agent/lib/brand.tsindex c0efd8ba..d9b30a3a 100644--- a/apps/agent/agent/lib/brand.ts+++ b/apps/agent/agent/lib/brand.ts@@ -57,7 +57,7 @@ export async function runBrand({if (!company) return { enriched: false, reason: "No such company." };- if (!contextDevEnabled()) {+ if (!(await contextDevEnabled())) {const reason ="Context.dev is not configured, so there is nowhere to look.";await settle(companyId, EnrichmentStatus.SKIPPED, reason);diff --git a/apps/agent/agent/lib/capabilities.ts b/apps/agent/agent/lib/capabilities.tsindex c5c7ed20..cef15dcc 100644--- a/apps/agent/agent/lib/capabilities.ts+++ b/apps/agent/agent/lib/capabilities.ts@@ -1,49 +1,77 @@import "@crm/env/load";+import { db } from "@crm/db";+import { readContextDevKey } from "@crm/db/settings";++export const CONTEXT_DEV = "CONTEXT_DEV";+export type Capability = {- readonly env: string;+ readonly id: string;readonly label: string;readonly gives: string;readonly enabled: boolean;+ readonly from: string;};-export function capabilities(): readonly Capability[] {- const set = (key: string) => Boolean(process.env[key]?.trim());+export async function contextDevKey(): Promise<string | null> {+ try {+ return await readContextDevKey(db);+ } catch (error) {+ console.error(+ `[agent] could not read the Context.dev key from the database: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );++ return null;+ }+}++export async function capabilities(): Promise<readonly Capability[]> {+ return capabilitiesFrom(await contextDevKey());+}++export function capabilitiesFrom(+ contextDev: string | null,+): readonly Capability[] {+ const fromEnv = (id: string) => ({+ id,+ from: id,+ enabled: Boolean(process.env[id]?.trim()),+ });return [{- env: "RAPIDAPI_KEY",+ ...fromEnv("RAPIDAPI_KEY"),label: "LinkedIn",gives:"a person's real name, current title, employer and tenure, self-reported, and so authoritative on identity",- enabled: set("RAPIDAPI_KEY"),},{- env: "PERPLEXITY_API_KEY",+ ...fromEnv("PERPLEXITY_API_KEY"),label: "Web research",gives:"open-web context with citations, and the search that finds a LinkedIn slug in the first place",- enabled: set("PERPLEXITY_API_KEY"),},{- env: "CONTEXT_DEV_API_KEY",+ id: CONTEXT_DEV,+ from: "Settings → General",label: "Company brand data",gives: "a company's logo, industry, location and socials from its domain",- enabled: set("CONTEXT_DEV_API_KEY"),+ enabled: contextDev !== null,},{- env: "BLOB_READ_WRITE_TOKEN",+ ...fromEnv("BLOB_READ_WRITE_TOKEN"),label: "Picture storage",gives:"somewhere to keep a logo or a profile photo. Without it a record has no picture at all, because the URLs these sources hand back expire and are never stored as they are",- enabled: set("BLOB_READ_WRITE_TOKEN"),},];}-export function enabled(env: string): boolean {- return capabilities().some(- (capability) => capability.env === env && capability.enabled,+export async function enabled(id: string): Promise<boolean> {+ return (await capabilities()).some(+ (capability) => capability.id === id && capability.enabled,);}@@ -61,8 +89,19 @@ export function unavailable(env: string): {};}-export function capabilitiesMarkdown(): string {- const all = capabilities();+export async function logCapabilities(): Promise<void> {+ for (const capability of await capabilities()) {+ console.log(+ `[agent] ${capability.enabled ? "on " : "off"} ${capability.label} (${capability.from})`,+ );+ }+}++export async function capabilitiesMarkdown(): Promise<string> {+ return markdownFor(await capabilities());+}++export function markdownFor(all: readonly Capability[]): string {const on = all.filter((capability) => capability.enabled);const off = all.filter((capability) => !capability.enabled);diff --git a/apps/agent/agent/lib/context-dev.ts b/apps/agent/agent/lib/context-dev.tsindex 42c0a214..30341d47 100644--- a/apps/agent/agent/lib/context-dev.ts+++ b/apps/agent/agent/lib/context-dev.ts@@ -1,5 +1,6 @@import ContextDev from "context.dev";import { APIError } from "context.dev/core/error";+import { contextDevKey } from "./capabilities";export type Brand = {domain?: string | null;@@ -47,18 +48,81 @@ export type SearchResult = {const TIMEOUT_MS = 60_000;-let client: ContextDev | null | undefined;+let client: { key: string; api: ContextDev } | null = null;-function contextDev(): ContextDev | null {- if (client === undefined) {- const apiKey = process.env.CONTEXT_DEV_API_KEY;- client = apiKey ? new ContextDev({ apiKey }) : null;+async function contextDev(): Promise<ContextDev | null> {+ const key = await contextDevKey();++ if (!key) {+ client = null;+ return null;+ }++ if (client?.key !== key) {+ client = { key, api: new ContextDev({ apiKey: key }) };+ }++ return client.api;+}++export async function contextDevEnabled(): Promise<boolean> {+ return (await contextDevKey()) !== null;+}++export type KeyCheck =+ | { outcome: "valid" }+ | { outcome: "invalid"; reason: string }+ | { outcome: "unknown"; reason: string };++/**+ * A free-provider address is refused with a documented 422 before any brand is+ * resolved, and a lookup that resolves nothing is not billed — so this proves+ * the key authenticates without spending a credit.+ */+const PROBE_EMAIL = "[email protected]";++const VERIFY_TIMEOUT_MS = 15_000;++export async function verifyKey(key: string): Promise<KeyCheck> {+ const api = new ContextDev({ apiKey: key });++ try {+ await api.brand.retrieve({+ type: "by_email",+ email: PROBE_EMAIL,+ timeoutMS: VERIFY_TIMEOUT_MS,+ });++ return { outcome: "valid" };+ } catch (error) {+ return classifyKey(error);}- return client;}-export function contextDevEnabled(): boolean {- return contextDev() !== null;+/**+ * 401 is the only answer that means *this key is wrong*. Everything else that+ * came back from Context.dev — a 422 refusing the probe address, a 403 about+ * the plan, a 429, a 500 — was served *after* the key authenticated, so the+ * key is good and only the probe was refused. Anything that never reached them+ * says nothing about the key at all.+ */+export function classifyKey(error: unknown): KeyCheck {+ if (!(error instanceof APIError)) {+ return { outcome: "unknown", reason: describe(error) };+ }++ if (error.status === 401) {+ return {+ outcome: "invalid",+ reason: "Context did not recognise that API key.",+ };+ }++ if (error.status === undefined) {+ return { outcome: "unknown", reason: describe(error) };+ }++ return { outcome: "valid" };}export async function brandByDomain(@@ -78,7 +142,7 @@ export async function brandByEmail(email: string): Promise<LookupResult> {}export async function prefetch(domain: string): Promise<void> {- const api = contextDev();+ const api = await contextDev();if (!api) return;try {@@ -93,7 +157,7 @@ export async function extract(): Promise<{ outcome: "found"; data: unknown } | { outcome: "failed"; reason: string }> {- const api = contextDev();+ const api = await contextDev();if (!api) {return { outcome: "failed", reason: "Context.dev is not configured." };}@@ -119,7 +183,7 @@ export async function search(| { outcome: "found"; results: SearchResult[] }| { outcome: "failed"; reason: string }> {- const api = contextDev();+ const api = await contextDev();if (!api) {return { outcome: "failed", reason: "Context.dev is not configured." };}@@ -153,7 +217,7 @@ export async function search(async function lookup(params: Parameters<ContextDev["brand"]["retrieve"]>[0],): Promise<LookupResult> {- const api = contextDev();+ const api = await contextDev();if (!api) {return { outcome: "skipped", reason: "Context.dev is not configured." };}diff --git a/apps/agent/agent/lib/preamble.ts b/apps/agent/agent/lib/preamble.tsindex ac6d5c41..4dd2b8e0 100644--- a/apps/agent/agent/lib/preamble.ts+++ b/apps/agent/agent/lib/preamble.ts@@ -30,8 +30,12 @@ export async function sessionPreamble(return noRecordPreamble();}-export function composeClosing(us: WorkspaceIdentity | null): string {- return [usMarkdown(us), capabilitiesMarkdown()].filter(Boolean).join("\n\n");+export async function composeClosing(+ us: WorkspaceIdentity | null,+): Promise<string> {+ return [usMarkdown(us), await capabilitiesMarkdown()]+ .filter(Boolean)+ .join("\n\n");}async function closing(): Promise<string> {@@ -351,7 +355,7 @@ export async function workspacePreamble("You are describing us to a colleague who has just joined, not writing our","home page back to us.","",- capabilitiesMarkdown(),+ await capabilitiesMarkdown(),].join("\n");return { markdown, focus: {} };diff --git a/apps/agent/agent/tools/get_contact_work_history.ts b/apps/agent/agent/tools/get_contact_work_history.tsindex b6ace330..f297748d 100644--- a/apps/agent/agent/tools/get_contact_work_history.ts+++ b/apps/agent/agent/tools/get_contact_work_history.ts@@ -11,7 +11,7 @@ export default defineTool({contactId: z.string(),}),async execute({ contactId }) {- if (!enabled("RAPIDAPI_KEY")) {+ if (!(await enabled("RAPIDAPI_KEY"))) {return { found: false as const, ...unavailable("RAPIDAPI_KEY") };}diff --git a/apps/agent/agent/tools/get_linkedin_profile.ts b/apps/agent/agent/tools/get_linkedin_profile.tsindex bc4cf3f4..f52e2175 100644--- a/apps/agent/agent/tools/get_linkedin_profile.ts+++ b/apps/agent/agent/tools/get_linkedin_profile.ts@@ -33,7 +33,7 @@ export default defineTool({includeHistory,contactId,}) {- if (!enabled("RAPIDAPI_KEY")) {+ if (!(await enabled("RAPIDAPI_KEY"))) {return { found: false as const, ...unavailable("RAPIDAPI_KEY") };}diff --git a/apps/agent/agent/tools/research_person.ts b/apps/agent/agent/tools/research_person.tsindex 82bbef6b..d44a43e8 100644--- a/apps/agent/agent/tools/research_person.ts+++ b/apps/agent/agent/tools/research_person.ts@@ -19,7 +19,7 @@ export default defineTool({.describe("Reason over more sources. Slower, better for prep briefs."),}),async execute({ question, deep }) {- if (!enabled("PERPLEXITY_API_KEY"))+ if (!(await enabled("PERPLEXITY_API_KEY")))return unavailable("PERPLEXITY_API_KEY");const charge = spend(deep ? 2 : 1);diff --git a/apps/agent/agent/tools/resolve_linkedin_profile.ts b/apps/agent/agent/tools/resolve_linkedin_profile.tsindex 23df16b6..b1432146 100644--- a/apps/agent/agent/tools/resolve_linkedin_profile.ts+++ b/apps/agent/agent/tools/resolve_linkedin_profile.ts@@ -13,7 +13,7 @@ export default defineTool({companyName: z.string().describe("The company the CRM has them at."),}),async execute({ email, companyName }) {- if (!enabled("PERPLEXITY_API_KEY")) {+ if (!(await enabled("PERPLEXITY_API_KEY"))) {return { candidateSlugs: [], ...unavailable("PERPLEXITY_API_KEY") };}diff --git a/apps/agent/test/capabilities.spec.ts b/apps/agent/test/capabilities.spec.tsindex 33412346..7b4ee8b9 100644--- a/apps/agent/test/capabilities.spec.ts+++ b/apps/agent/test/capabilities.spec.ts@@ -1,15 +1,15 @@import { afterEach, beforeEach, describe, expect, it } from "bun:test";import {- capabilities,- capabilitiesMarkdown,+ CONTEXT_DEV,+ capabilitiesFrom,enabled,+ markdownFor,unavailable,} from "../agent/lib/capabilities";const KEYS = ["RAPIDAPI_KEY","PERPLEXITY_API_KEY",- "CONTEXT_DEV_API_KEY","BLOB_READ_WRITE_TOKEN",] as const;@@ -30,36 +30,61 @@ afterEach(() => {});describe("capabilities", () => {- it("reports everything off on a bare install", () => {- expect(capabilities().every((c) => !c.enabled)).toBe(true);- expect(enabled("RAPIDAPI_KEY")).toBe(false);+ it("reports everything off on a bare install", async () => {+ expect(capabilitiesFrom(null).every((c) => !c.enabled)).toBe(true);+ expect(await enabled("RAPIDAPI_KEY")).toBe(false);});- it("turns one on without turning on the others", () => {+ it("turns one on without turning on the others", async () => {process.env.PERPLEXITY_API_KEY = "pplx-test";- expect(enabled("PERPLEXITY_API_KEY")).toBe(true);- expect(enabled("RAPIDAPI_KEY")).toBe(false);+ expect(await enabled("PERPLEXITY_API_KEY")).toBe(true);+ expect(await enabled("RAPIDAPI_KEY")).toBe(false);});- it("treats blank and whitespace as unset", () => {+ it("treats blank and whitespace as unset", async () => {process.env.RAPIDAPI_KEY = " ";- expect(enabled("RAPIDAPI_KEY")).toBe(false);+ expect(await enabled("RAPIDAPI_KEY")).toBe(false);});- it("is read live, so a late-configured process is not stuck off", () => {- expect(enabled("RAPIDAPI_KEY")).toBe(false);+ it("is read live, so a late-configured process is not stuck off", async () => {+ expect(await enabled("RAPIDAPI_KEY")).toBe(false);process.env.RAPIDAPI_KEY = "key";- expect(enabled("RAPIDAPI_KEY")).toBe(true);+ expect(await enabled("RAPIDAPI_KEY")).toBe(true);});- it("is unknown for a variable that is not a capability", () => {+ it("is unknown for a variable that is not a capability", async () => {process.env.SOMETHING_ELSE = "x";- expect(enabled("SOMETHING_ELSE")).toBe(false);+ expect(await enabled("SOMETHING_ELSE")).toBe(false);delete process.env.SOMETHING_ELSE;});});+describe("the Context key is a setting, never a variable", () => {+ const contextDev = (stored: string | null) =>+ capabilitiesFrom(stored).find((c) => c.id === CONTEXT_DEV);++ it("is on when a key is stored", () => {+ expect(contextDev("ctx-from-the-settings-page")?.enabled).toBe(true);+ });++ it("is off when nothing has been stored", () => {+ expect(contextDev(null)?.enabled).toBe(false);+ });++ it("is not turned on by an environment variable", () => {+ process.env.CONTEXT_DEV_API_KEY = "a-variable-nothing-reads";++ expect(contextDev(null)?.enabled).toBe(false);++ delete process.env.CONTEXT_DEV_API_KEY;+ });++ it("points at the settings page rather than a variable name", () => {+ expect(contextDev(null)?.from).toBe("Settings → General");+ });+});+describe("the unavailable result", () => {it("says retrying will not help", () => {const result = unavailable("RAPIDAPI_KEY");@@ -73,7 +98,7 @@ describe("the unavailable result", () => {describe("the capability briefing", () => {it("tells a bare install to work from the CRM alone", () => {- const markdown = capabilitiesMarkdown();+ const markdown = markdownFor(capabilitiesFrom(null));expect(markdown).toContain("No outside sources are configured");expect(markdown).toContain("read_crm_history");@@ -81,7 +106,7 @@ describe("the capability briefing", () => {it("lists what is on and what is off, separately", () => {process.env.RAPIDAPI_KEY = "key";- const markdown = capabilitiesMarkdown();+ const markdown = markdownFor(capabilitiesFrom(null));expect(markdown).toContain("Available:");expect(markdown).toContain("LinkedIn");@@ -89,9 +114,22 @@ describe("the capability briefing", () => {expect(markdown).toContain("Web research");});+ it("counts a stored Context key as configured", () => {+ process.env.RAPIDAPI_KEY = "key";++ const markdown = markdownFor(capabilitiesFrom("ctx"));++ expect(markdown).toContain("Company brand data");+ expect(markdown.indexOf("Company brand data")).toBeLessThan(+ markdown.indexOf("Not configured here"),+ );+ });+it("does not warn about missing sources when everything is on", () => {for (const key of KEYS) process.env[key] = "key";- expect(capabilitiesMarkdown()).not.toContain("Not configured here");+ expect(markdownFor(capabilitiesFrom("ctx"))).not.toContain(+ "Not configured here",+ );});});diff --git a/apps/agent/test/preamble.integration.spec.ts b/apps/agent/test/preamble.integration.spec.tsindex ff108308..c47b71aa 100644--- a/apps/agent/test/preamble.integration.spec.ts+++ b/apps/agent/test/preamble.integration.spec.ts@@ -216,7 +216,7 @@ describe("sessionPreamble", () => {describe("every session is told who we are", () => {it("ends each preamble with the same account of us", async () => {- const expected = composeClosing(await identity());+ const expected = await composeClosing(await identity());for (const { markdown } of [await contactPreamble(paulaId, rep),diff --git a/apps/agent/test/verify-key.spec.ts b/apps/agent/test/verify-key.spec.tsnew file mode 100644index 00000000..d942622f--- /dev/null+++ b/apps/agent/test/verify-key.spec.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "bun:test";+import { APIError } from "context.dev/core/error";+import { classifyKey } from "../agent/lib/context-dev";++const answered = (status: number, code?: string) =>+ new APIError(+ status,+ code ? { error_code: code } : undefined,+ undefined,+ new Headers(),+ );++describe("checking a Context key", () => {+ it("rejects only the answer that means the key is wrong", () => {+ const check = classifyKey(answered(401));++ expect(check.outcome).toBe("invalid");+ expect(check.outcome === "invalid" && check.reason).toContain(+ "did not recognise",+ );+ });++ it("accepts the refusal of the probe itself", () => {+ expect(classifyKey(answered(422, "FREE_EMAIL_DETECTED")).outcome).toBe(+ "valid",+ );+ });++ it("accepts a key that authenticated but is out of quota or off-plan", () => {+ expect(classifyKey(answered(403, "USAGE_EXCEEDED")).outcome).toBe("valid");+ expect(classifyKey(answered(403, "FORBIDDEN")).outcome).toBe("valid");+ });++ it("accepts a key when Context itself is having a bad day", () => {+ for (const status of [429, 500, 502, 503]) {+ expect(classifyKey(answered(status)).outcome).toBe("valid");+ }+ });++ it("cannot tell when the request never reached Context", () => {+ const check = classifyKey(new Error("connect ECONNREFUSED"));++ expect(check.outcome).toBe("unknown");+ expect(check.outcome === "unknown" && check.reason).toContain(+ "ECONNREFUSED",+ );+ });++ it("cannot tell when the error carries no status at all", () => {+ expect(+ classifyKey(new APIError(undefined, undefined, "aborted", new Headers()))+ .outcome,+ ).toBe("unknown");+ });++ it("never reports a bare network failure as a bad key", () => {+ for (const error of [+ new Error("The operation timed out."),+ new TypeError("fetch failed"),+ "a string nobody expected",+ ]) {+ expect(classifyKey(error).outcome).not.toBe("invalid");+ }+ });+});diff --git a/apps/agent/test/workspace.spec.ts b/apps/agent/test/workspace.spec.tsindex a3d798e5..13adb255 100644--- a/apps/agent/test/workspace.spec.ts+++ b/apps/agent/test/workspace.spec.ts@@ -86,8 +86,8 @@ describe("who we are", () => {});describe("every session is told who we are", () => {- it("carries the block in front of the capabilities", () => {- const closing = composeClosing(us);+ it("carries the block in front of the capabilities", async () => {+ const closing = await composeClosing(us);expect(closing).toContain("## Who we are");expect(closing.indexOf("## Who we are")).toBeLessThan(@@ -95,9 +95,9 @@ describe("every session is told who we are", () => {);});- it("degrades to the capabilities alone", () => {- expect(composeClosing(null)).not.toContain("## Who we are");- expect(composeClosing(null)).toContain("## What you can use here");+ it("degrades to the capabilities alone", async () => {+ expect(await composeClosing(null)).not.toContain("## Who we are");+ expect(await composeClosing(null)).toContain("## What you can use here");});});diff --git a/apps/agent/turbo.json b/apps/agent/turbo.jsonindex 3ecb99b6..25049716 100644--- a/apps/agent/turbo.json+++ b/apps/agent/turbo.json@@ -16,7 +16,6 @@"AGENT_BRIDGE_SECRET","AI_GATEWAY_API_KEY","BLOB_READ_WRITE_TOKEN",- "CONTEXT_DEV_API_KEY","DATABASE_URL","GITHUB_TOKEN","PERPLEXITY_API_KEY",diff --git a/apps/api/.scratch/existing.ts b/apps/api/.scratch/existing.tsnew file mode 100644index 00000000..16f1b360--- /dev/null+++ b/apps/api/.scratch/existing.ts@@ -0,0 +1,16 @@+import "@crm/env/load";+import { db } from "@crm/db";+import { readContextDevKey } from "@crm/db/settings";++// Simulate an existing deployment: key in the environment, nothing in the row.+await db.appSetting.upsert({+ where: { id: "app" },+ create: { id: "app", contextDevApiKey: null },+ update: { contextDevApiKey: null },+});++console.log("env var set? ", Boolean(process.env.CONTEXT_DEV_API_KEY?.trim()));+console.log("key the app finds ", await readContextDevKey(db));+console.log("=> researchKey.configured would be false, so the proxy gates everyone.");++await db.$disconnect();diff --git a/apps/api/.scratch/verify.ts b/apps/api/.scratch/verify.tsnew file mode 100644index 00000000..6b96aa4e--- /dev/null+++ b/apps/api/.scratch/verify.ts@@ -0,0 +1,19 @@+import "@crm/env/load";+import { ResearchKeyService } from "../src/agent/research-key.service";++const service = new ResearchKeyService();+const real = process.env.CONTEXT_DEV_API_KEY?.trim() ?? "";++console.log(+ "bad key ->",+ JSON.stringify(await service.verify("ctx_nope_not_real_key")),+);+console.log("real key ->", JSON.stringify(await service.verify(real)));++const secret = process.env.AGENT_BRIDGE_SECRET;+delete process.env.AGENT_BRIDGE_SECRET;+console.log("no bridge ->", JSON.stringify(await service.verify(real)));+process.env.AGENT_BRIDGE_SECRET = secret;++process.env.AGENT_URL = "http://127.0.0.1:59999";+console.log("agent down ->", JSON.stringify(await service.verify(real)));diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.tsindex 0d3c481d..e82b6d23 100644--- a/apps/api/src/agent/agent-trigger.service.ts+++ b/apps/api/src/agent/agent-trigger.service.ts@@ -2,6 +2,7 @@ import type { Db } from "@crm/db";import { PRIORITY } from "@crm/db/agent-tasks";import { Injectable, Logger } from "@nestjs/common";import { InjectDatabase } from "../database/database.constants";+import { bridge } from "./bridge";const POKE_TIMEOUT_MS = 2_000;@@ -192,10 +193,8 @@ export class AgentTriggerService {}private poke(): void {- const secret = process.env.AGENT_BRIDGE_SECRET?.trim();- if (!secret) return;-- const base = process.env.AGENT_URL?.trim() || "http://127.0.0.1:2000";+ const agent = bridge();+ if (!agent) return;const missed = (error: unknown) => {this.logger.debug({@@ -205,9 +204,9 @@ export class AgentTriggerService {};try {- void fetch(new URL("/internal/crm/dispatch", base), {+ void fetch(agent.url("/internal/crm/dispatch"), {method: "POST",- headers: { authorization: `Bearer ${secret}` },+ headers: { authorization: `Bearer ${agent.secret}` },signal: AbortSignal.timeout(POKE_TIMEOUT_MS),}).catch(missed);} catch (error) {diff --git a/apps/api/src/agent/agent.module.ts b/apps/api/src/agent/agent.module.tsindex fb1c4067..d88c9d59 100644--- a/apps/api/src/agent/agent.module.ts+++ b/apps/api/src/agent/agent.module.ts@@ -1,9 +1,10 @@import { Module } from "@nestjs/common";import { AgentQueueService } from "./agent-queue.service";import { AgentTriggerService } from "./agent-trigger.service";+import { ResearchKeyService } from "./research-key.service";@Module({- providers: [AgentTriggerService, AgentQueueService],- exports: [AgentTriggerService, AgentQueueService],+ providers: [AgentTriggerService, AgentQueueService, ResearchKeyService],+ exports: [AgentTriggerService, AgentQueueService, ResearchKeyService],})export class AgentModule {}diff --git a/apps/api/src/agent/bridge.ts b/apps/api/src/agent/bridge.tsnew file mode 100644index 00000000..a8c961c3--- /dev/null+++ b/apps/api/src/agent/bridge.ts@@ -0,0 +1,20 @@+const DEFAULT_AGENT_URL = "http://127.0.0.1:2000";++export interface Bridge {+ url(path: string): URL;+ secret: string;+}++/**+ * `AGENT_BRIDGE_SECRET` unset means there is no bridge, not an open one — the+ * same rule the rep bridge and the dispatch poke already follow. Every caller+ * has to say what it does without the agent.+ */+export function bridge(): Bridge | null {+ const secret = process.env.AGENT_BRIDGE_SECRET?.trim();+ if (!secret) return null;++ const base = process.env.AGENT_URL?.trim() || DEFAULT_AGENT_URL;++ return { url: (path) => new URL(path, base), secret };+}diff --git a/apps/api/src/agent/research-key.service.ts b/apps/api/src/agent/research-key.service.tsnew file mode 100644index 00000000..fd9e3edb--- /dev/null+++ b/apps/api/src/agent/research-key.service.ts@@ -0,0 +1,82 @@+import { Injectable, Logger } from "@nestjs/common";+import { bridge } from "./bridge";++const VERIFY_TIMEOUT_MS = 20_000;++export type KeyCheck =+ | { outcome: "valid" }+ | { outcome: "invalid"; reason: string }+ | { outcome: "unknown"; reason: string };++/**+ * Checking a Context key means calling Context, and a vendor client in this+ * process is the thing `docs/api.md` forbids. So the agent — which owns that+ * client, and the one place that knows a 401 from a 429 — is asked, and this+ * service only carries the question there and the answer back.+ */+@Injectable()+export class ResearchKeyService {+ private readonly logger = new Logger(ResearchKeyService.name);++ async verify(apiKey: string): Promise<KeyCheck> {+ const agent = bridge();++ if (!agent) {+ return {+ outcome: "unknown",+ reason:+ "This install has no AGENT_BRIDGE_SECRET, so nothing can check.",+ };+ }++ try {+ const response = await fetch(agent.url("/internal/crm/verify-key"), {+ method: "POST",+ headers: {+ authorization: `Bearer ${agent.secret}`,+ "content-type": "application/json",+ },+ body: JSON.stringify({ apiKey }),+ signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS),+ });++ if (!response.ok) {+ return this.cannotTell(`The agent answered ${response.status}.`);+ }++ const body = (await response.json()) as {+ outcome?: string;+ reason?: string;+ };++ if (body.outcome === "valid") return { outcome: "valid" };++ if (body.outcome === "invalid") {+ return {+ outcome: "invalid",+ reason:+ typeof body.reason === "string" && body.reason+ ? body.reason+ : "Context did not recognise that API key.",+ };+ }++ return this.cannotTell(+ typeof body.reason === "string" ? body.reason : "No answer.",+ );+ } catch (error) {+ return this.cannotTell(+ error instanceof Error ? error.message : String(error),+ );+ }+ }++ private cannotTell(reason: string): KeyCheck {+ this.logger.warn({+ message: "Could not check the Context key; saving it unverified",+ reason,+ });++ return { outcome: "unknown", reason };+ }+}diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.tsindex 6719a1f0..499b12df 100644--- a/apps/api/src/generated/server.ts+++ b/apps/api/src/generated/server.ts@@ -20,7 +20,7 @@ import { conversationListInput, conversationEventsInput, conversationSaveInput,import { dashboardSummaryInput } from "../dashboard/dashboard.contracts";import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput } from "../deals/deals.contracts";import { setAutoCreateInput, suppressDomainInput, threadInput, calendarEventInput } from "../google/google.contracts";-import { setAgentModelInput } from "../settings/settings.contracts";+import { setAgentModelInput, setResearchKeyInput } from "../settings/settings.contracts";import { ssoProviderListInput, registerSsoProviderInput, deleteSsoProviderInput } from "../sso/sso.contracts";import { memberListInput, updateWorkspaceInput, setMemberRoleInput } from "../workspace/workspace.contracts";import type { ActivitiesRouter } from "../activities/activities.router";@@ -179,7 +179,12 @@ const appRouter = t.router({.query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["modelCatalog"]>>),setAgentModel: publicProcedure.input(setAgentModelInput)- .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["setAgentModel"]>>)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["setAgentModel"]>>),+ researchKey: publicProcedure+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["researchKey"]>>),+ setResearchKey: publicProcedure+ .input(setResearchKeyInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<SettingsRouter["setResearchKey"]>>)}),sso: t.router({signInOptions: publicProcedurediff --git a/apps/api/src/settings/settings.contracts.ts b/apps/api/src/settings/settings.contracts.tsindex d8c7a4c5..bf951a31 100644--- a/apps/api/src/settings/settings.contracts.ts+++ b/apps/api/src/settings/settings.contracts.ts@@ -5,3 +5,17 @@ export const setAgentModelInput = z.object({});export type SetAgentModelInput = z.infer<typeof setAgentModelInput>;++export const setResearchKeyInput = z.object({+ apiKey: z+ .string()+ .trim()+ .min(8, "That is too short to be an API key.")+ .max(500)+ .refine(+ (value) => !/\s/.test(value),+ "An API key has no spaces in it. Paste the whole key on its own.",+ ),+});++export type SetResearchKeyInput = z.infer<typeof setResearchKeyInput>;diff --git a/apps/api/src/settings/settings.module.ts b/apps/api/src/settings/settings.module.tsindex 4465856f..8aaadaa6 100644--- a/apps/api/src/settings/settings.module.ts+++ b/apps/api/src/settings/settings.module.ts@@ -1,11 +1,12 @@import { Module } from "@nestjs/common";+import { AgentModule } from "../agent/agent.module";import { TrpcModule } from "../trpc/trpc.module";import { ModelCatalogService } from "./model-catalog.service";import { SettingsRouter } from "./settings.router";import { SettingsService } from "./settings.service";@Module({- imports: [TrpcModule],+ imports: [TrpcModule, AgentModule],providers: [ModelCatalogService, SettingsService, SettingsRouter],exports: [SettingsService],})diff --git a/apps/api/src/settings/settings.router.ts b/apps/api/src/settings/settings.router.tsindex cdfc1681..f4d56bf6 100644--- a/apps/api/src/settings/settings.router.ts+++ b/apps/api/src/settings/settings.router.ts@@ -2,7 +2,7 @@ import { Inject } from "@nestjs/common";import { Input, Mutation, Query, Router, UseMiddlewares } from "nestjs-trpc";import type { z } from "zod";import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";-import { setAgentModelInput } from "./settings.contracts";+import { setAgentModelInput, setResearchKeyInput } from "./settings.contracts";import { SettingsService } from "./settings.service";@Router({ alias: "settings" })@@ -26,4 +26,14 @@ export class SettingsRouter {async setAgentModel(@Input() input: z.infer<typeof setAgentModelInput>) {return this.settings.setAgentModel(input.modelId);}++ @Query()+ async researchKey() {+ return this.settings.researchKey();+ }++ @Mutation({ input: setResearchKeyInput })+ async setResearchKey(@Input() input: z.infer<typeof setResearchKeyInput>) {+ return this.settings.setResearchKey(input.apiKey);+ }}diff --git a/apps/api/src/settings/settings.service.ts b/apps/api/src/settings/settings.service.tsindex 6e00825b..22e345fd 100644--- a/apps/api/src/settings/settings.service.ts+++ b/apps/api/src/settings/settings.service.ts@@ -1,10 +1,14 @@import type { Db } from "@crm/db";import {DEFAULT_AGENT_MODEL,+ maskKey,readAgentModel,+ readContextDevKey,writeAgentModel,+ writeContextDevKey,} from "@crm/db/settings";import { BadRequestException, Injectable, Logger } from "@nestjs/common";+import { ResearchKeyService } from "../agent/research-key.service";import { InjectDatabase } from "../database/database.constants";import {type CatalogModel,@@ -24,6 +28,11 @@ export interface ModelCatalogResult {available: boolean;}+export interface ResearchKeySettings {+ configured: boolean;+ hint: string | null;+}+@Injectable()export class SettingsService {private readonly logger = new Logger(SettingsService.name);@@ -31,6 +40,7 @@ export class SettingsService {constructor(@InjectDatabase() private readonly db: Db,private readonly catalog: ModelCatalogService,+ private readonly researchKeys: ResearchKeyService,) {}async agentModel(): Promise<AgentModelSettings> {@@ -85,4 +95,27 @@ export class SettingsService {const models = await this.catalog.models();return { models: models ?? [], available: models !== null };}++ async researchKey(): Promise<ResearchKeySettings> {+ const key = await readContextDevKey(this.db);++ return { configured: key !== null, hint: key ? maskKey(key) : null };+ }++ async setResearchKey(apiKey: string): Promise<ResearchKeySettings> {+ const check = await this.researchKeys.verify(apiKey);++ if (check.outcome === "invalid") {+ throw new BadRequestException(check.reason);+ }++ await writeContextDevKey(this.db, apiKey);++ this.logger.log({+ message: "Context key saved",+ verified: check.outcome === "valid",+ });++ return this.researchKey();+ }}diff --git a/apps/app/app/(app)/settings/page.tsx b/apps/app/app/(app)/settings/page.tsxindex c9e00798..4e629157 100644--- a/apps/app/app/(app)/settings/page.tsx+++ b/apps/app/app/(app)/settings/page.tsx@@ -11,6 +11,7 @@ import { requireSession } from "@/lib/session";import { HydrateClient } from "@/lib/trpc/hydrate";import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";import { AgentModel } from "./agent-model";+import { ResearchKey } from "./research-key";import { WorkspaceForm } from "./workspace-form";export const metadata: Metadata = {@@ -27,6 +28,7 @@ export default async function GeneralSettingsPage() {queryClient.prefetchQuery(trpc.workspace.get.queryOptions()),queryClient.prefetchQuery(trpc.settings.agentModel.queryOptions()),queryClient.prefetchQuery(trpc.settings.modelCatalog.queryOptions()),+ queryClient.prefetchQuery(trpc.settings.researchKey.queryOptions()),]);return (@@ -44,6 +46,7 @@ export default async function GeneralSettingsPage() {<HydrateClient><div className="flex max-w-3xl flex-col gap-6"><WorkspaceForm />+ <ResearchKey /><AgentModel /></div></HydrateClient>diff --git a/apps/app/app/(app)/settings/research-key.tsx b/apps/app/app/(app)/settings/research-key.tsxnew file mode 100644index 00000000..3c5dab1a--- /dev/null+++ b/apps/app/app/(app)/settings/research-key.tsx@@ -0,0 +1,120 @@+"use client";++import { CONTEXT_DEV_SIGNUP_URL } from "@crm/db/settings";+import { Button } from "@crm/ui/components/button";+import {+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@crm/ui/components/card";+import {+ Field,+ FieldDescription,+ FieldGroup,+ FieldLabel,+} from "@crm/ui/components/field";+import { Input } from "@crm/ui/components/input";+import { Spinner } from "@crm/ui/components/spinner";+import { StatusIndicator } from "@crm/ui/components/status-indicator";+import { useMutation, useQuery } from "@tanstack/react-query";+import { useId, useState } from "react";+import { toast } from "sonner";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";++export function ResearchKey() {+ const trpc = useTRPC();+ const cache = useCrmCache();++ const keyId = useId();+ const [draft, setDraft] = useState("");++ const key = useQuery(trpc.settings.researchKey.queryOptions());++ const save = useMutation(+ trpc.settings.setResearchKey.mutationOptions({+ onSuccess: async () => {+ await cache.settings();+ setDraft("");+ toast.success("Context API key saved.");+ },+ onError: (error) => toast.error(error.message),+ }),+ );++ if (!key.data) return null;++ const { configured, hint } = key.data;++ return (+ <Card>+ <CardHeader>+ <CardTitle>Company research</CardTitle>+ <CardDescription>+ Enter your Context API key so our agents can research every company in+ the CRM.+ </CardDescription>++ <CardAction>+ <Button+ type="submit"+ form="research-key"+ disabled={save.isPending || draft.trim() === ""}+ >+ {save.isPending ? <Spinner data-icon="inline-start" /> : null}+ {configured ? "Replace key" : "Save key"}+ </Button>+ </CardAction>+ </CardHeader>++ <CardContent>+ <form+ id="research-key"+ onSubmit={(event) => {+ event.preventDefault();+ save.mutate({ apiKey: draft.trim() });+ }}+ >+ <FieldGroup>+ <Field>+ <div className="flex items-center justify-between gap-3">+ <FieldLabel htmlFor={keyId}>Context API key</FieldLabel>+ <StatusIndicator+ size="sm"+ tone={configured ? "success" : "warning"}+ label={configured ? "Connected" : "Not connected"}+ />+ </div>+ <Input+ id={keyId}+ type="password"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ placeholder={hint ?? "Paste the key"}+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ disabled={save.isPending}+ />+ <FieldDescription>+ Don't have a Context API key?{" "}+ <a+ href={CONTEXT_DEV_SIGNUP_URL}+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-4 hover:text-foreground"+ >+ Sign up here+ </a>+ </FieldDescription>+ </Field>+ </FieldGroup>+ </form>+ </CardContent>+ </Card>+ );+}diff --git a/apps/app/app/(auth)/onboarding/onboarding-form.tsx b/apps/app/app/(auth)/onboarding/onboarding-form.tsxindex 4bea2fef..5801a375 100644--- a/apps/app/app/(auth)/onboarding/onboarding-form.tsx+++ b/apps/app/app/(auth)/onboarding/onboarding-form.tsx@@ -32,7 +32,7 @@ export function OnboardingForm({ placeholder }: { placeholder: string }) {trpc.workspace.update.mutationOptions({onSuccess: () => {router.refresh();- router.replace("/");+ router.replace("/onboarding/research");},onError: (error) => toast.error(error.message),}),diff --git a/apps/app/app/(auth)/onboarding/research/page.tsx b/apps/app/app/(auth)/onboarding/research/page.tsxnew file mode 100644index 00000000..74babd31--- /dev/null+++ b/apps/app/app/(auth)/onboarding/research/page.tsx@@ -0,0 +1,23 @@+import type { Metadata } from "next";+import { AuthHeading, AuthShell } from "@/components/auth-shell";+import { requireGoogleAccess } from "@/lib/session";+import { ResearchForm } from "./research-form";++export const metadata: Metadata = {+ title: "Research key",+};++export default async function ResearchKeyPage() {+ await requireGoogleAccess();++ return (+ <AuthShell>+ <AuthHeading+ title="Level up your CRM data"+ description="Power your research agent with Context to research every company added to your CRM."+ />++ <ResearchForm />+ </AuthShell>+ );+}diff --git a/apps/app/app/(auth)/onboarding/research/research-form.tsx b/apps/app/app/(auth)/onboarding/research/research-form.tsxnew file mode 100644index 00000000..1833e507--- /dev/null+++ b/apps/app/app/(auth)/onboarding/research/research-form.tsx@@ -0,0 +1,92 @@+"use client";++import { CONTEXT_DEV_SIGNUP_URL } from "@crm/db/settings";+import { Button } from "@crm/ui/components/button";+import {+ Field,+ FieldDescription,+ FieldGroup,+ FieldLabel,+} from "@crm/ui/components/field";+import { Input } from "@crm/ui/components/input";+import { Spinner } from "@crm/ui/components/spinner";+import { useMutation } from "@tanstack/react-query";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useId } from "react";+import { toast } from "sonner";+import { RESEARCH_SKIP_PATH } from "@/lib/onboarding";+import { useTRPC } from "@/lib/trpc/client";++export function ResearchForm() {+ const trpc = useTRPC();+ const router = useRouter();++ const keyId = useId();++ const save = useMutation(+ trpc.settings.setResearchKey.mutationOptions({+ onSuccess: () => {+ router.refresh();+ router.replace("/");+ },+ onError: (error) => toast.error(error.message),+ }),+ );++ return (+ <form+ onSubmit={(event) => {+ event.preventDefault();++ const form = new FormData(event.currentTarget);++ save.mutate({ apiKey: String(form.get("apiKey") ?? "").trim() });+ }}+ className="flex flex-col gap-6"+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor={keyId}>Context API key</FieldLabel>+ <Input+ id={keyId}+ name="apiKey"+ type="password"+ placeholder="Paste the key"+ autoComplete="off"+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ autoFocus+ required+ />+ <FieldDescription>+ Don't have a Context API key?{" "}+ <a+ href={CONTEXT_DEV_SIGNUP_URL}+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-4 hover:text-foreground"+ >+ Sign up here+ </a>+ </FieldDescription>+ </Field>+ </FieldGroup>++ <div className="flex flex-col items-center gap-3">+ <Button type="submit" disabled={save.isPending} className="w-full">+ {save.isPending ? <Spinner data-icon="inline-start" /> : null}+ Continue+ </Button>++ <Link+ href={RESEARCH_SKIP_PATH}+ className="text-muted-foreground text-xxs underline underline-offset-4 hover:text-foreground"+ >+ Skip+ </Link>+ </div>+ </form>+ );+}diff --git a/apps/app/lib/onboarding.ts b/apps/app/lib/onboarding.tsindex 7a797b9a..18924b83 100644--- a/apps/app/lib/onboarding.ts+++ b/apps/app/lib/onboarding.ts@@ -3,48 +3,83 @@ import { API_URL } from "@/lib/env";export const ONBOARDING_PATH = "/onboarding";+export const RESEARCH_PATH = "/onboarding/research";++/**+ * Skip is a link the proxy answers rather than a page, so the gate that would+ * otherwise redirect it back to the form is the same thing that lets it go.+ */+export const RESEARCH_SKIP_PATH = "/onboarding/research/skip";+export const ONBOARDING_COOKIE = "crm.onboarded";+export const RESEARCH_COOKIE = "crm.research";++/**+ * Two cookies because they record two different facts: one caches *a key is+ * saved*, the other *this browser was asked and said not now*. One writer each,+ * and neither can be mistaken for the other.+ */+export const RESEARCH_SKIPPED_COOKIE = "crm.research.skipped";+const COOKIE_MAX_AGE = 60 * 60 * 24 * 365;const GATE_TIMEOUT_MS = 2_000;-export type OnboardingGate = "settled" | "required" | "unknown";+export type Gate = "settled" | "required" | "unknown";-export async function readOnboardingGate(+async function read<T>(request: NextRequest,-): Promise<OnboardingGate> {+ procedure: string,+): Promise<T | null> {const cookie = request.headers.get("cookie");- if (!cookie) return "unknown";+ if (!cookie) return null;try {- const response = await fetch(`${API_URL}/api/trpc/workspace.get`, {+ const response = await fetch(`${API_URL}/api/trpc/${procedure}`, {headers: { cookie },signal: AbortSignal.timeout(GATE_TIMEOUT_MS),});- if (!response.ok) return "unknown";+ if (!response.ok) return null;- const body = (await response.json()) as {- result?: { data?: { onboarded?: boolean; canRename?: boolean } };- };+ const body = (await response.json()) as { result?: { data?: T } };- const workspace = body.result?.data;-- if (typeof workspace?.onboarded !== "boolean") return "unknown";-- return workspace.onboarded || !workspace.canRename ? "settled" : "required";+ return body.result?.data ?? null;} catch {- return "unknown";+ return null;}}-export function settleOnboarding(+export async function readOnboardingGate(request: NextRequest): Promise<Gate> {+ const workspace = await read<{ onboarded?: boolean; canRename?: boolean }>(+ request,+ "workspace.get",+ );++ if (typeof workspace?.onboarded !== "boolean") return "unknown";++ return workspace.onboarded || !workspace.canRename ? "settled" : "required";+}++export async function readResearchGate(request: NextRequest): Promise<Gate> {+ const key = await read<{ configured?: boolean }>(+ request,+ "settings.researchKey",+ );++ if (typeof key?.configured !== "boolean") return "unknown";++ return key.configured ? "settled" : "required";+}++export function settle(request: NextRequest,response: NextResponse,+ name: string,): void {- response.cookies.set(ONBOARDING_COOKIE, "1", {+ response.cookies.set(name, "1", {httpOnly: true,sameSite: "lax",secure: request.nextUrl.protocol === "https:",diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.tsindex 2c6b39fc..320ef94e 100644--- a/apps/app/lib/trpc/cache.ts+++ b/apps/app/lib/trpc/cache.ts@@ -160,7 +160,14 @@ export function useCrmCache(): CrmCache {),settings: (options) =>- run([trpc.settings.agentModel.queryKey()], [], options),+ run(+ [+ trpc.settings.agentModel.queryKey(),+ trpc.settings.researchKey.queryKey(),+ ],+ [],+ options,+ ),workspace: (options) =>run(diff --git a/apps/app/proxy.ts b/apps/app/proxy.tsindex dddaab83..44ab213d 100644--- a/apps/app/proxy.ts+++ b/apps/app/proxy.ts@@ -2,10 +2,16 @@ import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";import { getSessionCookie } from "better-auth/cookies";import { type NextRequest, NextResponse } from "next/server";import {+ type Gate,ONBOARDING_COOKIE,ONBOARDING_PATH,+ RESEARCH_COOKIE,+ RESEARCH_PATH,+ RESEARCH_SKIP_PATH,+ RESEARCH_SKIPPED_COOKIE,readOnboardingGate,- settleOnboarding,+ readResearchGate,+ settle,} from "@/lib/onboarding";const SIGN_IN_PATH = "/sign-in";@@ -25,22 +31,35 @@ export async function proxy(request: NextRequest) {if (isUngated(pathname)) return NextResponse.next();- if (request.cookies.has(ONBOARDING_COOKIE)) return beyondOnboarding(request);+ if (pathname === RESEARCH_SKIP_PATH) {+ return remember(request, home(request), RESEARCH_SKIPPED_COOKIE);+ }- const gate = await readOnboardingGate(request);+ const onboarding = request.cookies.has(ONBOARDING_COOKIE)+ ? "settled"+ : await readOnboardingGate(request);- if (gate === "unknown") return NextResponse.next();+ const settled = onboarding === "settled" ? [ONBOARDING_COOKIE] : [];- if (gate === "required") {- return pathname === ONBOARDING_PATH- ? NextResponse.next()- : NextResponse.redirect(new URL(ONBOARDING_PATH, request.nextUrl));+ if (onboarding === "required") {+ return remember(request, sendTo(ONBOARDING_PATH, request), ...settled);}- const response = beyondOnboarding(request);- settleOnboarding(request, response);+ const skipped = request.cookies.has(RESEARCH_SKIPPED_COOKIE);- return response;+ const research: Gate = skipped+ ? "settled"+ : request.cookies.has(RESEARCH_COOKIE)+ ? "settled"+ : await readResearchGate(request);++ if (research === "required") {+ return remember(request, sendTo(RESEARCH_PATH, request), ...settled);+ }++ if (!skipped && research === "settled") settled.push(RESEARCH_COOKIE);++ return remember(request, past(request, onboarding, research), ...settled);}function isUngated(pathname: string): boolean {@@ -49,10 +68,38 @@ function isUngated(pathname: string): boolean {);}-function beyondOnboarding(request: NextRequest): NextResponse {- return request.nextUrl.pathname === ONBOARDING_PATH- ? NextResponse.redirect(new URL("/", request.nextUrl))- : NextResponse.next();+function home(request: NextRequest): NextResponse {+ return NextResponse.redirect(new URL("/", request.nextUrl));+}++function sendTo(path: string, request: NextRequest): NextResponse {+ return request.nextUrl.pathname === path+ ? NextResponse.next()+ : NextResponse.redirect(new URL(path, request.nextUrl));+}++function past(+ request: NextRequest,+ onboarding: Gate,+ research: Gate,+): NextResponse {+ const done = onboarding === "settled" && research === "settled";++ const setup =+ request.nextUrl.pathname === ONBOARDING_PATH ||+ request.nextUrl.pathname === RESEARCH_PATH;++ return done && setup ? home(request) : NextResponse.next();+}++function remember(+ request: NextRequest,+ response: NextResponse,+ ...cookies: string[]+): NextResponse {+ for (const name of cookies) settle(request, response, name);++ return response;}export const config = {diff --git a/apps/app/test/onboarding-gate.spec.ts b/apps/app/test/onboarding-gate.spec.tsindex 993ab1ad..674ea346 100644--- a/apps/app/test/onboarding-gate.spec.ts+++ b/apps/app/test/onboarding-gate.spec.ts@@ -1,7 +1,13 @@import { afterEach, describe, expect, it } from "bun:test";import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";import { NextRequest } from "next/server";-import { ONBOARDING_COOKIE, readOnboardingGate } from "../lib/onboarding";+import {+ ONBOARDING_COOKIE,+ RESEARCH_COOKIE,+ RESEARCH_SKIPPED_COOKIE,+ readOnboardingGate,+ readResearchGate,+} from "../lib/onboarding";import { proxy } from "../proxy";const SESSION_COOKIE = `${AUTH_COOKIE_PREFIX}.session_token=abc.def`;@@ -12,18 +18,53 @@ afterEach(() => {globalThis.fetch = realFetch;});-function stub(handler: () => Promise<Response>) {- globalThis.fetch = handler as unknown as typeof fetch;+function stub(handler: (url: string) => Promise<Response>) {+ globalThis.fetch = ((input: string | URL | Request) =>+ handler(String(input))) as unknown as typeof fetch;+}++function json(body: unknown, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });}function answerWith(body: unknown, status = 200) {- stub(- async () =>- new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- }),- );+ stub(async () => json(body, status));+}++const workspace = (data: { onboarded: boolean; canRename: boolean }) => ({+ result: { data },+});++const researchKey = (configured: boolean) => ({+ result: { data: { configured, hint: configured ? "••••9876" : null } },+});++/** Answers both gate procedures, counting the calls to each. */+function setup({+ onboarded = true,+ canRename = true,+ configured = true,+}: {+ onboarded?: boolean;+ canRename?: boolean;+ configured?: boolean;+} = {}) {+ const calls = { workspace: 0, research: 0 };++ stub(async (url) => {+ if (url.includes("workspace.get")) {+ calls.workspace += 1;+ return json(workspace({ onboarded, canRename }));+ }++ calls.research += 1;+ return json(researchKey(configured));+ });++ return calls;}function request(pathname: string, cookies: string[] = []) {@@ -38,10 +79,6 @@ function redirectedTo(response: Response): string | null {return location ? new URL(location).pathname : null;}-const workspace = (data: { onboarded: boolean; canRename: boolean }) => ({- result: { data },-});-describe("readOnboardingGate", () => {it("reads the answer out of a plain tRPC envelope", async () => {answerWith(workspace({ onboarded: false, canRename: true }));@@ -79,6 +116,30 @@ describe("readOnboardingGate", () => {});});+describe("readResearchGate", () => {+ it("is settled once a key is saved, and required until then", async () => {+ answerWith(researchKey(true));+ expect(await readResearchGate(request("/", [SESSION_COOKIE]))).toBe(+ "settled",+ );++ answerWith(researchKey(false));+ expect(await readResearchGate(request("/", [SESSION_COOKIE]))).toBe(+ "required",+ );+ });++ it("is unknown rather than required when the API cannot be read", async () => {+ stub(async () => {+ throw new Error("connect ECONNREFUSED");+ });++ expect(await readResearchGate(request("/", [SESSION_COOKIE]))).toBe(+ "unknown",+ );+ });+});+describe("proxy", () => {it("sends a stranger to sign in, and leaves them there", async () => {expect(redirectedTo(await proxy(request("/companies")))).toBe("/sign-in");@@ -87,7 +148,7 @@ describe("proxy", () => {it("ignores a neighbour's cookie from the parent domain", async () => {expect(AUTH_COOKIE_PREFIX).not.toBe("better-auth");- answerWith(workspace({ onboarded: true, canRename: true }));+ setup();expect(redirectedTo(@@ -99,7 +160,7 @@ describe("proxy", () => {});it("gates a signed-in rep who has not answered the form", async () => {- answerWith(workspace({ onboarded: false, canRename: true }));+ setup({ onboarded: false });expect(redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),@@ -107,7 +168,7 @@ describe("proxy", () => {});it("lets the form itself render", async () => {- answerWith(workspace({ onboarded: false, canRename: true }));+ setup({ onboarded: false });expect(redirectedTo(await proxy(request("/onboarding", [SESSION_COOKIE]))),@@ -115,38 +176,45 @@ describe("proxy", () => {});it("asks once, then remembers", async () => {- let calls = 0;- stub(async () => {- calls += 1;- return new Response(- JSON.stringify(workspace({ onboarded: true, canRename: true })),- );- });+ const calls = setup();const first = await proxy(request("/companies", [SESSION_COOKIE]));- const marker = first.cookies.get(ONBOARDING_COOKIE);- expect(marker?.value).toBe("1");- expect(marker?.httpOnly).toBe(true);- expect(calls).toBe(1);+ for (const name of [ONBOARDING_COOKIE, RESEARCH_COOKIE]) {+ const marker = first.cookies.get(name);+ expect(marker?.value).toBe("1");+ expect(marker?.httpOnly).toBe(true);+ }++ expect(calls).toEqual({ workspace: 1, research: 1 });await proxy(- request("/companies", [SESSION_COOKIE, `${ONBOARDING_COOKIE}=1`]),+ request("/companies", [+ SESSION_COOKIE,+ `${ONBOARDING_COOKIE}=1`,+ `${RESEARCH_COOKIE}=1`,+ ]),);- expect(calls).toBe(1);+ expect(calls).toEqual({ workspace: 1, research: 1 });});- it("takes a settled rep off the form", async () => {- answerWith(workspace({ onboarded: true, canRename: true }));+ it("takes a settled rep off both setup pages", async () => {+ setup();expect(redirectedTo(await proxy(request("/onboarding", [SESSION_COOKIE]))),).toBe("/");++ expect(+ redirectedTo(+ await proxy(request("/onboarding/research", [SESSION_COOKIE])),+ ),+ ).toBe("/");});it("never fights /grant-access, which would ping-pong forever", async () => {- answerWith(workspace({ onboarded: false, canRename: true }));+ setup({ onboarded: false });expect(redirectedTo(await proxy(request("/grant-access", [SESSION_COOKIE]))),@@ -154,7 +222,7 @@ describe("proxy", () => {});it("leaves the agent bridge alone", async () => {- answerWith(workspace({ onboarded: false, canRename: true }));+ setup({ onboarded: false });expect(redirectedTo(await proxy(request("/eve/v1/info", [SESSION_COOKIE]))),@@ -170,5 +238,85 @@ describe("proxy", () => {expect(redirectedTo(response)).toBeNull();expect(response.cookies.get(ONBOARDING_COOKIE)).toBeUndefined();+ expect(response.cookies.get(RESEARCH_COOKIE)).toBeUndefined();+ });+});++describe("the research key gate", () => {+ it("sends an onboarded rep with no key to the key form", async () => {+ setup({ configured: false });++ expect(+ redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),+ ).toBe("/onboarding/research");+ });++ it("lets that form render rather than looping onto itself", async () => {+ setup({ configured: false });++ expect(+ redirectedTo(+ await proxy(request("/onboarding/research", [SESSION_COOKIE])),+ ),+ ).toBeNull();+ });++ it("asks the first question first", async () => {+ const calls = setup({ onboarded: false, configured: false });++ expect(+ redirectedTo(await proxy(request("/companies", [SESSION_COOKIE]))),+ ).toBe("/onboarding");++ expect(calls.research).toBe(0);+ });++ it("does not settle the marker for a rep still being asked", async () => {+ setup({ configured: false });++ const response = await proxy(request("/companies", [SESSION_COOKIE]));++ expect(response.cookies.get(RESEARCH_COOKIE)).toBeUndefined();+ });++ it("lets a rep skip, and does not ask that browser again", async () => {+ const calls = setup({ configured: false });++ const skip = await proxy(+ request("/onboarding/research/skip", [SESSION_COOKIE]),+ );++ expect(redirectedTo(skip)).toBe("/");+ expect(skip.cookies.get(RESEARCH_SKIPPED_COOKIE)?.value).toBe("1");+ expect(calls.research).toBe(0);++ expect(+ redirectedTo(+ await proxy(+ request("/companies", [+ SESSION_COOKIE,+ `${RESEARCH_SKIPPED_COOKIE}=1`,+ ]),+ ),+ ),+ ).toBeNull();+ });++ it("does not record a key for a rep who only skipped", async () => {+ setup({ configured: false });++ const response = await proxy(+ request("/companies", [SESSION_COOKIE, `${RESEARCH_SKIPPED_COOKIE}=1`]),+ );++ expect(response.cookies.get(RESEARCH_COOKIE)).toBeUndefined();+ });++ it("remembers the workspace answer even while the key is outstanding", async () => {+ setup({ configured: false });++ const response = await proxy(request("/companies", [SESSION_COOKIE]));++ expect(response.cookies.get(ONBOARDING_COOKIE)?.value).toBe("1");});});diff --git a/docs/agent.md b/docs/agent.mdindex 40a7e7e3..907e5132 100644--- a/docs/agent.md+++ b/docs/agent.md@@ -244,6 +244,31 @@ and `FOR UPDATE SKIP LOCKED`, which already handle it.`AGENT_BRIDGE_SECRET` authorises it, and **unset means the route refuses ratherthan opens**, the same rule the rep bridge follows.+### Checking a key belongs to the person who typed it++`POST /internal/crm/verify-key` is the crm channel's second internal route, and+it exists because the API is not allowed to call Context.dev and this agent+already does. It takes a candidate key, probes with it, and answers `valid`,+`invalid` or `unknown` — no session, no model, no task row, because there is+nothing here to decide.++- **The probe is free and it is chosen to be.** A brand lookup only bills when+ it resolves a brand, and a free-provider address is refused with a documented+ `422` first, so `[email protected]` authenticates without buying anything.+ Do not "improve" this to a real domain: that is ten credits every time+ somebody saves a key, including every time they correct a typo.+- **`classifyKey` rejects on `401` and nothing else.** Every other status came+ back *after* the key was accepted, so it says something about the plan, the+ quota or Context's afternoon — not about the key. Treating a `429` as a bad+ key would refuse a perfectly good one at the worst possible moment.+- **It is the candidate key, never the stored one.** `verifyKey` builds a+ throwaway client from the argument, so checking a new key cannot be confused+ with exercising the one already saved.++The API's half is `ResearchKeyService`, and an `unknown` answer there saves the+key anyway — see+[the environment rules](./environment.md#the-context-key-is-asked-for-not-configured).+### Catching up what was missedEnrichment is queued when a record is created, so anything created before a@@ -342,6 +367,21 @@ help" result — checked **before** the research budget is charged.A missing key removes a place to look. It is never an error, and it must neverthrow.+**Not all of them are environment variables, which is why `capabilities()` is+async.** The Context.dev key is a row a rep can set on Settings → General — see+[the environment rules](./environment.md#the-context-key-is-asked-for-not-configured)+— so the answer to *what can I use here* now involves a read, and `enabled()`+and `capabilitiesMarkdown()` are awaited with it. `capabilitiesFrom()` and+`markdownFor()` are the pure halves, which is what keeps+`test/capabilities.spec.ts` a unit test rather than something that reports a+different answer depending on what the developer happens to have saved locally.++`contextDevKey()` is the only resolver, and `lib/context-dev.ts` builds its+client from it rather than from `process.env` — memoised on the key string, so+replacing the key swaps the client and nothing else does. There is no cache in+front of the read: a key saved in the browser applies to the next vendor call,+not the next deploy.+## Budget, and deciding what to do next- `lib/focus.ts` holds the per-session budget in `defineState`. Every vendordiff --git a/docs/api.md b/docs/api.mdindex 0a333d9d..824e31a8 100644--- a/docs/api.md+++ b/docs/api.md@@ -162,6 +162,38 @@ called, who works here, and what do we sell — and for nothing else.request through without writing the cookie. The alternative is an installthat cannot reach its own API redirecting every request to a form thatcannot be submitted.+- **There is a second gate behind the first**, `/onboarding/research`, which+ asks for the Context API key that gives the agent somewhere to look — see+ [the environment rules](./environment.md#the-context-key-is-asked-for-not-configured).+ It is the same shape as the onboarding gate and shares its machinery: a read+ (`settings.researchKey`), a `required`/`settled`/`unknown` answer, an httpOnly+ marker so it is asked once per browser, and fail-open on an unreachable API.+ - **The order is fixed and the second read is not made early.** A rep who has+ not named the workspace goes to `/onboarding` and `settings.researchKey` is+ never called — there is no point asking the second question while the first+ is open, and the test pins that the call count stays at zero.+ - **A settled workspace is remembered even while the key is outstanding.**+ The marker is written onto the *redirect* to the key form, so the workspace+ is not re-read on every request during the window a rep is being asked+ something else.+ - **Skip is a link the proxy answers, not a page.** `/onboarding/research/skip`+ never renders: the proxy recognises the path, writes the marker and sends+ them home. A route handler would have needed ungating — the gate would+ otherwise redirect the skip link back to the form it is trying to leave —+ and ungating is how you get a hole rather than a door.+ - **Two cookies, because they are two different facts.** `crm.research` caches+ *a key is saved*; `crm.research.skipped` records *this browser was asked and+ said not now*. Collapsing them into one would mean the skip link wrote a+ cookie claiming a key exists, and the proxy is careful not to: it only+ writes `crm.research` when the API actually said so.+ - **Settings → General is the same write.** `settings.setResearchKey` is+ posted by both, so there is one write path and no second opinion about what+ a valid key looks like — including the check: that mutation asks the agent+ whether Context recognises the key and refuses to save one that comes back+ `401`. See+ [the environment rules](./environment.md#the-context-key-is-asked-for-not-configured)+ for why the call is the agent's to make and why a check that cannot be made+ still saves.- **The name arrives as a placeholder, not as an answer.** A workspace iscreated as `DEFAULT_WORKSPACE_NAME` — the literal string `CRM` — and the fieldis empty with that behind it. It used to be derived from the sign-in domain,diff --git a/docs/environment.md b/docs/environment.mdindex a89ca8d8..f3d88fff 100644--- a/docs/environment.md+++ b/docs/environment.md@@ -177,11 +177,14 @@ Two sharp edges:Every outside source the agent can reach is optional, and it is designed to runwith none of them. A missing key removes a place to look; it is never an error.+The company research key is the exception and it is **not in this table**,+because it is not a variable at all — see+[the next section](#the-context-key-is-asked-for-not-configured).+| Variable | What it adds || --- | --- || `PERPLEXITY_API_KEY` | Open-web research with citations, and the search that finds a LinkedIn slug || `RAPIDAPI_KEY` | LinkedIn profiles via LinkDAPI — name, title, employer, tenure |-| `CONTEXT_DEV_API_KEY` | Company logo, industry, location and socials from a domain || `GITHUB_TOKEN` | Raises the GitHub rate limit from 60/hour when matching profiles || `BLOB_READ_WRITE_TOKEN` | Mirrors every logo and profile picture into Vercel Blob rather than linking them. Read by the API and the seed too — see below || `AI_GATEWAY_API_KEY` | The model. Not needed on Vercel, where OIDC handles it |@@ -194,6 +197,60 @@ agent plans around what it actually has, and gives the tools a sharedresearch budget is charged, so an install without a key does not pay for thediscovery on every contact.+### The Context key is asked for, not configured++**`CONTEXT_DEV_API_KEY` is not a variable in this repo, and adding one back+would be a second answer to a question that already has one.** Nothing reads it+— not `.env.example`, not `env.validation.ts`, not any `turbo.json`. The key+lives in `AppSetting` beside the agent's model, it is asked for at+`/onboarding/research`, and **Settings → General** changes it afterwards.++Same reason as [SSO](./api.md#sso-is-a-row-not-a-deployment): an admin who+cannot redeploy cannot set an environment variable. It goes further than SSO+does, because this is not a key an install can sensibly do without — it decides+whether a company arrives as itself or as a grey square with its initials in+it — so [the proxy asks for it](./api.md#the-gate-is-proxyts-and-it-is-answered-once-per-browser)+rather than leaving it to be discovered on a settings page nobody visits.++- **`readContextDevKey` in [`@crm/db/settings`](../packages/db/src/settings.ts)+ is the only reader**, and it reads one column. Everything downstream —+ `contextDevKey()` in the agent's `capabilities.ts`, the client in+ `lib/context-dev.ts`, the API's `settings.researchKey` — goes through it, so+ there is exactly one place that knows where the key is kept.+- **It is read live, not at boot.** There is no cache in front of it, so a key+ pasted into the settings page applies to the very next vendor call rather than+ to the next deployment. Each read is one indexed row in front of a lookup that+ is about to make an HTTP request anyway.+- **A database that cannot be read is a capability that is off**, not an+ exception. `contextDevKey()` logs and returns null, because a missing source+ must never throw — the rule at the top of this section, and the reason the+ agent keeps running against everything else it has.+- **The key is never read back.** The API returns whether one is set and its+ last four characters, and nothing returns the key itself. Same rule as an SSO+ client secret.+- **A wrong key is refused at the point it is typed, and the agent is what+ checks it.** Checking means calling Context, and [a vendor client in the API+ is a bug](./api.md#intelligence-never-lives-in-the-api) — so+ `settings.setResearchKey` asks the agent over the bridge+ (`POST /internal/crm/verify-key`) and only writes the row if the answer is not+ *invalid*. The agent already owns the client, the error classification and the+ key, so nothing about Context.dev is learned twice.+ - **The probe costs nothing.** A brand lookup only bills when it resolves a+ brand, and a free-provider address is refused with a documented `422`+ before any resolution — so `[email protected]` reaches Context, proves+ the key authenticates, and is never billed. Measured at about half a second.+ - **`401` is the only answer that means the key is wrong.** A `403` about the+ plan, a `422` refusing the probe, a `429`, a `500` — all of those were+ served *after* the key authenticated, so the key is good and only the probe+ was refused. `classifyKey` in `lib/context-dev.ts` holds that rule and+ `test/verify-key.spec.ts` pins every branch of it.+ - **A check that cannot be made is not a failed check.** No+ `AGENT_BRIDGE_SECRET`, an agent that is down, a timeout — all return+ `unknown`, and an unknown answer *saves the key* and logs that it went in+ unverified. The alternative is an install whose agent is not up yet being+ unable to finish onboarding, which is a worse failure than an unchecked+ key: the key is still checked by the first task that uses it.+`BLOB_READ_WRITE_TOKEN` is the one entry in that table the agent does not ownalone, which is why it is also declared in `apps/api/src/config/env.validation.ts`and in `apps/api/turbo.json`. The API writes two pictures of its own — thediff --git a/docs/images/context.png b/docs/images/context.pngnew file mode 100644index 00000000..c2557e15Binary files /dev/null and b/docs/images/context.png differdiff --git a/packages/db/prisma/migrations/20260803220000_context_dev_api_key/migration.sql b/packages/db/prisma/migrations/20260803220000_context_dev_api_key/migration.sqlnew file mode 100644index 00000000..ed92debb--- /dev/null+++ b/packages/db/prisma/migrations/20260803220000_context_dev_api_key/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "appSetting" ADD COLUMN "contextDevApiKey" TEXT;diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex ee9a3ed7..99f028c3 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -618,6 +618,8 @@ model AppSetting {agentModelContextWindow Int?+ contextDevApiKey String?+updatedAt DateTime @updatedAt@@map("appSetting")diff --git a/packages/db/src/settings.ts b/packages/db/src/settings.tsindex 23b979a5..f817528a 100644--- a/packages/db/src/settings.ts+++ b/packages/db/src/settings.ts@@ -46,3 +46,55 @@ export async function writeAgentModel(update: fields,});}++export const CONTEXT_DEV_SIGNUP_URL = "https://link.context.dev/crm";++export const CONTEXT_DEV_DISCOUNT_CODE = "CRM";++export async function readContextDevKey(db: Db): Promise<string | null> {+ const row = await db.appSetting.findUnique({+ where: { id: SETTINGS_ID },+ select: { contextDevApiKey: true },+ });++ return row?.contextDevApiKey?.trim() || null;+}++export async function writeContextDevKey(db: Db, key: string): Promise<void> {+ const contextDevApiKey = key.trim();++ await db.appSetting.upsert({+ where: { id: SETTINGS_ID },+ create: { id: SETTINGS_ID, contextDevApiKey },+ update: { contextDevApiKey },+ });+}++export function maskKey(key: string): string {+ const trimmed = key.trim();+ return trimmed.length > 4 ? `••••${trimmed.slice(-4)}` : "••••";+}++/**+ * The key used to be an environment variable, and an install that still sets+ * one is an install that was working. Moving the answer into a row must not+ * quietly take the capability away and put a setup form in front of everybody,+ * so the first boot after the upgrade adopts what is already there.+ *+ * This is the **only** thing in the repo that reads that variable, it runs once+ * — a filled column is never overwritten — and after it has run the variable is+ * vestigial. It is a migration, not a fallback: nothing consults the+ * environment while answering a request.+ */+export const LEGACY_CONTEXT_DEV_ENV = "CONTEXT_DEV_API_KEY";++export async function adoptLegacyContextDevKey(db: Db): Promise<boolean> {+ const key = process.env[LEGACY_CONTEXT_DEV_ENV]?.trim();++ if (!key) return false;+ if (await readContextDevKey(db)) return false;++ await writeContextDevKey(db, key);++ return true;+}diff --git a/packages/ui/src/styles/globals.css b/packages/ui/src/styles/globals.cssindex 406968eb..f44ac661 100644--- a/packages/ui/src/styles/globals.css+++ b/packages/ui/src/styles/globals.css@@ -187,6 +187,11 @@--font-sans: var(--font-sans);--font-mono: var(--font-mono);++ /* One step below text-xs, for the quiet way out of a form. */+ --text-xxs: 0.6875rem;+ --text-xxs--line-height: 1rem;+--radius-sm: 4px;--radius-md: var(--radius);--radius-lg: 8px;diff --git a/turbo.json b/turbo.jsonindex 3d0f4338..c00c1eb9 100644--- a/turbo.json+++ b/turbo.json@@ -36,7 +36,6 @@"PRISMA_LOG_QUERIES","PERPLEXITY_API_KEY","RAPIDAPI_KEY",- "CONTEXT_DEV_API_KEY","GITHUB_TOKEN","BLOB_READ_WRITE_TOKEN","AI_GATEWAY_API_KEY",