fix(connections): wire provider catalog setup and no-auth execution

Keep the credential form and compatible personal-account picker with their catalog definitions. Add no-auth runtime preparation and abort-aware Claude code input. Move independent Grok and Gemini live-workflow fixes to the qualification follow-up.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-06 09:51:13 -05:00
1 parent fa9b3d22a1
commit 3bb36afcd9
24 files changed
+945 -265

No files matched your search

+11 -22
View File
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import { HttpError, unprocessable } from "../errors.js";
import { mkdtemp, mkdir, symlink, writeFile, readFile, rm } from "node:fs/promises";
import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { and, eq } from "drizzle-orm";
@@ -17,7 +17,6 @@ import { decideCodexAuthMerge } from "@paperclipai/adapter-codex-local/server";
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
import { runAdapterExecutionTargetProcess } from "@paperclipai/adapter-utils/execution-target";
import { decideGrokAuthMerge } from "@paperclipai/adapter-grok-local/server";
import { resolvePaperclipInstanceRootForAdapter } from "@paperclipai/adapter-utils/server-utils";
export function isAiConnectionBusy(error: unknown): error is HttpError {
return error instanceof HttpError && error.status === 422 &&
@@ -269,13 +268,15 @@ export async function prepareManagedAiRuntime(
"The selected default changed. Retry this execution.",
);
const credentialRef = selection.grant.credentialSecretRefs.find((ref) => ref.configPath === "ai.credential");
if (!credentialRef) throw unprocessable("The selected AI credential is unavailable");
const readFreshness = async () => (await db.select({ epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion })
.from(companySecrets).where(and(eq(companySecrets.companyId, input.companyId), eq(companySecrets.id, credentialRef.secretId))).limit(1))[0];
const freshness = await readFreshness();
const value = await service.credential(selection);
const afterRead = await readFreshness();
if (!freshness || freshness.version !== afterRead?.version || freshness.epoch !== afterRead.epoch) throw unprocessable("The AI credential changed during preparation; retry this execution");
const routing = aiConnectionMetadataSchema.parse(selection.connection.config.ai).routing;
const noAuth = routing?.auth === "none";
if (!noAuth && !credentialRef) throw unprocessable("The selected AI credential is unavailable");
const readFreshness = async () => credentialRef ? (await db.select({ epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion })
.from(companySecrets).where(and(eq(companySecrets.companyId, input.companyId), eq(companySecrets.id, credentialRef.secretId))).limit(1))[0] : undefined;
const freshness = noAuth ? undefined : await readFreshness();
const value = noAuth ? "" : await service.credential(selection);
const afterRead = noAuth ? undefined : await readFreshness();
if (!noAuth && (!freshness || freshness.version !== afterRead?.version || freshness.epoch !== afterRead.epoch)) throw unprocessable("The AI credential changed during preparation; retry this execution");
home = await mkdtemp(
path.join(
os.tmpdir(),
@@ -289,7 +290,6 @@ export async function prepareManagedAiRuntime(
...Object.fromEntries(AI_AUTH_ENV_KEYS.map((key) => [key, ""])),
...managedAiHomeEnvironment(home),
};
const routing = aiConnectionMetadataSchema.parse(selection.connection.config.ai).routing;
const capability =
AI_CONNECTION_CAPABILITIES[input.binding.provider].methods[
selection.attribution.method
@@ -339,18 +339,7 @@ export async function prepareManagedAiRuntime(
.digest("hex")
.slice(0, 16);
const identity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${generation}`;
const sessionIdentity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${credentialRef.secretId}:${freshness.epoch}`;
if (input.adapterType === "grok_local") {
// Retain only transcripts across disposable credential homes. Scope them
// to the company, agent and credential identity, including rotations.
// Removing the runtime home removes the link, never its private target.
const scope = createHash("sha256")
.update(JSON.stringify([input.companyId, input.agentId, sessionIdentity]))
.digest("hex");
const sessions = path.join(resolvePaperclipInstanceRootForAdapter(), "companies", input.companyId, "grok-sessions", scope);
await mkdir(sessions, { recursive: true, mode: 0o700 });
await symlink(sessions, path.join(providerHome, "sessions"), "dir");
}
const sessionIdentity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${noAuth ? "no-auth" : `${credentialRef!.secretId}:${freshness!.epoch}`}`;
return {
sessionIdentity,
config: {
@@ -65,6 +65,23 @@ describe.skipIf(process.platform === "win32")("local browser subscription login"
await vi.waitFor(() => expect(() => process.kill(pid, 0)).toThrow());
});
it("cancels Claude while waiting for its browser code and terminates the provider", async () => {
const home = await fakeCli("claude", [
'echo $$ > "$CLAUDE_CONFIG_DIR/login.pid"',
'printf "Welcome to Claude Code\\nOpening browser to sign in…\\nBrowser didn\x27t open? Use the url below to sign in (c to copy)\\n"',
'printf "https://claude.com/cai/oauth/authorize?client_id=cid&code=abcdefgh&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&redirect_uri=https%%3A%%2F%%2Fplatform.claude.com%%2Foauth%%2Fcode%%2Fcallback&response_type=code&scope=user&state=0123456789abcdef\\n"',
'printf "Paste code here if prompted >\\n"',
'read -r entered',
].join("\n"));
const login = startLocalBrowserLogin("anthropic", home);
await vi.waitFor(() => expect(login.authorizationUrl).toBeDefined());
const pid = Number(await readFile(path.join(home, "login.pid"), "utf8"));
login.abort();
await vi.waitFor(() => expect(login.outcome).toBe("failure"));
await vi.waitFor(() => expect(() => process.kill(pid, 0)).toThrow());
await expect(readFile(path.join(home, ".credentials.json"))).rejects.toThrow();
});
it("returns a fixed failure without exposing provider error output", async () => {
const home = await fakeCli("codex", 'echo "private-provider-error" >&2\nexit 1');
const login = startLocalBrowserLogin("openai", home);
@@ -80,7 +80,12 @@ export function startLocalBrowserLogin(provider: "anthropic" | "openai", home: s
void runSetupTokenLogin(driver, {
timeoutMs: 300_000, signal: controller.signal,
onPrompt: (prompt) => { state.authorizationUrl = prompt.url; },
provideCode: () => codeReady,
provideCode: (signal) => new Promise<string>((resolve, reject) => {
const abort = () => reject(new Error("Local sign-in cancelled"));
if (signal.aborted) { abort(); return; }
signal.addEventListener("abort", abort, { once: true });
codeReady.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
}),
onCredential: async (bytes) => {
const file = await open(path.join(home, ".credentials.json"),
constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);