Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat(agent): CMP-1 add sandboxed builder and runner runtimes (#60)

grimd033dbf0a0bc
diff --git a/.env.example b/.env.example
index 8770db78..10c44bb8 100644
--- a/.env.example
+++ b/.env.example
@@ -79,6 +79,10 @@ GOOGLE_CLIENT_SECRET=""
# out on its next minute.
# AGENT_URL="http://127.0.0.1:2000"
+# Port used by the self-hosted Eve service. Hosted runtimes can keep injecting
+# their standard PORT variable instead.
+# AGENT_PORT="2000"
+
# Lets a signed-in rep talk to the agent from the contact sheet.
#
# The browser never calls the agent directly. The app proxies /eve/v1/* on its
diff --git a/AGENTS.md b/AGENTS.md
index acfa8f1b..d361a7d0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -44,3 +44,54 @@ rules and skills you read.
## Design
@docs/design.md
+
+## Median Tasks
+
+Median can use a project-local workspace binding. If this repository has
+`.median/config.json`, run `mdn` commands from inside this repository so the
+correct Median workspace profile is selected. The local config stores only a
+profile name; API keys stay in your user config.
+
+To bind this repository to a workspace:
+
+```
+mdn setup --local
+```
+
+Before starting work, check your assigned tasks:
+
+```
+mdn tasks --agent <your-agent-name>
+```
+
+When picking up a task:
+
+```
+mdn status <TASK-CODE> in_progress --agent <your-agent-name>
+```
+
+When completing a task:
+
+```
+mdn status <TASK-CODE> ready --agent <your-agent-name>
+```
+
+To create a new task:
+
+```
+mdn create --title "Description" --status todo --priority medium --agent <your-agent-name>
+```
+
+## Commit Messages & Pull Requests
+
+Always include the Median task ID in commit messages and PR titles so tasks get marked automatically.
+
+```
+git commit -m "MDN-42 fix: resolve auth token expiry"
+```
+
+For pull requests, include the task ID in the title:
+
+```
+MDN-42 fix: resolve auth token expiry
+```
diff --git a/apps/agent/agent/agent.ts b/apps/agent/agent/agent.ts
index de358c1f..56756af5 100644
--- a/apps/agent/agent/agent.ts
+++ b/apps/agent/agent/agent.ts
@@ -17,4 +17,9 @@ export default defineAgent({
fallback: DEFAULT_AGENT_MODEL.id,
events: { "session.started": () => selectedModel() },
}),
+ limits: {
+ maxInputTokensPerSession: 500_000,
+ maxOutputTokensPerSession: 50_000,
+ sessionTimeoutMs: 30 * 24 * 60 * 60 * 1000,
+ },
});
diff --git a/apps/agent/agent/channels/crm.ts b/apps/agent/agent/channels/crm.ts
index 44d686ac..43faef02 100644
--- a/apps/agent/agent/channels/crm.ts
+++ b/apps/agent/agent/channels/crm.ts
@@ -1,8 +1,19 @@
+import { timingSafeEqual } from "node:crypto";
import { EnrichmentStatus } from "@crm/db";
import { defineChannel, POST } from "eve/channels";
import { verifyKey } from "../lib/context-dev";
+import {
+ builderIdFromToken,
+ dispatchAgentRun,
+ dispatchBuilderSubmission,
+ drainAgentRuns,
+ drainBuilder,
+ failRun,
+ runIdFromToken,
+} from "../lib/custom-agent-dispatch";
import { brief, drainAll, taskAuth } from "../lib/dispatch";
import { settle } from "../lib/enrichment";
+import { finishRun } from "../lib/run-runtime";
import { completeTask, taskSubject } from "../lib/tasks";
const TASK_MARKER = "task:";
@@ -10,8 +21,13 @@ const TASK_MARKER = "task:";
function authorised(request: Request): boolean {
const secret = process.env.AGENT_BRIDGE_SECRET?.trim();
if (!secret) return false;
+ const header = request.headers.get("authorization");
+ if (!header?.startsWith("Bearer ")) return false;
+ const candidate = Buffer.from(header.slice("Bearer ".length));
+ const expected = Buffer.from(secret);
+ if (candidate.length !== expected.length) return false;
- return request.headers.get("authorization") === `Bearer ${secret}`;
+ return timingSafeEqual(candidate, expected);
}
export function taskToken(taskId: string): string {
@@ -47,6 +63,30 @@ export default defineChannel({
return new Response(null, { status: 202 });
}),
+ POST(
+ "/internal/crm/builder-dispatch",
+ async (request, { send, waitUntil }) => {
+ if (!authorised(request)) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ waitUntil(drainBuilder(send));
+ return new Response(null, { status: 202 });
+ },
+ ),
+
+ POST(
+ "/internal/crm/agent-dispatch",
+ async (request, { send, waitUntil }) => {
+ if (!authorised(request)) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ waitUntil(drainAgentRuns(send));
+ return new Response(null, { status: 202 });
+ },
+ ),
+
POST("/internal/crm/verify-key", async (request) => {
if (!authorised(request)) {
return new Response("Unauthorized", { status: 401 });
@@ -71,29 +111,112 @@ export default defineChannel({
],
events: {
+ async "message.completed"(data, channel) {
+ const conversationId = builderIdFromToken(channel.continuationToken);
+ if (!conversationId || !data.message?.trim()) return;
+
+ await import("@crm/db").then(({ db }) =>
+ db.agentConversation.updateMany({
+ where: { id: conversationId, kind: "BUILDER" },
+ data: {
+ lastAssistantAt: new Date(),
+ lastMessageAt: new Date(),
+ messageCount: { increment: 1 },
+ },
+ }),
+ );
+ },
+
async "session.waiting"(_data, channel) {
const taskId = taskFromToken(channel.continuationToken);
- if (!taskId) return;
+ if (taskId) {
+ const subject = await completeTask(taskId, "ran");
+ if (subject) await settle(subject, EnrichmentStatus.COMPLETE);
+ return;
+ }
+
+ const conversationId = builderIdFromToken(channel.continuationToken);
+ if (!conversationId) return;
- const subject = await completeTask(taskId, "ran");
- if (subject) await settle(subject, EnrichmentStatus.COMPLETE);
+ await import("@crm/db").then(({ db }) =>
+ db.agentConversation.updateMany({
+ where: { id: conversationId, kind: "BUILDER" },
+ data: { continuationToken: channel.continuationToken },
+ }),
+ );
},
async "turn.failed"(data, channel) {
const taskId = taskFromToken(channel.continuationToken);
- if (!taskId) return;
-
const reason =
- typeof data === "object" && data && "error" in data
- ? String((data as { error: unknown }).error)
- : "The research turn failed.";
+ typeof data === "object" && data && "message" in data
+ ? String((data as { message: unknown }).message)
+ : "The agent turn failed.";
+
+ if (taskId) {
+ const subject = await taskSubject(taskId);
+ if (subject) await settle(subject, EnrichmentStatus.FAILED, reason);
+ return;
+ }
- const subject = await taskSubject(taskId);
- if (subject) await settle(subject, EnrichmentStatus.FAILED, reason);
+ const runId = runIdFromToken(channel.continuationToken);
+ if (runId) await failRun(runId, "TURN_FAILED", reason);
+ },
+
+ async "session.completed"(_data, channel) {
+ const runId = runIdFromToken(channel.continuationToken);
+ if (!runId) return;
+
+ const { db } = await import("@crm/db");
+ const run = await db.agentRun.findUnique({
+ where: { id: runId },
+ select: { status: true, summary: true, result: true },
+ });
+ if (run?.status === "RUNNING") {
+ await finishRun(runId, {
+ summary: run.summary ?? "The agent run completed.",
+ result: recordOf(run.result),
+ });
+ }
+ },
+
+ async "session.failed"(data, channel) {
+ const conversationId = builderIdFromToken(channel.continuationToken);
+ if (conversationId) {
+ const { db } = await import("@crm/db");
+ await db.agentConversation.updateMany({
+ where: { id: conversationId, kind: "BUILDER" },
+ data: {
+ continuationToken: channel.continuationToken,
+ lastAssistantAt: new Date(),
+ lastMessageAt: new Date(),
+ },
+ });
+ return;
+ }
+
+ const runId = runIdFromToken(channel.continuationToken);
+ if (runId) await failRun(runId, data.code, data.message);
},
},
async receive(input, { send }) {
+ const builderSubmissionId =
+ typeof input.target?.builderSubmissionId === "string"
+ ? input.target.builderSubmissionId
+ : null;
+ if (builderSubmissionId) {
+ assertInternalDispatchAuth(input.auth);
+ return dispatchBuilderSubmission(builderSubmissionId, send);
+ }
+
+ const runId =
+ typeof input.target?.runId === "string" ? input.target.runId : null;
+ if (runId) {
+ assertInternalDispatchAuth(input.auth);
+ return dispatchAgentRun(runId, send);
+ }
+
const taskId =
typeof input.target?.taskId === "string" ? input.target.taskId : null;
@@ -105,3 +228,20 @@ export default defineChannel({
});
},
});
+
+function assertInternalDispatchAuth(value: unknown): void {
+ const auth = recordOf(value);
+ if (
+ auth.authenticator !== "app" ||
+ auth.principalType !== "runtime" ||
+ auth.principalId !== "eve:app"
+ ) {
+ throw new Error("Internal agent dispatch requires Eve app authentication.");
+ }
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
diff --git a/apps/agent/agent/hooks/audit.ts b/apps/agent/agent/hooks/audit.ts
index 0a363768..f096d34c 100644
--- a/apps/agent/agent/hooks/audit.ts
+++ b/apps/agent/agent/hooks/audit.ts
@@ -1,6 +1,8 @@
-import { db } from "@crm/db";
+import { db, type Prisma } from "@crm/db";
import { defineHook } from "eve/hooks";
import { currentFocus } from "../lib/focus";
+import { lockAgentRun } from "../lib/run-state";
+import { attribute, purposeOf } from "../lib/session-purpose";
const CUMULATIVE_DELTAS = new Set(["reasoning.appended"]);
@@ -12,18 +14,30 @@ export default defineHook({
if (!id || CUMULATIVE_DELTAS.has(event.type)) return;
try {
- await db.agentEvent.createMany({
- data: [
- {
- id,
- sessionId: ctx.session.id,
- contactId: currentFocus().contactId,
- type: event.type,
- data: ("data" in event ? (event.data ?? {}) : {}) as object,
- emittedAt: event.meta?.at ? new Date(event.meta.at) : new Date(),
- },
- ],
- skipDuplicates: true,
+ const data = ("data" in event ? (event.data ?? {}) : {}) as object;
+ const emittedAt = event.meta?.at ? new Date(event.meta.at) : new Date();
+ await db.$transaction(async (tx) => {
+ await tx.agentEvent.createMany({
+ data: [
+ {
+ id,
+ sessionId: ctx.session.id,
+ contactId: currentFocus().contactId,
+ type: event.type,
+ data,
+ emittedAt,
+ },
+ ],
+ skipDuplicates: true,
+ });
+
+ const purpose = purposeOf(ctx);
+ if (purpose === "builder") {
+ await persistBuilderLifecycle(tx, event, ctx.session.id, ctx);
+ }
+ if (purpose === "team-agent") {
+ await persistRunEvent(tx, id, event.type, data, emittedAt, ctx);
+ }
});
} catch (error) {
console.warn("[audit] could not record event", {
@@ -34,3 +48,136 @@ export default defineHook({
},
},
});
+
+async function persistBuilderLifecycle(
+ tx: Prisma.TransactionClient,
+ event: { type: string },
+ sessionId: string,
+ ctx: Parameters<typeof purposeOf>[0],
+) {
+ const conversationId = attribute(ctx, "conversationId");
+ if (!conversationId) return;
+
+ if (event.type === "session.started" && isRootSession(ctx)) {
+ await tx.agentConversation.updateMany({
+ where: { id: conversationId, kind: "BUILDER" },
+ data: { sessionId, continuationToken: null },
+ });
+ }
+
+ if (event.type === "message.received") {
+ const submissionId = attribute(ctx, "submissionId");
+ if (submissionId) {
+ await tx.agentConversationSubmission.updateMany({
+ where: { id: submissionId, conversationId },
+ data: { status: "ACCEPTED", acceptedAt: new Date() },
+ });
+ }
+ }
+}
+
+async function persistRunEvent(
+ tx: Prisma.TransactionClient,
+ eventId: string,
+ type: string,
+ data: object,
+ emittedAt: Date,
+ ctx: Parameters<typeof purposeOf>[0] & { session: { id: string } },
+) {
+ const runId = attribute(ctx, "runId");
+ if (!runId) return;
+
+ const run = await lockAgentRun(tx, runId);
+ if (
+ run.status === "SUCCEEDED" ||
+ run.status === "FAILED" ||
+ run.status === "CANCELLED"
+ ) {
+ return;
+ }
+ const existing = await tx.agentRunEvent.findUnique({
+ where: { id: eventId },
+ select: { id: true },
+ });
+ if (existing) return;
+
+ const sequence = run.nextEventSequence + 1;
+ const mayStart =
+ type === "session.started" &&
+ isRootSession(ctx) &&
+ (run.status === "QUEUED" || run.status === "RUNNING");
+ await tx.agentRun.update({
+ where: { id: run.id },
+ data: {
+ nextEventSequence: sequence,
+ ...(mayStart
+ ? {
+ sessionId: ctx.session.id,
+ status: "RUNNING",
+ startedAt: run.startedAt ?? new Date(),
+ }
+ : {}),
+ },
+ });
+
+ await tx.agentRunEvent.create({
+ data: {
+ id: eventId,
+ runId,
+ sequence,
+ type,
+ data: data as Prisma.InputJsonValue,
+ emittedAt,
+ },
+ });
+
+ if (type === "step.completed") {
+ const usage = recordOf(data).usage;
+ const values = recordOf(usage);
+ const inputTokens = numberOf(values.inputTokens);
+ const outputTokens = numberOf(values.outputTokens);
+ const costUsd = numberOf(values.costUsd);
+ const current = await tx.agentRun.findUniqueOrThrow({
+ where: { id: runId },
+ select: { inputTokens: true, outputTokens: true, costUsd: true },
+ });
+ await tx.agentRun.update({
+ where: { id: runId },
+ data: {
+ ...(inputTokens !== null
+ ? { inputTokens: (current.inputTokens ?? 0) + inputTokens }
+ : {}),
+ ...(outputTokens !== null
+ ? { outputTokens: (current.outputTokens ?? 0) + outputTokens }
+ : {}),
+ ...(costUsd !== null
+ ? { costUsd: Number(current.costUsd ?? 0) + costUsd }
+ : {}),
+ },
+ });
+ }
+
+ if (type === "message.completed") {
+ const message = recordOf(data).message;
+ if (typeof message === "string" && message.trim()) {
+ await tx.agentRun.updateMany({
+ where: { id: runId, status: "RUNNING" },
+ data: { summary: message.slice(0, 1000) },
+ });
+ }
+ }
+}
+
+function isRootSession(ctx: Parameters<typeof purposeOf>[0]): boolean {
+ return !("parent" in ctx.session) || !ctx.session.parent;
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function numberOf(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
diff --git a/apps/agent/agent/instructions.md b/apps/agent/agent/instructions.md
index 4aa0ab64..90381f98 100644
--- a/apps/agent/agent/instructions.md
+++ b/apps/agent/agent/instructions.md
@@ -1,111 +1,9 @@
-# CRM research agent
+# Comp AI CRM agent runtime
-You work out who the people in our CRM are, what the companies are, and where
-the deals stand — so a rep opens a record already knowing what they are dealing
-with.
+You are the durable Eve runtime behind Comp AI CRM. The session-specific
+instructions identify the only purpose of the current session. Follow that
+purpose exactly and do not borrow tools or behavior from another purpose.
-## The one rule
-
-**Never write a fact you have not read from a source.**
-
-Most contacts here arrived as an email address and a guess.
-`[email protected]` became a contact called "Pmarchetti" because that is what the
-address looks like title-cased. Your job is to replace that with something true,
-not with something that reads better.
-
-A confidently wrong fact is worse than a missing one, because nobody can tell it
-is wrong. If you cannot confirm something, leave it. That is a successful
-outcome.
-
-## How this works
-
-You do not assert confidence — you report **evidence**, and the ledger scores
-it. `record_fact` takes what you *saw* ("their signature block says Head of
-Security"), decides what that is worth, and either writes the record or offers a
-rep a suggestion. Strong evidence writes. Weak evidence becomes a question for a
-human. Both are the system working.
-
-So there is nothing to argue with and no bar to clear by trying harder. Report
-what you found, accurately, and move on.
-
-## The record you were opened on
-
-Every session starts from one record, and your session instructions say which
-and give you its id. Read that record before anything else:
-
-| Opened on | Start with |
-| --------- | --------------------- |
-| a person | `read_crm_history` |
-| a company | `read_company_history`|
-| a deal | `read_deal_history` |
-
-All three are free — our own database, no vendor, no budget — and they are the
-best evidence in the system besides.
-
-The one session that opens on no record is the one that writes up **the company
-you work for**. Your instructions name our own website; read it and call
-`write_workspace_profile`. Everything you write there is read back to you at the
-start of every other session, which is why it is kept short.
-
-## The three records are joined, and so are your tools
-
-A contact works somewhere. A company has people and deals. A deal has a company
-and the people on it. **You can always get from any one to the others**, and
-each read hands you the ids to do it:
-
-- `read_crm_history` returns the contact's **company id** and the deals they are
- on.
-- `read_company_history` returns **every contact there, with their ids**, and
- every deal.
-- `read_deal_history` returns the company and everyone attached, with ids.
-- `search_crm` finds any of the three by name, email address or domain.
-
-So two answers are always wrong:
-
-**"I don't have a tool that lists contacts by company."** You do. It is
-`read_company_history`, and the person asking is looking at that company.
-
-**"Could you paste the contact's name or email address?"** Never ask a rep for
-an id, and never ask them to search for you. Call `search_crm`. If it returns
-nothing, say so — that is a real answer. If it returns four Marchettis, name all
-four with their titles and ask which one they mean; choosing between candidates
-is a question, and pasting a cuid is a chore.
-
-## Where to look outside, in order
-
-1. **The CRM first, always.** A reply from their own address, a signature block,
- a meeting they attended. No data vendor can sell us any of that.
-2. **LinkedIn** (`resolve_linkedin_profile` → `get_linkedin_profile`) for
- identity: name, current title, employer, tenure. Self-reported, and
- authoritative for who someone is.
-3. **The open web** (`web_search`, `web_fetch`, `research_person`,
- `research_company`) for context: news, funding, what they have said publicly.
- Sometimes wrong about job titles — where it disagrees with LinkedIn about
- identity, LinkedIn wins.
-
-Search results are not evidence. A search for "Paula Marchetti" once returned
-Brightwater's CEO. A search tells you where to look.
-
-**Not every install has 2 and 3.** They each need an API key, and plenty of
-copies of this CRM run with none. Your session instructions list what this one
-has before you plan; a tool whose source is missing says so, costs nothing, and
-will say the same thing however many times you call it. This is normal, not
-broken. Step 1 needs no key, it is the strongest evidence anyway, and a record
-that says only what the mailbox proves is a good outcome.
-
-## Your budget
-
-Each session comes with a research budget, and **only vendor calls spend it**.
-Every read of our own CRM is free, however many you make. When the budget is
-gone, write up what you have and stop — or call `schedule_recheck` with a reason
-if it is worth another look later. Running out is not a failure; spending it all
-on somebody nobody is selling to is.
-
-## Skills
-
-Load these when the work calls for them, and before your first one of a session:
-
-- `identity-matching` — deciding whether a candidate really is this person.
-- `evidence` — which observation is which `kind`, and why it matters.
-- `writing-a-brief` — the Background panel a rep reads before a call.
-- `data-boundaries` — what you may read (everything) and what may leave.
+Never invent a CRM record, connected integration, completed action, or external
+side effect. Tools and persisted state are the authority for what exists and
+what happened.
diff --git a/apps/agent/agent/instructions/task.ts b/apps/agent/agent/instructions/task.ts
index 186ac5b3..a22b7afd 100644
--- a/apps/agent/agent/instructions/task.ts
+++ b/apps/agent/agent/instructions/task.ts
@@ -1,10 +1,23 @@
import { defineDynamic, defineInstructions } from "eve/instructions";
import { focusOn, setBudget } from "../lib/focus";
import { sessionPreamble } from "../lib/preamble";
+import { RESEARCH_INSTRUCTIONS } from "../lib/research-instructions";
+import { attribute, purposeOf } from "../lib/session-purpose";
export default defineDynamic({
events: {
"session.started": async (_event, ctx) => {
+ const purpose = purposeOf(ctx);
+ if (purpose === "builder") {
+ return builderInstructions(ctx);
+ }
+
+ if (purpose === "team-agent") {
+ return defineInstructions({
+ markdown: `This is one background run of a deployed team agent. Call agent_runner exactly once and pass the run id from your user message. Do not call research tools or perform work yourself. Relay the specialist's structured factual completion summary. Never claim an external action that the specialist did not log.`,
+ });
+ }
+
const attributes = ctx.session.auth.current?.attributes ?? {};
const budget = asNumber(attributes.budget);
const kind = asString(attributes.taskKind);
@@ -27,11 +40,38 @@ export default defineDynamic({
focusOn({ ...focus, sessionId: ctx.session.id });
- return defineInstructions({ markdown });
+ return defineInstructions({
+ markdown: `${RESEARCH_INSTRUCTIONS}\n\n${markdown}`,
+ });
},
+ "turn.started": (_event, ctx) =>
+ purposeOf(ctx) === "builder" ? builderInstructions(ctx) : null,
},
});
+function builderInstructions(ctx: Parameters<typeof purposeOf>[0]) {
+ return defineInstructions({
+ markdown: builderTaskMarkdown(
+ attribute(ctx, "commandType"),
+ attribute(ctx, "needsTitle") === "true",
+ ),
+ });
+}
+
+export function builderTaskMarkdown(
+ commandType: string | null,
+ needsTitle = false,
+): string {
+ const task =
+ commandType === "CREATE_AGENT"
+ ? `This private CRM chat turn is authorized to create or revise an agent. Call agent_builder exactly once. Pass the complete request, the conversation's relevant decisions, every tagged resource, and your understanding of any attachment. Do not call research tools or mutate CRM records yourself. If the specialist returns needs_input, call ask_question with exactly its question, options, and freeform policy instead of replying with a plain-text question. Ask exactly one decision at a time and never bundle several missing details into one prompt. After the answer, ask another question only if the build remains materially blocked. Ask only when the answer materially changes the trigger, records, integrations, schedule, outcome, or side effect. Do not interrupt a sufficiently specific request or ask about optional polish. If the specialist returns draft_ready, relay its concise summary and explain that the draft is ready for human review and is not deployed yet.`
+ : `This is a private CRM assistant chat. Answer the user's question directly. Use tagged records as scope and use available read-only CRM and research tools when evidence is needed. Use list_deals for pipeline-wide, open-deal, or inactivity questions and follow its pagination until the requested scope is complete. The chat renders list_deals output as a structured deal list. Do not restate or enumerate individual deal rows in prose, bullets, or tables; the structured list is the sole row-level presentation. Give only a concise synthesis, caveats, and useful next actions after the tool results. If one materially necessary decision is missing, call ask_question with one focused follow-up instead of guessing; do not interrupt for optional detail. Do not call agent_builder, create an agent draft, or mutate CRM records on this turn. Agent creation begins only from an explicit request to create or build one. Be concise, distinguish CRM evidence from inference, and say when the CRM does not contain the answer.`;
+
+ return needsTitle
+ ? `Before any other work, call set_chat_title once. Summarize the user's first message as a polished title of three to seven words in sentence case. Capture the intent, remove slash-command syntax and filler, and do not use quotation marks or ending punctuation.\n\n${task}`
+ : task;
+}
+
function asString(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
diff --git a/apps/agent/agent/lib/accounts.ts b/apps/agent/agent/lib/accounts.ts
index 45406d29..459c39b2 100644
--- a/apps/agent/agent/lib/accounts.ts
+++ b/apps/agent/agent/lib/accounts.ts
@@ -90,6 +90,8 @@ export async function readCompanyHistory(
threads?: number;
messagesPerThread?: number;
people?: number;
+ includeEmail?: boolean;
+ includeCalendar?: boolean;
} = {},
): Promise<CompanyHistory | null> {
const company = await db.company.findUnique({
@@ -110,6 +112,8 @@ export async function readCompanyHistory(
});
if (!company) return null;
+ const includeEmail = options.includeEmail ?? true;
+ const includeCalendar = options.includeCalendar ?? true;
const belongsToCompany = { OR: [{ companyId }, { contact: { companyId } }] };
@@ -127,7 +131,15 @@ export async function readCompanyHistory(
email: true,
linkedinUrl: true,
lastActivityAt: true,
- _count: { select: { emailThreads: true, calendarEvents: true } },
+ _count:
+ includeEmail || includeCalendar
+ ? {
+ select: {
+ emailThreads: includeEmail,
+ calendarEvents: includeCalendar,
+ },
+ }
+ : false,
},
}),
db.deal.findMany({
@@ -152,62 +164,74 @@ export async function readCompanyHistory(
},
},
}),
- db.emailThread.findMany({
- where: belongsToCompany,
- orderBy: { lastMessageAt: "desc" },
- take: options.threads ?? 5,
- select: {
- subject: true,
- messageCount: true,
- lastMessageAt: true,
- contact: { select: { id: true, firstName: true, lastName: true } },
- messages: {
- orderBy: { sentAt: "desc" },
- take: options.messagesPerThread ?? 4,
+ includeEmail
+ ? db.emailThread.findMany({
+ where: belongsToCompany,
+ orderBy: { lastMessageAt: "desc" },
+ take: options.threads ?? 5,
select: {
- direction: true,
- fromEmail: true,
- fromName: true,
- sentAt: true,
- body: true,
- snippet: true,
+ subject: true,
+ messageCount: true,
+ lastMessageAt: true,
+ contact: {
+ select: { id: true, firstName: true, lastName: true },
+ },
+ messages: {
+ orderBy: { sentAt: "desc" },
+ take: options.messagesPerThread ?? 4,
+ select: {
+ direction: true,
+ fromEmail: true,
+ fromName: true,
+ sentAt: true,
+ body: true,
+ snippet: true,
+ },
+ },
},
- },
- },
- }),
- db.calendarEvent.findMany({
- where: {
- OR: [
- { companyId },
- { contact: { companyId } },
- { attendees: { some: { contact: { companyId } } } },
- ],
- },
- orderBy: { startsAt: "desc" },
- take: 10,
- select: {
- title: true,
- startsAt: true,
- attendees: { select: { email: true, name: true } },
- },
- }),
+ })
+ : Promise.resolve([]),
+ includeCalendar
+ ? db.calendarEvent.findMany({
+ where: {
+ OR: [
+ { companyId },
+ { contact: { companyId } },
+ { attendees: { some: { contact: { companyId } } } },
+ ],
+ },
+ orderBy: { startsAt: "desc" },
+ take: 10,
+ select: {
+ title: true,
+ startsAt: true,
+ attendees: { select: { email: true, name: true } },
+ },
+ })
+ : Promise.resolve([]),
recentNotes({ companyId }),
- db.emailMessage.findFirst({
- where: {
- direction: EmailDirection.INBOUND,
- thread: belongsToCompany,
- },
- orderBy: { sentAt: "desc" },
- select: { sentAt: true, fromEmail: true, fromName: true },
- }),
+ includeEmail
+ ? db.emailMessage.findFirst({
+ where: {
+ direction: EmailDirection.INBOUND,
+ thread: belongsToCompany,
+ },
+ orderBy: { sentAt: "desc" },
+ select: { sentAt: true, fromEmail: true, fromName: true },
+ })
+ : Promise.resolve(null),
Promise.all([
db.contact.count({ where: { companyId } }),
- db.emailMessage.count({ where: { thread: belongsToCompany } }),
- db.calendarEvent.count({
- where: {
- OR: [{ companyId }, { contact: { companyId } }],
- },
- }),
+ includeEmail
+ ? db.emailMessage.count({ where: { thread: belongsToCompany } })
+ : Promise.resolve(0),
+ includeCalendar
+ ? db.calendarEvent.count({
+ where: {
+ OR: [{ companyId }, { contact: { companyId } }],
+ },
+ })
+ : Promise.resolve(0),
]),
]);
@@ -235,8 +259,8 @@ export async function readCompanyHistory(
email: person.email,
linkedinUrl: person.linkedinUrl,
lastActivityAt: person.lastActivityAt?.toISOString() ?? null,
- threads: person._count.emailThreads,
- meetings: person._count.calendarEvents,
+ threads: person._count?.emailThreads ?? 0,
+ meetings: person._count?.calendarEvents ?? 0,
needsIdentity: isDerivedName(
person.email,
person.firstName,
@@ -307,7 +331,12 @@ export type DealHistory = {
export async function readDealHistory(
dealId: string,
- options: { threads?: number; messagesPerThread?: number } = {},
+ options: {
+ threads?: number;
+ messagesPerThread?: number;
+ includeEmail?: boolean;
+ includeCalendar?: boolean;
+ } = {},
): Promise<DealHistory | null> {
const deal = await db.deal.findUnique({
where: { id: dealId },
@@ -344,6 +373,8 @@ export async function readDealHistory(
});
if (!deal) return null;
+ const includeEmail = options.includeEmail ?? true;
+ const includeCalendar = options.includeCalendar ?? true;
const contactIds = deal.contacts.map(({ contact }) => contact.id);
@@ -365,54 +396,67 @@ export async function readDealHistory(
take: 25,
select: { meta: true, createdAt: true },
}),
- db.emailThread.findMany({
- where: relatedThreads,
- orderBy: { lastMessageAt: "desc" },
- take: options.threads ?? 5,
- select: {
- subject: true,
- messageCount: true,
- lastMessageAt: true,
- contact: { select: { id: true, firstName: true, lastName: true } },
- messages: {
- orderBy: { sentAt: "desc" },
- take: options.messagesPerThread ?? 4,
+ includeEmail
+ ? db.emailThread.findMany({
+ where: relatedThreads,
+ orderBy: { lastMessageAt: "desc" },
+ take: options.threads ?? 5,
select: {
- direction: true,
- fromEmail: true,
- fromName: true,
- sentAt: true,
- body: true,
- snippet: true,
+ subject: true,
+ messageCount: true,
+ lastMessageAt: true,
+ contact: {
+ select: { id: true, firstName: true, lastName: true },
+ },
+ messages: {
+ orderBy: { sentAt: "desc" },
+ take: options.messagesPerThread ?? 4,
+ select: {
+ direction: true,
+ fromEmail: true,
+ fromName: true,
+ sentAt: true,
+ body: true,
+ snippet: true,
+ },
+ },
},
- },
- },
- }),
- db.calendarEvent.findMany({
- where:
- contactIds.length > 0
- ? {
- OR: [
- { contactId: { in: contactIds } },
- { attendees: { some: { contactId: { in: contactIds } } } },
- { companyId: deal.company.id },
- ],
- }
- : { companyId: deal.company.id },
- orderBy: { startsAt: "desc" },
- take: 10,
- select: {
- title: true,
- startsAt: true,
- attendees: { select: { email: true, name: true } },
- },
- }),
+ })
+ : Promise.resolve([]),
+ includeCalendar
+ ? db.calendarEvent.findMany({
+ where:
+ contactIds.length > 0
+ ? {
+ OR: [
+ { contactId: { in: contactIds } },
+ {
+ attendees: { some: { contactId: { in: contactIds } } },
+ },
+ { companyId: deal.company.id },
+ ],
+ }
+ : { companyId: deal.company.id },
+ orderBy: { startsAt: "desc" },
+ take: 10,
+ select: {
+ title: true,
+ startsAt: true,
+ attendees: { select: { email: true, name: true } },
+ },
+ })
+ : Promise.resolve([]),
recentNotes({ dealId }),
- db.emailMessage.findFirst({
- where: { direction: EmailDirection.INBOUND, thread: relatedThreads },
- orderBy: { sentAt: "desc" },
- select: { sentAt: true, fromEmail: true, fromName: true },
- }),
+ includeEmail
+ ? db.emailMessage.findFirst({
+ where: {
+ direction: EmailDirection.INBOUND,
+ thread: relatedThreads,
+ },
+ orderBy: { sentAt: "desc" },
+ select: { sentAt: true, fromEmail: true, fromName: true },
+ })
+ : Promise.resolve(null),
]);
const now = new Date();
@@ -469,9 +513,11 @@ export async function readDealHistory(
: null,
},
note:
- contactIds.length > 0
- ? "Email and meetings are filed against people and companies, never against a deal. The correspondence here is with the people on this deal and with the rest of the account — read the subjects before treating any of it as being about this deal."
- : "Nobody is attached to this deal, so the correspondence here is the whole account's. Attaching the people on it would make this answer sharper.",
+ includeEmail || includeCalendar
+ ? contactIds.length > 0
+ ? "Connected account history is filed against people and companies, never against a deal. The history here belongs to the people on this deal and the rest of the account — read the details before treating any of it as being about this deal."
+ : "Nobody is attached to this deal, so the correspondence here is the whole account's. Attaching the people on it would make this answer sharper."
+ : "Connected email and calendar history are outside this agent version's approved data sources.",
};
}
diff --git a/apps/agent/agent/lib/builder-runtime.ts b/apps/agent/agent/lib/builder-runtime.ts
new file mode 100644
index 00000000..2a30b816
--- /dev/null
+++ b/apps/agent/agent/lib/builder-runtime.ts
@@ -0,0 +1,683 @@
+import { isDeepStrictEqual } from "node:util";
+import { db, type Prisma } from "@crm/db";
+import { readAgentModel } from "@crm/db/settings";
+
+const GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
+const CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.readonly";
+
+export type BuilderResource = {
+ kind: "integration" | "company" | "contact" | "deal";
+ id: string;
+ label: string;
+};
+
+export type DraftTrigger = {
+ type: "MANUAL" | "SCHEDULE";
+ name: string;
+ summary: string;
+ nextRunAt?: string | null;
+ intervalMinutes?: number | null;
+};
+
+export type DraftAction =
+ | {
+ type: "crm.activity.create";
+ provider: "crm";
+ summary: string;
+ activityTypes: ("NOTE" | "TASK")[];
+ }
+ | {
+ type: "run.summary";
+ provider: "crm";
+ summary: string;
+ };
+
+export type DraftAgentInput = {
+ name: string;
+ description: string;
+ instructions: string;
+ trigger: DraftTrigger;
+ recordScope: "SELECTED" | "WORKSPACE";
+ resources: BuilderResource[];
+ actions: DraftAction[];
+ access: string[];
+};
+
+export const BUILDER_ARTIFACT_PATHS = [
+ "agent/README.md",
+ "agent/instructions.md",
+ "agent/manifest.json",
+] as const;
+
+export type BuilderArtifactPath = (typeof BUILDER_ARTIFACT_PATHS)[number];
+
+const ARTIFACT_LANGUAGES: Record<BuilderArtifactPath, string> = {
+ "agent/README.md": "markdown",
+ "agent/instructions.md": "markdown",
+ "agent/manifest.json": "json",
+};
+
+export async function writeBuilderArtifact(
+ conversationId: string,
+ userId: string,
+ path: BuilderArtifactPath,
+ content: string,
+) {
+ assertSafeArtifact(content);
+
+ return db.$transaction(async (tx) => {
+ const [conversation] = await tx.$queryRaw<Array<{ id: string }>>`
+ SELECT id
+ FROM "agentConversation"
+ WHERE id = ${conversationId}
+ AND "userId" = ${userId}
+ AND kind = 'BUILDER'
+ FOR UPDATE
+ `;
+ if (!conversation) {
+ throw new Error("This builder conversation is unavailable.");
+ }
+
+ const latest = await tx.agentBuilderArtifact.findFirst({
+ where: { conversationId, path },
+ orderBy: { revision: "desc" },
+ select: { id: true, revision: true, content: true, status: true },
+ });
+
+ if (latest?.content === content) {
+ return { saved: true as const, id: latest.id, revision: latest.revision };
+ }
+
+ const artifact = await tx.agentBuilderArtifact.create({
+ data: {
+ conversationId,
+ path,
+ language: ARTIFACT_LANGUAGES[path],
+ content,
+ previousContent: latest?.content ?? null,
+ revision: (latest?.revision ?? 0) + 1,
+ status: "WRITING",
+ },
+ select: { id: true, revision: true },
+ });
+
+ return { saved: true as const, ...artifact };
+ });
+}
+
+export async function builderContext(conversationId: string, userId: string) {
+ const conversation = await db.agentConversation.findFirst({
+ where: { id: conversationId, userId, kind: "BUILDER" },
+ select: {
+ id: true,
+ title: true,
+ agent: {
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ status: true,
+ versions: {
+ orderBy: { number: "desc" },
+ take: 1,
+ select: {
+ id: true,
+ number: true,
+ status: true,
+ manifest: true,
+ instructions: true,
+ },
+ },
+ },
+ },
+ submissions: {
+ orderBy: { createdAt: "asc" },
+ select: { id: true, message: true, createdAt: true },
+ },
+ },
+ });
+
+ if (!conversation)
+ throw new Error("This builder conversation is unavailable.");
+
+ const resources = uniqueResources(
+ conversation.submissions.flatMap((submission) =>
+ resourcesOf(submission.message),
+ ),
+ );
+
+ return {
+ conversation: {
+ id: conversation.id,
+ title: conversation.title,
+ },
+ availableConnections: await connectionStatus(userId),
+ resources: await describeResources(resources),
+ existingDraft: conversation.agent,
+ now: new Date().toISOString(),
+ };
+}
+
+export async function saveBuilderDraft(
+ conversationId: string,
+ userId: string,
+ input: DraftAgentInput,
+) {
+ const conversation = await db.agentConversation.findFirst({
+ where: { id: conversationId, userId, kind: "BUILDER" },
+ select: {
+ id: true,
+ submissions: { select: { message: true } },
+ },
+ });
+
+ if (!conversation)
+ throw new Error("This builder conversation is unavailable.");
+
+ const taggedResources = uniqueResources(
+ conversation.submissions.flatMap((submission) =>
+ resourcesOf(submission.message),
+ ),
+ );
+ const validation = await validateDraft(userId, input, taggedResources);
+ if (!validation.valid) {
+ return {
+ saved: false as const,
+ issues: validation.issues,
+ availableConnections: validation.connections,
+ };
+ }
+
+ const model = await readAgentModel(db);
+ const now = new Date();
+ const nextRunAt = scheduleDate(input.trigger, now);
+ const manifest = {
+ kind: "crm-team-agent",
+ name: input.name,
+ description: input.description,
+ trigger: {
+ type: input.trigger.type,
+ name: input.trigger.name,
+ summary: input.trigger.summary,
+ config:
+ input.trigger.type === "SCHEDULE"
+ ? {
+ intervalMinutes: input.trigger.intervalMinutes,
+ nextRunAt: nextRunAt?.toISOString(),
+ }
+ : {},
+ },
+ dataScope: {
+ mode: input.recordScope,
+ summary: scopeSummary(input.recordScope, input.resources),
+ resources: input.resources,
+ },
+ actions: input.actions,
+ access: input.access,
+ };
+ const sandboxPolicy = {
+ backend: "eve-default",
+ networkPolicy: "deny-all",
+ credentials: "app-runtime-only",
+ summary: "Isolated sandbox · deny-all network · bounded CRM tools",
+ };
+ const files = artifactFiles(input, manifest);
+ for (const file of files) assertSafeArtifact(file.content);
+
+ return db.$transaction(async (tx) => {
+ const [lockedConversation] = await tx.$queryRaw<
+ Array<{ id: string; agentId: string | null }>
+ >`
+ SELECT id, "agentId"
+ FROM "agentConversation"
+ WHERE id = ${conversationId}
+ AND "userId" = ${userId}
+ AND kind = 'BUILDER'
+ FOR UPDATE
+ `;
+ if (!lockedConversation) {
+ throw new Error("This builder conversation is unavailable.");
+ }
+
+ let agentId = lockedConversation.agentId;
+ let created = false;
+
+ if (!agentId) {
+ const agent = await tx.agentDefinition.create({
+ data: {
+ name: input.name,
+ description: input.description,
+ createdById: userId,
+ },
+ select: { id: true },
+ });
+ agentId = agent.id;
+ created = true;
+
+ await tx.agentConversation.update({
+ where: { id: conversationId },
+ data: { agentId, title: input.name },
+ });
+ } else {
+ const [agent] = await tx.$queryRaw<
+ Array<{
+ status: "DRAFT" | "LIVE" | "PAUSED" | "ARCHIVED" | "DELETED";
+ }>
+ >`
+ SELECT status
+ FROM "agentDefinition"
+ WHERE id = ${agentId}
+ FOR UPDATE
+ `;
+ if (!agent || agent.status === "DELETED") {
+ throw new Error("This agent is unavailable.");
+ }
+ if (agent.status === "DRAFT") {
+ await tx.agentDefinition.update({
+ where: { id: agentId },
+ data: { name: input.name, description: input.description },
+ });
+ }
+ }
+
+ const latest = await tx.agentVersion.findFirst({
+ where: { agentId },
+ orderBy: { number: "desc" },
+ select: {
+ id: true,
+ number: true,
+ status: true,
+ instructions: true,
+ manifest: true,
+ modelId: true,
+ modelContextWindowTokens: true,
+ },
+ });
+ if (
+ latest?.status === "READY" &&
+ latest.instructions === input.instructions &&
+ latest.modelId === model.id &&
+ latest.modelContextWindowTokens === model.contextWindowTokens &&
+ isDeepStrictEqual(latest.manifest, manifest)
+ ) {
+ await persistArtifactSnapshots(tx, conversationId, latest.id, files);
+ return {
+ saved: true as const,
+ agentId,
+ versionId: latest.id,
+ versionNumber: latest.number,
+ status: latest.status,
+ };
+ }
+
+ const number = (latest?.number ?? 0) + 1;
+ const version = await tx.agentVersion.create({
+ data: {
+ agentId,
+ number,
+ status: "READY",
+ instructions: input.instructions,
+ manifest: manifest as Prisma.InputJsonValue,
+ modelId: model.id,
+ modelContextWindowTokens: model.contextWindowTokens,
+ sandboxPolicy,
+ validation: {
+ status: "passed",
+ checkedAt: now.toISOString(),
+ capabilities: validation.capabilities,
+ },
+ sourceConversationId: conversationId,
+ createdById: userId,
+ },
+ select: { id: true, number: true, status: true },
+ });
+
+ await persistArtifactSnapshots(tx, conversationId, version.id, files);
+
+ await tx.agentTrigger.create({
+ data: {
+ agentId,
+ versionId: version.id,
+ type: input.trigger.type,
+ name: input.trigger.name,
+ config: manifest.trigger.config as Prisma.InputJsonValue,
+ createdById: userId,
+ nextRunAt,
+ },
+ });
+
+ if (created) {
+ await tx.agentAuditEvent.create({
+ data: {
+ agentId,
+ actorUserId: userId,
+ actorType: "USER",
+ actorId: userId,
+ type: "agent.created",
+ summary: "Created a draft agent from a private builder chat",
+ requestId: `builder:${conversationId}`,
+ },
+ });
+ }
+
+ await tx.agentAuditEvent.create({
+ data: {
+ agentId,
+ versionId: version.id,
+ actorUserId: userId,
+ actorType: "USER",
+ actorId: userId,
+ type: "version.created",
+ summary: `Prepared version ${number} for review`,
+ requestId: version.id,
+ after: { status: "READY", validation: "passed" },
+ },
+ });
+
+ return {
+ saved: true as const,
+ agentId,
+ versionId: version.id,
+ versionNumber: version.number,
+ status: version.status,
+ };
+ });
+}
+
+async function persistArtifactSnapshots(
+ tx: Prisma.TransactionClient,
+ conversationId: string,
+ versionId: string,
+ files: ReturnType<typeof artifactFiles>,
+) {
+ for (const file of files) {
+ const latestArtifact = await tx.agentBuilderArtifact.findFirst({
+ where: { conversationId, path: file.path },
+ orderBy: { revision: "desc" },
+ select: {
+ id: true,
+ versionId: true,
+ revision: true,
+ content: true,
+ status: true,
+ },
+ });
+ if (
+ latestArtifact?.content === file.content &&
+ latestArtifact.versionId === versionId &&
+ latestArtifact.status === "READY"
+ ) {
+ continue;
+ }
+ if (
+ latestArtifact?.content === file.content &&
+ latestArtifact.status === "WRITING" &&
+ latestArtifact.versionId === null
+ ) {
+ await tx.agentBuilderArtifact.update({
+ where: { id: latestArtifact.id },
+ data: { versionId, status: "READY" },
+ });
+ continue;
+ }
+
+ await tx.agentBuilderArtifact.create({
+ data: {
+ conversationId,
+ versionId,
+ path: file.path,
+ language: file.language,
+ content: file.content,
+ previousContent: latestArtifact?.content ?? null,
+ revision: (latestArtifact?.revision ?? 0) + 1,
+ status: "READY",
+ },
+ });
+ }
+}
+
+async function validateDraft(
+ userId: string,
+ input: DraftAgentInput,
+ taggedResources: BuilderResource[],
+) {
+ const connections = await connectionStatus(userId);
+ const issues: string[] = [];
+ const capabilities = new Set(["crm.read"]);
+ const resourceKeys = new Set<string>();
+ const recordResources = input.resources.filter(
+ (resource) => resource.kind !== "integration",
+ );
+
+ if (input.recordScope === "SELECTED" && recordResources.length === 0) {
+ issues.push("Selected CRM scope needs at least one tagged record.");
+ }
+ if (input.recordScope === "WORKSPACE" && recordResources.length > 0) {
+ issues.push("Workspace CRM scope cannot also list selected records.");
+ }
+ const taggedRecordKeys = new Set(
+ taggedResources
+ .filter((resource) => resource.kind !== "integration")
+ .map((resource) => `${resource.kind}:${resource.id}`),
+ );
+ for (const resource of recordResources) {
+ if (!taggedRecordKeys.has(`${resource.kind}:${resource.id}`)) {
+ issues.push(`${resource.label} was not tagged in this builder chat.`);
+ }
+ }
+
+ for (const resource of input.resources) {
+ const key = `${resource.kind}:${resource.id}`;
+ if (resourceKeys.has(key)) {
+ issues.push(`${resource.label} is listed more than once.`);
+ continue;
+ }
+ resourceKeys.add(key);
+
+ if (resource.kind !== "integration") continue;
+ if (resource.id === "google:gmail" && !connections.gmail) {
+ issues.push("Gmail is not connected for the chat owner.");
+ }
+ if (resource.id === "google:calendar" && !connections.calendar) {
+ issues.push("Google Calendar is not connected for the chat owner.");
+ }
+ if (!["google:gmail", "google:calendar"].includes(resource.id)) {
+ issues.push(`${resource.label} is not an available integration.`);
+ continue;
+ }
+ capabilities.add(`${resource.id}.read`);
+ }
+
+ for (const action of input.actions) {
+ capabilities.add(action.type);
+ if (action.type !== "crm.activity.create") continue;
+ if (new Set(action.activityTypes).size !== action.activityTypes.length) {
+ issues.push("CRM activity permissions must not repeat an activity type.");
+ }
+ }
+
+ const missingRecords = await missingResourceIds(input.resources);
+ issues.push(
+ ...missingRecords.map(
+ (resource) => `${resource.label} is no longer in the CRM.`,
+ ),
+ );
+
+ if (input.trigger.type === "SCHEDULE") {
+ const next = Date.parse(input.trigger.nextRunAt ?? "");
+ if (!Number.isFinite(next) || next <= Date.now()) {
+ issues.push("A scheduled agent needs a future next run time.");
+ }
+ if (
+ !input.trigger.intervalMinutes ||
+ input.trigger.intervalMinutes < 1 ||
+ input.trigger.intervalMinutes > 525_600
+ ) {
+ issues.push(
+ "A scheduled agent needs a recurrence from 1 minute to 1 year.",
+ );
+ }
+ }
+
+ return {
+ valid: issues.length === 0,
+ issues,
+ connections,
+ capabilities: [...capabilities],
+ };
+}
+
+async function connectionStatus(userId: string) {
+ const accounts = await db.account.findMany({
+ where: { userId, providerId: "google" },
+ select: { scope: true },
+ });
+ const scopes = new Set(
+ accounts.flatMap((account) => (account.scope ?? "").split(/[,\s]+/)),
+ );
+
+ return {
+ gmail: scopes.has(GMAIL_SCOPE),
+ calendar: scopes.has(CALENDAR_SCOPE),
+ crm: true,
+ };
+}
+
+async function describeResources(resources: BuilderResource[]) {
+ return Promise.all(
+ resources.map(async (resource) => {
+ if (resource.kind === "company") {
+ const row = await db.company.findUnique({
+ where: { id: resource.id },
+ select: { id: true, name: true, domain: true, industry: true },
+ });
+ return { ...resource, record: row };
+ }
+ if (resource.kind === "contact") {
+ const row = await db.contact.findUnique({
+ where: { id: resource.id },
+ select: {
+ id: true,
+ firstName: true,
+ lastName: true,
+ email: true,
+ title: true,
+ company: { select: { id: true, name: true } },
+ },
+ });
+ return { ...resource, record: row };
+ }
+ if (resource.kind === "deal") {
+ const row = await db.deal.findUnique({
+ where: { id: resource.id },
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ company: { select: { id: true, name: true } },
+ },
+ });
+ return {
+ ...resource,
+ record: row
+ ? {
+ ...row,
+ amount: row.amount === null ? null : Number(row.amount),
+ }
+ : null,
+ };
+ }
+ return { ...resource, record: null };
+ }),
+ );
+}
+
+async function missingResourceIds(resources: BuilderResource[]) {
+ const described = await describeResources(
+ resources.filter((resource) => resource.kind !== "integration"),
+ );
+ return described.filter((resource) => !resource.record);
+}
+
+function resourcesOf(value: unknown): BuilderResource[] {
+ if (!value || typeof value !== "object" || !("resources" in value)) return [];
+ const resources = (value as { resources?: unknown }).resources;
+ if (!Array.isArray(resources)) return [];
+
+ return resources.flatMap((resource) => {
+ if (!resource || typeof resource !== "object") return [];
+ const row = resource as Record<string, unknown>;
+ if (
+ !["integration", "company", "contact", "deal"].includes(
+ String(row.kind),
+ ) ||
+ typeof row.id !== "string" ||
+ typeof row.label !== "string"
+ ) {
+ return [];
+ }
+ return [resource as BuilderResource];
+ });
+}
+
+function uniqueResources(resources: BuilderResource[]): BuilderResource[] {
+ return [
+ ...new Map(
+ resources.map((resource) => [
+ `${resource.kind}:${resource.id}`,
+ resource,
+ ]),
+ ).values(),
+ ];
+}
+
+function scheduleDate(trigger: DraftTrigger, now: Date): Date | null {
+ if (trigger.type !== "SCHEDULE") return null;
+ const parsed = new Date(trigger.nextRunAt ?? "");
+ return parsed > now ? parsed : null;
+}
+
+function artifactFiles(input: DraftAgentInput, manifest: object) {
+ return [
+ {
+ path: "agent/README.md" as const,
+ language: ARTIFACT_LANGUAGES["agent/README.md"],
+ content: `# ${input.name}\n\n${input.description}\n\n## Trigger\n\n${input.trigger.summary}\n\n## Access\n\n${input.access.map((item) => `- ${item}`).join("\n") || "- CRM data in the approved scope"}\n`,
+ },
+ {
+ path: "agent/instructions.md" as const,
+ language: ARTIFACT_LANGUAGES["agent/instructions.md"],
+ content: `${input.instructions.trim()}\n`,
+ },
+ {
+ path: "agent/manifest.json" as const,
+ language: ARTIFACT_LANGUAGES["agent/manifest.json"],
+ content: `${JSON.stringify(manifest, null, 2)}\n`,
+ },
+ ];
+}
+
+function assertSafeArtifact(content: string): void {
+ const secretPatterns = [
+ /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/i,
+ /\b(?:api[_-]?key|password|secret|access[_-]?token)\b\s*[:=]\s*["']?[a-z0-9_./+=-]{12,}/i,
+ /\b(?:sk|pk)_(?:live|test)_[a-z0-9]{16,}/i,
+ ];
+
+ if (secretPatterns.some((pattern) => pattern.test(content))) {
+ throw new Error("Agent files cannot contain credentials or secret values.");
+ }
+}
+
+function scopeSummary(
+ recordScope: DraftAgentInput["recordScope"],
+ resources: BuilderResource[],
+): string {
+ const records = resources.filter(
+ (resource) => resource.kind !== "integration",
+ );
+ if (recordScope === "WORKSPACE") return "Workspace CRM records";
+ return records.map((resource) => resource.label).join(" · ");
+}
diff --git a/apps/agent/agent/lib/context-dev.ts b/apps/agent/agent/lib/context-dev.ts
index 30341d47..6f093c43 100644
--- a/apps/agent/agent/lib/context-dev.ts
+++ b/apps/agent/agent/lib/context-dev.ts
@@ -99,29 +99,22 @@ export async function verifyKey(key: string): Promise<KeyCheck> {
}
}
-/**
- * 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) {
+ if (error.status === undefined) {
+ return { outcome: "unknown", reason: describe(error) };
+ }
+
+ if (error.status === 401 && !recognisedKeyFailure(error)) {
return {
outcome: "invalid",
reason: "Context did not recognise that API key.",
};
}
- if (error.status === undefined) {
- return { outcome: "unknown", reason: describe(error) };
- }
-
return { outcome: "valid" };
}
@@ -281,6 +274,19 @@ function errorCode(error: APIError): string | undefined {
return typeof body?.error_code === "string" ? body.error_code : undefined;
}
+function recognisedKeyFailure(error: APIError): boolean {
+ const body = error.error as
+ | { error_code?: unknown; message?: unknown }
+ | undefined;
+ const detail = [body?.error_code, body?.message, error.message]
+ .filter((value): value is string => typeof value === "string")
+ .join(" ");
+
+ return /(usage|credit|quota|allowance|billing|rate.?limit|limit.?exceeded|insufficient.?permission)/i.test(
+ detail,
+ );
+}
+
function describe(error: unknown): string {
if (error instanceof APIError) {
return `${error.status ?? "?"} ${errorCode(error) ?? error.message}`;
diff --git a/apps/agent/agent/lib/conversation-title.ts b/apps/agent/agent/lib/conversation-title.ts
new file mode 100644
index 00000000..5eb2efbb
--- /dev/null
+++ b/apps/agent/agent/lib/conversation-title.ts
@@ -0,0 +1,40 @@
+import { db } from "@crm/db";
+
+export const BUILDER_CONVERSATION_TITLE_MAX_LENGTH = 60;
+
+export async function setBuilderConversationTitle(
+ conversationId: string,
+ userId: string,
+ title: string,
+) {
+ const normalized = title
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/^["'“”‘’]+|["'“”‘’]+$/g, "")
+ .slice(0, BUILDER_CONVERSATION_TITLE_MAX_LENGTH)
+ .trim();
+
+ if (!normalized) throw new Error("A chat title cannot be empty.");
+
+ const updated = await db.agentConversation.updateMany({
+ where: {
+ id: conversationId,
+ userId,
+ kind: "BUILDER",
+ title: null,
+ },
+ data: { title: normalized },
+ });
+
+ if (updated.count === 0) {
+ const conversation = await db.agentConversation.findFirst({
+ where: { id: conversationId, userId, kind: "BUILDER" },
+ select: { title: true },
+ });
+ if (!conversation)
+ throw new Error("This builder conversation is unavailable.");
+ return { saved: false as const, title: conversation.title };
+ }
+
+ return { saved: true as const, title: normalized };
+}
diff --git a/apps/agent/agent/lib/crm.ts b/apps/agent/agent/lib/crm.ts
index 7301cc0b..91599187 100644
--- a/apps/agent/agent/lib/crm.ts
+++ b/apps/agent/agent/lib/crm.ts
@@ -158,7 +158,12 @@ export type CrmHistory = {
export async function readCrmHistory(
contactId: string,
- options: { threads?: number; messagesPerThread?: number } = {},
+ options: {
+ threads?: number;
+ messagesPerThread?: number;
+ includeEmail?: boolean;
+ includeCalendar?: boolean;
+ } = {},
): Promise<CrmHistory | null> {
const contact = await db.contact.findUnique({
where: { id: contactId },
@@ -192,49 +197,55 @@ export async function readCrmHistory(
});
if (!contact) return null;
+ const includeEmail = options.includeEmail ?? true;
+ const includeCalendar = options.includeCalendar ?? true;
const [threads, meetings, colleagues] = await Promise.all([
- db.emailThread.findMany({
- where: { contactId },
- orderBy: { lastMessageAt: "desc" },
- take: options.threads ?? 5,
- select: {
- subject: true,
- messageCount: true,
- lastMessageAt: true,
- messages: {
- orderBy: { sentAt: "desc" },
- take: options.messagesPerThread ?? 6,
+ includeEmail
+ ? db.emailThread.findMany({
+ where: { contactId },
+ orderBy: { lastMessageAt: "desc" },
+ take: options.threads ?? 5,
select: {
- direction: true,
- fromEmail: true,
- fromName: true,
- sentAt: true,
- body: true,
- snippet: true,
+ subject: true,
+ messageCount: true,
+ lastMessageAt: true,
+ messages: {
+ orderBy: { sentAt: "desc" },
+ take: options.messagesPerThread ?? 6,
+ select: {
+ direction: true,
+ fromEmail: true,
+ fromName: true,
+ sentAt: true,
+ body: true,
+ snippet: true,
+ },
+ },
},
- },
- },
- }),
- db.calendarEvent.findMany({
- where: {
- OR: [{ contactId }, { attendees: { some: { contactId } } }],
- },
- orderBy: { startsAt: "desc" },
- take: 10,
- select: {
- title: true,
- startsAt: true,
- attendees: {
+ })
+ : Promise.resolve([]),
+ includeCalendar
+ ? db.calendarEvent.findMany({
+ where: {
+ OR: [{ contactId }, { attendees: { some: { contactId } } }],
+ },
+ orderBy: { startsAt: "desc" },
+ take: 10,
select: {
- email: true,
- name: true,
- contactId: true,
- responseStatus: true,
+ title: true,
+ startsAt: true,
+ attendees: {
+ select: {
+ email: true,
+ name: true,
+ contactId: true,
+ responseStatus: true,
+ },
+ },
},
- },
- },
- }),
+ })
+ : Promise.resolve([]),
contact.companyId
? db.contact.findMany({
where: { companyId: contact.companyId, id: { not: contactId } },
diff --git a/apps/agent/agent/lib/custom-agent-dispatch.ts b/apps/agent/agent/lib/custom-agent-dispatch.ts
new file mode 100644
index 00000000..1685b025
--- /dev/null
+++ b/apps/agent/agent/lib/custom-agent-dispatch.ts
@@ -0,0 +1,638 @@
+import { db, type Prisma } from "@crm/db";
+import type { SendFn } from "eve/channels";
+import { lockAgentRun, runTerminalEventId } from "./run-state";
+
+const BUILDER_BATCH = 20;
+const RUN_BATCH = 20;
+const MAX_BUILDER_ATTEMPTS = 3;
+const BUILDER_LEASE_MS = 5 * 60_000;
+const RUN_DELIVERY_LEASE_MS = 5 * 60_000;
+
+export async function pendingBuilderSubmissionIds(): Promise<string[]> {
+ await recoverBuilderSubmissions();
+ const rows = await db.agentConversationSubmission.findMany({
+ where: {
+ status: "PENDING",
+ conversation: {
+ kind: "BUILDER",
+ OR: [{ sessionId: null }, { continuationToken: { not: null } }],
+ },
+ },
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ take: BUILDER_BATCH * 3,
+ select: { id: true, conversationId: true },
+ });
+
+ const seen = new Set<string>();
+ return rows
+ .flatMap((row) => {
+ if (seen.has(row.conversationId)) return [];
+ seen.add(row.conversationId);
+ return [row.id];
+ })
+ .slice(0, BUILDER_BATCH);
+}
+
+export async function drainBuilder(send: SendFn): Promise<number> {
+ const ids = await pendingBuilderSubmissionIds();
+ await Promise.all(ids.map((id) => dispatchBuilderSubmission(id, send)));
+ return ids.length;
+}
+
+export async function dispatchBuilderSubmission(
+ submissionId: string,
+ send: SendFn,
+) {
+ const submission = await db.$transaction(async (tx) => {
+ const seed = await tx.agentConversationSubmission.findUnique({
+ where: { id: submissionId },
+ select: { conversationId: true },
+ });
+ if (!seed) throw new Error("Builder submission is unavailable.");
+
+ const conversation = await lockBuilderConversation(tx, seed.conversationId);
+ if (conversation?.kind !== "BUILDER") {
+ throw new Error("Builder submission is unavailable.");
+ }
+ if (conversation.sessionId && !conversation.continuationToken) {
+ throw new Error("Builder conversation is still processing a message.");
+ }
+
+ const [active, firstPending] = await Promise.all([
+ tx.agentConversationSubmission.findFirst({
+ where: { conversationId: conversation.id, status: "SENDING" },
+ select: { id: true },
+ }),
+ tx.agentConversationSubmission.findFirst({
+ where: { conversationId: conversation.id, status: "PENDING" },
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ select: { id: true },
+ }),
+ ]);
+ if (active || firstPending?.id !== submissionId) {
+ throw new Error(
+ "Builder submission was already claimed or is out of order.",
+ );
+ }
+
+ await tx.agentConversationSubmission.update({
+ where: { id: submissionId },
+ data: {
+ status: "SENDING",
+ attemptCount: { increment: 1 },
+ sentAt: new Date(),
+ errorCode: null,
+ errorMessage: null,
+ },
+ });
+ await tx.agentConversation.update({
+ where: { id: conversation.id },
+ data: { continuationToken: null },
+ });
+
+ return tx.agentConversationSubmission.findUniqueOrThrow({
+ where: { id: submissionId },
+ select: {
+ id: true,
+ commandType: true,
+ message: true,
+ attemptCount: true,
+ attachments: {
+ orderBy: { position: "asc" },
+ select: {
+ name: true,
+ mediaType: true,
+ content: true,
+ },
+ },
+ conversation: {
+ select: {
+ id: true,
+ title: true,
+ userId: true,
+ kind: true,
+ },
+ },
+ },
+ });
+ });
+ const conversationId = submission.conversation.id;
+
+ try {
+ const session = await send(
+ builderDeliveryMessage(
+ submission.id,
+ submission.message,
+ submission.attachments,
+ ),
+ {
+ auth: {
+ authenticator: "crm-builder",
+ principalType: "user",
+ principalId: submission.conversation.userId,
+ attributes: {
+ purpose: "builder",
+ commandType: builderCommandType(
+ submission.commandType,
+ submission.message,
+ ),
+ needsTitle: submission.conversation.title ? "false" : "true",
+ conversationId,
+ userId: submission.conversation.userId,
+ submissionId: submission.id,
+ },
+ },
+ continuationToken: builderToken(conversationId),
+ title: submission.conversation.title ?? "Agent builder",
+ },
+ );
+
+ await db.$transaction(async (tx) => {
+ const conversation = await lockBuilderConversation(tx, conversationId);
+ if (!conversation) return;
+ await tx.agentConversationSubmission.update({
+ where: { id: submission.id },
+ data: { status: "ACCEPTED", acceptedAt: new Date() },
+ });
+ await tx.agentConversation.update({
+ where: { id: conversationId },
+ data: { sessionId: session.id },
+ });
+ });
+
+ return session;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ const retry = submission.attemptCount < MAX_BUILDER_ATTEMPTS;
+ await db.$transaction(async (tx) => {
+ const conversation = await lockBuilderConversation(tx, conversationId);
+ if (!conversation) return;
+ await tx.agentConversationSubmission.update({
+ where: { id: submission.id },
+ data: {
+ status: retry ? "PENDING" : "FAILED",
+ errorCode: "DELIVERY_FAILED",
+ errorMessage: message,
+ },
+ });
+ await tx.agentConversation.update({
+ where: { id: conversationId },
+ data: { continuationToken: builderToken(conversationId) },
+ });
+ });
+ throw error;
+ }
+}
+
+export async function queueDueAgentRuns(now = new Date()): Promise<number> {
+ const triggers = await db.agentTrigger.findMany({
+ where: {
+ enabled: true,
+ type: "SCHEDULE",
+ nextRunAt: { lte: now },
+ agent: { status: "LIVE" },
+ },
+ orderBy: [{ nextRunAt: "asc" }, { id: "asc" }],
+ take: RUN_BATCH,
+ select: {
+ id: true,
+ agentId: true,
+ versionId: true,
+ nextRunAt: true,
+ config: true,
+ },
+ });
+
+ let queued = 0;
+ for (const trigger of triggers) {
+ if (!trigger.nextRunAt) continue;
+ const scheduledAt = trigger.nextRunAt;
+ const intervalMinutes = intervalOf(trigger.config);
+ const nextRunAt = advance(scheduledAt, intervalMinutes, now);
+ const idempotencyKey = `${trigger.id}:${scheduledAt.toISOString()}`;
+ const claimed = await db.$transaction(async (tx) => {
+ const [agent] = await tx.$queryRaw<Array<{ id: string; status: string }>>`
+ SELECT id, status
+ FROM "agentDefinition"
+ WHERE id = ${trigger.agentId}
+ FOR UPDATE
+ `;
+ if (agent?.status !== "LIVE") return false;
+
+ const updated = await tx.agentTrigger.updateMany({
+ where: {
+ id: trigger.id,
+ nextRunAt: scheduledAt,
+ enabled: true,
+ },
+ data: { nextRunAt, lastRunAt: scheduledAt },
+ });
+ if (updated.count === 0) return false;
+
+ await tx.agentRun.upsert({
+ where: { idempotencyKey },
+ create: {
+ agentId: trigger.agentId,
+ versionId: trigger.versionId,
+ triggerId: trigger.id,
+ triggerType: "SCHEDULE",
+ idempotencyKey,
+ correlationId: crypto.randomUUID(),
+ input: { scheduledFor: scheduledAt.toISOString() },
+ events: {
+ create: { sequence: 0, type: "run.queued", data: {} },
+ },
+ },
+ update: {},
+ });
+ return true;
+ });
+ if (claimed) queued += 1;
+ }
+
+ return queued;
+}
+
+export async function pendingAgentRunIds(): Promise<string[]> {
+ await recoverAgentRuns();
+ const rows = await db.agentRun.findMany({
+ where: { status: "QUEUED", agent: { status: "LIVE" } },
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ take: RUN_BATCH,
+ select: { id: true },
+ });
+ return rows.map((row) => row.id);
+}
+
+export async function drainAgentRuns(send: SendFn): Promise<number> {
+ await queueDueAgentRuns();
+ const ids = await pendingAgentRunIds();
+ await Promise.all(ids.map((id) => dispatchAgentRun(id, send)));
+ return ids.length;
+}
+
+export async function dispatchAgentRun(runId: string, send: SendFn) {
+ const run = await db.agentRun.findUnique({
+ where: { id: runId },
+ select: {
+ id: true,
+ status: true,
+ agentId: true,
+ versionId: true,
+ initiatedById: true,
+ agent: {
+ select: { name: true, createdById: true, status: true },
+ },
+ version: { select: { modelId: true } },
+ },
+ });
+ if (run?.status !== "QUEUED" || run.agent.status !== "LIVE") {
+ throw new Error("Agent run was already claimed or is not live.");
+ }
+
+ const claimed = await db.$transaction(async (tx) => {
+ const [agent] = await tx.$queryRaw<Array<{ id: string; status: string }>>`
+ SELECT id, status
+ FROM "agentDefinition"
+ WHERE id = ${run.agentId}
+ FOR UPDATE
+ `;
+ if (agent?.status !== "LIVE") return false;
+
+ const updated = await tx.agentRun.updateMany({
+ where: { id: runId, status: "QUEUED" },
+ data: {
+ status: "RUNNING",
+ startedAt: new Date(),
+ modelId: run.version.modelId,
+ },
+ });
+ return updated.count === 1;
+ });
+ if (!claimed)
+ throw new Error("Agent run was already claimed or is not live.");
+
+ const principalId = run.initiatedById ?? run.agent.createdById;
+ try {
+ const session = await send(`Execute deployed agent run ${run.id}.`, {
+ auth: {
+ authenticator: run.initiatedById ? "crm-user" : "crm-schedule",
+ principalType: run.initiatedById ? "user" : "runtime",
+ principalId,
+ attributes: {
+ purpose: "team-agent",
+ runId: run.id,
+ agentId: run.agentId,
+ versionId: run.versionId,
+ userId: principalId,
+ },
+ },
+ continuationToken: runToken(run.id),
+ title: `${run.agent.name} run`,
+ mode: "task",
+ });
+
+ await db.agentRun.updateMany({
+ where: { id: run.id, status: "RUNNING" },
+ data: { sessionId: session.id },
+ });
+ return session;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ await failRun(run.id, "DELIVERY_FAILED", message);
+ throw error;
+ }
+}
+
+export async function failRun(runId: string, code: string, message: string) {
+ return db.$transaction(async (tx) => {
+ const run = await lockAgentRun(tx, runId);
+ if (run.status === "FAILED") {
+ return { id: run.id, status: "FAILED" as const };
+ }
+ if (run.status === "SUCCEEDED" || run.status === "CANCELLED") {
+ return { id: run.id, status: run.status };
+ }
+
+ const sequence = run.nextEventSequence + 1;
+ const finishedAt = new Date();
+ await tx.agentRun.update({
+ where: { id: runId },
+ data: {
+ status: "FAILED",
+ errorCode: code,
+ errorMessage: message,
+ finishedAt,
+ nextEventSequence: sequence,
+ },
+ });
+ await tx.agentRunEvent.create({
+ data: {
+ id: runTerminalEventId(run.id, "failed"),
+ runId: run.id,
+ sequence,
+ type: "run.failed",
+ data: { code, message },
+ emittedAt: finishedAt,
+ },
+ });
+ await tx.agentAuditEvent.upsert({
+ where: {
+ agentId_type_requestId: {
+ agentId: run.agentId,
+ type: "run.failed",
+ requestId: run.id,
+ },
+ },
+ create: {
+ agentId: run.agentId,
+ versionId: run.versionId,
+ actorType: "AGENT",
+ actorId: run.id,
+ type: "run.failed",
+ summary: message,
+ requestId: run.id,
+ },
+ update: {},
+ });
+
+ return { id: run.id, status: "FAILED" as const };
+ });
+}
+
+export function builderToken(conversationId: string): string {
+ return `builder:${conversationId}`;
+}
+
+export function builderIdFromToken(token: string | undefined): string | null {
+ return idFromToken(token, "builder:");
+}
+
+export function runToken(runId: string): string {
+ return `run:${runId}`;
+}
+
+export function runIdFromToken(token: string | undefined): string | null {
+ return idFromToken(token, "run:");
+}
+
+async function recoverBuilderSubmissions() {
+ const stale = new Date(Date.now() - BUILDER_LEASE_MS);
+ const rows = await db.agentConversationSubmission.findMany({
+ where: {
+ status: "SENDING",
+ sentAt: { lt: stale },
+ },
+ orderBy: [{ sentAt: "asc" }, { id: "asc" }],
+ take: BUILDER_BATCH * 3,
+ select: { id: true, conversationId: true, attemptCount: true },
+ });
+
+ for (const row of rows) {
+ await db.$transaction(async (tx) => {
+ const conversation = await lockBuilderConversation(
+ tx,
+ row.conversationId,
+ );
+ if (conversation?.kind !== "BUILDER") return;
+ const claimed = await tx.agentConversationSubmission.updateMany({
+ where: { id: row.id, status: "SENDING", sentAt: { lt: stale } },
+ data:
+ row.attemptCount < MAX_BUILDER_ATTEMPTS
+ ? { status: "PENDING" }
+ : {
+ status: "FAILED",
+ errorCode: "DELIVERY_EXHAUSTED",
+ errorMessage:
+ "The builder could not accept this message after three attempts.",
+ },
+ });
+ if (claimed.count === 0) return;
+
+ await tx.agentConversation.updateMany({
+ where: { id: row.conversationId, kind: "BUILDER" },
+ data: { continuationToken: builderToken(row.conversationId) },
+ });
+ });
+ }
+}
+
+type LockedBuilderConversation = {
+ id: string;
+ kind: string;
+ sessionId: string | null;
+ continuationToken: string | null;
+};
+
+async function lockBuilderConversation(
+ tx: Prisma.TransactionClient,
+ conversationId: string,
+): Promise<LockedBuilderConversation | null> {
+ const [conversation] = await tx.$queryRaw<LockedBuilderConversation[]>`
+ SELECT id, kind, "sessionId", "continuationToken"
+ FROM "agentConversation"
+ WHERE id = ${conversationId}
+ FOR UPDATE
+ `;
+ return conversation ?? null;
+}
+
+async function recoverAgentRuns() {
+ const stale = new Date(Date.now() - RUN_DELIVERY_LEASE_MS);
+ const rows = await db.agentRun.findMany({
+ where: {
+ status: "RUNNING",
+ sessionId: null,
+ startedAt: { lt: stale },
+ },
+ orderBy: [{ startedAt: "asc" }, { id: "asc" }],
+ take: RUN_BATCH * 3,
+ select: { id: true, agentId: true },
+ });
+
+ for (const row of rows) {
+ await db.$transaction(async (tx) => {
+ const [agent] = await tx.$queryRaw<Array<{ status: string }>>`
+ SELECT status
+ FROM "agentDefinition"
+ WHERE id = ${row.agentId}
+ FOR UPDATE
+ `;
+ const run = await lockAgentRun(tx, row.id);
+ if (
+ run.status !== "RUNNING" ||
+ run.sessionId !== null ||
+ !run.startedAt ||
+ run.startedAt >= stale
+ ) {
+ return;
+ }
+
+ const sequence = run.nextEventSequence + 1;
+ const cancelled = agent?.status !== "LIVE" && agent?.status !== "PAUSED";
+ await tx.agentRun.update({
+ where: { id: run.id },
+ data: cancelled
+ ? {
+ status: "CANCELLED",
+ errorCode: "AGENT_UNAVAILABLE",
+ errorMessage:
+ "The agent was unavailable when delivery recovery ran.",
+ finishedAt: new Date(),
+ nextEventSequence: sequence,
+ }
+ : {
+ status: "QUEUED",
+ startedAt: null,
+ errorCode: null,
+ errorMessage: null,
+ finishedAt: null,
+ nextEventSequence: sequence,
+ },
+ });
+ await tx.agentRunEvent.create({
+ data: {
+ id: `run-delivery-${cancelled ? "cancelled" : "recovered"}:${run.id}:${run.startedAt.toISOString()}`,
+ runId: run.id,
+ sequence,
+ type: cancelled ? "run.cancelled" : "run.delivery_recovered",
+ data: cancelled ? { reason: "agent.unavailable" } : {},
+ },
+ });
+ });
+ }
+}
+
+export function builderDeliveryMessage(
+ submissionId: string,
+ value: unknown,
+ attachments: readonly BuilderDeliveryAttachment[] = [],
+): Parameters<SendFn>[0] {
+ const message = recordOf(value);
+ const inputResponse = recordOf(message.inputResponse);
+ const response =
+ typeof inputResponse.requestId === "string" &&
+ typeof inputResponse.answer === "string"
+ ? inputResponse.answer.trim()
+ : "";
+ if (response) return response;
+
+ const text = typeof message.text === "string" ? message.text : "";
+ const resources = Array.isArray(message.resources) ? message.resources : [];
+ const context = [
+ `Submission id: ${submissionId}`,
+ resources.length > 0
+ ? `Tagged resources: ${resources.map(resourceLabel).filter(Boolean).join(", ")}`
+ : null,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ const parts: Array<Record<string, unknown>> = [
+ { type: "text", text: `${context}\n\n${text}` },
+ ];
+
+ for (const attachment of attachments) {
+ parts.push({
+ type: "file",
+ data: attachment.content,
+ mediaType: attachment.mediaType,
+ filename: attachment.name,
+ });
+ }
+
+ return parts as Parameters<SendFn>[0];
+}
+
+export function builderCommandType(
+ commandType: string,
+ value: unknown,
+): string {
+ const inputResponse = recordOf(recordOf(value).inputResponse);
+ return typeof inputResponse.requestId === "string" &&
+ typeof inputResponse.answer === "string"
+ ? "CREATE_AGENT"
+ : commandType;
+}
+
+type BuilderDeliveryAttachment = {
+ name: string;
+ mediaType: string;
+ content: Uint8Array;
+};
+
+function resourceLabel(value: unknown): string | null {
+ const row = recordOf(value);
+ return typeof row.label === "string" ? row.label : null;
+}
+
+function intervalOf(value: unknown): number {
+ const interval = recordOf(value).intervalMinutes;
+ return typeof interval === "number" &&
+ Number.isFinite(interval) &&
+ interval >= 1
+ ? Math.min(interval, 525_600)
+ : 1440;
+}
+
+function advance(from: Date, intervalMinutes: number, now: Date): Date {
+ const intervalMs = intervalMinutes * 60_000;
+ const missed = Math.max(
+ 1,
+ Math.floor((now.getTime() - from.getTime()) / intervalMs) + 1,
+ );
+ return new Date(from.getTime() + missed * intervalMs);
+}
+
+function idFromToken(token: string | undefined, marker: string): string | null {
+ if (!token) return null;
+ const index = token.lastIndexOf(marker);
+ if (index === -1) return null;
+ const id = token.slice(index + marker.length);
+ return id || null;
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
diff --git a/apps/agent/agent/lib/lookup.ts b/apps/agent/agent/lib/lookup.ts
index ecd5fbe9..76accbcd 100644
--- a/apps/agent/agent/lib/lookup.ts
+++ b/apps/agent/agent/lib/lookup.ts
@@ -1,4 +1,5 @@
-import { db } from "@crm/db";
+import { DealStage, db } from "@crm/db";
+import { LOSING_DEAL_STAGES, OPEN_DEAL_STAGES } from "@crm/db/deal-stage";
import { domainOf, normalise } from "./names";
export type RecordKind = "contact" | "company" | "deal";
@@ -43,6 +44,117 @@ export type SearchResult = {
total: number;
};
+export type DealListStatus = "open" | "won" | "lost" | "all";
+
+export type DealListOptions = {
+ status?: DealListStatus;
+ inactiveForDays?: number;
+ companyId?: string;
+ ownerId?: string;
+ limit?: number;
+ cursor?: string;
+ now?: Date;
+};
+
+export async function listDeals(options: DealListOptions = {}) {
+ const status = options.status ?? "open";
+ const limit = Math.min(Math.max(options.limit ?? 50, 1), 100);
+ const now = options.now ?? new Date();
+ const cutoff =
+ options.inactiveForDays === undefined
+ ? null
+ : new Date(
+ now.getTime() - Math.max(options.inactiveForDays, 0) * 86_400_000,
+ );
+ const stages =
+ status === "open"
+ ? [...OPEN_DEAL_STAGES]
+ : status === "won"
+ ? [DealStage.CLOSED_WON]
+ : status === "lost"
+ ? [...LOSING_DEAL_STAGES]
+ : null;
+
+ const rows = await db.deal.findMany({
+ where: {
+ ...(stages ? { stage: { in: stages } } : {}),
+ ...(options.companyId ? { companyId: options.companyId } : {}),
+ ...(options.ownerId ? { ownerId: options.ownerId } : {}),
+ ...(cutoff
+ ? {
+ OR: [
+ { lastActivityAt: { lte: cutoff } },
+ { lastActivityAt: null, createdAt: { lte: cutoff } },
+ ],
+ }
+ : {}),
+ },
+ orderBy: [
+ { lastActivityAt: { sort: "asc", nulls: "first" } },
+ { createdAt: "asc" },
+ { id: "asc" },
+ ],
+ ...(options.cursor ? { cursor: { id: options.cursor }, skip: 1 } : {}),
+ take: limit + 1,
+ select: {
+ id: true,
+ name: true,
+ stage: true,
+ amount: true,
+ currency: true,
+ createdAt: true,
+ lastActivityAt: true,
+ expectedCloseDate: true,
+ company: {
+ select: {
+ id: true,
+ name: true,
+ domain: true,
+ iconUrl: true,
+ iconDarkUrl: true,
+ iconTone: true,
+ logoUrl: true,
+ },
+ },
+ owner: { select: { id: true, name: true, email: true, image: true } },
+ },
+ });
+ const hasMore = rows.length > limit;
+ const page = rows.slice(0, limit);
+
+ return {
+ criteria: {
+ status,
+ inactiveForDays: options.inactiveForDays ?? null,
+ companyId: options.companyId ?? null,
+ ownerId: options.ownerId ?? null,
+ },
+ asOf: now.toISOString(),
+ deals: page.map((deal) => {
+ const activityDate = deal.lastActivityAt ?? deal.createdAt;
+ return {
+ id: deal.id,
+ name: deal.name,
+ stage: deal.stage,
+ amount: deal.amount === null ? null : Number(deal.amount),
+ currency: deal.currency,
+ company: deal.company,
+ owner: deal.owner,
+ createdAt: deal.createdAt.toISOString(),
+ lastActivityAt: deal.lastActivityAt?.toISOString() ?? null,
+ daysSinceLastActivity: Math.max(
+ 0,
+ Math.floor((now.getTime() - activityDate.getTime()) / 86_400_000),
+ ),
+ neverActive: deal.lastActivityAt === null,
+ expectedCloseDate: deal.expectedCloseDate?.toISOString() ?? null,
+ };
+ }),
+ hasMore,
+ nextCursor: hasMore ? page.at(-1)?.id : null,
+ };
+}
+
export async function searchCrm(
query: string,
options: { kinds?: RecordKind[]; limit?: number } = {},
diff --git a/apps/agent/agent/lib/research-instructions.ts b/apps/agent/agent/lib/research-instructions.ts
new file mode 100644
index 00000000..b29b5781
--- /dev/null
+++ b/apps/agent/agent/lib/research-instructions.ts
@@ -0,0 +1,26 @@
+export const RESEARCH_INSTRUCTIONS = `# CRM research agent
+
+Work out who the people in the CRM are, what the companies are, and where deals
+stand so a rep opens a record already knowing what they are dealing with.
+
+Never write a fact you have not read from a source. A confidently wrong fact is
+worse than a missing one. If you cannot confirm something, leave it missing.
+Report evidence through the evidence tools instead of asserting confidence.
+
+Read the record you were opened on before doing anything else. Use
+read_crm_history for a contact, read_company_history for a company, and
+read_deal_history for a deal. These CRM reads are free, authoritative, and join
+to related contacts, companies, and deals. Use search_crm when a request names a
+record without an id. Never ask a rep to find an id the CRM can resolve.
+
+Look outside the CRM only after reading internal history. Prefer LinkedIn for
+identity and the open web for context. Search results point to sources but are
+not themselves evidence. When an install lacks a vendor capability, continue
+with CRM evidence instead of treating that absence as a failure.
+
+Only vendor calls spend the session research budget. When it is gone, write up
+what you have and stop, or schedule a recheck when another look is justified.
+
+Load identity-matching before deciding whether a candidate is the same person,
+evidence before recording facts, writing-a-brief before a background brief, and
+data-boundaries before moving data outside the CRM.`;
diff --git a/apps/agent/agent/lib/run-runtime.ts b/apps/agent/agent/lib/run-runtime.ts
new file mode 100644
index 00000000..f3a2e310
--- /dev/null
+++ b/apps/agent/agent/lib/run-runtime.ts
@@ -0,0 +1,644 @@
+import { createHash } from "node:crypto";
+import { ActivityType, db, type Prisma } from "@crm/db";
+import { lockIdempotencyKey } from "@crm/db/idempotency";
+import { readCompanyHistory, readDealHistory } from "./accounts";
+import { readCrmHistory } from "./crm";
+import { searchCrm } from "./lookup";
+import { lockAgentRun, runTerminalEventId } from "./run-state";
+
+const ACTION_LEASE_MS = 5 * 60_000;
+
+type RunResource = {
+ kind: "integration" | "company" | "contact" | "deal";
+ id: string;
+ label: string;
+};
+
+type RunRecordScope = "SELECTED" | "WORKSPACE";
+
+export async function approvedRunInstructions(runId: string): Promise<string> {
+ const run = await db.agentRun.findUnique({
+ where: { id: runId },
+ select: {
+ status: true,
+ version: { select: { instructions: true } },
+ },
+ });
+
+ if (!run) throw new Error("This agent run is unavailable.");
+ if (run.status !== "RUNNING") {
+ throw new Error("This agent run is not active.");
+ }
+ return run.version.instructions;
+}
+
+export async function runContext(runId: string) {
+ const run = await db.agentRun.findUnique({
+ where: { id: runId },
+ select: {
+ id: true,
+ status: true,
+ triggerType: true,
+ input: true,
+ agent: { select: { id: true, name: true, description: true } },
+ version: {
+ select: {
+ id: true,
+ number: true,
+ manifest: true,
+ modelId: true,
+ sandboxPolicy: true,
+ },
+ },
+ trigger: { select: { id: true, name: true, type: true, config: true } },
+ },
+ });
+
+ if (!run) throw new Error("This agent run is unavailable.");
+ if (run.status !== "RUNNING") {
+ throw new Error("This agent run is not active.");
+ }
+
+ const dataScope = manifestDataScope(run.version.manifest);
+ return {
+ ...run,
+ recordScope: dataScope.mode,
+ allowedResources: dataScope.resources,
+ allowedActions: manifestActions(run.version.manifest),
+ now: new Date().toISOString(),
+ };
+}
+
+export async function queryRunCrm(
+ runId: string,
+ input: {
+ query: string;
+ kinds?: ("contact" | "company" | "deal")[];
+ limit: number;
+ },
+) {
+ const run = await runContext(runId);
+ const scoped = run.allowedResources.filter(
+ (resource) => resource.kind !== "integration",
+ );
+ const result = await searchCrm(input.query, input);
+ if (run.recordScope === "WORKSPACE") return result;
+
+ const allowed = new Set(
+ scoped.map((resource) => `${resource.kind}:${resource.id}`),
+ );
+ const contacts = result.contacts.filter((row) =>
+ allowed.has(`contact:${row.id}`),
+ );
+ const companies = result.companies.filter((row) =>
+ allowed.has(`company:${row.id}`),
+ );
+ const deals = result.deals.filter((row) => allowed.has(`deal:${row.id}`));
+ return {
+ ...result,
+ contacts,
+ companies,
+ deals,
+ total: contacts.length + companies.length + deals.length,
+ };
+}
+
+export async function readRunRecord(
+ runId: string,
+ input: {
+ kind: "contact" | "company" | "deal";
+ id: string;
+ },
+) {
+ const run = await runContext(runId);
+ assertResourceAllowed(run.recordScope, run.allowedResources, input);
+ const sources = allowedHistorySources(run.allowedResources);
+
+ if (input.kind === "contact")
+ return readCrmHistory(input.id, {
+ threads: 10,
+ includeEmail: sources.gmail,
+ includeCalendar: sources.calendar,
+ });
+ if (input.kind === "company") {
+ return readCompanyHistory(input.id, {
+ threads: 10,
+ people: 50,
+ includeEmail: sources.gmail,
+ includeCalendar: sources.calendar,
+ });
+ }
+ return readDealHistory(input.id, {
+ threads: 10,
+ includeEmail: sources.gmail,
+ includeCalendar: sources.calendar,
+ });
+}
+
+export async function createRunActivity(
+ runId: string,
+ callId: string,
+ input: {
+ type: "NOTE" | "TASK";
+ targetKind: "company" | "contact" | "deal";
+ targetId: string;
+ subject?: string | null;
+ body?: string | null;
+ dueAt?: string | null;
+ },
+) {
+ const run = await db.agentRun.findUnique({
+ where: { id: runId },
+ select: {
+ id: true,
+ status: true,
+ agentId: true,
+ initiatedById: true,
+ agent: { select: { createdById: true } },
+ version: { select: { manifest: true } },
+ },
+ });
+ if (!run) throw new Error("This agent run is unavailable.");
+
+ assertActivityAllowed(run.version.manifest, input.type);
+ const dataScope = manifestDataScope(run.version.manifest);
+ assertResourceAllowed(dataScope.mode, dataScope.resources, {
+ kind: input.targetKind,
+ id: input.targetId,
+ });
+ const idempotencyKey = `${runId}:${callId}`;
+ const requestHash = actionRequestHash(input);
+ const existing = await db.agentAction.findUnique({
+ where: { idempotencyKey },
+ select: {
+ id: true,
+ status: true,
+ externalId: true,
+ errorMessage: true,
+ requestHash: true,
+ },
+ });
+ if (existing) assertActionRequestMatches(existing.requestHash, requestHash);
+ if (existing?.status === "SUCCEEDED") {
+ return {
+ actionId: existing.id,
+ activityId: existing.externalId,
+ replayed: true,
+ };
+ }
+ if (run.status !== "RUNNING") {
+ throw new Error("This agent run is not active.");
+ }
+ if (input.type === "TASK" && !input.subject?.trim()) {
+ throw new Error("A CRM task needs a subject.");
+ }
+ if (input.type === "NOTE" && !input.subject?.trim() && !input.body?.trim()) {
+ throw new Error("A CRM note needs a subject or body.");
+ }
+ const dueAt = input.dueAt ? new Date(input.dueAt) : null;
+ if (dueAt && Number.isNaN(dueAt.getTime())) {
+ throw new Error("The due date is invalid.");
+ }
+ const target = await targetRecord(input.targetKind, input.targetId);
+ if (!target) throw new Error("The requested CRM target no longer exists.");
+
+ let action = existing;
+ if (!action) {
+ action = await db.$transaction(async (tx) => {
+ await lockIdempotencyKey(tx, idempotencyKey);
+ const winner = await tx.agentAction.findUnique({
+ where: { idempotencyKey },
+ select: {
+ id: true,
+ status: true,
+ externalId: true,
+ errorMessage: true,
+ requestHash: true,
+ },
+ });
+ if (winner) {
+ assertActionRequestMatches(winner.requestHash, requestHash);
+ return winner;
+ }
+
+ return tx.agentAction.create({
+ data: {
+ agentId: run.agentId,
+ runId,
+ type: "crm.activity.create",
+ provider: "crm",
+ targetType: input.targetKind,
+ targetId: input.targetId,
+ targetLabel: target.label,
+ summary:
+ input.subject?.trim() ||
+ `Create a ${input.type.toLowerCase()} on ${target.label}`,
+ metadata: { activityType: input.type },
+ idempotencyKey,
+ requestHash,
+ },
+ select: {
+ id: true,
+ status: true,
+ externalId: true,
+ errorMessage: true,
+ requestHash: true,
+ },
+ });
+ });
+ }
+ if (action.status === "SUCCEEDED") {
+ return {
+ actionId: action.id,
+ activityId: action.externalId,
+ replayed: true,
+ };
+ }
+
+ const claimed = await db.agentAction.updateMany({
+ where: {
+ id: action.id,
+ OR: [
+ { status: { in: ["PLANNED", "FAILED"] } },
+ {
+ status: "RUNNING",
+ startedAt: { lt: new Date(Date.now() - ACTION_LEASE_MS) },
+ },
+ ],
+ },
+ data: {
+ status: "RUNNING",
+ startedAt: new Date(),
+ completedAt: null,
+ attemptCount: { increment: 1 },
+ errorCode: null,
+ errorMessage: null,
+ },
+ });
+ if (claimed.count === 0) {
+ const current = await db.agentAction.findUnique({
+ where: { id: action.id },
+ select: { status: true, externalId: true },
+ });
+ if (current?.status === "SUCCEEDED") {
+ return {
+ actionId: action.id,
+ activityId: current.externalId,
+ replayed: true,
+ };
+ }
+ throw new Error("This agent action is already in progress.");
+ }
+
+ try {
+ const activityId = `agent-action-${action.id}`;
+ const now = new Date();
+
+ await db.$transaction(async (tx) => {
+ await tx.activity.upsert({
+ where: { id: activityId },
+ create: {
+ id: activityId,
+ type: input.type === "TASK" ? ActivityType.TASK : ActivityType.NOTE,
+ subject: input.subject?.trim() || null,
+ body: input.body?.trim() || null,
+ occurredAt: now,
+ dueAt: input.type === "TASK" ? dueAt : null,
+ companyId: target.companyId,
+ contactId: target.contactId,
+ dealId: target.dealId,
+ createdById: run.initiatedById ?? run.agent.createdById,
+ meta: {
+ source: "agent",
+ agentId: run.agentId,
+ runId,
+ actionId: action.id,
+ },
+ },
+ update: {},
+ });
+
+ if (target.companyId) {
+ await tx.company.update({
+ where: { id: target.companyId },
+ data: { lastActivityAt: now },
+ });
+ }
+ if (target.contactId) {
+ await tx.contact.update({
+ where: { id: target.contactId },
+ data: { lastActivityAt: now },
+ });
+ }
+ if (target.dealId) {
+ await tx.deal.update({
+ where: { id: target.dealId },
+ data: { lastActivityAt: now },
+ });
+ }
+
+ await tx.agentAction.update({
+ where: { id: action.id },
+ data: {
+ status: "SUCCEEDED",
+ externalId: activityId,
+ completedAt: now,
+ },
+ });
+ });
+
+ return { actionId: action.id, activityId, replayed: false };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ await db.agentAction.updateMany({
+ where: { id: action.id, status: "RUNNING" },
+ data: {
+ status: "FAILED",
+ errorCode: "ACTION_REJECTED",
+ errorMessage: message,
+ completedAt: new Date(),
+ },
+ });
+ throw error;
+ }
+}
+
+export async function stageRunResult(
+ runId: string,
+ input: { summary: string; result?: Record<string, unknown> | null },
+) {
+ return db.$transaction(async (tx) => {
+ const run = await lockAgentRun(tx, runId);
+ if (run.status !== "RUNNING") {
+ throw new Error(`This agent run already ended with ${run.status}.`);
+ }
+
+ await assertRunSummaryAllowed(tx, run.versionId);
+ await tx.agentRun.update({
+ where: { id: runId },
+ data: {
+ summary: input.summary,
+ result: (input.result ?? {}) as Prisma.InputJsonValue,
+ },
+ });
+
+ return { id: run.id, status: "RUNNING" as const };
+ });
+}
+
+export async function finishRun(
+ runId: string,
+ input: { summary: string; result?: Record<string, unknown> | null },
+) {
+ return db.$transaction(async (tx) => {
+ const run = await lockAgentRun(tx, runId);
+ if (run.status === "SUCCEEDED") {
+ return { id: run.id, status: "SUCCEEDED" as const };
+ }
+ if (run.status !== "RUNNING") {
+ throw new Error(`This agent run already ended with ${run.status}.`);
+ }
+ await assertRunSummaryAllowed(tx, run.versionId);
+
+ const sequence = run.nextEventSequence + 1;
+ const finishedAt = new Date();
+ await tx.agentRun.update({
+ where: { id: runId },
+ data: {
+ status: "SUCCEEDED",
+ summary: input.summary,
+ result: (input.result ?? {}) as Prisma.InputJsonValue,
+ finishedAt,
+ nextEventSequence: sequence,
+ },
+ });
+ await tx.agentRunEvent.create({
+ data: {
+ id: runTerminalEventId(run.id, "completed"),
+ runId: run.id,
+ sequence,
+ type: "run.completed",
+ data: { summary: input.summary },
+ emittedAt: finishedAt,
+ },
+ });
+ await tx.agentAuditEvent.upsert({
+ where: {
+ agentId_type_requestId: {
+ agentId: run.agentId,
+ type: "run.completed",
+ requestId: run.id,
+ },
+ },
+ create: {
+ agentId: run.agentId,
+ versionId: run.versionId,
+ actorType: "AGENT",
+ actorId: run.id,
+ type: "run.completed",
+ summary: input.summary,
+ requestId: run.id,
+ },
+ update: {},
+ });
+
+ return { id: run.id, status: "SUCCEEDED" as const };
+ });
+}
+
+async function assertRunSummaryAllowed(
+ tx: Prisma.TransactionClient,
+ versionId: string,
+): Promise<void> {
+ const version = await tx.agentVersion.findUniqueOrThrow({
+ where: { id: versionId },
+ select: { manifest: true },
+ });
+ if (
+ !manifestActions(version.manifest).some(
+ (action) => action.type === "run.summary",
+ )
+ ) {
+ throw new Error("Agent version does not allow a run summary.");
+ }
+}
+
+function manifestDataScope(value: unknown): {
+ mode: RunRecordScope;
+ resources: RunResource[];
+} {
+ const manifest = recordOf(value);
+ const scope = recordOf(manifest.dataScope);
+ if (scope.mode !== "SELECTED" && scope.mode !== "WORKSPACE") {
+ throw new Error("Agent version has no valid CRM record scope.");
+ }
+ if (!Array.isArray(scope.resources)) {
+ throw new Error("Agent version has no valid CRM resources.");
+ }
+
+ const resources = scope.resources.flatMap((resource) => {
+ if (!resource || typeof resource !== "object") return [];
+ const row = resource as Record<string, unknown>;
+ if (
+ !["integration", "company", "contact", "deal"].includes(
+ String(row.kind),
+ ) ||
+ typeof row.id !== "string" ||
+ typeof row.label !== "string"
+ ) {
+ return [];
+ }
+ return [resource as RunResource];
+ });
+ const records = resources.filter(
+ (resource) => resource.kind !== "integration",
+ );
+ if (scope.mode === "SELECTED" && records.length === 0) {
+ throw new Error("Agent version selected no CRM records.");
+ }
+ if (scope.mode === "WORKSPACE" && records.length > 0) {
+ throw new Error("Agent version mixes workspace and selected CRM scope.");
+ }
+ return { mode: scope.mode, resources };
+}
+
+function manifestActions(value: unknown) {
+ const actions = recordOf(value).actions;
+ return Array.isArray(actions) ? actions.map(recordOf) : [];
+}
+
+function assertActivityAllowed(
+ manifest: unknown,
+ activityType: "NOTE" | "TASK",
+) {
+ const allowed = manifestActions(manifest).some(
+ (action) =>
+ action.type === "crm.activity.create" &&
+ Array.isArray(action.activityTypes) &&
+ action.activityTypes.includes(activityType),
+ );
+ if (!allowed) {
+ throw new Error(
+ `Agent version does not allow CRM ${activityType.toLowerCase()} activities.`,
+ );
+ }
+}
+
+function assertResourceAllowed(
+ mode: RunRecordScope,
+ resources: RunResource[],
+ input: { kind: "contact" | "company" | "deal"; id: string },
+) {
+ if (mode === "WORKSPACE") return;
+ const records = resources.filter(
+ (resource) => resource.kind !== "integration",
+ );
+ if (
+ records.some(
+ (resource) => resource.kind === input.kind && resource.id === input.id,
+ )
+ ) {
+ return;
+ }
+ throw new Error(
+ "That CRM record is outside this agent version's approved scope.",
+ );
+}
+
+export function allowedHistorySources(resources: RunResource[]): {
+ gmail: boolean;
+ calendar: boolean;
+} {
+ const integrations = new Set(
+ resources
+ .filter((resource) => resource.kind === "integration")
+ .map((resource) => resource.id),
+ );
+ return {
+ gmail: integrations.has("google:gmail"),
+ calendar: integrations.has("google:calendar"),
+ };
+}
+
+async function targetRecord(kind: "company" | "contact" | "deal", id: string) {
+ if (kind === "company") {
+ const company = await db.company.findUnique({
+ where: { id },
+ select: { id: true, name: true },
+ });
+ return company
+ ? {
+ label: company.name,
+ companyId: company.id,
+ contactId: null,
+ dealId: null,
+ }
+ : null;
+ }
+ if (kind === "contact") {
+ const contact = await db.contact.findUnique({
+ where: { id },
+ select: { id: true, firstName: true, lastName: true, companyId: true },
+ });
+ return contact
+ ? {
+ label: [contact.firstName, contact.lastName]
+ .filter(Boolean)
+ .join(" "),
+ companyId: contact.companyId,
+ contactId: contact.id,
+ dealId: null,
+ }
+ : null;
+ }
+
+ const deal = await db.deal.findUnique({
+ where: { id },
+ select: { id: true, name: true, companyId: true },
+ });
+ return deal
+ ? {
+ label: deal.name,
+ companyId: deal.companyId,
+ contactId: null,
+ dealId: deal.id,
+ }
+ : null;
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function actionRequestHash(input: {
+ type: "NOTE" | "TASK";
+ targetKind: "company" | "contact" | "deal";
+ targetId: string;
+ subject?: string | null;
+ body?: string | null;
+ dueAt?: string | null;
+}): string {
+ return createHash("sha256")
+ .update(
+ JSON.stringify({
+ type: input.type,
+ targetKind: input.targetKind,
+ targetId: input.targetId,
+ subject: input.subject?.trim() || null,
+ body: input.body?.trim() || null,
+ dueAt: input.dueAt?.trim() || null,
+ }),
+ )
+ .digest("hex");
+}
+
+function assertActionRequestMatches(
+ existingHash: string | null,
+ requestHash: string,
+): void {
+ if (existingHash !== requestHash) {
+ throw new Error("That agent action call was already used for other input.");
+ }
+}
diff --git a/apps/agent/agent/lib/run-state.ts b/apps/agent/agent/lib/run-state.ts
new file mode 100644
index 00000000..e92f0656
--- /dev/null
+++ b/apps/agent/agent/lib/run-state.ts
@@ -0,0 +1,33 @@
+import type { Prisma } from "@crm/db";
+import type { AgentRunStatus } from "@crm/db/enums";
+
+export type LockedAgentRun = {
+ id: string;
+ agentId: string;
+ versionId: string;
+ status: AgentRunStatus;
+ sessionId: string | null;
+ startedAt: Date | null;
+ nextEventSequence: number;
+};
+
+export async function lockAgentRun(
+ tx: Prisma.TransactionClient,
+ runId: string,
+): Promise<LockedAgentRun> {
+ const [run] = await tx.$queryRaw<LockedAgentRun[]>`
+ SELECT id, "agentId", "versionId", status, "sessionId", "startedAt", "nextEventSequence"
+ FROM "agentRun"
+ WHERE id = ${runId}
+ FOR UPDATE
+ `;
+ if (!run) throw new Error("This agent run is unavailable.");
+ return run;
+}
+
+export function runTerminalEventId(
+ runId: string,
+ terminal: "completed" | "failed",
+) {
+ return `run-terminal:${runId}:${terminal}`;
+}
diff --git a/apps/agent/agent/lib/session-purpose.ts b/apps/agent/agent/lib/session-purpose.ts
new file mode 100644
index 00000000..2b85f12d
--- /dev/null
+++ b/apps/agent/agent/lib/session-purpose.ts
@@ -0,0 +1,69 @@
+export type SessionPurpose = "builder" | "team-agent" | "research";
+
+type PurposeContext = {
+ readonly session: {
+ readonly auth: {
+ readonly current: {
+ readonly attributes: Readonly<Record<string, unknown>>;
+ } | null;
+ readonly initiator: {
+ readonly attributes: Readonly<Record<string, unknown>>;
+ } | null;
+ };
+ };
+};
+
+export function purposeOf(ctx: PurposeContext): SessionPurpose {
+ const purpose = attribute(ctx, "purpose");
+ if (purpose === "builder" || purpose === "team-agent") return purpose;
+ return "research";
+}
+
+export function attribute(ctx: PurposeContext, key: string): string | null {
+ const current = ctx.session.auth.current?.attributes[key];
+ if (typeof current === "string" && current.trim()) return current.trim();
+
+ const initiator = ctx.session.auth.initiator?.attributes[key];
+ return typeof initiator === "string" && initiator.trim()
+ ? initiator.trim()
+ : null;
+}
+
+export function requireAttribute(ctx: PurposeContext, key: string): string {
+ const value = attribute(ctx, key);
+ if (!value) throw new Error(`This session is missing ${key}.`);
+ return value;
+}
+
+export function requireBuilderAttribute(
+ ctx: PurposeContext,
+ key: string,
+): string {
+ if (
+ purposeOf(ctx) !== "builder" ||
+ attribute(ctx, "commandType") !== "CREATE_AGENT"
+ ) {
+ throw new Error(
+ "Agent creation requires an explicit request to create or build an agent.",
+ );
+ }
+ return requireAttribute(ctx, key);
+}
+
+export function requireTeamAgentAttribute(
+ ctx: PurposeContext,
+ key: string,
+): string {
+ if (purposeOf(ctx) !== "team-agent") {
+ throw new Error(
+ "This deployed-agent tool is unavailable for this session.",
+ );
+ }
+ return requireAttribute(ctx, key);
+}
+
+export function assertResearchPurpose(ctx: PurposeContext): void {
+ if (purposeOf(ctx) !== "research") {
+ throw new Error("This CRM research tool is unavailable for this session.");
+ }
+}
diff --git a/apps/agent/agent/schedules/dispatch.ts b/apps/agent/agent/schedules/dispatch.ts
index e1d81d65..4662099d 100644
--- a/apps/agent/agent/schedules/dispatch.ts
+++ b/apps/agent/agent/schedules/dispatch.ts
@@ -1,18 +1,49 @@
import { defineSchedule } from "eve/schedules";
import crm from "../channels/crm";
+import {
+ pendingAgentRunIds,
+ pendingBuilderSubmissionIds,
+ queueDueAgentRuns,
+} from "../lib/custom-agent-dispatch";
import { brief, drainAll, taskAuth } from "../lib/dispatch";
export default defineSchedule({
cron: "* * * * *",
async run({ receive, waitUntil, appAuth }) {
waitUntil(
- drainAll((task) =>
- receive(crm, {
- message: brief(task),
- target: { taskId: task.id },
- auth: taskAuth(task, appAuth),
- }),
- ),
+ Promise.all([
+ drainAll((task) =>
+ receive(crm, {
+ message: brief(task),
+ target: { taskId: task.id },
+ auth: taskAuth(task, appAuth),
+ }),
+ ),
+ (async () => {
+ await queueDueAgentRuns();
+ const [builderIds, runIds] = await Promise.all([
+ pendingBuilderSubmissionIds(),
+ pendingAgentRunIds(),
+ ]);
+
+ await Promise.all([
+ ...builderIds.map((builderSubmissionId) =>
+ receive(crm, {
+ message: "Continue a queued private agent-builder chat.",
+ target: { builderSubmissionId },
+ auth: appAuth,
+ }),
+ ),
+ ...runIds.map((runId) =>
+ receive(crm, {
+ message: "Execute a queued deployed agent run.",
+ target: { runId },
+ auth: appAuth,
+ }),
+ ),
+ ]);
+ })(),
+ ]),
);
},
});
diff --git a/apps/agent/agent/subagents/agent_builder/agent.ts b/apps/agent/agent/subagents/agent_builder/agent.ts
new file mode 100644
index 00000000..19b75699
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/agent.ts
@@ -0,0 +1,39 @@
+import { DEFAULT_AGENT_MODEL } from "@crm/db/settings";
+import { defineAgent, defineDynamic } from "eve";
+import { z } from "zod";
+import { selectedModel } from "../../lib/model";
+
+export default defineAgent({
+ description:
+ "Turn one private CRM builder-chat request into a validated, reviewable team-agent version without deploying it.",
+ model: defineDynamic({
+ fallback: DEFAULT_AGENT_MODEL.id,
+ events: { "session.started": () => selectedModel() },
+ }),
+ outputSchema: z.discriminatedUnion("status", [
+ z.object({
+ status: z.literal("needs_input"),
+ question: z.string().min(1).max(500),
+ options: z
+ .array(
+ z.object({
+ id: z.string().min(1).max(80),
+ label: z.string().min(1).max(120),
+ }),
+ )
+ .max(4),
+ allowFreeform: z.boolean(),
+ }),
+ z.object({
+ status: z.literal("draft_ready"),
+ summary: z.string().min(1).max(1000),
+ agentId: z.string().min(1),
+ versionId: z.string().min(1),
+ }),
+ ]),
+ limits: {
+ maxInputTokensPerSession: 250_000,
+ maxOutputTokensPerSession: 20_000,
+ sessionTimeoutMs: 24 * 60 * 60 * 1000,
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_builder/instructions.md b/apps/agent/agent/subagents/agent_builder/instructions.md
new file mode 100644
index 00000000..6506c68e
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/instructions.md
@@ -0,0 +1,64 @@
+# CRM agent builder
+
+You design one bounded internal team agent from the request delegated by the
+private builder chat.
+
+Call `inspect_context` first. It is the authority for connected integrations,
+selected CRM records, the current time, and any existing draft. Never invent a
+connection or record.
+
+The user should not need to provide a complete specification. Treat a short
+description of the job or desired outcome as enough to draft when a safe,
+bounded interpretation exists. Use the inspected CRM context and existing draft
+to do the design work: infer a clear name, instructions, relevant CRM record
+types, and useful output. When omitted, prefer a manual trigger, no external
+integration, and `run.summary` over a side effect. Use exact tagged records when
+present. A request about a pipeline, workspace-wide collection, or class of CRM
+records may use `WORKSPACE`; do not expand a request about one record into
+workspace access. Human review of the completed draft is the place to expose
+these choices.
+
+Make the smallest agent that solves the stated pain. Its instructions must say
+exactly when it runs, which CRM records it may read, what output or CRM action
+it may produce, and when it must stop. Preserve the user's meaning and wording
+where that is clearer than a rewrite.
+
+The currently executable action types are `crm.activity.create` for CRM notes
+and tasks, and `run.summary` for a logged result with no external side effect.
+Gmail and Google Calendar are read-only sources when connected. Do not promise
+email sending, Slack, arbitrary webhooks, or any integration the context does
+not report.
+
+If no safe and useful draft is possible because an essential target, explicitly
+requested connection, schedule, outcome, or side effect remains ambiguous, do
+not call `save_agent_draft`. Return `needs_input` with one focused question for
+the parent to ask the user. Include two to four mutually exclusive options when
+they clarify a real choice, and set `allowFreeform` when a custom answer is
+valid. Ask only when the answer materially changes the bounded behavior and the
+least-privilege defaults above do not resolve it. Return exactly one decision
+per pause; never bundle several missing details into one question. After the
+answer, ask the next question only if the build is still materially blocked. Do
+not interrupt for a name, wording, optional polish, or another choice that can
+be safely represented in the reviewable draft. For a schedule, calculate a
+future `nextRunAt` from the supplied current time and provide its recurrence in
+minutes.
+
+Choose the record scope explicitly. Use `SELECTED` only for the exact tagged CRM
+records reported by `inspect_context`. Use `WORKSPACE` only when the user clearly
+asks for workspace-wide CRM access. Never treat an empty selected scope as
+workspace access.
+
+For `crm.activity.create`, list the exact allowed activity types. Authorize
+`NOTE`, `TASK`, or both only when the request calls for them. A prose summary
+never grants an activity type by itself.
+
+When the behavior is specific and supported, build the agent in front of the
+user. Call `write_agent_file` for `agent/instructions.md`, then
+`agent/manifest.json`, then `agent/README.md`. These are durable working
+revisions, so write complete useful contents and revise a file with another
+call when necessary. Never put credentials, tokens, or secret values in a
+file. After the three files agree, call `save_agent_draft` once with the exact
+same behavior. A successful save creates exact final file snapshots and an
+immutable version in READY state for human review. It does not deploy it.
+Return `draft_ready` with the saved agent and version ids plus a plain-language
+summary of the trigger, data scope, action, and access.
diff --git a/apps/agent/agent/subagents/agent_builder/sandbox/sandbox.ts b/apps/agent/agent/subagents/agent_builder/sandbox/sandbox.ts
new file mode 100644
index 00000000..a9f1c9fb
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/sandbox/sandbox.ts
@@ -0,0 +1,9 @@
+import { defaultBackend, defineSandbox } from "eve/sandbox";
+
+export default defineSandbox({
+ backend: defaultBackend({
+ vercel: { networkPolicy: "deny-all" },
+ docker: { networkPolicy: "deny-all" },
+ microsandbox: { networkPolicy: "deny-all" },
+ }),
+});
diff --git a/apps/agent/agent/subagents/agent_builder/tools/ask_question.ts b/apps/agent/agent/subagents/agent_builder/tools/ask_question.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/ask_question.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/bash.ts b/apps/agent/agent/subagents/agent_builder/tools/bash.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/bash.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/glob.ts b/apps/agent/agent/subagents/agent_builder/tools/glob.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/glob.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/grep.ts b/apps/agent/agent/subagents/agent_builder/tools/grep.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/grep.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/inspect_context.ts b/apps/agent/agent/subagents/agent_builder/tools/inspect_context.ts
new file mode 100644
index 00000000..53890c44
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/inspect_context.ts
@@ -0,0 +1,16 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { builderContext } from "../../../lib/builder-runtime";
+import { requireBuilderAttribute } from "../../../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Read the authoritative builder-chat scope, connected sources, selected CRM records, current time, and latest draft.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ return builderContext(
+ requireBuilderAttribute(ctx, "conversationId"),
+ requireBuilderAttribute(ctx, "userId"),
+ );
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_builder/tools/read_file.ts b/apps/agent/agent/subagents/agent_builder/tools/read_file.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/read_file.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/save_agent_draft.ts b/apps/agent/agent/subagents/agent_builder/tools/save_agent_draft.ts
new file mode 100644
index 00000000..3528a620
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/save_agent_draft.ts
@@ -0,0 +1,57 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { saveBuilderDraft } from "../../../lib/builder-runtime";
+import { requireBuilderAttribute } from "../../../lib/session-purpose";
+
+const resource = z.object({
+ kind: z.enum(["integration", "company", "contact", "deal"]),
+ id: z.string().min(1),
+ label: z.string().min(1).max(120),
+});
+
+const trigger = z.object({
+ type: z.enum(["MANUAL", "SCHEDULE"]),
+ name: z.string().min(1).max(120),
+ summary: z.string().min(1).max(240),
+ nextRunAt: z.string().nullish(),
+ intervalMinutes: z.number().int().min(1).max(525_600).nullish(),
+});
+
+const action = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("crm.activity.create"),
+ provider: z.literal("crm"),
+ summary: z.string().min(1).max(240),
+ activityTypes: z
+ .array(z.enum(["NOTE", "TASK"]))
+ .min(1)
+ .max(2),
+ }),
+ z.object({
+ type: z.literal("run.summary"),
+ provider: z.literal("crm"),
+ summary: z.string().min(1).max(240),
+ }),
+]);
+
+export default defineTool({
+ description:
+ "Validate and save one immutable agent version for human review. This never deploys the agent.",
+ inputSchema: z.object({
+ name: z.string().trim().min(1).max(100),
+ description: z.string().trim().min(1).max(320),
+ instructions: z.string().trim().min(40).max(20_000),
+ trigger,
+ recordScope: z.enum(["SELECTED", "WORKSPACE"]),
+ resources: z.array(resource).max(30),
+ actions: z.array(action).min(1).max(10),
+ access: z.array(z.string().trim().min(1).max(120)).max(20),
+ }),
+ async execute(input, ctx) {
+ return saveBuilderDraft(
+ requireBuilderAttribute(ctx, "conversationId"),
+ requireBuilderAttribute(ctx, "userId"),
+ input,
+ );
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_builder/tools/todo.ts b/apps/agent/agent/subagents/agent_builder/tools/todo.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/todo.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/web_fetch.ts b/apps/agent/agent/subagents/agent_builder/tools/web_fetch.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/web_fetch.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/web_search.ts b/apps/agent/agent/subagents/agent_builder/tools/web_search.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/web_search.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_builder/tools/write_agent_file.ts b/apps/agent/agent/subagents/agent_builder/tools/write_agent_file.ts
new file mode 100644
index 00000000..8e46d38a
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/write_agent_file.ts
@@ -0,0 +1,24 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import {
+ BUILDER_ARTIFACT_PATHS,
+ writeBuilderArtifact,
+} from "../../../lib/builder-runtime";
+import { requireBuilderAttribute } from "../../../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Write one durable agent file revision so the user can follow the build live. Write instructions and the manifest before saving the final draft.",
+ inputSchema: z.object({
+ path: z.enum(BUILDER_ARTIFACT_PATHS),
+ content: z.string().min(1).max(40_000),
+ }),
+ async execute(input, ctx) {
+ return writeBuilderArtifact(
+ requireBuilderAttribute(ctx, "conversationId"),
+ requireBuilderAttribute(ctx, "userId"),
+ input.path,
+ input.content,
+ );
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_builder/tools/write_file.ts b/apps/agent/agent/subagents/agent_builder/tools/write_file.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_builder/tools/write_file.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/agent.ts b/apps/agent/agent/subagents/agent_runner/agent.ts
new file mode 100644
index 00000000..1d8be775
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/agent.ts
@@ -0,0 +1,44 @@
+import { db } from "@crm/db";
+import { DEFAULT_AGENT_MODEL } from "@crm/db/settings";
+import { defineAgent, defineDynamic } from "eve";
+import { z } from "zod";
+import { attribute, purposeOf } from "../../lib/session-purpose";
+
+export default defineAgent({
+ description:
+ "Execute one immutable deployed CRM agent version and persist its result and every side effect.",
+ model: defineDynamic({
+ fallback: DEFAULT_AGENT_MODEL.id,
+ events: {
+ "session.started": async (_event, ctx) => {
+ if (purposeOf(ctx) !== "team-agent") return null;
+ const runId = attribute(ctx, "runId");
+ if (!runId) return null;
+
+ const run = await db.agentRun.findUnique({
+ where: { id: runId },
+ select: {
+ version: {
+ select: { modelId: true, modelContextWindowTokens: true },
+ },
+ },
+ });
+ return run
+ ? {
+ model: run.version.modelId,
+ modelContextWindowTokens: run.version.modelContextWindowTokens,
+ }
+ : null;
+ },
+ },
+ }),
+ outputSchema: z.object({
+ summary: z.string().min(1).max(1000),
+ result: z.record(z.string(), z.unknown()).nullable(),
+ }),
+ limits: {
+ maxInputTokensPerSession: 500_000,
+ maxOutputTokensPerSession: 40_000,
+ sessionTimeoutMs: 24 * 60 * 60 * 1000,
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_runner/instructions.md b/apps/agent/agent/subagents/agent_runner/instructions.md
new file mode 100644
index 00000000..850a703a
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/instructions.md
@@ -0,0 +1,24 @@
+# Deployed CRM agent runner
+
+Execute exactly one pinned team-agent run.
+
+The approved version instructions are supplied as system instructions at
+session start. Call `inspect_run` first for its immutable manifest, trigger,
+approved scope, allowed actions, and current time. Follow the approved business
+intent only through the tools exposed here. Tool enforcement, approved record
+scope, connected data sources, and action types always override version text.
+
+Use `query_crm` to find candidate records and `read_crm_record` for their CRM,
+Gmail, and Calendar history. Those sources are read-only. Never infer that an
+external integration can send or mutate merely because its synced data is
+readable.
+
+`create_crm_activity` is the only current side-effecting tool. Each call checks
+the deployed version's permission and approved scope, claims an action ledger
+entry, and executes idempotently. Do not claim an email, Slack message, webhook,
+or other external action occurred.
+
+Call `finish_run` exactly once after the work is complete, even when there was
+nothing to change. Give a concise factual summary and a small structured result.
+Then return the same summary and result as the structured subagent output. Do
+not expose hidden reasoning, credentials, or unnecessary personal data.
diff --git a/apps/agent/agent/subagents/agent_runner/instructions/run.ts b/apps/agent/agent/subagents/agent_runner/instructions/run.ts
new file mode 100644
index 00000000..d9af57b2
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/instructions/run.ts
@@ -0,0 +1,17 @@
+import { defineDynamic, defineInstructions } from "eve/instructions";
+import { approvedRunInstructions } from "../../../lib/run-runtime";
+import { attribute, purposeOf } from "../../../lib/session-purpose";
+
+export default defineDynamic({
+ events: {
+ "session.started": async (_event, ctx) => {
+ if (purposeOf(ctx) !== "team-agent") return null;
+ const runId = attribute(ctx, "runId");
+ if (!runId) return null;
+
+ return defineInstructions({
+ markdown: `# Human-approved version instructions\n\n${await approvedRunInstructions(runId)}`,
+ });
+ },
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_runner/sandbox/sandbox.ts b/apps/agent/agent/subagents/agent_runner/sandbox/sandbox.ts
new file mode 100644
index 00000000..a9f1c9fb
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/sandbox/sandbox.ts
@@ -0,0 +1,9 @@
+import { defaultBackend, defineSandbox } from "eve/sandbox";
+
+export default defineSandbox({
+ backend: defaultBackend({
+ vercel: { networkPolicy: "deny-all" },
+ docker: { networkPolicy: "deny-all" },
+ microsandbox: { networkPolicy: "deny-all" },
+ }),
+});
diff --git a/apps/agent/agent/subagents/agent_runner/tools/ask_question.ts b/apps/agent/agent/subagents/agent_runner/tools/ask_question.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/ask_question.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/bash.ts b/apps/agent/agent/subagents/agent_runner/tools/bash.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/bash.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/create_crm_activity.ts b/apps/agent/agent/subagents/agent_runner/tools/create_crm_activity.ts
new file mode 100644
index 00000000..f510e7bb
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/create_crm_activity.ts
@@ -0,0 +1,24 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { createRunActivity } from "../../../lib/run-runtime";
+import { requireTeamAgentAttribute } from "../../../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Create an approved internal CRM note or task on an approved record. The version must allow the exact activity type. The action is logged before it executes and is idempotent across retries.",
+ inputSchema: z.object({
+ type: z.enum(["NOTE", "TASK"]),
+ targetKind: z.enum(["company", "contact", "deal"]),
+ targetId: z.string().min(1),
+ subject: z.string().trim().max(240).nullish(),
+ body: z.string().trim().max(10_000).nullish(),
+ dueAt: z.string().nullish(),
+ }),
+ async execute(input, ctx) {
+ return createRunActivity(
+ requireTeamAgentAttribute(ctx, "runId"),
+ ctx.callId,
+ input,
+ );
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_runner/tools/finish_run.ts b/apps/agent/agent/subagents/agent_runner/tools/finish_run.ts
new file mode 100644
index 00000000..c312d254
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/finish_run.ts
@@ -0,0 +1,16 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { stageRunResult } from "../../../lib/run-runtime";
+import { requireTeamAgentAttribute } from "../../../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Finish this run successfully with its concise summary and structured result.",
+ inputSchema: z.object({
+ summary: z.string().trim().min(1).max(1000),
+ result: z.record(z.string(), z.unknown()).nullish(),
+ }),
+ async execute(input, ctx) {
+ return stageRunResult(requireTeamAgentAttribute(ctx, "runId"), input);
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_runner/tools/glob.ts b/apps/agent/agent/subagents/agent_runner/tools/glob.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/glob.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/grep.ts b/apps/agent/agent/subagents/agent_runner/tools/grep.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/grep.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/inspect_run.ts b/apps/agent/agent/subagents/agent_runner/tools/inspect_run.ts
new file mode 100644
index 00000000..1ae44c21
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/inspect_run.ts
@@ -0,0 +1,13 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { runContext } from "../../../lib/run-runtime";
+import { requireTeamAgentAttribute } from "../../../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Read the immutable version manifest, trigger, approved scope, allowed actions, and current time for this run.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ return runContext(requireTeamAgentAttribute(ctx, "runId"));
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_runner/tools/query_crm.ts b/apps/agent/agent/subagents/agent_runner/tools/query_crm.ts
new file mode 100644
index 00000000..34f762e0
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/query_crm.ts
@@ -0,0 +1,17 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { queryRunCrm } from "../../../lib/run-runtime";
+import { requireTeamAgentAttribute } from "../../../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Search contacts, companies, and deals inside this deployed version's approved CRM scope.",
+ inputSchema: z.object({
+ query: z.string().trim().min(2).max(160),
+ kinds: z.array(z.enum(["contact", "company", "deal"])).optional(),
+ limit: z.number().int().min(1).max(50).default(20),
+ }),
+ async execute(input, ctx) {
+ return queryRunCrm(requireTeamAgentAttribute(ctx, "runId"), input);
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_runner/tools/read_crm_record.ts b/apps/agent/agent/subagents/agent_runner/tools/read_crm_record.ts
new file mode 100644
index 00000000..ec77d347
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/read_crm_record.ts
@@ -0,0 +1,16 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { readRunRecord } from "../../../lib/run-runtime";
+import { requireTeamAgentAttribute } from "../../../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Read one approved CRM record with its CRM history and only the connected email or calendar sources approved by this version.",
+ inputSchema: z.object({
+ kind: z.enum(["contact", "company", "deal"]),
+ id: z.string().min(1),
+ }),
+ async execute(input, ctx) {
+ return readRunRecord(requireTeamAgentAttribute(ctx, "runId"), input);
+ },
+});
diff --git a/apps/agent/agent/subagents/agent_runner/tools/read_file.ts b/apps/agent/agent/subagents/agent_runner/tools/read_file.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/read_file.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/todo.ts b/apps/agent/agent/subagents/agent_runner/tools/todo.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/todo.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/web_fetch.ts b/apps/agent/agent/subagents/agent_runner/tools/web_fetch.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/web_fetch.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/web_search.ts b/apps/agent/agent/subagents/agent_runner/tools/web_search.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/web_search.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/subagents/agent_runner/tools/write_file.ts b/apps/agent/agent/subagents/agent_runner/tools/write_file.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/subagents/agent_runner/tools/write_file.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/tools/agent.ts b/apps/agent/agent/tools/agent.ts
new file mode 100644
index 00000000..04bd0544
--- /dev/null
+++ b/apps/agent/agent/tools/agent.ts
@@ -0,0 +1,3 @@
+import { disableTool } from "eve/tools";
+
+export default disableTool();
diff --git a/apps/agent/agent/tools/enrich_company.ts b/apps/agent/agent/tools/enrich_company.ts
index 5b034c56..58fc2acd 100644
--- a/apps/agent/agent/tools/enrich_company.ts
+++ b/apps/agent/agent/tools/enrich_company.ts
@@ -2,6 +2,7 @@ import { defineTool } from "eve/tools";
import { z } from "zod";
import { runBrand } from "../lib/brand";
import { spend } from "../lib/focus";
+import { assertResearchPurpose } from "../lib/session-purpose";
export default defineTool({
description:
@@ -15,7 +16,8 @@ export default defineTool({
"Bypass the vendor's ~90-day cache. Only when a rep has asked for a fresh look.",
),
}),
- async execute({ companyId, fresh }) {
+ async execute({ companyId, fresh }, ctx) {
+ assertResearchPurpose(ctx);
const result = await runBrand({ companyId, fresh, spend });
if (!result.enriched) {
diff --git a/apps/agent/agent/tools/fetch_contact_photo.ts b/apps/agent/agent/tools/fetch_contact_photo.ts
index 8b8f6f04..46999e86 100644
--- a/apps/agent/agent/tools/fetch_contact_photo.ts
+++ b/apps/agent/agent/tools/fetch_contact_photo.ts
@@ -3,6 +3,7 @@ import { defineTool } from "eve/tools";
import { z } from "zod";
import { spend } from "../lib/focus";
import { runPortrait } from "../lib/portrait";
+import { assertResearchPurpose } from "../lib/session-purpose";
export default defineTool({
description:
@@ -14,7 +15,8 @@ export default defineTool({
.default(false)
.describe("Replace an existing photo. Only when a rep asked."),
}),
- async execute({ contactId, force }) {
+ async execute({ contactId, force }, ctx) {
+ assertResearchPurpose(ctx);
if (!blobEnabled()) {
return {
stored: false as const,
diff --git a/apps/agent/agent/tools/identify_contact.ts b/apps/agent/agent/tools/identify_contact.ts
index 015e8e3b..e31f7d28 100644
--- a/apps/agent/agent/tools/identify_contact.ts
+++ b/apps/agent/agent/tools/identify_contact.ts
@@ -4,6 +4,7 @@ import type { Evidence, EvidenceKind } from "../lib/evidence";
import { WEIGHTS } from "../lib/evidence";
import { recordFact } from "../lib/facts";
import { focusOn } from "../lib/focus";
+import { assertResearchPurpose } from "../lib/session-purpose";
export default defineTool({
description:
@@ -24,7 +25,8 @@ export default defineTool({
.min(1),
sourceUrl: z.string().describe("The page a rep should open to check."),
}),
- async execute(input) {
+ async execute(input, ctx) {
+ assertResearchPurpose(ctx);
focusOn({ contactId: input.contactId });
const result = await recordFact({
diff --git a/apps/agent/agent/tools/list_deals.ts b/apps/agent/agent/tools/list_deals.ts
new file mode 100644
index 00000000..5f8bb3f8
--- /dev/null
+++ b/apps/agent/agent/tools/list_deals.ts
@@ -0,0 +1,48 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import { listDeals } from "../lib/lookup";
+import { assertResearchPurpose } from "../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "List deals across the CRM with pipeline status and inactivity filters. Use this for broad requests such as all open deals, stale deals, deals untouched for a number of days, or a pipeline sweep. Results are oldest-touch first and paginated; continue with nextCursor while hasMore is true. Free.",
+ inputSchema: z.object({
+ status: z.enum(["open", "won", "lost", "all"]).default("open"),
+ inactiveForDays: z
+ .number()
+ .int()
+ .min(0)
+ .max(3650)
+ .optional()
+ .describe(
+ "Return deals whose last activity was at least this many days ago. Deals with no activity qualify once they are this old.",
+ ),
+ companyId: z.string().optional(),
+ ownerId: z.string().optional(),
+ limit: z.number().int().min(1).max(100).default(50),
+ cursor: z.string().optional(),
+ }),
+ async execute(input, ctx) {
+ assertResearchPurpose(ctx);
+ return listDeals(input);
+ },
+ toModelOutput(output) {
+ return {
+ type: "json",
+ value: {
+ ...output,
+ deals: output.deals.map((deal) => ({
+ ...deal,
+ company: { id: deal.company.id, name: deal.company.name },
+ owner: deal.owner
+ ? {
+ id: deal.owner.id,
+ name: deal.owner.name,
+ email: deal.owner.email,
+ }
+ : null,
+ })),
+ },
+ };
+ },
+});
diff --git a/apps/agent/agent/tools/record_fact.ts b/apps/agent/agent/tools/record_fact.ts
index 1f4925d8..899400f2 100644
--- a/apps/agent/agent/tools/record_fact.ts
+++ b/apps/agent/agent/tools/record_fact.ts
@@ -4,6 +4,7 @@ import type { Evidence, EvidenceKind } from "../lib/evidence";
import { WEIGHTS } from "../lib/evidence";
import { FACT_FIELDS, type FactField, recordFact } from "../lib/facts";
import { focusOn } from "../lib/focus";
+import { assertResearchPurpose } from "../lib/session-purpose";
export default defineTool({
description:
@@ -44,7 +45,8 @@ export default defineTool({
.optional()
.describe("The page a rep should open to check."),
}),
- async execute(input) {
+ async execute(input, ctx) {
+ assertResearchPurpose(ctx);
focusOn({ contactId: input.contactId });
const result = await recordFact({
diff --git a/apps/agent/agent/tools/record_job_change.ts b/apps/agent/agent/tools/record_job_change.ts
index f6b6688e..d7fdbb72 100644
--- a/apps/agent/agent/tools/record_job_change.ts
+++ b/apps/agent/agent/tools/record_job_change.ts
@@ -5,6 +5,7 @@ import { sensitiveWrite } from "../lib/approval";
import { writeTimelineNote } from "../lib/crm";
import { lastEmployerChange } from "../lib/facts";
import { focusOn } from "../lib/focus";
+import { assertResearchPurpose } from "../lib/session-purpose";
export default defineTool({
description:
@@ -21,7 +22,8 @@ export default defineTool({
approval: sensitiveWrite(
"Raise the change without `moveToCompanyId` — the alert lands on the timeline and their owner decides whether to move them.",
),
- async execute({ contactId, moveToCompanyId }) {
+ async execute({ contactId, moveToCompanyId }, ctx) {
+ assertResearchPurpose(ctx);
focusOn({ contactId });
const change = await lastEmployerChange(contactId);
diff --git a/apps/agent/agent/tools/schedule_recheck.ts b/apps/agent/agent/tools/schedule_recheck.ts
index 53af62b0..fa918891 100644
--- a/apps/agent/agent/tools/schedule_recheck.ts
+++ b/apps/agent/agent/tools/schedule_recheck.ts
@@ -1,6 +1,7 @@
import { PRIORITY } from "@crm/db/agent-tasks";
import { defineTool } from "eve/tools";
import { z } from "zod";
+import { assertResearchPurpose } from "../lib/session-purpose";
import { scheduleTask } from "../lib/tasks";
const MIN_DAYS = 1;
@@ -33,7 +34,8 @@ export default defineTool({
.default(4)
.describe("Vendor calls the next run may spend."),
}),
- async execute({ contactId, days, reason, budget }) {
+ async execute({ contactId, days, reason, budget }, ctx) {
+ assertResearchPurpose(ctx);
const dueAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000);
await scheduleTask({
diff --git a/apps/agent/agent/tools/set_chat_title.ts b/apps/agent/agent/tools/set_chat_title.ts
new file mode 100644
index 00000000..9ad62cf3
--- /dev/null
+++ b/apps/agent/agent/tools/set_chat_title.ts
@@ -0,0 +1,26 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+import {
+ BUILDER_CONVERSATION_TITLE_MAX_LENGTH,
+ setBuilderConversationTitle,
+} from "../lib/conversation-title";
+import { purposeOf, requireAttribute } from "../lib/session-purpose";
+
+export default defineTool({
+ description:
+ "Set the concise title for a new private builder chat. Available only when the current turn says the chat needs a title.",
+ inputSchema: z.object({
+ title: z.string().trim().min(1).max(BUILDER_CONVERSATION_TITLE_MAX_LENGTH),
+ }),
+ async execute({ title }, ctx) {
+ if (purposeOf(ctx) !== "builder") {
+ throw new Error("Chat titles can only be set in builder conversations.");
+ }
+
+ return setBuilderConversationTitle(
+ requireAttribute(ctx, "conversationId"),
+ requireAttribute(ctx, "userId"),
+ title,
+ );
+ },
+});
diff --git a/apps/agent/agent/tools/set_contact_socials.ts b/apps/agent/agent/tools/set_contact_socials.ts
index 28ac10f1..8011c730 100644
--- a/apps/agent/agent/tools/set_contact_socials.ts
+++ b/apps/agent/agent/tools/set_contact_socials.ts
@@ -4,6 +4,7 @@ import { personForVerification } from "../lib/crm";
import type { Evidence } from "../lib/evidence";
import { recordFact } from "../lib/facts";
import { focusOn } from "../lib/focus";
+import { assertResearchPurpose } from "../lib/session-purpose";
import { parseSocialUrl, verifyGithub, verifyX } from "../lib/socials";
export default defineTool({
@@ -22,7 +23,8 @@ export default defineTool({
"A candidate github.com profile URL from find_contact_socials.",
),
}),
- async execute({ contactId, twitterUrl, githubUrl }) {
+ async execute({ contactId, twitterUrl, githubUrl }, ctx) {
+ assertResearchPurpose(ctx);
focusOn({ contactId });
const person = await personForVerification(contactId);
diff --git a/apps/agent/agent/tools/write_brief.ts b/apps/agent/agent/tools/write_brief.ts
index 95f0684a..190d1f04 100644
--- a/apps/agent/agent/tools/write_brief.ts
+++ b/apps/agent/agent/tools/write_brief.ts
@@ -4,6 +4,7 @@ import type { Evidence, EvidenceKind } from "../lib/evidence";
import { WEIGHTS } from "../lib/evidence";
import { writeBrief } from "../lib/facts";
import { focusOn } from "../lib/focus";
+import { assertResearchPurpose } from "../lib/session-purpose";
const MAX_NARRATIVE = 400;
@@ -47,7 +48,8 @@ export default defineTool({
.min(1),
sourceUrl: z.string().optional(),
}),
- async execute(input) {
+ async execute(input, ctx) {
+ assertResearchPurpose(ctx);
focusOn({ contactId: input.contactId });
const narrative = input.narrative.trim();
diff --git a/apps/agent/agent/tools/write_workspace_profile.ts b/apps/agent/agent/tools/write_workspace_profile.ts
index 0c94a313..5618f357 100644
--- a/apps/agent/agent/tools/write_workspace_profile.ts
+++ b/apps/agent/agent/tools/write_workspace_profile.ts
@@ -7,6 +7,7 @@ import {
import { defineTool } from "eve/tools";
import { z } from "zod";
import { currentFocus } from "../lib/focus";
+import { assertResearchPurpose } from "../lib/session-purpose";
import { identity } from "../lib/workspace";
const line = (what: string) =>
@@ -35,7 +36,8 @@ export default defineTool({
),
sourceUrl: z.string().optional(),
}),
- async execute(input) {
+ async execute(input, ctx) {
+ assertResearchPurpose(ctx);
const us = await identity();
if (!us?.website) {
diff --git a/apps/agent/evals/agent-builder.eval.ts b/apps/agent/evals/agent-builder.eval.ts
new file mode 100644
index 00000000..f32c620e
--- /dev/null
+++ b/apps/agent/evals/agent-builder.eval.ts
@@ -0,0 +1,174 @@
+import { db } from "@crm/db";
+import { defineEval } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
+
+export default defineEval({
+ description:
+ "Turn a short outcome request into a safe, review-only team agent through the durable CRM channel.",
+ tags: ["builder", "integration"],
+ timeoutMs: 180_000,
+ async test(t) {
+ const secret = process.env.AGENT_BRIDGE_SECRET?.trim();
+ if (
+ !process.env.DATABASE_URL ||
+ !secret ||
+ (!process.env.AI_GATEWAY_API_KEY && !process.env.VERCEL_OIDC_TOKEN)
+ ) {
+ t.skip(
+ "Requires DATABASE_URL, AGENT_BRIDGE_SECRET, and an AI Gateway credential.",
+ );
+ return;
+ }
+
+ const suffix = crypto.randomUUID();
+ const userId = `builder-eval-user-${suffix}`;
+ let conversationId: string | null = null;
+ let sessionId: string | null = null;
+
+ try {
+ await db.user.create({
+ data: {
+ id: userId,
+ name: "Agent Builder Eval",
+ email: `${userId}@example.test`,
+ },
+ });
+ const conversation = await db.agentConversation.create({
+ data: {
+ kind: "BUILDER",
+ userId,
+ submissions: {
+ create: {
+ submittedById: userId,
+ clientRequestId: crypto.randomUUID(),
+ commandType: "CREATE_AGENT",
+ message: {
+ text: "Build me an agent that gives me a snapshot of our CRM accounts.",
+ resources: [],
+ },
+ },
+ },
+ },
+ select: { id: true },
+ });
+ conversationId = conversation.id;
+
+ const response = await t.target.fetch("/internal/crm/builder-dispatch", {
+ method: "POST",
+ headers: { authorization: `Bearer ${secret}` },
+ });
+ await t.require(response.status, equals(202));
+
+ sessionId = await waitForBuilderSession(conversation.id, t.signal);
+ await t.require(
+ sessionId,
+ satisfies(
+ (value) => typeof value === "string",
+ "builder session started",
+ ),
+ );
+ const session = await t.target.attachSession(sessionId as string);
+ session.succeeded();
+ session.calledSubagent("agent_builder", { count: 1 });
+ session.notCalledTool("record_fact");
+ session.notCalledTool("record_job_change");
+
+ const saved = await db.agentConversation.findUniqueOrThrow({
+ where: { id: conversation.id },
+ select: {
+ agent: {
+ select: {
+ status: true,
+ versions: {
+ orderBy: { number: "desc" },
+ take: 1,
+ select: { status: true, manifest: true },
+ },
+ },
+ },
+ builderArtifacts: {
+ where: { status: "READY" },
+ select: { path: true },
+ },
+ },
+ });
+ t.check(saved.agent?.status, equals("DRAFT"));
+ t.check(saved.agent?.versions[0]?.status, equals("READY"));
+ t.check(saved.builderArtifacts.length, equals(3));
+ t.check(
+ saved.agent?.versions[0]?.manifest,
+ satisfies((value) => {
+ const manifest = recordOf(value);
+ const scope = recordOf(manifest.dataScope);
+ const actions = Array.isArray(manifest.actions)
+ ? manifest.actions.map(recordOf)
+ : [];
+ return (
+ scope.mode === "WORKSPACE" &&
+ actions.length === 1 &&
+ actions[0]?.type === "run.summary"
+ );
+ }, "saved manifest is workspace-scoped and side-effect-free"),
+ );
+ } finally {
+ await cleanupBuilderEval(userId, conversationId, sessionId);
+ }
+ },
+});
+
+async function waitForBuilderSession(
+ conversationId: string,
+ signal: AbortSignal,
+): Promise<string | null> {
+ for (let attempt = 0; attempt < 600; attempt += 1) {
+ if (signal.aborted) return null;
+ const conversation = await db.agentConversation.findUnique({
+ where: { id: conversationId },
+ select: { sessionId: true },
+ });
+ if (conversation?.sessionId) return conversation.sessionId;
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ return null;
+}
+
+async function cleanupBuilderEval(
+ userId: string,
+ conversationId: string | null,
+ sessionId: string | null,
+) {
+ const agents = await db.agentDefinition.findMany({
+ where: { createdById: userId },
+ select: { id: true },
+ });
+ const agentIds = agents.map((agent) => agent.id);
+ if (sessionId) await db.agentEvent.deleteMany({ where: { sessionId } });
+ if (conversationId) {
+ await db.agentBuilderArtifact.deleteMany({ where: { conversationId } });
+ }
+ if (agentIds.length > 0) {
+ await db.agentBuilderArtifact.deleteMany({
+ where: { version: { agentId: { in: agentIds } } },
+ });
+ await db.agentAuditEvent.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentTrigger.deleteMany({ where: { agentId: { in: agentIds } } });
+ await db.agentDefinition.updateMany({
+ where: { id: { in: agentIds } },
+ data: { currentVersionId: null },
+ });
+ await db.agentVersion.deleteMany({ where: { agentId: { in: agentIds } } });
+ await db.agentDefinition.deleteMany({ where: { id: { in: agentIds } } });
+ }
+ if (conversationId) {
+ await db.agentConversation.deleteMany({ where: { id: conversationId } });
+ }
+ await db.user.deleteMany({ where: { id: userId } });
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
diff --git a/apps/agent/evals/evals.config.ts b/apps/agent/evals/evals.config.ts
new file mode 100644
index 00000000..b482d055
--- /dev/null
+++ b/apps/agent/evals/evals.config.ts
@@ -0,0 +1,6 @@
+import { defineEvalConfig } from "eve/evals";
+
+export default defineEvalConfig({
+ maxConcurrency: 1,
+ timeoutMs: 180_000,
+});
diff --git a/apps/agent/package.json b/apps/agent/package.json
index 0c437819..b65d0454 100644
--- a/apps/agent/package.json
+++ b/apps/agent/package.json
@@ -6,13 +6,14 @@
"license": "MIT",
"scripts": {
"backfill:images": "bun scripts/backfill-brand-images.ts",
- "dev": "eve dev --no-ui",
- "dev:tui": "eve dev",
+ "dev": "eve dev",
+ "dev:headless": "eve dev --no-ui",
"dispatch": "curl -fsS -X POST \"${AGENT_URL:-http://127.0.0.1:2000}/eve/v1/dev/schedules/dispatch\"",
"build": "eve build",
- "start": "eve start",
+ "start": "bun scripts/start.ts",
"check-types": "tsc --noEmit",
"test": "CRM_TELEMETRY_DISABLED=1 bun test",
+ "eval": "CRM_TELEMETRY_DISABLED=1 eve eval",
"lint": "biome check .",
"clean": "rm -rf .turbo .eve node_modules"
},
@@ -27,6 +28,7 @@
"devDependencies": {
"@crm/typescript-config": "workspace:*",
"@types/node": "^24.0.0",
+ "just-bash": "^3.2.0",
"microsandbox": "^0.6.8",
"typescript": "^5.9.2"
}
diff --git a/apps/agent/scripts/start.ts b/apps/agent/scripts/start.ts
new file mode 100644
index 00000000..af93f7e5
--- /dev/null
+++ b/apps/agent/scripts/start.ts
@@ -0,0 +1,42 @@
+import { spawn } from "node:child_process";
+import { constants } from "node:os";
+
+const rawPort = process.env.AGENT_PORT ?? process.env.PORT ?? "2000";
+const port = Number(rawPort);
+
+if (!Number.isInteger(port) || port < 1 || port > 65_535) {
+ throw new Error(
+ `AGENT_PORT or PORT must be a valid port, received ${rawPort}.`,
+ );
+}
+
+const cli = process.platform === "win32" ? "eve.cmd" : "eve";
+const child = spawn(cli, ["start", "--port", String(port)], {
+ stdio: "inherit",
+ env: process.env,
+});
+
+let settled = false;
+
+const finish = (code: number) => {
+ if (settled) return;
+ settled = true;
+ process.exitCode = code;
+};
+
+const forward = (signal: NodeJS.Signals) => {
+ if (!child.killed) child.kill(signal);
+};
+
+process.once("SIGINT", forward);
+process.once("SIGTERM", forward);
+
+child.once("exit", (code, signal) => {
+ const signalNumber = signal ? constants.signals[signal] : null;
+ finish(code ?? (signalNumber ? 128 + signalNumber : 1));
+});
+
+child.once("error", (error) => {
+ console.error(`[agent] could not start eve: ${error.message}`);
+ finish(1);
+});
diff --git a/apps/agent/test/accounts.integration.spec.ts b/apps/agent/test/accounts.integration.spec.ts
index e66747c7..536eaf0e 100644
--- a/apps/agent/test/accounts.integration.spec.ts
+++ b/apps/agent/test/accounts.integration.spec.ts
@@ -257,6 +257,25 @@ describe("readCompanyHistory", () => {
]);
});
+ it("omits connected history when the caller did not approve those sources", async () => {
+ const history = await readCompanyHistory(companyId, {
+ includeEmail: false,
+ includeCalendar: false,
+ });
+
+ expect(history?.threads).toEqual([]);
+ expect(history?.meetings).toEqual([]);
+ expect(history?.stats.emails).toBe(0);
+ expect(history?.stats.meetings).toBe(0);
+ expect(history?.stats.lastReplyAt).toBeNull();
+ expect(history?.stats.nextMeetingAt).toBeNull();
+ expect(
+ history?.people.every(
+ (person) => person.threads === 0 && person.meetings === 0,
+ ),
+ ).toBe(true);
+ });
+
it("returns null for a company that does not exist", async () => {
expect(await readCompanyHistory("nope")).toBeNull();
});
@@ -303,6 +322,19 @@ describe("readDealHistory", () => {
expect(history?.note).toContain("never against a deal");
});
+ it("omits deal correspondence when connected sources are not approved", async () => {
+ const history = await readDealHistory(dealId, {
+ includeEmail: false,
+ includeCalendar: false,
+ });
+
+ expect(history?.threads).toEqual([]);
+ expect(history?.meetings).toEqual([]);
+ expect(history?.stats.theyReplied).toBe(false);
+ expect(history?.stats.nextMeetingAt).toBeNull();
+ expect(history?.note).toContain("outside this agent version");
+ });
+
it("returns null for a deal that does not exist", async () => {
expect(await readDealHistory("nope")).toBeNull();
});
diff --git a/apps/agent/test/builder-runtime.integration.spec.ts b/apps/agent/test/builder-runtime.integration.spec.ts
new file mode 100644
index 00000000..ba625c6f
--- /dev/null
+++ b/apps/agent/test/builder-runtime.integration.spec.ts
@@ -0,0 +1,361 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { db } from "@crm/db";
+import {
+ saveBuilderDraft,
+ writeBuilderArtifact,
+} from "../agent/lib/builder-runtime";
+import { setBuilderConversationTitle } from "../agent/lib/conversation-title";
+
+const suffix = crypto.randomUUID();
+const userId = `builder-runtime-user-${suffix}`;
+let conversationId = "";
+let agentId = "";
+const conversationIds: string[] = [];
+
+beforeAll(async () => {
+ await db.user.create({
+ data: {
+ id: userId,
+ name: "Builder Runtime Test",
+ email: `${userId}@example.test`,
+ },
+ });
+ const conversation = await db.agentConversation.create({
+ data: { kind: "BUILDER", userId },
+ select: { id: true },
+ });
+ conversationId = conversation.id;
+ conversationIds.push(conversation.id);
+});
+
+afterAll(async () => {
+ const agentIds = (
+ await db.agentDefinition.findMany({
+ where: { createdById: userId },
+ select: { id: true },
+ })
+ ).map((agent) => agent.id);
+ if (agentIds.length > 0) {
+ await db.agentBuilderArtifact.deleteMany({
+ where: {
+ OR: [
+ { conversationId: { in: conversationIds } },
+ { version: { agentId: { in: agentIds } } },
+ ],
+ },
+ });
+ await db.agentAuditEvent.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentTrigger.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentDefinition.updateMany({
+ where: { id: { in: agentIds } },
+ data: { currentVersionId: null },
+ });
+ await db.agentVersion.deleteMany({
+ where: { agentId: { in: agentIds } },
+ });
+ await db.agentDefinition.deleteMany({
+ where: { id: { in: agentIds } },
+ });
+ }
+ await db.agentConversation.deleteMany({
+ where: { id: { in: conversationIds } },
+ });
+ await db.user.deleteMany({ where: { id: userId } });
+});
+
+describe("builder persistence", () => {
+ it("sets a concise model-authored title only once", async () => {
+ const conversation = await db.agentConversation.create({
+ data: { kind: "BUILDER", userId },
+ select: { id: true },
+ });
+ conversationIds.push(conversation.id);
+
+ expect(
+ await setBuilderConversationTitle(
+ conversation.id,
+ userId,
+ " “Flag stale pipeline deals” ",
+ ),
+ ).toEqual({ saved: true, title: "Flag stale pipeline deals" });
+ expect(
+ await setBuilderConversationTitle(
+ conversation.id,
+ userId,
+ "Replace the title",
+ ),
+ ).toEqual({ saved: false, title: "Flag stale pipeline deals" });
+ });
+
+ it("serializes concurrent file writes and draft saves", async () => {
+ const instructions =
+ "When manually triggered, review the approved CRM scope and write a concise run summary without changing external systems.";
+ const writes = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ writeBuilderArtifact(
+ conversationId,
+ userId,
+ "agent/instructions.md",
+ `${instructions}\n`,
+ ),
+ ),
+ );
+
+ expect(new Set(writes.map((write) => write.id)).size).toBe(1);
+ expect(new Set(writes.map((write) => write.revision))).toEqual(
+ new Set([1]),
+ );
+
+ const input = {
+ name: "Meeting prep",
+ description: "Prepare a concise CRM meeting brief.",
+ instructions,
+ trigger: {
+ type: "MANUAL" as const,
+ name: "Manual",
+ summary: "Run when a rep requests meeting preparation.",
+ },
+ recordScope: "WORKSPACE" as const,
+ resources: [],
+ actions: [
+ {
+ type: "run.summary" as const,
+ provider: "crm" as const,
+ summary: "Write a run summary.",
+ },
+ ],
+ access: ["Read CRM records in the approved scope"],
+ };
+ const saves = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ saveBuilderDraft(conversationId, userId, input),
+ ),
+ );
+ const saved = saves.flatMap((save) => (save.saved ? [save] : []));
+
+ expect(saved).toHaveLength(4);
+ expect(new Set(saved.map((save) => save.agentId)).size).toBe(1);
+ expect(new Set(saved.map((save) => save.versionId)).size).toBe(1);
+ agentId = saved[0]?.agentId ?? "";
+ expect(await db.agentDefinition.count({ where: { id: agentId } })).toBe(1);
+ expect(await db.agentVersion.count({ where: { agentId } })).toBe(1);
+
+ const artifact = await db.agentBuilderArtifact.findFirstOrThrow({
+ where: { conversationId, path: "agent/instructions.md" },
+ orderBy: { revision: "desc" },
+ select: { revision: true, status: true, versionId: true },
+ });
+ expect(artifact).toEqual({
+ revision: 1,
+ status: "READY",
+ versionId: saved[0]?.versionId,
+ });
+ });
+
+ it("assigns consecutive versions to distinct concurrent drafts", async () => {
+ const conversation = await db.agentConversation.create({
+ data: { kind: "BUILDER", userId },
+ select: { id: true },
+ });
+ conversationIds.push(conversation.id);
+ const base = {
+ description: "Prepare a distinct CRM run summary.",
+ trigger: {
+ type: "MANUAL" as const,
+ name: "Manual",
+ summary: "Run when a rep requests it.",
+ },
+ recordScope: "WORKSPACE" as const,
+ resources: [],
+ actions: [
+ {
+ type: "run.summary" as const,
+ provider: "crm" as const,
+ summary: "Write a run summary.",
+ },
+ ],
+ access: ["Read workspace CRM records"],
+ };
+ const saves = await Promise.all(
+ Array.from({ length: 4 }, (_, index) =>
+ saveBuilderDraft(conversation.id, userId, {
+ ...base,
+ name: `Concurrent draft ${index + 1}`,
+ instructions: `When manually triggered, prepare distinct CRM summary ${index + 1} without changing external systems.`,
+ }),
+ ),
+ );
+ const saved = saves.flatMap((save) => (save.saved ? [save] : []));
+
+ expect(saved).toHaveLength(4);
+ expect(new Set(saved.map((save) => save.agentId)).size).toBe(1);
+ expect(saved.map((save) => save.versionNumber).sort()).toEqual([
+ 1, 2, 3, 4,
+ ]);
+ expect(
+ await db.agentVersion.count({
+ where: { agentId: saved[0]?.agentId },
+ }),
+ ).toBe(4);
+ });
+
+ it("fails closed on unsupported integrations and ambiguous record scope", async () => {
+ const conversation = await db.agentConversation.create({
+ data: { kind: "BUILDER", userId },
+ select: { id: true },
+ });
+ conversationIds.push(conversation.id);
+ const base = {
+ name: "Safe scope",
+ description: "Keep a bounded CRM summary.",
+ instructions:
+ "When manually triggered, read only the approved CRM scope and return a concise summary without changing CRM records.",
+ trigger: {
+ type: "MANUAL" as const,
+ name: "Manual",
+ summary: "Run only when a teammate requests it.",
+ },
+ actions: [
+ {
+ type: "run.summary" as const,
+ provider: "crm" as const,
+ summary: "Return a run summary.",
+ },
+ ],
+ access: ["Read approved CRM records"],
+ };
+
+ const unsupported = await saveBuilderDraft(conversation.id, userId, {
+ ...base,
+ recordScope: "WORKSPACE",
+ resources: [
+ { kind: "integration", id: "google:drive", label: "Google Drive" },
+ ],
+ });
+ expect(unsupported).toMatchObject({
+ saved: false,
+ issues: ["Google Drive is not an available integration."],
+ });
+
+ const ambiguous = await saveBuilderDraft(conversation.id, userId, {
+ ...base,
+ recordScope: "SELECTED",
+ resources: [],
+ });
+ expect(ambiguous).toMatchObject({
+ saved: false,
+ issues: ["Selected CRM scope needs at least one tagged record."],
+ });
+ });
+
+ it("keeps a live definition unchanged until a revised version is deployed", async () => {
+ const conversation = await db.agentConversation.create({
+ data: { kind: "BUILDER", userId },
+ select: { id: true },
+ });
+ conversationIds.push(conversation.id);
+
+ const original = {
+ name: "Workspace pulse",
+ description: "Report the workspace company count.",
+ instructions:
+ "When manually triggered, read workspace companies and return the company count in a concise run summary without changing CRM records.",
+ trigger: {
+ type: "MANUAL" as const,
+ name: "Manual",
+ summary: "Run when a teammate requests a workspace pulse.",
+ },
+ recordScope: "WORKSPACE" as const,
+ resources: [],
+ actions: [
+ {
+ type: "run.summary" as const,
+ provider: "crm" as const,
+ summary: "Write a run summary.",
+ },
+ ],
+ access: ["Read workspace CRM records"],
+ };
+ const first = await saveBuilderDraft(conversation.id, userId, original);
+ if (!first.saved) throw new Error("Initial draft was not saved");
+
+ await db.$transaction([
+ db.agentVersion.update({
+ where: { id: first.versionId },
+ data: { status: "DEPLOYED" },
+ }),
+ db.agentDefinition.update({
+ where: { id: first.agentId },
+ data: {
+ name: "Workspace pulse",
+ description: "Team-visible description",
+ status: "LIVE",
+ currentVersionId: first.versionId,
+ },
+ }),
+ ]);
+
+ const revised = {
+ ...original,
+ name: "Workspace health pulse",
+ description: "Report company and open-deal counts.",
+ };
+ await writeBuilderArtifact(
+ conversation.id,
+ userId,
+ "agent/README.md",
+ `# ${revised.name}\n\n${revised.description}\n\n## Trigger\n\n${revised.trigger.summary}\n\n## Access\n\n- ${revised.access[0]}\n`,
+ );
+ const second = await saveBuilderDraft(conversation.id, userId, revised);
+ if (!second.saved) throw new Error("Revised draft was not saved");
+
+ const [definition, version, artifacts] = await Promise.all([
+ db.agentDefinition.findUniqueOrThrow({
+ where: { id: first.agentId },
+ select: {
+ name: true,
+ description: true,
+ status: true,
+ currentVersionId: true,
+ },
+ }),
+ db.agentVersion.findUniqueOrThrow({
+ where: { id: second.versionId },
+ select: { number: true, status: true, manifest: true },
+ }),
+ db.agentBuilderArtifact.findMany({
+ where: { conversationId: conversation.id, versionId: second.versionId },
+ select: { path: true, status: true },
+ }),
+ ]);
+
+ expect(second.versionId).not.toBe(first.versionId);
+ expect(definition).toEqual({
+ name: "Workspace pulse",
+ description: "Team-visible description",
+ status: "LIVE",
+ currentVersionId: first.versionId,
+ });
+ expect(version).toMatchObject({
+ number: 2,
+ status: "READY",
+ manifest: {
+ name: revised.name,
+ description: revised.description,
+ },
+ });
+ expect(artifacts).toHaveLength(3);
+ expect(artifacts.every((artifact) => artifact.status === "READY")).toBe(
+ true,
+ );
+ expect(
+ await db.agentBuilderArtifact.count({
+ where: { conversationId: conversation.id, status: "WRITING" },
+ }),
+ ).toBe(0);
+ });
+});
diff --git a/apps/agent/test/custom-agent-runtime.spec.ts b/apps/agent/test/custom-agent-runtime.spec.ts
new file mode 100644
index 00000000..963136fa
--- /dev/null
+++ b/apps/agent/test/custom-agent-runtime.spec.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it } from "bun:test";
+import { builderTaskMarkdown } from "../agent/instructions/task";
+import {
+ builderCommandType,
+ builderDeliveryMessage,
+ builderIdFromToken,
+ builderToken,
+ runIdFromToken,
+ runToken,
+} from "../agent/lib/custom-agent-dispatch";
+import { allowedHistorySources } from "../agent/lib/run-runtime";
+import {
+ assertResearchPurpose,
+ attribute,
+ purposeOf,
+ requireBuilderAttribute,
+ requireTeamAgentAttribute,
+} from "../agent/lib/session-purpose";
+
+const context = (purpose?: string, commandType?: string) => ({
+ session: {
+ auth: {
+ current: purpose
+ ? {
+ attributes: {
+ purpose,
+ conversationId: "chat-1",
+ commandType,
+ },
+ }
+ : { attributes: {} },
+ initiator: { attributes: { userId: "user-1" } },
+ },
+ },
+});
+
+describe("custom agent continuation tokens", () => {
+ it("round-trips a builder conversation through the channel token", () => {
+ expect(builderIdFromToken(builderToken("chat-1"))).toBe("chat-1");
+ expect(builderIdFromToken(`crm:${builderToken("chat-1")}`)).toBe("chat-1");
+ });
+
+ it("round-trips a team agent run without accepting another token kind", () => {
+ expect(runIdFromToken(runToken("run-1"))).toBe("run-1");
+ expect(runIdFromToken(builderToken("chat-1"))).toBeNull();
+ });
+});
+
+describe("builder delivery messages", () => {
+ it("keeps clarification answers in agent-creation mode", () => {
+ expect(
+ builderCommandType("CHAT", {
+ inputResponse: { requestId: "question-1", answer: "crm-task" },
+ }),
+ ).toBe("CREATE_AGENT");
+ expect(builderCommandType("CHAT", { text: "Research this company" })).toBe(
+ "CHAT",
+ );
+ });
+
+ it("delivers a question response without submission wrapper text", () => {
+ expect(
+ builderDeliveryMessage("submission-1", {
+ text: "Use a CRM task instead",
+ inputResponse: {
+ requestId: "question-1",
+ answer: "crm-task",
+ },
+ }),
+ ).toBe("crm-task");
+ });
+
+ it("delivers persisted attachment bytes with model-visible metadata", () => {
+ const content = Buffer.from("quarterly plan");
+ const message = builderDeliveryMessage(
+ "submission-2",
+ { text: "Summarize this file", resources: [], attachments: [] },
+ [
+ {
+ name: "plan.txt",
+ mediaType: "text/plain",
+ content,
+ },
+ ],
+ );
+
+ expect(message).toEqual([
+ {
+ type: "text",
+ text: "Submission id: submission-2\n\nSummarize this file",
+ },
+ {
+ type: "file",
+ data: content,
+ mediaType: "text/plain",
+ filename: "plan.txt",
+ },
+ ]);
+ });
+});
+
+describe("session purpose boundaries", () => {
+ it("reads current-turn attributes before initiator attributes", () => {
+ expect(attribute(context("builder"), "conversationId")).toBe("chat-1");
+ expect(attribute(context("builder"), "userId")).toBe("user-1");
+ });
+
+ it("defaults ordinary CRM sessions to research", () => {
+ expect(purposeOf(context())).toBe("research");
+ expect(() => assertResearchPurpose(context())).not.toThrow();
+ });
+
+ it("rejects research writes from builder and team-agent sessions", () => {
+ expect(() => assertResearchPurpose(context("builder"))).toThrow();
+ expect(() => assertResearchPurpose(context("team-agent"))).toThrow();
+ });
+
+ it("binds specialist tools to their explicit session purpose", () => {
+ expect(
+ requireBuilderAttribute(
+ context("builder", "CREATE_AGENT"),
+ "conversationId",
+ ),
+ ).toBe("chat-1");
+ expect(() =>
+ requireBuilderAttribute(context("builder", "CHAT"), "conversationId"),
+ ).toThrow();
+ expect(() =>
+ requireTeamAgentAttribute(context("builder"), "runId"),
+ ).toThrow();
+ });
+});
+
+describe("deployed agent data sources", () => {
+ it("enables only integrations stored in the approved manifest", () => {
+ expect(allowedHistorySources([])).toEqual({
+ gmail: false,
+ calendar: false,
+ });
+ expect(
+ allowedHistorySources([
+ { kind: "integration", id: "google:gmail", label: "Gmail" },
+ ]),
+ ).toEqual({ gmail: true, calendar: false });
+ });
+});
+
+describe("builder command routing", () => {
+ it("delegates only the explicit creation command to the agent builder", () => {
+ const creation = builderTaskMarkdown("CREATE_AGENT");
+ expect(creation).toContain("Call agent_builder exactly once");
+ expect(creation).toContain("call ask_question");
+ expect(creation).toContain("exactly one decision at a time");
+ expect(creation).toContain(
+ "Do not interrupt a sufficiently specific request",
+ );
+ const chat = builderTaskMarkdown("CHAT");
+ expect(chat).toContain("Do not call agent_builder");
+ expect(chat).toContain("call ask_question");
+ expect(chat).toContain("one focused follow-up");
+ expect(chat).toContain(
+ "Do not restate or enumerate individual deal rows in prose, bullets, or tables",
+ );
+ expect(builderTaskMarkdown(null)).toContain("private CRM assistant chat");
+ });
+
+ it("requires the configured model to title only a new builder chat", () => {
+ const untitled = builderTaskMarkdown("CHAT", true);
+ expect(untitled).toContain("call set_chat_title once");
+ expect(untitled).toContain("three to seven words");
+ expect(builderTaskMarkdown("CHAT", false)).not.toContain("set_chat_title");
+ });
+});
diff --git a/apps/agent/test/durable-agent-runtime.integration.spec.ts b/apps/agent/test/durable-agent-runtime.integration.spec.ts
new file mode 100644
index 00000000..41663744
--- /dev/null
+++ b/apps/agent/test/durable-agent-runtime.integration.spec.ts
@@ -0,0 +1,641 @@
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { db } from "@crm/db";
+import type { SendFn } from "eve/channels";
+import audit from "../agent/hooks/audit";
+import {
+ builderToken,
+ dispatchAgentRun,
+ dispatchBuilderSubmission,
+ failRun,
+ pendingAgentRunIds,
+ pendingBuilderSubmissionIds,
+ queueDueAgentRuns,
+} from "../agent/lib/custom-agent-dispatch";
+import {
+ createRunActivity,
+ finishRun,
+ stageRunResult,
+} from "../agent/lib/run-runtime";
+
+const suffix = crypto.randomUUID();
+const userId = `durable-runtime-user-${suffix}`;
+const domain = `durable-${suffix}.example.test`;
+let agentId = "";
+let versionId = "";
+let companyId = "";
+let otherCompanyId = "";
+let triggerId = "";
+const builderConversationIds: string[] = [];
+
+beforeAll(async () => {
+ await db.user.create({
+ data: {
+ id: userId,
+ name: "Durable Runtime Test",
+ email: `${userId}@example.test`,
+ },
+ });
+ const [company, otherCompany] = await Promise.all([
+ db.company.create({
+ data: { name: "Durable Runtime Company", domain },
+ select: { id: true },
+ }),
+ db.company.create({
+ data: { name: "Out of Scope Company", domain: `other-${domain}` },
+ select: { id: true },
+ }),
+ ]);
+ companyId = company.id;
+ otherCompanyId = otherCompany.id;
+
+ const agent = await db.agentDefinition.create({
+ data: {
+ name: "Durable runtime",
+ status: "LIVE",
+ createdById: userId,
+ },
+ select: { id: true },
+ });
+ agentId = agent.id;
+ const version = await db.agentVersion.create({
+ data: {
+ agentId,
+ number: 1,
+ status: "DEPLOYED",
+ instructions: "Create one approved CRM activity.",
+ manifest: {
+ dataScope: {
+ mode: "SELECTED",
+ resources: [
+ {
+ kind: "company",
+ id: companyId,
+ label: "Durable Runtime Company",
+ },
+ ],
+ },
+ actions: [
+ { type: "crm.activity.create", activityTypes: ["NOTE"] },
+ { type: "run.summary" },
+ ],
+ },
+ modelId: "test/model",
+ sandboxPolicy: {},
+ createdById: userId,
+ approvedAt: new Date(),
+ deployedAt: new Date(),
+ },
+ select: { id: true },
+ });
+ versionId = version.id;
+ await db.agentDefinition.update({
+ where: { id: agentId },
+ data: { currentVersionId: versionId },
+ });
+ const trigger = await db.agentTrigger.create({
+ data: {
+ agentId,
+ versionId,
+ type: "SCHEDULE",
+ name: "Every hour",
+ config: { intervalMinutes: 60 },
+ createdById: userId,
+ enabled: true,
+ nextRunAt: new Date(Date.now() - 60_000),
+ },
+ select: { id: true },
+ });
+ triggerId = trigger.id;
+});
+
+afterAll(async () => {
+ if (builderConversationIds.length > 0) {
+ await db.agentConversation.deleteMany({
+ where: { id: { in: builderConversationIds } },
+ });
+ }
+ if (agentId) {
+ await db.agentEvent.deleteMany({
+ where: { sessionId: { startsWith: `durable-session-${suffix}` } },
+ });
+ await db.agentRunEvent.deleteMany({ where: { run: { agentId } } });
+ await db.agentAction.deleteMany({ where: { agentId } });
+ await db.activity.deleteMany({
+ where: { meta: { path: ["agentId"], equals: agentId } },
+ });
+ await db.agentAuditEvent.deleteMany({ where: { agentId } });
+ await db.agentRun.deleteMany({ where: { agentId } });
+ await db.agentTrigger.deleteMany({ where: { agentId } });
+ await db.agentDefinition.updateMany({
+ where: { id: agentId },
+ data: { currentVersionId: null },
+ });
+ await db.agentVersion.deleteMany({ where: { agentId } });
+ await db.agentDefinition.deleteMany({ where: { id: agentId } });
+ }
+ await db.company.deleteMany({
+ where: { id: { in: [companyId, otherCompanyId] } },
+ });
+ await db.user.deleteMany({ where: { id: userId } });
+});
+
+async function createRun(
+ status: "QUEUED" | "RUNNING" = "RUNNING",
+ startedAt: Date | null = new Date(),
+ sessionId: string | null = null,
+) {
+ return db.agentRun.create({
+ data: {
+ agentId,
+ versionId,
+ triggerType: "MANUAL",
+ status,
+ startedAt,
+ sessionId,
+ idempotencyKey: `durable-run-${crypto.randomUUID()}`,
+ correlationId: crypto.randomUUID(),
+ events: { create: { sequence: 0, type: "run.queued", data: {} } },
+ },
+ select: { id: true },
+ });
+}
+
+describe("durable custom-agent runtime", () => {
+ it("advances a due trigger only when its run is committed", async () => {
+ const now = new Date();
+ const results = await Promise.all(
+ Array.from({ length: 4 }, () => queueDueAgentRuns(now)),
+ );
+
+ expect(results.reduce((total, count) => total + count, 0)).toBe(1);
+ const [trigger, scheduledRuns] = await Promise.all([
+ db.agentTrigger.findUniqueOrThrow({ where: { id: triggerId } }),
+ db.agentRun.findMany({
+ where: { triggerId },
+ select: { id: true, status: true, input: true },
+ }),
+ ]);
+ expect(trigger.lastRunAt).not.toBeNull();
+ expect(trigger.nextRunAt?.getTime()).toBeGreaterThan(now.getTime());
+ expect(scheduledRuns).toHaveLength(1);
+ expect(scheduledRuns[0]?.status).toBe("QUEUED");
+ });
+
+ it("recovers only sessionless runs with an expired delivery lease", async () => {
+ const stale = new Date(Date.now() - 10 * 60_000);
+ const [recoverable, active] = await Promise.all([
+ createRun("RUNNING", stale),
+ createRun("RUNNING", stale, `durable-session-${suffix}-already-started`),
+ ]);
+
+ const pending = await pendingAgentRunIds();
+ const [recovered, untouched] = await Promise.all([
+ db.agentRun.findUniqueOrThrow({ where: { id: recoverable.id } }),
+ db.agentRun.findUniqueOrThrow({ where: { id: active.id } }),
+ ]);
+ expect(pending).toContain(recoverable.id);
+ expect(recovered).toMatchObject({ status: "QUEUED", startedAt: null });
+ expect(
+ await db.agentRunEvent.count({
+ where: { runId: recoverable.id, type: "run.delivery_recovered" },
+ }),
+ ).toBe(1);
+ expect(untouched.status).toBe("RUNNING");
+ });
+
+ it("claims one live run delivery and persists its Eve session", async () => {
+ const run = await createRun("QUEUED", null);
+ let deliveries = 0;
+ const sessionId = `durable-session-${suffix}-agent-dispatch`;
+ const send = (async () => {
+ deliveries += 1;
+ return { id: sessionId };
+ }) as unknown as SendFn;
+
+ const attempts = await Promise.allSettled([
+ dispatchAgentRun(run.id, send),
+ dispatchAgentRun(run.id, send),
+ ]);
+ const persisted = await db.agentRun.findUniqueOrThrow({
+ where: { id: run.id },
+ });
+ expect(
+ attempts.filter((attempt) => attempt.status === "fulfilled"),
+ ).toHaveLength(1);
+ expect(deliveries).toBe(1);
+ expect(persisted).toMatchObject({
+ status: "RUNNING",
+ sessionId,
+ modelId: "test/model",
+ });
+ });
+
+ it("restores a builder continuation when a delivery lease expires", async () => {
+ const conversation = await db.agentConversation.create({
+ data: {
+ kind: "BUILDER",
+ userId,
+ sessionId: `durable-session-${suffix}-builder`,
+ continuationToken: null,
+ submissions: {
+ create: {
+ submittedById: userId,
+ clientRequestId: crypto.randomUUID(),
+ message: { text: "Continue building" },
+ status: "SENDING",
+ attemptCount: 1,
+ sentAt: new Date(Date.now() - 10 * 60_000),
+ },
+ },
+ },
+ select: { id: true, submissions: { select: { id: true } } },
+ });
+ builderConversationIds.push(conversation.id);
+
+ await pendingBuilderSubmissionIds();
+ const [submission, restored] = await Promise.all([
+ db.agentConversationSubmission.findUniqueOrThrow({
+ where: { id: conversation.submissions[0]?.id },
+ }),
+ db.agentConversation.findUniqueOrThrow({
+ where: { id: conversation.id },
+ }),
+ ]);
+ expect(submission.status).toBe("PENDING");
+ expect(restored.continuationToken).toBe(builderToken(conversation.id));
+ });
+
+ it("keeps concurrent builder dispatches in conversation order", async () => {
+ const conversation = await db.agentConversation.create({
+ data: { kind: "BUILDER", userId },
+ select: { id: true },
+ });
+ builderConversationIds.push(conversation.id);
+ const firstCreatedAt = new Date();
+ const [first, second] = await Promise.all([
+ db.agentConversationSubmission.create({
+ data: {
+ conversationId: conversation.id,
+ submittedById: userId,
+ clientRequestId: crypto.randomUUID(),
+ message: { text: "First" },
+ createdAt: firstCreatedAt,
+ },
+ select: { id: true },
+ }),
+ db.agentConversationSubmission.create({
+ data: {
+ conversationId: conversation.id,
+ submittedById: userId,
+ clientRequestId: crypto.randomUUID(),
+ message: { text: "Second" },
+ createdAt: new Date(firstCreatedAt.getTime() + 1),
+ },
+ select: { id: true },
+ }),
+ ]);
+ const started = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ let deliveries = 0;
+ const send = (async () => {
+ deliveries += 1;
+ started.resolve();
+ await release.promise;
+ return { id: `durable-session-${suffix}-builder-dispatch` };
+ }) as unknown as SendFn;
+
+ const firstDispatch = dispatchBuilderSubmission(first.id, send);
+ await started.promise;
+ let secondError: Error | null = null;
+ try {
+ await dispatchBuilderSubmission(second.id, send);
+ } catch (error) {
+ secondError = error as Error;
+ }
+ release.resolve();
+ await firstDispatch;
+
+ const submissions = await db.agentConversationSubmission.findMany({
+ where: { id: { in: [first.id, second.id] } },
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ select: { id: true, status: true },
+ });
+ expect(deliveries).toBe(1);
+ expect(secondError?.message).toContain(
+ "already claimed or is out of order",
+ );
+ expect(submissions).toEqual([
+ { id: first.id, status: "ACCEPTED" },
+ { id: second.id, status: "PENDING" },
+ ]);
+ });
+
+ it("loads persisted attachment bytes into the Eve builder turn", async () => {
+ const content = Buffer.from("durable attachment");
+ const conversation = await db.agentConversation.create({
+ data: {
+ kind: "BUILDER",
+ userId,
+ submissions: {
+ create: {
+ submittedById: userId,
+ clientRequestId: crypto.randomUUID(),
+ message: {
+ text: "Read the attachment",
+ resources: [],
+ attachments: [
+ {
+ name: "brief.txt",
+ type: "text/plain",
+ size: content.byteLength,
+ },
+ ],
+ },
+ attachments: {
+ create: {
+ position: 0,
+ name: "brief.txt",
+ mediaType: "text/plain",
+ size: content.byteLength,
+ content,
+ },
+ },
+ },
+ },
+ },
+ select: { id: true, submissions: { select: { id: true } } },
+ });
+ builderConversationIds.push(conversation.id);
+ let delivered: unknown;
+ const send = (async (input: unknown) => {
+ delivered = input;
+ return { id: `durable-session-${suffix}-attachment` };
+ }) as unknown as SendFn;
+
+ await dispatchBuilderSubmission(
+ conversation.submissions[0]?.id ?? "",
+ send,
+ );
+ const parts = Array.isArray(delivered) ? delivered : [];
+ expect(parts).toHaveLength(2);
+ expect(parts[1]).toMatchObject({
+ type: "file",
+ mediaType: "text/plain",
+ filename: "brief.txt",
+ });
+ expect(Buffer.from(recordOf(parts[1]).data as Uint8Array)).toEqual(content);
+ });
+
+ it("ingests a replayed Eve event and its usage exactly once", async () => {
+ const run = await createRun();
+ const eventId = `evt_${suffix}_usage`;
+ type AuditHandler = (
+ event: {
+ type: string;
+ data: object;
+ meta: { id: string; at: string };
+ },
+ ctx: {
+ session: {
+ id: string;
+ auth: {
+ current: { attributes: Record<string, unknown> };
+ initiator: null;
+ };
+ };
+ },
+ ) => Promise<void>;
+ const handler = audit.events["*"] as unknown as AuditHandler;
+ const event = {
+ type: "step.completed",
+ data: { usage: { inputTokens: 5, outputTokens: 3, costUsd: 0.01 } },
+ meta: { id: eventId, at: new Date().toISOString() },
+ };
+ const context = {
+ session: {
+ id: `durable-session-${suffix}-usage`,
+ auth: {
+ current: {
+ attributes: { purpose: "team-agent", runId: run.id },
+ },
+ initiator: null,
+ },
+ },
+ };
+
+ await handler(event, context);
+ await handler(event, context);
+
+ const persisted = await db.agentRun.findUniqueOrThrow({
+ where: { id: run.id },
+ });
+ expect(persisted).toMatchObject({
+ inputTokens: 5,
+ outputTokens: 3,
+ nextEventSequence: 1,
+ });
+ expect(Number(persisted.costUsd)).toBe(0.01);
+ expect(await db.agentRunEvent.count({ where: { id: eventId } })).toBe(1);
+ expect(await db.agentEvent.count({ where: { id: eventId } })).toBe(1);
+ });
+
+ it("keeps a nested subagent session from replacing the root run session", async () => {
+ const rootSessionId = `durable-session-${suffix}-root`;
+ const run = await createRun("RUNNING", new Date(), rootSessionId);
+ type AuditHandler = (
+ event: {
+ type: string;
+ data: object;
+ meta: { id: string; at: string };
+ },
+ ctx: {
+ session: {
+ id: string;
+ parent?: unknown;
+ auth: {
+ current: { attributes: Record<string, unknown> };
+ initiator: null;
+ };
+ };
+ },
+ ) => Promise<void>;
+ const handler = audit.events["*"] as unknown as AuditHandler;
+
+ await handler(
+ {
+ type: "session.started",
+ data: {},
+ meta: {
+ id: `evt_${suffix}_nested_started`,
+ at: new Date().toISOString(),
+ },
+ },
+ {
+ session: {
+ id: `durable-session-${suffix}-nested`,
+ parent: { id: rootSessionId },
+ auth: {
+ current: {
+ attributes: { purpose: "team-agent", runId: run.id },
+ },
+ initiator: null,
+ },
+ },
+ },
+ );
+
+ expect(
+ await db.agentRun.findUniqueOrThrow({ where: { id: run.id } }),
+ ).toMatchObject({ sessionId: rootSessionId });
+ });
+
+ it("lets the first terminal state win without duplicate terminal logs", async () => {
+ const [completed, failed] = await Promise.all([createRun(), createRun()]);
+ await finishRun(completed.id, { summary: "Completed safely" });
+ await failRun(completed.id, "LATE_FAILURE", "This arrived late");
+ await failRun(failed.id, "FIRST_FAILURE", "Failed safely");
+ let lateCompletionError: Error | null = null;
+ try {
+ await finishRun(failed.id, {
+ summary: "This must not overwrite failure",
+ });
+ } catch (error) {
+ lateCompletionError = error as Error;
+ }
+ await failRun(failed.id, "SECOND_FAILURE", "This arrived late");
+
+ const [completedRow, failedRow] = await Promise.all([
+ db.agentRun.findUniqueOrThrow({ where: { id: completed.id } }),
+ db.agentRun.findUniqueOrThrow({ where: { id: failed.id } }),
+ ]);
+ expect(completedRow).toMatchObject({
+ status: "SUCCEEDED",
+ summary: "Completed safely",
+ });
+ expect(failedRow).toMatchObject({
+ status: "FAILED",
+ errorCode: "FIRST_FAILURE",
+ errorMessage: "Failed safely",
+ });
+ expect(lateCompletionError?.message).toContain("already ended with FAILED");
+ expect(
+ await db.agentRunEvent.count({
+ where: {
+ runId: { in: [completed.id, failed.id] },
+ type: { in: ["run.completed", "run.failed"] },
+ },
+ }),
+ ).toBe(2);
+ });
+
+ it("stages tool output before the session owns terminal completion", async () => {
+ const run = await createRun();
+ await stageRunResult(run.id, {
+ summary: "Staged safely",
+ result: { noted: 2 },
+ });
+ const staged = await db.agentRun.findUniqueOrThrow({
+ where: { id: run.id },
+ });
+ expect(staged).toMatchObject({
+ status: "RUNNING",
+ summary: "Staged safely",
+ result: { noted: 2 },
+ });
+ expect(
+ await db.agentRunEvent.count({
+ where: { runId: run.id, type: "run.completed" },
+ }),
+ ).toBe(0);
+
+ await finishRun(run.id, {
+ summary: staged.summary ?? "Staged safely",
+ result: staged.result as Record<string, unknown>,
+ });
+ expect(
+ await db.agentRun.findUniqueOrThrow({ where: { id: run.id } }),
+ ).toMatchObject({ status: "SUCCEEDED", summary: "Staged safely" });
+ });
+
+ it("claims an approved CRM action once and rejects scope before target access", async () => {
+ const run = await createRun();
+ const input = {
+ type: "NOTE" as const,
+ targetKind: "company" as const,
+ targetId: companyId,
+ subject: "Durable note",
+ body: "Created exactly once.",
+ };
+ const attempts = await Promise.allSettled(
+ Array.from({ length: 4 }, () =>
+ createRunActivity(run.id, "shared-call", input),
+ ),
+ );
+ expect(
+ attempts.filter((attempt) => attempt.status === "fulfilled").length,
+ ).toBeGreaterThanOrEqual(1);
+ const replay = await createRunActivity(run.id, "shared-call", input);
+ expect(replay.replayed).toBe(true);
+ let reusedCallError: Error | null = null;
+ try {
+ await createRunActivity(run.id, "shared-call", {
+ ...input,
+ body: "Different input must not replay the earlier action.",
+ });
+ } catch (error) {
+ reusedCallError = error as Error;
+ }
+ expect(reusedCallError?.message).toContain("already used for other input");
+ expect(
+ await db.agentAction.count({
+ where: { runId: run.id, idempotencyKey: `${run.id}:shared-call` },
+ }),
+ ).toBe(1);
+ expect(
+ await db.activity.count({
+ where: { meta: { path: ["runId"], equals: run.id } },
+ }),
+ ).toBe(1);
+
+ let scopeError: Error | null = null;
+ try {
+ await createRunActivity(run.id, "out-of-scope", {
+ ...input,
+ targetId: otherCompanyId,
+ });
+ } catch (error) {
+ scopeError = error as Error;
+ }
+ expect(scopeError?.message).toContain("outside this agent version");
+ expect(
+ await db.agentAction.count({
+ where: { idempotencyKey: `${run.id}:out-of-scope` },
+ }),
+ ).toBe(0);
+
+ let activityTypeError: Error | null = null;
+ try {
+ await createRunActivity(run.id, "unapproved-task", {
+ ...input,
+ type: "TASK",
+ subject: "This type was not approved",
+ });
+ } catch (error) {
+ activityTypeError = error as Error;
+ }
+ expect(activityTypeError?.message).toContain(
+ "does not allow CRM task activities",
+ );
+ expect(
+ await db.agentAction.count({
+ where: { idempotencyKey: `${run.id}:unapproved-task` },
+ }),
+ ).toBe(0);
+ });
+});
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
diff --git a/apps/agent/test/lanes.integration.spec.ts b/apps/agent/test/lanes.integration.spec.ts
index 5bd365fe..a2cde1ce 100644
--- a/apps/agent/test/lanes.integration.spec.ts
+++ b/apps/agent/test/lanes.integration.spec.ts
@@ -4,6 +4,7 @@ import { DIRECT_KINDS, isDirectKind, PRIORITY } from "@crm/db/agent-tasks";
import { claimDue } from "../agent/lib/tasks";
const REASON = "lane-test";
+const TEST_PRIORITY_OFFSET = 1_000_000;
const VISIBLE = { only: DIRECT_KINDS } as const;
const RESEARCH = { except: DIRECT_KINDS } as const;
@@ -21,7 +22,7 @@ async function queue(kind: string, priority: number) {
kind,
reason: REASON,
dueAt: new Date(Date.now() - 1000),
- priority,
+ priority: TEST_PRIORITY_OFFSET + priority,
budget: 2,
},
select: { id: true },
diff --git a/apps/agent/test/lookup.integration.spec.ts b/apps/agent/test/lookup.integration.spec.ts
index 6e441056..c903c565 100644
--- a/apps/agent/test/lookup.integration.spec.ts
+++ b/apps/agent/test/lookup.integration.spec.ts
@@ -1,6 +1,6 @@
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
import { DealStage, db } from "@crm/db";
-import { searchCrm } from "../agent/lib/lookup";
+import { listDeals, searchCrm } from "../agent/lib/lookup";
const suffix = process.env.TEST_RUN_ID ?? "lookup-spec";
const domain = `northwind-${suffix}.test`;
@@ -11,6 +11,8 @@ let brightwaterId: string;
let paulaId: string;
let peterId: string;
let dealId: string;
+let freshDealId: string;
+let closedDealId: string;
beforeAll(async () => {
await cleanup();
@@ -21,12 +23,20 @@ beforeAll(async () => {
name: "Rep One",
email: `rep.${suffix}@example.test`,
emailVerified: true,
+ image: "https://cdn.example.test/rep-one.png",
},
select: { id: true },
});
const northwind = await db.company.create({
- data: { name: `Northwind ${suffix}`, domain },
+ data: {
+ name: `Northwind ${suffix}`,
+ domain,
+ iconUrl: "https://cdn.example.test/northwind-icon.png",
+ iconDarkUrl: "https://cdn.example.test/northwind-icon-dark.png",
+ iconTone: "opaque",
+ logoUrl: "https://cdn.example.test/northwind-logo.svg",
+ },
select: { id: true },
});
northwindId = northwind.id;
@@ -69,10 +79,35 @@ beforeAll(async () => {
ownerId: user.id,
stage: DealStage.QUALIFIED_TO_BUY,
amount: 12_000,
+ lastActivityAt: new Date("2026-06-01T12:00:00.000Z"),
},
select: { id: true },
});
dealId = deal.id;
+
+ const freshDeal = await db.deal.create({
+ data: {
+ name: `Fresh expansion ${suffix}`,
+ companyId: northwindId,
+ ownerId: user.id,
+ stage: DealStage.CONTRACT_SENT,
+ lastActivityAt: new Date("2026-08-04T12:00:00.000Z"),
+ },
+ select: { id: true },
+ });
+ freshDealId = freshDeal.id;
+
+ const closedDeal = await db.deal.create({
+ data: {
+ name: `Closed renewal ${suffix}`,
+ companyId: brightwaterId,
+ ownerId: user.id,
+ stage: DealStage.CLOSED_LOST,
+ lastActivityAt: new Date("2026-05-01T12:00:00.000Z"),
+ },
+ select: { id: true },
+ });
+ closedDealId = closedDeal.id;
});
afterAll(cleanup);
@@ -164,3 +199,43 @@ describe("searchCrm", () => {
expect((await searchCrm("a")).total).toBe(0);
});
});
+
+describe("listDeals", () => {
+ it("lists stale open deals across the pipeline", async () => {
+ const result = await listDeals({
+ status: "open",
+ inactiveForDays: 14,
+ now: new Date("2026-08-05T12:00:00.000Z"),
+ });
+ const ids = result.deals.map((deal) => deal.id);
+
+ expect(ids).toContain(dealId);
+ expect(ids).not.toContain(freshDealId);
+ expect(ids).not.toContain(closedDealId);
+ expect(result.deals.find((deal) => deal.id === dealId)).toMatchObject({
+ daysSinceLastActivity: 65,
+ neverActive: false,
+ company: {
+ domain,
+ iconUrl: "https://cdn.example.test/northwind-icon.png",
+ iconDarkUrl: "https://cdn.example.test/northwind-icon-dark.png",
+ iconTone: "opaque",
+ logoUrl: "https://cdn.example.test/northwind-logo.svg",
+ },
+ owner: { image: "https://cdn.example.test/rep-one.png" },
+ });
+ });
+
+ it("paginates a broad deal sweep without repeating a row", async () => {
+ const first = await listDeals({ status: "all", limit: 1 });
+ expect(first.hasMore).toBe(true);
+ expect(first.nextCursor).toBeTruthy();
+
+ const second = await listDeals({
+ status: "all",
+ limit: 1,
+ cursor: first.nextCursor ?? undefined,
+ });
+ expect(second.deals[0]?.id).not.toBe(first.deals[0]?.id);
+ });
+});
diff --git a/apps/agent/test/verify-key.spec.ts b/apps/agent/test/verify-key.spec.ts
index d942622f..ab01df88 100644
--- a/apps/agent/test/verify-key.spec.ts
+++ b/apps/agent/test/verify-key.spec.ts
@@ -31,6 +31,20 @@ describe("checking a Context key", () => {
expect(classifyKey(answered(403, "FORBIDDEN")).outcome).toBe("valid");
});
+ it("accepts an exhausted free-tier key when Context answers with 401", () => {
+ expect(classifyKey(answered(401, "USAGE_EXCEEDED")).outcome).toBe("valid");
+ expect(
+ classifyKey(
+ new APIError(
+ 401,
+ { message: "This account has no API credits remaining." },
+ undefined,
+ new Headers(),
+ ),
+ ).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");
diff --git a/apps/agent/turbo.json b/apps/agent/turbo.json
index 0f8bc0bd..534a71b7 100644
--- a/apps/agent/turbo.json
+++ b/apps/agent/turbo.json
@@ -10,6 +10,22 @@
"dependsOn": ["topo", "^build"]
},
"dev": {
+ "dependsOn": ["$TURBO_EXTENDS$"],
+ "cache": false,
+ "interactive": true,
+ "persistent": true,
+ "passThroughEnv": [
+ "AGENT_BRIDGE_SECRET",
+ "AI_GATEWAY_API_KEY",
+ "BLOB_READ_WRITE_TOKEN",
+ "DATABASE_URL",
+ "GITHUB_TOKEN",
+ "PERPLEXITY_API_KEY",
+ "RAPIDAPI_KEY"
+ ]
+ },
+ "dev:headless": {
+ "dependsOn": ["$TURBO_EXTENDS$"],
"cache": false,
"persistent": true,
"passThroughEnv": [
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.ts
index 108718bb..3f808b0a 100644
--- a/apps/api/src/companies/companies.service.ts
+++ b/apps/api/src/companies/companies.service.ts
@@ -5,6 +5,7 @@ import {
Prisma as PrismaNamespace,
type RecordSource,
} from "@crm/db";
+import { OPEN_DEAL_STAGES } from "@crm/db/deal-stage";
import {
BadRequestException,
ConflictException,
@@ -22,7 +23,6 @@ import { type BulkResult, requireOwner, runBulk } from "../crm/bulk";
import { blankToNull, toCents } from "../crm/values";
import { ConversionService } from "../currency/conversion.service";
import { InjectDatabase } from "../database/database.constants";
-import { OPEN_DEAL_STAGES } from "../deals/deal-stage";
import { FieldsService } from "../fields/fields.service";
import {
countsByKey,
diff --git a/apps/api/src/dashboard/dashboard.service.ts b/apps/api/src/dashboard/dashboard.service.ts
index c47f123e..f338fd46 100644
--- a/apps/api/src/dashboard/dashboard.service.ts
+++ b/apps/api/src/dashboard/dashboard.service.ts
@@ -1,9 +1,9 @@
import { ActivityType, type Db, DealStage } from "@crm/db";
+import { OPEN_DEAL_STAGES } from "@crm/db/deal-stage";
import { Injectable } from "@nestjs/common";
import { toCents } from "../crm/values";
import { ConversionService } from "../currency/conversion.service";
import { InjectDatabase } from "../database/database.constants";
-import { OPEN_DEAL_STAGES } from "../deals/deal-stage";
import type { DashboardSummaryInput } from "./dashboard.contracts";
const OWNER_SELECT = {
diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.ts
index 83480594..2dbcc5a3 100644
--- a/apps/api/src/deals/deals.service.ts
+++ b/apps/api/src/deals/deals.service.ts
@@ -6,6 +6,12 @@ import {
Prisma as PrismaNamespace,
} from "@crm/db";
import { normalizeCurrency } from "@crm/db/currency";
+import {
+ CLOSED_DEAL_STAGES,
+ isClosedStage,
+ LOSING_DEAL_STAGES,
+ OPEN_DEAL_STAGES,
+} from "@crm/db/deal-stage";
import {
BadRequestException,
Injectable,
@@ -34,12 +40,6 @@ import {
paginate,
resolveOrderBy,
} from "../trpc/list-input";
-import {
- CLOSED_DEAL_STAGES,
- isClosedStage,
- LOSING_DEAL_STAGES,
- OPEN_DEAL_STAGES,
-} from "./deal-stage";
import type {
ClosingWindow,
DealAttachContactInput,
diff --git a/apps/app/lib/agent-transcript.ts b/apps/app/lib/agent-transcript.ts
index 360bacff..a315c9a5 100644
--- a/apps/app/lib/agent-transcript.ts
+++ b/apps/app/lib/agent-transcript.ts
@@ -39,7 +39,9 @@ const VERBS: Record<string, string> = {
enrich_company: "Looked up the company",
schedule_recheck: "Decided when to look again",
record_job_change: "Raised a job change",
+ list_deals: "Reviewed the deal pipeline",
list_outstanding_work: "Looked for outstanding work",
+ set_chat_title: "Named this chat",
list_fields: "Read what this workspace tracks",
set_field_value: "Filled in a custom field",
manage_fields: "Changed what the CRM tracks",
diff --git a/bun.lock b/bun.lock
index 0ef96d7d..432ca0d2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -24,6 +24,7 @@
"devDependencies": {
"@crm/typescript-config": "workspace:*",
"@types/node": "^24.0.0",
+ "just-bash": "^3.2.0",
"microsandbox": "^0.6.8",
"typescript": "^5.9.2",
},
@@ -473,6 +474,16 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
+ "@jitl/quickjs-ffi-types": ["@jitl/[email protected]", "", {}, "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg=="],
+
+ "@jitl/quickjs-wasmfile-debug-asyncify": ["@jitl/[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-EX8zbXwGqCgAE764M+qvkHtyXDi/FUoMBea0JnES7vCM3P7a2+EOZOjGv85wtZ2sJhI1oJ+nekmqpOODFDY+hw=="],
+
+ "@jitl/quickjs-wasmfile-debug-sync": ["@jitl/[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-LeYWrPGC1uNCTBWvibo3ZLJj0CSVNYUXvJpXMCmuQ5Sap2cCACc3uvGvYV4homHHBAzfw5akoTqMMS4YFRtw+Q=="],
+
+ "@jitl/quickjs-wasmfile-release-asyncify": ["@jitl/[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-3oSwPfja12ICz4aIblB58cuY8JlEq5Txt8Cut4VLo+LH47QN+mzCnSgnbB03hWzg1LBcc+VyyI9UOag7a1NF+Q=="],
+
+ "@jitl/quickjs-wasmfile-release-sync": ["@jitl/[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-BKNDI/TPBfGlLNGYpLrhcDGXmIk4xHm4MRAisOBnOzpXVn9HZWsfmMAc9WMBrAHjvvds6HOikKeaOBKdPdpVrg=="],
+
"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -491,8 +502,12 @@
"@mermaid-js/parser": ["@mermaid-js/[email protected]", "", { "dependencies": { "@chevrotain/types": "~11.1.2" } }, "sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA=="],
+ "@mixmark-io/domino": ["@mixmark-io/[email protected]", "", {}, "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw=="],
+
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="],
+ "@mongodb-js/zstd": ["@mongodb-js/[email protected]", "", { "dependencies": { "node-addon-api": "^8.5.0", "prebuild-install": "^7.1.3" } }, "sha512-mQ2s0pYYiav+tzCDR05Zptem8Ey2v8s11lri5RKGhTtL4COVCvVCk5vtyRYNT+9L8qSfyOqqefF9UtnW8mC5jA=="],
+
"@mrleebo/prisma-ast": ["@mrleebo/[email protected]", "", { "dependencies": { "chevrotain": "^10.5.0", "lilconfig": "^2.1.0" } }, "sha512-XyroGQXcHrZdvmrGJvsA9KNeOOgGMg1Vg9OlheUsBOSKznLMDl+YChxbkboRHvtFYJEMRYmlV3uoo/njCw05iw=="],
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" } }, "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw=="],
@@ -1531,7 +1546,7 @@
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
- "ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
+ "ini": ["[email protected]", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
@@ -1615,6 +1630,8 @@
"jsonfile": ["[email protected]", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="],
+ "just-bash": ["[email protected]", "", { "dependencies": { "diff": "^8.0.2", "fast-xml-parser": "^5.7.3", "file-type": "^21.2.0", "ini": "^6.0.0", "minimatch": "^10.1.1", "modern-tar": "^0.7.3", "papaparse": "^5.5.3", "quickjs-emscripten": "^0.32.0", "re2js": "^1.2.1", "seek-bzip": "^2.0.0", "smol-toml": "^1.6.0", "sprintf-js": "^1.1.3", "sql.js": "^1.13.0", "turndown": "^7.2.2", "undici": "^7.25.0", "yaml": "^2.8.2" }, "optionalDependencies": { "@mongodb-js/zstd": "^7.0.0", "node-liblzma": "^2.0.3" }, "bin": { "just-bash": "dist/bin/just-bash.js", "just-bash-shell": "dist/bin/shell/shell.js" } }, "sha512-hRTLLWBXCKuosjaNFJR7uPYBza+T2vjG3NdPBz4wxlctlnxwrbLjtLQf6RtSKmy/jzNJ6/URCtvxrXjy6yFGeQ=="],
+
"katex": ["[email protected]", "", { "dependencies": { "commander": "^8.3.0" }, "bin": { "katex": "cli.js" } }, "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg=="],
"keyv": ["[email protected]", "", { "dependencies": { "@keyv/serialize": "^1.1.1" } }, "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw=="],
@@ -1807,6 +1824,8 @@
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
+ "modern-tar": ["[email protected]", "", {}, "sha512-t9VmxaqrmANnEOBhpSDI6HD192Ge48k8vmWqQQL7hSFEqHEYwZbbsu49+aKLWZeRvFs3j1pMhXOqqF4kPlvjkQ=="],
+
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"multer": ["[email protected]", "", { "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", "concat-stream": "^2.0.0", "type-is": "^1.6.18" } }, "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ=="],
@@ -1835,6 +1854,12 @@
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g=="],
+ "node-addon-api": ["[email protected]", "", {}, "sha512-4eUQWVPCUUUiBjLnHS3cXWeC6ryoPUc0U3rP7IuzapoGbzMqd/r6KKO0clr0b+snQhsrueFEhCZDdK+LK7hxKg=="],
+
+ "node-gyp-build": ["[email protected]", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="],
+
+ "node-liblzma": ["[email protected]", "", { "dependencies": { "node-addon-api": "^8.5.0", "node-gyp-build": "^4.8.4" }, "bin": { "nxz": "lib/cli/nxz.js" } }, "sha512-s0KzNOWwOJJgPG6wxg6cKohnAl9Wk/oW1KrQaVzJBjQwVcUGPQCzpR46Ximygjqj/3KhOrtJXnYMp/xYAXp75g=="],
+
"node-releases": ["[email protected]", "", {}, "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ=="],
"node-rsa": ["[email protected]", "", { "dependencies": { "asn1": "^0.2.4" } }, "sha512-Jd4cvbJMryN21r5HgxQOpMEqv+ooke/korixNNK3mGqfGJmy0M77WDDzo/05969+OkMy3XW1UuZsSmW9KQm7Fw=="],
@@ -1875,6 +1900,8 @@
"package-manager-detector": ["[email protected]", "", {}, "sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A=="],
+ "papaparse": ["[email protected]", "", {}, "sha512-SwzWD9gl/ElwYLCI0nUja1mFJzjq2D8ziShfNBa7zCHzkOozeOGDwHWQ+tvCzEZcewecWZ5U7kUopDnG+DFYEQ=="],
+
"parent-module": ["[email protected]", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
"parse-entities": ["[email protected]", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
@@ -1983,6 +2010,10 @@
"queue-microtask": ["[email protected]", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
+ "quickjs-emscripten": ["[email protected]", "", { "dependencies": { "@jitl/quickjs-wasmfile-debug-asyncify": "0.32.0", "@jitl/quickjs-wasmfile-debug-sync": "0.32.0", "@jitl/quickjs-wasmfile-release-asyncify": "0.32.0", "@jitl/quickjs-wasmfile-release-sync": "0.32.0", "quickjs-emscripten-core": "0.32.0" } }, "sha512-So0Sqw869y/S2oE3Nuc0uT3Dhqgvsj8FSrwBdsuTosVsG8ME5/OcudU1GxsrIFdFABgy17GHnTVO9TYV/bLQcA=="],
+
+ "quickjs-emscripten-core": ["[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
+
"radix-ui": ["[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-accessible-icon": "1.1.15", "@radix-ui/react-accordion": "1.2.20", "@radix-ui/react-alert-dialog": "1.1.23", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-aspect-ratio": "1.1.15", "@radix-ui/react-avatar": "1.2.6", "@radix-ui/react-checkbox": "1.3.11", "@radix-ui/react-collapsible": "1.1.20", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-context-menu": "2.3.7", "@radix-ui/react-dialog": "1.1.23", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-dropdown-menu": "2.1.24", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-form": "0.1.16", "@radix-ui/react-hover-card": "1.1.23", "@radix-ui/react-label": "2.1.15", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-menubar": "1.1.24", "@radix-ui/react-navigation-menu": "1.2.22", "@radix-ui/react-one-time-password-field": "0.1.16", "@radix-ui/react-password-toggle-field": "0.1.11", "@radix-ui/react-popover": "1.1.23", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-progress": "1.1.16", "@radix-ui/react-radio-group": "1.4.7", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-scroll-area": "1.2.18", "@radix-ui/react-select": "2.3.7", "@radix-ui/react-separator": "1.1.15", "@radix-ui/react-slider": "1.4.7", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-switch": "1.3.7", "@radix-ui/react-tabs": "1.1.21", "@radix-ui/react-toast": "1.2.23", "@radix-ui/react-toggle": "1.1.18", "@radix-ui/react-toggle-group": "1.1.19", "@radix-ui/react-toolbar": "1.1.19", "@radix-ui/react-tooltip": "1.2.16", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-escape-keydown": "1.1.5", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-QBdhh1arIEUvPC0dQ5+nwWAxt7+N+oP/9jPwjJkGFoSk/sqxg32gJtSXGtFh8frAIcS6oC9cx2Q+7KYCQLOAeA=="],
"range-parser": ["[email protected]", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="],
@@ -1993,6 +2024,8 @@
"rc9": ["[email protected]", "", { "dependencies": { "defu": "^6.1.6", "destr": "^2.0.5" } }, "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ=="],
+ "re2js": ["[email protected]", "", {}, "sha512-KTOIcZTSOpOxbu3i0+T6mFQ6tkxXKlTxfcMFs1trQbsMnG84qNq+DjXr8Afu+FEFjvF1NNlldpC7roPyazFI8g=="],
+
"react": ["[email protected]", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="],
"react-day-picker": ["[email protected]", "", { "dependencies": { "@date-fns/tz": "^1.4.1", "date-fns": "^4.1.0" }, "peerDependencies": { "@types/react": ">=16.8.0", "react": ">=16.8.0" }, "optionalPeers": ["@types/react"] }, "sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w=="],
@@ -2087,6 +2120,8 @@
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
+ "seek-bzip": ["[email protected]", "", { "dependencies": { "commander": "^6.0.0" }, "bin": { "seek-bunzip": "bin/seek-bunzip", "seek-table": "bin/seek-bzip-table" } }, "sha512-SMguiTnYrhpLdk3PwfzHeotrcwi8bNV4iemL9tx9poR/yeaMYwB9VzR1w7b57DuWpuqR8n6oZboi0hj3AxZxQg=="],
+
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"send": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
@@ -2125,6 +2160,8 @@
"sisteransi": ["[email protected]", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="],
+ "smol-toml": ["[email protected]", "", {}, "sha512-PPlsspAZ4jbMBu5DMFhfUGDQLu/vrL4SyBROVS37x8ynnVmFIs1VPBz1Co8Xks3TvpIaZXmU85y4DrQ+UyVFoQ=="],
+
"sonner": ["[email protected]", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w=="],
"source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
@@ -2135,6 +2172,10 @@
"split2": ["[email protected]", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],
+ "sprintf-js": ["[email protected]", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
+
+ "sql.js": ["[email protected]", "", {}, "sha512-gcj8zBWU5cFsi9WUP+4bFNXAyF1iRpA3LLyS/DP5xlrNzGmPIizUeBggKa8DbDwdqaKwUcTEnChtd2grWo/x/A=="],
+
"sqlstring": ["[email protected]", "", {}, "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="],
"srvx": ["[email protected]", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-LqZxxBDMKuMAZzFzJnDCkFOrs9MZQZr0LvHiO/SuSZVdQaXD7xQ5UWTUxheJrQPve1qk9MG2B/yttUvJxw8egQ=="],
@@ -2229,6 +2270,8 @@
"turbo": ["[email protected]", "", { "optionalDependencies": { "@turbo/darwin-64": "2.10.8", "@turbo/darwin-arm64": "2.10.8", "@turbo/linux-64": "2.10.8", "@turbo/linux-arm64": "2.10.8", "@turbo/windows-64": "2.10.8", "@turbo/windows-arm64": "2.10.8" }, "bin": { "turbo": "bin/turbo" } }, "sha512-9+8YX5QOkGXzZxcIykTHgaooRHGMWO+jfdyRK0o+rN0U7hBIig2MrJ8r/aNzIPDPhdA73SGb0O+tIztaModTMg=="],
+ "turndown": ["[email protected]", "", { "dependencies": { "@mixmark-io/domino": "^2.2.0" } }, "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ=="],
+
"tw-animate-css": ["[email protected]", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
"type-is": ["[email protected]", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
@@ -2331,6 +2374,8 @@
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
+ "yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
+
"yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
"yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
@@ -2649,6 +2694,8 @@
"h3/rou3": ["[email protected]", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="],
+ "just-bash/undici": ["[email protected]", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
+
"katex/commander": ["[email protected]", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],
"log-symbols/is-unicode-supported": ["[email protected]", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="],
@@ -2683,8 +2730,12 @@
"radix-ui/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="],
+ "rc/ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
+
"restore-cursor/onetime": ["[email protected]", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],
+ "seek-bzip/commander": ["[email protected]", "", {}, "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA=="],
+
"shadcn/commander": ["[email protected]", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="],
"shadcn/open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.4.0", "define-lazy-prop": "^3.0.0", "is-in-ssh": "^1.0.0", "is-inside-container": "^1.0.0", "powershell-utils": "^0.1.0", "wsl-utils": "^0.3.0" } }, "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw=="],
diff --git a/docs/agent.md b/docs/agent.md
index 8a86ea8d..358faacb 100644
--- a/docs/agent.md
+++ b/docs/agent.md
@@ -210,6 +210,54 @@ the backend factory** so it cannot be forgotten per session. Costs nothing —
**Never give the sandbox `DATABASE_URL`.** CRM access is authored tools. A shell with
credentials and network is exfiltration-shaped; with neither it is a text processor.
+## Team-agent builder and runner
+
+`agent_builder` and `agent_runner` are declared subagents with independent
+instructions, tools and deny-all sandboxes. They inherit nothing from the root. The
+root built-in `agent` copy tool is disabled; these two named specialists are the only
+delegation paths for custom agents.
+
+- **Creation requires the current `CREATE_AGENT` turn.** Every builder tool checks the
+ purpose and command type in session auth. A normal builder chat cannot create a
+ draft by prompt alone.
+- **Builder output is typed.** `needs_input` carries one question and its choices for
+ the parent to surface through eve HITL. `draft_ready` carries the immutable version
+ ids. The specialist cannot ask directly because its `ask_question` is disabled.
+- **Empty never means all.** A version chooses `SELECTED` or `WORKSPACE` record scope.
+ Selected scope requires at least one record tagged in that private conversation;
+ workspace scope is an explicit grant and cannot also list selected records.
+- **Connections are executable permissions.** Only `google:gmail` and
+ `google:calendar` are accepted, only when connected, and the runner does not query
+ their synced tables unless the deployed manifest includes that source.
+- **Actions are structured permissions.** `crm.activity.create` separately names
+ `NOTE`, `TASK`, or both. Runtime enforcement never infers a grant from the action's
+ prose summary. Every action is ledgered before execution and keyed by eve's call id
+ for replay safety.
+- **Deployment is the human approval boundary.** Saving produces a private READY
+ version and never deploys it. The review screen shows its trigger, scope, actions,
+ access and exact files. A user's Deploy action pins that immutable version for the
+ team. Scheduled runner sessions use task mode and therefore cannot pause for a
+ per-action approval; the deployed permission and idempotent runtime checks are the
+ boundary.
+- **Approved instructions are system context.** The runner resolves the pinned
+ version instructions at `session.started`, then calls `inspect_run` for the manifest
+ and current run state. Every runner tool also checks the `team-agent` purpose and
+ revalidates scope and action permission.
+- **No generic execution surface.** Both specialists disable shell, file, arbitrary
+ web, todo and direct-question built-ins. CRM access exists only through their small
+ authored tool sets. Tool code runs in the trusted app runtime; the sandbox remains
+ isolated and deny-all.
+
+Runner manifests fail closed when either the explicit record-scope mode or an
+activity type grant is missing. Versions created before these typed permissions were
+introduced must be revised and deployed again before they can run.
+
+`bun run --filter=agent eval` runs the eve end-to-end builder eval against the real
+HTTP channel. It creates an isolated private conversation, dispatches the builder,
+asserts the declared subagent path, verifies a READY side-effect-free manifest, and
+cleans up its rows. It skips visibly when the database, bridge secret or model
+credential is unavailable.
+
## The bridge
```
@@ -248,6 +296,284 @@ were written, sessions looked clean, but **no task reached `finishedAt`**, so co
sat on "Researching" forever. Hidden because the archived event's
`data.continuationToken` is *un-namespaced* while `channel.continuationToken` is not.
+### Conversations are kept
+
+A record accumulates conversations, and they survive a reload. `AgentConversation`
+holds the *handle* — the durable eve session id plus its cursor — while the
+transcript itself is already in `AgentEvent`, written by the audit hook. Nothing
+is stored twice.
+
+- **Resuming.** The panel passes the saved cursor as `initialSession`, so
+ reopening a contact continues last week's thread rather than starting another.
+ eve keeps sessions for 30 days.
+- **Replay from the start.** `streamIndex: 0` on resume, deliberately — the
+ saved index is where the *last reader* stopped, and a reopened thread should
+ show what was said in it, not only what has happened since.
+- **Which thread is open lives in the URL** (`?thread=`), like every other view
+ state in the sheet, so a refresh keeps your place and a conversation is a link.
+ It is cleared when the record or the tab changes, by the same rule that drops
+ a half-typed quick-add form.
+- **Nothing mounts until the list has loaded.** Rendering a thread while the
+ history is still in flight starts a *new* eve session and then remounts onto
+ the real one — which presents as "the history only appears if I refresh".
+- **The thread the panel landed on is captured once.** Re-deriving "the latest"
+ as the list changes would swap the open conversation out from under a live
+ answer the moment the first save adds a row. `resolveThread` in
+ `lib/agent-transcript.ts` holds the rule, and it is tested.
+- **The panel is not unmounted when you switch tabs.** It holds a live stream,
+ and Radix drops an inactive tab by default — which aborts the stream
+ mid-answer, so the reply landed in the durable session with nothing attached
+ to receive it. That is the "I went to another tab and the answer never came
+ back" bug, and no amount of re-reading state on the way in could fix it,
+ because the events had been dropped. `keepMounted` on the tab descriptor
+ (`detail-sheet.tsx`) keeps it alive; it renders nothing until the tab is
+ opened once, so flicking through records costs nothing.
+- **A thread is loaded with `session.snapshot()`, not by hand.** One call
+ returns the complete event prefix, the cursor that continues from it, and a
+ continuation token *if and only if* eve will accept another turn — about 30ms
+ against a hundred-event thread. `lib/agent-session.ts` is the whole of it.
+
+ What it replaced is worth remembering, because every panel bug of the last
+ day came out of it: a raw `fetch` of `…/stream?startIndex=-1`, parsing the
+ last line into a state machine. The endpoint *follows*, so awaiting the body
+ never returned. The stream opens with a bare newline, so "the first line" was
+ empty — which failed closed to "busy" and locked **every** reopened
+ conversation with "still working on the last question", including ones parked
+ with a perfectly good token. And a read that failed reported the *session* as
+ working rather than reporting itself as broken, so it could never recover.
+ The framework had a documented answer to the exact question that code was
+ asking. Read the guide before hand-rolling the protocol.
+- **The token is the authority on whether a message can be sent**, not our
+ reading of the events. eve returns one only when the captured prefix ends
+ parked, which is precisely the condition under which the next send lands.
+- **A turn that has gone quiet for 90 seconds is over, not working.** A
+ restarted agent leaves sessions with no closing boundary; they never park, and
+ treating them as in-flight locks that thread forever.
+- **An unreachable agent is `offline`, not `working`.** One is a fact about us
+ and the other a claim about the session; stated as the latter it is both
+ untrue and unrecoverable, since the read fails identically next time. The
+ transcript then comes from our own `AgentEvent` archive — which is also what
+ makes a thread older than eve's 30-day retention still readable — and the
+ composer stays usable.
+- **An ended thread gets a button, not a locked box.** Ended and working both
+ disable the composer and mean completely different things: one is a wait of
+ seconds, the other is permanent. `composerState()` keeps them apart, and an
+ ended thread offers **Start a new conversation**, which moves the picker to a
+ new thread. The transcript stays on screen throughout, and the save hook
+ treats the fresh session as a new conversation by comparing session ids
+ rather than by whether the panel started empty.
+- **`autoScroll` and nothing else.** The scroller is a state machine
+ (`following-bottom`, `free-scrolling`, `anchored-to-message`) and
+ `scrollAnchor` selects the third, which *stops it following the bottom* — the
+ answer then streams below the fold while the modes fight over each new row.
+ Left alone, `autoScroll` follows the tail while the reader is at the bottom
+ and releases the moment they scroll away, which lights the jump-to-end button.
+- **One `MessageScrollerItem` per message, not per part.** The row is what the
+ scroller measures; a row per tool call adds a boundary every few hundred
+ milliseconds during an answer. Part ids prefer `toolCallId`, which is stable
+ across a call's streaming states.
+- **A thread nobody has spoken in is loaded from nothing.** The snapshot query
+ is disabled without a conversation; a brand-new thread mounts with no session
+ and no events, and its first message creates both.
+- **Scoped to the rep.** Two people asking about the same contact are having two
+ conversations. `ConversationsService` filters on the caller, and a session id
+ in a request body decides which row, never whose.
+- **Cached the way `api.md` prescribes**: read through
+ `cache-manager` (Redis when `REDIS_URL` is set), write on miss, explicit
+ invalidation on every save. The list is read on every sheet open and changes
+ only when somebody sends a message, which is the shape a cache is for.
+
+This lives in the API rather than the agent, and that is not a breach of rule
+one: listing a record's history researches nothing, scores nothing and decides
+nothing. The agent owns judgement; the data surface owns filing.
+
+### Turning it on
+
+Same value in both processes, from the one root `.env`:
+
+```sh
+AGENT_URL="http://127.0.0.1:2000" # the default
+AGENT_BRIDGE_SECRET="$(openssl rand -base64 32)"
+```
+
+Then `bun run dev` (the agent serves on `:2000`) and open any contact.
+
+**If the Agent tab errors:**
+
+| Symptom | Cause |
+| --- | --- |
+| `503`, "not configured for this install" | `AGENT_BRIDGE_SECRET` is unset in the app's process |
+| `401` | The two processes hold *different* secrets |
+| `502`, "not reachable" | The agent is not running, or `AGENT_URL` is wrong |
+
+`eve dev` takes about five seconds to bind, and it listens on **IPv4 only**.
+That is why `AGENT_URL` defaults to `http://127.0.0.1:2000` rather than
+`http://localhost:2000`: Node resolves `localhost` to `::1` first, so the
+`localhost` form fails to connect on a machine where the agent is plainly
+running — and reports itself as "not reachable", which sends you looking in the
+wrong place.
+
+A variable in `.env` is not enough on its own: Turbo runs in strict env mode, so
+`apps/app/turbo.json` and `apps/agent/turbo.json` both declare the pair in
+`passThroughEnv`. Adding a variable and not declaring it produces exactly the
+`401` above.
+
+### Checking it without a browser
+
+`localDev()` accepts anything on loopback, so a bare `curl` to `127.0.0.1`
+proves nothing about the bridge. Send a non-loopback `Host` to make that entry
+skip:
+
+```sh
+curl -s -o /dev/null -w '%{http_code}\n' \
+ -H 'Host: agent.example.com' \
+ http://127.0.0.1:2000/eve/v1/info # 401
+
+curl -s -H 'Host: agent.example.com' \
+ -H "authorization: Bearer $TOKEN" \
+ http://127.0.0.1:2000/eve/v1/info | jq '.tools.available | length'
+```
+
+`GET /eve/v1/info` is the whole inventory — tools, skills, schedules, channels,
+sandbox, and a `diagnostics` count that is the fastest way to find a file eve
+silently ignored.
+
+## Watching it work
+
+`eve dev` shows every tool call, every result and every token in its interactive
+TUI, and it is the agent package's default `dev` command. The package's Turbo
+task is explicitly interactive, so select the agent pane and press Enter to hand
+stdin to eve. Type `/traces` to open the live trace viewer; Ctrl+Z returns input
+to Turbo.
+
+`dev:headless` keeps `eve dev --no-ui` available when a terminal cannot render
+the nested TUI. It starts the same server on the same port with the same routes
+and watcher. In that mode `hooks/activity.ts` narrates the session instead: a
+line per tool call with its arguments, a line per result with how long it took,
+the finish reason and token spend of each step, and any failure with its code.
+
+- **The lines go to stderr, not stdout.** The TUI's default log mode is `stderr`
+ and it keeps stdout buffered and hidden, so a `console.log` here would be
+ invisible in the mode it exists to serve. Written to stderr the same lines show
+ under `--no-ui`, under the TUI, and in `eve logs`.
+- **Contents print outside production; the shape prints everywhere.** Which tool
+ ran, whether it worked, what it cost — none of that is anybody's data, so it
+ logs wherever the agent runs. Arguments and replies carry names, addresses and
+ whatever a rep typed, which is the "nothing sensitive logged" rule above, so
+ they are gated on `NODE_ENV`. In production the durable record is an
+ `AgentEvent` row, not a log drain.
+- **It is not the audit trail.** `hooks/audit.ts` writes every event to
+ `AgentEvent` whatever this prints, and the panel's transcript is read back from
+ there. A change to one is not a change to the other.
+- **A call is timed by remembering it, because the result event does not carry
+ the tool name or a duration.** The map of in-flight calls is bounded rather
+ than trusted: a turn that dies between request and result would otherwise leak
+ an entry per call, forever, in a process that stays up for days.
+
+`eve logs` reads the full record back, but only for an **interactive** `eve dev`
+— that is the process that writes `.eve/logs/`. Under `--no-ui` the pane is the
+record, so keep the turbo scrollback rather than going looking for a file that
+was never written.
+
+Two consequences of opting into `dev:headless`, both worth recognising rather
+than debugging:
+
+- **A headless dev process cannot reconnect.** An interactive `eve dev`
+ reconnects to a local server that is already up; `dev:headless` rejects it and
+ exits non-zero. `A dev server is already running for this eve agent` means
+ exactly what it says: use the terminal it is in, or stop it before starting
+ another.
+- **An orphaned agent holds the port.** If turbo dies without reaping its child,
+ nothing on screen says so and every later `dev:headless` fails the same way.
+ `lsof -nP -iTCP:2000 -sTCP:LISTEN` names the process to kill.
+
+### Nothing is researching, and the queue only grows
+
+**`eve dev` never fires schedules on their cron cadence.** It is one line in
+eve's own [schedules guide](../apps/agent/node_modules/eve/docs/schedules.mdx),
+and it used to be the single most confusing thing about working on this agent,
+because every visible part of the loop worked: the Research button wrote its
+`AgentTask` row, the sheet said *Queued*, the toast promised the page would
+update — and `schedules/dispatch.ts`, the only thing that turns a row into a
+session, was never called. Twenty rows sat with `attempts = 0` and `AgentEvent`
+was empty. Nothing was broken and nothing reported a problem, because nothing
+ran.
+
+**The poke is what makes dev behave like production now**, which is most of why
+it was widened to both lanes — see [dispatch on demand](#dispatch-on-demand).
+A row written by the API is dispatched immediately whatever the clock is doing,
+so the schedule is a backstop rather than the only door.
+
+**It only does that when `AGENT_BRIDGE_SECRET` is set**, and that variable is
+optional: `poke()` reads it first and returns without sending anything when it is
+unset. So an install that has not set it is back at the paragraph above with no
+cron behind it either — rows queue, nothing dispatches, and the queue looks
+exactly like a slow agent. Set it, or run the dispatch below by hand.
+
+That leaves two cases where the clock's absence bites even with the poke
+working, and both look identical to the above: **a task the API did not
+write** — `schedule_recheck`,
+which books its own `dueAt` weeks out — and **anything queued while the agent was
+down**, since a missed poke is not retried. For those, the dev server mounts a
+one-shot route that runs the exact dispatch path production cron uses:
+
+```sh
+bun run --filter=agent dispatch
+# {"scheduleId":"dispatch","sessionIds":["wrun_01KZ…", …]}
+```
+
+It drains **both lanes**, exactly as the cron does: up to `VISIBLE_BATCH` (60)
+`brand` and `portrait` rows six at a time, handled in the process with no session
+at all, and `RESEARCH_BATCH` (12) research rows, one session each. So the
+`sessionIds` it prints are the research rows only — a run that resolved forty
+logos prints an empty list and was not idle. Either way it spends real credits, a
+vendor call per visible row and a model session per research one; that is the
+point of it, and the reason it is a command you run rather than a ticker somebody
+leaves on. Watch the agent pane; the session ids it returns are also streamable at
+`GET /eve/v1/session/:id/stream`.
+
+`eve start` on a built app *does* run the schedule, and so does Vercel, where
+each `defineSchedule` becomes a Cron Job. Dev is the only place the clock is
+missing.
+
+### The continuation token you write is not the one you read
+
+**eve namespaces a continuation token with the channel's name.** `channels/crm.ts`
+mints `task:<id>`; by the time `session.waiting` hands it back on the channel
+context it is `crm:task:<id>`. The `eve` channel's own sessions read back as
+`eve:<uuid>` for the same reason.
+
+This is worth stating because of how it failed, which was silently and
+completely. `taskToken()` used to mint `crm:task:<id>` itself, so the handler was
+matching `startsWith("crm:task:")` against `crm:crm:task:<id>`, getting `null`,
+and returning before `completeTask`. Nothing errored. The research ran, facts
+were written, briefs were saved, and the agent pane showed a clean session — but
+**no task ever reached `finishedAt`**, so every contact sat on "Researching"
+forever and the sweep re-queued work that had already been done. Twenty-eight
+tasks, zero finished.
+
+Two things made it survive a reading:
+
+- **The event data and the channel accessor disagree.** `session.waiting`'s
+ `data.continuationToken` carries the token *as stored* — un-namespaced — while
+ `channel.continuationToken` carries it namespaced. Debugging from the archived
+ event says the token is fine, because from that angle it is.
+- **Nothing downstream depends on settling.** The record's status is the only
+ thing that notices, and "still researching" is indistinguishable from
+ "researching slowly" until you look at `attempts` in the table.
+
+So `taskFromToken` keys on the `task:` marker rather than a fixed prefix, which
+reads correctly whoever namespaced it and still settles sessions parked before
+the fix. `test/crm-token.spec.ts` pins all three forms.
+
+The general rule: **a channel handler must not assume the token it receives is
+byte-identical to the one it sent.** Parse for your own marker.
+
+## Tests
+
+`bun run --filter=agent test`. The integration specs need `DATABASE_URL` and run
+against a real Postgres, which is the point — "never overwrite a human" is only
+true if the transaction says so.
**`taskFromToken` keys on the `task:` marker, not a fixed prefix**
(`test/crm-token.spec.ts`). **A channel handler must not assume the token it receives
is byte-identical to the one it sent.**
diff --git a/docs/setup.md b/docs/setup.md
index d329e438..01200dff 100644
--- a/docs/setup.md
+++ b/docs/setup.md
@@ -16,6 +16,14 @@ bun run dev # app :3000, api :3001, agent :2000
Prisma from the repo root: `db:generate`, `db:migrate`, `db:push`, `db:reset`,
`db:seed`, `db:studio`, `db:deploy`.
+`dev` depends on `^dev:prepare`, so every start applies pending migrations and
+regenerates the Prisma client before a single server boots. That is why the first
+run needs `db:migrate` only for the seed that follows it. When the database and
+`schema.prisma` have diverged past what `migrate deploy` can reconcile,
+`dev:prepare` stops the whole run rather than starting servers against a schema
+they do not match — reconcile with `db:migrate`, or `db:reset` when the divergence
+is an edited migration that has already been applied.
+
## Google Cloud
- **Enable the Gmail API and the Google Calendar API** on the project.
@@ -43,10 +51,14 @@ inventory, including a `diagnostics` count that finds files eve silently ignored
## Running the agent
-**`bun run dev` is `eve dev --no-ui`** — turbo gives each task a pty, so the
-interactive TUI and turbo redraw over each other. `dev:tui` keeps the interactive one,
-and only that writes `.eve/logs/` for `eve logs`; under `--no-ui` the turbo pane is
-the record.
+The agent package's default `dev` command is interactive `eve dev`. The root
+Turbo task marks it interactive, so select the agent pane and press Enter before
+using the eve TUI. Run `turbo run dev:headless --filter=agent` when a terminal
+cannot render the TUI; that uses `eve dev --no-ui`, and the Turbo pane is the
+record because only interactive development writes `.eve/logs/` for `eve logs`.
+Reach for the Turbo task rather than `bun run --filter=agent dev:headless`: the
+package script alone skips `dev:prepare`, so the agent would start against
+unmigrated tables.
`hooks/activity.ts` is the replacement narration, **to stderr** (the TUI hides
stdout), printing shape everywhere and argument contents outside production only. It
diff --git a/doctor.config.json b/doctor.config.json
new file mode 100644
index 00000000..9ebf512b
--- /dev/null
+++ b/doctor.config.json
@@ -0,0 +1,34 @@
+{
+ "$schema": "https://react.doctor/schema/config.json",
+ "ignore": {
+ "overrides": [
+ {
+ "files": ["components/inline-script.tsx"],
+ "rules": ["react-doctor/nextjs-no-native-script"]
+ },
+ {
+ "files": [
+ "src/components/accordion.tsx",
+ "src/components/button.tsx",
+ "src/components/icon.tsx",
+ "src/components/link.tsx",
+ "src/components/marker.tsx",
+ "src/components/popover.tsx",
+ "src/components/select.tsx",
+ "src/components/sheet.tsx",
+ "src/components/tabs.tsx",
+ "src/components/textarea.tsx",
+ "src/components/toggle.tsx"
+ ],
+ "rules": ["react-doctor/only-export-components"]
+ },
+ {
+ "files": [
+ "src/components/chart.tsx",
+ "src/components/dashboard-chart.tsx"
+ ],
+ "rules": ["react-doctor/prefer-dynamic-import"]
+ }
+ ]
+ }
+}
diff --git a/packages/db/package.json b/packages/db/package.json
index 80d57015..e4d45c34 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -9,6 +9,7 @@
"./blob": "./src/blob.ts",
"./client": "./src/client.ts",
"./currency": "./src/currency.ts",
+ "./deal-stage": "./src/deal-stage.ts",
"./enums": "./src/generated/prisma/enums.ts",
"./favicon": "./src/favicon.ts",
"./fields": "./src/fields.ts",
diff --git a/packages/db/prisma/migrations/20260806160000_agent_version_model_context_window/migration.sql b/packages/db/prisma/migrations/20260806160000_agent_version_model_context_window/migration.sql
new file mode 100644
index 00000000..09d9297a
--- /dev/null
+++ b/packages/db/prisma/migrations/20260806160000_agent_version_model_context_window/migration.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "agentVersion"
+ADD COLUMN "modelContextWindowTokens" INTEGER NOT NULL DEFAULT 1000000;
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index fa33726f..b2705a0a 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -610,11 +610,12 @@ model AgentVersion {
number Int
status AgentVersionStatus @default(DRAFT)
- instructions String
- manifest Json
- modelId String
- sandboxPolicy Json
- validation Json?
+ instructions String
+ manifest Json
+ modelId String
+ modelContextWindowTokens Int @default(1000000)
+ sandboxPolicy Json
+ validation Json?
sourceConversationId String?
sourceConversation AgentConversation? @relation("AgentVersionSourceConversation", fields: [sourceConversationId], references: [id], onDelete: SetNull)
diff --git a/apps/api/src/deals/deal-stage.ts b/packages/db/src/deal-stage.ts
similarity index 90%
rename from apps/api/src/deals/deal-stage.ts
rename to packages/db/src/deal-stage.ts
index a0b1e990..99f32fb3 100644
--- a/apps/api/src/deals/deal-stage.ts
+++ b/packages/db/src/deal-stage.ts
@@ -1,4 +1,4 @@
-import { DealStage } from "@crm/db";
+import { DealStage } from "./generated/prisma/enums";
export const OPEN_DEAL_STAGES = [
DealStage.DEMO_BOOKED,
diff --git a/packages/telemetry/src/allowlist.ts b/packages/telemetry/src/allowlist.ts
index c58791b1..007ae6a7 100644
--- a/packages/telemetry/src/allowlist.ts
+++ b/packages/telemetry/src/allowlist.ts
@@ -106,6 +106,7 @@ export function permitted(
}
export const AGENT_TOOLS = [
+ "agent",
"archive_field",
"enrich_company",
"fetch_contact_photo",
@@ -113,6 +114,7 @@ export const AGENT_TOOLS = [
"get_contact_work_history",
"get_linkedin_profile",
"identify_contact",
+ "list_deals",
"list_fields",
"list_outstanding_work",
"manage_fields",
@@ -126,6 +128,7 @@ export const AGENT_TOOLS = [
"resolve_linkedin_profile",
"schedule_recheck",
"search_crm",
+ "set_chat_title",
"set_contact_socials",
"set_field_value",
"write_brief",
@@ -133,7 +136,6 @@ export const AGENT_TOOLS = [
] as const;
export const EVE_TOOLS = [
- "agent",
"ask_question",
"bash",
"connection_search",
diff --git a/turbo.json b/turbo.json
index a7cd31f1..ed196c2e 100644
--- a/turbo.json
+++ b/turbo.json
@@ -90,6 +90,14 @@
"dependsOn": ["^dev:prepare"],
"cache": false,
"persistent": true
+ },
+ "dev:headless": {
+ "dependsOn": ["^dev:prepare"],
+ "cache": false,
+ "persistent": true
+ },
+ "dev:prepare": {
+ "cache": false
}
}
}