mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
fix(server): apply the issue interaction resolution policy to direct tool review decisions (#22656)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When an agent's tool call needs review, Paperclip creates a tool action request and an approval card on the task > - A person can decide it on the card (the issue thread path) or through `POST /api/tool-gateway/action-requests/:id/approve|decline` > - The issue thread path applies the interaction resolution policy, but the direct routes checked only company membership > - So the two paths could give different answers for the same review, for example in another member's private chat > - This pull request puts the human rule for tool reviews in one shared function and applies it to every human decision on a pending review > - The benefit is that the direct routes and the card always agree on who can decide a tool review ## Linked Issues or Issue Description Refs #22635 **What happened?** The direct approve and decline routes for tool action requests skipped the issue-interaction resolution policy. A member could decide a tool review that the issue thread path refuses, for example a review in a chat conversation that another member owns. **What did you expect to happen?** Both paths use the same policy and give the same result. **Steps to reproduce** Open a chat conversation as one member, let the agent request a reviewed tool call, then approve it through the direct route as a different member. The new test covers this case. **Impact** Access-control hardening for tool reviews. ## What Changed - Add `evaluateHumanToolReviewResolution`, `assertHumanToolReviewResolution` and `conversationInteractionResponderAllowed` to `server/src/services/issue-thread-interaction-resolution.ts`. The rule applies the personal-conversation visibility rule, the conversation owner rule and the existing audience evaluator (`evaluateIssueThreadInteractionResolverAudience`, as a governed action). - `commitToolActionReview` applies this rule inside its decision transaction, on the issue and interaction rows it already locks. Both the issue thread path and the direct routes reach it, so one rule decides for both. - The direct approve and decline routes call the same rule function first, for pending and settled reviews, before any state change or detail is returned (for example a cancelled request after a signature failure, expiry, or formal approval details). The in-transaction check stays the authoritative one. - A settled request with no task or interaction can be read only by the person who requested it; others get `404`. Only the explicit internal recovery flag skips the check. - A decision with no user identity is refused with `human_review_required`; the code no longer substitutes a placeholder identity. - The issue thread route uses `conversationInteractionResponderAllowed` for its existing conversation owner check. - Recovery of an already approved review passes an explicit internal flag and skips the human check, so interrupted executions still resume with no user action. ## Verification - New table test in `server/src/__tests__/tool-gateway.test.ts` mounts the real issue routes and the gateway routes on one database, for a chat owned by one member, a personal dashboard conversation and an ordinary task. For approve and decline it compares both paths for the owner and another member. It also checks settled reviews through the direct route, the recovery of an approved review, that a non-owner cannot cancel a review with an unverifiable signature or see expiry details, that a decision without a user is refused, and that a detached settled request is visible only to its requester. Before the fix the direct route let the other member approve a chat review and the action ran (`200`, `executed`). After the fix both paths refuse the other member for chats (`403`) and personal dashboards (`404`), both allow the other member for ordinary tasks, and both allow the owner. - `npx vitest run` on `tool-gateway`, `issue-thread-interaction-routes`, `agent-conversations`, `connection-management.integration`, `mcp-tasks` and `prompt-injection-gateway`: 497 tests pass. - `tsc --noEmit` for `server` passes. ## Risks - A member who is not the owner of a private chat can no longer approve or decline its tool reviews through the direct routes. The card already refused this. - Low risk otherwise. Ordinary task reviews have no addressee and stay open to non-viewer members, as before. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ffb300e22a
commit
574448e910
5 files changed
+256
-13
No files matched your search
@@ -57,6 +57,8 @@ import { resolveNativeRuntimeMcpSnapshot } from "../services/native-runtime/runt
|
||||
import type { ToolMcpGatewayTokenAction } from "@paperclipai/shared";
|
||||
import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js";
|
||||
import { mcpGatewayProtocolRoutes, toolGatewayRoutes } from "../routes/tool-gateway.js";
|
||||
import { issueRoutes } from "../routes/issues.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import {
|
||||
canonicalToolArguments,
|
||||
@@ -5739,6 +5741,147 @@ rl.on("line", (line) => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ scenario: "a chat owned by one member", outsiderAllowed: false, outsiderStatus: 403,
|
||||
issuePatch: (agentId: string) => ({ conversationAgentId: agentId, conversationUserId: "alice", conversationState: "active" as const }) },
|
||||
{ scenario: "a personal dashboard conversation", outsiderAllowed: false, outsiderStatus: 404,
|
||||
issuePatch: () => ({ originKind: "responsibility_dashboard", originId: "alice" }) },
|
||||
{ scenario: "an ordinary task", outsiderAllowed: true, outsiderStatus: 200,
|
||||
issuePatch: () => ({}) },
|
||||
])("gives the direct tool review routes and the issue thread path the same answer for $scenario", async ({ outsiderAllowed, outsiderStatus, issuePatch }) => {
|
||||
const company = await createCompany(db);
|
||||
const agent = await createAgent(db, company.id);
|
||||
const { issue, run } = await createIssueAndRun(db, company.id, agent.id);
|
||||
await createActiveMember(db, company.id, "alice");
|
||||
await createActiveMember(db, company.id, "bob");
|
||||
const patch = issuePatch(agent.id);
|
||||
if (Object.keys(patch).length > 0) await db.update(issues).set(patch).where(eq(issues.id, issue.id));
|
||||
const remote = await createRemoteMcpTool(db, company.id, { toolName: "send_note", riskLevel: "write" });
|
||||
await allowAllToolsForAgent(db, company.id, agent.id);
|
||||
await db.insert(toolPolicies).values({
|
||||
companyId: company.id,
|
||||
name: "Review note writes",
|
||||
policyType: "require_approval",
|
||||
selectors: { connectionId: remote.connection.id },
|
||||
priority: 10,
|
||||
});
|
||||
const gateway = createTestToolGatewayService(db, { remoteHttpRequest: async (_url, init) => {
|
||||
const body = JSON.parse(String(init.body)) as { id: string };
|
||||
return new Response(JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: "sent" }] } }),
|
||||
{ headers: { "content-type": "application/json" } });
|
||||
} });
|
||||
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
|
||||
const tool = (await gateway.listToolsForSession(session.token)).find((item) => item.connectionId === remote.connection.id)!;
|
||||
const requestReview = async () => {
|
||||
await gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: { key: "note", value: randomUUID() } })
|
||||
.then(() => { throw new Error("Expected the call to need review"); }, (error) => expectGatewayError(error, 409, "approval_required"));
|
||||
const [pending] = await db.select().from(toolActionRequests)
|
||||
.where(and(eq(toolActionRequests.companyId, company.id), eq(toolActionRequests.status, "pending")));
|
||||
return pending!;
|
||||
};
|
||||
const boardActor = (userId: string): Express.Request["actor"] => ({
|
||||
type: "board",
|
||||
userId,
|
||||
source: "session",
|
||||
companyIds: [company.id],
|
||||
memberships: [{ companyId: company.id, membershipRole: "member", status: "active" }],
|
||||
isInstanceAdmin: false,
|
||||
});
|
||||
const issueApp = (userId: string) => {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = boardActor(userId);
|
||||
next();
|
||||
});
|
||||
app.use("/api", issueRoutes(db, {} as never, {
|
||||
approveToolActionRequest: (input) => gateway.approveActionRequest(input),
|
||||
declineToolActionRequest: (input) => gateway.declineActionRequest(input),
|
||||
}));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
};
|
||||
const direct = (userId: string, actionRequestId: string, decision: "approve" | "decline") =>
|
||||
request(createGatewayRouteApp(db, gateway, boardActor(userId)))
|
||||
.post(`/api/tool-gateway/action-requests/${actionRequestId}/${decision}`)
|
||||
.send({ companyId: company.id });
|
||||
const outcomes = async (userId: string, decision: "approve" | "decline") => {
|
||||
const viaIssue = await requestReview();
|
||||
const issueStatus = (await request(issueApp(userId))
|
||||
.post(`/api/issues/${issue.id}/interactions/${viaIssue.interactionId}/${decision === "approve" ? "accept" : "reject"}`)
|
||||
.send({})).status;
|
||||
const viaDirect = await requestReview();
|
||||
const directStatus = (await direct(userId, viaDirect.id, decision)).status;
|
||||
const [after] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests)
|
||||
.where(eq(toolActionRequests.id, viaDirect.id));
|
||||
await db.update(toolActionRequests).set({ status: "expired" })
|
||||
.where(and(eq(toolActionRequests.companyId, company.id), eq(toolActionRequests.status, "pending")));
|
||||
return { issueAllowed: issueStatus < 300, directAllowed: directStatus < 300, directRequestStatus: after!.status };
|
||||
};
|
||||
|
||||
for (const decision of ["approve", "decline"] as const) {
|
||||
const outsider = await outcomes("bob", decision);
|
||||
expect(outsider.issueAllowed).toBe(outsiderAllowed);
|
||||
expect(outsider.directAllowed).toBe(outsiderAllowed);
|
||||
if (!outsiderAllowed) expect(outsider.directRequestStatus).toBe("pending");
|
||||
const owner = await outcomes("alice", decision);
|
||||
expect(owner).toMatchObject({ issueAllowed: true, directAllowed: true });
|
||||
}
|
||||
|
||||
const settled = await requestReview();
|
||||
expect((await direct("alice", settled.id, "approve")).status).toBe(200);
|
||||
expect((await direct("bob", settled.id, "approve")).status).toBe(outsiderAllowed ? 200 : outsiderStatus);
|
||||
expect((await direct("bob", settled.id, "decline")).status).toBe(outsiderAllowed ? 409 : outsiderStatus);
|
||||
|
||||
await db.update(toolActionRequests).set({ status: "approved" }).where(eq(toolActionRequests.id, settled.id));
|
||||
await expect(gateway.approveActionRequest({
|
||||
companyId: company.id, actionRequestId: settled.id, actor: { userId: "alice" }, recoveringApprovedReview: true,
|
||||
})).resolves.toBeDefined();
|
||||
|
||||
const unverifiable = await requestReview();
|
||||
await db.update(toolActionRequests).set({ signedArguments: "unverifiable" }).where(eq(toolActionRequests.id, unverifiable.id));
|
||||
const outsiderOnUnverifiable = await direct("bob", unverifiable.id, "approve");
|
||||
if (!outsiderAllowed) {
|
||||
expect(outsiderOnUnverifiable.status).toBe(outsiderStatus);
|
||||
const [untouched] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests)
|
||||
.where(eq(toolActionRequests.id, unverifiable.id));
|
||||
expect(untouched!.status).toBe("pending");
|
||||
const expired = await requestReview();
|
||||
await db.update(toolActionRequests).set({ expiresAt: new Date(Date.now() - 60_000) }).where(eq(toolActionRequests.id, expired.id));
|
||||
const outsiderOnExpired = await direct("bob", expired.id, "approve");
|
||||
expect(outsiderOnExpired.status).toBe(outsiderStatus);
|
||||
expect(JSON.stringify(outsiderOnExpired.body)).not.toMatch(/expire|approvalId|target_changed/i);
|
||||
await db.update(toolActionRequests).set({ status: "expired" }).where(eq(toolActionRequests.id, expired.id));
|
||||
}
|
||||
await db.update(toolActionRequests).set({ status: "expired" }).where(eq(toolActionRequests.id, unverifiable.id));
|
||||
|
||||
const anonymous = await requestReview();
|
||||
await expect(gateway.approveActionRequest({ companyId: company.id, actionRequestId: anonymous.id, actor: { userId: null } }))
|
||||
.rejects.toMatchObject({ status: 403 });
|
||||
await expect(gateway.declineActionRequest({ companyId: company.id, actionRequestId: anonymous.id, actor: { userId: null } }))
|
||||
.rejects.toMatchObject({ status: 403 });
|
||||
const [stillPending] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests)
|
||||
.where(eq(toolActionRequests.id, anonymous.id));
|
||||
expect(stillPending!.status).toBe("pending");
|
||||
await db.update(toolActionRequests).set({ status: "expired" }).where(eq(toolActionRequests.id, anonymous.id));
|
||||
|
||||
const legacyApproved = await requestReview();
|
||||
await db.update(toolActionRequests).set({ status: "approved", decidedAt: new Date(), decidedByUserId: null, resolvedByUserId: null })
|
||||
.where(eq(toolActionRequests.id, legacyApproved.id));
|
||||
await expect(gateway.recoverApprovedActionReviews(company.id)).resolves.toMatchObject({ retry: false });
|
||||
const [recovered] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests)
|
||||
.where(eq(toolActionRequests.id, legacyApproved.id));
|
||||
expect(recovered!.status).not.toBe("approved");
|
||||
await expect(gateway.recoverApprovedActionReviews(company.id)).resolves.toMatchObject({ retry: false });
|
||||
|
||||
const detached = await requestReview();
|
||||
expect((await direct("alice", detached.id, "approve")).status).toBe(200);
|
||||
await db.update(toolActionRequests).set({ issueId: null, interactionId: null, requestedByUserId: "alice", decidedByUserId: null, resolvedByUserId: null })
|
||||
.where(eq(toolActionRequests.id, detached.id));
|
||||
expect((await direct("bob", detached.id, "approve")).status).toBe(404);
|
||||
expect((await direct("alice", detached.id, "approve")).status).toBe(200);
|
||||
});
|
||||
|
||||
it("denies agents without responsible-user authority from runtime control and gateway audit routes", async () => {
|
||||
const company = await createCompany(db);
|
||||
const agent = await createAgent(db, company.id);
|
||||
|
||||
@@ -406,6 +406,7 @@ import {
|
||||
import {
|
||||
addressedHumanOnlyDenialMessage,
|
||||
evaluateIssueThreadInteractionResolverAudience,
|
||||
conversationInteractionResponderAllowed,
|
||||
issueThreadInteractionAttentionAgentAllowed,
|
||||
type IssueThreadInteractionResolverAudienceDecision,
|
||||
type IssueThreadInteractionResolverRestriction,
|
||||
@@ -6426,7 +6427,7 @@ export function issueRoutes(
|
||||
interactionId: string,
|
||||
relayedHumanUserId?: string | null,
|
||||
) {
|
||||
if (issue.conversationAgentId && req.actor.type === "board" && req.actor.userId !== issue.conversationUserId) {
|
||||
if (req.actor.type === "board" && !conversationInteractionResponderAllowed(issue, req.actor.userId)) {
|
||||
throw forbidden("Only the conversation owner can respond to chat interactions");
|
||||
}
|
||||
// Actor-only gates deliberately precede the interaction lookup. An actor
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
} from "@paperclipai/shared";
|
||||
import { normalizeIssueThreadInteractionResolverPolicy } from "@paperclipai/shared";
|
||||
import { HttpError } from "../errors.js";
|
||||
import { dashboardConversationReadable, type DashboardConversationFields } from "./responsibility-privacy.js";
|
||||
|
||||
export const ISSUE_THREAD_INTERACTION_RESOLUTION_DENIAL_CODES = [
|
||||
"interaction_not_found",
|
||||
@@ -18,6 +19,7 @@ export const ISSUE_THREAD_INTERACTION_RESOLUTION_DENIAL_CODES = [
|
||||
"interaction_issue_closed",
|
||||
"interaction_governed_action_denied",
|
||||
"review_policy_denied",
|
||||
"interaction_conversation_owner_required",
|
||||
] as const;
|
||||
|
||||
export type IssueThreadInteractionResolutionDenialCode =
|
||||
@@ -427,3 +429,52 @@ export function issueThreadInteractionAttentionAgentAllowed(input: {
|
||||
governedAction: input.governedAction,
|
||||
}).allowed;
|
||||
}
|
||||
|
||||
export function conversationInteractionResponderAllowed(
|
||||
issue: { conversationAgentId?: string | null; conversationUserId?: string | null },
|
||||
userId: string | null | undefined,
|
||||
) {
|
||||
return !issue.conversationAgentId || (Boolean(userId) && userId === issue.conversationUserId);
|
||||
}
|
||||
|
||||
export type HumanToolReviewResolutionDecision =
|
||||
| { allowed: true }
|
||||
| {
|
||||
allowed: false;
|
||||
status: 403 | 404 | 422;
|
||||
code: IssueThreadInteractionResolutionDenialCode;
|
||||
message: string;
|
||||
details?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export function evaluateHumanToolReviewResolution(input: {
|
||||
userId: string;
|
||||
issue: DashboardConversationFields & { conversationAgentId?: string | null; conversationUserId?: string | null };
|
||||
interaction: IssueThreadInteractionResolverAudienceInput["interaction"];
|
||||
}): HumanToolReviewResolutionDecision {
|
||||
if (!dashboardConversationReadable({ type: "board", userId: input.userId }, input.issue)) {
|
||||
return { allowed: false, status: 404, code: "interaction_not_found", message: "Issue not found" };
|
||||
}
|
||||
if (!conversationInteractionResponderAllowed(input.issue, input.userId)) {
|
||||
return {
|
||||
allowed: false,
|
||||
status: 403,
|
||||
code: "interaction_conversation_owner_required",
|
||||
message: "Only the conversation owner can respond to chat interactions",
|
||||
};
|
||||
}
|
||||
const decision = evaluateIssueThreadInteractionResolverAudience({
|
||||
actor: { type: "user", userId: input.userId },
|
||||
interaction: input.interaction,
|
||||
governedAction: true,
|
||||
});
|
||||
if (decision.allowed) return { allowed: true };
|
||||
return { allowed: false, status: decision.status, code: decision.code, message: decision.message, details: decision.details };
|
||||
}
|
||||
|
||||
export function assertHumanToolReviewResolution(input: Parameters<typeof evaluateHumanToolReviewResolution>[0]) {
|
||||
const decision = evaluateHumanToolReviewResolution(input);
|
||||
if (!decision.allowed) {
|
||||
throw issueThreadInteractionResolutionError(decision.status, decision.code, decision.message, decision.details);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
type Db,
|
||||
} from "@paperclipai/db";
|
||||
import { conflict, forbidden, notFound } from "../errors.js";
|
||||
import { assertIssueThreadInteractionResolverAudience } from "./issue-thread-interaction-resolution.js";
|
||||
import { assertHumanToolReviewResolution } from "./issue-thread-interaction-resolution.js";
|
||||
import { emitConnectionInvoked } from "./connector-telemetry.js";
|
||||
import { toolAccessPolicyService } from "./tool-access-policy.js";
|
||||
import {
|
||||
@@ -34,8 +34,9 @@ export async function commitToolActionReview(
|
||||
actor: { agentId?: string | null; userId?: string | null };
|
||||
},
|
||||
) {
|
||||
if (input.actor.agentId)
|
||||
throw forbidden("Only a human can resolve a tool review");
|
||||
if (input.actor.agentId || !input.actor.userId)
|
||||
throw forbidden("Only a human can resolve a tool review", { code: "human_review_required" });
|
||||
const userId = input.actor.userId;
|
||||
const [source] = await db
|
||||
.select()
|
||||
.from(toolActionRequests)
|
||||
@@ -133,10 +134,11 @@ export async function commitToolActionReview(
|
||||
payload.toolAction.invocationId !== current.invocationId
|
||||
)
|
||||
throw conflict("Tool review context does not match");
|
||||
assertIssueThreadInteractionResolverAudience({
|
||||
actor: { type: "user", userId: input.actor.userId ?? "board" },
|
||||
if (!issue) throw conflict("Tool review context does not match");
|
||||
assertHumanToolReviewResolution({
|
||||
userId,
|
||||
issue,
|
||||
interaction,
|
||||
governedAction: true,
|
||||
});
|
||||
if (interaction.status !== "pending")
|
||||
throw conflict("This review has already been resolved");
|
||||
@@ -148,8 +150,8 @@ export async function commitToolActionReview(
|
||||
.update(toolActionRequests)
|
||||
.set({
|
||||
status: input.decision,
|
||||
resolvedByUserId: input.actor.userId ?? "board",
|
||||
decidedByUserId: input.actor.userId ?? "board",
|
||||
resolvedByUserId: userId,
|
||||
decidedByUserId: userId,
|
||||
decidedAt: now,
|
||||
resolvedAt: now,
|
||||
updatedAt: now,
|
||||
@@ -165,7 +167,7 @@ export async function commitToolActionReview(
|
||||
companyId: input.companyId,
|
||||
actionRequestId: current.id,
|
||||
body: { approvalThreshold: 1, priority: 40, argumentMode: "action" },
|
||||
actor: { userId: input.actor.userId ?? "board" },
|
||||
actor: { userId: userId },
|
||||
});
|
||||
}
|
||||
await tx
|
||||
@@ -193,7 +195,7 @@ export async function commitToolActionReview(
|
||||
.update(issueThreadInteractions)
|
||||
.set({
|
||||
status: input.decision === "approved" ? "accepted" : "rejected",
|
||||
resolvedByUserId: input.actor.userId ?? "board",
|
||||
resolvedByUserId: userId,
|
||||
resolvedAt: now,
|
||||
updatedAt: now,
|
||||
result:
|
||||
@@ -226,7 +228,7 @@ export async function commitToolActionReview(
|
||||
{
|
||||
companyId: input.companyId,
|
||||
actorType: "user",
|
||||
actorId: input.actor.userId ?? "board",
|
||||
actorId: userId,
|
||||
action:
|
||||
input.decision === "approved"
|
||||
? "issue.thread_interaction_accepted"
|
||||
|
||||
@@ -264,6 +264,7 @@ import {
|
||||
import { toolDiscoveryScheduler, ToolDiscoveryBusyError } from "./tool-discovery-scheduler.js";
|
||||
import { commitToolActionReview } from "./tool-action-review.js";
|
||||
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
|
||||
import { evaluateHumanToolReviewResolution } from "./issue-thread-interaction-resolution.js";
|
||||
import {
|
||||
createToolRuntimeSupervisor,
|
||||
ToolRuntimeSupervisorError,
|
||||
@@ -2233,6 +2234,41 @@ export function createToolGatewayService(
|
||||
};
|
||||
}
|
||||
|
||||
async function assertHumanMayActOnToolReview(
|
||||
actionRequest: typeof toolActionRequests.$inferSelect,
|
||||
userId: string | null | undefined,
|
||||
) {
|
||||
if (!userId) {
|
||||
throw new ToolGatewayHttpError(403, "Only a human can resolve a tool review", "human_review_required");
|
||||
}
|
||||
if (!actionRequest.issueId || !actionRequest.interactionId) {
|
||||
if (actionRequest.status === "pending"
|
||||
|| [actionRequest.requestedByUserId, actionRequest.decidedByUserId, actionRequest.resolvedByUserId].includes(userId)) return;
|
||||
throw new ToolGatewayHttpError(404, "Tool action request not found", "action_request_not_found");
|
||||
}
|
||||
const [interaction] = await db
|
||||
.select()
|
||||
.from(issueThreadInteractions)
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.id, actionRequest.interactionId),
|
||||
eq(issueThreadInteractions.companyId, actionRequest.companyId),
|
||||
eq(issueThreadInteractions.issueId, actionRequest.issueId),
|
||||
))
|
||||
.limit(1);
|
||||
const [issue] = await db
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(and(eq(issues.id, actionRequest.issueId), eq(issues.companyId, actionRequest.companyId)))
|
||||
.limit(1);
|
||||
if (!interaction || !issue) {
|
||||
throw new ToolGatewayHttpError(404, "Tool action request not found", "action_request_not_found");
|
||||
}
|
||||
const decision = evaluateHumanToolReviewResolution({ userId, issue, interaction });
|
||||
if (!decision.allowed) {
|
||||
throw new ToolGatewayHttpError(decision.status, decision.message, decision.code);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveRunContext(input: {
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
@@ -12726,7 +12762,7 @@ export function createToolGatewayService(
|
||||
const { request, invocation, payload } = prepared;
|
||||
if (!isTestOriginInvocation(invocation) && payload.executionOnApprove !== true) return false;
|
||||
await this.approveActionRequest({ companyId: request.companyId, actionRequestId: request.id,
|
||||
actor: { userId: request.decidedByUserId ?? request.resolvedByUserId } });
|
||||
actor: { userId: request.decidedByUserId ?? request.resolvedByUserId }, recoveringApprovedReview: true });
|
||||
const [remaining] = await db.select({ status: toolActionRequests.status, errorCode: toolInvocations.errorCode })
|
||||
.from(toolActionRequests).innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
|
||||
.where(eq(toolActionRequests.id, request.id));
|
||||
@@ -12748,6 +12784,7 @@ export function createToolGatewayService(
|
||||
|
||||
async approveActionRequest(input: {
|
||||
companyId: string;
|
||||
recoveringApprovedReview?: boolean;
|
||||
rememberAction?: boolean;
|
||||
issueId?: string;
|
||||
interactionId?: string;
|
||||
@@ -12772,6 +12809,7 @@ export function createToolGatewayService(
|
||||
"action_request_not_found",
|
||||
);
|
||||
}
|
||||
if (!input.recoveringApprovedReview) await assertHumanMayActOnToolReview(actionRequest, input.actor.userId);
|
||||
const [invocation] = await db
|
||||
.select()
|
||||
.from(toolInvocations)
|
||||
@@ -13048,6 +13086,14 @@ export function createToolGatewayService(
|
||||
reason?: string;
|
||||
actor: { agentId?: string | null; userId?: string | null };
|
||||
}) {
|
||||
if (!input.actor.agentId) {
|
||||
const [actionRequest] = await db
|
||||
.select()
|
||||
.from(toolActionRequests)
|
||||
.where(and(eq(toolActionRequests.id, input.actionRequestId), eq(toolActionRequests.companyId, input.companyId)))
|
||||
.limit(1);
|
||||
if (actionRequest) await assertHumanMayActOnToolReview(actionRequest, input.actor.userId);
|
||||
}
|
||||
const updated = await commitToolActionReview(db, {
|
||||
...input,
|
||||
decision: "rejected",
|
||||
|
||||
Reference in new issue
Block a user