mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 20:09:10 +01:00
fix: recover provider authentication inside tasks (#14629)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents need a working model provider connection to run a task. > - A provider can reject a stored credential after the task starts. > - The failed run must ask the responsible user to repair that connection. > - This pull request adds that request directly to the task and reuses Connections sign-in. > - The user can choose an API key or subscription, then continue the task with a fresh session. ## Linked Issues or Issue Description **What happened?** A run that ended with `acpx_auth_required` or another known provider authentication error did not immediately offer an inline way to connect the provider. A repair form could also lock the user to the failed account's sign-in method. **Expected behavior** Show a provider connection card in the task as soon as the authentication failure is saved. Allow the responsible user to connect or repair the provider with any supported sign-in method. Keep the connection name automatic and resume the task after successful setup. **Steps to reproduce** 1. Run a task with a supported provider and an expired or invalid credential. 2. Let the run fail with a provider authentication error. 3. Open the task and attempt to repair the connection. Related work: Refs #13724 and #13726. This change adds the inline task repair flow and method choice. ## What Changed - Classify provider authentication failures and create one connection request for the current task. A persisted blocked classification suppresses automatic retries only after the repair card is created; unsupported providers retain their existing recovery path. - Mark only the attributed, unchanged credential as needing sign-in. Preserve credentials that were refreshed after the failed run started. - Reuse the provider sign-in controls inside the task. Allow API key and subscription choices for Claude, Codex, and Grok. Keep names hidden and generate a default from the user, provider, and method. - Keep the existing account when reconnecting with the same method. Create and select another account when the method changes. Validate updates to explicit agent bindings through the normal agent save path. - Require explicit adoption for legacy agent authentication. Validate in the agent environment, then commit the binding, connection install, audit, and card completion in one transaction. Keep failed setup and account selection visible and retryable. - Add regression tests and update the specification and Connections documentation. ## Verification - Fresh local verification: 199 tests passed across the inline form, provider method selector, default naming, authentication and recovery classifiers, run liveness, OpenAPI routes, database adoption/rollback, and Cursor execution suites. The adoption database suite also passed against disposable Docker PostgreSQL. - Full repository `pnpm build` and `pnpm -r typecheck` passed on the latest commit. Token gates are clean. - Embedded browser: opened real task cards from seeded authentication failures; switched Claude from API key to subscription and back; switched Codex from subscription to API key; confirmed the name field stays hidden. Provider sign-in was not completed with real credentials. - The broad local `pnpm test:run` started before review fixes and was interrupted after the working tree changed; it is not counted as a passing full run. Fresh focused tests passed. CI supplies the full test and browser suite results for the current commit. - CI is green on commit `4b97a4e447045ff3d7516525a187a5d1d21e0d4c`: 54 checks passed and two Storybook checks were skipped by their path rules. The workspace preview job passed on one rerun after a local-server startup timeout; its rerun passed 835 tests. - Greptile is 5/5 on the same commit with no actionable findings and no unresolved review threads. ## Risks - Incorrect authentication classification could prompt for a connection unnecessarily. Tests exclude tool authorization, quota, and unrelated runtime failures. - A method change selects the new personal provider default, which also applies to other agents that use that user's default. Explicit account bindings use the existing permission and runtime validation path. - Credential invalidation must not race with refresh or reconnect. The code compares the saved credential generation and grant update time under locks. - No database migration or new credential storage format is required. ## Model Used OpenAI GPT-6 through Codex. The exact model ID and context window size were not exposed in this session. Capabilities used: reasoning, repository editing, shell commands, database tests, and embedded-browser interaction. ## 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 (focused tests listed above) - [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 - [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
a027f76a72
commit
2f6fa3b6dc
25 files changed
+748
-58
No files matched your search
@@ -46,6 +46,74 @@ beforeAll(async () => {
|
||||
afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });
|
||||
|
||||
describe("managed AI connections", () => {
|
||||
it.each([
|
||||
["anthropic", false], ["openai", false], ["anthropic", true], ["openai", true],
|
||||
] as const)("turns a %s auth failure into one card and resumes after repair (switch method: %s)", async (provider, switchMethod) => {
|
||||
const userId = `auth-recovery-${provider}-${switchMethod}`;
|
||||
const id = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
const adapterType = provider === "openai" ? "codex_local" : "claude_local";
|
||||
const selectedBinding = { provider, method: "api_key", mode: "responsible_user" } as const;
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "member" });
|
||||
await db.insert(agents).values({ id, companyId, name: "Auth recovery", adapterType, runtimeConfig: { aiConnection: selectedBinding } });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Fix provider login", status: "in_progress", assigneeAgentId: id });
|
||||
const account = await service.save(companyId, userId, { provider, method: "api_key", ownership: "personal", name: "Recovery account", apiKey: "fixture", agentIds: [id], allAgents: false }, "fixture-recovery-key");
|
||||
const runtime = await prepareManagedAiRuntime(db, { companyId, agentId: id, responsibleUserId: userId, adapterType, binding: selectedBinding, config: {} });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: userId,
|
||||
contextSnapshot: { issueId, aiConnection: { ...runtime.attribution, identity: runtime.identity } } });
|
||||
await runtime.cleanup();
|
||||
const intents = connectionIntentService(db);
|
||||
const card = await intents.requestForRunAuthFailure(runId);
|
||||
expect(card).toMatchObject({ state: "needs_user_action", service: provider });
|
||||
expect((await intents.requestForRunAuthFailure(runId))?.interactionId).toBe(card!.interactionId);
|
||||
const setup = await intents.setupOptions(card!.interactionId!);
|
||||
expect(setup.existingConnections).toEqual([]);
|
||||
expect(setup.aiRepair).toMatchObject({ canReconnect: true, connection: { id: account.connectionId, status: "needs_attention" } });
|
||||
await expect(intents.complete(card!.interactionId!, account.connectionId, userId)).rejects.toThrow();
|
||||
// A stopped run's token cannot call the public request path.
|
||||
await expect(intents.request({ sub: id, company_id: companyId, run_id: runId, responsible_user_id: userId }, provider, { purpose: "ai" })).rejects.toThrow("no longer active");
|
||||
// Reverification can keep the same credential bytes; it still supersedes the failure.
|
||||
let repaired = account;
|
||||
if (switchMethod) {
|
||||
const token = provider === "openai" ? JSON.stringify({ tokens: { access_token: "fixture-subscription", refresh_token: "fixture-refresh", id_token: "fixture-id", account_id: "fixture-account" } }) : "fixture-subscription";
|
||||
repaired = await service.save(companyId, userId, { provider, method: "subscription", ownership: "personal", name: "Recovery subscription", loginSessionId: "fixture", agentIds: [id], allAgents: false }, token);
|
||||
await service.setDefault(companyId, userId, repaired.grantId);
|
||||
const [original] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, account.grantId));
|
||||
expect(original.status).toBe("needs_reauthorization");
|
||||
} else {
|
||||
await service.save(companyId, userId, { provider, method: "api_key", ownership: "personal", name: "Recovery account", connectionId: account.connectionId, apiKey: "fixture", agentIds: [id], allAgents: false }, provider === "openai" ? "fixture-recovery-key" : "fixture-repaired-key");
|
||||
}
|
||||
expect((await intents.setupOptions(card!.interactionId!)).existingConnections.map(connection => connection.id)).toEqual([repaired.connectionId]);
|
||||
await intents.complete(card!.interactionId!, repaired.connectionId, userId);
|
||||
const wakeup = vi.fn(async (_agentId, opts) => {
|
||||
await db.insert(agentWakeupRequests).values({ companyId, agentId: id, source: "automation", status: "queued", idempotencyKey: opts.idempotencyKey });
|
||||
return null;
|
||||
});
|
||||
await connectionIntentDeliveryService(db, { wakeup } as never).deliver(card!.interactionId!);
|
||||
expect(wakeup).toHaveBeenCalledTimes(1);
|
||||
expect(wakeup).toHaveBeenCalledWith(id, expect.objectContaining({ contextSnapshot: expect.objectContaining({ forceFreshSession: true }) }));
|
||||
// Reprocessing an old failure cannot invalidate the newly saved credential.
|
||||
await intents.requestForRunAuthFailure(runId);
|
||||
expect((await service.select({ companyId, agentId: id, userId, adapterType, binding: selectedBinding })).grant.status).toBe("active");
|
||||
});
|
||||
|
||||
it("offers a compatible connection for legacy auth failures without silently adopting it", async () => {
|
||||
const id = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
await db.insert(agents).values({ id, companyId, name: "Legacy Codex", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" } });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Legacy auth", status: "in_progress", assigneeAgentId: id });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, nativeIssueId: issueId, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: "alice", contextSnapshot: {} });
|
||||
const intents = connectionIntentService(db);
|
||||
const card = await intents.requestForRunAuthFailure(runId);
|
||||
expect(card).toMatchObject({ service: "openai", state: "needs_user_action" });
|
||||
expect(await intents.setupOptions(card!.interactionId!)).toMatchObject({ aiConnectionRequiresAdoption: true, aiConnection: { provider: "openai", mode: "responsible_user" } });
|
||||
const [unchanged] = await db.select().from(agents).where(eq(agents.id, id));
|
||||
expect(unchanged.runtimeConfig.aiConnection).toBeUndefined();
|
||||
await db.insert(heartbeatRuns).values({ companyId, agentId: id, status: "succeeded", responsibleUserId: "alice", contextSnapshot: { issueId }, createdAt: new Date(Date.now() + 1000) });
|
||||
expect(await intents.requestForRunAuthFailure(runId)).toBeNull();
|
||||
});
|
||||
it.each([
|
||||
["anthropic", "claude_local", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
|
||||
["openai", "codex_local", "CODEX_HOME", "OPENAI_API_KEY"],
|
||||
@@ -668,7 +736,7 @@ describe("managed AI connections", () => {
|
||||
expect((await service.select(selectionInput)).grant.id).toBe(account.grantId);
|
||||
});
|
||||
|
||||
it("validates runner account adoption in the inherited sandbox and refuses an unavailable target", async () => {
|
||||
it.each([false, true])("validates runner account adoption in the inherited sandbox (inline: %s)", async (inline) => {
|
||||
const { agentRoutes } = await import("../routes/agents.js");
|
||||
const { instanceSettingsService } = await import("../services/instance-settings.js");
|
||||
const targetModule = await import("../services/environment-execution-target.js");
|
||||
@@ -676,12 +744,20 @@ describe("managed AI connections", () => {
|
||||
const { requireServerAdapter } = await import("../adapters/index.js");
|
||||
const settings = instanceSettingsService(db);
|
||||
const previous = await settings.get();
|
||||
const [environment] = await db.insert(environments).values({ name: "Adoption sandbox", driver: "sandbox", config: { provider: "daytona" } }).returning();
|
||||
const [environment] = await db.insert(environments).values({ name: `Adoption sandbox ${inline}`, driver: "sandbox", config: { provider: "daytona" } }).returning();
|
||||
await settings.update({ defaultEnvironmentId: environment.id });
|
||||
const id = randomUUID();
|
||||
await db.insert(agents).values({ id, companyId, name: "Runner adoption", adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-5.6-sol" } });
|
||||
const account = await service.save(companyId, "alice", { provider: "openai", method: "api_key", ownership: "personal", name: "Runner adoption account", apiKey: "fixture-adoption-key", agentIds: [id], allAgents: false }, "fixture-adoption-key");
|
||||
const account = await service.save(companyId, "alice", { provider: "openai", method: "api_key", ownership: "personal", name: "Runner adoption account", apiKey: "fixture-adoption-key", agentIds: inline ? [] : [id], allAgents: false }, "fixture-adoption-key");
|
||||
await service.setDefault(companyId, "alice", account.grantId);
|
||||
let interactionId: string | undefined;
|
||||
if (inline) {
|
||||
const issueId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Atomic adoption", status: "in_progress", assigneeAgentId: id });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: "alice", contextSnapshot: { issueId } });
|
||||
interactionId = (await connectionIntentService(db).requestForRunAuthFailure(runId))!.interactionId!;
|
||||
}
|
||||
const target = { kind: "remote", transport: "sandbox", remoteCwd: "/workspace", providerKey: "daytona", runner: { execute: vi.fn(async () => ({ exitCode: 0, stdout: "", stderr: "", timedOut: false })) } } as const;
|
||||
const resolveTarget = vi.spyOn(targetModule, "resolveEnvironmentExecutionTarget").mockResolvedValue(target);
|
||||
const release = vi.fn(async () => undefined);
|
||||
@@ -695,26 +771,54 @@ describe("managed AI connections", () => {
|
||||
app.use((error: { status?: number; message: string }, _req: express.Request, res: express.Response, _next: express.NextFunction) => { res.status(error.status ?? 500).json({ error: error.message }); });
|
||||
const selected = { provider: "openai", method: "api_key", mode: "responsible_user" } as const;
|
||||
const providerRequest = vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(null, { status: 200 }));
|
||||
const adopt = () => inline
|
||||
? request(app).post(`/api/agents/${id}/connection-intents/${interactionId}/adopt`).send({ connectionId: account.connectionId })
|
||||
: request(app).patch(`/api/agents/${id}`).send({ runtimeConfig: { aiConnection: selected } });
|
||||
try {
|
||||
// Target resolution can return only warning checks. Adoption still must
|
||||
// fail closed, rather than quietly running the probe on the server host.
|
||||
resolveTarget.mockResolvedValueOnce(null);
|
||||
const unavailable = await request(app).patch(`/api/agents/${id}`).send({ runtimeConfig: { aiConnection: selected } });
|
||||
const unavailable = await adopt();
|
||||
expect(unavailable.status, JSON.stringify(unavailable.body)).toBe(422);
|
||||
expect(probe).not.toHaveBeenCalled();
|
||||
expect(providerRequest).not.toHaveBeenCalled();
|
||||
expect((await db.select().from(agents).where(eq(agents.id, id)))[0].runtimeConfig.aiConnection).toBeUndefined();
|
||||
const saved = await request(app).patch(`/api/agents/${id}`).send({ runtimeConfig: { aiConnection: selected } });
|
||||
if (inline) {
|
||||
const assertUnchanged = async () => {
|
||||
expect((await db.select().from(agents).where(eq(agents.id, id)))[0].runtimeConfig.aiConnection).toBeUndefined();
|
||||
expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.connectionId))).toEqual([]);
|
||||
expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId!)))[0].status).toBe("pending");
|
||||
};
|
||||
await assertUnchanged();
|
||||
// Force the last write to fail after binding and install changes.
|
||||
await db.execute(sql.raw(`CREATE FUNCTION reject_atomic_adoption() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.id = '${interactionId}'::uuid THEN RAISE EXCEPTION 'injected resolution failure'; END IF; RETURN NEW; END $$`));
|
||||
await db.execute(sql.raw("CREATE TRIGGER reject_atomic_adoption BEFORE UPDATE ON issue_thread_interactions FOR EACH ROW EXECUTE FUNCTION reject_atomic_adoption()"));
|
||||
try {
|
||||
const failed = await adopt();
|
||||
expect(failed.status).toBe(500);
|
||||
await assertUnchanged();
|
||||
} finally {
|
||||
await db.execute(sql.raw("DROP TRIGGER reject_atomic_adoption ON issue_thread_interactions"));
|
||||
await db.execute(sql.raw("DROP FUNCTION reject_atomic_adoption()"));
|
||||
}
|
||||
}
|
||||
const saved = await adopt();
|
||||
expect(saved.status, JSON.stringify(saved.body)).toBe(200);
|
||||
expect(saved.body.defaultEnvironmentId).toBeNull();
|
||||
expect(saved.body.runtimeConfig.aiConnection).toEqual(selected);
|
||||
const savedAgent = (await db.select().from(agents).where(eq(agents.id, id)))[0];
|
||||
expect(savedAgent.defaultEnvironmentId).toBeNull();
|
||||
expect(savedAgent.runtimeConfig.aiConnection).toEqual(inline ? { ...selected, method: "subscription" } : selected);
|
||||
if (inline) {
|
||||
expect(saved.body.status).toBe("accepted");
|
||||
expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.connectionId))).toHaveLength(1);
|
||||
expect((await adopt()).status).toBe(200);
|
||||
}
|
||||
expect(acquire).toHaveBeenCalledWith(expect.objectContaining({ companyId, environment: expect.objectContaining({ id: environment.id }) }));
|
||||
expect(probe).toHaveBeenCalledWith(expect.objectContaining({ executionTarget: target, config: expect.objectContaining({ provider: "codex", model: "gpt-5.6-sol", managedAiConnection: expect.any(Object) }) }));
|
||||
expect(providerRequest).toHaveBeenCalledWith("https://api.openai.com/v1/models", expect.objectContaining({
|
||||
headers: { Authorization: "Bearer fixture-adoption-key" },
|
||||
redirect: "error",
|
||||
}));
|
||||
expect(release).toHaveBeenCalledTimes(2);
|
||||
expect(release).toHaveBeenCalledTimes(inline ? 3 : 2);
|
||||
expect(JSON.stringify(saved.body)).not.toContain("fixture-adoption-key");
|
||||
} finally {
|
||||
providerRequest.mockRestore(); probe.mockRestore(); runtime.mockRestore(); resolveTarget.mockRestore();
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import { completeConnectionIntentSchema } from "@paperclipai/shared";
|
||||
import { agentFileStore, agentFileTokenFromHash } from "../services/agent-file-store.js";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { resolveAgentAppearance, agentAvatarUrl } from "@paperclipai/shared";
|
||||
@@ -5367,6 +5369,34 @@ export function agentRoutes(
|
||||
res.json(result.bundle);
|
||||
});
|
||||
|
||||
router.post("/agents/:id/connection-intents/:interactionId/adopt", validate(completeConnectionIntentSchema), async (req, res) => {
|
||||
assertBoard(req);
|
||||
const agent = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Agent not found");
|
||||
if (!agent) return;
|
||||
await assertCanUpdateAgent(req, agent);
|
||||
const userId = responsibleUserForAiRequest(req);
|
||||
const intents = connectionIntentService(db);
|
||||
const interactionId = req.params.interactionId as string;
|
||||
const loaded = await intents.loadIntent(interactionId);
|
||||
if (loaded.issue.companyId !== agent.companyId || loaded.interaction.payload.requestingAgentId !== agent.id) throw notFound("Connection intent not found");
|
||||
if (!userId || loaded.interaction.addresseeUserId !== userId) throw forbidden("Only the addressed user can adopt this connection");
|
||||
const connectionId = req.body.connectionId as string;
|
||||
if (loaded.interaction.status === "accepted" && loaded.interaction.result?.connectionId === connectionId) {
|
||||
res.json(loaded.interaction);
|
||||
return;
|
||||
}
|
||||
if (loaded.interaction.status !== "pending") throw conflict("Connection intent is already resolved");
|
||||
const setup = await intents.setupOptions(interactionId);
|
||||
if (!setup.aiConnectionRequiresAdoption || !setup.aiConnection) throw conflict("The agent’s AI configuration changed. Reload the task and try again.");
|
||||
// Probe in the agent's execution environment without installing access.
|
||||
// The binding, install, audit, and card resolution commit together below.
|
||||
const validatedConnectionId = await validateManagedAgentBinding(req, agent.companyId, agent.id, agent.adapterType, agent.adapterConfig, setup.aiConnection, agent.defaultEnvironmentId, true, true);
|
||||
if (validatedConnectionId !== connectionId) throw conflict("This is no longer the selected account. Reload the task and try again.");
|
||||
res.json(await intents.complete(interactionId, connectionId, userId, {
|
||||
validatedAdoption: { agentUpdatedAt: agent.updatedAt, binding: setup.aiConnection },
|
||||
}));
|
||||
});
|
||||
|
||||
router.patch("/agents/:id", validate(updateAgentSchema), async (req, res) => {
|
||||
const id = req.params.id as string;
|
||||
const existing = await getAccessibleResource(req, res, svc.getById(id), "Agent not found");
|
||||
|
||||
@@ -1442,6 +1442,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"GET /api/connection-intents/{interactionId}/setup-options",
|
||||
"POST /api/connection-intents/{interactionId}/phase",
|
||||
"POST /api/connection-intents/{interactionId}/complete",
|
||||
"POST /api/agents/{id}/connection-intents/{interactionId}/adopt",
|
||||
"POST /api/connection-intents/{interactionId}/decline",
|
||||
"GET /api/companies/{companyId}/tools/profiles",
|
||||
"POST /api/companies/{companyId}/tools/profiles",
|
||||
@@ -10256,6 +10257,23 @@ registerCurrentRoute({
|
||||
body: completeConnectionIntentSchema,
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/agents/{id}/connection-intents/{interactionId}/adopt",
|
||||
tags: ["connection-intents", "agents"],
|
||||
summary: "Validate and atomically adopt an AI connection for a legacy agent",
|
||||
body: completeConnectionIntentSchema,
|
||||
responses: {
|
||||
200: r.ok(),
|
||||
400: r.badRequest,
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
404: r.notFound,
|
||||
409: r.conflict,
|
||||
422: r.unprocessable,
|
||||
},
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "post",
|
||||
path: "/api/connection-intents/{interactionId}/decline",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { aiBindingForAuthRecovery, isAiAuthenticationFailure } from "./ai-auth-failure.js";
|
||||
|
||||
describe("AI authentication failure recovery", () => {
|
||||
it.each(["acpx_auth_required", "claude_auth_required", "codex_auth_required", "grok_auth_required", "adapter_auth_missing", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"])("recognizes %s", (code) => {
|
||||
expect(isAiAuthenticationFailure(code)).toBe(true);
|
||||
});
|
||||
it.each(["github_auth_required", "native_adopted_runner_authentication_timeout", "rate_limit", "adapter_failed", "permission_denied", undefined])("does not treat %s as model authentication", (code) => {
|
||||
expect(isAiAuthenticationFailure(code)).toBe(false);
|
||||
});
|
||||
it.each([
|
||||
["codex_local", {}, "openai"],
|
||||
["claude_local", {}, "anthropic"],
|
||||
["paperclip_runner", { provider: "codex" }, "openai"],
|
||||
["paperclip_runner", { provider: "acpx", acpxAgent: "claude" }, "anthropic"],
|
||||
["paperclip_runner", { provider: "acpx", acpxAgent: "grok" }, "xai"],
|
||||
["opencode_local", { model: "openrouter/model" }, "openrouter"],
|
||||
] as const)("maps %s %j to %s", (adapter, config, provider) => {
|
||||
expect(aiBindingForAuthRecovery(adapter, config)).toMatchObject({ provider, mode: "responsible_user" });
|
||||
});
|
||||
it("does not guess a provider for unsupported harnesses or routes", () => {
|
||||
expect(aiBindingForAuthRecovery("gemini_local", {})).toBeUndefined();
|
||||
expect(aiBindingForAuthRecovery("opencode_local", { model: "anthropic/claude" })).toBeUndefined();
|
||||
expect(aiBindingForAuthRecovery("paperclip_runner", { provider: "acpx", acpxAgent: "custom" })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { AI_PROVIDERS, isAiConnectionCompatible, type AiConnectionBinding } from "@paperclipai/shared";
|
||||
|
||||
/** Provider authentication signals only. Tool authorization and quotas need different repairs. */
|
||||
export function isAiAuthenticationFailure(code: string | null | undefined): boolean {
|
||||
return Boolean(code && (
|
||||
/^(acpx|claude|codex|grok|opencode|gemini|kimi|pi|cursor)_auth_required$/.test(code)
|
||||
|| ["adapter_auth_missing", "authentication_required", "auth_required", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"].includes(code)
|
||||
));
|
||||
}
|
||||
|
||||
/** 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 aiBindingForAuthRecovery(
|
||||
adapterType: string,
|
||||
config: Record<string, unknown>,
|
||||
): AiConnectionBinding | undefined {
|
||||
for (const provider of AI_PROVIDERS) {
|
||||
const binding = { provider, method: provider === "openrouter" ? "api_key" : "subscription", mode: "responsible_user" } as const;
|
||||
if (isAiConnectionCompatible(binding, adapterType, config.model, config.provider, config.acpxAgent)) return binding;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { syncConnectionCredentialBindings } from "./connection-credential-bindings.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { and, eq, inArray, or } from "drizzle-orm";
|
||||
import {
|
||||
type Db,
|
||||
@@ -373,7 +373,7 @@ export function aiConnectionService(db: Db) {
|
||||
} satisfies AiConnectionAttribution,
|
||||
};
|
||||
}
|
||||
async function credential(row: Awaited<ReturnType<typeof select>>) {
|
||||
async function credential(row: Pick<Awaited<ReturnType<typeof select>>, "connection" | "grant">) {
|
||||
const ref = row.grant.credentialSecretRefs.find(
|
||||
(r) => r.configPath === "ai.credential",
|
||||
);
|
||||
@@ -775,5 +775,49 @@ export function aiConnectionService(db: Db) {
|
||||
return { connectionId: id, grantId };
|
||||
});
|
||||
}
|
||||
return { list, select, credential, save, setDefault, membership };
|
||||
/** A late failure must never invalidate credentials that were refreshed or reconnected meanwhile. */
|
||||
async function markAuthenticationFailed(input: {
|
||||
companyId: string;
|
||||
runId: string;
|
||||
agentId: string;
|
||||
runStartedAt: Date;
|
||||
attribution: AiConnectionAttribution & { identity: string };
|
||||
}) {
|
||||
return db.transaction(async (tx) => {
|
||||
const { attribution } = input;
|
||||
const [grant] = await tx.select().from(connectionGrants).where(and(
|
||||
eq(connectionGrants.companyId, input.companyId),
|
||||
eq(connectionGrants.id, attribution.grantId),
|
||||
eq(connectionGrants.connectionId, attribution.connectionId),
|
||||
)).for("update");
|
||||
if (!grant || grant.status !== "active" || grant.updatedAt > input.runStartedAt) return;
|
||||
const [connection] = await tx.select().from(toolConnections).where(and(
|
||||
eq(toolConnections.companyId, input.companyId),
|
||||
eq(toolConnections.id, attribution.connectionId),
|
||||
eq(toolConnections.connectionPurpose, "ai"),
|
||||
));
|
||||
if (!connection) return;
|
||||
const metadata = aiConnectionMetadataSchema.safeParse(connection.config.ai);
|
||||
if (!metadata.success || metadata.data.provider !== attribution.provider || metadata.data.method !== attribution.method) return;
|
||||
const ref = grant.credentialSecretRefs.find((candidate) => candidate.configPath === "ai.credential");
|
||||
if (!ref) return;
|
||||
await tx.select({ id: companySecrets.id }).from(companySecrets).where(and(
|
||||
eq(companySecrets.companyId, input.companyId), eq(companySecrets.id, ref.secretId),
|
||||
)).for("update");
|
||||
const value = await aiConnectionService(tx as unknown as Db).credential({ connection, grant });
|
||||
const generation = createHash("sha256").update(value).digest("hex").slice(0, 16);
|
||||
if (attribution.identity !== `${grant.id}:${attribution.responsibleUserId ?? "shared"}:${generation}`) return;
|
||||
await tx.update(connectionGrants).set({ status: "needs_reauthorization", updatedAt: new Date() })
|
||||
.where(eq(connectionGrants.id, grant.id));
|
||||
await tx.update(toolConnections).set({ healthStatus: "error", healthMessage: "Sign in again to restore this AI connection.", updatedAt: new Date() })
|
||||
.where(eq(toolConnections.id, connection.id));
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId: input.companyId, actorType: "system", actorId: "heartbeat",
|
||||
agentId: input.agentId, runId: input.runId, action: "ai_connection.authentication_failed",
|
||||
entityType: "tool_connection", entityId: connection.id,
|
||||
details: { provider: attribution.provider, grantId: grant.id },
|
||||
});
|
||||
});
|
||||
}
|
||||
return { list, select, credential, save, setDefault, membership, markAuthenticationFailed };
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { agentService } from "./agents.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { aiConnectionBindingSchema } from "@paperclipai/shared";
|
||||
import { and, eq, desc, isNull } from "drizzle-orm";
|
||||
import { aiBindingForAuthRecovery, isAiAuthenticationFailure } from "./ai-auth-failure.js";
|
||||
import { and, eq, desc, isNull, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
@@ -30,6 +32,8 @@ import {
|
||||
type ConnectionsSearchResult,
|
||||
type ToolApplication,
|
||||
type ToolConnection,
|
||||
type AiConnectionAttribution,
|
||||
type AiConnectionBinding,
|
||||
} from "@paperclipai/shared";
|
||||
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import type { RuntimeToolsTokenClaims } from "../runtime-tools-token.js";
|
||||
@@ -137,16 +141,18 @@ export function connectionIntentService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRunContext(claims: ConnectionRunClaims) {
|
||||
async function loadRunContext(claims: ConnectionRunClaims, failedAuthRun = false) {
|
||||
let run = await db
|
||||
.select({
|
||||
id: heartbeatRuns.id,
|
||||
companyId: heartbeatRuns.companyId,
|
||||
agentId: heartbeatRuns.agentId,
|
||||
status: heartbeatRuns.status,
|
||||
errorCode: heartbeatRuns.errorCode,
|
||||
responsibleUserId: heartbeatRuns.responsibleUserId,
|
||||
activeIdentityContextId: heartbeatRuns.activeIdentityContextId,
|
||||
contextSnapshot: heartbeatRuns.contextSnapshot,
|
||||
nativeIssueId: heartbeatRuns.nativeIssueId,
|
||||
})
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, claims.run_id))
|
||||
@@ -157,14 +163,16 @@ 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 (run.status !== "running") throw forbidden("Runtime tool token is no longer active");
|
||||
if (run.activeIdentityContextId) {
|
||||
if (failedAuthRun ? run.status !== "failed" || !isAiAuthenticationFailure(run.errorCode) : run.status !== "running") {
|
||||
throw forbidden("Runtime tool token is no longer active");
|
||||
}
|
||||
if (run.activeIdentityContextId && !failedAuthRun) {
|
||||
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);
|
||||
const issueId = text(snapshot?.issueId) ?? text(snapshot?.taskId) ?? run.nativeIssueId;
|
||||
if (!issueId) throw unprocessable("Connection requests require a task-bound heartbeat run");
|
||||
const [issue, agent, responsibleMembership] = await Promise.all([
|
||||
db.select({
|
||||
@@ -214,10 +222,11 @@ export function connectionIntentService(db: Db) {
|
||||
};
|
||||
}
|
||||
|
||||
async function managedAgent(companyId: string, agentId: string, serviceSlug: string) {
|
||||
async function managedAgent(companyId: string, agentId: string, serviceSlug: string, fallback?: AiConnectionBinding) {
|
||||
const [agent] = await db.select().from(agents).where(and(eq(agents.companyId, companyId), eq(agents.id, agentId)));
|
||||
const binding = aiConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data;
|
||||
return agent && binding?.provider === serviceSlug ? { agent, binding } : null;
|
||||
const saved = aiConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data;
|
||||
const binding = saved ?? fallback;
|
||||
return agent && binding?.provider === serviceSlug ? { agent, binding, requiresAdoption: !saved } : null;
|
||||
}
|
||||
|
||||
async function usableConnectionForAgent(input: {
|
||||
@@ -534,6 +543,15 @@ export function connectionIntentService(db: Db) {
|
||||
options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {},
|
||||
): Promise<ConnectionRequestResult> {
|
||||
const context = await loadRunContext(claims);
|
||||
return requestWithContext(context, serviceSlug, options);
|
||||
}
|
||||
|
||||
async function requestWithContext(
|
||||
context: Awaited<ReturnType<typeof loadRunContext>>,
|
||||
serviceSlug: string,
|
||||
options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {},
|
||||
): Promise<ConnectionRequestResult> {
|
||||
const claims = { sub: context.agent.id, company_id: context.run.companyId, run_id: context.run.id, responsible_user_id: context.run.responsibleUserId! };
|
||||
const route = parseAggregatorRoute(serviceSlug);
|
||||
let upstreamService: { slug: string; name: string; selectionInteractionId?: string } | undefined;
|
||||
if (options.targetService) {
|
||||
@@ -645,13 +663,34 @@ export function connectionIntentService(db: Db) {
|
||||
const loaded = await loadIntent(interactionId);
|
||||
const payload = connectionIntentPayloadSchema.parse(loaded.interaction.payload);
|
||||
const app = await resolveService(payload.serviceSlug, loaded.issue.companyId, loaded.interaction.addresseeUserId!, payload.requestingAgentId, payload.purpose);
|
||||
const managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null;
|
||||
let managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null;
|
||||
if (payload.purpose === "ai" && !managed) {
|
||||
const [source] = await db.select().from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.id, loaded.interaction.sourceRunId!), eq(heartbeatRuns.companyId, loaded.issue.companyId),
|
||||
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, aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig));
|
||||
}
|
||||
}
|
||||
if (payload.purpose === "ai" && !managed) throw conflict("The agent’s AI configuration changed. Start a new execution.");
|
||||
const inventory = await connectionInventory(loaded.issue.companyId);
|
||||
const usableAiConnection = managed ? await usableConnectionForAgent({
|
||||
let usableAiConnection = managed ? await usableConnectionForAgent({
|
||||
companyId: loaded.issue.companyId, agentId: payload.requestingAgentId,
|
||||
responsibleUserId: loaded.interaction.addresseeUserId!, serviceSlug: app.slug, purpose: "ai",
|
||||
}) : null;
|
||||
if (managed?.requiresAdoption) {
|
||||
try {
|
||||
const selected = await aiConnectionService(db).select({
|
||||
companyId: loaded.issue.companyId, agentId: managed.agent.id, userId: loaded.interaction.addresseeUserId!,
|
||||
adapterType: managed.agent.adapterType, model: managed.agent.adapterConfig.model,
|
||||
runnerProvider: managed.agent.adapterConfig.provider, acpxAgent: managed.agent.adapterConfig.acpxAgent,
|
||||
binding: managed.binding, allowUninstalledPersonal: true,
|
||||
});
|
||||
usableAiConnection = await access.getConnection(selected.connection.id, loaded.issue.companyId);
|
||||
} catch (error) { if (![403, 404, 422].includes((error as { status?: number }).status ?? 0)) throw error; }
|
||||
}
|
||||
const aiAccounts = managed ? await aiConnectionService(db).list(loaded.issue.companyId, loaded.interaction.addresseeUserId!) : [];
|
||||
const selectedAiAccount = managed ? aiAccounts.find((account) =>
|
||||
account.provider === managed.binding.provider && (managed.binding.mode === "responsible_user" || account.method === managed.binding.method)
|
||||
@@ -694,6 +733,7 @@ export function connectionIntentService(db: Db) {
|
||||
})),
|
||||
requestedAgentId: payload.requestingAgentId,
|
||||
aiConnection: managed?.binding,
|
||||
aiConnectionRequiresAdoption: managed?.requiresAdoption || undefined,
|
||||
aiRepair: selectedAiAccount ? {
|
||||
connection: selectedAiAccount,
|
||||
canReconnect: selectedAiGrant?.createdByUserId === loaded.interaction.addresseeUserId
|
||||
@@ -711,6 +751,7 @@ export function connectionIntentService(db: Db) {
|
||||
options: {
|
||||
canManageOrganizationGrant?: boolean;
|
||||
bypassCurrentMembershipCheck?: boolean;
|
||||
validatedAdoption?: { agentUpdatedAt: Date; binding: AiConnectionBinding };
|
||||
} = {},
|
||||
) {
|
||||
const loaded = await loadIntent(interactionId);
|
||||
@@ -760,7 +801,27 @@ export function connectionIntentService(db: Db) {
|
||||
if (payload.purpose === "ai" && selectedConnection.connectionPurpose !== "ai") throw conflict("Select an AI account for this authentication request");
|
||||
if (selectedConnection.connectionPurpose === "ai") {
|
||||
if (payload.purpose !== "ai") throw conflict("AI authentication cannot satisfy a tool connection request");
|
||||
const managed = await managedAgent(loaded.issue.companyId, payload.requestingAgentId, payload.serviceSlug);
|
||||
let managed;
|
||||
if (options.validatedAdoption) {
|
||||
const [agent] = await tx.select().from(agents).where(and(eq(agents.id, payload.requestingAgentId), eq(agents.companyId, loaded.issue.companyId))).for("update");
|
||||
if (!agent || agent.runtimeConfig.aiConnection || agent.updatedAt.getTime() !== options.validatedAdoption.agentUpdatedAt.getTime()) {
|
||||
throw conflict("The agent changed during validation. Reload the task and try again.");
|
||||
}
|
||||
const binding = options.validatedAdoption.binding;
|
||||
if (binding.provider !== payload.serviceSlug || binding.mode !== "responsible_user") throw conflict("Invalid legacy adoption binding");
|
||||
const updated = await agentService(txDb).update(agent.id, {
|
||||
runtimeConfig: { ...agent.runtimeConfig, aiConnection: binding },
|
||||
}, { recordRevision: { createdByUserId: userId, source: "patch" } });
|
||||
if (!updated) throw notFound("Agent not found");
|
||||
await logActivity(txDb, {
|
||||
companyId: loaded.issue.companyId, actorType: "user", actorId: userId,
|
||||
action: "agent.updated", entityType: "agent", entityId: agent.id,
|
||||
details: { connectionIntentId: interactionId, aiConnectionAdopted: true },
|
||||
});
|
||||
managed = { agent: updated, binding, requiresAdoption: false };
|
||||
} else {
|
||||
managed = await managedAgent(loaded.issue.companyId, payload.requestingAgentId, payload.serviceSlug);
|
||||
}
|
||||
if (!managed) throw conflict("Configure the agent’s AI connection before using this account");
|
||||
const service = aiConnectionService(txDb);
|
||||
if (managed.binding.mode === "responsible_user") {
|
||||
@@ -883,6 +944,30 @@ export function connectionIntentService(db: Db) {
|
||||
usableConnectionForAgent,
|
||||
search,
|
||||
request,
|
||||
// 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;
|
||||
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),
|
||||
sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId', ${heartbeatRuns.nativeIssueId}::text) = ${context.issue.id}`,
|
||||
)).orderBy(desc(heartbeatRuns.createdAt)).limit(1);
|
||||
if (latest?.id !== run.id) return null;
|
||||
const [agent] = await db.select().from(agents).where(and(eq(agents.id, run.agentId), eq(agents.companyId, run.companyId)));
|
||||
if (!agent) return null;
|
||||
const saved = aiConnectionBindingSchema.safeParse(agent.runtimeConfig.aiConnection).data;
|
||||
const binding = saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig);
|
||||
if (!binding) return null;
|
||||
const attribution = record(run.contextSnapshot?.aiConnection);
|
||||
if (attribution && attribution.provider !== binding.provider) return null;
|
||||
if (saved && attribution && typeof attribution.identity === "string" && typeof attribution.connectionId === "string" && typeof attribution.grantId === "string") {
|
||||
await aiConnectionService(db).markAuthenticationFailed({ companyId: run.companyId, runId: run.id, agentId: run.agentId,
|
||||
runStartedAt: run.startedAt ?? run.createdAt,
|
||||
attribution: attribution as unknown as AiConnectionAttribution & { identity: string } });
|
||||
}
|
||||
return requestWithContext(context, binding.provider, { purpose: "ai" });
|
||||
},
|
||||
loadIntent,
|
||||
setupOptions,
|
||||
complete,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isAiAuthenticationBlocked } from "./ai-auth-failure.js";
|
||||
import { CHAT_COMPLETION_WAKE_REASON, prepareChatCompletionTurn, chatCompletionInstruction, isCompletedOnboardingHandoffWake } from "./chat-completion-delivery.js";
|
||||
import { isAgentDirectoryCopy } from "./agent-directory-working-copies.js";
|
||||
|
||||
@@ -18295,9 +18296,16 @@ export function heartbeatService(
|
||||
run: typeof heartbeatRuns.$inferSelect,
|
||||
resultJson?: Record<string, unknown> | null,
|
||||
) {
|
||||
const classification = classifyRunLiveness(
|
||||
await buildRunLivenessInput(run, resultJson),
|
||||
);
|
||||
const authRepair = run.status === "failed"
|
||||
? await connectionIntentService(db).requestForRunAuthFailure(run.id).catch(() => {
|
||||
logger.warn({ runId: run.id }, "Could not attach provider authentication repair; run failure remains available");
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
const classification = classifyRunLiveness({
|
||||
...await buildRunLivenessInput(run, resultJson),
|
||||
authenticationRepairRequested: Boolean(authRepair?.interactionId),
|
||||
});
|
||||
return db
|
||||
.update(heartbeatRuns)
|
||||
.set({
|
||||
@@ -21436,7 +21444,7 @@ export function heartbeatService(
|
||||
await finalizeAiConnectionBusyDeferral(run, error, !authorizedNonAssigneeWake);
|
||||
return;
|
||||
}
|
||||
if (responsibleUserId && issueId && aiBinding.mode === "responsible_user") {
|
||||
if (responsibleUserId && issueId) {
|
||||
await connectionIntentService(db).request({ sub: agent.id, company_id: agent.companyId, run_id: run.id, responsible_user_id: responsibleUserId }, aiBinding.provider, { purpose: "ai" }).catch(() => {
|
||||
logger.warn({ runId: run.id, agentId: agent.id }, "Could not attach AI connection request; runtime configuration action remains available");
|
||||
});
|
||||
@@ -26443,11 +26451,14 @@ export function heartbeatService(
|
||||
options: { suppressImmediateRecovery?: boolean } = {},
|
||||
) {
|
||||
try {
|
||||
const source = await getRun(run.id);
|
||||
const { postCommitEffects } = await wakeQueue.releaseIssueExecution({
|
||||
companyId: run.companyId,
|
||||
runId: run.id,
|
||||
now: new Date(),
|
||||
suppressImmediateRecovery: options.suppressImmediateRecovery,
|
||||
// A durable authentication card owns recovery. This covers the review path,
|
||||
// while continuation classification blocks periodic generic retries.
|
||||
suppressImmediateRecovery: options.suppressImmediateRecovery || isAiAuthenticationBlocked(source),
|
||||
});
|
||||
await applyWakeQueuePostCommitEffects(postCommitEffects);
|
||||
const completed = await getRun(run.id);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { classifyRunLiveness } from "../run-liveness.js";
|
||||
import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
PROVIDER_QUOTA_RECOVERY_DEFAULT_BACKOFF_MS,
|
||||
@@ -7,6 +9,20 @@ import {
|
||||
import { legacyExecutionNeedsReconciliation } from "../legacy-execution-recovery.js";
|
||||
|
||||
describe("classifyAdapterFailureForRecovery", () => {
|
||||
it.each(["acpx_auth_required", "claude_auth_required", "codex_auth_required", "adapter_auth_missing", "refresh_token_reused", "authentication_required"])("does not automatically retry provider authentication failure %s", (errorCode) => {
|
||||
const classification = classifyRunLiveness({ runStatus: "failed", issue: null, errorCode, authenticationRepairRequested: true });
|
||||
const run = { errorCode, ...classification };
|
||||
expect(isAiAuthenticationBlocked(run)).toBe(true);
|
||||
expect(classifyContinuationFailure(run as never)).toMatchObject({ kind: "non_retryable", maxAttempts: 0 });
|
||||
});
|
||||
|
||||
it.each(["kimi_auth_required", "acpx_auth_required", "gemini_auth_required"])("preserves recovery when %s did not produce an inline repair card", (errorCode) => {
|
||||
const classification = classifyRunLiveness({ runStatus: "failed", issue: null, errorCode, authenticationRepairRequested: false });
|
||||
const run = { errorCode, ...classification };
|
||||
expect(isAiAuthenticationBlocked(run)).toBe(false);
|
||||
expect(classifyContinuationFailure(run as never).kind).toBe("default");
|
||||
});
|
||||
|
||||
it("uses a typed ACP quota reset without needing the provider's original message", () => {
|
||||
const now = new Date("2026-07-15T20:00:00.000Z");
|
||||
expect(classifyAdapterFailureForRecovery({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
|
||||
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
|
||||
import { settleSlackConversation } from "../slack-conversation-lifecycle.js";
|
||||
import { externalConversationStateSql } from "../slack-conversation-state.js";
|
||||
@@ -710,7 +711,7 @@ export function classifyContinuationFailure(
|
||||
errorCode,
|
||||
};
|
||||
}
|
||||
if (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode)) {
|
||||
if (isAiAuthenticationBlocked(latestRun) || (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode))) {
|
||||
return {
|
||||
kind: "non_retryable",
|
||||
maxAttempts: 0,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isAiAuthenticationFailure } from "./ai-auth-failure.js";
|
||||
import type { HeartbeatRunStatus, IssueStatus, RunLivenessState } from "@paperclipai/shared";
|
||||
|
||||
export type RunLivenessActionability =
|
||||
@@ -37,6 +38,8 @@ export interface RunLivenessClassificationInput {
|
||||
errorCode?: string | null;
|
||||
continuationAttempt?: number | null;
|
||||
evidence?: Partial<RunLivenessEvidenceInput> | null;
|
||||
/** Set by the controller only after creating a durable connection card. */
|
||||
authenticationRepairRequested?: boolean;
|
||||
}
|
||||
|
||||
export interface RunLivenessClassification {
|
||||
@@ -320,6 +323,10 @@ 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)) {
|
||||
return output("blocked", "Waiting for provider authentication repair", "Complete the connection request to continue this task");
|
||||
}
|
||||
|
||||
if (input.runStatus !== "succeeded") {
|
||||
if (hasUnmanagedBackgroundTaskEvidence(input.resultJson)) {
|
||||
return output("failed", UNMANAGED_BACKGROUND_TASK_LIVENESS_REASON);
|
||||
|
||||
Reference in new issue
Block a user