diff --git a/doc/agent-permission-defaults.md b/doc/agent-permission-defaults.md index f9fad7be056..b53dbe8a15d 100644 --- a/doc/agent-permission-defaults.md +++ b/doc/agent-permission-defaults.md @@ -19,7 +19,9 @@ This document describes the server defaults for an ordinary, standard trust agen ## Not granted by default -These permission keys have no blanket grant for new standard agents: `agents:create` (the flag above is separate), `environments:manage`, `tools:admin`, `users:invite`, `users:manage_permissions`, and `joins:approve`. Existing agents keep their current permissions. The defaults above apply when a new standard agent is created or a pending new hire is activated. Some actions have separate bounded paths; the absence of a grant row does not describe every route decision. +These permission keys have no blanket grant for new standard agents: `agents:create` (the flag above is separate), `environments:manage`, `tools:admin`, `users:invite`, `users:manage_permissions`, `tasks:retry`, and `joins:approve`. Existing agents keep their current permissions. The defaults above apply when a new standard agent is created or a pending new hire is activated. Some actions have separate bounded paths; the absence of a grant row does not describe every route decision. + +`tasks:retry` lets one agent press a task's Retry (`POST /api/issues/{id}/retry`) for the board user who granted it. Only a grant saved by a board user without a scope counts. The agent's own key scope, trust boundary and company policy still apply. The Retry runs with that person's authority and gates, so the agent can press it only where the person could. Chat tasks stay with their conversation owner. Each agent can request at most 3 Retries per task in a rolling day, and each request is logged as `issue.retry_requested_by_agent` with the agent and the granting user. The new direct grants do not grant company administration, user permission management, blanket tool administration, or cross-company access. The responsible user's permissions, route checks, and the normal approval gates still apply. diff --git a/docs/api/issues.md b/docs/api/issues.md index bab03cc0776..3e0e03c9f06 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -208,7 +208,7 @@ POST /api/issues/{issueId}/release Releases your ownership of the task. -## Retry a Stopped Task (Board) +## Retry a Stopped Task (Board, or an Agent with a Retry Grant) ``` POST /api/issues/{issueId}/retry @@ -226,6 +226,14 @@ Saves a Retry request for the task's latest stopped run. The same `idempotencyKe Every answer includes `presentation`, the task's current interruption state. +An agent can call this endpoint only when a board user granted it `tasks:retry` without a scope. A grant that an agent saved, or a grant with a scope, does not count. The agent's call must: + +- come from one of the agent's own runs in the company (`X-Paperclip-Run-Id` for an agent API key). Another run gives `403`. +- use an unscoped key. A skill-test or task-bridge key gives `403`. +- be on a task that the agent itself can read and that its own trust limits and company policy let it change. Only the rule about the task's assignee does not apply. + +The Retry then runs as the user who granted it, with that user's access and Retry checks. Chat tasks give `403`. Each agent can save at most 3 Retry requests on one task in a rolling day. A replay of the same `idempotencyKey` counts once. The fourth request gives `429` with `details.code: "agent_task_retry_cap_reached"`. Each request is logged as `issue.retry_requested_by_agent`, with the agent, its run and the granting user. + ## Check Now ``` diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index 3f1500b7050..6204293794b 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -1205,6 +1205,7 @@ export const PERMISSION_KEYS = [ "tasks:assign", "tasks:assign_scope", "tasks:manage_active_checkouts", + "tasks:retry", "joins:approve", ] as const; export type PermissionKey = (typeof PERMISSION_KEYS)[number]; diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts index f562c0a16e9..508e7124061 100644 --- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts +++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts @@ -172,6 +172,7 @@ const mockObserveCrossIssueInfluence = vi.hoisted(() => vi.fn(async () => null)) const mockRetryWorkspaceExport = vi.hoisted(() => vi.fn()); const mockRequestWorkspaceRecovery = vi.hoisted(() => vi.fn()); const mockRequestTaskRetry = vi.hoisted(() => vi.fn()); +const mockAgentTaskRetryActor = vi.hoisted(() => vi.fn()); const mockOnboardingFirstTaskDependenciesAllowed = vi.hoisted(() => vi.fn(async () => undefined)); const mockGetExperimental = vi.hoisted(() => vi.fn()); const mockResumeWorkspaceFinalization = vi.hoisted(() => vi.fn()); @@ -185,6 +186,8 @@ function registerRouteMocks() { }) }; }); vi.doMock("../services/task-retry.js", () => ({ requestTaskRetry: mockRequestTaskRetry })); + vi.doMock("../services/agent-task-retry.js", () => ({ agentOwnsRun: async () => true, + agentTaskRetryActor: mockAgentTaskRetryActor, recordAgentTaskRetry: async () => undefined })); vi.doMock("../services/onboarding-first-task-admission.js", async () => ({ ...await vi.importActual("../services/onboarding-first-task-admission.js"), assertOnboardingFirstTaskDependenciesAllowed: mockOnboardingFirstTaskDependenciesAllowed, @@ -542,6 +545,7 @@ describe("agent issue mutation checkout ownership", () => { mockChatRunRetries.prepareFailedChatRunRetry.mockReset(); mockChatRunRetries.processFailedChatRunRetry.mockReset(); mockRequestTaskRetry.mockReset().mockResolvedValue({ requestId: recoveryActionId, accepted: true, stale: false }); + mockAgentTaskRetryActor.mockReset().mockResolvedValue(null); mockGetExperimental.mockReset().mockResolvedValue({ enableAgentChat: true }); mockAccessService.canUser.mockReset(); mockAccessService.decide.mockReset(); @@ -918,7 +922,7 @@ describe("agent issue mutation checkout ownership", () => { it("admits ordinary Retry only for a board actor with task mutation permission", async () => { const body = { idempotencyKey: recoveryActionId, observedRunId: ownerRunId }; const deniedAgent = await request(createApp(peerActor())).post(`/api/issues/${issueId}/retry`).send(body); - expect(deniedAgent.status).toBe(403); + expect(deniedAgent.status, JSON.stringify(deniedAgent.body)).toBe(403); expect(mockRequestTaskRetry).not.toHaveBeenCalled(); mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({ allowed: input.action !== "issue:mutate", action: input.action, reason: "test_gate", explanation: "Task is read-only.", @@ -934,6 +938,21 @@ describe("agent issue mutation checkout ownership", () => { })); }); + it("keeps a granted agent's own write boundary on Retry", async () => { + mockAgentTaskRetryActor.mockResolvedValue({ ...boardActor(), source: "board_key", + memberships: [{ companyId, membershipRole: "owner", status: "active" }] }); + mockAccessService.decide.mockImplementation(async (input: { action: string; actor: { type: string } }) => + input.actor.type === "agent" && input.action === "issue:mutate" + ? { allowed: false, action: input.action, reason: "deny_low_trust_boundary", explanation: "Issue is outside this low-trust boundary." } + : { allowed: true, action: input.action, reason: "allow_test", explanation: "Allowed." }); + const body = { idempotencyKey: recoveryActionId, observedRunId: ownerRunId }; + + const denied = await request(createApp(peerActor())).post(`/api/issues/${issueId}/retry`).send(body); + + expect(denied.status, JSON.stringify(denied.body)).toBe(403); + expect(mockRequestTaskRetry).not.toHaveBeenCalled(); + }); + it("rejects client-selected workspace strategy and certifications on ordinary Retry", async () => { const response = await request(createApp(boardActor())).post(`/api/issues/${issueId}/retry`).send({ idempotencyKey: recoveryActionId, observedRunId: ownerRunId, diff --git a/server/src/__tests__/issue-scheduled-retry-routes.test.ts b/server/src/__tests__/issue-scheduled-retry-routes.test.ts index 274acc9be1e..de3d4117ab5 100644 --- a/server/src/__tests__/issue-scheduled-retry-routes.test.ts +++ b/server/src/__tests__/issue-scheduled-retry-routes.test.ts @@ -17,6 +17,7 @@ import { activityLog, agents, agentWakeupRequests, + authUsers, companies, companyMemberships, createDb, @@ -28,11 +29,14 @@ import { issueRelations, issueTreeHolds, issues, + principalPermissionGrants, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; +import { createLocalAgentJwt } from "../agent-auth-jwt.js"; +import { actorMiddleware } from "../middleware/auth.js"; import { errorHandler } from "../middleware/index.js"; import { issueRoutes } from "../routes/issues.js"; import { runningProcesses } from "../adapters/index.js"; @@ -75,8 +79,10 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => { await db.delete(heartbeatRunEvents); await db.delete(heartbeatRuns); await db.delete(agentWakeupRequests); + await db.delete(principalPermissionGrants); await db.delete(agents); await db.delete(companyMemberships); + await db.delete(authUsers); await db.delete(companies); }); @@ -114,6 +120,7 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => { agentId, companyId, runId: randomUUID(), + keyScope: { kind: "standard" }, source: "agent_jwt", }; } @@ -994,6 +1001,327 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => { }); }); + describe("agent Retry with a board user's tasks:retry grant", () => { + async function grant(f: { companyId: string; agentId: string }, grantedByUserId: string | null, + scope: Record | null = null) { + await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "agent", + principalId: f.agentId, permissionKey: "tasks:retry", grantedByUserId, scope }); + } + function retry(f: { companyId: string; agentId: string; issueId: string; sourceRunId: string; retryRunId: string }, + opts: { runId?: string; idempotencyKey?: string; actor?: Partial } = {}) { + return request(createApp({ ...agentActor(f.companyId, f.agentId), runId: opts.runId ?? f.sourceRunId, ...opts.actor } as Express.Request["actor"])) + .post(`/api/issues/${f.issueId}/retry`) + .send({ idempotencyKey: opts.idempotencyKey ?? randomUUID(), observedRunId: f.retryRunId }); + } + async function retryRunStatus(f: { retryRunId: string }) { + return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId)).then(rows => rows[0]!.status); + } + + it("refuses an agent without the grant", async () => { + const f = await seedIssueWithRetry(); + const res = await retry(f); + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("refuses a grant that no board user saved", async () => { + const f = await seedIssueWithRetry(); + await grant(f, null); + const res = await retry(f); + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("presses Retry as the granting person and logs the agent and the person", async () => { + const f = await seedIssueWithRetry(); + await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") }) + .where(eq(heartbeatRuns.id, f.retryRunId)); + await grant(f, "board-user"); + + const res = await retry(f); + + expect(res.status, JSON.stringify(res.body)).toBe(202); + expect(res.body).toMatchObject({ accepted: true, scheduledRetry: { outcome: "promoted" } }); + expect(await retryRunStatus(f)).toBe("queued"); + const events = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId), + eq(activityLog.action, "issue.retry_requested_by_agent"))); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ actorType: "agent", actorId: f.agentId, agentId: f.agentId, + runId: f.sourceRunId, details: { grantedByUserId: "board-user" } }); + }); + + it("admits a granted agent authenticated through actorMiddleware with normalized standard keyScope", async () => { + vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "agent-task-retry-jwt-test-secret"); + vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default"); + try { + const f = await seedIssueWithRetry(); + const now = new Date("2026-05-06T18:00:00.000Z"); + await db.insert(authUsers).values({ + id: "board-user", + name: "Board User", + email: "board-user@example.com", + emailVerified: true, + createdAt: now, + updatedAt: now, + }); + await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") }) + .where(eq(heartbeatRuns.id, f.retryRunId)); + await grant(f, "board-user"); + + const token = createLocalAgentJwt(f.agentId, f.companyId, "codex_local", f.sourceRunId, "board-user"); + expect(token).not.toBeNull(); + const app = express(); + app.use(express.json()); + app.use(actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null })); + app.use("/api", issueRoutes(db, {} as any)); + app.use(errorHandler); + + const res = await request(app) + .post(`/api/issues/${f.issueId}/retry`) + .set("Authorization", `Bearer ${token!}`) + .send({ idempotencyKey: randomUUID(), observedRunId: f.retryRunId }); + + expect(res.status, JSON.stringify(res.body)).toBe(202); + expect(res.body).toMatchObject({ accepted: true, scheduledRetry: { outcome: "promoted" } }); + expect(await retryRunStatus(f)).toBe("queued"); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("enforces the agent's responsible-user write ceiling when acting on behalf of a viewer", async () => { + const f = await seedIssueWithRetry(); + const now = new Date("2026-05-06T18:00:00.000Z"); + await db.insert(authUsers).values({ + id: "viewer-user", + name: "Viewer User", + email: "viewer-user@example.com", + emailVerified: true, + createdAt: now, + updatedAt: now, + }); + await db.insert(companyMemberships).values({ + companyId: f.companyId, + principalType: "user", + principalId: "viewer-user", + status: "active", + membershipRole: "viewer", + }); + await grant(f, "board-user"); + + const res = await retry(f, { + actor: { + onBehalfOfUserId: "viewer-user", + onBehalfOfMemberships: [{ companyId: f.companyId, membershipRole: "viewer", status: "active" }], + }, + }); + + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(res.body).toMatchObject({ details: { code: "RESPONSIBLE_USER_UNAUTHORIZED" } }); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("preserves pause gates when a granted agent presses Retry on a paused assignee", async () => { + const f = await seedIssueWithRetry({ agentStatus: "paused" }); + await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") }) + .where(eq(heartbeatRuns.id, f.retryRunId)); + await grant(f, "board-user"); + + const res = await retry(f); + + expect(res.status, JSON.stringify(res.body)).toBe(202); + expect(res.body).toMatchObject({ + accepted: true, + scheduledRetry: { outcome: "gate_suppressed" }, + }); + const [run] = await db.select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode }) + .from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId)); + expect(run).toEqual({ status: "cancelled", errorCode: "agent_not_invokable" }); + }); + + it("applies the granting person's gates", async () => { + const f = await seedIssueWithRetry(); + await db.update(issues).set({ visibility: "private", createdByUserId: "task-owner", responsibleUserId: "task-owner" }) + .where(eq(issues.id, f.issueId)); + await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: "other-member", + status: "active", membershipRole: "member" }); + await grant(f, "other-member"); + + const res = await retry(f); + + expect([403, 404], JSON.stringify(res.body)).toContain(res.status); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("fails closed when the grant is revoked or the granting member is no longer active", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user"); + await db.update(companyMemberships).set({ status: "suspended" }).where(and( + eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "board-user"))); + + const suspendedRes = await retry(f); + expect(suspendedRes.status, JSON.stringify(suspendedRes.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + + await db.update(companyMemberships).set({ status: "active" }).where(and( + eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "board-user"))); + await db.delete(principalPermissionGrants).where(and( + eq(principalPermissionGrants.companyId, f.companyId), + eq(principalPermissionGrants.principalId, f.agentId), + eq(principalPermissionGrants.permissionKey, "tasks:retry"))); + + const revokedRes = await retry(f); + expect(revokedRes.status, JSON.stringify(revokedRes.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("fails closed with 404 for a cross-company task even with a grant in the agent's own company", async () => { + const f = await seedIssueWithRetry(); + const other = await seedIssueWithRetry(); + await grant(f, "board-user"); + + const res = await request(createApp({ ...agentActor(f.companyId, f.agentId), runId: f.sourceRunId })) + .post(`/api/issues/${other.issueId}/retry`) + .send({ idempotencyKey: randomUUID(), observedRunId: other.retryRunId }); + + expect(res.status, JSON.stringify(res.body)).toBe(404); + expect(await retryRunStatus(other)).toBe("scheduled_retry"); + }); + + it("refuses chat tasks even when the agent holds a tasks:retry grant", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user"); + await db.update(issues).set({ + conversationAgentId: f.agentId, + conversationUserId: "board-user", + conversationState: "waiting", + }).where(eq(issues.id, f.issueId)); + + const res = await retry(f); + + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("caps an agent's Retries on one task per day", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user"); + for (let i = 0; i < 3; i += 1) expect((await retry(f)).status).not.toBe(429); + + const res = await retry(f); + + expect(res.status, JSON.stringify(res.body)).toBe(429); + expect(res.body).toMatchObject({ details: { code: "agent_task_retry_cap_reached" } }); + }); + + it("counts a replayed request once toward the cap", async () => { + const f = await seedIssueWithRetry(); + await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") }) + .where(eq(heartbeatRuns.id, f.retryRunId)); + await grant(f, "board-user"); + const idempotencyKey = randomUUID(); + for (let i = 0; i < 4; i += 1) expect((await retry(f, { idempotencyKey })).status).toBe(202); + + const events = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId), + eq(activityLog.action, "issue.retry_requested_by_agent"))); + expect(events).toHaveLength(1); + }); + + it("does not let an old unsaved idempotency key from yesterday bypass today's daily cap", async () => { + const f = await seedIssueWithRetry(); + await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") }) + .where(eq(heartbeatRuns.id, f.retryRunId)); + await grant(f, "board-user"); + const oldUnsavedKey = randomUUID(); + await db.insert(activityLog).values({ + companyId: f.companyId, + actorType: "agent", + actorId: f.agentId, + agentId: f.agentId, + runId: f.sourceRunId, + action: "issue.retry_requested_by_agent", + entityType: "issue", + entityId: f.issueId, + details: { grantedByUserId: "board-user", idempotencyKey: oldUnsavedKey }, + createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), + }); + + for (let i = 0; i < 3; i += 1) expect((await retry(f)).status).not.toBe(429); + + const res = await retry(f, { idempotencyKey: oldUnsavedKey }); + + expect(res.status, JSON.stringify(res.body)).toBe(429); + expect(res.body).toMatchObject({ details: { code: "agent_task_retry_cap_reached" } }); + }); + + it("deduplicates overlapping calls with the same idempotencyKey within the current 24h window", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user"); + const duplicateKey = randomUUID(); + await db.insert(activityLog).values({ + companyId: f.companyId, + actorType: "agent", + actorId: f.agentId, + agentId: f.agentId, + runId: f.sourceRunId, + action: "issue.retry_requested_by_agent", + entityType: "issue", + entityId: f.issueId, + details: { grantedByUserId: "board-user", idempotencyKey: duplicateKey }, + }); + + for (let i = 0; i < 4; i += 1) expect((await retry(f, { idempotencyKey: duplicateKey })).status).not.toBe(429); + + const events = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId), + eq(activityLog.action, "issue.retry_requested_by_agent"))); + expect(events).toHaveLength(1); + }); + + it("refuses a run id that is not the agent's own run", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user"); + + const res = await retry(f, { runId: randomUUID() }); + + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("refuses a grant saved with a scope", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user", { projectIds: [randomUUID()] }); + + const res = await retry(f); + + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("keeps a low-trust agent within its own task boundary", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user"); + await db.update(agents).set({ permissions: { trustPreset: "low_trust_review", authorizationPolicy: { + trustBoundary: { mode: "low_trust_review", companyId: f.companyId, rootIssueId: randomUUID() } } } }) + .where(eq(agents.id, f.agentId)); + + const res = await retry(f); + + expect([403, 404], JSON.stringify(res.body)).toContain(res.status); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + + it("keeps a scoped key within its own limits", async () => { + const f = await seedIssueWithRetry(); + await grant(f, "board-user"); + + const res = await retry(f, { actor: { source: "agent_key", keyId: randomUUID(), + keyScope: { kind: "skill_test", issueId: randomUUID() } } as Partial }); + + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(await retryRunStatus(f)).toBe("scheduled_retry"); + }); + }); + it("requires board access for retry-now", async () => { const { companyId, agentId, issueId } = await seedIssueWithRetry(); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 4763566c656..16879efbc7b 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -10103,11 +10103,46 @@ export function issueRoutes( }); router.post("/issues/:id/retry", validate(taskRetrySchema), async (req, res) => { + // An agent holding a board user's tasks:retry grant presses Retry as that + // person, so the person's gates apply, within a per-task daily cap. + let agentRetry: { companyId: string; agentId: string; runId: string } | null = null; + if (req.actor.type === "agent" && req.actor.agentId && req.actor.companyId) { + const { agentOwnsRun, agentTaskRetryActor } = await import("../services/agent-task-retry.js"); + const grantor = await agentTaskRetryActor(db, { companyId: req.actor.companyId, agentId: req.actor.agentId, + runId: req.actor.runId }); + if (grantor) { + // The agent's own limits apply first: scoped keys never use the grant, + // the run must be the agent's, and the agent's own issue:read and + // issue:mutate checks (trust boundary, company policy, interaction + // rules, and responsible-user ceiling) must pass. The grant lifts only + // the board-only gate and task-assignee ownership rule. + if (req.actor.keyScope && req.actor.keyScope.kind !== "standard") + throw forbidden("Scoped credentials cannot use the Retry grant"); + const runId = requireAgentRunId(req, res); + if (!runId) return; + if (!(await agentOwnsRun(db, { companyId: req.actor.companyId, agentId: req.actor.agentId, runId }))) + throw forbidden("Run does not belong to this agent"); + const own = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Issue not found"); + if (!own || !(await assertIssueReadAllowed(req, res, own))) return; + const ownWrite = await decideIssueAccess(req, own, "issue:mutate"); + if (!ownWrite.allowed) + throw forbidden(ownWrite.explanation, authorizationDeniedDetails(ownWrite)); + agentRetry = { companyId: req.actor.companyId, agentId: req.actor.agentId, runId }; + req.actor = grantor; + } + } assertBoard(req); const issue = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Issue not found"); if (!issue || !(await assertIssueReadAllowed(req, res, issue))) return; + if (agentRetry && issue.companyId !== agentRetry.companyId) throw notFound("Issue not found"); const decision = await decideIssueAccess(req, issue, "issue:mutate"); if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision)); + if (agentRetry) { + if (issue.conversationAgentId) throw forbidden("Only the conversation owner can retry a chat run"); + const { recordAgentTaskRetry } = await import("../services/agent-task-retry.js"); + await recordAgentTaskRetry(db, { issueId: issue.id, ...agentRetry, grantedByUserId: req.actor.userId!, + idempotencyKey: req.body.idempotencyKey }); + } if (issue.conversationAgentId) { if (!req.actor.userId || req.actor.userId !== issue.conversationUserId) throw forbidden("Only the conversation owner can retry a chat run"); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 649ac809a12..684211fd227 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -1517,7 +1517,6 @@ const BOARD_ONLY_OPERATIONS = new Set([ // Cancelling a question is board-only (routes/issues.ts rejects agent actors). Withdraw is not listed here: its // route admits the card's creator agent and the task's assignee, so agents withdraw their own pending card there. "POST /api/issues/{id}/interactions/{interactionId}/cancel", - "POST /api/issues/{id}/retry", "GET /api/companies/{companyId}/prompt-injection-prevention", "PUT /api/companies/{companyId}/prompt-injection-prevention", "GET /api/companies/{companyId}/prompt-injection-prevention/models", @@ -11957,7 +11956,7 @@ registerCurrentRoute({ tags: ["issues"], summary: "Request one durable task retry from current input and preserved results", body: taskRetrySchema, - responses: { 200: r.ok(), 202: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict }, + responses: { 200: r.ok(), 202: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 429: r.tooManyRequests }, }); registerCurrentRoute({ diff --git a/server/src/services/agent-task-retry.ts b/server/src/services/agent-task-retry.ts new file mode 100644 index 00000000000..6e8a4ed530f --- /dev/null +++ b/server/src/services/agent-task-retry.ts @@ -0,0 +1,89 @@ +import { and, count, eq, gt, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { isUuidLike } from "@paperclipai/shared"; +import { activityLog, agentWakeupRequests, companyMemberships, heartbeatRuns, principalPermissionGrants } from "@paperclipai/db"; +import { HttpError } from "../errors.js"; +import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; + +/** Retries one granted agent may request on one task in a rolling day. */ +export const AGENT_TASK_RETRY_DAILY_CAP = 3; +export const AGENT_TASK_RETRY_ACTION = "issue.retry_requested_by_agent"; + +/** + * The board actor an agent presses Retry as: the active member whose + * tasks:retry grant names this agent. Only a grant a board user saved counts; + * a grant row written by an agent has no granting user. A grant saved with a + * scope does not count, since the Retry runs with the person's full task + * access and could reach outside that scope. The actor covers only + * the agent's company, so every Retry gate the person meets applies unchanged. + */ +export async function agentTaskRetryActor(db: Db, agent: { companyId: string; agentId: string; runId?: string }) { + const [grantor] = await db.select({ userId: companyMemberships.principalId, membershipRole: companyMemberships.membershipRole }) + .from(principalPermissionGrants) + .innerJoin(companyMemberships, and(eq(companyMemberships.companyId, principalPermissionGrants.companyId), + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.principalId, principalPermissionGrants.grantedByUserId), + eq(companyMemberships.status, "active"))) + .where(and( + eq(principalPermissionGrants.companyId, agent.companyId), + eq(principalPermissionGrants.principalType, "agent"), + eq(principalPermissionGrants.principalId, agent.agentId), + eq(principalPermissionGrants.permissionKey, "tasks:retry"), + sql`coalesce(${principalPermissionGrants.scope}, '{}'::jsonb) = '{}'::jsonb`)) + .limit(1); + if (!grantor) return null; + return { + type: "board", userId: grantor.userId, companyIds: [agent.companyId], isInstanceAdmin: false, + memberships: [{ companyId: agent.companyId, membershipRole: grantor.membershipRole, status: "active" }], + source: "board_key", runId: agent.runId, + } satisfies Express.Request["actor"]; +} + +/** Whether the run id the agent sent names one of its own runs in its company. */ +export async function agentOwnsRun(db: Db, input: { companyId: string; agentId: string; runId: string }) { + if (!isUuidLike(input.runId)) return false; + const [run] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, input.runId), + eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId))); + return Boolean(run); +} + +/** + * Count an agent's Retry toward its daily cap on the task. The activity row + * names the agent and the grantor, and is written before the Retry so refused + * and failed attempts count too. A replay of an idempotency key that already + * has a saved Retry receipt for this task and grantor, or was already counted + * for this agent within the current 24-hour window, counts once; an old + * unsaved attempt from outside the window cannot bypass today's cap. + */ +export async function recordAgentTaskRetry(db: Db, input: { + companyId: string; issueId: string; agentId: string; runId: string; grantedByUserId: string; idempotencyKey: string; +}) { + const publications: ActivityPublication[] = []; + await db.transaction(async tx => { + await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${`agent-task-retry:${input.issueId}`}))`); + const [savedReceipt] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, input.companyId), + eq(agentWakeupRequests.idempotencyKey, `task-retry:${input.idempotencyKey}`), + eq(agentWakeupRequests.requestedByActorId, input.grantedByUserId), + sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`)).limit(1); + if (savedReceipt) return; + const [recentReplay] = await tx.select({ id: activityLog.id }).from(activityLog).where(and( + eq(activityLog.companyId, input.companyId), eq(activityLog.entityType, "issue"), + eq(activityLog.entityId, input.issueId), eq(activityLog.action, AGENT_TASK_RETRY_ACTION), + eq(activityLog.actorId, input.agentId), gt(activityLog.createdAt, sql`now() - interval '1 day'`), + sql`${activityLog.details}->>'idempotencyKey' = ${input.idempotencyKey}`)).limit(1); + if (recentReplay) return; + const [{ value: recent }] = await tx.select({ value: count() }).from(activityLog).where(and( + eq(activityLog.companyId, input.companyId), eq(activityLog.entityType, "issue"), + eq(activityLog.entityId, input.issueId), eq(activityLog.action, AGENT_TASK_RETRY_ACTION), + eq(activityLog.actorId, input.agentId), gt(activityLog.createdAt, sql`now() - interval '1 day'`))); + if (recent >= AGENT_TASK_RETRY_DAILY_CAP) + throw new HttpError(429, `An agent can request at most ${AGENT_TASK_RETRY_DAILY_CAP} Retries on a task per day`, + { code: "agent_task_retry_cap_reached" }); + await logActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "agent", actorId: input.agentId, + agentId: input.agentId, runId: input.runId, action: AGENT_TASK_RETRY_ACTION, entityType: "issue", + entityId: input.issueId, details: { grantedByUserId: input.grantedByUserId, idempotencyKey: input.idempotencyKey } }, + publications); + }); + for (const publication of publications) publishActivity(publication); +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 48cf8d9b0db..7748303d873 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -237,7 +237,7 @@ "packages/shared/src/connector-availability.ts": "7797798bc989b774e8b6e62748ad689f66ab4193", "packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a", "packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955", - "packages/shared/src/constants.ts": "3f1500b70505cd586f5430ad1acb1851bf053fb1", + "packages/shared/src/constants.ts": "6204293794b5ef24159e1f0e01f686b6847ee6c2", "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe",