feat(plugins): honor harness login driver preferences (#23425)

## Thinking Path

> - People use Paperclip to manage agents and the accounts they use.
> - A harness can sign in on an environment supplied by a plugin.
> - Some plugins offer several environments with different login
requirements.
> - Today the task environment also determines where sign-in runs.
> - This change lets the plugin declare its preferred login drivers.
> - A company can use a temporary environment for sign-in and keep
running tasks on its chosen computer.

## Linked Issues or Issue Description

**Subsystem affected**

Plugin manifests, login target selection, and the harness sign-in UI.

**Current behavior**

A plugin with several environments cannot direct sign-in to a preferred
driver. Selecting an agent computer for tasks can require an agent even
when a temporary environment is available for login.

**Proposed behavior**

Allow the manifest to declare an ordered list of login drivers. Select
the first eligible environment for the company and harness before
starting a login.

**Reason and benefit**

A plugin can offer agentless sign-in first and keep an agent-targeted
computer as a fallback. The choice applies only to sign-in.

**Additional context**

This builds on the agentless login capability in #23392.

## What Changed

- Validate ordered login driver keys in the manifest and expose the
eligible environments to the company.
- Use the same selection rule for device login, setup-token login,
onboarding, agent configuration, and AI Connections.
- Bind the session and lease to the selected environment. Existing agent
eligibility checks apply when the target needs an agent.

## Verification

- Server and UI typechecks passed. Focused Vitest runs covered shared
manifest validation, driver order, the company access boundary, lease
checks, both HTTP login flows, and the UI helpers.
- The public SDK source input registry was regenerated. The registry
change requires broad CI coverage under `pnpm verify`.
- Regression tests cover skipping an environment without an eligible
computer, using a newly prepared draft computer, and holding the
selected host across capability and readiness updates during sign-in.
The UI typecheck and all 16 focused login tests passed on the final
commit.
- No external provider credentials were used.

## Risks

A plugin that opts in must declare at least one usable driver for the
user's harness and company. If none qualifies, the start fails before
acquisition. Manifests that omit the field keep their existing routing.
There is no database migration.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex (GPT-6), with local code inspection, TypeScript checks, and
test execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [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:
Nicky LeachandPaperclip authored and GitHub committed 2026-12-01 16:58:28 -08:00
1 parent f0ee1b40f0
commit 550d8fc576
21 files changed
+475 -146

No files matched your search

@@ -1,7 +1,7 @@
import type { Request, Response } from "express";
import type { z } from "zod";
type LoginTarget = { agentId: string | undefined; environment: { driver: string } };
type LoginTarget = { agentId: string | undefined; environment: { id: string; driver: string } };
/**
* The result of the shared adapter login start-route spine. The spine returns it
+9 -7
View File
@@ -1581,8 +1581,9 @@ export function agentRoutes(
companyId: string,
environmentId: string,
options: { requireSetupTokenLoginProvider?: boolean; agentId?: string; adapterType?: string; selectComputer?: boolean },
start?: { workerManager?: PluginWorkerManager },
) {
const target = await resolveLoginEnvironmentTarget(db, { companyId, environmentId, ...options });
const target = await resolveLoginEnvironmentTarget(db, { companyId, environmentId, ...options }, start);
// Gate the Claude setup-token login on the provider capability. Only a
// sandbox provider that advertises the setup-token login capability
// implements the setup-token pseudo-terminal methods. The setup-token start
@@ -1591,7 +1592,7 @@ export function agentRoutes(
// reconciliation that rebinds the environment to an unsupported provider
// still fails closed before the lease and the pseudo-terminal.
if (options.requireSetupTokenLoginProvider) {
await assertSetupTokenLoginProviderCapability(environmentId);
await assertSetupTokenLoginProviderCapability(target.environment.id);
}
return target;
}
@@ -3824,8 +3825,8 @@ export function agentRoutes(
// runtime state before the provider lease.
const target = await resolveSandboxLoginTarget(companyId, data.environmentId, {
agentId: data.agentId, adapterType: data.adapterType, selectComputer: Boolean(data.aiConnection),
});
await assertDeviceLoginProviderCapability(data.environmentId, data.adapterType);
}, { workerManager: options.pluginWorkerManager });
await assertDeviceLoginProviderCapability(target.environment.id, data.adapterType);
return target;
},
});
@@ -3842,7 +3843,7 @@ export function agentRoutes(
try {
result = await adapterLoginService.start({
companyId,
environmentId: data.environmentId,
environmentId: target.environment.id,
agentId: target.agentId,
environmentDriver: target.environment.driver,
adapterType: type,
@@ -7059,11 +7060,12 @@ export function agentRoutes(
agentId: data.agentId,
adapterType: data.adapterType,
selectComputer: Boolean(data.aiConnection),
}),
}, { workerManager: options.pluginWorkerManager }),
});
if (!resolved) return;
const { ownerUserId, data, target } = resolved;
const { environmentId, adapterType } = data;
const { adapterType } = data;
const environmentId = target.environment.id;
if (req.actor.type === "agent" && !data.aiConnection) throw forbidden("Agent logins must save a managed AI account");
if (data.aiConnection) {
await assertAiConnectionCreateAccess(db, req, companyId, data.aiConnection);
+12 -5
View File
@@ -60,6 +60,7 @@ import {
assertAgentsReadyForEnvironmentChange,
} from "../services/plugin-environment-driver.js";
import { getConfiguredSecretProvider } from "../secrets/configured-provider.js";
import { listPluginLoginTargets } from "../services/login-environment.js";
import { assertBoard, assertBoardOrgAccess, boardAccessRequired, getActorInfo } from "./authz.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { environmentService } from "../services/environments.js";
@@ -401,7 +402,7 @@ export function environmentRoutes(
assertBoardOrgAccess(req);
}
function assertCustomImageCompanyAccess(req: Request, companyId: string) {
function assertEnvironmentCompanyAccess(req: Request, companyId: string) {
assertBoard(req);
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
const allowedCompanies = req.actor.companyIds ?? [];
@@ -522,7 +523,7 @@ export function environmentRoutes(
? req.query.companyId.trim()
: null;
if (queryCompanyId) {
assertCustomImageCompanyAccess(req, queryCompanyId);
assertEnvironmentCompanyAccess(req, queryCompanyId);
return queryCompanyId;
}
if (req.actor.type === "board" && req.actor.companyIds?.length === 1) {
@@ -531,7 +532,7 @@ export function environmentRoutes(
const companyIds = await instanceSettings.listCompanyIds();
if (companyIds.length === 1 && companyIds[0]) {
const companyId = companyIds[0];
assertCustomImageCompanyAccess(req, companyId);
assertEnvironmentCompanyAccess(req, companyId);
return companyId;
}
throw unprocessable("companyId query parameter is required for environment customImage setup.");
@@ -543,7 +544,7 @@ export function environmentRoutes(
): Promise<string> {
const metadataCompanyId = readCustomImageSetupSessionCompanyId(session);
if (metadataCompanyId) {
assertCustomImageCompanyAccess(req, metadataCompanyId);
assertEnvironmentCompanyAccess(req, metadataCompanyId);
return metadataCompanyId;
}
return await resolveCustomImageCompanyId(req);
@@ -820,7 +821,13 @@ export function environmentRoutes(
])),
},
);
res.json({ ...capabilities, loginPtyDrivers: Object.fromEntries(loginDrivers.map(driver => [
let pluginLoginTargets;
if (loginDrivers.some(driver => driver.loginDriverPreference)) {
const companyId = req.params.companyId as string;
assertEnvironmentCompanyAccess(req, companyId);
pluginLoginTargets = await listPluginLoginTargets(db, companyId, loginDrivers);
}
res.json({ ...capabilities, ...(pluginLoginTargets && { pluginLoginTargets }), loginPtyDrivers: Object.fromEntries(loginDrivers.map(driver => [
`${driver.pluginKey}:${driver.driverKey}`, {
supportsLoginPty: driver.supportsLoginPty === true,
loginAdapters: driver.loginAdapters,
+44 -3
View File
@@ -3,15 +3,21 @@ import { eq } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, companies, createDb, environmentLeases, environments, type Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { assertLoginEnvironmentTarget, resolveLoginEnvironmentTarget } from "./login-environment.js";
const fixtures = vi.hoisted(() => ({ environment: { id: "environment", driver: "plugin" }, instanceDefault: "environment", companies: ["company"], agent: { id: "agent", companyId: "company", adapterType: "paperclip_runner", lifecycleState: "verifying", defaultEnvironmentId: "environment" } as Record<string, unknown> | undefined }));
vi.mock("./environments.js", () => ({ environmentService: () => ({ getById: async () => fixtures.environment, listBoundCompanyIds: async () => fixtures.companies }) }));
const { list, getById, listBoundCompanyIds } = vi.hoisted(() => ({ list: vi.fn(), getById: vi.fn(), listBoundCompanyIds: vi.fn() }));
vi.mock("./environments.js", () => ({ environmentService: () => ({ list, getById, listBoundCompanyIds }) }));
vi.mock("./instance-settings.js", () => ({ instanceSettingsService: () => ({ get: async () => ({ defaultEnvironmentId: fixtures.instanceDefault }) }) }));
vi.mock("./environment-selection.js", () => ({ assertEnvironmentSelectionForCompany: vi.fn(async () => {}) }));
const { getByKey } = vi.hoisted(() => ({ getByKey: vi.fn() }));
vi.mock("./plugin-registry.js", () => ({ pluginRegistryService: () => ({ getByKey }) }));
const db = { select: () => ({ from: () => ({ where: () => ({ limit: async () => fixtures.agent ? [fixtures.agent] : [] }) }) }) } as unknown as Db;
beforeEach(() => { fixtures.instanceDefault = "environment"; fixtures.environment = { id: "environment", driver: "plugin" }; fixtures.companies = ["company"]; fixtures.agent = { id: "agent", companyId: "company", adapterType: "paperclip_runner", lifecycleState: "verifying", defaultEnvironmentId: "environment" }; });
const db = { selectDistinctOn: () => ({ from: () => ({ where: () => ({ orderBy: async () => [] }) }) }), select: () => ({ from: () => ({ where: () => ({ limit: async () => fixtures.agent ? [fixtures.agent] : [], orderBy: async () => [] }) }) }) } as unknown as Db;
beforeEach(() => {
getById.mockImplementation(async () => fixtures.environment);
listBoundCompanyIds.mockImplementation(async () => fixtures.companies);
getByKey.mockReset();
fixtures.instanceDefault = "environment"; fixtures.environment = { id: "environment", driver: "plugin" }; fixtures.companies = ["company"]; fixtures.agent = { id: "agent", companyId: "company", adapterType: "paperclip_runner", lifecycleState: "verifying", defaultEnvironmentId: "environment" }; });
describe("login environment transport target", () => {
it("acquires an opted-in plugin login without selecting an agent", async () => {
Object.assign(fixtures.environment, { config: { pluginKey: "computers", driverKey: "temporary" } });
@@ -25,6 +31,41 @@ describe("login environment transport target", () => {
Object.assign(fixtures.environment, { config: { pluginKey: "computers", driverKey: "persistent" } });
await expect(assertLoginEnvironmentTarget(db, input)).rejects.toMatchObject({ status: 400 });
});
it("selects the first company-visible login driver and pins the lease check to that environment", async () => {
const keys = ["first", "second", "computer"];
const rows = keys.map(key => ({ id: key, status: "active", driver: "plugin", config: { pluginKey: "example", driverKey: key } }));
const methods = ["environmentAcquireLease", "environmentInspectLease", "environmentReleaseLease", "loginPtyOpen",
"loginPtyInput", "loginPtyStop", "loginPtyClose", "loginPtyReadCredential"];
const start = { workerManager: { isRunning: () => true, getWorker: () => ({ supportedMethods: methods }) } as unknown as PluginWorkerManager };
getByKey.mockResolvedValue({ id: "plugin", pluginKey: "example", status: "ready", manifestJson: {
loginDriverPreference: keys, environmentDrivers: keys.map(driverKey => ({
driverKey, kind: "environment_driver", creationOperationVersion: 1, supportsLoginPty: true, supportsAgentlessLogin: driverKey !== "computer",
})),
} });
list.mockResolvedValue([...rows].reverse());
getById.mockImplementation(async id => rows.find(row => row.id === id));
fixtures.agent!.defaultEnvironmentId = "computer";
const request = { companyId: "company", environmentId: "computer", agentId: "agent", adapterType: "codex_local" };
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toMatchObject({ environment: rows[0], agentId: undefined });
expect(list).toHaveBeenCalledWith({ driver: "plugin", status: "active" });
listBoundCompanyIds.mockImplementation(async id => id === "first" ? ["another-company"] : []);
const second = await resolveLoginEnvironmentTarget(db, request, start);
expect(second).toEqual({ environment: rows[1], agentId: undefined });
listBoundCompanyIds.mockResolvedValue([]);
await expect(assertLoginEnvironmentTarget(db, { ...request, environmentId: second.environment.id, agentId: undefined })).resolves.toEqual(rows[1]);
list.mockResolvedValue([rows[2]]);
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toMatchObject({ environment: rows[2], agentId: "agent" });
await expect(resolveLoginEnvironmentTarget(db, { ...request, agentId: undefined }, start)).rejects.toMatchObject({ status: 400 });
list.mockResolvedValue([...rows]);
keys.unshift(keys.pop()!);
await expect(resolveLoginEnvironmentTarget(db, { ...request, agentId: undefined, selectComputer: true }, start))
.resolves.toEqual({ environment: rows[0], agentId: undefined });
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toEqual({ environment: rows[2], agentId: "agent" });
fixtures.agent!.lifecycleState = "preparing";
await expect(resolveLoginEnvironmentTarget(db, request, start)).resolves.toEqual({ environment: rows[0], agentId: undefined });
methods.pop();
await expect(resolveLoginEnvironmentTarget(db, request, start)).rejects.toMatchObject({ status: 400 });
});
it("permits a verifying saved agent on its own computer", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).resolves.toEqual(fixtures.environment); });
it("leaves which adapters a computer signs in to its driver's declared support", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent", adapterType: "grok_local" })).resolves.toEqual(fixtures.environment); });
it("rejects an adapter that has no Paperclip sign-in", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent", adapterType: "copilot_runtime" })).rejects.toMatchObject({ status: 400 }); });
+116 -39
View File
@@ -1,11 +1,53 @@
import { agents, environmentLeases, type Db } from "@paperclipai/db";
import { adapterLoginCommandKey } from "@paperclipai/shared";
import { and, asc, eq, isNull, notExists, notInArray, or, sql } from "drizzle-orm";
import { adapterLoginCommandKey, type PluginLoginTarget } from "@paperclipai/shared";
import { and, asc, eq, notExists, notInArray, or, sql } from "drizzle-orm";
import { badRequest, forbidden, notFound } from "../errors.js";
import { assertEnvironmentSelectionForCompany } from "./environment-selection.js";
import { environmentService } from "./environments.js";
import { pluginRegistryService } from "./plugin-registry.js";
import { instanceSettingsService } from "./instance-settings.js";
import { pluginDriverLoginAdapters, type ReadyPluginEnvironmentDriver } from "./plugin-environment-driver.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
type LoginDriver = Pick<ReadyPluginEnvironmentDriver, "pluginKey" | "driverKey" | "loginAdapters" | "loginDriverPreference" | "supportsAgentlessLogin">;
/** The same company-scoped catalog is used to present and to start a login. */
export async function listPluginLoginTargets(db: Db, companyId: string, drivers: LoginDriver[], includeComputerAvailability = true) {
const preferences = new Map(drivers.flatMap(driver =>
driver.loginDriverPreference ? [[driver.pluginKey, driver.loginDriverPreference] as const] : []));
if (!preferences.size) return {};
const environments = environmentService(db);
const rows = await environments.list({ status: "active", driver: "plugin" });
rows.sort((a, b) => a.id.localeCompare(b.id));
const visible = await Promise.all(rows.filter(row => {
const { pluginKey, driverKey } = row.config;
return typeof pluginKey === "string" && typeof driverKey === "string" && preferences.get(pluginKey)?.includes(driverKey);
}).map(async row => {
const companies = await environments.listBoundCompanyIds(row.id);
return !companies.length || companies.includes(companyId) ? row : null;
}));
const targets: Record<string, PluginLoginTarget[]> = Object.create(null);
let computers: Awaited<ReturnType<typeof availableLoginComputers>> | undefined;
for (const [pluginKey, preference] of preferences) {
const ordered: PluginLoginTarget[] = [];
for (const driverKey of preference) {
const driver = drivers.find(item => item.pluginKey === pluginKey && item.driverKey === driverKey);
if (!driver?.loginAdapters.length) continue;
for (const row of visible) {
if (row && row.config.pluginKey === pluginKey && row.config.driverKey === driverKey) {
const target: PluginLoginTarget = { environmentId: row.id, driverKey, loginAdapters: driver.loginAdapters };
if (!driver.supportsAgentlessLogin && includeComputerAvailability) {
computers ??= await availableLoginComputers(db, companyId);
target.automaticComputerAvailable = computers.has(row.id);
}
ordered.push(target);
}
}
}
targets[pluginKey] = ordered;
}
return targets;
}
type LoginEnvironmentTarget = { companyId: string; environmentId: string; agentId?: string; adapterType?: string };
@@ -17,6 +59,7 @@ export async function assertLoginEnvironmentTarget(db: Db, input: LoginEnvironme
export async function resolveLoginEnvironmentTarget(
db: Db,
input: LoginEnvironmentTarget & { selectComputer?: boolean },
start?: { workerManager?: PluginWorkerManager },
) {
const environments = environmentService(db);
await assertEnvironmentSelectionForCompany(environments, input.companyId, input.environmentId, {
@@ -31,45 +74,79 @@ export async function resolveLoginEnvironmentTarget(
return { environment, agentId: undefined };
}
if (input.adapterType && !adapterLoginCommandKey(input.adapterType)) throw badRequest("This provider login is not supported on agent computers.", { code: "login_adapter_unsupported" });
if (!input.agentId) {
const config = environment.config;
if (typeof config?.pluginKey === "string" && typeof config.driverKey === "string") {
const plugin = await pluginRegistryService(db).getByKey(config.pluginKey);
const driver = plugin?.manifestJson.environmentDrivers?.find(item => item.driverKey === config.driverKey);
if (plugin?.status === "ready" && driver?.kind !== "sandbox_provider" && driver?.supportsLoginPty && driver.supportsAgentlessLogin) {
return { environment, agentId: undefined };
const config = environment.config;
const plugin = typeof config?.pluginKey === "string" && (start || !input.agentId)
? await pluginRegistryService(db).getByKey(config.pluginKey) : null;
const preference = plugin?.manifestJson.loginDriverPreference;
if (start && plugin && preference) {
const methods = plugin.status === "ready" && start.workerManager?.isRunning(plugin.id)
? start.workerManager.getWorker(plugin.id)?.supportedMethods ?? [] : [];
const drivers = (plugin.manifestJson.environmentDrivers ?? []).map(driver => ({
pluginKey: plugin.pluginKey, driverKey: driver.driverKey, loginDriverPreference: preference,
loginAdapters: pluginDriverLoginAdapters(driver, methods), supportsAgentlessLogin: driver.supportsAgentlessLogin,
}));
const targets = (await listPluginLoginTargets(db, input.companyId, drivers, false))[plugin.pluginKey] ?? [];
const eligible = targets.filter(target => target.loginAdapters.includes(input.adapterType ?? ""));
// Within a driver, try the requested environment before its siblings.
const ownIndex = eligible.findIndex(target => target.environmentId === environment.id);
if (ownIndex >= 0) {
const own = eligible[ownIndex]!;
eligible.splice(ownIndex, 1);
const firstSibling = eligible.findIndex(target => target.driverKey === own.driverKey);
eligible.splice(firstSibling < 0 ? ownIndex : firstSibling, 0, own);
}
let computers = input.agentId ? await availableLoginComputers(db, input.companyId, input.agentId) : undefined;
for (const candidate of eligible) {
const agentless = drivers.find(driver => driver.driverKey === candidate.driverKey)?.supportsAgentlessLogin;
let agentId: string | undefined;
if (!agentless) {
if (!input.agentId && !input.selectComputer) continue;
computers ??= await availableLoginComputers(db, input.companyId);
agentId = computers.get(candidate.environmentId);
if (!agentId) continue;
}
const selected = await environments.getById(candidate.environmentId);
if (selected?.status === "active" && selected.config.pluginKey === plugin.pluginKey && selected.config.driverKey === candidate.driverKey) {
return { environment: selected, agentId };
}
}
if (!input.selectComputer) throw badRequest("Select an agent computer for sign-in.", { code: "login_agent_required" });
const settings = await instanceSettingsService(db).get();
const matchesEnvironment = eq(agents.defaultEnvironmentId, environment.id);
const activeLogin = db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, input.companyId),
eq(environmentLeases.environmentId, environment.id),
eq(environmentLeases.status, "active"),
sql`${environmentLeases.metadata}->>'purpose' = 'login'`,
sql`${environmentLeases.metadata}->>'agentId' = ${agents.id}::text`,
));
const [agent] = await db.select({ id: agents.id }).from(agents).where(and(
eq(agents.companyId, input.companyId),
eq(agents.adapterType, "paperclip_runner"),
notExists(activeLogin),
settings.defaultEnvironmentId === environment.id
? or(matchesEnvironment, isNull(agents.defaultEnvironmentId))
: matchesEnvironment,
or(
and(eq(agents.lifecycleState, "ready"), notInArray(agents.status, ["paused", "terminated", "pending_approval"])),
and(eq(agents.lifecycleState, "verifying"), notInArray(agents.status, ["terminated", "pending_approval"])),
),
)).orderBy(asc(agents.lifecycleState), asc(agents.id)).limit(1);
if (!agent) throw badRequest("No agent computer is available for sign-in.", { code: "login_agent_unavailable" });
return { environment, agentId: agent.id };
throw badRequest("No eligible login environment is available.", { code: "login_environment_unavailable" });
}
const [agent] = await db.select().from(agents).where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId))).limit(1);
if (!agent || agent.companyId !== input.companyId) throw notFound("Agent not found");
const inherited = agent.defaultEnvironmentId ?? (await instanceSettingsService(db).get()).defaultEnvironmentId;
if (inherited !== environment.id || agent.adapterType !== "paperclip_runner" || !["ready", "verifying"].includes(agent.lifecycleState)) {
throw badRequest("The selected agent computer is not available for sign-in.", { code: "login_agent_unavailable" });
const driver = plugin?.manifestJson.environmentDrivers?.find(item => item.driverKey === environment.config.driverKey);
if (!input.agentId && plugin?.status === "ready" && driver?.kind !== "sandbox_provider" && driver?.supportsLoginPty && driver.supportsAgentlessLogin) {
return { environment, agentId: undefined };
}
return { environment, agentId: agent.id };
if (!input.agentId && !input.selectComputer) throw badRequest("Select an agent computer for sign-in.", { code: "login_agent_required" });
const computers = await availableLoginComputers(db, input.companyId, input.agentId);
const agentId = computers.get(environment.id);
if (!agentId) throw badRequest("No agent computer is available for sign-in.", { code: "login_agent_unavailable" });
return { environment, agentId };
}
/** First usable computer per environment, or the caller's exact computer when supplied. */
async function availableLoginComputers(db: Db, companyId: string, agentId?: string): Promise<Map<string, string>> {
if (agentId) {
const [agent] = await db.select().from(agents).where(and(eq(agents.id, agentId), eq(agents.companyId, companyId))).limit(1);
if (!agent || agent.companyId !== companyId) throw notFound("Agent not found");
if (agent.adapterType !== "paperclip_runner" || !["ready", "verifying"].includes(agent.lifecycleState)) return new Map();
const environmentId = agent.defaultEnvironmentId ?? (await instanceSettingsService(db).get()).defaultEnvironmentId;
return environmentId ? new Map([[environmentId, agent.id]]) : new Map();
}
const settings = await instanceSettingsService(db).get();
const effective = sql<string>`coalesce(${agents.defaultEnvironmentId}, ${settings.defaultEnvironmentId}::uuid)`;
const activeLogin = db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, companyId), eq(environmentLeases.environmentId, effective),
eq(environmentLeases.status, "active"), sql`${environmentLeases.metadata}->>'purpose' = 'login'`,
sql`${environmentLeases.metadata}->>'agentId' = ${agents.id}::text`,
));
// Sort once so the first agent for each environment is deterministic, including agents that inherit the instance default.
const key = sql`"login_environment_id"`;
const rows = await db.selectDistinctOn([key], { environmentId: effective.as("login_environment_id"), id: agents.id }).from(agents).where(and(
eq(agents.companyId, companyId), eq(agents.adapterType, "paperclip_runner"), notExists(activeLogin),
or(
and(eq(agents.lifecycleState, "ready"), notInArray(agents.status, ["paused", "terminated", "pending_approval"])),
and(eq(agents.lifecycleState, "verifying"), notInArray(agents.status, ["terminated", "pending_approval"])),
),
)).orderBy(key, asc(agents.lifecycleState), asc(agents.id));
return new Map(rows.filter(row => row.environmentId).map(row => [row.environmentId, row.id]));
}
@@ -212,6 +212,7 @@ export interface ReadyPluginEnvironmentDriver {
supportedAdapters?: string[];
loginAdapters: string[];
supportsAgentlessLogin?: boolean;
loginDriverPreference?: string[];
supportsInteractiveSetup?: PluginEnvironmentDriverDeclaration["supportsInteractiveSetup"];
interactiveSetupConnectionTypes?: PluginEnvironmentDriverDeclaration["interactiveSetupConnectionTypes"];
supportsTemplateCapture?: PluginEnvironmentDriverDeclaration["supportsTemplateCapture"];
@@ -473,6 +474,7 @@ export async function listReadyPluginEnvironmentDrivers(input: {
supportsTemplateDelete: driver.supportsTemplateDelete,
supportsLoginPty: driver.kind === "environment_driver" ? pluginSupportsLoginPty(driver, [...workerMethods]) : sandboxProviderSupportsLoginPty(driver),
...(driver.supportsAgentlessLogin ? { supportsAgentlessLogin: true } : {}),
...(plugin.manifestJson.loginDriverPreference ? { loginDriverPreference: plugin.manifestJson.loginDriverPreference } : {}),
...supportedAdapterFields(plugin.pluginKey, driver, [...workerMethods]),
})),
);