diff --git a/doc/execution-github-identity.md b/doc/execution-github-identity.md
index 10786facda0..8f093f80eb6 100644
--- a/doc/execution-github-identity.md
+++ b/doc/execution-github-identity.md
@@ -192,7 +192,9 @@ a reconnect requirement.
An explicit dedicated-agent grant overrides personal selection. Revoked, disabled, unavailable, or ambiguous dedicated grants do not fall back to a person's account. Removing the dedicated configuration restores personal selection.
-Connection setup and permissions display: “This agent uses this GitHub account for everyone's work, instead of the person giving instructions.”
+A dedicated account signs in one agent. The person who connected the account, a company owner or admin, or an instance admin can share it with other agents of the company on the connection's permissions page. Each share is an audited delegation on the dedicated grant. An agent uses a shared account for managed git and for the connection's tools only through that share list: an install of the connection or an app profile binding never gives an agent the account. An agent that has its own dedicated account uses its own account first.
+
+Connection setup and permissions display: “This agent uses this GitHub account for everyone's work, instead of the person giving instructions.” The permissions page lists each agent that uses the account. A person who can share it sees “Share this account with other agents”.
The GitHub permissions page shows repositories across all connected accounts in one scrollable list. It has no account filter or repository search. Repository icons, private-repository indicators, refresh, and GitHub configuration links remain available. The “Add More Repos on GitHub” button opens GitHub’s app installation and repository-access setup.
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index dab61eb6382..076c2aba16f 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -2459,6 +2459,8 @@ export {
connectionTokenSubjectSchema,
startConnectionAuthorizationSchema,
createConnectionGrantDelegationSchema,
+ replaceDedicatedAccountAgentsSchema,
+ DEDICATED_ACCOUNT_SHARE_LIMIT,
replaceConnectionGrantMembersSchema,
toolConnectionTestCallSchema,
toolPolicyTestRequestSchema,
@@ -2551,6 +2553,7 @@ export {
type UpdateToolMcpGateway,
type ConnectionTokenRequestInput,
type CreateConnectionGrantDelegation,
+ type ReplaceDedicatedAccountAgents,
type ReplaceConnectionGrantMembersInput,
type ImportMcpJson,
type ToolPolicyTestRequestInput,
diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts
index 203dc803d73..65f9f89a79b 100644
--- a/packages/shared/src/types/tool-access.ts
+++ b/packages/shared/src/types/tool-access.ts
@@ -340,6 +340,8 @@ export interface ConnectionGrantsResponse {
capabilities: ToolConnectionCapabilities;
currentUserId: string | null;
members: ConnectionAudienceMember[];
+ dedicatedAgentIds?: string[];
+ canShareDedicatedIdentity?: boolean;
}
/** A company member that can appear in an organization grant's audience. */
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index c96d9929e41..0739d0fdc6a 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -947,6 +947,8 @@ export {
connectionTokenSubjectSchema,
startConnectionAuthorizationSchema,
createConnectionGrantDelegationSchema,
+ replaceDedicatedAccountAgentsSchema,
+ DEDICATED_ACCOUNT_SHARE_LIMIT,
replaceConnectionGrantMembersSchema,
createToolTrustRuleFromActionRequestSchema,
revokeToolTrustRuleSchema,
@@ -1039,6 +1041,7 @@ export {
type UpsertToolCatalogEntry,
type ConnectionTokenRequestInput,
type CreateConnectionGrantDelegation,
+ type ReplaceDedicatedAccountAgents,
type ReplaceConnectionGrantMembersInput,
type ToolPolicyTestRequestInput,
type CreateToolTrustRuleFromActionRequest,
diff --git a/packages/shared/src/validators/tool-access.ts b/packages/shared/src/validators/tool-access.ts
index f7ed5d9b279..29a4a25c495 100644
--- a/packages/shared/src/validators/tool-access.ts
+++ b/packages/shared/src/validators/tool-access.ts
@@ -75,6 +75,11 @@ export const createConnectionGrantDelegationSchema = z.object({
agentId: z.string().guid(),
});
export type CreateConnectionGrantDelegation = z.infer;
+export const DEDICATED_ACCOUNT_SHARE_LIMIT = 1000;
+export const replaceDedicatedAccountAgentsSchema = z.object({
+ agentIds: z.array(z.string().guid()).max(DEDICATED_ACCOUNT_SHARE_LIMIT),
+}).strict();
+export type ReplaceDedicatedAccountAgents = z.infer;
export const toolConnectionCredentialPolicySchema = z.enum(["shared", "per_user", "per_user_with_fallback", "per_agent"]);
export const toolConnectionStatusSchema = z.enum(["draft", "active", "disabled", "archived"]);
export const toolConnectionInstallTargetTypeSchema = z.enum(["company", "agent"]);
diff --git a/server/src/__tests__/agent-grant-scope.test.ts b/server/src/__tests__/agent-grant-scope.test.ts
new file mode 100644
index 00000000000..7cbcb28bb02
--- /dev/null
+++ b/server/src/__tests__/agent-grant-scope.test.ts
@@ -0,0 +1,179 @@
+import { randomUUID } from "node:crypto";
+import { and, eq } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import {
+ agents,
+ companies,
+ connectionGrantDelegations,
+ connectionGrants,
+ createDb,
+ toolAccessAuditEvents,
+ toolApplications,
+ toolConnectionInstalls,
+ toolConnections,
+ toolProfileBindings,
+ toolProfiles,
+} from "@paperclipai/db";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+import {
+ agentGrantPreference,
+ agentGrantScope,
+ createAgentGrantStore,
+ dedicatedIdentityAgentIds,
+ reauthorizeAgentGrant,
+} from "../services/tool-access/connections/agent-grant.js";
+import { toolAccessService } from "../services/tool-access.js";
+
+const support = await getEmbeddedPostgresTestSupport();
+
+(support.supported ? describe : describe.skip)("dedicated agent grant sharing", () => {
+ let database: Awaited>;
+ let db: ReturnType;
+
+ beforeAll(async () => {
+ database = await startEmbeddedPostgresTestDatabase("paperclip-agent-grant-scope-");
+ db = createDb(database.connectionString);
+ }, 30_000);
+
+ afterAll(async () => {
+ await db?.$client.end({ timeout: 1 });
+ await database?.cleanup();
+ }, 60_000);
+
+ async function seed() {
+ const companyId = randomUUID();
+ const [owner, shared, installed, bound, unpicked, former, retired] = Array.from({ length: 7 }, () => randomUUID());
+ const applicationId = randomUUID();
+ const connectionId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: companyId, issuePrefix: companyId.slice(0, 8) });
+ await db.insert(agents).values([owner, shared, installed, bound, unpicked, former, retired].map((id) => ({
+ id, companyId, name: id, role: "engineer", adapterType: "codex_local", status: id === retired ? "terminated" : "idle",
+ })));
+ await db.insert(toolApplications).values({ id: applicationId, companyId, name: applicationId, type: "mcp_http" });
+ await db.insert(toolConnections).values({
+ id: connectionId, companyId, applicationId, name: connectionId, uid: connectionId,
+ transport: "mcp_remote", status: "active", enabled: true, credentialPolicy: "per_agent",
+ config: { sourceTemplateKey: "github" },
+ });
+ const [revoked] = await db.insert(connectionGrants).values({
+ companyId, connectionId, kind: "agent", subjectAgentId: former, status: "revoked", credentialSecretRefs: [],
+ }).returning();
+ const [active] = await db.insert(connectionGrants).values({
+ companyId, connectionId, kind: "agent", subjectAgentId: owner, status: "active", credentialSecretRefs: [],
+ createdByUserId: "user-owner",
+ }).returning();
+ await db.insert(toolConnectionInstalls).values([owner, installed].map((targetId) => ({
+ companyId, connectionId, targetType: "agent" as const, targetId,
+ })));
+ const [profile] = await db.insert(toolProfiles).values({
+ companyId, profileKey: `app:${connectionId}`, name: `app ${connectionId}`,
+ }).returning();
+ await db.insert(toolProfileBindings).values({ companyId, profileId: profile!.id, targetType: "agent", targetId: bound });
+ await db.insert(connectionGrantDelegations).values({ companyId, grantId: active!.id, agentId: shared, createdByUserId: "user-owner" });
+ return { companyId, connectionId, owner, shared, installed, bound, unpicked, former, retired, active: active!, revoked: revoked! };
+ }
+
+ async function grantFor(input: Awaited>, agentId: string, activeOnly = true) {
+ const rows = await db.select().from(connectionGrants).where(and(
+ eq(connectionGrants.companyId, input.companyId),
+ eq(connectionGrants.connectionId, input.connectionId),
+ eq(connectionGrants.kind, "agent"),
+ activeOnly ? eq(connectionGrants.status, "active") : undefined,
+ agentGrantScope(db, agentId),
+ )).orderBy(...agentGrantPreference(agentId)).limit(1);
+ return rows[0]?.id ?? null;
+ }
+
+ it("serves the signed-in agent and agents it is shared with, never an agent picked only by install or access", async () => {
+ const input = await seed();
+ expect(await grantFor(input, input.owner)).toBe(input.active.id);
+ expect(await grantFor(input, input.shared)).toBe(input.active.id);
+ expect(await grantFor(input, input.installed)).toBeNull();
+ expect(await grantFor(input, input.bound)).toBeNull();
+ expect(await grantFor(input, input.unpicked)).toBeNull();
+ });
+
+ it("keeps a former agent on its own revoked grant and off the live one", async () => {
+ const input = await seed();
+ expect(await grantFor(input, input.former, false)).toBe(input.revoked.id);
+ expect(await grantFor(input, input.former)).toBeNull();
+ });
+
+ it("lists the signed-in agent and the shared agents of the live dedicated grant", () => {
+ const grants = [
+ { kind: "agent" as const, status: "active" as const, subjectAgentId: "owner", delegations: [{ agentId: "shared" }] },
+ { kind: "agent" as const, status: "revoked" as const, subjectAgentId: "former", delegations: [{ agentId: "old-share" }] },
+ ];
+ expect(dedicatedIdentityAgentIds({ credentialPolicy: "per_agent" }, grants)).toEqual(["owner", "shared"]);
+ expect(dedicatedIdentityAgentIds({ credentialPolicy: "per_user" }, grants)).toEqual([]);
+ });
+
+ it("keeps the share list when the dedicated account is revoked, so shared agents ask to reconnect", async () => {
+ const input = await seed();
+ await toolAccessService(db).revokeConnectionGrant(input.connectionId, input.active.id, { actorType: "user", actorId: "user-owner" });
+ const shares = await db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, input.active.id));
+ expect(shares.map((row) => row.agentId)).toEqual([input.shared]);
+ expect(await grantFor(input, input.shared)).toBeNull();
+ expect(await grantFor(input, input.shared, false)).toBe(input.active.id);
+ });
+
+ it("clears the share list when a reconnect brings a different account or a different authorizer", async () => {
+ const input = await seed();
+ const shares = () => db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, input.active.id));
+ await db.update(connectionGrants).set({ providerTenant: { externalId: "github-1" } }).where(eq(connectionGrants.id, input.active.id));
+ const grant = input.active;
+ expect(await reauthorizeAgentGrant(db, grant, { authorizingUserId: "user-owner", externalId: "github-1" }))
+ .toEqual({ createdByUserId: "user-owner" });
+ expect(await shares()).toHaveLength(1);
+ expect(await reauthorizeAgentGrant(db, grant, { authorizingUserId: "user-owner", externalId: "github-2" }))
+ .toEqual({ createdByUserId: "user-owner" });
+ expect(await shares()).toHaveLength(0);
+ await db.insert(connectionGrantDelegations).values({ companyId: input.companyId, grantId: input.active.id, agentId: input.shared, createdByUserId: "user-owner" });
+ expect(await reauthorizeAgentGrant(db, grant, { authorizingUserId: "user-other" })).toEqual({ createdByUserId: "user-other" });
+ expect(await shares()).toHaveLength(0);
+ expect(await reauthorizeAgentGrant(db, { ...grant, kind: "user" }, { authorizingUserId: "user-other" })).toEqual({});
+ });
+
+ it("checks share permission against the locked grant, so a share made before a reconnect cannot land after it", async () => {
+ const input = await seed();
+ await db.update(connectionGrants).set({ createdByUserId: "user-new" }).where(eq(connectionGrants.id, input.active.id));
+ const seen: Array = [];
+ await expect(createAgentGrantStore(db).replaceSharedAgents({
+ companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id, agentIds: [input.installed],
+ actorUserId: "user-owner",
+ mayShare: (grant) => { seen.push(grant.createdByUserId); return grant.createdByUserId === "user-owner"; },
+ })).rejects.toMatchObject({ status: 403 });
+ expect(seen).toEqual(["user-new"]);
+ const shares = await db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, input.active.id));
+ expect(shares.map((row) => row.agentId)).toEqual([input.shared]);
+ });
+
+ it("replaces the share list with active agents of the company and records an audit event", async () => {
+ const input = await seed();
+ const store = createAgentGrantStore(db);
+ const replaced = await store.replaceSharedAgents({
+ companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id,
+ agentIds: [input.installed, input.owner, input.installed], actorUserId: "user-admin", mayShare: () => true,
+ });
+ expect(replaced.map((row) => row.agentId)).toEqual([input.installed]);
+ expect(await grantFor(input, input.installed)).toBe(input.active.id);
+ expect(await grantFor(input, input.shared)).toBeNull();
+ const [audit] = await db.select().from(toolAccessAuditEvents).where(and(
+ eq(toolAccessAuditEvents.connectionId, input.connectionId),
+ eq(toolAccessAuditEvents.action, "connection_grant.shared_agents_replaced"),
+ ));
+ expect(audit?.details).toMatchObject({ addedAgentIds: [input.installed], removedAgentIds: [input.shared] });
+
+ for (const agentIds of [[input.retired], [randomUUID()]]) {
+ await expect(store.replaceSharedAgents({
+ companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id, agentIds, actorUserId: "user-admin", mayShare: () => true,
+ })).rejects.toMatchObject({ status: 422 });
+ }
+ await expect(store.replaceSharedAgents({
+ companyId: input.companyId, connectionId: input.connectionId, grantId: input.revoked.id, agentIds: [], actorUserId: "user-admin", mayShare: () => true,
+ })).rejects.toMatchObject({ status: 409 });
+ expect((await store.replaceSharedAgents({
+ companyId: input.companyId, connectionId: input.connectionId, grantId: input.active.id, agentIds: [], actorUserId: "user-admin", mayShare: () => true,
+ }))).toEqual([]);
+ });
+});
diff --git a/server/src/__tests__/dedicated-account-sharing-routes.test.ts b/server/src/__tests__/dedicated-account-sharing-routes.test.ts
new file mode 100644
index 00000000000..848cfa92d7d
--- /dev/null
+++ b/server/src/__tests__/dedicated-account-sharing-routes.test.ts
@@ -0,0 +1,146 @@
+import { randomUUID } from "node:crypto";
+import express from "express";
+import request from "supertest";
+import { eq } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import {
+ agents,
+ companies,
+ companyMemberships,
+ connectionGrantDelegations,
+ connectionGrants,
+ createDb,
+ principalPermissionGrants,
+ toolApplications,
+ toolConnections,
+} from "@paperclipai/db";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+import { DEDICATED_ACCOUNT_SHARE_LIMIT, replaceDedicatedAccountAgentsSchema } from "@paperclipai/shared";
+import { toolAccessRoutes } from "../routes/tool-access.js";
+import { createAgentGrantStore } from "../services/tool-access/connections/agent-grant.js";
+import { errorHandler } from "../middleware/index.js";
+
+const support = await getEmbeddedPostgresTestSupport();
+
+(support.supported ? describe : describe.skip)("sharing a dedicated account with other agents", () => {
+ let database: Awaited>;
+ let db: ReturnType;
+
+ beforeAll(async () => {
+ database = await startEmbeddedPostgresTestDatabase("paperclip-dedicated-account-sharing-");
+ db = createDb(database.connectionString, { maxConnections: 4 });
+ }, 30_000);
+
+ afterAll(async () => {
+ await db?.$client.end({ timeout: 1 });
+ await database?.cleanup();
+ }, 60_000);
+
+ const roles = { connector: "operator", admin: "admin", operator: "operator", member: "member" } as const;
+
+ async function seed() {
+ const companyId = randomUUID();
+ const [subject, shared] = [randomUUID(), randomUUID()];
+ const applicationId = randomUUID();
+ const connectionId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: companyId, issuePrefix: companyId.slice(0, 8) });
+ await db.insert(companyMemberships).values(Object.entries(roles).map(([userId, membershipRole]) => ({
+ companyId, principalType: "user", principalId: `${companyId}-${userId}`, status: "active", membershipRole,
+ })));
+ await db.insert(principalPermissionGrants).values({
+ companyId, principalType: "user", principalId: `${companyId}-operator`, permissionKey: "tools:manage_connections",
+ scope: null, grantedByUserId: `${companyId}-admin`,
+ });
+ await db.insert(agents).values([subject, shared].map((id) => ({
+ id, companyId, name: id, role: "engineer", adapterType: "codex_local",
+ })));
+ await db.insert(toolApplications).values({ id: applicationId, companyId, name: applicationId, type: "mcp_http" });
+ await db.insert(toolConnections).values({
+ id: connectionId, companyId, applicationId, name: connectionId, uid: connectionId,
+ transport: "mcp_remote", status: "active", enabled: true, credentialPolicy: "per_agent",
+ config: { sourceTemplateKey: "github" }, createdByUserId: `${companyId}-connector`,
+ });
+ const [grant] = await db.insert(connectionGrants).values({
+ companyId, connectionId, kind: "agent", subjectAgentId: subject, status: "active", credentialSecretRefs: [],
+ createdByUserId: `${companyId}-connector`,
+ }).returning();
+ return { companyId, connectionId, grantId: grant!.id, subject, shared };
+ }
+
+ function app(companyId: string, user: keyof typeof roles) {
+ const server = express();
+ server.use(express.json());
+ server.use((req, _res, next) => {
+ req.actor = {
+ type: "board", userId: `${companyId}-${user}`, sessionId: `session-${randomUUID()}`, userName: user, userEmail: null,
+ isInstanceAdmin: false, source: "session", companyIds: [companyId],
+ memberships: [{ companyId, membershipRole: roles[user], status: "active" }],
+ };
+ next();
+ });
+ server.use("/api", toolAccessRoutes(db, {}));
+ server.use(errorHandler);
+ return server;
+ }
+
+ const share = (input: Awaited>, user: keyof typeof roles, agentIds: string[]) =>
+ request(app(input.companyId, user))
+ .put(`/api/tool-connections/${input.connectionId}/grants/${input.grantId}/shared-agents`)
+ .send({ agentIds });
+
+ const sharedWith = async (grantId: string) =>
+ (await db.select().from(connectionGrantDelegations).where(eq(connectionGrantDelegations.grantId, grantId))).map((row) => row.agentId);
+
+ it("lets only the person who connected the account or a company admin share it", async () => {
+ const input = await seed();
+ for (const user of ["operator", "member"] as const) {
+ const refused = await share(input, user, [input.shared]);
+ expect(refused.status).toBe(403);
+ }
+ expect((await share(input, "operator", [input.shared])).body.error)
+ .toBe("Only the person who connected this account or a company admin can share it with other agents");
+ expect(await sharedWith(input.grantId)).toEqual([]);
+
+ const byConnector = await share(input, "connector", [input.shared]);
+ expect(byConnector.status).toBe(200);
+ expect(byConnector.body).toEqual({ grantId: input.grantId, agentIds: [input.shared] });
+ expect(await sharedWith(input.grantId)).toEqual([input.shared]);
+
+ expect(replaceDedicatedAccountAgentsSchema.safeParse({ agentIds: Array.from({ length: DEDICATED_ACCOUNT_SHARE_LIMIT }, () => randomUUID()) }).success).toBe(true);
+ expect(replaceDedicatedAccountAgentsSchema.safeParse({ agentIds: Array.from({ length: DEDICATED_ACCOUNT_SHARE_LIMIT + 1 }, () => randomUUID()) }).success).toBe(false);
+ const byAdmin = await share(input, "admin", []);
+ expect(byAdmin.status).toBe(200);
+ expect(await sharedWith(input.grantId)).toEqual([]);
+ });
+
+ it("tells the page who uses the account and whether this person can share it", async () => {
+ const input = await seed();
+ await share(input, "connector", [input.shared]);
+ const forConnector = await request(app(input.companyId, "connector")).get(`/api/tool-connections/${input.connectionId}/grants`);
+ expect(forConnector.status).toBe(200);
+ expect(new Set(forConnector.body.dedicatedAgentIds)).toEqual(new Set([input.subject, input.shared]));
+ expect(forConnector.body.canShareDedicatedIdentity).toBe(true);
+ const forOperator = await request(app(input.companyId, "operator")).get(`/api/tool-connections/${input.connectionId}/grants`);
+ expect(forOperator.body.canShareDedicatedIdentity).toBe(false);
+ });
+
+ it("moves share authority to the person who reconnects the account and clears the old shares", async () => {
+ const input = await seed();
+ await share(input, "connector", [input.shared]);
+ const store = createAgentGrantStore(db);
+ await store.upsertConnectAgentGrant({
+ companyId: input.companyId, connectionId: input.connectionId, subjectAgentId: input.subject,
+ credentialSecretRefs: [], actor: { actorType: "user", actorId: `${input.companyId}-connector` },
+ });
+ expect(await sharedWith(input.grantId)).toEqual([input.shared]);
+
+ await store.upsertConnectAgentGrant({
+ companyId: input.companyId, connectionId: input.connectionId, subjectAgentId: input.subject,
+ credentialSecretRefs: [], actor: { actorType: "user", actorId: `${input.companyId}-operator` },
+ });
+ expect(await sharedWith(input.grantId)).toEqual([]);
+ expect((await share(input, "connector", [input.shared])).status).toBe(403);
+ expect((await share(input, "operator", [input.shared])).status).toBe(200);
+ expect(await sharedWith(input.grantId)).toEqual([input.shared]);
+ });
+});
diff --git a/server/src/__tests__/github-operation-credentials.test.ts b/server/src/__tests__/github-operation-credentials.test.ts
index 75eeeacfcb5..786679645d1 100644
--- a/server/src/__tests__/github-operation-credentials.test.ts
+++ b/server/src/__tests__/github-operation-credentials.test.ts
@@ -15,6 +15,7 @@ import {
companies,
companyMemberships,
companySecrets,
+ connectionGrantDelegations,
connectionGrants,
createDb,
heartbeatRuns,
@@ -25,6 +26,8 @@ import {
toolApplications,
toolConnectionInstalls,
toolConnections,
+ toolProfileBindings,
+ toolProfiles,
userSecretDefinitions,
} from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared";
@@ -560,6 +563,50 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
env: {},
});
});
+ it("lends a dedicated account only to the agents it is shared with, never to an agent picked by install or access", async () => {
+ const input = await seed();
+ const personal = await grant(input, "A");
+ const robot = await grant(input, "robot", true);
+ const [shared, installed, bound, former] = [randomUUID(), randomUUID(), randomUUID(), randomUUID()];
+ await db.insert(agents).values([shared, installed, bound, former].map((id) => ({
+ id, companyId: input.companyId, name: id, role: "engineer", adapterType: "codex_local",
+ })));
+ await db.insert(toolConnectionInstalls).values([shared, installed, bound].map((targetId) => ({
+ companyId: input.companyId, connectionId: personal.connectionId, targetType: "agent" as const, targetId,
+ })));
+ await db.insert(toolConnectionInstalls).values({
+ companyId: input.companyId, connectionId: robot.connectionId, targetType: "agent", targetId: installed,
+ });
+ const [profile] = await db.insert(toolProfiles).values({
+ companyId: input.companyId, profileKey: `app:${robot.connectionId}`, name: `app ${robot.connectionId}`,
+ }).returning();
+ await db.insert(toolProfileBindings).values({
+ companyId: input.companyId, profileId: profile!.id, targetType: "agent", targetId: bound,
+ });
+ const [robotGrant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, robot.id));
+ const [formerGrant] = await db.insert(connectionGrants).values({
+ companyId: input.companyId, connectionId: robot.connectionId, kind: "agent", subjectAgentId: former,
+ status: "revoked", credentialSecretRefs: robotGrant!.credentialSecretRefs,
+ providerTenant: { ...robotGrant!.providerTenant, github: { ...robotGrant!.providerTenant!.github!, userId: "former-robot", login: "former-robot" } },
+ }).returning();
+ await db.insert(connectionGrantDelegations).values([robot.id, formerGrant!.id].map((grantId) => ({
+ companyId: input.companyId, grantId, agentId: shared, createdByUserId: "A",
+ })));
+ expect(await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId: shared, responsibleUserId: "A" }))
+ .toMatchObject({ configured: true, identitySource: "dedicated", grant: { id: robot.id } });
+ for (const agentId of [installed, bound]) {
+ expect(await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId, responsibleUserId: "A" }))
+ .toMatchObject({ configured: true, identitySource: "personal", grant: { id: personal.id } });
+ }
+ await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, robot.id));
+ const revoked = await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId: shared, responsibleUserId: "A" });
+ expect(revoked).toMatchObject({ configured: true, identitySource: "dedicated" });
+ expect(revoked.grant).toBeUndefined();
+ await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.id, robot.id));
+ const own = await grant({ ...input, agentId: shared }, "shared-robot", true);
+ expect(await resolveManagedGitHubIdentitySelection(db, input.companyId, { agentId: shared, responsibleUserId: "A" }))
+ .toMatchObject({ identitySource: "dedicated", grant: { id: own.id } });
+ });
it("does not resolve the company default person's GitHub", async () => {
const input = await seed();
await grant(input, "A");
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index ed5dfab97f2..3d135aac28d 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -315,6 +315,7 @@ import {
testMachineSignInSchema,
rotateMachineSignInSchema,
configureRailwaySshSchema,
+ replaceDedicatedAccountAgentsSchema,
createToolApplicationSchema,
updateToolApplicationSchema,
createToolConnectionSchema,
@@ -12936,6 +12937,25 @@ registerCurrentRoute({
summary: "Replace the member audience of a tool connection grant",
});
+registerCurrentRoute({
+ "x-paperclip-transport": "rest",
+ "x-paperclip-connection-management": "connections:configure",
+ method: "put",
+ path: "/api/tool-connections/{connectionId}/grants/{grantId}/shared-agents",
+ tags: ["tool-access"],
+ summary: "Replace the agents that share a dedicated account",
+ body: replaceDedicatedAccountAgentsSchema,
+ responses: {
+ 200: r.ok(),
+ 400: r.badRequest,
+ 401: r.unauthorized,
+ 403: r.forbidden,
+ 404: r.notFound,
+ 409: r.conflict,
+ 422: r.unprocessable,
+ },
+});
+
registerCurrentRoute({
"x-paperclip-transport": "rest",
"x-paperclip-connection-management": "connections:configure",
diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts
index 34406aceea3..b0dba41b372 100644
--- a/server/src/routes/tool-access.ts
+++ b/server/src/routes/tool-access.ts
@@ -31,6 +31,7 @@ import {
type MachineSignInStatus,
configureRailwaySshSchema,
createConnectionGrantDelegationSchema,
+ replaceDedicatedAccountAgentsSchema,
createToolStdioCommandTemplateSchema,
createToolApplicationSchema,
createToolConnectionSchema,
@@ -108,6 +109,7 @@ import { trustedBoardMutationOrigin } from "../middleware/board-mutation-guard.j
import { connectionIntentService } from "../services/connection-intents.js";
import { redactRemoteUrlCredential } from "../services/remote-url-credentials.js";
import { connectionIntentDeliveryService } from "../services/connection-intent-delivery.js";
+import { createAgentGrantStore, dedicatedIdentityAgentIds } from "../services/tool-access/connections/agent-grant.js";
import type { heartbeatService } from "../services/heartbeat.js";
const COMPANY_INSTALL_DENIAL_REASON =
@@ -654,6 +656,16 @@ function connectorEnrollmentPrincipal(req: Request): string {
return membership;
}
+ function canShareDedicatedAccount(req: Request, companyId: string, grant: { createdByUserId?: string | null }) {
+ if (req.actor.type !== "board") return false;
+ if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true;
+ const membership = req.actor.memberships?.find((item) => item.companyId === companyId);
+ if (membership?.status !== "active") return false;
+ const userId = connectionRequestUserId(req);
+ return Boolean(userId && grant.createdByUserId === userId)
+ || ["owner", "admin"].includes(String(membership.membershipRole));
+ }
+
async function isToolConnectionManager(req: Request, companyId: string) {
assertBoardOrAgent(req);
assertCompanyAccess(req, companyId);
@@ -2067,6 +2079,9 @@ function connectorEnrollmentPrincipal(req: Request): string {
members: capabilities.canConfigure
? await svc.listConnectionAudienceMembers(connection.companyId)
: [],
+ dedicatedAgentIds: dedicatedIdentityAgentIds(connection, listed.grants),
+ canShareDedicatedIdentity: listed.grants.some((grant) => grant.kind === "agent" && grant.status === "active"
+ && canShareDedicatedAccount(req, connection.companyId, grant)),
});
});
@@ -2179,6 +2194,36 @@ function connectorEnrollmentPrincipal(req: Request): string {
res.status(201).json(delegation);
});
+ router.put("/tool-connections/:connectionId/grants/:grantId/shared-agents", managementGuard("connections:configure", "PUT /tool-connections/:connectionId/grants/:grantId/shared-agents"), validate(replaceDedicatedAccountAgentsSchema), async (req, res) => {
+ assertBoard(req);
+ const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
+ if (!connection) return;
+ const { grants } = await svc.listConnectionGrants(connection.id, connection.companyId);
+ const grant = grants.find((candidate) => candidate.id === req.params.grantId && candidate.kind === "agent");
+ if (!grant) throw notFound("Dedicated account not found");
+ if (!canShareDedicatedAccount(req, connection.companyId, grant)) {
+ throw forbidden("Only the person who connected this account or a company admin can share it with other agents");
+ }
+ const delegations = await createAgentGrantStore(db).replaceSharedAgents({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ grantId: grant.id,
+ agentIds: req.body.agentIds,
+ actorUserId: connectionRequestUserId(req)!,
+ actor: connectionRequestActor(req),
+ mayShare: (locked) => canShareDedicatedAccount(req, connection.companyId, locked),
+ });
+ await logActivity(db, {
+ companyId: connection.companyId,
+ ...connectionRequestActor(req),
+ action: "tool_connection.dedicated_account_shared",
+ entityType: "connection_grant",
+ entityId: grant.id,
+ details: { connectionId: connection.id, agentIds: delegations.map((row) => row.agentId) },
+ });
+ res.json({ grantId: grant.id, agentIds: delegations.map((row) => row.agentId) });
+ });
+
router.delete("/tool-connections/:connectionId/grants/:grantId/delegations/:delegationId", managementGuard("connections:profiles", "DELETE /tool-connections/:connectionId/grants/:grantId/delegations/:delegationId", { personal: true }), async (req, res) => {
assertBoardOrAgent(req);
const connection = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
diff --git a/server/src/services/git-credentials.ts b/server/src/services/git-credentials.ts
index fed5e00d6fa..b17d8ff2c8f 100644
--- a/server/src/services/git-credentials.ts
+++ b/server/src/services/git-credentials.ts
@@ -14,6 +14,7 @@ import { and, eq, inArray, or, sql } from "drizzle-orm";
import { isGitHubDotCom } from "./github-fetch.js";
import { secretService } from "./secrets.js";
import { toolAccessService } from "./tool-access.js";
+import { sharedAgentGrantIds } from "./tool-access/connections/agent-grant.js";
/**
* Server-side git credentials for managed project checkouts and execution-workspace base
@@ -392,12 +393,18 @@ export async function resolveManagedGitHubIdentitySelection(
eq(toolConnectionInstalls.companyId, companyId),
inArray(toolConnectionInstalls.connectionId, connectionIds),
));
- const eligibleConnectionIds = new Set(githubConnections.filter((connection) => installs.some((install) =>
- install.connectionId === connection.id && (
- (install.targetType === "company" && install.targetId === companyId)
- || (install.targetType === "agent" && install.targetId === context.agentId)
- )
- )).map((connection) => connection.id));
+ const sharedGrants = context.agentId
+ ? await sharedAgentGrantIds(db, companyId, context.agentId, githubConnections
+ .filter((connection) => connection.credentialPolicy === "per_agent").map((connection) => connection.id))
+ : new Map();
+ const sharedConnectionIds = new Set(sharedGrants.values());
+ const eligibleConnectionIds = new Set(githubConnections.filter((connection) => sharedConnectionIds.has(connection.id)
+ || installs.some((install) =>
+ install.connectionId === connection.id && (
+ (install.targetType === "company" && install.targetId === companyId)
+ || (install.targetType === "agent" && install.targetId === context.agentId)
+ )
+ )).map((connection) => connection.id));
// A GitHub connection installed only for another agent is not configured for
// this run. Treating the company-wide connection as configured here would
// make unrelated agents fail before their adapter starts and would also
@@ -409,9 +416,16 @@ export async function resolveManagedGitHubIdentitySelection(
context.explicitGrantId ? eq(connectionGrants.id, context.explicitGrantId) : undefined,
or(eq(connectionGrants.kind, "agent"), eq(connectionGrants.kind, "user")),
));
- const dedicated = context.agentId
+ const ownDedicated = context.agentId
? grants.filter((grant) => grant.kind === "agent" && grant.subjectAgentId === context.agentId)
: [];
+ const sharedDedicated = ownDedicated.length > 0 || !context.agentId
+ ? []
+ : grants.filter((grant) => grant.kind === "agent" && sharedGrants.has(grant.id));
+ const liveSharedDedicated = sharedDedicated.filter((grant) => grant.status === "active");
+ const dedicated = ownDedicated.length > 0
+ ? ownDedicated
+ : liveSharedDedicated.length > 0 ? liveSharedDedicated : sharedDedicated;
// Connections are already restricted above to the owner-selected install
// targets. Within that consent boundary the server-resolved responsible user
// is authoritative; standing delegation is only an ownerless-run fallback.
diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts
index 5cd52c6656b..77704e9e257 100644
--- a/server/src/services/tool-access.ts
+++ b/server/src/services/tool-access.ts
@@ -33,7 +33,7 @@ import { toApplication } from "./tool-access/applications/projection.js";
import { groupedActions } from "./tool-access/catalog/action-summary.js";
import { createConnectionSetupPolicy, assertSupportedConnection } from "./tool-access/connections/setup-policy.js";
import { createOrganizationGrantStore } from "./tool-access/connections/organization-grant.js";
-import { createAgentGrantStore } from "./tool-access/connections/agent-grant.js";
+import { createAgentGrantStore, reauthorizeAgentGrant } from "./tool-access/connections/agent-grant.js";
import { createPersonalConnectionIdentity } from "./tool-access/connections/personal-identity.js";
import { createOAuthStateStore } from "./tool-access/oauth/state.js";
import { createOAuthCatalogCompletion } from "./tool-access/oauth/catalog-completion.js";
@@ -4039,9 +4039,10 @@ export function toolAccessService(
}
}
if (agentGrant) {
+ const authorizer = await reauthorizeAgentGrant(tx, agentGrant, { authorizingUserId: connectionActorUserId(actor) });
await tx
.update(connectionGrants)
- .set({ credentialSecretRefs, updatedAt })
+ .set({ credentialSecretRefs, updatedAt, ...authorizer })
.where(eq(connectionGrants.id, agentGrant.id));
}
const [nextConnection] = await tx
diff --git a/server/src/services/tool-access/connections/agent-grant.ts b/server/src/services/tool-access/connections/agent-grant.ts
index 67e6262a824..7fb16fd67e3 100644
--- a/server/src/services/tool-access/connections/agent-grant.ts
+++ b/server/src/services/tool-access/connections/agent-grant.ts
@@ -1,15 +1,84 @@
-import { and, eq } from "drizzle-orm";
+import { and, desc, eq, exists, inArray, ne, or, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
-import { connectionGrants, toolAccessAuditEvents, toolConnections } from "@paperclipai/db";
+import { agents, connectionGrantDelegations, connectionGrants, toolAccessAuditEvents, toolConnections } from "@paperclipai/db";
import type { CreateToolConnection } from "@paperclipai/shared";
-import { conflict } from "../../../errors.js";
+import { conflict, forbidden, notFound, unprocessable } from "../../../errors.js";
import { connectionActorUserId } from "../actor.js";
import type { ActorInfo } from "../types.js";
type ConnectionGrant = typeof connectionGrants.$inferSelect;
+export function agentGrantScope(db: Pick, agentId: string): SQL {
+ return or(
+ eq(connectionGrants.subjectAgentId, agentId),
+ exists(db.select({ id: connectionGrantDelegations.id }).from(connectionGrantDelegations).where(and(
+ eq(connectionGrantDelegations.companyId, connectionGrants.companyId),
+ eq(connectionGrantDelegations.grantId, connectionGrants.id),
+ eq(connectionGrantDelegations.agentId, agentId),
+ ))),
+ )!;
+}
+
+export function agentGrantPreference(agentId: string): SQL[] {
+ return [desc(eq(connectionGrants.status, "active")), desc(eq(connectionGrants.subjectAgentId, agentId))];
+}
+
+export async function sharedAgentGrantIds(
+ db: Pick,
+ companyId: string,
+ agentId: string,
+ connectionIds: string[],
+): Promise
- Used only by {agentName}. This dedicated connection takes precedence over the responsible person's GitHub.
+ {sharedIdentity
+ ? `Shared by the agents picked for ${dedicatedIdentity.connection.name}.`
+ : `Used only by ${agentName}.`} This dedicated connection takes precedence over the responsible person's GitHub.
This agent uses this GitHub account for everyone’s work, instead of the person giving instructions.
+
+ {identityAgents.length > 1
+ ? "These agents use this GitHub account for everyone’s work, instead of the person giving instructions."
+ : "This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."}
+