From 725a9e36b6818a2f728f12857e85ea6f064b0a7f Mon Sep 17 00:00:00 2001
From: Devin Foley
Date: Tue, 1 Dec 2026 22:40:42 -0800
Subject: [PATCH] fix(connections): let a dedicated account serve every agent
picked for its connection (#23431)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A GitHub connection can use "A dedicated account for an agent", for
example a bot account that an agent uses instead of the person who gives
instructions
> - The account lives on the grant of the agent that signed in. Core
gives one connection to one signed-in agent
> - A team often wants several agents to use the same bot account, or to
move a bot account to a new agent. Today each agent needs its own GitHub
sign-in as the bot
> - The permissions page also lets an owner pick more agents for the
connection, which looks like sharing but gives those agents nothing
> - Sharing a credential must stay under the owner's control: an install
of a connection needs only `agents:configure`, which agents and
operators have, so installs cannot be the share signal
> - This pull request adds an explicit share list for a dedicated
account. Only the person who connected the account, a company owner or
admin, or an instance admin can change it
> - The benefit is that a bot account can serve several agents without a
new sign-in, and no one else can attach the account to their agents
## Linked Issues or Issue Description
No public issue exists.
**What happened?**
A GitHub connection with a dedicated account was signed in for agent A.
The owner then picked agent B for the same connection on the permissions
page. The page showed "Used only by A" and also "2 agents selected" with
A and B. Agent B made no GitHub tool calls through the connection, and
its git work used the responsible person's GitHub account. There was no
way to let agent B use the bot account without a second GitHub sign-in
as the bot.
**Expected behavior**
The owner of a dedicated account can share it with chosen agents, and
those agents use it for managed git and the connection's tools. No one
else can share it.
**Steps to reproduce**
1. Add a GitHub connection with "A dedicated account for an agent" and
pick agent A.
2. On the connection's permissions page, pick agent B too.
3. Start a run for agent B that pushes with git. See that it uses the
responsible person's account, and that the page offers no way to share
the bot account.
**Paperclip version or commit**
`master` at fcb8fc5deb7.
**Deployment mode**
Any deployment with a GitHub connection that uses a dedicated agent
account.
## What Changed
- `agent-grant.ts`:
- `agentGrantScope`: a dedicated grant serves its signed-in agent, or an
agent with a share row (a `connection_grant_delegations` row on the
agent grant). Installs and app profile bindings do not count.
- `replaceSharedAgents`: replaces the share list in one transaction, and
checks share permission again on the locked grant row, so a share
request cannot land after another person's reconnect. It accepts only
active agents of the company, skips the signed-in agent, refuses an
inactive grant, and records a `connection_grant.shared_agents_replaced`
audit event.
- `sharedAgentGrantIds` and `dedicatedIdentityAgentIds` read the share
list.
- New route `PUT
/tool-connections/:connectionId/grants/:grantId/shared-agents` with
`replaceDedicatedAccountAgentsSchema` (at most
`DEDICATED_ACCOUNT_SHARE_LIMIT`, 1000 agents, the same as a grant's
member audience; the picker does not send a larger selection and says
why). Only a board user can call it, and only when the user connected
the account, is a company owner or admin, or is an instance admin.
Agents and other operators get 403.
- The credential access, tool gateway and token broker lookups for a
per-agent connection use `agentGrantScope`.
- `git-credentials.ts`: managed git identity uses the share list. An
agent that has its own dedicated account uses its own account first.
Live shared grants come before revoked ones, and a run still asks for a
reconnect when no live grant remains.
- The grants endpoint returns `dedicatedAgentIds` (the signed-in agent
and the shared agents) and `canShareDedicatedIdentity` for the viewer.
- Existing delegation lookups match only personal grants, so a share
never acts as a personal delegation.
- Every path that replaces a dedicated grant's credential (the connect
upsert, the cloud connector callback and the credential reconnect) calls
`reauthorizeAgentGrant`. It locks and rereads the grant, records the new
authorizer as the grant's `createdByUserId`, and clears the share list
when the authorizer or the provider account changes. So only the person
behind the current credential, or an admin, can share it.
- `revokeConnectionGrant` keeps the share rows of a dedicated agent
grant, so a revoked account asks shared agents to reconnect instead of
switching them to a person's account. A reconnect reactivates the same
grant with its shares.
- Permissions page: the GitHub identity card lists each agent that uses
the account and, for a person who can share it, shows "Share this
account with other agents". The sharing state lives in the new
`useDedicatedAccountSharing` hook.
- Agent Tools tab: uses `dedicatedAgentIds`, so a shared agent shows the
shared account.
- `doc/execution-github-identity.md`: describes the share list and who
can change it.
## Verification
- `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter
@paperclipai/ui typecheck` pass.
- `server/src/__tests__/agent-grant-scope.test.ts` (7 tests, including a
reconnect that clears shares and a share request whose permission is
checked against the locked, already-reconnected grant): the signed-in
and shared agents get the grant; installed, bound and unpicked agents do
not; a former agent keeps only its own revoked grant; the share list
accepts only active company agents, skips the signed-in agent, refuses
an inactive grant and records an audit event.
- `server/src/__tests__/dedicated-account-sharing-routes.test.ts` (3
tests): an operator with `tools:manage_connections` and a member get
403; after another person reconnects the account, the shares are cleared
and only that person (or an admin) can share; the person who connected
the account and an admin can replace the list; the grants endpoint
reports the agents and the viewer's permission.
- `github-operation-credentials.test.ts`: a shared agent uses the
dedicated account; installed and bound agents use the person's account;
an agent's own dedicated account comes first; a revoked grant for
another account does not make the identity ambiguous. 27 tests pass.
- `agent-grant-scope.test.ts` also checks that a revoke keeps the share
list (fails without the change), and
`github-operation-credentials.test.ts` checks that a shared agent gets a
reconnect error, not the person's account, after a revoke.
- UI: `DedicatedIdentity.test.tsx` (4 tests, including the sharing
picker with 800 agents and 20 unchanged rerenders under a fixed read
budget), `dedicated-github-identity.test.ts` (3 tests) and
`useDedicatedIdentityAgents.test.ts` (2 tests, 800 agents behind a read
counter).
- I ran the 92 server test files that mention per-agent connections,
agent grants, dedicated accounts or delegations: 81 files and 6852 tests
pass, including `openapi-routes.test.ts` with the new route in the spec.
The other 11 files are integration tests that skip without their test
database. I also ran 34 UI test files for the apps pages, the Tools tab
and replay masking: 457 tests pass.
- `tests/runner-e2e/source-sdk-public-inputs.json` is regenerated with
`source-sdk-public-inputs.mjs --write`, because the change touches
pinned `packages/shared` files.
## Risks
- No schema change: the share list reuses
`connection_grant_delegations`.
- Agents keep their current identity after this change. An agent uses a
shared account only after an owner or admin shares it.
- A connection manager who is not an admin can still remove a share
through the existing delegation delete route. That only reduces access.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, read-only database queries on a hosted instance for
the diagnosis).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip
---
doc/execution-github-identity.md | 4 +-
packages/shared/src/index.ts | 3 +
packages/shared/src/types/tool-access.ts | 2 +
packages/shared/src/validators/index.ts | 3 +
packages/shared/src/validators/tool-access.ts | 5 +
.../src/__tests__/agent-grant-scope.test.ts | 179 ++++++++++++++++++
.../dedicated-account-sharing-routes.test.ts | 146 ++++++++++++++
.../github-operation-credentials.test.ts | 47 +++++
server/src/routes/openapi.ts | 20 ++
server/src/routes/tool-access.ts | 45 +++++
server/src/services/git-credentials.ts | 28 ++-
server/src/services/tool-access.ts | 5 +-
.../tool-access/connections/agent-grant.ts | 159 +++++++++++++++-
.../tool-access/connections/grants.ts | 4 +-
.../services/tool-access/credential-access.ts | 3 +-
.../tool-access/oauth/cloud-callback.ts | 4 +-
.../tool-access/token-broker/service.ts | 4 +-
server/src/services/tool-gateway.ts | 4 +-
.../runner-e2e/source-sdk-public-inputs.json | 8 +-
ui/src/api/tools.ts | 5 +
.../hooks/useDedicatedIdentityAgents.test.ts | 57 ++++++
ui/src/hooks/useDedicatedIdentityAgents.ts | 46 +++++
ui/src/lib/dedicated-github-identity.test.ts | 33 ++++
ui/src/lib/dedicated-github-identity.ts | 14 ++
ui/src/pages/AgentToolsTab.tsx | 17 +-
ui/src/pages/apps/AppDetail.tsx | 6 +
.../app-detail/DedicatedIdentity.test.tsx | 119 ++++++++++++
.../apps/app-detail/IdentitiesSection.tsx | 75 +++++++-
28 files changed, 1004 insertions(+), 41 deletions(-)
create mode 100644 server/src/__tests__/agent-grant-scope.test.ts
create mode 100644 server/src/__tests__/dedicated-account-sharing-routes.test.ts
create mode 100644 ui/src/hooks/useDedicatedIdentityAgents.test.ts
create mode 100644 ui/src/hooks/useDedicatedIdentityAgents.ts
create mode 100644 ui/src/lib/dedicated-github-identity.test.ts
create mode 100644 ui/src/lib/dedicated-github-identity.ts
create mode 100644 ui/src/pages/apps/app-detail/DedicatedIdentity.test.tsx
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."}
+