Merge current MCP foundation

* codex/paperclip-public-mcp:
  test(shared): make the worktree port registry lock suite deterministic (#12798)
  fix(adapter-utils): make the directory merge lock crash test deterministic (#14881)
  feat(connections): make AgentMail a default connection with inline setup (#14772)
  fix(chat): hide ignored provider information (#14929)
  build(deps): bump aws-actions/configure-aws-credentials from 6.2.3 to 6.3.0 (#12966)

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-02 10:34:18 -05:00
commit a75c50f79f
94 files changed
+4126 -2196

No files matched your search

@@ -24,6 +24,43 @@ const message = (extra = {}) =>
...extra,
});
describe("AgentMail protocol boundary", () => {
it("checks the visible inbox list without probing an uncreated address", async () => {
const fetcher = vi.fn(async () => Response.json({ inboxes: [{ inbox_id: "Ralph@agentmail.to" }] }));
await expect(agentmailApi("private-key", fetcher).checkAddress("ralph@agentmail.to"))
.resolves.toEqual({ address: "ralph@agentmail.to", status: "taken" });
expect(fetcher).toHaveBeenCalledOnce();
expect(fetcher).toHaveBeenCalledWith("https://api.agentmail.to/v0/inboxes?limit=100", expect.objectContaining({ method: "GET", body: undefined }));
});
it("never treats an unlisted inbox as proof that an address is available", async () => {
const fetcher = vi.fn(async () => Response.json({ inboxes: [], next_page_token: "more-inboxes" }));
await expect(agentmailApi("private-key", fetcher).checkAddress("ralph@agentmail.to"))
.resolves.toEqual({ address: "ralph@agentmail.to", status: "unknown" });
});
it("can create the checked address and its access key when the provider caches missing inbox lookups", async () => {
let created = false;
let negativeLookupCached = false;
const fetcher = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
const path = new URL(String(url)).pathname;
if (path === "/v0/inboxes" && init?.method === "GET") return Response.json({ inboxes: [] });
if (path === "/v0/inboxes" && init?.method === "POST") {
created = true;
return Response.json({ inbox_id: "ralph@agentmail.to" });
}
if (path === "/v0/inboxes/ralph%40agentmail.to" && !created) negativeLookupCached = true;
if (!created || negativeLookupCached) return Response.json({ code: "not_found" }, { status: 404 });
return Response.json({ api_key: "test-runtime-key", api_key_id: "runtime-id" });
});
const api = agentmailApi("test-account-key", fetcher);
await expect(api.checkAddress("ralph@agentmail.to")).resolves.toMatchObject({ status: "unknown" });
const inbox = await api.createInbox({ username: "ralph" });
await expect(api.createInboxKey(inbox.inbox_id)).resolves.toMatchObject({ api_key_id: "runtime-id" });
expect(negativeLookupCached).toBe(false);
});
it.each([401, 403, 404, 429, 503])("preserves lookup errors (%s) rather than claiming an address is taken or free", async status => {
const fetcher = vi.fn(async () => Response.json({ code: "missing_permission" }, { status }));
await expect(agentmailApi("private-key", fetcher).checkAddress("ralph@agentmail.to"))
.rejects.toMatchObject({ status, operation: "list_inboxes" });
});
it("verifies the exact raw body and rejects forged or stale Svix signatures", () => {
const secret = `whsec_${Buffer.from("a-test-secret-only").toString("base64")}`;
const body = JSON.stringify({
@@ -322,6 +359,10 @@ describe("AgentMail protocol boundary", () => {
expect(send?.responses).toHaveProperty("202");
const setup = operations.find(o => o.path === "/api/companies/{companyId}/email/inspect");
expect(JSON.stringify(setup?.authorization)).toContain("board");
const check = operations.find(o => o.path === "/api/companies/{companyId}/email/connections/{connectionId}/check-address");
expect(check?.requestBody).toBeDefined();
expect(JSON.stringify(check?.authorization)).toContain("board");
expect(check?.responses).toHaveProperty("429");
});
});
@@ -281,17 +281,24 @@ const support = await getEmbeddedPostgresTestSupport();
await instanceSettingsService(db).updateExperimental({ enableChatConnectors: false });
}
});
it("discovers all purposes with truthful setup actions and the chat feature gate", async () => {
it.each([false, true])("discovers AgentMail with truthful setup actions regardless of the chat setting (%s)", async (enabled) => {
await resetQuestions();
const service = connectionIntentService(db);
expect((await service.search(claims, "agentmail")).results.some(item => item.service === "agentmail")).toBe(false);
await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true });
await instanceSettingsService(db).updateExperimental({ enableChatConnectors: enabled });
try {
const result = await service.search(claims, "agentmail");
expect(result.results[0]?.methods).toEqual([expect.objectContaining({
key: "email-agent", purpose: "channel", setupPath: `/AGG/apps/chat/connect?provider=agentmail&purpose=chat&agentId=${claims.sub}`,
})]);
expect(result.instruction).toContain("setupPath");
expect(result.instruction).toContain("connection_request");
const requested = await service.request(claims, "agentmail");
expect(requested).toMatchObject({ state: "needs_user_action", interactionId: expect.any(String) });
expect(await service.request(claims, "agentmail")).toMatchObject({ interactionId: requested.interactionId });
const options = await service.setupOptions(requested.interactionId!);
expect(options.interaction.payload).toMatchObject({ purpose: "channel", serviceSlug: "agentmail", requestingAgentId: claims.sub });
expect(options.emailSetup).toEqual({ credentialConnectionId: null, readyConnectionId: null });
await service.decline(requested.interactionId!, "responsible-user");
await expect(service.request(claims, "agentmail")).rejects.toThrow(/already been resolved/);
const browse = await service.search(claims, "");
expect(browse.results.some(item => item.service === "agentmail")).toBe(true);
expect(browse.results.some(item => item.service === "anthropic")).toBe(true);
@@ -0,0 +1,82 @@
import express from "express";
import request from "supertest";
import type { Db } from "@paperclipai/db";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { forbidden } from "../errors.js";
import { errorHandler } from "../middleware/error-handler.js";
import { emailRoutes } from "../routes/email.js";
import type { EmailChannelService } from "../services/email-channels.js";
const mocks = vi.hoisted(() => ({ credential: vi.fn(), listCredentials: vi.fn(), permission: vi.fn() }));
vi.mock("../services/email-connections.js", () => ({ emailConnectionService: () => ({ credential: mocks.credential, listCredentials: mocks.listCredentials }) }));
vi.mock("../services/access.js", () => ({ accessService: () => ({ hasPermission: mocks.permission }) }));
const companyId = "11111111-1111-4111-8111-111111111111";
const connectionId = "22222222-2222-4222-8222-222222222222";
const path = `/api/companies/${companyId}/email/connections/${connectionId}/check-address`;
const input = { username: "ralph", domain: "agentmail.to" };
function app(actor = { type: "board", source: "local_implicit", userId: "board" } as express.Request["actor"]) {
const instance = express();
instance.use(express.json());
instance.use((req, _res, next) => { req.actor = actor; next(); });
instance.use("/api", emailRoutes({} as Db, {} as EmailChannelService));
instance.use(errorHandler);
return instance;
}
beforeEach(() => {
vi.resetAllMocks();
mocks.credential.mockResolvedValue({ value: "private-key" });
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ inboxes: [{ inbox_id: "ralph@agentmail.to" }] })));
});
afterEach(() => vi.unstubAllGlobals());
describe("AgentMail address checks", () => {
it("lists saved-key metadata with company and manager access checks", async () => {
const listPath = `/api/companies/${companyId}/email/connections`;
mocks.listCredentials.mockResolvedValue([{ id: connectionId, label: "AgentMail account key", scope: "organization" }]);
const response = await request(app()).get(listPath).expect(200);
expect(response.headers["cache-control"]).toBe("no-store");
expect(mocks.listCredentials).toHaveBeenCalledWith(companyId, expect.objectContaining({ userId: "board" }));
mocks.listCredentials.mockClear();
await request(app({ type: "agent", agentId: connectionId, companyId })).get(listPath).expect(403);
await request(app({ type: "board", source: "session", userId: "member", companyIds: [] })).get(listPath).expect(404);
await request(app({ type: "board", source: "session", userId: "member", companyIds: [companyId] })).get(listPath).expect(403);
expect(mocks.listCredentials).not.toHaveBeenCalled();
});
it("uses the company-scoped saved credential and returns only address status", async () => {
const response = await request(app()).post(path).send({ username: "Ralph", domain: "AgentMail.to" }).expect(200);
expect(response.body).toEqual({ address: "ralph@agentmail.to", status: "taken" });
expect(response.headers["cache-control"]).toBe("no-store");
expect(mocks.credential).toHaveBeenCalledWith(companyId, connectionId, expect.objectContaining({ userId: "board" }));
expect(fetch).toHaveBeenCalledWith("https://api.agentmail.to/v0/inboxes?limit=100", expect.objectContaining({ method: "GET" }));
expect(response.text).not.toContain("private-key");
});
it.each([
{ username: "bad/name", domain: "agentmail.to" },
{ username: "r".repeat(65), domain: "agentmail.to" },
{ username: "ralph", domain: "https://other.test" },
{ ...input, apiKey: "unexpected" },
])("rejects malformed input before reading credentials (%#)", async body => {
await request(app()).post(path).send(body).expect(400);
expect(mocks.credential).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
});
it("does not allow agents to check addresses", async () => {
await request(app({ type: "agent", agentId: connectionId, companyId })).post(path).send(input).expect(403);
expect(fetch).not.toHaveBeenCalled();
});
it("requires company access and connection management permission", async () => {
await request(app({ type: "board", source: "session", userId: "member", companyIds: [] })).post(path).send(input).expect(404);
await request(app({ type: "board", source: "session", userId: "member", companyIds: [companyId] })).post(path).send(input).expect(403);
expect(mocks.credential).not.toHaveBeenCalled();
});
it("preserves credential access checks", async () => {
mocks.credential.mockRejectedValueOnce(forbidden("Credential access denied"));
await request(app()).post(path).send(input).expect(403);
expect(fetch).not.toHaveBeenCalled();
});
it("surfaces rate limits without copying provider bodies", async () => {
vi.mocked(fetch).mockResolvedValueOnce(Response.json({ code: "rate_limit_exceeded", message: "private-key" }, { status: 429, headers: { "retry-after": "10" } }));
const response = await request(app()).post(path).send(input).expect(429);
expect(response.headers["retry-after"]).toBe("10");
expect(response.text).not.toContain("private-key");
});
});
@@ -1,3 +1,4 @@
import { connectionIntentService } from "../services/connection-intents.js";
import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments, annotateConnectorSkills } from "../services/connector-runtime.js";
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
import { renderPaperclipWakePrompt, resolvePaperclipDesiredSkillNames, resolveLegacyPaperclipDesiredSkillNames } from "@paperclipai/adapter-utils/server-utils";
@@ -5,6 +6,7 @@ import express from "express";
import type WebSocket from "ws";
import request from "supertest";
import { issueRoutes } from "../routes/issues.js";
import { emailRoutes } from "../routes/email.js";
import { errorHandler } from "../middleware/index.js";
import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";
import { randomUUID } from "node:crypto";
@@ -43,6 +45,7 @@ import {
issues,
authUsers,
companyMemberships,
principalPermissionGrants,
toolConnections,
toolConnectionInstalls,
connectionGrants,
@@ -59,6 +62,7 @@ import {
agentmailMessageSchema,
type AgentmailMessage,
} from "../services/agentmail-api.js";
import { accessService } from "../services/access.js";
import { emailConnectionService } from "../services/email-connections.js";
import { toolAccessService } from "../services/tool-access.js";
import { emailSendSchema } from "@paperclipai/shared";
@@ -78,7 +82,7 @@ describe("AgentMail durable email pipeline", () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-email-");
db = createDb(database.connectionString);
await instanceSettingsService(db).updateExperimental({
enableChatConnectors: true,
enableChatConnectors: false,
});
await db.insert(authUsers).values({
id: "email-board",
@@ -178,12 +182,11 @@ describe("AgentMail durable email pipeline", () => {
expect((await resolveConnectorAssignments(db, binding))[0].resources).toHaveLength(1);
});
it("removes connector contributions when the experimental gate or credential access is revoked", async () => {
it("keeps AgentMail available with chat disabled and removes contributions when credential access is revoked", async () => {
const f = await fixture();
const binding = { companyId: f.companyId, agentId: f.agentId };
await instanceSettingsService(db).updateExperimental({ enableChatConnectors: false });
try { expect(await resolveConnectorAssignments(db, binding)).toEqual([]); }
finally { await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true }); }
expect((await resolveConnectorAssignments(db, binding)).map(item => item.key)).toEqual(["agentmail"]);
const endpoint = await f.service.getEndpoint(f.endpointId);
await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, endpoint.connectionId));
expect(await resolveConnectorAssignments(db, binding)).toEqual([]);
@@ -981,6 +984,57 @@ describe("AgentMail durable email pipeline", () => {
expect(f.wakeup).toHaveBeenCalledTimes(1);
});
it("suggests only same-provider active credentials authorized for this user", async () => {
const f = await fixture();
const svc = emailConnectionService(db, f.fetcher);
const actor = { userId: "email-board" };
const own = await svc.connect(f.companyId, { apiKey: "private-key", grantKind: "user", allAgents: false,
agentIds: [], idempotencyKey: randomUUID() }, actor);
const shared = await svc.connect(f.companyId, { apiKey: "shared-key", grantKind: "organization", allAgents: false,
agentIds: [], idempotencyKey: randomUUID() }, actor);
const other = await svc.connect(f.companyId, { apiKey: "other-user-key", grantKind: "user", allAgents: false,
agentIds: [], idempotencyKey: randomUUID() }, { userId: "different-user" });
const choices = await svc.listCredentials(f.companyId, actor);
expect(choices.map(option => option.id).sort()).toEqual([own.id, shared.id].sort());
expect(JSON.stringify(choices)).not.toMatch(/private-key|shared-key|other-user-key|secretId|api_key_hash/);
expect(choices[0]).toMatchObject({ scope: "inbox", inboxId: f.address });
expect((await svc.listCredentials(randomUUID(), actor))).toEqual([]);
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, own.id));
await db.update(toolConnections).set({ config: { provider: "different", emailCredential: true } }).where(eq(toolConnections.id, shared.id));
expect(await svc.listCredentials(f.companyId, actor)).toEqual([]);
expect((await svc.listCredentials(f.companyId, { userId: "different-user" })).map(option => option.id)).toEqual([other.id]);
});
it("bounds legacy saved-key discovery and checks slow keys concurrently", async () => {
const f = await fixture();
const actor = { userId: "email-board" };
const svc = emailConnectionService(db, f.fetcher);
const ids = [];
for (let i = 0; i < 2; i++) {
const row = await svc.connect(f.companyId, { apiKey: `legacy-key-${i}`, grantKind: "organization", allAgents: false,
agentIds: [], idempotencyKey: randomUUID() }, actor);
ids.push(row.id);
await db.update(toolConnections).set({ config: { provider: "agentmail", emailCredential: true } }).where(eq(toolConnections.id, row.id));
}
let concurrent = 0, peak = 0;
const signals: AbortSignal[] = [];
const slowFetch = vi.fn<typeof fetch>(async (_url, init) => {
concurrent++; peak = Math.max(peak, concurrent);
const signal = init!.signal!; signals.push(signal);
try {
return await new Promise<Response>((_resolve, reject) => {
if (signal.aborted) reject(new Error("Discovery deadline"));
else signal.addEventListener("abort", () => reject(new Error("Discovery deadline")), { once: true });
});
} finally { concurrent--; }
});
const choices = await emailConnectionService(db, slowFetch).listCredentials(f.companyId, actor);
expect(choices.map(option => option.id).sort()).toEqual(ids.sort());
expect(choices.every(option => option.scope === "unavailable")).toBe(true);
expect(peak).toBe(2);
expect(signals.every(signal => signal.aborted)).toBe(true);
}, 10_000);
it("saves a scoped credential before inbox setup, preserves personal ownership, and adds the chosen agent", async () => {
const f = await fixture();
const svc = emailConnectionService(db, f.fetcher);
@@ -1060,6 +1114,214 @@ describe("AgentMail durable email pipeline", () => {
).rejects.toThrow(/revoked/);
});
it.each(["new", "reused"] as const)("finishes a %s account for the final agent with only connection-management permission", async kind => {
const f = await fixture("websocket");
const actor = { userId: "email-board" };
await f.service.control(f.endpointId, "remove", actor);
const selectedAgentId = randomUUID();
await db.insert(agents).values({ id: selectedAgentId, companyId: f.companyId, name: "Final email agent",
role: "engineer", status: "idle", adapterType: "process", permissions: {} });
await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user",
principalId: actor.userId, permissionKey: "tools:manage_connections" });
expect(await accessService(db).hasPermission(f.companyId, "user", actor.userId, "tools:manage_connections")).toBe(true);
expect(await accessService(db).hasPermission(f.companyId, "user", actor.userId, "agent_config:update")).toBe(false);
const requestId = randomUUID();
const svc = emailConnectionService(db, f.fetcher);
const connection = await svc.connect(f.companyId, { apiKey: "test-key", grantKind: "organization",
allAgents: false, agentIds: [f.agentId], idempotencyKey: kind === "new" ? requestId : randomUUID() }, actor);
const server = express();
server.use(express.json());
server.use((req, _res, next) => {
req.actor = { type: "board", source: "session", userId: actor.userId, companyIds: [f.companyId] };
next();
});
server.use("/api", emailRoutes(db, f.service));
server.use(errorHandler);
const input = { assignedAgentId: selectedAgentId, credentialConnectionId: connection.id,
inboxId: f.address, receiveMode: "websocket", idempotencyKey: requestId };
const route = `/api/companies/${f.companyId}/email/inboxes`;
// Keep one listener for this journey instead of racing ephemeral listeners
// against Node's HTTP keep-alive socket reuse between requests.
const http = server.listen(0, "127.0.0.1");
await new Promise<void>((resolve, reject) => { http.once("listening", resolve); http.once("error", reject); });
try {
const response = await request(http).post(route).send(input).expect(201);
expect(response.body).toMatchObject({ assignedAgentId: selectedAgentId, status: "active", address: f.address });
await request(http).post(route).send(input).expect(201);
const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));
expect(installs.map(i => i.targetId).sort()).toEqual((kind === "new" ? [selectedAgentId] : [f.agentId, selectedAgentId]).sort());
await expect(svc.assertAgentAccess(f.companyId, connection.id, selectedAgentId)).resolves.toBeUndefined();
if (kind === "new") await expect(svc.assertAgentAccess(f.companyId, connection.id, f.agentId)).rejects.toThrow(/no longer has access/);
await request(http).post(`/api/companies/${randomUUID()}/email/inboxes`).send(input).expect(404);
} finally {
await new Promise<void>((resolve, reject) => http.close(error => error ? reject(error) : resolve()));
}
});
it.each([
["before setup", "company"], ["before setup", "agents"],
["after a failed setup", "company"], ["after a failed setup", "agents"],
] as const)("preserves permissions edited %s to include %s access", async (when, scope) => {
const f = await fixture("websocket");
const actor = { userId: "email-board" };
await f.service.control(f.endpointId, "remove", actor);
const selectedAgentId = randomUUID(), otherAgentId = randomUUID();
await db.insert(agents).values([selectedAgentId, otherAgentId].map(id => ({ id, companyId: f.companyId,
name: "Email agent", role: "engineer", status: "idle", adapterType: "process", permissions: {} })));
const requestId = randomUUID();
const connection = await emailConnectionService(db, f.fetcher).connect(f.companyId, {
apiKey: "test-key", grantKind: "organization", allAgents: false, agentIds: [f.agentId], idempotencyKey: requestId,
}, actor);
const input = { assignedAgentId: selectedAgentId, credentialConnectionId: connection.id,
inboxId: f.address, receiveMode: "websocket" as const, idempotencyKey: requestId };
if (when === "after a failed setup") {
const provider = vi.mocked(f.fetcher).getMockImplementation()!;
vi.mocked(f.fetcher).mockImplementation(async (url, init) =>
decodeURIComponent(new URL(String(url)).pathname) === `/v0/inboxes/${f.address}`
? new Response(null, { status: 403 }) : provider(url, init));
await expect(f.service.setup(f.companyId, input, actor)).rejects.toThrow();
vi.mocked(f.fetcher).mockImplementation(provider);
}
const requestedInstalls = scope === "company"
? [{ targetType: "company" as const, targetId: f.companyId }]
: [f.agentId, otherAgentId].map(targetId => ({ targetType: "agent" as const, targetId }));
await toolAccessService(db).putConnectionInstalls(connection.id, { installs: requestedInstalls }, { actorType: "user", actorId: actor.userId });
const before = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));
const result = await f.service.setup(f.companyId, input, actor);
expect(result.status).toBe("active");
const after = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));
for (const install of before) expect(after).toContainEqual(install);
expect(after.map(i => i.targetId).sort()).toEqual((scope === "company" ? [f.companyId] : [f.agentId, otherAgentId, selectedAgentId]).sort());
});
it.each(["create_inbox", "create_inbox_key", "address_taken"] as const)("reports a provider rejection during %s and resumes the same setup after correction", async (failedOperation) => {
const f = await fixture("websocket");
await f.service.control(f.endpointId, "remove", { userId: "email-board" });
const provider = vi.mocked(f.fetcher).getMockImplementation()!;
let denied = true;
let createdInboxes = 0;
vi.mocked(f.fetcher).mockImplementation(async (url, init) => {
const pathname = new URL(String(url)).pathname;
if (pathname === "/v0/auth/me" && new Headers(init?.headers).get("authorization") === "Bearer organization-test-key") {
return Response.json({ scope_type: "organization", organization_id: "organization" });
}
if (pathname === "/v0/inboxes" && init?.method === "POST") {
if (failedOperation === "address_taken") {
const body = JSON.parse(String(init.body));
if (body.username === "ralph") return Response.json({ code: "resource_taken", message: "private provider detail" }, { status: 403 });
expect(body.username).toBe("ralph-team");
}
if (denied && failedOperation === "create_inbox") return new Response("private provider denial", { status: 403 });
createdInboxes++;
return Response.json({ inbox_id: f.address });
}
if (pathname.endsWith("/api-keys") && init?.method === "POST") {
if (denied && failedOperation === "create_inbox_key") return new Response("private provider denial", { status: 403 });
return Response.json({ api_key: "test-key", api_key_id: "inbox-runtime-key" });
}
return provider(url, init);
});
const account = await emailConnectionService(db, f.fetcher).connect(f.companyId, {
apiKey: "organization-test-key", grantKind: "organization", allAgents: false,
agentIds: [f.agentId], idempotencyKey: randomUUID(),
}, { userId: "email-board" });
const server = express();
server.use(express.json());
server.use((req, _res, next) => {
req.actor = { type: "board", source: "local_implicit", userId: "email-board" };
next();
});
server.use("/api", emailRoutes(db, f.service));
server.use(errorHandler);
const id = randomUUID();
const input = { assignedAgentId: f.agentId, credentialConnectionId: account.id,
username: "ralph", domain: "agentmail.to", receiveMode: "websocket", idempotencyKey: id };
const route = `/api/companies/${f.companyId}/email/inboxes`;
const failure = await request(server).post(route).send(input).expect(failedOperation === "address_taken" ? 409 : 422);
expect(failure.body.error).toContain(failedOperation === "address_taken" ? "already in use" : "AgentMail did not allow Paperclip");
expect(failure.body.details).toMatchObject({ providerStatus: 403, operation: failedOperation === "address_taken" ? "create_inbox" : failedOperation });
expect(failure.text).not.toMatch(/private provider denial|organization-test-key|Internal server error/);
const [draft] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, id));
expect(draft.status).toBe("draft");
expect(draft.botExternalId).toBe(failedOperation === "create_inbox_key" ? f.address : null);
denied = false;
if (failedOperation === "address_taken") input.username = "ralph-team";
const connected = await request(server).post(route).send(input).expect(201);
expect(connected.body).toMatchObject({ id, status: "active", address: f.address });
await request(server).post(route).send(input).expect(201);
expect(createdInboxes).toBe(1);
const endpoints = await db.select().from(chatEndpoints).where(and(
eq(chatEndpoints.companyId, f.companyId), ne(chatEndpoints.status, "archived"),
));
expect(endpoints.map(endpoint => endpoint.id)).toEqual([id]);
});
it.each(["inbox", "organization"] as const)("completes an AgentMail card with a %s key only after its assigned inbox is usable", async (scope) => {
const f = await fixture("websocket");
const actor = { userId: "email-board" };
await f.service.control(f.endpointId, "remove", actor);
const provider = vi.mocked(f.fetcher).getMockImplementation()!;
const createdInboxes: unknown[] = [];
vi.mocked(f.fetcher).mockImplementation(async (url, init) => {
const pathname = new URL(String(url)).pathname;
if (pathname === "/v0/auth/me" && new Headers(init?.headers).get("authorization") === "Bearer organization-test-key") {
return Response.json({ scope_type: "organization", organization_id: "organization" });
}
if (pathname === "/v0/inboxes" && init?.method === "POST") {
createdInboxes.push(JSON.parse(String(init.body)));
return Response.json({ inbox_id: f.address });
}
if (pathname.endsWith("/api-keys") && init?.method === "POST") {
return Response.json({ api_key: "test-key", api_key_id: "inbox-runtime-key" });
}
return provider(url, init);
});
const issue = await issueService(db).create(f.companyId, { title: "Acquire an email address", assigneeAgentId: f.agentId, status: "in_progress" });
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId,
status: "running", responsibleUserId: "email-board", contextSnapshot: { issueId: issue.id } });
const claims = { sub: f.agentId, company_id: f.companyId, run_id: runId, responsible_user_id: "email-board" };
const intents = connectionIntentService(db);
const requested = await intents.request(claims, "agentmail");
const id = requested.interactionId!;
const account = await emailConnectionService(db, f.fetcher).connect(f.companyId, {
apiKey: scope === "organization" ? "organization-test-key" : "test-key", grantKind: "organization", allAgents: false, agentIds: [f.agentId], idempotencyKey: id,
}, actor);
expect((await intents.setupOptions(id)).emailSetup).toEqual({ credentialConnectionId: account.id, readyConnectionId: null });
expect((await intents.search(claims, "agentmail")).results[0].state).not.toBe("ready");
await expect(intents.complete(id, account.id, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);
const inbox = await f.service.setup(f.companyId, { assignedAgentId: f.agentId,
credentialConnectionId: account.id, receiveMode: "websocket", idempotencyKey: id }, actor);
expect(createdInboxes).toEqual(scope === "organization"
? [{ display_name: "Email agent", client_id: `paperclip-${id}` }] : []);
const retry = await f.service.setup(f.companyId, { assignedAgentId: f.agentId,
credentialConnectionId: account.id, receiveMode: "websocket", idempotencyKey: id }, actor);
expect(retry.connectionId).toBe(inbox.connectionId);
expect(createdInboxes).toHaveLength(scope === "organization" ? 1 : 0);
expect((await intents.setupOptions(id)).emailSetup?.readyConnectionId).toBe(inbox.connectionId);
await expect(intents.complete(id, inbox.connectionId, "someone-else", { canManageOrganizationGrant: true })).rejects.toThrow(/addressed user/);
await expect(intents.complete(id, inbox.connectionId, "email-board")).rejects.toThrow(/connection-management/);
const otherAgentId = randomUUID();
await db.insert(agents).values({ id: otherAgentId, companyId: f.companyId, name: "Other agent", role: "engineer", status: "idle", adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} });
await db.update(chatEndpoints).set({ assignedAgentId: otherAgentId }).where(eq(chatEndpoints.id, id));
await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);
await db.update(chatEndpoints).set({ assignedAgentId: f.agentId, status: "paused" }).where(eq(chatEndpoints.id, id));
await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);
await db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, id));
const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, account.id));
expect(grants.map(grant => grant.kind)).toEqual(["organization"]);
const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.id));
expect(installs.map(install => ({ type: install.targetType, id: install.targetId }))).toEqual([{ type: "agent", id: f.agentId }]);
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, account.id));
await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);
await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.connectionId, account.id));
const completed = await intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true });
expect(completed).toMatchObject({ status: "accepted", result: { outcome: "connected", connectionId: inbox.connectionId } });
expect((await intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).id).toBe(id);
expect(await intents.request(claims, "agentmail")).toMatchObject({ state: "ready", interactionId: null, connectionId: inbox.connectionId });
expect((await intents.search(claims, "agentmail")).results[0]).toMatchObject({ state: "ready", connectionId: inbox.connectionId });
});
it("checks AgentMail account and inbox health without local stdio or MCP discovery", async () => {
const f = await fixture();
const connection = await emailConnectionService(db, f.fetcher).connect(f.companyId, {
@@ -0,0 +1,113 @@
import express from "express";
import request from "supertest";
import type { Db } from "@paperclipai/db";
import { describe, expect, it, vi } from "vitest";
import { forbidden } from "../errors.js";
import { errorHandler } from "../middleware/error-handler.js";
import { emailRoutes } from "../routes/email.js";
import { agentmailApi } from "../services/agentmail-api.js";
import type { EmailChannelService } from "../services/email-channels.js";
const companyId = "11111111-1111-4111-8111-111111111111";
const agentId = "22222222-2222-4222-8222-222222222222";
const setupPath = `/api/companies/${companyId}/email/inboxes`;
const setupInput = {
assignedAgentId: agentId,
apiKey: "private-api-key",
username: "ralph",
receiveMode: "websocket",
idempotencyKey: "33333333-3333-4333-8333-333333333333",
};
function app(setup: () => Promise<unknown>) {
const instance = express();
instance.use(express.json());
instance.use((req, _res, next) => {
req.actor = { type: "board", source: "local_implicit", userId: "board" };
next();
});
instance.use("/api", emailRoutes({} as Db, { setup, inspect: setup } as unknown as EmailChannelService));
instance.use(errorHandler);
return instance;
}
describe("AgentMail provider errors at the HTTP boundary", () => {
it("explains a key-creation 404 without claiming the allocated address is missing", async () => {
const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({ code: "not_found" }, { status: 404 })));
const response = await request(app(() => api.createInboxKey("ralph@agentmail.to")))
.post(setupPath).send(setupInput).expect(422);
expect(response.body.error).toBe("AgentMail could not create an access key for this inbox. The email address was saved; try finishing the connection again.");
expect(response.body.details).toMatchObject({ providerStatus: 404, operation: "create_inbox_key" });
});
it.each(["resource_taken", "already_exists"])("identifies %s on inbox creation even when AgentMail returns 403", async (code) => {
const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({
code, message: "private provider message", fix: "private-api-key", docs: "https://untrusted.invalid",
}, { status: 403 })));
const response = await request(app(() => api.createInbox({ username: "ralph" })))
.post(setupPath).send(setupInput).expect(409);
expect(response.body).toMatchObject({
code: "agentmail_address_taken", error: "This email address is already in use. Choose a different address.",
details: { field: "username", providerStatus: 403, operation: "create_inbox" },
});
expect(response.text).not.toMatch(/private|untrusted/);
});
it("does not mislabel a taken resource during another operation as a taken address", async () => {
const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({ code: "resource_taken" }, { status: 403 })));
const response = await request(app(() => api.createInboxKey("ralph@agentmail.to")))
.post(setupPath).send(setupInput).expect(422);
expect(response.body.code).toBe("agentmail_request_failed");
expect(response.body.error).not.toContain("already in use");
});
it.each([
[401, 422, "AgentMail rejected the API key"],
[403, 422, "AgentMail did not allow Paperclip to create the email address"],
[400, 422, "Try a different address"],
[409, 422, "Try a different address"],
[422, 422, "Try a different address"],
[404, 422, "could not find the requested inbox or resource"],
[429, 429, "rate limiting"],
[503, 502, "temporarily unavailable"],
])("explains provider %i without exposing the provider body", async (providerStatus, status, message) => {
const fetcher = vi.fn(async () => new Response("private provider body and private-api-key", {
status: providerStatus,
headers: { "Retry-After": "12" },
}));
const api = agentmailApi("private-api-key", fetcher);
const response = await request(app(() => api.createInbox({ username: "ralph" })))
.post(setupPath).send(setupInput);
expect(response.status).toBe(status);
expect(response.body.error).toContain(message);
expect(response.body.details).toEqual({
code: "agentmail_request_failed", providerStatus, operation: "create_inbox",
});
expect(response.text).not.toMatch(/private|Internal server error/);
if (providerStatus === 429) expect(response.headers["retry-after"]).toBe("12");
});
it("explains a denied runtime-key creation without suggesting a different address", async () => {
const api = agentmailApi("private-api-key", vi.fn(async () => new Response(null, { status: 403 })));
const response = await request(app(() => api.createInboxKey("ralph@agentmail.to")))
.post(setupPath).send(setupInput).expect(422);
expect(response.body.error).toContain("create an inbox-scoped API key");
expect(response.body.error).not.toContain("different address");
expect(response.body.details.operation).toBe("create_inbox_key");
});
it("keeps a rejected provider key distinct from Paperclip session authentication", async () => {
const api = agentmailApi("private-api-key", vi.fn(async () => new Response(null, { status: 401 })));
const response = await request(app(() => api.whoami()))
.post(`/api/companies/${companyId}/email/inspect`).send({ apiKey: "private-api-key" }).expect(422);
expect(response.body.error).toContain("AgentMail rejected the API key");
expect(response.body.details.operation).toBe("inspect_key");
});
it("preserves Paperclip authorization errors", async () => {
const response = await request(app(async () => { throw forbidden("Missing permission: tools:manage_connections"); }))
.post(setupPath).send(setupInput).expect(403);
expect(response.body.error).toBe("Missing permission: tools:manage_connections");
expect(response.body.details).toBeUndefined();
});
});
+82 -4
View File
@@ -1,7 +1,8 @@
import { Router, type Request } from "express";
import { Router, type ErrorRequestHandler, type Request } from "express";
import { z } from "zod";
import {
emailConnectionSchema,
emailAddressCheckSchema,
emailEndpointSetupSchema,
emailSendSchema,
isUuidLike,
@@ -11,7 +12,9 @@ import { validate } from "../middleware/validate.js";
import { assertBoard, assertCompanyAccess, hasCompanyAccess } from "./authz.js";
import { emailConnectionService } from "../services/email-connections.js";
import { accessService } from "../services/access.js";
import { badRequest, forbidden, notFound } from "../errors.js";
import { badRequest, forbidden, HttpError, notFound } from "../errors.js";
import { agentmailApi, AgentmailApiError } from "../services/agentmail-api.js";
import { logger } from "../middleware/logger.js";
import type {
EmailChannelService,
EmailActor,
@@ -25,6 +28,62 @@ function actor(req: Request): EmailActor {
localImplicit: req.actor.source === "local_implicit",
};
}
// Provider rejections describe setup/account problems, not Paperclip crashes.
// Only local messages and operation names reach the UI; never forward a body.
const agentmailErrorHandler: ErrorRequestHandler = (error, _req, res, next) => {
if (!(error instanceof AgentmailApiError)) return next(error);
logger.warn({ operation: error.operation, providerStatus: error.status, providerCode: error.providerCode }, "AgentMail request rejected");
const actions: Partial<Record<AgentmailApiError["operation"], string>> = {
request: "complete this request",
inspect_key: "verify the API key",
create_inbox: "create the email address",
create_inbox_key: "create an inbox-scoped API key",
create_webhook: "register the email webhook",
};
const action = actions[error.operation] ?? "complete this request";
let status = 422;
let code = "agentmail_request_failed";
let message: string;
const addressTaken = error.operation === "create_inbox"
&& [403, 409, 422].includes(error.status)
&& (error.providerCode === "resource_taken" || error.providerCode === "already_exists");
if (addressTaken) {
status = 409;
code = "agentmail_address_taken";
message = "This email address is already in use. Choose a different address.";
} else if (error.providerCode === "limit_exceeded") {
message = "Your AgentMail account has reached its resource limit. Free up space or increase your plan’s limit, then try again.";
} else if (error.providerCode === "domain_not_verified") {
message = "Verify this domain in AgentMail before creating an email address, or choose another domain.";
} else if (error.status === 401) {
message = "AgentMail rejected the API key. Check that it is correct and has not been revoked, then reconnect.";
} else if (error.status === 403) {
message = `AgentMail did not allow Paperclip to ${action}. Check your API key permissions and AgentMail account limits, then try again.`;
} else if (error.status === 429) {
status = 429;
res.set("Retry-After", String(Math.ceil(error.retryAfterMs / 1000)));
message = "AgentMail is rate limiting requests. Wait a moment, then try again.";
} else if ([400, 409, 422].includes(error.status) && error.operation === "create_inbox") {
message = "AgentMail could not create this email address. Try a different address and check that its domain is available in your AgentMail account.";
} else if (error.status === 404) {
message = error.operation === "create_inbox_key"
? "AgentMail could not create an access key for this inbox. The email address was saved; try finishing the connection again."
: "AgentMail could not find the requested inbox or resource. Check that it still exists and that your API key can access it.";
} else if (error.status >= 500) {
status = 502;
message = "AgentMail is temporarily unavailable. Try again in a moment.";
} else {
message = `AgentMail could not ${action}. Check your AgentMail settings, then try again.`;
}
next(new HttpError(status, message, {
code,
providerStatus: error.status,
operation: error.operation,
...(addressTaken ? { field: "username" } : {}),
}));
};
export function emailRoutes(db: Db, service: EmailChannelService) {
const router = Router();
async function manager(req: Request, companyId: string) {
@@ -45,13 +104,19 @@ export function emailRoutes(db: Db, service: EmailChannelService) {
)
throw forbidden("Missing permission: tools:manage_connections");
}
router.get("/companies/:companyId/email/connections", async (req, res) => {
const companyId = req.params.companyId as string;
await manager(req, companyId);
res.set("Cache-Control", "no-store").json(
await emailConnectionService(db).listCredentials(companyId, actor(req)),
);
});
router.post(
"/companies/:companyId/email/connections",
validate(emailConnectionSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
await manager(req, companyId);
await service.requireEnabled();
res
.status(201)
.json(
@@ -68,7 +133,6 @@ export function emailRoutes(db: Db, service: EmailChannelService) {
async (req, res) => {
const companyId = req.params.companyId as string;
await manager(req, companyId);
await service.requireEnabled();
const saved = await emailConnectionService(db).credential(
companyId,
req.params.connectionId as string,
@@ -79,6 +143,19 @@ export function emailRoutes(db: Db, service: EmailChannelService) {
.json(await service.inspect(saved.value));
},
);
router.post(
"/companies/:companyId/email/connections/:connectionId/check-address",
validate(emailAddressCheckSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
await manager(req, companyId);
const saved = await emailConnectionService(db).credential(
companyId, req.params.connectionId as string, actor(req),
);
res.set("Cache-Control", "no-store").json(await agentmailApi(saved.value)
.checkAddress(`${req.body.username}@${req.body.domain}`));
},
);
router.get("/companies/:companyId/email/inboxes", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
@@ -229,6 +306,7 @@ export function emailRoutes(db: Db, service: EmailChannelService) {
res.json(delivery);
},
);
router.use(agentmailErrorHandler);
return router;
}
export function emailWebhookRoutes(service: EmailChannelService) {
+22 -1
View File
@@ -12,6 +12,7 @@ import {
localAiLoginStartSchema,
emailEndpointSetupSchema,
emailConnectionSchema,
emailAddressCheckSchema,
emailSendSchema,
browserUseControlSchema,
browserUseSettingsSchema,
@@ -1509,8 +1510,10 @@ const BOARD_ONLY_OPERATIONS = new Set([
"POST /api/tool-gateway/action-requests/{id}/decline",
"POST /api/companies/{companyId}/email/inspect",
"POST /api/companies/{companyId}/email/inboxes",
"GET /api/companies/{companyId}/email/connections",
"POST /api/companies/{companyId}/email/connections",
"POST /api/companies/{companyId}/email/connections/{connectionId}/inspect",
"POST /api/companies/{companyId}/email/connections/{connectionId}/check-address",
"POST /api/email/inboxes/{endpointId}/control",
"POST /api/email/inboxes/{endpointId}/reconnect",
"POST /api/companies/{companyId}/email/deliveries/{publicationId}/resolve",
@@ -2131,7 +2134,25 @@ for (const [method, path, summary, body] of browserUseOperations) {
// Explicit task-bound email. Board setup and agent actions share the same vaulted
// connection, while automatic chat publication never applies to these endpoints.
registry.registerPath({
method: "post",
path: "/api/companies/{companyId}/email/connections/{connectionId}/check-address",
tags: ["Email"],
summary: "Check for an existing AgentMail address using a saved credential",
description: "Requires a board connection manager and enabled chat connectors. Read-only: does not create or reserve an inbox. A missing inbox returns unknown because AgentMail hides resources outside the credential scope; it is never proof of availability.",
request: {
params: z.object({ companyId: z.string().uuid(), connectionId: z.string().uuid() }),
body: jsonBody(emailAddressCheckSchema),
},
responses: {
200: r.ok(z.object({ address: z.string(), status: z.enum(["taken", "unknown"]) })),
400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound,
422: r.unprocessable, 429: { description: "AgentMail request limit reached; retry later" },
502: r.serverError,
},
});
for (const [method, path, summary, body, success] of [
["get", "/api/companies/{companyId}/email/connections", "List accessible saved AgentMail API keys (metadata only)", undefined, 200],
["post", "/api/companies/{companyId}/email/connections", "Save AgentMail credential and access", emailConnectionSchema, 201],
["post", "/api/companies/{companyId}/email/connections/{connectionId}/inspect", "Inspect inboxes using a saved AgentMail credential", undefined, 200],
["get", "/api/companies/{companyId}/email/inboxes", "List authorized AgentMail inboxes", undefined, 200],
@@ -2145,7 +2166,7 @@ for (const [method, path, summary, body, success] of [
["post", "/api/companies/{companyId}/email/deliveries/{publicationId}/resolve", "Resolve uncertain email after checking the provider", z.object({ outcome: z.enum(["sent", "failed"]), providerMessageId: z.string().min(1).max(998).optional() }).strict(), 200],
] as const) {
registry.registerPath({ method, path, tags: ["Email"], summary,
description: "Experimental AgentMail channel. Internal comments never send email. Agent sends require assigned inbox and task ownership, active run authority, and configured action policies. Preserve the same idempotencyKey and payload across retries. New conversations create an email child task; replies require conversationId and replyToMessageId. Reply-all is deliberate and never includes Bcc.",
description: "AgentMail email connection. Available without the experimental chat setting. Internal comments never send email. Agent sends require assigned inbox and task ownership, active run authority, and configured action policies. Preserve the same idempotencyKey and payload across retries. New conversations create an email child task; replies require conversationId and replyToMessageId. Reply-all is deliberate and never includes Bcc.",
request: { params: z.object(Object.fromEntries([...path.matchAll(/\{([^}]+)\}/g)].map(match => [match[1], z.string().uuid()]))), ...(body ? { body: jsonBody(body) } : {}) },
responses: { [success]: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
});
+13 -1
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import { Webhook } from "svix";
import type { EmailEnvelope } from "@paperclipai/shared";
import type { EmailAddressCheckResult, EmailEnvelope } from "@paperclipai/shared";
const strings = z.array(z.string());
export const agentmailMessageSchema = z.object({
@@ -284,6 +284,18 @@ export function agentmailApi(apiKey: string, fetchImpl: typeof fetch = fetch) {
request,
whoami: () => request<AgentmailScope>("/auth/me"),
getInbox: (id: string) => request<AgentmailInbox>(inboxPath(id)),
checkAddress: async (address: string): Promise<EmailAddressCheckResult> => {
// Do not GET a speculative inbox ID. Live AgentMail caches missing inbox
// lookups, so checking a free name can make key creation return 404 after
// the inbox is created. Listing avoids priming that negative lookup.
const { inboxes } = await request<{ inboxes: AgentmailInbox[] }>("/inboxes?limit=100");
// An absent entry can be outside this page or credential's scope. Only
// creation is authoritative; never claim an unlisted address is free.
return {
address,
status: inboxes.some(inbox => inbox.inbox_id.toLowerCase() === address.toLowerCase()) ? "taken" : "unknown",
};
},
listInboxes: () =>
request<{ inboxes: AgentmailInbox[] }>("/inboxes?limit=100"),
listDomains: () =>
+74 -12
View File
@@ -1,3 +1,5 @@
import { emailChannelService } from "./email-channels.js";
import { emailConnectionService } from "./email-connections.js";
import { agentService } from "./agents.js";
import { logActivity } from "./activity-log.js";
import { aiConnectionService } from "./ai-connections.js";
@@ -237,7 +239,7 @@ export function connectionIntentService(db: Db) {
agentId: string;
responsibleUserId: string;
serviceSlug: string;
purpose?: "ai";
purpose?: "ai" | "channel";
inventory?: Awaited<ReturnType<typeof connectionInventory>>;
}) {
const managed = input.purpose === "ai" ? await managedAgent(input.companyId, input.agentId, input.serviceSlug) : null;
@@ -248,6 +250,11 @@ export function connectionIntentService(db: Db) {
} catch (error) { if ([403, 404, 422].includes((error as { status?: number }).status ?? 0)) return null; throw error; }
}
if (input.purpose === "ai") return null;
if (input.purpose === "channel") {
if (input.serviceSlug !== "agentmail") return null;
const inboxes = await assignedAgentmailInboxes(db, input.companyId, input.agentId);
return inboxes[0] ? access.getConnection(inboxes[0].connectionId, input.companyId) : null;
}
const inventory = input.inventory ?? await connectionInventory(input.companyId);
const matching = inventory.connections.filter((connection) =>
sourceSlugForConnection(connection, inventory.applicationsById) === input.serviceSlug
@@ -318,11 +325,24 @@ export function connectionIntentService(db: Db) {
));
}
async function resolveService(service: string, companyId: string, userId: string, agentId: string, purpose?: "ai") {
// Readiness uses the same credential, feature and assignment checks as the
// runtime's AgentMail tools; it never starts a worker or contacts the provider.
function assignedAgentmailInboxes(database: Db, companyId: string, agentId: string) {
return emailChannelService(database, { heartbeat: { wakeup: async () => {
throw new Error("Connection discovery cannot start an email worker");
} } }).assignedInboxes(companyId, agentId);
}
async function resolveService(service: string, companyId: string, userId: string, agentId: string, purpose?: "ai" | "channel") {
if (!service.startsWith("connection:")) {
const app = getAppStoreDefinition(service);
if (!app) throw notFound("Connection service was not found");
const methods = purpose === "ai" ? getAvailableConnectionMethods(app).filter(method => method.transport === "runtime_auth") : availableToolConnectionMethods(app);
if (purpose === "channel" && service !== "agentmail") {
throw unprocessable("This email connection is not available");
}
const methods = purpose === "ai" ? getAvailableConnectionMethods(app).filter(method => method.transport === "runtime_auth")
: purpose === "channel" ? getAvailableConnectionMethods(app).filter(method => method.purpose === "channel")
: availableToolConnectionMethods(app);
return { ...app, available: app.availability?.available !== false,
searchCapabilities: methods.map((method) =>
`${method.whenToUse} ${method.capabilityProfile?.label ?? ""} ${method.capabilityProfile?.description ?? ""}`).join(" "),
@@ -364,7 +384,7 @@ export function connectionIntentService(db: Db) {
const candidates: Array<{ item: ConnectionSearchResultItem; score: number; nameScore: number }> = [];
const authorizedCatalogs = new Map<string, Awaited<ReturnType<typeof indexedCatalog>>>();
const discoveryMethods = (app: (typeof APP_STORE_DEFINITIONS)[number]) => getAvailableConnectionMethods(app)
.filter(method => method.purpose !== "channel" || settings.enableChatConnectors);
.filter(method => method.purpose !== "channel" || app.slug === "agentmail" || settings.enableChatConnectors);
const services = [...APP_STORE_DEFINITIONS.filter(app => discoveryMethods(app).length).map((app) => app.slug),
...inventory.connections.filter((connection) =>
sourceSlugForConnection(connection, inventory.applicationsById)?.startsWith("connection:")
@@ -406,7 +426,7 @@ export function connectionIntentService(db: Db) {
`${app.description ?? ""} ${app.searchCapabilities} ${catalog.map(tool => `${tool.toolName} ${tool.description ?? ""}`).join(" ")}`);
if (!score) continue;
const ready = await usableConnectionForAgent({ companyId: run.companyId, agentId: agent.id,
responsibleUserId: run.responsibleUserId!, serviceSlug: service, purpose: aiOnly ? "ai" : undefined, inventory });
responsibleUserId: run.responsibleUserId!, serviceSlug: service, purpose: aiOnly ? "ai" : service === "agentmail" ? "channel" : undefined, inventory });
const denied = !aiOnly && !ready && matching.length > 0 && await administrativeDenial(run.companyId, agent.id, service, inventory);
candidates.push({ score, nameScore, item: {
service, name: app.name, description: app.description ?? null, logoUrl: app.branding.logoUrl ?? null,
@@ -540,7 +560,7 @@ export function connectionIntentService(db: Db) {
function discoverySuggestions(results: ConnectionSearchResultItem[]): ConnectionsSearchResult {
return { version: 1, query, results: results.slice(0, 40),
instruction: "Multiple apps match this query. Choose the relevant service and method using descriptions and purposes. For available or needs_user_action results, tool methods use connection_request and channel or AI methods use setupPath. Use ready tools as installed; ready AI authentication applies to the next execution without reconnection. For an aggregator result, search its aggregator.targetService to obtain the provider-choice question and follow that instruction before requesting a connection. Respect unavailable states. Do not treat a search match as provider consent or app authorization." };
instruction: "Multiple apps match this query. Choose the relevant service and method using descriptions and purposes. For available or needs_user_action results, tool methods and AgentMail use connection_request to show the inline setup card; other channel or AI methods use setupPath. Use ready tools as installed; ready AI authentication applies to the next execution without reconnection. For an aggregator result, search its aggregator.targetService to obtain the provider-choice question and follow that instruction before requesting a connection. Respect unavailable states. Do not treat a search match as provider consent or app authorization." };
}
}
@@ -550,9 +570,13 @@ export function connectionIntentService(db: Db) {
: !suggestions && isRemoteMcpConnectorId(results[0]!.service) && results[0]!.state !== "unavailable"
? `${results[0]!.name} is an external service. When the user explicitly names this provider, disclose that it handles the connection and requests to the requested app; no additional provider-choice question is necessary. ${results[0]!.state === "ready" ? aggregatorContinuationInstruction(results[0]!.service, "The requested app") : "Call connection_request with the returned service identifier and follow its instruction. Provider setup does not yet verify underlying app access."}`
: !suggestions && results[0]!.state === "unavailable" ? "This connection is unavailable or administratively restricted. Explain the reason. Do not bypass it using another provider."
: suggestions || results.length > 1 ? "These are ranked connection matches. Choose the relevant service and method using their descriptions and purposes; extra query words need not match. For available or needs_user_action tool methods, call connection_request with the service identifier to present its setup card. For available or needs_user_action channel or AI methods, share the method's setupPath. Use ready tools as installed; ready AI authentication is available for the agent's next execution and does not need reconnection. Respect unavailable states and recorded user choices. Clarify only if the intended service is still ambiguous; unrelated matches are not evidence of support."
: suggestions || results.length > 1 ? "These are ranked connection matches. Choose the relevant service and method using their descriptions and purposes; extra query words need not match. For available or needs_user_action tool methods or AgentMail, call connection_request with the service identifier to present its setup card. For other available or needs_user_action channel or AI methods, share the method's setupPath. Use ready tools as installed; ready AI authentication is available for the agent's next execution and does not need reconnection. Respect unavailable states and recorded user choices. Clarify only if the intended service is still ambiguous; unrelated matches are not evidence of support."
: results[0]!.state === "ready" && results[0]!.methods.every(method => method.purpose === "ai")
? "AI authentication is available for this agent's next execution. Do not create another connection request or ask the user to reconnect."
: results[0]!.service === "agentmail"
? results[0]!.state === "ready"
? "An active AgentMail inbox is assigned to you. Use agentmail_inboxes to read its address. Do not request another connection."
: "Call connection_request with service agentmail to show the inline API-key card. Do not send a setup link or ask for the key in chat. The card creates an inbox for this agent; wait for completion before claiming an email address."
: results[0]!.methods.every(method => method.purpose && method.purpose !== "tool")
? "Choose the method relevant to the task using its purpose and label. Share its setupPath with the user to open the existing channel or AI setup flow. These methods do not use the tool connection_request card. Do not claim tools or an inbox are ready before setup finishes."
: results[0]!.state === "ready" ? "Use the installed connection. Do not create another connection request."
@@ -615,7 +639,7 @@ export function connectionIntentService(db: Db) {
async function request(
claims: ConnectionRunClaims,
serviceSlug: string,
options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {},
options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {},
): Promise<ConnectionRequestResult> {
const context = await loadRunContext(claims);
return requestWithContext(context, serviceSlug, options);
@@ -624,7 +648,7 @@ export function connectionIntentService(db: Db) {
async function requestWithContext(
context: Awaited<ReturnType<typeof loadRunContext>>,
serviceSlug: string,
options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {},
options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {},
): Promise<ConnectionRequestResult> {
const claims = { sub: context.agent.id, company_id: context.run.companyId, run_id: context.run.id, responsible_user_id: context.run.responsibleUserId! };
const route = parseAggregatorRoute(serviceSlug);
@@ -653,6 +677,9 @@ export function connectionIntentService(db: Db) {
upstreamService = { slug: route.targetService, name: selected.aggregator.targetName, selectionInteractionId: options.selectionInteractionId };
serviceSlug = route.provider;
}
// AgentMail has one channel method. Infer it from the server-owned catalog
// identifier instead of asking the model to invent a new tool argument.
if (serviceSlug === "agentmail" && !options.purpose) options = { ...options, purpose: "channel" };
const app = await resolveService(serviceSlug, context.run.companyId, context.run.responsibleUserId!, context.agent.id, options.purpose);
if (!app.available || app.methods.length === 0) {
throw unprocessable(`Connection service ${serviceSlug} is not available`);
@@ -671,10 +698,10 @@ export function connectionIntentService(db: Db) {
state: "ready",
connectionId: ready.id,
interactionId: null,
instruction: isRemoteMcpConnectorId(app.slug) ? aggregatorContinuationInstruction(app.slug, upstreamService?.name ?? "The requested app") : options.purpose === "ai" ? `${app.name} authentication is available for the next execution.` : `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`,
instruction: isRemoteMcpConnectorId(app.slug) ? aggregatorContinuationInstruction(app.slug, upstreamService?.name ?? "The requested app") : options.purpose === "channel" ? "An active AgentMail inbox is assigned to you. Use agentmail_inboxes to read its address; do not request another connection." : options.purpose === "ai" ? `${app.name} authentication is available for the next execution.` : `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`,
};
}
if (options.purpose !== "ai" && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) {
if (!options.purpose && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) {
throw forbidden("This agent has no permitted actions for this service. Ask an administrator to review tool permissions; reconnecting will not remove a denial.");
}
const outcomeId = context.run.contextSnapshot?.interactionId;
@@ -702,7 +729,7 @@ export function connectionIntentService(db: Db) {
sourceRunId: context.run.id,
sourceIdentityContextId: context.run.activeIdentityContextId,
addresseeUserId: context.run.responsibleUserId!,
idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? ":ai" : ""}`,
idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? `:${options.purpose}` : ""}`,
},
);
if (interaction.status !== "pending") throw conflict("This connection request has already been resolved. Follow its recorded outcome.");
@@ -738,6 +765,25 @@ export function connectionIntentService(db: Db) {
const loaded = await loadIntent(interactionId);
const payload = connectionIntentPayloadSchema.parse(loaded.interaction.payload);
const app = await resolveService(payload.serviceSlug, loaded.issue.companyId, loaded.interaction.addresseeUserId!, payload.requestingAgentId, payload.purpose);
if (payload.purpose === "channel") {
const [saved] = await db.select().from(toolConnections).where(and(
eq(toolConnections.companyId, loaded.issue.companyId),
eq(toolConnections.uid, `agentmail-account-${interactionId}`),
));
// A retry may recover only this card's account, after checking the
// addressed person's current access. No arbitrary connection is selected.
const credential = saved ? await emailConnectionService(db).get(loaded.issue.companyId, saved.id, { userId: loaded.interaction.addresseeUserId! }) : null;
const inboxes = await assignedAgentmailInboxes(db, loaded.issue.companyId, payload.requestingAgentId);
return {
version: 1, interaction: loaded.interaction,
service: { service: app.slug, name: app.name, description: app.description ?? null,
logoUrl: app.branding.logoUrl ?? null, methods: app.methods, source: app.source,
state: "needs_user_action", connectionId: null },
existingConnections: [], requestedAgentId: payload.requestingAgentId,
emailSetup: { credentialConnectionId: credential?.id ?? null,
readyConnectionId: inboxes.find(inbox => inbox.id === interactionId)?.connectionId ?? null },
};
}
let managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null;
if (payload.purpose === "ai" && !managed) {
const [source] = await db.select().from(heartbeatRuns).where(and(
@@ -873,6 +919,22 @@ export function connectionIntentService(db: Db) {
throw conflict("Finish and test this connection before using it for the task");
}
if (payload.purpose === "channel") {
if (payload.serviceSlug !== "agentmail" || !options.canManageOrganizationGrant) {
throw forbidden("AgentMail inbox setup requires connection-management authority");
}
const inboxes = await assignedAgentmailInboxes(txDb, loaded.issue.companyId, payload.requestingAgentId);
const inbox = inboxes.find(inbox => inbox.connectionId === selectedConnection.id);
if (!inbox?.address) throw conflict("Finish creating an active inbox for the requesting agent before continuing");
const credentialId = selectedConnection.config?.credentialConnectionId;
if (typeof credentialId !== "string") throw conflict("Use a saved AgentMail account for this inbox");
await emailConnectionService(txDb).get(loaded.issue.companyId, credentialId, { userId });
return txInteractions.resolveConnectionIntent(loaded.issue, interactionId, {
version: 1, outcome: "connected", connectionId: selectedConnection.id,
instruction: "Your AgentMail inbox is ready. Use agentmail_inboxes to read its verified address and continue the user's request.",
}, { userId });
}
if (selectedConnection.connectionPurpose === "channel") throw conflict("An email inbox cannot satisfy a tool connection request");
if (payload.purpose === "ai" && selectedConnection.connectionPurpose !== "ai") throw conflict("Select an AI account for this authentication request");
if (selectedConnection.connectionPurpose === "ai") {
if (payload.purpose !== "ai") throw conflict("AI authentication cannot satisfy a tool connection request");
+1 -6
View File
@@ -3,11 +3,10 @@ import type { Db } from "@paperclipai/db";
import { emailSendSchema } from "@paperclipai/shared";
import { emailChannelService } from "../email-channels.js";
import { forbidden, notFound } from "../../errors.js";
import { instanceSettingsService } from "../instance-settings.js";
const AGENTMAIL_EMAIL_CONTRACT = {
description:
"Use an assigned AgentMail inbox for this task. Internal comments and final responses never send email. List inboxes, read the current email thread, explicitly send a new email child task or reply, and inspect delivery. Requires experimental email connections. A send needs a UUID idempotencyKey; preserve it and the identical payload on retry. A reply uses conversationId and replyToMessageId from thread; replyAll defaults false and excludes Bcc. Sending does not close the task.",
"Use an assigned AgentMail inbox for this task. Internal comments and final responses never send email. List inboxes, read the current email thread, explicitly send a new email child task or reply, and inspect delivery. A send needs a UUID idempotencyKey; preserve it and the identical payload on retry. A reply uses conversationId and replyToMessageId from thread; replyAll defaults false and excludes Bcc. Sending does not close the task.",
inputSchema: {
type: "object",
properties: {
@@ -118,10 +117,6 @@ export async function executeAgentmailTool(
},
value: unknown,
) {
if (
!(await instanceSettingsService(db).getExperimental()).enableChatConnectors
)
throw forbidden("Experimental email connections are disabled");
const input = schema.parse(value);
// This facade only persists intents/reads. The app's durable email worker owns execution.
const service = emailChannelService(db, {
+1 -21
View File
@@ -129,14 +129,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
let activeTick: Promise<void> | null = null;
let timer: ReturnType<typeof setInterval> | undefined;
async function enabled() {
return (await instanceSettingsService(db).getExperimental())
.enableChatConnectors;
}
async function requireEnabled() {
if (!(await enabled()))
throw forbidden("Enable experimental chat connections first");
}
async function getEndpoint(id: string) {
const [row] = await db
.select()
@@ -620,7 +612,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
input: EmailEndpointSetupInput,
actor: EmailActor,
) {
await requireEnabled();
const [agent] = await db
.select()
.from(agents)
@@ -797,6 +788,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
input.credentialConnectionId,
agent.id,
actor,
input.idempotencyKey,
);
} else if (controlKey) await vault(endpoint, "controlKey", controlKey);
if (!controlKey) throw badRequest("AgentMail API key required");
@@ -919,7 +911,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
}
async function admit(endpoint: Endpoint, value: unknown) {
await requireEnabled();
await active(endpoint);
const event = normalizeAgentmailEvent(value);
if (!event) return;
@@ -1452,7 +1443,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
input: EmailSendInput,
actor: EmailActor,
): Promise<EmailPublicationSummary> {
await requireEnabled();
const endpoint = await getEndpoint(input.endpointId);
if (endpoint.companyId !== companyId)
throw notFound("Email inbox not found");
@@ -1647,7 +1637,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
const input = send.request;
let attempted = false;
try {
await requireEnabled();
await active(endpoint);
const sourceId = input.parentIssueId ?? pub.issueId;
await authorize(endpoint, sourceId, send.actor);
@@ -2064,11 +2053,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
if (ticking || stopped) return;
ticking = true;
try {
if (!(await enabled())) {
for (const state of sockets.values()) state.socket.close();
sockets.clear();
return;
}
const endpoints = await db
.select()
.from(chatEndpoints)
@@ -2272,7 +2256,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
if (endpoint.status === "archived")
throw conflict("This inbox is disconnected");
if (action === "resume") {
await requireEnabled();
if (!config.activationAt)
throw conflict("Complete inbox setup before resuming");
await agentmailApi(await credential(endpoint), fetchImpl).getInbox(
@@ -2368,7 +2351,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
receiveMode: "websocket" | "webhook",
actor: EmailActor,
) {
await requireEnabled();
const endpoint = await getEndpoint(id);
if (endpoint.status === "archived" || !endpoint.botExternalId)
throw conflict("Create a new inbox connection");
@@ -2591,7 +2573,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
};
}
async function assignedInboxes(companyId: string, agentId: string) {
if (!(await enabled())) return [];
const rows = await db.select().from(chatEndpoints).where(and(
eq(chatEndpoints.companyId, companyId), eq(chatEndpoints.assignedAgentId, agentId),
eq(chatEndpoints.provider, "agentmail"), eq(chatEndpoints.status, "active"),
@@ -2610,7 +2591,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
}
return {
assignedInboxes,
requireEnabled,
authorizeRead,
setup,
getEndpoint,
+80 -13
View File
@@ -8,8 +8,8 @@ import {
companySecrets,
toolConnectionInstalls,
} from "@paperclipai/db";
import type { EmailConnectionInput } from "@paperclipai/shared";
import { badRequest, forbidden, notFound } from "../errors.js";
import type { EmailConnectionInput, EmailCredentialOption } from "@paperclipai/shared";
import { badRequest, forbidden, HttpError, notFound } from "../errors.js";
import { secretService } from "./secrets.js";
import { toolAccessService } from "./tool-access.js";
import { agentmailApi } from "./agentmail-api.js";
@@ -75,6 +75,56 @@ export function emailConnectionService(
}
return connection;
}
async function listCredentials(companyId: string, actor: EmailActor): Promise<EmailCredentialOption[]> {
const connections = await db.select().from(toolConnections).where(and(
eq(toolConnections.companyId, companyId), eq(toolConnections.status, "active"),
eq(toolConnections.enabled, true),
));
const options: EmailCredentialOption[] = [];
const candidates = connections.filter(connection => connection.config.provider === "agentmail" && connection.config.emailCredential);
// New credentials already have verified scope metadata. Legacy credentials
// get a bounded discovery pass: four workers share one three-second budget.
const deadline = AbortSignal.timeout(3_000);
const discoveryFetch: typeof fetch = (input, init) => fetchImpl(input, {
...init, signal: init?.signal ? AbortSignal.any([init.signal, deadline]) : deadline,
});
let next = 0;
await Promise.all(Array.from({ length: Math.min(4, candidates.length) }, async () => {
while (next < candidates.length) {
const connection = candidates[next++];
try {
await get(companyId, connection.id, actor);
} catch (error) {
if (error instanceof HttpError && [403, 404].includes(error.status)) continue;
throw error;
}
const storedScope = connection.config.emailScope;
let scope: EmailCredentialOption["scope"] = storedScope === "organization" || storedScope === "pod" || storedScope === "inbox"
? storedScope : "unavailable";
let inboxId = typeof connection.config.emailInboxId === "string" ? connection.config.emailInboxId : null;
if (scope === "unavailable" && !deadline.aborted) {
try {
const saved = await credential(companyId, connection.id, actor);
if (!deadline.aborted) {
const identity = await agentmailApi(saved.value, discoveryFetch).whoami();
scope = identity.scope_type;
inboxId = identity.inbox_id ?? null;
}
} catch {
// Never expose a provider body, key, hash, or secret reference.
}
}
options.push({
id: connection.id, scope, inboxId, createdAt: connection.createdAt.toISOString(),
label: connection.name !== "AgentMail" ? connection.name
: scope === "inbox" ? `AgentMail inbox key${inboxId ? ` · ${inboxId}` : ""}`
: scope === "unavailable" ? "AgentMail key · unavailable" : "AgentMail account key",
});
}
}));
return options.sort((a, b) => Number(b.scope === "organization" || b.scope === "pod")
- Number(a.scope === "organization" || a.scope === "pod") || b.createdAt.localeCompare(a.createdAt));
}
async function assertAgentAccess(
companyId: string,
id: string,
@@ -126,7 +176,7 @@ export function emailConnectionService(
input: EmailConnectionInput,
actor: EmailActor,
) {
await agentmailApi(input.apiKey, fetchImpl).whoami();
const identity = await agentmailApi(input.apiKey, fetchImpl).whoami();
return db.transaction(async (tx) => {
const db = tx as unknown as Db;
await db.execute(
@@ -166,7 +216,7 @@ export function emailConnectionService(
actor,
);
const secret = await secrets.create(companyId, {
name: `AgentMail account ${randomUUID()}`,
name: `AgentMail ${identity.scope_type === "inbox" ? "inbox" : "account"} API key ${randomUUID().slice(0, 8)}`,
provider: "local_encrypted",
value: input.apiKey,
});
@@ -190,7 +240,7 @@ export function emailConnectionService(
credentialPolicy: "shared",
enabled: true,
status: "active",
config: { provider: "agentmail", emailCredential: true },
config: { provider: "agentmail", emailCredential: true, emailScope: identity.scope_type, emailInboxId: identity.inbox_id ?? null },
transportConfig: {},
credentialSecretRefs: [
{
@@ -241,6 +291,11 @@ export function emailConnectionService(
actorSource: actor.localImplicit ? "local_implicit" : "session",
},
);
const initialInstalls = await db.select({ id: toolConnectionInstalls.id })
.from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));
await db.update(toolConnections).set({
config: { ...connection.config, emailSetupInitialInstallIds: initialInstalls.map(install => install.id) },
}).where(eq(toolConnections.id, connection.id));
await logActivity(db, {
companyId,
actorType: "user",
@@ -262,6 +317,7 @@ export function emailConnectionService(
id: string,
agentId: string,
actor: EmailActor,
setupRequestId: string,
) {
return db.transaction(async (tx) => {
const db = tx as unknown as Db;
@@ -275,26 +331,37 @@ export function emailConnectionService(
),
)
.for("update");
await emailConnectionService(db, fetchImpl).get(companyId, id, actor);
const connection = await emailConnectionService(db, fetchImpl).get(companyId, id, actor);
const tools = toolAccessService(db);
const installs = await db
.select()
.from(toolConnectionInstalls)
.where(eq(toolConnectionInstalls.connectionId, id));
// Apply the setup default once, only if nobody has edited access since
// saving the key. Install IDs detect removal/re-addition as well as new
// agent/company grants. Later retries always preserve those edits.
const initialIds = connection.config.emailSetupInitialInstallIds;
const ownsInitialAccess = connection.uid === `agentmail-account-${setupRequestId}` && Array.isArray(initialIds);
const replaceInitialAccess = ownsInitialAccess && initialIds.length === installs.length
&& installs.every(install => initialIds.includes(install.id));
if (ownsInitialAccess) {
const { emailSetupInitialInstallIds: _initialIds, ...config } = connection.config;
await db.update(toolConnections).set({ config }).where(eq(toolConnections.id, id));
}
if (
installs.some(
(i) => i.targetType === "company" || i.targetId === agentId,
)
replaceInitialAccess
? installs.length === 1 && installs[0].targetType === "agent" && installs[0].targetId === agentId
: installs.some((i) => i.targetType === "company" || i.targetId === agentId)
)
return;
await tools.putConnectionInstalls(
id,
{
installs: [
...installs.map((i) => ({
...(replaceInitialAccess ? [] : installs.map((i) => ({
targetType: i.targetType,
targetId: i.targetId,
})),
}))),
{ targetType: "agent", targetId: agentId },
],
},
@@ -308,12 +375,12 @@ export function emailConnectionService(
companyId,
actorType: "user",
actorId: actor.userId ?? "board",
action: "email.connection.agent_added",
action: replaceInitialAccess ? "email.connection.agents_updated" : "email.connection.agent_added",
entityType: "tool_connection",
entityId: id,
details: { agentId },
});
});
}
return { get, credential, connect, allowAgent, assertAgentAccess };
return { get, credential, connect, listCredentials, allowAgent, assertAgentAccess };
}