mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-29 12:59:13 +01:00
feat(connections): connect services from native task feeds (#13058)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use connections to reach external services. > - A fresh native task can have no service tools installed. > - The agent needs a way to discover services and ask the responsible person for access. > - This pull request brings the existing connection-intent flow into native task execution. > - The person can connect from the task, and the agent can continue with updated tools. ## Linked Issues or Issue Description **Subsystem affected** Native runner tool authority, connection intents, task interactions, and shared connection setup. **Problem or motivation** A task that needs an unconnected service cannot finish its work. Leaving the task to configure access also loses context. A resolved request must survive a restart and resume the correct agent once. **Proposed solution** Expose connection discovery and access requests as server-owned native tools. Render a durable task card and use the shared setup dialog. Persist outcome delivery and start a fresh provider session after access is ready. **Alternatives considered** Sending the person to the Connections page adds navigation and does not solve continuation. Polling for authorization consumes runs and can create duplicate requests. **Roadmap alignment** This extends the existing connection-intent runtime and setup experience. It reuses the shared access model and the native runner. Related: #12345, #12347. The service-slug fix in #12906 is related but separate. Companion evaluation PR: https://github.com/paperclipai/paperclip-evals/pull/21. ## What Changed - Expose `connections_search` and `connection_request` with server-bound company, task, agent, and responsible user. Preserve the legacy entry points. - Discover catalog services and authorized custom connections. Check installation, identity, health, and executable permissions before reporting ready. - Keep pending cards through ordinary messages. Reuse requests and retire stale ownership. Put Connect at the right of Not now. - Reuse the shared setup flow in a task dialog. Keep access additive and default to the requesting agent. Recover from cancelled or blocked OAuth windows with a new-tab fallback. - Persist outcome delivery with an idempotent wake key. Resume in a fresh session and recheck ownership before dispatch. - Add native browser fixtures, offline Storybook states, server contracts, and evaluation fixtures. Update guidance and documentation. ## Verification - `pnpm build`: passed after replaying the change on current master. - `pnpm -r typecheck`: passed. - `pnpm check:token-gates`: passed. - `pnpm --filter @paperclipai/ui build-storybook`: passed. - New continuation-policy regression cases: 16 passed. - Docker-backed PostgreSQL regressions passed for requester-only OAuth access, assignment-only expiry, terminal expiry, and credential-free setup metadata. - Shared setup and task-card UI tests: 121 passed, including configured MCP reconnect URL recovery and preserving user edits across refetch. - Storybook browser checks: all 119 passed on the latest reconnect fix. - `pnpm test:run`: 4,734 tests passed in the first server group, but embedded PostgreSQL startup failures and resulting cleanup errors prevented a complete local pass. All Linux CI lanes passed on the latest reviewed commit. One external-object route test returned an unexplained 500 on the first run; it passed twice locally and the failed shard passed on retry without code changes. - Earlier feature-checkout evidence: three deterministic native browser journeys passed, including restart delivery and an actual fixture tool result. Legacy scripted coverage also passed. All 59 added stories were inspected in light and dark themes. - Live Notion testing recorded successful provider reads. The manual test used a local-trusted instance. It does not prove authenticated/cloud deployment or every provider journey. - Native browser rerun reached the embedded PostgreSQL startup limit before bootstrap, so the latest checkout’s full native browser journey remains unverified. Both OAuth page/task regression cases passed against isolated Docker-backed PostgreSQL 17. They verify no premature task access, requester-only completion, additive retries, and reconnect preservation. - Applied both new migrations twice to isolated PostgreSQL 17. Foreign keys remained intact, duplicate active delivery keys were rejected, and failed delivery records did not block retries. Reviewer path: start a fresh test drive, enable the native runner, use an agent that can perform work directly, and ask it to summarize a Notion page. Connect from the card, then verify the resumed provider call and source-linked answer. The default test-drive CEO is instructed to delegate, so it can introduce an unrelated hiring step. ## Risks - Two additive migrations create durable deliveries and a partial unique wake index. They are idempotent. The wake index can require a maintenance window on large tables because migrations run in a transaction. - OAuth and continuation cross asynchronous boundaries. Tests cover ownership changes, retries, additive access, and restart delivery; live provider behavior still varies. - The latest requester-scope fix has not yet been exercised through live OAuth. GitHub, API-key, authenticated-user, and all recovery journeys are not claimed as verified. ## Model Used OpenAI GPT-6-based Codex assisted with implementation, tests, and review using tools and code execution. The runtime does not expose the exact model version, context window, or reasoning setting. Live evaluation used `gpt-5.6-luna`; manual native testing used `gpt-5.6-sol`. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used and disclosed unavailable runtime details - [x] I have checked ROADMAP.md and confirmed this extends existing connection work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR following the feature issue template - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket id - [ ] I have run all required tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
5128b4f323
commit
e095b84dab
67 files changed
+88330
-327
No files matched your search
@@ -0,0 +1,120 @@
|
||||
import { connectionIntentService } from "./connection-intents.js";
|
||||
import { and, eq, isNull, lte, asc, notInArray } from "drizzle-orm";
|
||||
import { connectionIntentDeliveries, issueThreadInteractions, issues, agentWakeupRequests, companyMemberships, type Db } from "@paperclipai/db";
|
||||
import type { heartbeatService } from "./heartbeat.js";
|
||||
type Heartbeat = ReturnType<typeof heartbeatService>;
|
||||
|
||||
export async function wakeConnectionIntentAfterResolution(
|
||||
heartbeat: Pick<Heartbeat, "wakeup">,
|
||||
input: {
|
||||
loaded: {
|
||||
issue: { id: string; assigneeAgentId: string | null; status: string };
|
||||
interaction: { id: string; resolvedAt?: string | Date | null };
|
||||
};
|
||||
status: string;
|
||||
actorId: string;
|
||||
},
|
||||
) {
|
||||
const agentId = input.loaded.issue.assigneeAgentId;
|
||||
if (!agentId || !["in_progress", "in_review"].includes(input.loaded.issue.status)) return;
|
||||
const resolvedAt = input.loaded.interaction.resolvedAt;
|
||||
const interactionResolvedAt = resolvedAt instanceof Date ? resolvedAt.toISOString() : resolvedAt;
|
||||
await heartbeat.wakeup(agentId, {
|
||||
source: "automation",
|
||||
triggerDetail: "system",
|
||||
reason: "issue_commented",
|
||||
payload: {
|
||||
issueId: input.loaded.issue.id,
|
||||
interactionId: input.loaded.interaction.id,
|
||||
interactionKind: "connection_intent",
|
||||
interactionStatus: input.status,
|
||||
mutation: "interaction",
|
||||
},
|
||||
idempotencyKey: `connection-intent:${input.loaded.interaction.id}:${input.status}`,
|
||||
requestedByActorType: "user",
|
||||
requestedByActorId: input.actorId,
|
||||
contextSnapshot: {
|
||||
issueId: input.loaded.issue.id,
|
||||
taskId: input.loaded.issue.id,
|
||||
interactionId: input.loaded.interaction.id,
|
||||
interactionKind: "connection_intent",
|
||||
interactionStatus: input.status,
|
||||
mutation: "interaction",
|
||||
wakeReason: "issue_commented",
|
||||
source: "connection_intent.resolved",
|
||||
...(interactionResolvedAt
|
||||
? { interactionResolvedAt }
|
||||
: {}),
|
||||
forceFreshSession: true,
|
||||
},
|
||||
issueStateGuard: {
|
||||
statuses: ["in_progress", "in_review"],
|
||||
assigneeAgentId: agentId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function connectionIntentDeliveryService(db: Db, heartbeat: Pick<Heartbeat, "wakeup">) {
|
||||
async function deliver(interactionId: string) {
|
||||
// Deterministic acceptance-test failpoint: preserve committed outcomes across a server restart.
|
||||
if (process.env.NODE_ENV === "test" && process.env.PAPERCLIP_TEST_CONNECTION_DELIVERY_HOLD === "1") return;
|
||||
const now = new Date();
|
||||
// The retry deadline is also the worker lease. A crashed worker is reclaimed.
|
||||
const [claimed] = await db.update(connectionIntentDeliveries)
|
||||
.set({ nextAttemptAt: new Date(now.getTime() + 60_000) })
|
||||
.where(and(eq(connectionIntentDeliveries.interactionId, interactionId), isNull(connectionIntentDeliveries.deliveredAt), lte(connectionIntentDeliveries.nextAttemptAt, now))).returning();
|
||||
if (!claimed) return;
|
||||
const [loaded] = await db.select({ interaction: issueThreadInteractions, issue: issues })
|
||||
.from(issueThreadInteractions).innerJoin(issues, eq(issues.id, issueThreadInteractions.issueId))
|
||||
.where(and(eq(issueThreadInteractions.id, interactionId), eq(issueThreadInteractions.companyId, claimed.companyId), eq(issues.companyId, claimed.companyId)));
|
||||
const interaction = loaded?.interaction;
|
||||
const payload = interaction?.payload as { requestingAgentId?: string; serviceSlug?: string } | undefined;
|
||||
if (!loaded || !interaction || !["accepted", "rejected"].includes(interaction.status)
|
||||
|| ["done", "cancelled"].includes(loaded.issue.status) || loaded.issue.assigneeAgentId !== payload?.requestingAgentId) {
|
||||
await db.update(connectionIntentDeliveries).set({ deliveredAt: new Date() }).where(eq(connectionIntentDeliveries.interactionId, interactionId));
|
||||
return;
|
||||
}
|
||||
const userId = interaction.addresseeUserId;
|
||||
if (userId !== "local-board") {
|
||||
const [membership] = await db.select().from(companyMemberships).where(and(
|
||||
eq(companyMemberships.companyId, claimed.companyId), eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.principalId, userId ?? ""), eq(companyMemberships.status, "active"),
|
||||
)).limit(1);
|
||||
if (!membership?.membershipRole || membership.membershipRole === "viewer") {
|
||||
await db.update(connectionIntentDeliveries).set({ deliveredAt: new Date() }).where(eq(connectionIntentDeliveries.interactionId, interactionId));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (interaction.status === "accepted") {
|
||||
const ready = await connectionIntentService(db).usableConnectionForAgent({ companyId: claimed.companyId,
|
||||
agentId: payload!.requestingAgentId!, responsibleUserId: userId!, serviceSlug: payload!.serviceSlug! });
|
||||
if (!ready) return;
|
||||
}
|
||||
if (!["in_progress", "in_review"].includes(loaded.issue.status)) return;
|
||||
const durableWake = () => db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, claimed.companyId),
|
||||
eq(agentWakeupRequests.idempotencyKey, `connection-intent:${interactionId}:${interaction.status}`),
|
||||
notInArray(agentWakeupRequests.status, ["skipped", "failed", "cancelled"]),
|
||||
)).limit(1);
|
||||
// Check before dispatch: the previous worker may have crashed after enqueueing.
|
||||
if (!(await durableWake()).length) {
|
||||
try {
|
||||
await wakeConnectionIntentAfterResolution(heartbeat, { loaded, status: interaction.status, actorId: interaction.resolvedByUserId ?? interaction.addresseeUserId! });
|
||||
} catch (error) {
|
||||
// The unique wake key also protects overlapping leases. Other failures retry.
|
||||
if (!(await durableWake()).length) throw error;
|
||||
}
|
||||
}
|
||||
if ((await durableWake()).length) {
|
||||
await db.update(connectionIntentDeliveries).set({ deliveredAt: new Date() }).where(eq(connectionIntentDeliveries.interactionId, interactionId));
|
||||
}
|
||||
}
|
||||
return { deliver, tryDeliver: async (id: string) => { try { await deliver(id); } catch { /* Persisted delivery remains due after its lease. */ } }, sweepPending: async () => {
|
||||
const rows = await db.select().from(connectionIntentDeliveries).where(and(isNull(connectionIntentDeliveries.deliveredAt), lte(connectionIntentDeliveries.nextAttemptAt, new Date())))
|
||||
.orderBy(asc(connectionIntentDeliveries.nextAttemptAt)).limit(50);
|
||||
let failed = 0;
|
||||
for (const row of rows) { try { await deliver(row.interactionId); } catch { failed += 1; } }
|
||||
return { scanned: rows.length, failed };
|
||||
}};
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { and, eq } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
toolConnections,
|
||||
toolCatalogEntries,
|
||||
companyMemberships,
|
||||
heartbeatRuns,
|
||||
issueThreadInteractions,
|
||||
@@ -12,8 +14,9 @@ import {
|
||||
CONNECTABLE_APP_DEFINITIONS,
|
||||
connectionIntentPayloadSchema,
|
||||
getAvailableConnectionMethods,
|
||||
isToolConnectionAttentionHealth,
|
||||
type ConnectionSearchResultItem,
|
||||
getAppStoreDefinition,
|
||||
getConnectableAppDefinition,
|
||||
type ConnectionIntentInteraction,
|
||||
type ConnectionIntentSetupOptions,
|
||||
type ConnectionRequestResult,
|
||||
@@ -25,8 +28,11 @@ import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import type { RuntimeToolsTokenClaims } from "../runtime-tools-token.js";
|
||||
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
|
||||
import { toolAccessService } from "./tool-access.js";
|
||||
import { captureRunIdentity } from "./run-identity.js";
|
||||
import { resolveManagedGitHubIdentitySelection } from "./git-credentials.js";
|
||||
|
||||
type ConnectionRunClaims = Pick<RuntimeToolsTokenClaims, "sub" | "company_id" | "run_id" | "responsible_user_id">;
|
||||
|
||||
type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
@@ -47,14 +53,12 @@ function sourceSlugForConnection(
|
||||
connection: ToolConnection,
|
||||
applications: ReadonlyMap<string, ToolApplication>,
|
||||
) {
|
||||
return text(connection.config?.sourceTemplateKey)
|
||||
const source = text(connection.config?.sourceTemplateKey)
|
||||
?? text(connection.transportConfig?.sourceTemplateKey)
|
||||
?? sourceSlugForApplication(applications.get(connection.applicationId));
|
||||
return source && getAppStoreDefinition(source) ? source : `connection:${connection.id}`;
|
||||
}
|
||||
|
||||
function displayDescription(app: (typeof CONNECTABLE_APP_DEFINITIONS)[number]) {
|
||||
return text(app.description) ?? null;
|
||||
}
|
||||
|
||||
export function connectionIntentService(db: Db) {
|
||||
const interactions = issueThreadInteractionService(db);
|
||||
@@ -118,8 +122,8 @@ export function connectionIntentService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRunContext(claims: RuntimeToolsTokenClaims) {
|
||||
const run = await db
|
||||
async function loadRunContext(claims: ConnectionRunClaims) {
|
||||
let run = await db
|
||||
.select({
|
||||
id: heartbeatRuns.id,
|
||||
companyId: heartbeatRuns.companyId,
|
||||
@@ -139,6 +143,11 @@ export function connectionIntentService(db: Db) {
|
||||
|| (!run.activeIdentityContextId && run.responsibleUserId !== claims.responsible_user_id)
|
||||
) throw forbidden("Runtime tool token does not match its heartbeat run");
|
||||
if (run.status !== "running") throw forbidden("Runtime tool token is no longer active");
|
||||
if (run.activeIdentityContextId) {
|
||||
const current = await captureRunIdentity(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id });
|
||||
run = { ...run, responsibleUserId: current.run.responsibleUserId };
|
||||
}
|
||||
if (!run.responsibleUserId) throw forbidden("This task needs a responsible user to connect a service");
|
||||
const snapshot = record(run.contextSnapshot);
|
||||
const issueId = text(snapshot?.issueId) ?? text(snapshot?.taskId);
|
||||
if (!issueId) throw unprocessable("Connection requests require a task-bound heartbeat run");
|
||||
@@ -171,6 +180,7 @@ export function connectionIntentService(db: Db) {
|
||||
) {
|
||||
throw forbidden("Responsible user is no longer authorized for company write access");
|
||||
}
|
||||
if (issue.assigneeAgentId !== agent.id) throw conflict("The requesting agent no longer owns this task");
|
||||
if (issue.status === "done" || issue.status === "cancelled") {
|
||||
throw conflict("Connection requests cannot be created on a closed task");
|
||||
}
|
||||
@@ -199,21 +209,23 @@ export function connectionIntentService(db: Db) {
|
||||
const inventory = input.inventory ?? await connectionInventory(input.companyId);
|
||||
const matching = inventory.connections.filter((connection) =>
|
||||
sourceSlugForConnection(connection, inventory.applicationsById) === input.serviceSlug
|
||||
&& connection.status === "active"
|
||||
&& connection.enabled
|
||||
&& connection.status !== "archived"
|
||||
);
|
||||
if (matching.length === 0) return null;
|
||||
if (input.serviceSlug === "github") {
|
||||
const selection = await resolveManagedGitHubIdentitySelection(db, input.companyId, {
|
||||
agentId: input.agentId,
|
||||
responsibleUserId: input.responsibleUserId,
|
||||
});
|
||||
return selection.grant
|
||||
? matching.find((connection) => connection.id === selection.grant!.connectionId) ?? null
|
||||
: null;
|
||||
}
|
||||
const effective = await access.getEffectiveProfilesForAgent(input.companyId, input.agentId);
|
||||
const installedIds = new Set(effective.installedConnections.map((connection) => connection.id));
|
||||
const permittedIds = new Set(effective.allowedTools.map((tool) => tool.connectionId));
|
||||
const usable = (connection: ToolConnection | undefined) => connection
|
||||
&& installedIds.has(connection.id) && permittedIds.has(connection.id)
|
||||
&& connection.status === "active" && connection.enabled
|
||||
&& ["mcp_remote", "local_stdio"].includes(connection.transport)
|
||||
&& !isToolConnectionAttentionHealth(connection.healthStatus) ? connection : null;
|
||||
if (input.serviceSlug === "github") {
|
||||
const selection = await resolveManagedGitHubIdentitySelection(db, input.companyId, {
|
||||
agentId: input.agentId, responsibleUserId: input.responsibleUserId,
|
||||
});
|
||||
return usable(matching.find((connection) => connection.id === selection.grant?.connectionId));
|
||||
}
|
||||
const installed = matching.filter((connection) => installedIds.has(connection.id));
|
||||
const grantsByConnection = await Promise.all(installed.map(async (connection) => ({
|
||||
connection,
|
||||
@@ -228,7 +240,7 @@ export function connectionIntentService(db: Db) {
|
||||
.map((grant) => ({ connection, grant })));
|
||||
if (dedicated.length > 0) {
|
||||
const active = dedicated.filter(({ grant }) => grant.status === "active");
|
||||
return active.length === 1 ? active[0]!.connection : null;
|
||||
return active.length === 1 ? usable(active[0]!.connection) : null;
|
||||
}
|
||||
|
||||
const personal = grantsByConnection.flatMap(({ connection, grants }) => grants
|
||||
@@ -236,68 +248,121 @@ export function connectionIntentService(db: Db) {
|
||||
.map((grant) => ({ connection, grant })));
|
||||
if (personal.length > 0) {
|
||||
const active = personal.filter(({ grant }) => grant.status === "active");
|
||||
return active.length === 1 ? active[0]!.connection : null;
|
||||
return active.length === 1 ? usable(active[0]!.connection) : null;
|
||||
}
|
||||
|
||||
const organization = grantsByConnection.flatMap(({ connection, grants }) => grants
|
||||
.filter((grant) => grant.kind === "organization")
|
||||
.map((grant) => ({ connection, grant })));
|
||||
const activeOrganization = organization.filter(({ grant }) => grant.status === "active");
|
||||
return activeOrganization.length === 1 ? activeOrganization[0]!.connection : null;
|
||||
return activeOrganization.length === 1 ? usable(activeOrganization[0]!.connection) : null;
|
||||
}
|
||||
|
||||
async function search(claims: RuntimeToolsTokenClaims, query: string): Promise<ConnectionsSearchResult> {
|
||||
async function administrativeDenial(companyId: string, agentId: string, serviceSlug: string, inventory: Awaited<ReturnType<typeof connectionInventory>>) {
|
||||
const effective = await access.getEffectiveProfilesForAgent(companyId, agentId);
|
||||
const installed = effective.installedConnections.filter((connection) => sourceSlugForConnection(connection, inventory.applicationsById) === serviceSlug);
|
||||
if (!installed.length || effective.allowedTools.some((tool) => installed.some((connection) => connection.id === tool.connectionId))) return false;
|
||||
for (const connection of installed) {
|
||||
if ((await indexedCatalog(connection.id, companyId)).some((tool) => tool.entryKind === "tool")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function indexedCatalog(connectionId: string, companyId: string) {
|
||||
// Discovery must not contact providers or mutate their health/cache state.
|
||||
return db.select().from(toolCatalogEntries).where(and(
|
||||
eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.connectionId, connectionId),
|
||||
eq(toolCatalogEntries.status, "active"),
|
||||
));
|
||||
}
|
||||
|
||||
async function resolveService(service: string, companyId: string, userId: string, agentId: string) {
|
||||
if (!service.startsWith("connection:")) {
|
||||
const app = getAppStoreDefinition(service);
|
||||
if (!app) throw notFound("Connection service was not found");
|
||||
return { ...app, available: app.availability?.available !== false,
|
||||
searchCapabilities: getAvailableConnectionMethods(app).map((method) =>
|
||||
`${method.whenToUse} ${method.capabilityProfile?.label ?? ""} ${method.capabilityProfile?.description ?? ""}`).join(" "),
|
||||
methods: getAvailableConnectionMethods(app).map((method) => ({
|
||||
key: method.key, label: method.label ?? method.key, auth: method.auth,
|
||||
})), source: "catalog" as const };
|
||||
}
|
||||
const id = service.slice("connection:".length);
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
|
||||
throw notFound("Configured connection was not found");
|
||||
}
|
||||
const connection = await access.getConnection(id, companyId);
|
||||
const { grants } = await access.listConnectionGrants(id, companyId);
|
||||
if (connection.status === "archived" || !grants.some((grant) => grant.status === "active" && (
|
||||
grant.kind === "organization" || (grant.kind === "user" && grant.subjectUserId === userId)
|
||||
|| (grant.kind === "agent" && grant.subjectAgentId === agentId)
|
||||
))) throw notFound("Configured connection was not found");
|
||||
const application = await access.getApplication(connection.applicationId, companyId);
|
||||
return {
|
||||
slug: service, name: connection.name, description: application.description, searchCapabilities: "",
|
||||
branding: { logoUrl: undefined, darkLogoUrl: undefined },
|
||||
available: connection.enabled,
|
||||
methods: [{ key: "configured", label: "Use configured connection", auth:
|
||||
connection.authKind === "oauth" ? "oauth" as const : connection.authKind === "none" ? "none" as const : "api_key" as const }],
|
||||
source: "configured" as const,
|
||||
};
|
||||
}
|
||||
|
||||
async function search(claims: ConnectionRunClaims, query: string): Promise<ConnectionsSearchResult> {
|
||||
const { run, agent } = await loadRunContext(claims);
|
||||
const normalized = query.trim().toLocaleLowerCase();
|
||||
const tokens = normalized.split(/[^\p{L}\p{N}]+/u).filter(Boolean);
|
||||
const inventory = await connectionInventory(run.companyId);
|
||||
const results = await Promise.all(APP_STORE_DEFINITIONS
|
||||
.filter((app) => !normalized
|
||||
|| app.slug.toLocaleLowerCase().includes(normalized)
|
||||
|| app.name.toLocaleLowerCase().includes(normalized)
|
||||
|| displayDescription(app)?.toLocaleLowerCase().includes(normalized))
|
||||
.map(async (app) => {
|
||||
const methods = getAvailableConnectionMethods(app);
|
||||
const matching = inventory.connections.filter((connection) =>
|
||||
sourceSlugForConnection(connection, inventory.applicationsById) === app.slug
|
||||
&& connection.status !== "archived"
|
||||
);
|
||||
const ready = await usableConnectionForAgent({
|
||||
companyId: run.companyId,
|
||||
agentId: agent.id,
|
||||
responsibleUserId: run.responsibleUserId!,
|
||||
serviceSlug: app.slug,
|
||||
inventory,
|
||||
});
|
||||
return {
|
||||
service: app.slug,
|
||||
name: app.name,
|
||||
description: displayDescription(app),
|
||||
logoUrl: app.branding.logoUrl ?? null,
|
||||
methods: methods.map((method) => ({
|
||||
key: method.key,
|
||||
label: method.label ?? method.key,
|
||||
auth: method.auth,
|
||||
})),
|
||||
state: app.availability?.available === false || methods.length === 0
|
||||
? "unavailable" as const
|
||||
: ready
|
||||
? "ready" as const
|
||||
: matching.length > 0
|
||||
? "needs_user_action" as const
|
||||
: "available" as const,
|
||||
connectionId: ready?.id ?? null,
|
||||
};
|
||||
const candidates: Array<{ item: ConnectionSearchResultItem; score: number }> = [];
|
||||
const services = [...APP_STORE_DEFINITIONS.map((app) => app.slug),
|
||||
...inventory.connections.filter((connection) =>
|
||||
sourceSlugForConnection(connection, inventory.applicationsById)?.startsWith("connection:")
|
||||
&& connection.status !== "archived").map((connection) => `connection:${connection.id}`)];
|
||||
for (const service of services) {
|
||||
let app;
|
||||
try { app = await resolveService(service, run.companyId, run.responsibleUserId!, agent.id); }
|
||||
catch (error) { if (service.startsWith("connection:") && (error as { status?: number }).status === 404) continue; throw error; }
|
||||
const matching = inventory.connections.filter((connection) =>
|
||||
sourceSlugForConnection(connection, inventory.applicationsById) === service && connection.status !== "archived");
|
||||
// Indexed descriptions can contain private workspace metadata, including
|
||||
// for catalog providers. Check each configured connection's audience first.
|
||||
const catalogs = await Promise.all(matching.map(async (connection) => {
|
||||
const { grants } = await access.listConnectionGrants(connection.id, run.companyId);
|
||||
const authorized = grants.some((grant) => grant.status === "active" && (
|
||||
grant.kind === "organization" || (grant.kind === "user" && grant.subjectUserId === run.responsibleUserId)
|
||||
|| (grant.kind === "agent" && grant.subjectAgentId === agent.id)
|
||||
));
|
||||
return authorized ? indexedCatalog(connection.id, run.companyId) : [];
|
||||
}));
|
||||
return { version: 1, query, results };
|
||||
const catalog = catalogs.flat().filter((entry) => entry.status === "active");
|
||||
const haystack = `${app.slug} ${app.name} ${app.description ?? ""} ${app.searchCapabilities} ${catalog.map((tool) => `${tool.toolName} ${tool.description ?? ""}`).join(" ")}`.toLocaleLowerCase();
|
||||
const score = !normalized ? 1 : app.slug === normalized || app.name.toLocaleLowerCase() === normalized
|
||||
? 1000 : tokens.reduce((sum, token) => sum + (haystack.includes(token) ? 1 : 0), 0);
|
||||
if (!score) continue;
|
||||
const ready = await usableConnectionForAgent({ companyId: run.companyId, agentId: agent.id,
|
||||
responsibleUserId: run.responsibleUserId!, serviceSlug: service, inventory });
|
||||
const denied = !ready && matching.length > 0 && await administrativeDenial(run.companyId, agent.id, service, inventory);
|
||||
candidates.push({ score, item: {
|
||||
service, name: app.name, description: app.description ?? null, logoUrl: app.branding.logoUrl ?? null,
|
||||
methods: app.methods, source: app.source,
|
||||
state: ready ? "ready" : denied ? "unavailable" : !app.available || !app.methods.length ? "unavailable"
|
||||
: matching.length ? "needs_user_action" : "available",
|
||||
reason: ready ? "Connection is installed and usable by this agent" : denied ? "An administrator has not permitted executable tools for this agent; reconnecting cannot grant that permission" : !app.available ? "Connection is disabled or unavailable"
|
||||
: matching.some((connection) => isToolConnectionAttentionHealth(connection.healthStatus)) ? "Connection needs attention"
|
||||
: matching.length ? "Review identity and access for this agent" : "Connect this service to continue",
|
||||
connectionId: ready?.id ?? null,
|
||||
}});
|
||||
}
|
||||
return { version: 1, query, results: candidates.sort((a, b) => b.score - a.score || a.item.name.localeCompare(b.item.name)).slice(0, 20).map(({ item }) => item) };
|
||||
}
|
||||
|
||||
async function request(
|
||||
claims: RuntimeToolsTokenClaims,
|
||||
claims: ConnectionRunClaims,
|
||||
serviceSlug: string,
|
||||
): Promise<ConnectionRequestResult> {
|
||||
const context = await loadRunContext(claims);
|
||||
const app = getAppStoreDefinition(serviceSlug);
|
||||
if (!app || app.availability?.available === false || getAvailableConnectionMethods(app).length === 0) {
|
||||
const app = await resolveService(serviceSlug, context.run.companyId, context.run.responsibleUserId!, context.agent.id);
|
||||
if (!app.available || app.methods.length === 0) {
|
||||
throw unprocessable(`Connection service ${serviceSlug} is not available`);
|
||||
}
|
||||
const ready = await usableConnectionForAgent({
|
||||
@@ -313,9 +378,19 @@ export function connectionIntentService(db: Db) {
|
||||
state: "ready",
|
||||
connectionId: ready.id,
|
||||
interactionId: null,
|
||||
instruction: `${app.name} is connected and available in this run.`,
|
||||
instruction: `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`,
|
||||
};
|
||||
}
|
||||
if (await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) {
|
||||
throw forbidden("This agent has no permitted actions for this service. Ask an administrator to review tool permissions; reconnecting will not remove a denial.");
|
||||
}
|
||||
const outcomeId = context.run.contextSnapshot?.interactionId;
|
||||
if (typeof outcomeId === "string") {
|
||||
const [outcome] = await db.select().from(issueThreadInteractions).where(and(eq(issueThreadInteractions.id, outcomeId), eq(issueThreadInteractions.companyId, context.run.companyId), eq(issueThreadInteractions.issueId, context.issue.id)));
|
||||
if (outcome?.kind === "connection_intent" && outcome.status === "rejected" && connectionIntentPayloadSchema.parse(outcome.payload).serviceSlug === app.slug) {
|
||||
throw conflict("The user declined this connection. Pursue alternatives; do not request it again in this continuation.");
|
||||
}
|
||||
}
|
||||
const interaction = await interactions.createConnectionIntent(
|
||||
context.issue,
|
||||
{
|
||||
@@ -330,17 +405,19 @@ export function connectionIntentService(db: Db) {
|
||||
phase: "requested",
|
||||
},
|
||||
sourceRunId: context.run.id,
|
||||
sourceIdentityContextId: context.run.activeIdentityContextId,
|
||||
addresseeUserId: context.run.responsibleUserId!,
|
||||
idempotencyKey: `connection-intent:${context.run.id}:${app.slug}`,
|
||||
idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}`,
|
||||
},
|
||||
);
|
||||
if (interaction.status !== "pending") throw conflict("This connection request has already been resolved. Follow its recorded outcome.");
|
||||
return {
|
||||
version: 1,
|
||||
service: app.slug,
|
||||
state: "needs_user_action",
|
||||
connectionId: null,
|
||||
interactionId: interaction.id,
|
||||
instruction: `A connection card was sent to the responsible user. End this run and wait for continuation.`,
|
||||
instruction: `A connection card was sent to the responsible user. Finish independent work, then yield and wait for continuation. Do not repeat this request.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -359,8 +436,7 @@ export function connectionIntentService(db: Db) {
|
||||
async function setupOptions(interactionId: string): Promise<ConnectionIntentSetupOptions> {
|
||||
const loaded = await loadIntent(interactionId);
|
||||
const payload = connectionIntentPayloadSchema.parse(loaded.interaction.payload);
|
||||
const app = getConnectableAppDefinition(payload.serviceSlug);
|
||||
if (!app) throw notFound("Connection service is no longer available");
|
||||
const app = await resolveService(payload.serviceSlug, loaded.issue.companyId, loaded.interaction.addresseeUserId!, payload.requestingAgentId);
|
||||
const inventory = await connectionInventory(loaded.issue.companyId);
|
||||
const matchingConnections = inventory.connections.filter((connection) =>
|
||||
sourceSlugForConnection(connection, inventory.applicationsById) === app.slug
|
||||
@@ -371,7 +447,8 @@ export function connectionIntentService(db: Db) {
|
||||
const { grants } = await access.listConnectionGrants(connection.id, loaded.issue.companyId);
|
||||
const eligible = grants.some((grant) =>
|
||||
grant.status === "active"
|
||||
&& (grant.kind === "organization" || grant.subjectUserId === loaded.interaction.addresseeUserId)
|
||||
&& (grant.kind === "organization" || grant.subjectUserId === loaded.interaction.addresseeUserId
|
||||
|| (grant.kind === "agent" && grant.subjectAgentId === payload.requestingAgentId))
|
||||
);
|
||||
return eligible ? connection : null;
|
||||
}))).filter((connection): connection is ToolConnection => connection !== null);
|
||||
@@ -381,17 +458,16 @@ export function connectionIntentService(db: Db) {
|
||||
service: {
|
||||
service: app.slug,
|
||||
name: app.name,
|
||||
description: displayDescription(app),
|
||||
description: app.description ?? null,
|
||||
logoUrl: app.branding.logoUrl ?? null,
|
||||
methods: getAvailableConnectionMethods(app).map((method) => ({
|
||||
key: method.key,
|
||||
label: method.label ?? method.key,
|
||||
auth: method.auth,
|
||||
})),
|
||||
methods: app.methods,
|
||||
source: app.source,
|
||||
state: existingConnections.length > 0 ? "needs_user_action" : "available",
|
||||
connectionId: null,
|
||||
},
|
||||
existingConnections,
|
||||
existingConnections: existingConnections.map(({ id, applicationId, name, status, enabled }) => ({
|
||||
id, applicationId, name, status, enabled,
|
||||
})),
|
||||
requestedAgentId: payload.requestingAgentId,
|
||||
};
|
||||
}
|
||||
@@ -406,7 +482,10 @@ export function connectionIntentService(db: Db) {
|
||||
} = {},
|
||||
) {
|
||||
const loaded = await loadIntent(interactionId);
|
||||
if (loaded.interaction.status !== "pending") throw conflict("Connection intent is already resolved");
|
||||
if (loaded.interaction.status !== "pending") {
|
||||
if (loaded.interaction.status === "accepted" && loaded.interaction.result?.connectionId === connectionId && loaded.interaction.addresseeUserId === userId) return loaded.interaction;
|
||||
throw conflict("Connection intent is already resolved");
|
||||
}
|
||||
if (loaded.interaction.addresseeUserId !== userId) throw forbidden("Only the addressed user can connect this service");
|
||||
await assertCurrentUserWriteAccess(
|
||||
loaded.issue.companyId,
|
||||
@@ -415,6 +494,8 @@ export function connectionIntentService(db: Db) {
|
||||
);
|
||||
const payload = connectionIntentPayloadSchema.parse(loaded.interaction.payload);
|
||||
return db.transaction(async (tx) => {
|
||||
const [task] = await tx.select().from(issues).where(and(eq(issues.id, loaded.issue.id), eq(issues.companyId, loaded.issue.companyId))).for("update");
|
||||
if (!task || task.assigneeAgentId !== payload.requestingAgentId || ["done", "cancelled"].includes(task.status)) throw conflict("Connection request no longer belongs to an active task");
|
||||
// Membership downgrade/removal takes the same row lock. Whichever side
|
||||
// commits first is authoritative: a completed revocation makes this
|
||||
// revalidation fail, while completion holds authority through OAuth
|
||||
@@ -428,6 +509,7 @@ export function connectionIntentService(db: Db) {
|
||||
const txDb = tx as unknown as Db;
|
||||
const txAccess = toolAccessService(txDb);
|
||||
const txInteractions = issueThreadInteractionService(txDb);
|
||||
await tx.select({ id: toolConnections.id }).from(toolConnections).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, loaded.issue.companyId))).for("update");
|
||||
let selectedConnection = await txAccess.getConnection(connectionId, loaded.issue.companyId);
|
||||
const selectedApplication = await txAccess.getApplication(
|
||||
selectedConnection.applicationId,
|
||||
@@ -439,7 +521,7 @@ export function connectionIntentService(db: Db) {
|
||||
) !== payload.serviceSlug) {
|
||||
throw notFound("Connection does not match this intent");
|
||||
}
|
||||
if (selectedConnection.status !== "active" || !selectedConnection.enabled) {
|
||||
if (selectedConnection.status !== "active" || !selectedConnection.enabled || isToolConnectionAttentionHealth(selectedConnection.healthStatus)) {
|
||||
throw conflict("Finish and test this connection before using it for the task");
|
||||
}
|
||||
|
||||
@@ -452,13 +534,14 @@ export function connectionIntentService(db: Db) {
|
||||
);
|
||||
if (selectedConnection.authKind === "oauth" && pendingPersonalGrant) {
|
||||
// txAccess is bound to the outer transaction. Its internal transactions
|
||||
// become savepoints, so activation, credential bindings, the all-agents
|
||||
// profile, and the company install roll back with any later failure.
|
||||
// become savepoints, so activation, credential bindings, and the
|
||||
// requesting agent's access roll back with any later failure.
|
||||
await txAccess.finalizeOAuthAccess(
|
||||
loaded.issue.companyId,
|
||||
selectedConnection.id,
|
||||
{ grantKind: "user" },
|
||||
{ actorType: "user", actorId: userId },
|
||||
payload.requestingAgentId,
|
||||
);
|
||||
selectedConnection = await txAccess.getConnection(
|
||||
selectedConnection.id,
|
||||
@@ -475,10 +558,11 @@ export function connectionIntentService(db: Db) {
|
||||
const organizationGrant = grants.find((grant) =>
|
||||
grant.kind === "organization" && grant.status === "active"
|
||||
);
|
||||
if (!personalGrant && !organizationGrant) {
|
||||
const dedicatedGrant = grants.find((grant) => grant.kind === "agent" && grant.status === "active" && grant.subjectAgentId === payload.requestingAgentId);
|
||||
if (!personalGrant && !organizationGrant && !dedicatedGrant) {
|
||||
throw conflict("This connection has no usable identity grant");
|
||||
}
|
||||
if (!personalGrant && !options.canManageOrganizationGrant) {
|
||||
if (!personalGrant && !dedicatedGrant && !options.canManageOrganizationGrant) {
|
||||
throw forbidden("Sharing a company connection requires connection-management authority");
|
||||
}
|
||||
|
||||
@@ -504,6 +588,15 @@ export function connectionIntentService(db: Db) {
|
||||
actorId: userId,
|
||||
});
|
||||
|
||||
const effective = await txAccess.getEffectiveProfilesForAgent(loaded.issue.companyId, payload.requestingAgentId);
|
||||
if (!effective.allowedTools.some((tool) => tool.connectionId === selectedConnection.id)) throw conflict("This connection has no permitted tools. Review its action permissions before continuing.");
|
||||
|
||||
const runtimeConnection = await connectionIntentService(txDb).usableConnectionForAgent({
|
||||
companyId: loaded.issue.companyId, agentId: payload.requestingAgentId,
|
||||
responsibleUserId: userId, serviceSlug: payload.serviceSlug,
|
||||
});
|
||||
if (runtimeConnection?.id !== selectedConnection.id) throw conflict("This identity is not the connection this agent can execute. Resolve conflicting identities before continuing.");
|
||||
|
||||
return txInteractions.resolveConnectionIntent(
|
||||
loaded.issue,
|
||||
interactionId,
|
||||
@@ -536,6 +629,7 @@ export function connectionIntentService(db: Db) {
|
||||
|
||||
return {
|
||||
validate: loadRunContext,
|
||||
usableConnectionForAgent,
|
||||
search,
|
||||
request,
|
||||
loadIntent,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { CONNECTION_REQUEST_TOOL_DESCRIPTION, CONNECTIONS_SEARCH_TOOL_DESCRIPTION } from "@paperclipai/shared";
|
||||
|
||||
export const RUNTIME_CONNECTION_TOOL_DEFINITIONS = [
|
||||
{
|
||||
name: "connections_search",
|
||||
description: CONNECTIONS_SEARCH_TOOL_DESCRIPTION,
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { query: { type: "string" } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "connection_request",
|
||||
description: CONNECTION_REQUEST_TOOL_DESCRIPTION,
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { service: { type: "string" } },
|
||||
required: ["service"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -17462,11 +17462,12 @@ export function heartbeatService(
|
||||
isResolvedInteractionContinuationWakeContext(context)
|
||||
) {
|
||||
try {
|
||||
// Claim the issue under the same in_progress predicate used by the
|
||||
// Claim the issue under the same active-status predicate used by the
|
||||
// queued-run staleness gate. This is the final atomic guard before
|
||||
// dispatch: an operator parking the issue after claim but before this
|
||||
// checkout must not be overwritten by the continuation.
|
||||
await issuesSvc.checkout(issueId, agent.id, ["in_progress"], run.id);
|
||||
await issuesSvc.checkout(issueId, agent.id, context.interactionKind === "connection_intent"
|
||||
? ["in_progress", "in_review"] : ["in_progress"], run.id);
|
||||
context[PAPERCLIP_HARNESS_CHECKOUT_KEY] = true;
|
||||
} catch (error) {
|
||||
if (!isCheckoutConflictError(error)) throw error;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { connectionIntentDeliveries } from "@paperclipai/db";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, asc, desc, eq, inArray, isNotNull, isNull, ne } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
@@ -656,7 +657,7 @@ function shouldReturnAcceptedConfirmationToCreatorAgent(args: {
|
||||
}
|
||||
|
||||
function shouldSupersedeInteractionOnUserComment(interaction: UserCommentSupersedableInteraction) {
|
||||
if (interaction.kind === "connection_intent") return true;
|
||||
if (interaction.kind === "connection_intent") return false;
|
||||
return interaction.payload.supersedeOnUserComment === true;
|
||||
}
|
||||
|
||||
@@ -2034,6 +2035,7 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
input: {
|
||||
payload: ConnectionIntentInteraction["payload"];
|
||||
sourceRunId: string;
|
||||
sourceIdentityContextId?: string | null;
|
||||
addresseeUserId: string;
|
||||
idempotencyKey: string;
|
||||
},
|
||||
@@ -2049,7 +2051,9 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
existing.kind !== "connection_intent"
|
||||
|| existing.sourceRunId !== input.sourceRunId
|
||||
|| existing.addresseeUserId !== input.addresseeUserId
|
||||
|| !isDeepStrictEqual(existing.payload, payload)
|
||||
|| (existing.kind === "connection_intent"
|
||||
? connectionIntentPayloadSchema.parse(existing.payload).serviceSlug !== payload.serviceSlug
|
||||
: !isDeepStrictEqual(existing.payload, payload))
|
||||
) {
|
||||
throw conflict("Interaction idempotency key already exists for a different request", {
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
@@ -2058,17 +2062,31 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
return hydrateInteraction(existing) as ConnectionIntentInteraction;
|
||||
}
|
||||
|
||||
let inserted = false;
|
||||
const created = await db.transaction(async (tx) => {
|
||||
const issueRow = await tx
|
||||
.select({ status: issues.status })
|
||||
.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId })
|
||||
.from(issues)
|
||||
.where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)))
|
||||
.for("update")
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!issueRow || isTerminalIssueStatus(issueRow.status)) {
|
||||
if (!issueRow || isTerminalIssueStatus(issueRow.status) || issueRow.assigneeAgentId !== payload.requestingAgentId) {
|
||||
throw conflict("Cannot create an interaction on a closed issue");
|
||||
}
|
||||
|
||||
// Serialize on the task so retries and later runs share the same live card.
|
||||
const pending = await tx.select().from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, issue.companyId),
|
||||
eq(issueThreadInteractions.issueId, issue.id),
|
||||
eq(issueThreadInteractions.kind, "connection_intent"),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
eq(issueThreadInteractions.createdByAgentId, payload.requestingAgentId),
|
||||
eq(issueThreadInteractions.addresseeUserId, input.addresseeUserId),
|
||||
));
|
||||
const reusable = pending.find((candidate) =>
|
||||
connectionIntentPayloadSchema.parse(candidate.payload).serviceSlug === payload.serviceSlug);
|
||||
if (reusable) return reusable;
|
||||
|
||||
const [row] = await tx
|
||||
.insert(issueThreadInteractions)
|
||||
.values({
|
||||
@@ -2083,6 +2101,7 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
effectiveResolverPolicySource: "governed_action",
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
sourceRunId: input.sourceRunId,
|
||||
sourceIdentityContextId: input.sourceIdentityContextId ?? null,
|
||||
title: `Connect ${payload.serviceName}`,
|
||||
summary: `${payload.requestingAgentName} needs this connection to continue.`,
|
||||
createdByAgentId: payload.requestingAgentId,
|
||||
@@ -2127,11 +2146,12 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
.where(inArray(issueThreadInteractions.id, supersededIds));
|
||||
}
|
||||
await touchIssue(tx, issue.id);
|
||||
inserted = true;
|
||||
return row;
|
||||
});
|
||||
|
||||
const interaction = hydrateInteraction(created) as ConnectionIntentInteraction;
|
||||
emitInteractionCreatedTelemetry({
|
||||
if (inserted) emitInteractionCreatedTelemetry({
|
||||
interactionKind: "connection_intent",
|
||||
usedDeprecatedResolverPolicyAlias: false,
|
||||
});
|
||||
@@ -2182,7 +2202,8 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
? "rejected"
|
||||
: "expired";
|
||||
const resolvedAt = now();
|
||||
const [updated] = await db
|
||||
const updated = await db.transaction(async (tx) => {
|
||||
const [row] = await tx
|
||||
.update(issueThreadInteractions)
|
||||
.set({
|
||||
status,
|
||||
@@ -2198,6 +2219,12 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
))
|
||||
.returning();
|
||||
if (!row) throw interactionAlreadyResolvedError();
|
||||
if (status === "accepted" || status === "rejected") {
|
||||
await tx.insert(connectionIntentDeliveries).values({ interactionId, companyId: issue.companyId }).onConflictDoNothing();
|
||||
}
|
||||
return row;
|
||||
});
|
||||
if (!updated) throw interactionAlreadyResolvedError();
|
||||
await touchIssue(db, issue.id);
|
||||
const interaction = hydrateInteraction(updated) as ConnectionIntentInteraction;
|
||||
@@ -3573,6 +3600,15 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
|
||||
return expired;
|
||||
},
|
||||
|
||||
expireConnectionIntentsForOwnershipChange: async (issue: { id: string; companyId: string }) => {
|
||||
const expired = await db.update(issueThreadInteractions).set({
|
||||
status: "expired", result: { version: 1, outcome: "expired", reason: "The task assignment changed" },
|
||||
resolvedAt: now(), updatedAt: now(),
|
||||
}).where(and(eq(issueThreadInteractions.companyId, issue.companyId), eq(issueThreadInteractions.issueId, issue.id),
|
||||
eq(issueThreadInteractions.kind, "connection_intent"), eq(issueThreadInteractions.status, "pending"))).returning();
|
||||
if (expired.length) await db.delete(toolOauthStates).where(inArray(toolOauthStates.interactionId, expired.map((row) => row.id)));
|
||||
return expired;
|
||||
},
|
||||
expirePendingInteractionsForTerminalIssue: async (
|
||||
issue: { id: string; companyId: string; status: string },
|
||||
actor: InteractionActor = {},
|
||||
|
||||
@@ -7981,6 +7981,10 @@ export function issueService(db: Db) {
|
||||
.returning()
|
||||
.then((rows: Array<typeof issues.$inferSelect>) => rows[0] ?? null);
|
||||
if (!updated) return null;
|
||||
if (updated.assigneeAgentId !== existing.assigneeAgentId || updated.assigneeUserId !== existing.assigneeUserId) {
|
||||
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
||||
await issueThreadInteractionService(tx).expireConnectionIntentsForOwnershipChange(updated);
|
||||
}
|
||||
if (existing.status !== updated.status) {
|
||||
if (
|
||||
(existing.status === "done" || existing.status === "cancelled")
|
||||
|
||||
@@ -279,7 +279,7 @@ export async function materializeNativeInteractionResponses(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (interaction.kind === "suggest_tasks") {
|
||||
if (interaction.kind === "suggest_tasks" || interaction.kind === "connection_intent") {
|
||||
if (
|
||||
(interaction.status !== "accepted" && interaction.status !== "rejected")
|
||||
|| !interaction.result
|
||||
|
||||
@@ -180,6 +180,7 @@ import {
|
||||
nativeSessionFailureSourceCode,
|
||||
nativeSessionRecoveryProjection,
|
||||
nativeGovernedWaitResult,
|
||||
nativeToolsRefreshWaitResult,
|
||||
parseRemoteExecutableCandidate,
|
||||
buildRemoteCodexLauncherCommand,
|
||||
mayUsePreinstalledRunnerArtifact,
|
||||
@@ -2176,6 +2177,15 @@ describe("provider plan synchronization", () => {
|
||||
});
|
||||
|
||||
describe("native governed waits", () => {
|
||||
it("yields to an existing tools-refresh wake without claiming completion or a human interaction", () => {
|
||||
const result = nativeToolsRefreshWaitResult({ wakeId: "wake-1", key: "connection-intent:tools:run-1:digest",
|
||||
completionContract: { revision: "4", objective: "Read the archive", criteria: [{ id: "read", requirement: "Read the archive" }] } });
|
||||
expect(result.completionClaim).toMatchObject({ contractRevision: "4", objectiveSatisfied: false });
|
||||
expect(result.artifacts).toEqual([]);
|
||||
expect(result.continuation).toMatchObject({ kind: "same_agent", idempotencyKey: "connection-intent:tools:run-1:digest" });
|
||||
expect(result.evidence).toEqual([{ ref: "wakeup:wake-1" }]);
|
||||
});
|
||||
|
||||
it("turns a durable pending interaction into a response-wake result", () => {
|
||||
expect(
|
||||
nativeGovernedWaitResult({
|
||||
|
||||
@@ -56,8 +56,9 @@ import {
|
||||
type PaperclipRunnerTransport,
|
||||
} from "@paperclipai/adapter-utils/runner-connectivity";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { and, desc, eq, gt, inArray, or, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, gt, inArray, like, notInArray, or, sql } from "drizzle-orm";
|
||||
import {
|
||||
agentWakeupRequests,
|
||||
documentRevisions,
|
||||
environmentLeases,
|
||||
heartbeatRunEvents,
|
||||
@@ -885,6 +886,22 @@ export function createGovernedWaitEventObservation(
|
||||
};
|
||||
}
|
||||
|
||||
export function nativeToolsRefreshWaitResult(input: {
|
||||
wakeId: string; key: string;
|
||||
completionContract: NativeExecutionInput["completionContract"]["contract"];
|
||||
}): PrpStructuredRunResult {
|
||||
const ref = `wakeup:${input.wakeId}`;
|
||||
return {
|
||||
schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded",
|
||||
summary: "Continuing with the newly installed connection tools.",
|
||||
completionClaim: { contractRevision: input.completionContract.revision, objectiveSatisfied: false,
|
||||
criteria: input.completionContract.criteria.map((criterion) => ({ criterionId: criterion.id, status: "unknown", evidenceRefs: [ref] })),
|
||||
remainingWork: [{ description: "Continue in the queued session with updated tools.", blocksCompletion: true }] },
|
||||
evidence: [{ ref }], verification: [], attentionRequests: [], artifacts: [],
|
||||
continuation: { kind: "same_agent", summary: "Use the updated connection tools in a fresh session.", idempotencyKey: input.key },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Partial item-verdict responses deliberately leave their original durable
|
||||
* interaction pending. They are already authority-checked before entering the
|
||||
@@ -4343,6 +4360,10 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
issueThreadInteractions.sourceRunId,
|
||||
input.execution.binding.runId,
|
||||
),
|
||||
and(
|
||||
eq(issueThreadInteractions.kind, "connection_intent"),
|
||||
eq(issueThreadInteractions.createdByAgentId, input.execution.binding.agentId),
|
||||
),
|
||||
...(continuingInteractionIds.length > 0
|
||||
? [inArray(issueThreadInteractions.id, continuingInteractionIds)]
|
||||
: []),
|
||||
@@ -4356,12 +4377,20 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
)
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
return interaction
|
||||
? nativeGovernedWaitResult({
|
||||
interaction,
|
||||
completionContract: input.execution.completionContract.contract,
|
||||
})
|
||||
: null;
|
||||
if (interaction) return nativeGovernedWaitResult({
|
||||
interaction, completionContract: input.execution.completionContract.contract,
|
||||
});
|
||||
// A ready connection can become installed after the provider snapshot was
|
||||
// pinned. Its already-durable wake is also a valid reason to end this turn.
|
||||
const [refresh] = await input.db.select({ id: agentWakeupRequests.id, key: agentWakeupRequests.idempotencyKey })
|
||||
.from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, input.execution.binding.companyId),
|
||||
eq(agentWakeupRequests.agentId, input.execution.binding.agentId),
|
||||
like(agentWakeupRequests.idempotencyKey, `connection-intent:tools:${input.execution.binding.runId}:%`),
|
||||
notInArray(agentWakeupRequests.status, ["skipped", "failed", "cancelled"]),
|
||||
)).limit(1);
|
||||
return refresh?.key ? nativeToolsRefreshWaitResult({ wakeId: refresh.id, key: refresh.key,
|
||||
completionContract: input.execution.completionContract.contract }) : null;
|
||||
}
|
||||
const runnerExecution =
|
||||
input.useRunnerd && input.runnerExecutionTarget?.kind === "remote"
|
||||
@@ -6203,6 +6232,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
runId: input.execution.binding.runId,
|
||||
agentId: input.execution.binding.agentId,
|
||||
normalizedSessionId: nativeSessionKey(input.execution),
|
||||
pinnedMcpDigest: "runtimeContext" in input.execution ? input.execution.runtimeContext.mcp.digest : undefined,
|
||||
workMode: input.execution.task.workMode,
|
||||
enqueueWakeup: input.enqueueWakeup,
|
||||
});
|
||||
|
||||
@@ -63,8 +63,9 @@ describe("PaperclipRunnerToolAuthority", () => {
|
||||
|
||||
it("advertises only real bindings and reads the bound task", async () => {
|
||||
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
|
||||
expect(authority.definitions()).toHaveLength(16);
|
||||
expect(authority.definitions()).toHaveLength(18);
|
||||
expect(authority.definitions().map((tool) => tool.name)).toEqual(expect.arrayContaining([
|
||||
"connections_search", "connection_request",
|
||||
"get_task_context", "get_task_history", "search_tasks", "report_progress",
|
||||
"request_human_input",
|
||||
"create_task", "set_dependencies",
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { resolveNativeRuntimeMcpSnapshot } from "./runtime-context.js";
|
||||
import { connectionIntentService } from "../connection-intents.js";
|
||||
import { RUNTIME_CONNECTION_TOOL_DEFINITIONS } from "../connection-tool-definitions.js";
|
||||
import { connectionsSearchInputSchema, connectionRequestInputSchema, CONNECTION_INTENT_AGENT_GUIDANCE } from "@paperclipai/shared";
|
||||
import { createHash } from "node:crypto";
|
||||
import { runnerApiToolsEnabled } from "./runner-api-rollout.js";
|
||||
import { openRunnerApiWorkspaceFile } from "./runner-api-files.js";
|
||||
@@ -10,10 +14,11 @@ import { workspaceFileResourceService } from "../workspace-file-resources.js";
|
||||
import { badRequest, forbidden } from "../../errors.js";
|
||||
import { searchRunnerApi } from "./runner-api-catalog.js";
|
||||
import { executeRunnerApi, validateRunnerApiCall, RUNNER_API_MAX_BYTES, type RunnerApiFile } from "./runner-api-client.js";
|
||||
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||
import { and, desc, eq, isNull, notInArray } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
agentWakeupRequests,
|
||||
documentRevisions,
|
||||
heartbeatRuns,
|
||||
issueApprovals,
|
||||
@@ -46,6 +51,7 @@ type Binding = {
|
||||
runId: string;
|
||||
agentId: string;
|
||||
normalizedSessionId?: string;
|
||||
pinnedMcpDigest?: string;
|
||||
/** Server-owned API origin and storage; never obtained from tool input. */
|
||||
apiUrl?: string;
|
||||
storage?: StorageService;
|
||||
@@ -61,6 +67,7 @@ type Binding = {
|
||||
requestedByActorType: "agent";
|
||||
requestedByActorId: string;
|
||||
contextSnapshot: Record<string, unknown>;
|
||||
issueStateGuard?: { statuses: string[]; assigneeAgentId: string };
|
||||
}) => Promise<unknown>;
|
||||
};
|
||||
|
||||
@@ -90,7 +97,7 @@ export class PaperclipRunnerToolAuthority {
|
||||
|
||||
definitions(): Array<Record<string, unknown>> {
|
||||
const workMode = this.binding.workMode ?? "standard";
|
||||
return CAPABILITY_SEMANTIC_TOOL_CATALOG
|
||||
return [...RUNTIME_CONNECTION_TOOL_DEFINITIONS, ...CAPABILITY_SEMANTIC_TOOL_CATALOG
|
||||
.filter((descriptor) =>
|
||||
IMPLEMENTED_OPERATIONS.has(descriptor.operationId)
|
||||
&& (runnerApiToolsEnabled(this.binding.companyId, this.binding.apiToolsEnabled) || !["search_api", "call_api"].includes(descriptor.operationId))
|
||||
@@ -100,10 +107,42 @@ export class PaperclipRunnerToolAuthority {
|
||||
name: descriptor.operationId,
|
||||
description: descriptor.description,
|
||||
inputSchema: descriptor.inputSchema,
|
||||
}));
|
||||
}))];
|
||||
}
|
||||
|
||||
async execute(call: { tool: string; callId: string; arguments: unknown }): Promise<unknown> {
|
||||
if (RUNTIME_CONNECTION_TOOL_DEFINITIONS.some((tool) => tool.name === call.tool)) {
|
||||
await this.#boundContext();
|
||||
const { run } = await captureRunIdentity(this.db, this.binding);
|
||||
if (!run.responsibleUserId) throw forbidden("This task needs a responsible user before requesting a connection");
|
||||
const claims = {
|
||||
sub: this.binding.agentId, company_id: this.binding.companyId,
|
||||
run_id: this.binding.runId, responsible_user_id: run.responsibleUserId,
|
||||
};
|
||||
const connections = connectionIntentService(this.db);
|
||||
if (call.tool === "connections_search") return connections.search(claims, connectionsSearchInputSchema.parse(call.arguments).query);
|
||||
const result = await connections.request(claims, connectionRequestInputSchema.parse(call.arguments).service);
|
||||
if (result.state === "ready" && this.binding.pinnedMcpDigest && this.binding.enqueueWakeup) {
|
||||
const current = await resolveNativeRuntimeMcpSnapshot({ db: this.db, agent: { id: this.binding.agentId, companyId: this.binding.companyId }, runId: this.binding.runId });
|
||||
if (current.digest !== this.binding.pinnedMcpDigest) {
|
||||
const idempotencyKey = `connection-intent:tools:${this.binding.runId}:${current.digest}`;
|
||||
const delivered = () => this.db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, this.binding.companyId), eq(agentWakeupRequests.idempotencyKey, idempotencyKey),
|
||||
notInArray(agentWakeupRequests.status, ["skipped", "failed", "cancelled"]),
|
||||
)).limit(1);
|
||||
if (!(await delivered()).length) try { await this.binding.enqueueWakeup(this.binding.agentId, {
|
||||
source: "assignment", triggerDetail: "system", reason: "issue_assigned",
|
||||
payload: { issueId: this.binding.issueId, mutation: "connection_tools_refreshed" },
|
||||
idempotencyKey,
|
||||
issueStateGuard: { statuses: ["in_progress", "in_review"], assigneeAgentId: this.binding.agentId },
|
||||
requestedByActorType: "agent", requestedByActorId: this.binding.agentId,
|
||||
contextSnapshot: { issueId: this.binding.issueId, taskId: this.binding.issueId, forceFreshSession: true, wakeReason: "issue_assigned", source: "connection_tools.refreshed" },
|
||||
}); } catch (error) { if (!(await delivered()).length) throw error; }
|
||||
return { ...result, instruction: "Access is already authorized. A fresh continuation with updated tools is queued. Finish independent work, then yield. Do not request authorization again." };
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (!IMPLEMENTED_OPERATIONS.has(call.tool)) throw new Error("paperclip_runner_tool_not_advertised");
|
||||
if (!runnerApiToolsEnabled(this.binding.companyId, this.binding.apiToolsEnabled) && ["search_api", "call_api"].includes(call.tool)) throw new Error("paperclip_runner_tool_not_advertised");
|
||||
const context = await this.#boundContext();
|
||||
@@ -126,6 +165,7 @@ export class PaperclipRunnerToolAuthority {
|
||||
status: context.run.status,
|
||||
invocationSource: context.run.invocationSource,
|
||||
},
|
||||
connectionGuidance: CONNECTION_INTENT_AGENT_GUIDANCE,
|
||||
acceptedPlan: await this.#acceptedPlan(context.run.contextSnapshot),
|
||||
};
|
||||
case "get_task_history": {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, inArray, notInArray, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { CreateIssueThreadInteraction } from "@paperclipai/shared";
|
||||
import {
|
||||
@@ -459,6 +459,15 @@ async function materializeDecisionEffect(input: {
|
||||
}
|
||||
if (effect.kind === "enqueue_continuation") {
|
||||
failAt("continuation_materialization", input.failpoint);
|
||||
if (effect.idempotencyKey.startsWith(`connection-intent:tools:${input.runId}:`)) {
|
||||
const [refresh] = await input.tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.agentId, effect.agentId),
|
||||
eq(agentWakeupRequests.idempotencyKey, effect.idempotencyKey),
|
||||
notInArray(agentWakeupRequests.status, ["skipped", "failed", "cancelled"]),
|
||||
)).limit(1);
|
||||
if (refresh) return { effectKind: effect.kind, targetType: "agent_wakeup_request", targetId: refresh.id,
|
||||
payload: { continuationKind: effect.continuationKind, summary: effect.summary } };
|
||||
}
|
||||
const wakeId = await enqueueWake({
|
||||
tx: input.tx,
|
||||
companyId: input.companyId,
|
||||
|
||||
@@ -8789,13 +8789,14 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
|
||||
let existingApplication: typeof toolApplications.$inferSelect | null = null;
|
||||
let requestedResumeConnection: typeof toolConnections.$inferSelect | null = null;
|
||||
if (input.resumeConnectionId) {
|
||||
const requestedConnectionId = input.resumeConnectionId ?? input.reconnectConnectionId;
|
||||
if (requestedConnectionId) {
|
||||
const [connection] = await db.select().from(toolConnections).where(and(
|
||||
eq(toolConnections.id, input.resumeConnectionId),
|
||||
eq(toolConnections.id, requestedConnectionId),
|
||||
eq(toolConnections.companyId, companyId),
|
||||
));
|
||||
if (!connection) throw notFound("Incomplete app connection not found");
|
||||
if (connection.status !== "draft") {
|
||||
if (input.resumeConnectionId && connection.status !== "draft") {
|
||||
throw conflict("Only an incomplete app connection can resume setup", {
|
||||
code: "connection_setup_not_incomplete",
|
||||
});
|
||||
@@ -8808,6 +8809,10 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
eq(toolApplications.companyId, companyId),
|
||||
));
|
||||
if (!application) throw notFound("App not found");
|
||||
const source = asRecord(connection.config).sourceTemplateKey ?? asRecord(connection.transportConfig).sourceTemplateKey ?? asRecord(application.metadata).sourceTemplateKey ?? asRecord(application.metadata).source;
|
||||
if (input.reconnectConnectionId && ((galleryEntry && source !== galleryEntry.slug) || (!galleryEntry && typeof source === "string" && getConnectableAppDefinition(source)))) {
|
||||
throw badRequest("Reconnect must preserve the configured provider");
|
||||
}
|
||||
requestedResumeConnection = connection;
|
||||
existingApplication = application;
|
||||
} else if (input.applicationId) {
|
||||
@@ -9923,6 +9928,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
metadata: { source: "app_gallery_finish" },
|
||||
}));
|
||||
const transactionResult = await db.transaction(async (tx) => {
|
||||
await tx.select({ id: toolConnections.id }).from(toolConnections).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, companyId))).for("update");
|
||||
const [existingProfile] = await tx
|
||||
.select()
|
||||
.from(toolProfiles)
|
||||
@@ -9930,6 +9936,12 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
.limit(1);
|
||||
let profileId: string;
|
||||
if (existingProfile) {
|
||||
if (input.preserveExistingAccess) {
|
||||
const priorBindings = await tx.select().from(toolProfileBindings).where(eq(toolProfileBindings.profileId, existingProfile.id));
|
||||
for (const prior of priorBindings) if (!bindingInputs.some((binding) => binding.targetType === prior.targetType && binding.targetId === prior.targetId)) bindingInputs.push({ targetType: prior.targetType, targetId: prior.targetId, priority: prior.priority, metadata: prior.metadata });
|
||||
const priorEntries = await tx.select().from(toolProfileEntries).where(eq(toolProfileEntries.profileId, existingProfile.id));
|
||||
for (const prior of priorEntries) if (!entries.some((entry) => entry.catalogEntryId && entry.catalogEntryId === prior.catalogEntryId)) entries.push({ selectorType: prior.selectorType, effect: prior.effect, applicationId: prior.applicationId, connectionId: prior.connectionId, catalogEntryId: prior.catalogEntryId, toolName: prior.toolName, riskLevel: prior.riskLevel, conditions: prior.conditions });
|
||||
}
|
||||
await tx
|
||||
.delete(toolProfileBindings)
|
||||
.where(and(eq(toolProfileBindings.companyId, companyId), eq(toolProfileBindings.profileId, existingProfile.id)));
|
||||
@@ -10048,6 +10060,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
companyId,
|
||||
connection,
|
||||
askFirstEntries: askFirstRows,
|
||||
disableStale: !input.preserveExistingAccess,
|
||||
actor,
|
||||
}, tx);
|
||||
const [updatedConnection] = await tx
|
||||
@@ -10801,7 +10814,17 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
suggestedDefaults: ConnectToolAppResult["suggestedDefaults"];
|
||||
activateQuarantined?: boolean;
|
||||
actor?: ActorInfo;
|
||||
interactionId?: string | null;
|
||||
}) {
|
||||
const linkedInteraction = input.interactionId
|
||||
? await db.select({ kind: issueThreadInteractions.kind }).from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.id, input.interactionId),
|
||||
eq(issueThreadInteractions.companyId, input.connection.companyId),
|
||||
)).limit(1).then((rows) => rows[0] ?? null)
|
||||
: null;
|
||||
// A task callback only prepares the catalog. The intent completion transaction
|
||||
// validates current ownership and adds the requesting agent's access.
|
||||
const deferTaskAccess = linkedInteraction?.kind === "connection_intent";
|
||||
const installs = await db.select().from(toolConnectionInstalls).where(and(
|
||||
eq(toolConnectionInstalls.companyId, input.connection.companyId),
|
||||
eq(toolConnectionInstalls.connectionId, input.connection.id),
|
||||
@@ -10820,7 +10843,9 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
: suggestedAgentIds.length > 0
|
||||
? { agentIds: suggestedAgentIds }
|
||||
: "all_agents";
|
||||
const access: FinishToolApp["access"] = installs.length === 0
|
||||
const access: FinishToolApp["access"] = deferTaskAccess
|
||||
? { agentIds: [] }
|
||||
: installs.length === 0
|
||||
? normalizedSuggestedAccess
|
||||
: companyInstall
|
||||
? "all_agents"
|
||||
@@ -10844,8 +10869,9 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
? enabledCatalog.filter((entry) => entry.status === "quarantined").map((entry) => entry.id)
|
||||
: undefined,
|
||||
access,
|
||||
preserveExistingAccess: deferTaskAccess,
|
||||
}, input.actor);
|
||||
if (installs.length === 0) {
|
||||
if (!deferTaskAccess && installs.length === 0) {
|
||||
const installTargets = access === "all_agents"
|
||||
? [{ targetType: "company" as const, targetId: input.connection.companyId }]
|
||||
: [...new Set(access.agentIds)].map((agentId) => ({ targetType: "agent" as const, targetId: agentId }));
|
||||
@@ -11137,6 +11163,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
: recommended;
|
||||
const finished = shouldFinalizeManagedDefaults
|
||||
? await finishOAuthCatalogWithRecommendedDefaults({
|
||||
interactionId: stateRow.interactionId,
|
||||
connection,
|
||||
catalog: refresh.catalog,
|
||||
suggestedDefaults,
|
||||
@@ -11286,6 +11313,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
const method = connectionMethodForConnection(galleryEntry, connection);
|
||||
const refresh = await refreshCatalog(connection.id, input.actor, {
|
||||
enableAllByDefault: true,
|
||||
skipDefaultProfileSync: true,
|
||||
credentialHeaders: {
|
||||
...projectedConnectionHeaders(connection),
|
||||
[credential.headerName]: `${credential.headerPrefix ?? ""}${token.token}`,
|
||||
@@ -11293,6 +11321,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
});
|
||||
const suggestedDefaults = recommendedDefaultsForApp(galleryEntry, method.key);
|
||||
const finished = await finishOAuthCatalogWithRecommendedDefaults({
|
||||
interactionId: stateRow.interactionId,
|
||||
connection,
|
||||
catalog: refresh.catalog,
|
||||
suggestedDefaults,
|
||||
@@ -11544,6 +11573,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
// Activate and discover with the just-issued token before returning.
|
||||
const refresh = await refreshCatalog(connection.id, input.actor, {
|
||||
enableAllByDefault: true,
|
||||
skipDefaultProfileSync: true,
|
||||
credentialHeaders: { Authorization: `Bearer ${token.accessToken}` },
|
||||
});
|
||||
const [application] = await db.select().from(toolApplications).where(eq(toolApplications.id, connection.applicationId));
|
||||
@@ -11552,6 +11582,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
? recommendedDefaultsForApp(galleryEntry, connectionMethodForConnection(galleryEntry, connection).key)
|
||||
: { access: "all_agents" as const, askFirstRiskLevels: [] };
|
||||
const finished = await finishOAuthCatalogWithRecommendedDefaults({
|
||||
interactionId: stateRow.interactionId,
|
||||
connection,
|
||||
catalog: refresh.catalog,
|
||||
suggestedDefaults,
|
||||
@@ -11697,7 +11728,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
});
|
||||
|
||||
await checkConnectionHealth(connection.id, input.actor);
|
||||
const refresh = await refreshCatalog(connection.id, input.actor, { enableAllByDefault: true });
|
||||
const refresh = await refreshCatalog(connection.id, input.actor, { enableAllByDefault: true, skipDefaultProfileSync: true });
|
||||
const [application] = await db.select().from(toolApplications).where(eq(toolApplications.id, connection.applicationId));
|
||||
const suggestedDefaults = galleryEntry ? recommendedDefaultsForApp(
|
||||
galleryEntry,
|
||||
@@ -11707,6 +11738,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
askFirstRiskLevels: [],
|
||||
};
|
||||
const finished = await finishOAuthCatalogWithRecommendedDefaults({
|
||||
interactionId: stateRow.interactionId,
|
||||
connection,
|
||||
catalog: refresh.catalog,
|
||||
suggestedDefaults,
|
||||
@@ -11735,7 +11767,9 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
connectionId: string,
|
||||
input: FinalizeOAuthAccess,
|
||||
actor?: ActorInfo,
|
||||
requestingAgentId?: string,
|
||||
): Promise<FinishToolAppResult> {
|
||||
if (requestingAgentId) await assertAgentsInCompany(companyId, [requestingAgentId]);
|
||||
let connection = await getConnectionRow(connectionId, companyId);
|
||||
if (connection.authKind !== "oauth") throw badRequest("This connection does not use browser sign-in");
|
||||
if (connection.status === "archived") throw conflict("Archived app connections cannot be finished");
|
||||
@@ -11953,13 +11987,14 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
|
||||
askFirstCatalogEntryIds: catalog
|
||||
.filter((entry) => askFirstRiskLevels.has(entry.riskLevel))
|
||||
.map((entry) => entry.id),
|
||||
access: "all_agents",
|
||||
access: requestingAgentId ? { agentIds: [requestingAgentId] } : "all_agents",
|
||||
preserveExistingAccess: Boolean(requestingAgentId),
|
||||
}, actor);
|
||||
await db.insert(toolConnectionInstalls).values({
|
||||
companyId,
|
||||
connectionId: connection.id,
|
||||
targetType: "company",
|
||||
targetId: companyId,
|
||||
targetType: requestingAgentId ? "agent" : "company",
|
||||
targetId: requestingAgentId ?? companyId,
|
||||
createdByUserId: actorUserId,
|
||||
}).onConflictDoNothing();
|
||||
return finished;
|
||||
|
||||
Reference in new issue
Block a user