mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 03:36:57 +01:00
fix(connections): recover missing personal AI credentials in chat (#15376)
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
ea8e686197
commit
2ca0d26a99
19 files changed
+359
-35
No files matched your search
@@ -1,4 +1,43 @@
|
||||
import { AI_PROVIDERS, AI_CONNECTION_CAPABILITIES, isAiConnectionCompatible, type AiConnectionBinding } from "@paperclipai/shared";
|
||||
import { AI_PROVIDERS, AI_CONNECTION_CAPABILITIES, isAiConnectionCompatible, type AiConnectionBinding, type AiProvider } from "@paperclipai/shared";
|
||||
|
||||
type AuthenticationFailure = {
|
||||
errorCode?: string | null;
|
||||
resultJson?: unknown;
|
||||
};
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown> : null;
|
||||
}
|
||||
|
||||
/** A personal model credential gap is repairable without changing other secrets. */
|
||||
function missingPersonalAiCredentialProvider(run: AuthenticationFailure): AiProvider | undefined {
|
||||
if (run.errorCode !== "configuration_incomplete") return undefined;
|
||||
const gap = record(record(run.resultJson)?.configurationIncomplete);
|
||||
if (gap?.reason !== "secret_binding_missing" || !Array.isArray(gap.missingBindings) || !gap.missingBindings.length) return undefined;
|
||||
const missingBindings = gap.missingBindings;
|
||||
return AI_PROVIDERS.find(provider => {
|
||||
const keys = new Set(Object.values(AI_CONNECTION_CAPABILITIES[provider].methods).map(method => method.envKey));
|
||||
return missingBindings.every((value: unknown) => {
|
||||
const binding = record(value);
|
||||
return binding?.bindingType === "user_secret_ref"
|
||||
&& ["user_secret_missing", "secret_inactive"].includes(String(binding.errorCode))
|
||||
&& typeof binding.envKey === "string" && keys.has(binding.envKey)
|
||||
&& binding.configPath === `env.${binding.envKey}`;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function isAiConnectionConfigurationFailure(run: AuthenticationFailure): boolean {
|
||||
return run.errorCode === "configuration_incomplete" && (
|
||||
record(record(run.resultJson)?.configurationIncomplete)?.reason === "ai_connection_unavailable"
|
||||
|| Boolean(missingPersonalAiCredentialProvider(run))
|
||||
);
|
||||
}
|
||||
|
||||
export function isAiAuthenticationRepairable(run: AuthenticationFailure): boolean {
|
||||
return isAiAuthenticationFailure(run.errorCode) || isAiConnectionConfigurationFailure(run);
|
||||
}
|
||||
|
||||
/** Provider authentication signals only. Tool authorization and quotas need different repairs. */
|
||||
export function isAiAuthenticationFailure(code: string | null | undefined): boolean {
|
||||
@@ -9,15 +48,18 @@ export function isAiAuthenticationFailure(code: string | null | undefined): bool
|
||||
}
|
||||
|
||||
/** Only a persisted blocked classification confirms that an inline repair owns recovery. */
|
||||
export function isAiAuthenticationBlocked(run: { errorCode?: string | null; livenessState?: string | null } | null | undefined): boolean {
|
||||
return run?.livenessState === "blocked" && isAiAuthenticationFailure(run.errorCode);
|
||||
export function isAiAuthenticationBlocked(run: (AuthenticationFailure & { livenessState?: string | null }) | null | undefined): boolean {
|
||||
return run?.livenessState === "blocked" && isAiAuthenticationRepairable(run);
|
||||
}
|
||||
|
||||
export function aiBindingForAuthRecovery(
|
||||
adapterType: string,
|
||||
config: Record<string, unknown>,
|
||||
failure?: AuthenticationFailure,
|
||||
): AiConnectionBinding | undefined {
|
||||
const missingProvider = failure ? missingPersonalAiCredentialProvider(failure) : undefined;
|
||||
for (const provider of AI_PROVIDERS) {
|
||||
if (missingProvider && missingProvider !== provider) continue;
|
||||
const binding = { provider, method: AI_CONNECTION_CAPABILITIES[provider].methods.subscription ? "subscription" : "api_key", mode: "responsible_user" } as const;
|
||||
if (isAiConnectionCompatible(binding, adapterType, config.model, config.provider, config.acpxAgent)) return binding;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { connectionIntentService } from "./connection-intents.js";
|
||||
import { isAiConnectionConfigurationFailure } from "./ai-auth-failure.js";
|
||||
import { and, eq, isNull, lte, asc, notInArray, desc, sql } from "drizzle-orm";
|
||||
import { connectionIntentDeliveries, issueThreadInteractions, issues, agentWakeupRequests, companyMemberships, heartbeatRuns, chatConversations, chatEndpoints, type Db } from "@paperclipai/db";
|
||||
import type { heartbeatService } from "./heartbeat.js";
|
||||
@@ -79,9 +80,8 @@ export function connectionIntentDeliveryService(db: Db, heartbeat: Pick<Heartbea
|
||||
eq(heartbeatRuns.companyId, issue.companyId),
|
||||
sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${issue.id}`,
|
||||
)).orderBy(desc(heartbeatRuns.createdAt)).limit(1);
|
||||
const gap = latest?.resultJson?.configurationIncomplete as { reason?: string } | undefined;
|
||||
if (latest?.id !== loaded.interaction.sourceRunId || latest.status !== "failed"
|
||||
|| latest.errorCode !== "configuration_incomplete" || gap?.reason !== "ai_connection_unavailable") return null;
|
||||
|| !isAiConnectionConfigurationFailure(latest)) return null;
|
||||
// Restricted external chat retries require their original chat provenance.
|
||||
// Their existing Try again path owns that authorization and delivery.
|
||||
const [restrictedChat] = await tx.select({ id: chatConversations.id }).from(chatConversations)
|
||||
|
||||
@@ -6,7 +6,7 @@ import { createHash } from "node:crypto";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { aiConnectionBindingSchema, aiConnectionRouterBindingSchema } from "@paperclipai/shared";
|
||||
import { aiBindingForAuthRecovery, isAiAuthenticationFailure } from "./ai-auth-failure.js";
|
||||
import { aiBindingForAuthRecovery, isAiAuthenticationFailure, isAiAuthenticationRepairable } from "./ai-auth-failure.js";
|
||||
import { and, eq, desc, isNull, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
@@ -162,6 +162,7 @@ export function connectionIntentService(db: Db) {
|
||||
agentId: heartbeatRuns.agentId,
|
||||
status: heartbeatRuns.status,
|
||||
errorCode: heartbeatRuns.errorCode,
|
||||
resultJson: heartbeatRuns.resultJson,
|
||||
responsibleUserId: heartbeatRuns.responsibleUserId,
|
||||
activeIdentityContextId: heartbeatRuns.activeIdentityContextId,
|
||||
contextSnapshot: heartbeatRuns.contextSnapshot,
|
||||
@@ -176,7 +177,7 @@ export function connectionIntentService(db: Db) {
|
||||
|| run.agentId !== claims.sub
|
||||
|| (!run.activeIdentityContextId && run.responsibleUserId !== claims.responsible_user_id)
|
||||
) throw forbidden("Runtime tool token does not match its heartbeat run");
|
||||
if (failedAuthRun ? run.status !== "failed" || !isAiAuthenticationFailure(run.errorCode) : run.status !== "running") {
|
||||
if (failedAuthRun ? run.status !== "failed" || !isAiAuthenticationRepairable(run) : run.status !== "running") {
|
||||
throw forbidden("Runtime tool token is no longer active");
|
||||
}
|
||||
if (run.activeIdentityContextId && !failedAuthRun) {
|
||||
@@ -854,8 +855,8 @@ export function connectionIntentService(db: Db) {
|
||||
eq(heartbeatRuns.agentId, payload.requestingAgentId),
|
||||
));
|
||||
const [agent] = await db.select().from(agents).where(and(eq(agents.id, payload.requestingAgentId), eq(agents.companyId, loaded.issue.companyId)));
|
||||
if (source?.status === "failed" && isAiAuthenticationFailure(source.errorCode) && !source.contextSnapshot?.aiConnection && agent && !agent.runtimeConfig.aiConnection) {
|
||||
managed = await managedAgent(loaded.issue.companyId, agent.id, app.slug, { fallback: aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig) });
|
||||
if (source?.status === "failed" && isAiAuthenticationRepairable(source) && !source.contextSnapshot?.aiConnection && agent && !agent.runtimeConfig.aiConnection) {
|
||||
managed = await managedAgent(loaded.issue.companyId, agent.id, app.slug, { fallback: aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig, source) });
|
||||
}
|
||||
}
|
||||
if (payload.purpose === "ai" && !managed) throw conflict("The agent’s AI configuration changed. Start a new execution.");
|
||||
@@ -1165,7 +1166,7 @@ export function connectionIntentService(db: Db) {
|
||||
// Controller-only entry point. Runtime tokens still require a running run.
|
||||
requestForRunAuthFailure: async (runId: string) => {
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
if (!run || run.status !== "failed" || !isAiAuthenticationFailure(run.errorCode) || !run.responsibleUserId) return null;
|
||||
if (!run || run.status !== "failed" || !isAiAuthenticationRepairable(run) || !run.responsibleUserId) return null;
|
||||
const context = await loadRunContext({ sub: run.agentId, company_id: run.companyId, run_id: run.id, responsible_user_id: run.responsibleUserId }, true);
|
||||
const [latest] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, run.companyId),
|
||||
@@ -1178,7 +1179,7 @@ export function connectionIntentService(db: Db) {
|
||||
const router = aiConnectionRouterBindingSchema.safeParse(agent.runtimeConfig.aiConnection).data;
|
||||
const selected = router ? record(run.contextSnapshot?.aiRouterSelection) : null;
|
||||
const managed = router && selected ? await managedAgent(run.companyId, run.agentId, String(record(selected.binding)?.provider), { sourceRunId: run.id }) : null;
|
||||
const binding = router ? managed?.binding : saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig);
|
||||
const binding = router ? managed?.binding : saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig, run);
|
||||
if (!binding) return null;
|
||||
const attribution = record(run.contextSnapshot?.aiConnection);
|
||||
if (attribution && attribution.provider !== binding.provider) return null;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isAiAuthenticationFailure } from "./ai-auth-failure.js";
|
||||
import { isAiAuthenticationRepairable } from "./ai-auth-failure.js";
|
||||
import type { HeartbeatRunStatus, IssueStatus, RunLivenessState } from "@paperclipai/shared";
|
||||
|
||||
export type RunLivenessActionability =
|
||||
@@ -323,7 +323,7 @@ export function classifyRunLiveness(input: RunLivenessClassificationInput): RunL
|
||||
return output("needs_followup", input.errorCode ? `Run interrupted (${input.errorCode})` : "Run interrupted");
|
||||
}
|
||||
|
||||
if (input.runStatus === "failed" && input.authenticationRepairRequested && isAiAuthenticationFailure(input.errorCode)) {
|
||||
if (input.runStatus === "failed" && input.authenticationRepairRequested && isAiAuthenticationRepairable(input)) {
|
||||
return output("blocked", "Waiting for provider authentication repair", "Complete the connection request to continue this task");
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user