The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(plugin-sdk): interactions/approvals respond + attachment read capabilities for the chat gateway (#10066)
Michael Nguyen5a00040c4cc3
diff --git a/packages/plugins/sdk/src/host-client-factory.ts b/packages/plugins/sdk/src/host-client-factory.tsindex a22c10f8ed..00f5d6efe3 100644--- a/packages/plugins/sdk/src/host-client-factory.ts+++ b/packages/plugins/sdk/src/host-client-factory.ts@@ -239,6 +239,17 @@ export interface HostServices {listComments(params: WorkerToHostMethods["issues.listComments"][0]): Promise<WorkerToHostMethods["issues.listComments"][1]>;createComment(params: WorkerToHostMethods["issues.createComment"][0]): Promise<WorkerToHostMethods["issues.createComment"][1]>;createInteraction(params: WorkerToHostMethods["issues.createInteraction"][0]): Promise<WorkerToHostMethods["issues.createInteraction"][1]>;+ listInteractions(params: WorkerToHostMethods["issues.listInteractions"][0]): Promise<WorkerToHostMethods["issues.listInteractions"][1]>;+ respondInteraction(params: WorkerToHostMethods["issues.respondInteraction"][0]): Promise<WorkerToHostMethods["issues.respondInteraction"][1]>;+ listAttachments(params: WorkerToHostMethods["issues.listAttachments"][0]): Promise<WorkerToHostMethods["issues.listAttachments"][1]>;+ getAttachmentContent(params: WorkerToHostMethods["issues.getAttachmentContent"][0]): Promise<WorkerToHostMethods["issues.getAttachmentContent"][1]>;+ };++ /** Provides `approvals.list`, `approvals.get`, `approvals.decide`. */+ approvals: {+ list(params: WorkerToHostMethods["approvals.list"][0]): Promise<WorkerToHostMethods["approvals.list"][1]>;+ get(params: WorkerToHostMethods["approvals.get"][0]): Promise<WorkerToHostMethods["approvals.get"][1]>;+ decide(params: WorkerToHostMethods["approvals.decide"][0]): Promise<WorkerToHostMethods["approvals.decide"][1]>;};/** Provides `issues.documents.list`, `issues.documents.get`, `issues.documents.upsert`, `issues.documents.delete`. */@@ -445,6 +456,15 @@ const METHOD_CAPABILITY_MAP: Record<WorkerToHostMethodName, PluginCapability | n"issues.listComments": "issue.comments.read","issues.createComment": "issue.comments.create","issues.createInteraction": "issue.interactions.create",+ "issues.listInteractions": "issue.interactions.read",+ "issues.respondInteraction": "issue.interactions.respond",+ "issues.listAttachments": "issue.attachments.read",+ "issues.getAttachmentContent": "issue.attachments.read",++ // Approvals+ "approvals.list": "approvals.read",+ "approvals.get": "approvals.read",+ "approvals.decide": "approvals.respond",// Issue Documents"issues.documents.list": "issue.documents.read",@@ -894,6 +914,29 @@ export function createHostClientHandlers("issues.createInteraction": gated("issues.createInteraction", async (params) => {return services.issues.createInteraction(params);}),+ "issues.listInteractions": gated("issues.listInteractions", async (params) => {+ return services.issues.listInteractions(params);+ }),+ "issues.respondInteraction": gated("issues.respondInteraction", async (params) => {+ return services.issues.respondInteraction(params);+ }),+ "issues.listAttachments": gated("issues.listAttachments", async (params) => {+ return services.issues.listAttachments(params);+ }),+ "issues.getAttachmentContent": gated("issues.getAttachmentContent", async (params) => {+ return services.issues.getAttachmentContent(params);+ }),++ // Approvals+ "approvals.list": gated("approvals.list", async (params) => {+ return services.approvals.list(params);+ }),+ "approvals.get": gated("approvals.get", async (params) => {+ return services.approvals.get(params);+ }),+ "approvals.decide": gated("approvals.decide", async (params) => {+ return services.approvals.decide(params);+ }),// Issue Documents"issues.documents.list": gated("issues.documents.list", async (params) => {diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.tsindex bcb0f277df..2f35e5b90b 100644--- a/packages/plugins/sdk/src/protocol.ts+++ b/packages/plugins/sdk/src/protocol.ts@@ -28,8 +28,10 @@ import type {IssueDocument,IssueDocumentSummary,IssueAssigneeAdapterOverrides,+ IssueAttachment,IssueThreadInteraction,CreateIssueThreadInteraction,+ Approval,PluginManagedAgentResolution,PluginManagedProjectResolution,PluginManagedRoutineResolution,@@ -55,6 +57,7 @@ import type {PluginIssueOrchestrationSummary,PluginIssueRelationSummary,PluginIssueSubtree,+ PluginIssueAttachmentContent,PluginIssueWakeupBatchResult,PluginIssueWakeupResult,PluginJobContext,@@ -1468,6 +1471,34 @@ export interface WorkerToHostMethods {},result: IssueThreadInteraction,];+ "issues.listInteractions": [+ params: { issueId: string; companyId: string },+ result: IssueThreadInteraction[],+ ];+ "issues.respondInteraction": [+ params: {+ issueId: string;+ interactionId: string;+ companyId: string;+ action: "accept" | "reject";+ /**+ * Active human company member the decision is attributed to. Required —+ * resolving an interaction is a board-user action; the host re-verifies+ * active membership at apply time and never trusts this value blindly.+ */+ actorUserId?: string;+ reason?: string | null;+ },+ result: { interaction: IssueThreadInteraction; applied: boolean },+ ];+ "issues.listAttachments": [+ params: { issueId: string; companyId: string },+ result: IssueAttachment[],+ ];+ "issues.getAttachmentContent": [+ params: { attachmentId: string; companyId: string; maxBytes?: number | null },+ result: PluginIssueAttachmentContent | null,+ ];// Issue Documents"issues.documents.list": [@@ -1495,6 +1526,31 @@ export interface WorkerToHostMethods {result: void,];+ // Approvals+ "approvals.list": [+ params: { companyId: string; status?: string | null },+ result: Approval[],+ ];+ "approvals.get": [+ params: { approvalId: string; companyId: string },+ result: Approval | null,+ ];+ "approvals.decide": [+ params: {+ approvalId: string;+ companyId: string;+ action: "approve" | "reject";+ /**+ * Active human company member the decision is attributed to. Required —+ * deciding an approval is a board-user action; the host re-verifies+ * active membership at apply time and never trusts this value blindly.+ */+ actorUserId?: string;+ decisionNote?: string | null;+ },+ result: { approval: Approval; applied: boolean },+ ];+// Agents (read)"agents.list": [params: { companyId: string; status?: string; limit?: number; offset?: number },diff --git a/packages/plugins/sdk/src/testing.ts b/packages/plugins/sdk/src/testing.tsindex 6d56802298..8894bda890 100644--- a/packages/plugins/sdk/src/testing.ts+++ b/packages/plugins/sdk/src/testing.ts@@ -17,9 +17,11 @@ import type {IssueComment,IssueThreadInteraction,CreateIssueThreadInteraction,+ IssueAttachment,IssueDocument,Agent,Goal,+ Approval,} from "@paperclipai/shared";import type {EventFilter,@@ -108,6 +110,9 @@ export interface TestHarness {projects?: Project[];issues?: Issue[];issueComments?: IssueComment[];+ issueInteractions?: IssueThreadInteraction[];+ issueAttachments?: Array<IssueAttachment & { contentBase64?: string }>;+ approvals?: Approval[];agents?: Agent[];goals?: Goal[];projectWorkspaces?: PluginWorkspace[];@@ -492,6 +497,9 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {const blockedByIssueIds = new Map<string, string[]>();const issueComments = new Map<string, IssueComment[]>();const issueInteractions = new Map<string, IssueThreadInteraction[]>();+ const issueAttachments = new Map<string, IssueAttachment[]>();+ const attachmentContentById = new Map<string, string>();+ const approvals = new Map<string, Approval>();const issueDocuments = new Map<string, IssueDocument>();const agents = new Map<string, Agent>();const goals = new Map<string, Goal>();@@ -528,6 +536,31 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {}return stamped;}++ /**+ * Mirror the host's `requireActiveHumanMember` write bar so the harness+ * rejects the same forged/over-privileged attributions production does: the+ * actor must be an active `user` member of the company whose `membershipRole`+ * is not the read-only `viewer` role (the web app 403s viewers on these same+ * board write-routes). Keeps the harness a faithful mirror so a plugin test+ * cannot pass an attribution production would reject. Seed members via+ * `createTestPluginHost({ accessMembers: [...] })`.+ */+ function assertActiveHumanMemberCanWrite(companyId: string, actorUserId: string) {+ const member = [...accessMembers.values()].find(+ (entry) =>+ entry.companyId === companyId+ && entry.principalType === "user"+ && entry.principalId === actorUserId+ && entry.status === "active",+ );+ if (!member) {+ throw new Error(`actorUserId "${actorUserId}" is not an active human member of this company`);+ }+ if (member.membershipRole === "viewer") {+ throw new Error(`actorUserId "${actorUserId}" has viewer (read-only) access and cannot take this write action`);+ }+ }const projectWorkspaces = new Map<string, PluginWorkspace[]>();const executionWorkspaces = new Map<string, PluginExecutionWorkspaceMetadata>();const localFolderStatuses = new Map<string, PluginLocalFolderStatus>();@@ -1681,23 +1714,7 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {throw new Error(`Issue not found: ${issueId}`);}if (options?.actorUserId) {- // Mirror the host's `requireActiveHumanMember` check so the harness- // rejects the same forged attributions production does: the actor- // must be an active `user` member of the issue's company. Seed- // members via `createTestPluginHost({ accessMembers: [...] })`.- const actorUserId = options.actorUserId;- const isActiveHumanMember = [...accessMembers.values()].some(- (member) =>- member.companyId === companyId- && member.principalType === "user"- && member.principalId === actorUserId- && member.status === "active",- );- if (!isActiveHumanMember) {- throw new Error(- `actorUserId "${actorUserId}" is not an active human member of this company`,- );- }+ assertActiveHumanMemberCanWrite(companyId, options.actorUserId);}const now = new Date();const comment: IssueComment = {@@ -1765,6 +1782,66 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {async requestCheckboxConfirmation(issueId, interaction, companyId, options) {return this.createInteraction(issueId, { ...interaction, kind: "request_checkbox_confirmation" }, companyId, options) as Promise<any>;},+ async listInteractions(issueId, companyId) {+ requireCapability(manifest, capabilitySet, "issue.interactions.read");+ if (!isInCompany(issues.get(issueId), companyId)) return [];+ return issueInteractions.get(issueId) ?? [];+ },+ async respondInteraction(issueId, interactionId, input, companyId) {+ requireCapability(manifest, capabilitySet, "issue.interactions.respond");+ const parentIssue = issues.get(issueId);+ if (!isInCompany(parentIssue, companyId)) {+ throw new Error(`Issue not found: ${issueId}`);+ }+ if (!input.actorUserId) {+ throw new Error("actorUserId is required to respond to an interaction on behalf of a board user");+ }+ const actorUserId = input.actorUserId;+ // Mirror the host's active-human-member write re-verification.+ assertActiveHumanMemberCanWrite(companyId, actorUserId);+ const list = issueInteractions.get(issueId) ?? [];+ const current = list.find((entry) => entry.id === interactionId);+ if (!current) {+ throw new Error(`Interaction not found: ${interactionId}`);+ }+ if (current.status !== "pending") {+ return { interaction: current, applied: false };+ }+ const resolved: IssueThreadInteraction = {+ ...current,+ status: input.action === "accept" ? "accepted" : "rejected",+ updatedAt: new Date(),+ } as IssueThreadInteraction;+ const index = list.indexOf(current);+ list[index] = resolved;+ issueInteractions.set(issueId, list);+ return { interaction: resolved, applied: true };+ },+ async listAttachments(issueId, companyId) {+ requireCapability(manifest, capabilitySet, "issue.attachments.read");+ if (!isInCompany(issues.get(issueId), companyId)) return [];+ return issueAttachments.get(issueId) ?? [];+ },+ async getAttachmentContent(attachmentId, companyId, options) {+ requireCapability(manifest, capabilitySet, "issue.attachments.read");+ const attachment = [...issueAttachments.values()]+ .flat()+ .find((entry) => entry.id === attachmentId);+ if (!attachment || attachment.companyId !== companyId) return null;+ const maxBytes = typeof options?.maxBytes === "number" && options.maxBytes > 0 ? options.maxBytes : null;+ if (maxBytes !== null && attachment.byteSize > maxBytes) {+ throw new Error(`attachment ${attachment.id} is ${attachment.byteSize} bytes, over the ${maxBytes}-byte cap`);+ }+ const contentBase64 = attachmentContentById.get(attachment.id) ?? "";+ return {+ attachmentId: attachment.id,+ contentType: attachment.contentType,+ byteSize: attachment.byteSize,+ sha256: attachment.sha256,+ originalFilename: attachment.originalFilename ?? null,+ contentBase64,+ };+ },documents: {async list(issueId, companyId) {requireCapability(manifest, capabilitySet, "issue.documents.read");@@ -1916,6 +1993,47 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {},},},+ approvals: {+ async list(input) {+ requireCapability(manifest, capabilitySet, "approvals.read");+ return [...approvals.values()].filter(+ (approval) =>+ approval.companyId === input.companyId+ && (!input.status || approval.status === input.status),+ );+ },+ async get(approvalId, companyId) {+ requireCapability(manifest, capabilitySet, "approvals.read");+ const approval = approvals.get(approvalId);+ if (!approval || approval.companyId !== companyId) return null;+ return approval;+ },+ async decide(approvalId, input, companyId) {+ requireCapability(manifest, capabilitySet, "approvals.respond");+ const approval = approvals.get(approvalId);+ if (!approval || approval.companyId !== companyId) {+ throw new Error(`Approval not found: ${approvalId}`);+ }+ if (!input.actorUserId) {+ throw new Error("actorUserId is required to decide an approval on behalf of a board user");+ }+ const actorUserId = input.actorUserId;+ assertActiveHumanMemberCanWrite(companyId, actorUserId);+ if (approval.status !== "pending") {+ return { approval, applied: false };+ }+ const decided: Approval = {+ ...approval,+ status: input.action === "approve" ? "approved" : "rejected",+ decisionNote: input.decisionNote ?? null,+ decidedByUserId: actorUserId,+ decidedAt: new Date(),+ updatedAt: new Date(),+ };+ approvals.set(approvalId, decided);+ return { approval: decided, applied: true };+ },+ },agents: {async list(input) {requireCapability(manifest, capabilitySet, "agents.read");@@ -2400,6 +2518,19 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {list.push(row);issueComments.set(row.issueId, list);}+ for (const row of input.issueInteractions ?? []) {+ const list = issueInteractions.get(row.issueId) ?? [];+ list.push(row);+ issueInteractions.set(row.issueId, list);+ }+ for (const row of input.issueAttachments ?? []) {+ const { contentBase64, ...attachment } = row;+ const list = issueAttachments.get(attachment.issueId) ?? [];+ list.push(attachment);+ issueAttachments.set(attachment.issueId, list);+ attachmentContentById.set(attachment.id, contentBase64 ?? "");+ }+ for (const row of input.approvals ?? []) approvals.set(row.id, row);for (const row of input.agents ?? []) agents.set(row.id, row);for (const row of input.goals ?? []) goals.set(row.id, row);for (const row of input.projectWorkspaces ?? []) {diff --git a/packages/plugins/sdk/src/types.ts b/packages/plugins/sdk/src/types.tsindex f8645456ee..dc33e9b03d 100644--- a/packages/plugins/sdk/src/types.ts+++ b/packages/plugins/sdk/src/types.ts@@ -23,7 +23,9 @@ import type {IssueDocumentSummary,IssueRelationIssueSummary,IssueAssigneeAdapterOverrides,+ IssueAttachment,IssueThreadInteraction,+ Approval,SuggestTasksInteraction,AskUserQuestionsInteraction,RequestConfirmationInteraction,@@ -1319,6 +1321,20 @@ export interface PluginIssueSummariesClient {}): Promise<PluginIssueOrchestrationSummary>;}+/**+ * Attachment content bytes returned by `ctx.issues.getAttachmentContent`.+ * Bytes are base64-encoded; there is no URL surface.+ */+export interface PluginIssueAttachmentContent {+ attachmentId: string;+ contentType: string;+ byteSize: number;+ sha256: string;+ originalFilename: string | null;+ /** The attachment's raw bytes, base64-encoded. */+ contentBase64: string;+}+/*** `ctx.issues` — read and mutate issues plus comments.*@@ -1333,6 +1349,9 @@ export interface PluginIssueSummariesClient {* - `issue.comments.create` for `createComment`* - `issue.comments.create_human_attributed` for `createComment` calls that pass `actorUserId`* - `issue.interactions.create` for `createInteraction`, `suggestTasks`, `askUserQuestions`, `requestConfirmation`, and `requestCheckboxConfirmation`+ * - `issue.interactions.read` for `listInteractions`+ * - `issue.interactions.respond` for `respondInteraction`+ * - `issue.attachments.read` for `listAttachments` and `getAttachmentContent`* - `issue.documents.read` for `documents.list` and `documents.get`* - `issue.documents.write` for `documents.upsert` and `documents.delete`*/@@ -1489,6 +1508,47 @@ export interface PluginIssuesClient {companyId: string,options?: { authorAgentId?: string },): Promise<RequestCheckboxConfirmationInteraction>;+ /**+ * List the issue-thread interactions (decision cards) on an issue.+ * Requires `issue.interactions.read`.+ */+ listInteractions(issueId: string, companyId: string): Promise<IssueThreadInteraction[]>;+ /**+ * Resolve (accept/reject) a pending issue-thread interaction on behalf of a+ * paired board user. Requires `issue.interactions.respond`.+ *+ * `actorUserId` is the human company member the decision is attributed to.+ * The host independently re-verifies that this user is an active human+ * member of the issue's company before applying the decision — a plugin can+ * only ever resolve interactions as an identity that could have resolved+ * them in the web app (whose interaction-resolve routes are board-only).+ *+ * Returns the (possibly already-resolved) interaction and `applied`, which is+ * `true` when this call performed the resolution and `false` when the+ * interaction had already converged to a resolved state (idempotent replays).+ */+ respondInteraction(+ issueId: string,+ interactionId: string,+ input: { action: "accept" | "reject"; actorUserId?: string; reason?: string | null },+ companyId: string,+ ): Promise<{ interaction: IssueThreadInteraction; applied: boolean }>;+ /** List attachment metadata for an issue. Requires `issue.attachments.read`. */+ listAttachments(issueId: string, companyId: string): Promise<IssueAttachment[]>;+ /**+ * Read an attachment's content bytes (base64) through the capability-scoped+ * host bridge. Requires `issue.attachments.read`.+ *+ * Company-scoped and audit-logged host-side; there is no URL surface. Returns+ * `null` for an unknown or cross-company attachment id (indistinguishable by+ * design). Pass `maxBytes` to refuse over-cap assets — the host throws rather+ * than partially reading when the stored size exceeds the cap.+ */+ getAttachmentContent(+ attachmentId: string,+ companyId: string,+ options?: { maxBytes?: number | null },+ ): Promise<PluginIssueAttachmentContent | null>;/** Read and write issue documents. Requires `issue.documents.read` / `issue.documents.write`. */documents: PluginIssueDocumentsClient;/** Read and write blocker relationships. */@@ -1497,6 +1557,36 @@ export interface PluginIssuesClient {summaries: PluginIssueSummariesClient;}+/**+ * `ctx.approvals` — read and decide company approvals.+ *+ * Requires `approvals.read` for `list` / `get`; `approvals.respond` for+ * `decide`. Approval payloads returned by `list` / `get` are redacted host-side+ * to match the web app's own approval read surface (no secret leakage through+ * the bridge).+ */+export interface PluginApprovalsClient {+ list(input: { companyId: string; status?: string | null }): Promise<Approval[]>;+ get(approvalId: string, companyId: string): Promise<Approval | null>;+ /**+ * Approve or reject an approval on behalf of a paired board user.+ *+ * `actorUserId` is the human company member the decision is attributed to.+ * The host independently re-verifies that this user is an active human member+ * of the approval's company before applying the decision — a plugin can only+ * ever decide approvals as an identity that could have decided them in the+ * web app (whose approval-decision routes are board-only).+ *+ * `applied` is `true` when this call performed the decision and `false` when+ * the approval had already converged to a decided state (idempotent replays).+ */+ decide(+ approvalId: string,+ input: { action: "approve" | "reject"; actorUserId?: string; decisionNote?: string | null },+ companyId: string,+ ): Promise<{ approval: Approval; applied: boolean }>;+}+/*** `ctx.agents` — read and manage agents.*@@ -1924,6 +2014,9 @@ export interface PluginContext {/** Read and write issues, comments, and documents. Requires issue capabilities. */issues: PluginIssuesClient;+ /** Read and decide company approvals. Requires `approvals.read` / `approvals.respond`. */+ approvals: PluginApprovalsClient;+/** Read and manage agents. Requires `agents.read` for reads; `agents.pause` / `agents.resume` / `agents.invoke` for write ops. */agents: PluginAgentsClient;diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.tsindex 4f40baa712..076751034d 100644--- a/packages/plugins/sdk/src/worker-rpc-host.ts+++ b/packages/plugins/sdk/src/worker-rpc-host.ts@@ -956,6 +956,42 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost}) as Promise<RequestCheckboxConfirmationInteraction>;},+ async listInteractions(issueId: string, companyId: string) {+ return callHost("issues.listInteractions", { issueId, companyId });+ },++ async respondInteraction(+ issueId: string,+ interactionId: string,+ input: { action: "accept" | "reject"; actorUserId?: string; reason?: string | null },+ companyId: string,+ ) {+ return callHost("issues.respondInteraction", {+ issueId,+ interactionId,+ companyId,+ action: input.action,+ actorUserId: input.actorUserId,+ reason: input.reason,+ });+ },++ async listAttachments(issueId: string, companyId: string) {+ return callHost("issues.listAttachments", { issueId, companyId });+ },++ async getAttachmentContent(+ attachmentId: string,+ companyId: string,+ options?: { maxBytes?: number | null },+ ) {+ return callHost("issues.getAttachmentContent", {+ attachmentId,+ companyId,+ maxBytes: options?.maxBytes ?? null,+ });+ },+documents: {async list(issueId: string, companyId: string) {return callHost("issues.documents.list", { issueId, companyId });@@ -1028,6 +1064,33 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost},},+ approvals: {+ async list(input: { companyId: string; status?: string | null }) {+ return callHost("approvals.list", {+ companyId: input.companyId,+ status: input.status,+ });+ },++ async get(approvalId: string, companyId: string) {+ return callHost("approvals.get", { approvalId, companyId });+ },++ async decide(+ approvalId: string,+ input: { action: "approve" | "reject"; actorUserId?: string; decisionNote?: string | null },+ companyId: string,+ ) {+ return callHost("approvals.decide", {+ approvalId,+ companyId,+ action: input.action,+ actorUserId: input.actorUserId,+ decisionNote: input.decisionNote,+ });+ },+ },+agents: {async list(input) {return callHost("agents.list", {diff --git a/packages/plugins/sdk/tests/host-client-factory.test.ts b/packages/plugins/sdk/tests/host-client-factory.test.tsindex b741e0b4eb..2c87650af5 100644--- a/packages/plugins/sdk/tests/host-client-factory.test.ts+++ b/packages/plugins/sdk/tests/host-client-factory.test.ts@@ -306,3 +306,115 @@ describe("createHostClientHandlers invocation company scope", () => {expect(createComment).toHaveBeenCalled();});});++describe("createHostClientHandlers capability gating for LOOA-641 methods", () => {+ const context = { invocationScope: { companyId: "company-a" } };++ it("denies issues.respondInteraction without issue.interactions.respond", async () => {+ const respondInteraction = vi.fn(async () => ({ interaction: { id: "i" }, applied: true }));+ const services = { issues: { respondInteraction } } as unknown as HostServices;+ const handlers = createHostClientHandlers({+ pluginId: "paperclip.test",+ // A read grant must not confer the ability to respond.+ capabilities: ["issue.interactions.read"],+ services,+ });+ await expect(+ handlers["issues.respondInteraction"]({+ issueId: "issue-a", interactionId: "int-a", companyId: "company-a", action: "accept", actorUserId: "user-a",+ }, context),+ ).rejects.toBeInstanceOf(CapabilityDeniedError);+ expect(respondInteraction).not.toHaveBeenCalled();+ });++ it("allows issues.respondInteraction with issue.interactions.respond", async () => {+ const respondInteraction = vi.fn(async () => ({ interaction: { id: "i" }, applied: true }));+ const services = { issues: { respondInteraction } } as unknown as HostServices;+ const handlers = createHostClientHandlers({+ pluginId: "paperclip.test",+ capabilities: ["issue.interactions.respond"],+ services,+ });+ await expect(+ handlers["issues.respondInteraction"]({+ issueId: "issue-a", interactionId: "int-a", companyId: "company-a", action: "accept", actorUserId: "user-a",+ }, context),+ ).resolves.toEqual({ interaction: { id: "i" }, applied: true });+ expect(respondInteraction).toHaveBeenCalledOnce();+ });++ it("denies approvals.decide without approvals.respond", async () => {+ const decide = vi.fn(async () => ({ approval: { id: "a" }, applied: true }));+ const services = { approvals: { decide } } as unknown as HostServices;+ const handlers = createHostClientHandlers({+ pluginId: "paperclip.test",+ // A read grant must not confer the ability to decide.+ capabilities: ["approvals.read"],+ services,+ });+ await expect(+ handlers["approvals.decide"]({+ approvalId: "a", companyId: "company-a", action: "approve", actorUserId: "user-a",+ }, context),+ ).rejects.toBeInstanceOf(CapabilityDeniedError);+ expect(decide).not.toHaveBeenCalled();+ });++ it("allows approvals.decide with approvals.respond", async () => {+ const decide = vi.fn(async () => ({ approval: { id: "a" }, applied: true }));+ const services = { approvals: { decide } } as unknown as HostServices;+ const handlers = createHostClientHandlers({+ pluginId: "paperclip.test",+ capabilities: ["approvals.respond"],+ services,+ });+ await expect(+ handlers["approvals.decide"]({+ approvalId: "a", companyId: "company-a", action: "approve", actorUserId: "user-a",+ }, context),+ ).resolves.toEqual({ approval: { id: "a" }, applied: true });+ expect(decide).toHaveBeenCalledOnce();+ });++ it("denies read methods without their read capability", async () => {+ const listInteractions = vi.fn(async () => []);+ const list = vi.fn(async () => []);+ const getAttachmentContent = vi.fn(async () => null);+ const services = {+ issues: { listInteractions, getAttachmentContent },+ approvals: { list },+ } as unknown as HostServices;+ const handlers = createHostClientHandlers({+ pluginId: "paperclip.test",+ capabilities: [],+ services,+ });+ await expect(+ handlers["issues.listInteractions"]({ issueId: "i", companyId: "company-a" }, context),+ ).rejects.toBeInstanceOf(CapabilityDeniedError);+ await expect(+ handlers["approvals.list"]({ companyId: "company-a" }, context),+ ).rejects.toBeInstanceOf(CapabilityDeniedError);+ await expect(+ handlers["issues.getAttachmentContent"]({ attachmentId: "at", companyId: "company-a" }, context),+ ).rejects.toBeInstanceOf(CapabilityDeniedError);+ expect(listInteractions).not.toHaveBeenCalled();+ expect(list).not.toHaveBeenCalled();+ expect(getAttachmentContent).not.toHaveBeenCalled();+ });++ it("enforces invocation company scope on the new methods", async () => {+ const list = vi.fn(async () => []);+ const services = { approvals: { list } } as unknown as HostServices;+ const handlers = createHostClientHandlers({+ pluginId: "paperclip.test",+ capabilities: ["approvals.read"],+ services,+ });+ // Requesting company-b while scoped to company-a must be denied.+ await expect(+ handlers["approvals.list"]({ companyId: "company-b" }, context),+ ).rejects.toBeInstanceOf(InvocationScopeDeniedError);+ expect(list).not.toHaveBeenCalled();+ });+});diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.tsindex 6056b0b0b6..e6aa21d173 100644--- a/packages/shared/src/constants.ts+++ b/packages/shared/src/constants.ts@@ -1235,6 +1235,14 @@ export const PLUGIN_CAPABILITIES = ["issue.relations.read","issue.subtree.read","issue.comments.read",+ // Read pending issue-thread interactions (decision cards) on an issue.+ "issue.interactions.read",+ // Read issue attachment metadata and, via the capability-scoped host+ // bridge, attachment content bytes (bytes-only, company-scoped, audit-logged).+ "issue.attachments.read",+ // Read company approvals (list + get). The host redacts approval payloads to+ // match the web app's own approval read surface.+ "approvals.read","issue.documents.read","agents.read","goals.read",@@ -1258,6 +1266,16 @@ export const PLUGIN_CAPABILITIES = ["issue.comments.create","issue.comments.create_human_attributed","issue.interactions.create",+ // Respond to (accept/reject) an issue-thread interaction on behalf of a+ // paired board user. Impersonation surface: the host independently+ // re-verifies the actor is an active human member of the company at apply+ // time (never trusts plugin-supplied identity), matching the web app's+ // board-only interaction resolve route.+ "issue.interactions.respond",+ // Decide (approve/reject) a company approval on behalf of a paired board+ // user. Same apply-time active-human-member re-verification as above; the+ // web app's approval decision routes are board-only.+ "approvals.respond","issue.documents.write","projects.managed","routines.managed",diff --git a/server/src/__tests__/plugin-orchestration-apis.test.ts b/server/src/__tests__/plugin-orchestration-apis.test.tsindex d43ffbb015..1f3f2e0658 100644--- a/server/src/__tests__/plugin-orchestration-apis.test.ts+++ b/server/src/__tests__/plugin-orchestration-apis.test.ts@@ -8,6 +8,8 @@ import {activityLog,agentWakeupRequests,agents,+ approvals,+ assets,companies,companyMemberships,costEvents,@@ -15,8 +17,10 @@ import {executionWorkspaces,heartbeatRunEvents,heartbeatRuns,+ issueAttachments,issueComments,issueRelations,+ issueThreadInteractions,issues,pluginManagedResources,plugins,@@ -95,6 +99,10 @@ describeEmbeddedPostgres("plugin orchestration APIs", () => {await db.delete(agentWakeupRequests);await db.delete(issueRelations);await db.delete(issueComments);+ await db.delete(issueThreadInteractions);+ await db.delete(issueAttachments);+ await db.delete(assets);+ await db.delete(approvals);await db.delete(issues);await db.delete(executionWorkspaces);await db.delete(pluginManagedResources);@@ -786,6 +794,31 @@ describeEmbeddedPostgres("plugin orchestration APIs", () => {await expect(db.select().from(agentWakeupRequests)).resolves.toHaveLength(0);});+ it("rejects a human-attributed plugin comment when actorUserId is a viewer-role (read-only) member", async () => {+ // LOOA-648: a viewer is a real active member but is read-only in the web+ // app (routes/authz.ts "Viewer access is read-only"). Attributing a comment+ // to them is a write the paired user could not make interactively.+ const { companyId, agentId } = await seedCompanyAndAgent();+ const viewerUserId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId, principalType: "user", principalId: viewerUserId, status: "active", membershipRole: "viewer",+ });+ const issueId = randomUUID();+ await db.insert(issues).values({+ id: issueId, companyId, title: "Needs human input", status: "in_review", priority: "medium", assigneeAgentId: agentId,+ });++ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.issues.createComment({ issueId, companyId, body: "Here's my answer", actorUserId: viewerUserId }),+ ).rejects.toThrow("viewer (read-only) access");++ // No comment persisted, no assignee woken.+ await expect(db.select().from(agentWakeupRequests)).resolves.toHaveLength(0);+ const comments = await services.issues.listComments({ issueId, companyId });+ expect(comments).toHaveLength(0);+ });+it("creates a human-attributed plugin comment and wakes the issue's assignee", async () => {const { companyId, agentId } = await seedCompanyAndAgent();const humanUserId = randomUUID();@@ -852,4 +885,296 @@ describeEmbeddedPostgres("plugin orchestration APIs", () => {.where(eq(heartbeatRuns.id, wakeupRequest!.runId!));expect(run).toMatchObject({ agentId, companyId, status: "queued" });});++ // ---------------------------------------------------------------------------+ // LOOA-641 — interactions.respond / approvals.decide impersonation surface.+ // The host must independently re-verify the paired user's active membership+ // at apply time and never trust the plugin-supplied identity.+ // ---------------------------------------------------------------------------++ async function seedInteraction(+ companyId: string,+ issueId: string,+ overrides: Partial<typeof issueThreadInteractions.$inferInsert> = {},+ ) {+ const interactionId = randomUUID();+ await db.insert(issueThreadInteractions).values({+ id: interactionId,+ companyId,+ issueId,+ kind: "request_confirmation",+ status: "pending",+ continuationPolicy: "wake_assignee",+ payload: { version: 1, prompt: "Proceed?" } as never,+ ...overrides,+ });+ return interactionId;+ }++ it("respondInteraction fails closed when actorUserId is omitted", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ await db.insert(issues).values({+ id: issueId, companyId, title: "Decision", status: "in_review", priority: "medium", assigneeAgentId: agentId,+ });+ const interactionId = await seedInteraction(companyId, issueId);+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.issues.respondInteraction({ issueId, interactionId, companyId, action: "accept" }),+ ).rejects.toThrow("actorUserId is required");+ });++ it("respondInteraction rejects an actorUserId that is not an active company member", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ await db.insert(issues).values({+ id: issueId, companyId, title: "Decision", status: "in_review", priority: "medium", assigneeAgentId: agentId,+ });+ const interactionId = await seedInteraction(companyId, issueId);+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.issues.respondInteraction({+ issueId, interactionId, companyId, action: "accept", actorUserId: randomUUID(),+ }),+ ).rejects.toThrow("is not an active human member of this company");++ // The interaction must remain pending — no resolution was applied.+ const [row] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId));+ expect(row?.status).toBe("pending");+ });++ it("respondInteraction rejects a viewer-role active member and leaves the interaction pending", async () => {+ // LOOA-648: viewers are read-only board members (routes/authz.ts). A plugin+ // holding issue.interactions.respond must not resolve an interaction on+ // their behalf — that is a write the viewer is 403'd on in the web app.+ const { companyId, agentId } = await seedCompanyAndAgent();+ const viewerUserId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId, principalType: "user", principalId: viewerUserId, status: "active", membershipRole: "viewer",+ });+ const issueId = randomUUID();+ await db.insert(issues).values({+ id: issueId, companyId, title: "Decision", status: "in_review", priority: "medium", assigneeAgentId: agentId,+ });+ const interactionId = await seedInteraction(companyId, issueId);+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.issues.respondInteraction({+ issueId, interactionId, companyId, action: "accept", actorUserId: viewerUserId,+ }),+ ).rejects.toThrow("viewer (read-only) access");++ const [row] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId));+ expect(row?.status).toBe("pending");+ });++ it("respondInteraction applies for a non-viewer human role (operator)", async () => {+ // LOOA-648 regression: owner/admin/operator must still pass the write bar.+ // Issue has no assignee so the continuation wakeup is a no-op — this+ // isolates the membership check from run orchestration.+ const { companyId } = await seedCompanyAndAgent();+ const operatorUserId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId, principalType: "user", principalId: operatorUserId, status: "active", membershipRole: "operator",+ });+ const issueId = randomUUID();+ await db.insert(issues).values({+ id: issueId, companyId, title: "Decision", status: "in_review", priority: "medium",+ });+ const interactionId = await seedInteraction(companyId, issueId);+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ const result = await services.issues.respondInteraction({+ issueId, interactionId, companyId, action: "accept", actorUserId: operatorUserId,+ });+ expect(result.applied).toBe(true);+ const [row] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId));+ expect(row?.status).toBe("accepted");+ });++ it("respondInteraction converges (applied:false) when the interaction is already resolved", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const humanUserId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId, principalType: "user", principalId: humanUserId, status: "active", membershipRole: "owner",+ });+ const issueId = randomUUID();+ await db.insert(issues).values({+ id: issueId, companyId, title: "Decision", status: "in_review", priority: "medium", assigneeAgentId: agentId,+ });+ const interactionId = await seedInteraction(companyId, issueId, { status: "rejected" });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ const result = await services.issues.respondInteraction({+ issueId, interactionId, companyId, action: "accept", actorUserId: humanUserId,+ });+ expect(result.applied).toBe(false);+ expect(result.interaction).toMatchObject({ id: interactionId, status: "rejected" });+ });++ it("approvals.decide fails closed when actorUserId is omitted", async () => {+ const { companyId } = await seedCompanyAndAgent();+ const approvalId = randomUUID();+ await db.insert(approvals).values({+ id: approvalId, companyId, type: "request_board_approval", status: "pending", payload: { title: "Ship it" },+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.approvals.decide({ approvalId, companyId, action: "approve" }),+ ).rejects.toThrow("actorUserId is required");+ const [row] = await db.select().from(approvals).where(eq(approvals.id, approvalId));+ expect(row?.status).toBe("pending");+ });++ it("approvals.decide rejects an actorUserId that is not an active company member", async () => {+ const { companyId } = await seedCompanyAndAgent();+ const approvalId = randomUUID();+ await db.insert(approvals).values({+ id: approvalId, companyId, type: "request_board_approval", status: "pending", payload: { title: "Ship it" },+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.approvals.decide({ approvalId, companyId, action: "approve", actorUserId: randomUUID() }),+ ).rejects.toThrow("is not an active human member of this company");+ const [row] = await db.select().from(approvals).where(eq(approvals.id, approvalId));+ expect(row?.status).toBe("pending");+ });++ it("approvals.decide rejects a viewer-role active member and leaves the approval pending", async () => {+ // LOOA-648: the exploit at the heart of the review — a plugin holding+ // approvals.respond decides an approval for a viewer who is 403'd in the+ // web UI. The host must reject the viewer before applying the decision.+ const { companyId } = await seedCompanyAndAgent();+ const viewerUserId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId, principalType: "user", principalId: viewerUserId, status: "active", membershipRole: "viewer",+ });+ const approvalId = randomUUID();+ await db.insert(approvals).values({+ id: approvalId, companyId, type: "request_board_approval", status: "pending", payload: { title: "Ship it" },+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.approvals.decide({ approvalId, companyId, action: "approve", actorUserId: viewerUserId }),+ ).rejects.toThrow("viewer (read-only) access");+ const [row] = await db.select().from(approvals).where(eq(approvals.id, approvalId));+ expect(row?.status).toBe("pending");+ });++ it("approvals.decide applies for a non-viewer human role (admin)", async () => {+ // LOOA-648 regression: owner/admin/operator must still pass the write bar.+ const { companyId } = await seedCompanyAndAgent();+ const adminUserId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId, principalType: "user", principalId: adminUserId, status: "active", membershipRole: "admin",+ });+ const approvalId = randomUUID();+ await db.insert(approvals).values({+ id: approvalId, companyId, type: "request_board_approval", status: "pending", payload: { title: "Ship it" },+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ const result = await services.approvals.decide({+ approvalId, companyId, action: "approve", actorUserId: adminUserId,+ });+ expect(result.applied).toBe(true);+ expect(result.approval).toMatchObject({ id: approvalId, status: "approved", decidedByUserId: adminUserId });+ const [row] = await db.select().from(approvals).where(eq(approvals.id, approvalId));+ expect(row?.status).toBe("approved");+ });++ it("approvals.decide applies for an active member and redacts secret payload fields", async () => {+ const { companyId } = await seedCompanyAndAgent();+ const humanUserId = randomUUID();+ await db.insert(companyMemberships).values({+ companyId, principalType: "user", principalId: humanUserId, status: "active", membershipRole: "owner",+ });+ const approvalId = randomUUID();+ await db.insert(approvals).values({+ id: approvalId,+ companyId,+ type: "request_board_approval",+ status: "pending",+ payload: { title: "Ship it", botToken: "xoxb-super-secret" },+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ const result = await services.approvals.decide({+ approvalId, companyId, action: "approve", actorUserId: humanUserId, decisionNote: "lgtm",+ });+ expect(result.applied).toBe(true);+ expect(result.approval).toMatchObject({ id: approvalId, status: "approved", decidedByUserId: humanUserId });+ // Bridge output must be redacted the same way the web app redacts approvals.+ expect(result.approval.payload.title).toBe("Ship it");+ expect(result.approval.payload.botToken).toBe("***REDACTED***");++ // Persisted row is decided; the raw stored secret is untouched (redaction is+ // an output transform, not a mutation).+ const [row] = await db.select().from(approvals).where(eq(approvals.id, approvalId));+ expect(row?.status).toBe("approved");+ });++ it("approvals.list redacts payloads and is company-scoped", async () => {+ const { companyId } = await seedCompanyAndAgent();+ const otherCompany = randomUUID();+ await db.insert(companies).values({+ id: otherCompany, name: "Other", issuePrefix: issuePrefix(otherCompany), requireBoardApprovalForNewAgents: false,+ });+ await db.insert(approvals).values({+ id: randomUUID(), companyId, type: "request_board_approval", status: "pending",+ payload: { title: "Mine", accessToken: "sekret" },+ });+ await db.insert(approvals).values({+ id: randomUUID(), companyId: otherCompany, type: "request_board_approval", status: "pending",+ payload: { title: "Theirs" },+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ const rows = await services.approvals.list({ companyId });+ expect(rows).toHaveLength(1);+ expect(rows[0]!.payload.title).toBe("Mine");+ expect(rows[0]!.payload.accessToken).toBe("***REDACTED***");+ });++ it("getAttachmentContent returns null for a cross-company attachment id", async () => {+ const { companyId, agentId } = await seedCompanyAndAgent();+ const otherCompany = randomUUID();+ await db.insert(companies).values({+ id: otherCompany, name: "Other", issuePrefix: issuePrefix(otherCompany), requireBoardApprovalForNewAgents: false,+ });+ const otherIssueId = randomUUID();+ await db.insert(issues).values({+ id: otherIssueId, companyId: otherCompany, title: "Theirs", status: "todo", priority: "medium",+ });+ const assetId = randomUUID();+ await db.insert(assets).values({+ id: assetId, companyId: otherCompany, provider: "local_disk", objectKey: "k", contentType: "image/png",+ byteSize: 10, sha256: "abc",+ });+ const attachmentId = randomUUID();+ await db.insert(issueAttachments).values({+ id: attachmentId, companyId: otherCompany, issueId: otherIssueId, assetId,+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ // Requested under our own company: the cross-company id must be invisible.+ void agentId;+ const content = await services.issues.getAttachmentContent({ attachmentId, companyId });+ expect(content).toBeNull();+ });++ it("getAttachmentContent refuses an over-cap attachment", async () => {+ const { companyId } = await seedCompanyAndAgent();+ const issueId = randomUUID();+ await db.insert(issues).values({+ id: issueId, companyId, title: "Has asset", status: "todo", priority: "medium",+ });+ const assetId = randomUUID();+ await db.insert(assets).values({+ id: assetId, companyId, provider: "local_disk", objectKey: "k", contentType: "image/png",+ byteSize: 5_000_000, sha256: "abc",+ });+ const attachmentId = randomUUID();+ await db.insert(issueAttachments).values({+ id: attachmentId, companyId, issueId, assetId,+ });+ const services = buildHostServices(db, "plugin-record-id", "paperclip.gateway", createEventBusStub());+ await expect(+ services.issues.getAttachmentContent({ attachmentId, companyId, maxBytes: 1_000_000 }),+ ).rejects.toThrow("over the");+ });});diff --git a/server/src/__tests__/plugin-sdk-testing.test.ts b/server/src/__tests__/plugin-sdk-testing.test.tsindex c304c4ad9a..63f86c3276 100644--- a/server/src/__tests__/plugin-sdk-testing.test.ts+++ b/server/src/__tests__/plugin-sdk-testing.test.ts@@ -203,6 +203,48 @@ describe("plugin SDK test harness", () => {).rejects.toThrow('actorUserId "user-1" is not an active human member of this company');});+ it("rejects a human-attributed comment when the actorUserId is a viewer-role (read-only) member", async () => {+ // LOOA-648: the harness mirrors the host's viewer write-bar so a plugin's+ // own test suite cannot pass an attribution production rejects. A viewer is+ // an active member but read-only in the web app.+ const manifest: PaperclipPluginManifestV1 = {+ id: "paperclip.test-human-attributed-comment-viewer",+ apiVersion: 1,+ version: "0.1.0",+ displayName: "Human-Attributed Comment (viewer)",+ description: "Test plugin",+ author: "Paperclip",+ categories: ["automation"],+ capabilities: ["issue.comments.create", "issue.comments.create_human_attributed"],+ entrypoints: { worker: "./dist/worker.js" },+ };+ const harness = createTestHarness({ manifest });+ harness.seed({+ issues: [{+ id: "issue-1",+ companyId: "company-1",+ title: "Human attribution",+ status: "todo",+ priority: "medium",+ }],+ accessMembers: [{+ id: "member-viewer",+ companyId: "company-1",+ principalType: "user",+ principalId: "user-1",+ status: "active",+ membershipRole: "viewer",+ grants: [],+ createdAt: new Date("2026-06-03T11:00:00.000Z"),+ updatedAt: new Date("2026-06-03T11:00:00.000Z"),+ }],+ });++ await expect(+ harness.ctx.issues.createComment("issue-1", "relayed reply", "company-1", { actorUserId: "user-1" }),+ ).rejects.toThrow("viewer (read-only) access");+ });+it("attributes a comment to an active human member for a verified actorUserId", async () => {const manifest: PaperclipPluginManifestV1 = {id: "paperclip.test-human-attributed-comment-verified",diff --git a/server/src/services/plugin-capability-validator.ts b/server/src/services/plugin-capability-validator.tsindex 15d6544f83..7f03126234 100644--- a/server/src/services/plugin-capability-validator.ts+++ b/server/src/services/plugin-capability-validator.ts@@ -61,6 +61,12 @@ const OPERATION_CAPABILITIES: Record<string, readonly PluginCapability[]> = {"issues.relations.get": ["issue.relations.read"],"issue.comments.list": ["issue.comments.read"],"issue.comments.get": ["issue.comments.read"],+ "issue.interactions.list": ["issue.interactions.read"],+ "issue.interactions.read": ["issue.interactions.read"],+ "issue.attachments.list": ["issue.attachments.read"],+ "issue.attachments.get": ["issue.attachments.read"],+ "approvals.list": ["approvals.read"],+ "approvals.get": ["approvals.read"],"agents.list": ["agents.read"],"agents.get": ["agents.read"],"agents.managed.get": ["agents.managed"],@@ -93,7 +99,11 @@ const OPERATION_CAPABILITIES: Record<string, readonly PluginCapability[]> = {"issues.requestWakeup": ["issues.wakeup"],"issues.requestWakeups": ["issues.wakeup"],"issue.comments.create": ["issue.comments.create"],+ "issue.comments.create_human_attributed": ["issue.comments.create_human_attributed"],"issue.interactions.create": ["issue.interactions.create"],+ "issue.interactions.respond": ["issue.interactions.respond"],+ "approvals.respond": ["approvals.respond"],+ "approvals.decide": ["approvals.respond"],"activity.log": ["activity.log.write"],"metrics.write": ["metrics.write"],"telemetry.track": ["telemetry.track"],diff --git a/server/src/services/plugin-host-services.ts b/server/src/services/plugin-host-services.tsindex e0162431f8..8b80aea644 100644--- a/server/src/services/plugin-host-services.ts+++ b/server/src/services/plugin-host-services.ts@@ -40,6 +40,8 @@ import { documentService } from "./documents.js";import { heartbeatService } from "./heartbeat.js";import { budgetService } from "./budgets.js";import { issueApprovalService } from "./issue-approvals.js";+import { approvalService } from "./approvals.js";+import { getStorageService } from "../storage/index.js";import { subscribeCompanyLiveEvents } from "./live-events.js";import { createHash, randomBytes, randomUUID } from "node:crypto";import path from "node:path";@@ -75,7 +77,7 @@ import { logger } from "../middleware/logger.js";import { getTelemetryClient } from "../telemetry.js";import { accessService } from "./access.js";import { authorizationService, type AuthorizationActor } from "./authorization.js";-import { sanitizeRecord } from "../redaction.js";+import { redactEventPayload, sanitizeRecord } from "../redaction.js";// ---------------------------------------------------------------------------// SSRF protection for plugin HTTP fetch@@ -544,6 +546,8 @@ export function buildHostServices(const authorization = authorizationService(db);const budgets = budgetService(db);const issueApprovals = issueApprovalService(db);+ const approvalSvc = approvalService(db);+ const interactions = issueThreadInteractionService(db);const scopedBus = eventBus.forPlugin(pluginKey);// Track active session event subscriptions for cleanup@@ -660,12 +664,27 @@ export function buildHostServices(* plugin attribute a mutation to them. Mirrors the authorization bar the* web app's own board routes apply — a plugin can only ever attribute an* action to an identity that could have taken it in the web app itself.- * Used by any plugin capability that accepts an `actorUserId` (currently- * `createComment`'s human-attributed path).+ * Used by any plugin capability that accepts an `actorUserId`+ * (`createComment`'s human-attributed path, `respondInteraction`, and+ * `approvals.decide`).+ *+ * All current call sites are non-safe (write) actions, so by default this+ * also rejects a `viewer`-role member — the web app's board write-routes+ * treat `membershipRole === "viewer"` as read-only and 403 it ("Viewer+ * access is read-only", routes/authz.ts:115-116). Without this bar a plugin+ * holding `approvals.respond` / `issue.interactions.respond` could attribute+ * a decision to a viewer who is denied that same action in the web UI —+ * strictly more authority than the paired user has (privilege escalation).+ * A future *read-only* attribution path can opt into allowing viewers with+ * `{ allowViewer: true }`; the default is failure-closed.*/- const requireActiveHumanMember = async (companyId: string, userId: string): Promise<void> => {+ const requireActiveHumanMember = async (+ companyId: string,+ userId: string,+ { allowViewer = false }: { allowViewer?: boolean } = {},+ ): Promise<void> => {const [membership] = await db- .select({ id: companyMemberships.id })+ .select({ id: companyMemberships.id, membershipRole: companyMemberships.membershipRole }).from(companyMemberships).where(and(eq(companyMemberships.companyId, companyId),@@ -677,8 +696,115 @@ export function buildHostServices(if (!membership) {throw new Error(`actorUserId "${userId}" is not an active human member of this company`);}+ if (!allowViewer && membership.membershipRole === "viewer") {+ throw new Error(`actorUserId "${userId}" has viewer (read-only) access and cannot take this write action`);+ }+ };++ /**+ * Wake the assignee of a continuation issue after a plugin-relayed board-user+ * interaction resolution, mirroring the web app's board interaction routes+ * (routes/issues.ts's queueResolvedInteractionContinuationWakeup) so a+ * confirmation accepted/rejected from chat resumes the agent the same way it+ * would from the web app. Deliberately narrower than the HTTP helper: it+ * carries the core interaction context plus the plan-review continuation+ * payload (the confirmation kind the gateway resolves), and skips the+ * checkbox/tool-action/item-verdict extras that the gateway's yes/no decision+ * cards never produce. Failure-tolerant: a wake failure is logged, never+ * thrown back to the plugin (the decision itself already applied).+ */+ const queuePluginInteractionContinuationWakeup = (args: {+ issue: { id: string; assigneeAgentId: string | null; status: string };+ interaction: {+ id: string;+ kind: string;+ status: string;+ continuationPolicy: string;+ sourceCommentId?: string | null;+ sourceRunId?: string | null;+ payload?: unknown;+ };+ actorUserId: string;+ source: string;+ }): void => {+ const { interaction, issue } = args;+ if (+ interaction.continuationPolicy !== "wake_assignee"+ && interaction.continuationPolicy !== "wake_assignee_on_accept"+ ) return;+ if (+ interaction.continuationPolicy === "wake_assignee_on_accept"+ && interaction.status !== "accepted"+ ) return;+ if (interaction.status === "expired") return;+ if (!issue.assigneeAgentId || issue.status === "done" || issue.status === "cancelled") return;++ let planReviewInteraction: Record<string, unknown> | null = null;+ if (interaction.kind === "request_confirmation" && isRecord(interaction.payload)) {+ const target = isRecord(interaction.payload.target) ? interaction.payload.target : null;+ if (+ target+ && target.type === "issue_document"+ && target.key === "plan"+ && typeof target.issueId === "string"+ && target.issueId === issue.id+ ) {+ planReviewInteraction = {+ id: interaction.id,+ kind: interaction.kind,+ status: interaction.status,+ target,+ acceptedTargetRevision: interaction.status === "accepted" ? target : null,+ };+ }+ }++ void heartbeat.wakeup(issue.assigneeAgentId, {+ source: "automation",+ triggerDetail: "system",+ reason: "issue_commented",+ payload: {+ issueId: issue.id,+ interactionId: interaction.id,+ interactionKind: interaction.kind,+ interactionStatus: interaction.status,+ sourceCommentId: interaction.sourceCommentId ?? null,+ sourceRunId: interaction.sourceRunId ?? null,+ ...(planReviewInteraction ? { planReviewInteraction } : {}),+ mutation: "interaction",+ },+ requestedByActorType: "user",+ requestedByActorId: args.actorUserId,+ contextSnapshot: {+ issueId: issue.id,+ taskId: issue.id,+ interactionId: interaction.id,+ interactionKind: interaction.kind,+ interactionStatus: interaction.status,+ ...(planReviewInteraction ? { planReviewInteraction } : {}),+ wakeReason: "issue_commented",+ source: `plugin:${pluginKey}`,+ },+ }).catch((err) => logger.warn({+ err,+ issueId: issue.id,+ interactionId: interaction.id,+ agentId: issue.assigneeAgentId,+ source: args.source,+ }, "failed to wake assignee on plugin-relayed interaction resolution"));};+ /**+ * Redact an approval's payload before returning it through the plugin bridge,+ * mirroring the web app's own approval read routes (routes/approvals.ts's+ * redactApprovalPayload). Ensures the chat surface never receives secrets the+ * web app itself hides from an approval reader.+ */+ const redactApprovalPayload = <T extends { payload: Record<string, unknown> }>(approval: T): T => ({+ ...approval,+ payload: redactEventPayload(approval.payload) ?? {},+ });+const pluginActivityDetails = (details: Record<string, unknown> | null | undefined,actor?: { actorAgentId?: string | null; actorUserId?: string | null; actorRunId?: string | null },@@ -2123,6 +2249,228 @@ export function buildHostServices(});return interaction as any;},+ async listInteractions(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ if (!inCompany(await issues.getById(params.issueId), companyId)) return [];+ return (await interactions.listForIssue(params.issueId)) as any;+ },+ async respondInteraction(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ const issue = requireInCompany("Issue", await issues.getById(params.issueId), companyId);+ // Resolving an interaction is a board-user action (the web app's+ // interaction-resolve routes are board-only). The host re-verifies the+ // paired user is an active human member at apply time and never trusts+ // the plugin-supplied identity — matching the createComment bar.+ if (!params.actorUserId) {+ throw new Error("actorUserId is required to respond to an interaction on behalf of a board user");+ }+ await requireActiveHumanMember(companyId, params.actorUserId);++ const current = await interactions.getById(params.interactionId);+ if (!current || current.issueId !== issue.id || current.companyId !== companyId) {+ throw new Error(`Interaction "${params.interactionId}" not found for this issue`);+ }+ // Idempotent replay: an already-resolved interaction converges without+ // re-applying, so a duplicate button tap from chat is a safe no-op.+ if (current.status !== "pending") {+ return { interaction: current as any, applied: false };+ }++ const actor = { userId: params.actorUserId };+ let resolved: typeof current;+ let continuationTarget = {+ id: issue.id,+ assigneeAgentId: issue.assigneeAgentId,+ status: issue.status,+ };+ if (params.action === "accept") {+ const result = await interactions.acceptInteraction(+ { id: issue.id, companyId, projectId: issue.projectId ?? null, goalId: issue.goalId ?? null },+ params.interactionId,+ {},+ actor,+ );+ resolved = result.interaction as typeof current;+ if (result.continuationIssue) {+ continuationTarget = {+ id: result.continuationIssue.id,+ assigneeAgentId: result.continuationIssue.assigneeAgentId,+ status: result.continuationIssue.status,+ };+ }+ } else {+ resolved = (await interactions.rejectInteraction(+ { id: issue.id, companyId },+ params.interactionId,+ { reason: params.reason ?? undefined },+ actor,+ )) as typeof current;+ }++ await logPluginActivity({+ companyId,+ action: params.action === "accept"+ ? "issue.thread_interaction_accepted"+ : "issue.thread_interaction_rejected",+ entityType: "issue",+ entityId: issue.id,+ actor: { actorUserId: params.actorUserId },+ details: {+ identifier: issue.identifier,+ interactionId: resolved.id,+ interactionKind: resolved.kind,+ interactionStatus: resolved.status,+ },+ });++ queuePluginInteractionContinuationWakeup({+ issue: continuationTarget,+ interaction: resolved,+ actorUserId: params.actorUserId,+ source: `plugin:${pluginKey}:interaction.${params.action}`,+ });++ return { interaction: resolved as any, applied: true };+ },+ async listAttachments(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ if (!inCompany(await issues.getById(params.issueId), companyId)) return [];+ return (await issues.listAttachments(params.issueId)) as any;+ },+ async getAttachmentContent(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ const attachment = await issues.getAttachmentById(params.attachmentId);+ // Unknown and cross-company ids are deliberately indistinguishable to+ // the plugin: both return null (no existence oracle across companies).+ if (!attachment || attachment.companyId !== companyId) return null;++ const maxBytes = typeof params.maxBytes === "number" && params.maxBytes > 0 ? params.maxBytes : null;+ if (maxBytes !== null && attachment.byteSize > maxBytes) {+ throw new Error(+ `attachment ${attachment.id} is ${attachment.byteSize} bytes, over the ${maxBytes}-byte cap`,+ );+ }++ const object = await getStorageService().getObject(attachment.companyId, attachment.objectKey);+ const chunks: Buffer[] = [];+ let total = 0;+ for await (const chunk of object.stream) {+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ total += buf.length;+ // Defense in depth: enforce the cap during streaming too, so a+ // metadata/object size mismatch can never exceed the requested cap.+ if (maxBytes !== null && total > maxBytes) {+ object.stream.destroy();+ throw new Error(`attachment ${attachment.id} exceeded the ${maxBytes}-byte cap while reading`);+ }+ chunks.push(buf);+ }+ const bytes = Buffer.concat(chunks);++ await logPluginActivity({+ companyId,+ action: "issue.attachment.read",+ entityType: "issue",+ entityId: attachment.issueId,+ details: {+ attachmentId: attachment.id,+ byteSize: bytes.length,+ contentType: attachment.contentType,+ },+ });++ return {+ attachmentId: attachment.id,+ contentType: attachment.contentType,+ byteSize: bytes.length,+ sha256: attachment.sha256,+ originalFilename: attachment.originalFilename ?? null,+ contentBase64: bytes.toString("base64"),+ };+ },+ },++ approvals: {+ async list(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ const rows = await approvalSvc.list(companyId, params.status ?? undefined);+ // Match the web app's approval read surface: payloads are redacted so+ // the chat bridge never receives secrets the web app itself hides.+ return rows.map((approval) => redactApprovalPayload(approval)) as any;+ },+ async get(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ const approval = await approvalSvc.getById(params.approvalId);+ if (!approval || approval.companyId !== companyId) return null;+ return redactApprovalPayload(approval) as any;+ },+ async decide(params) {+ const companyId = ensureCompanyId(params.companyId);+ await ensurePluginAvailableForCompany(companyId);+ const existing = await approvalSvc.getById(params.approvalId);+ if (!existing || existing.companyId !== companyId) {+ throw new Error(`Approval "${params.approvalId}" not found`);+ }+ // Deciding an approval is a board-user action (the web app's approval+ // decision routes are board-only). Re-verify active membership at apply+ // time; never trust the plugin-supplied identity.+ if (!params.actorUserId) {+ throw new Error("actorUserId is required to decide an approval on behalf of a board user");+ }+ await requireActiveHumanMember(companyId, params.actorUserId);++ const { approval, applied } = params.action === "approve"+ ? await approvalSvc.approve(params.approvalId, params.actorUserId, params.decisionNote ?? null)+ : await approvalSvc.reject(params.approvalId, params.actorUserId, params.decisionNote ?? null);++ await logPluginActivity({+ companyId,+ action: params.action === "approve" ? "approval.approved" : "approval.rejected",+ entityType: "approval",+ entityId: approval.id,+ actor: { actorUserId: params.actorUserId },+ details: {+ type: approval.type,+ requestedByAgentId: approval.requestedByAgentId,+ applied,+ },+ });++ // Mirror the web app's approve/reject routes: wake the requesting agent+ // so it resumes after a chat-driven decision. Only on a fresh decision+ // (applied) and only when a requester agent exists.+ if (applied && approval.requestedByAgentId) {+ void heartbeat.wakeup(approval.requestedByAgentId, {+ source: "automation",+ triggerDetail: "system",+ reason: params.action === "approve" ? "approval_approved" : "approval_rejected",+ payload: {+ approvalId: approval.id,+ approvalStatus: approval.status,+ },+ requestedByActorType: "user",+ requestedByActorId: params.actorUserId,+ contextSnapshot: {+ source: `plugin:${pluginKey}:approval.${params.action}`,+ approvalId: approval.id,+ approvalStatus: approval.status,+ wakeReason: params.action === "approve" ? "approval_approved" : "approval_rejected",+ },+ }).catch((err) => logger.warn({+ err,+ approvalId: approval.id,+ requestedByAgentId: approval.requestedByAgentId,+ }, "failed to wake requester on plugin-relayed approval decision"));+ }++ return { approval: redactApprovalPayload(approval) as any, applied };+ },},issueDocuments: {