feat(plugin-sdk): declare supported adapters per environment driver (#22827)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Environment plugins can run agent tasks on remote computers, and can
run the provider sign-in for those computers
> - Core decides which adapters can sign in on a plugin environment from
a fixed Claude and Codex rule and a `supportsCodexLogin` flag
> - A plugin cannot say which adapters it supports, so Grok has no
sign-in on a plugin computer, and a plugin can run an adapter that it
cannot sign in
> - This pull request lets a Runner task driver declare its supported
adapters, and makes support mean the full adapter lifecycle: runs and,
where Paperclip offers one, sign-in
> - The benefit is one extensible support contract per driver, with no
partial matrix, and Grok subscription sign-in on plugin computers

## Linked Issues or Issue Description

**Subsystem affected**

Plugin SDK environment drivers, plugin sign-in (login pseudo-terminal),
plugin Runner task credentials, and agent Runner selection.

**Problem or motivation**

Core allows plugin-computer sign-in only for Claude, and for Codex when
the plugin can read back a credential file. The flag for that is named
`supportsCodexLogin`, which does not describe what it does. A plugin
cannot advertise which adapters it supports. Grok has a device sign-in
in Core, but it has no sign-in on a plugin computer, and a Grok
subscription cannot reach a plugin task. A plugin can also run an
adapter that has no sign-in on that plugin. This gives a partial support
matrix.

**Proposed solution**

A Runner task driver declares `supportedAdapters`. Support for an
adapter means the full lifecycle. The driver must run the adapter, and
it must run the Paperclip sign-in when the adapter has one. Core
validates the declaration in the manifest, and Core checks it again
against the methods of the running worker. An adapter that fails either
check is not offered for sign-in, for save, or for runs. The sign-in
contract moves to one shared map, so a new adapter sign-in is one entry
in that map.

**Alternatives considered**

A separate per-capability table (runs, sign-in, credential read-back)
was rejected. It permits the partial matrix that this change removes.
The existing sign-in map and credential sets already contain the
necessary data.

**Additional context**

Related open pull requests: Refs #14001 (Kubernetes plugin login
pseudo-terminal), Refs #21327 (Grok device link in the sign-in UI).

## What Changed

- Environment drivers can declare `supportedAdapters`. The manifest is
rejected when the list has duplicates, when the driver is not a Runner
task driver, or when it lists an adapter that has a Paperclip sign-in
and the driver does not declare the login pseudo-terminal with
`creationOperationVersion: 1`.
- Core removes a listed adapter when the running worker does not
implement the methods it needs (task methods, and sign-in methods with
credential read-back for file sign-ins). Core logs a warning one time
for each removed adapter.
- `supportsCodexLogin` is replaced by `loginAdapters`, the adapters that
can sign in on that environment. Drivers without `supportedAdapters`
keep the current behaviour: Claude, and Codex when the worker reads back
credentials.
- A new shared sign-in map holds the adapters that Paperclip signs in
and where each sign-in leaves its credential (terminal output or a
file). Manifest validation, server admission, environment presentation,
and the Connections sign-in step use this map. Two hard-coded Claude and
Codex lists are removed.
- Credential read-back accepts any file sign-in key and returns `{ kind:
"auth-file", content }`.
- The plugin task credential `codex-auth-json` becomes `{ type:
"auth-file", provider: "codex" | "grok", content }`.
- A Grok subscription is delivered to plugin tasks as an `auth-file`
credential. A refreshed Grok file returns to the account through the
existing write-back. The write-back record now stores its provider.
- On a driver that lists adapters, Core refuses to save, offer, or
submit a Runner harness that is not on the list. The error is
`agent_runner_unavailable`.
- The SDK README and the plugin environment task and AI connection docs
describe the contract.

## Verification

- `pnpm --filter @paperclipai/server typecheck`, `pnpm --filter
@paperclipai/plugin-sdk typecheck`, and `pnpm --filter @paperclipai/ui
typecheck` pass.
- Targeted server tests pass: plugin environment driver capabilities,
plugin login credential, plugin Runner credentials, plugin task
credential write-back (Codex and Grok, with a provider mismatch case),
environment task runtime submit gating, agent Runner selection, login
environment, login session runtime, device login routes and service,
setup token, login command, and adapter routes.
- Plugin Runner probe and integration tests pass (run from the
repository root).
- Shared tests (77) and plugin SDK tests (129) pass, including the new
manifest validation cases.
- UI AI connection tests (67) pass.
- Not run locally: the full suite (CI runs it), a render test for the
Connections credential step, and an end-to-end route test for computer
device sign-in admission. Unit tests cover that admission.

## Risks

- Breaking change for plugins that use the plugin SDK task credential or
credential read-back. `codex-auth-json` becomes `auth-file`, and the
read-back result kind changes. A plugin must update to the new SDK
shapes in the same release.
- Plugins that do not declare `supportedAdapters` keep the current
behaviour. No warning is logged for them.
- `supportedAdapters` applies to Runner task drivers only. Sandbox
providers reject the field. Support for sandbox providers is a separate
change.
- The new-agent screen does not offer sign-in on a plugin computer. That
sign-in needs a target computer, and the Connections flow selects it.
This is the current behaviour for Claude and Codex.
- No migration. The write-back record treats a missing provider as
Codex, so records written before this change still work.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test runs) and extended thinking.

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
authored and GitHub committed 2026-12-01 08:13:39 -08:00
1 parent 36c2ad39c8
commit ab099dc379
51 files changed
+655 -169

No files matched your search

@@ -196,6 +196,16 @@ describe("adapter routes", () => {
expect(pluginRunner).toMatchObject({ type: "paperclip_runner", loaded: true, disabled: false });
expect(pluginRunner.supportedRunners.length).toBeGreaterThan(0);
expect(pluginRunner.candidateHarnesses).toBeUndefined();
expect(pluginRunner.supportedAdapters).toBeUndefined();
});
it("offers paperclip_runner with the driver's list when it lists only a wrapper choice", async () => {
const response = await request(createApp({}, { resolveRunnerTarget: async () => ({ driver: "plugin", runnerTasks: true, supportedAdapters: ["copilot_runtime"] }) }))
.get("/api/adapters?companyId=company-1&environmentId=plugin-tasks");
expect(response.status).toBe(200);
const pluginRunner = response.body.find((adapter: any) => adapter.type === "paperclip_runner");
expect(pluginRunner.supportedRunners.length).toBeGreaterThan(0);
expect(pluginRunner.supportedAdapters).toEqual(["copilot_runtime"]);
expect(response.body.find((adapter: any) => adapter.type === "claude_local").supportedRunners).toEqual([]);
});
it("keeps ordinary adapter discovery available after candidate startup authority expires", async () => {
mockCandidateForRunnerTarget.mockImplementation(() => { throw new Error("ACPX candidate startup authorization expired"); });
@@ -869,6 +869,32 @@ describe("agent routes adapter validation: runner rollout and upgrades", () => {
expect(mockAgentService.rollbackConfigRevision).not.toHaveBeenCalled();
});
it("refuses a rollback to a Runner harness its environment no longer supports", async () => {
const selection = await import("../services/agent-runner-selection.js");
const { unprocessable } = await import("../errors.js");
const check = vi.spyOn(selection, "assertRunnerTaskEnvironmentSupportsHarness").mockRejectedValue(
unprocessable("This environment does not support the selected harness.", { code: "agent_runner_unavailable", harness: "grok_local" }));
try {
const existing = await mockAgentService.getById();
mockAgentService.getById.mockResolvedValue({ ...existing, adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" } });
const restored = { provider: "acpx", acpxAgent: "grok", model: "grok-4.7" };
mockAgentService.getConfigRevision.mockResolvedValue({
afterConfig: { adapterType: "paperclip_runner", adapterConfig: restored, runtimeConfig: {}, defaultEnvironmentId: "computer" },
});
const app = await createApp();
const response = await requestApp(app, (baseUrl) =>
request(baseUrl).post(
"/api/agents/11111111-1111-4111-8111-111111111111/config-revisions/33333333-3333-4333-8333-333333333333/rollback",
),
);
expect(response.status, JSON.stringify(response.body)).toBe(422);
expect(response.body.details).toMatchObject({ code: "agent_runner_unavailable", harness: "grok_local" });
expect(check).toHaveBeenCalledWith(expect.anything(), existing.companyId, expect.objectContaining({
adapterType: "paperclip_runner", adapterConfig: restored, defaultEnvironmentId: "computer" }));
expect(mockAgentService.rollbackConfigRevision).not.toHaveBeenCalled();
} finally { check.mockRestore(); }
});
it.each(["rejected", "warned"] as const)("checks a rollback's restored env and environment for protected keys (%s)", async outcome => {
const existing = await mockAgentService.getById();
const adapterConfig = { ...(existing.adapterConfig as Record<string, unknown>), env: { DESKTOP_SESSION: { type: "plain", value: "mine" } } };
@@ -201,7 +201,7 @@ suite("Google sign-in task credential writeback for plugin Runners", () => {
});
it.each([
["a Codex credential", { type: "codex-auth-json", authJson: "{\"tokens\":{}}" }],
["a Codex credential", { type: "auth-file", provider: "codex", content: "{\"tokens\":{}}" }],
["a Gemini API key", { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } }],
["an invalid sign-in", { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: "{\"refresh_token\":\"fixture-refreshed\"}" } }],
])("refuses %s as a Google sign-in snapshot without saving or echoing it", async (_name, snapshot) => {
@@ -334,7 +334,7 @@ describe("plugin-provided Runner execution", () => {
});
it("requires project validation for the exact configuration, provider, and projects before credential dispatch", async () => {
const operation = { ...submit, preparedLaunchId: "configuration", accountIdentity: "account",
credential: { type: "codex-auth-json" as const, authJson: '{"OPENAI_API_KEY":"never-leak"}' } };
credential: { type: "auth-file" as const, provider: "codex" as const, content: '{"OPENAI_API_KEY":"never-leak"}' } };
const proof = { configurationId: "configuration", provider: "openai", projectIds: [projectId] };
for (const invalid of [undefined, { ...proof, configurationId: "other" }, { ...proof, provider: "anthropic" }, { ...proof, projectIds: [] }]) {
const value = row(); Object.assign(value.lease.metadata, { runnerTaskProjectAuthValidation: invalid });
@@ -375,6 +375,28 @@ describe("plugin-provided Runner execution", () => {
operation: { ...operation, credential: credentials[harness === "grok" ? "copilot" : "grok"] } })).rejects.toThrow("validation unavailable");
expect(denied.call).not.toHaveBeenCalled();
});
it("submits only adapters that the listing driver's worker supports end to end", async () => {
const login = ["environmentAcquireLease", "environmentInspectLease", "environmentReleaseLease", "loginPtyOpen", "loginPtyInput", "loginPtyStop", "loginPtyClose"];
Object.assign(state.plugin.manifestJson.environmentDrivers[0], { supportsLoginPty: true, creationOperationVersion: 1, supportedAdapters: ["codex_local", "copilot_runtime"] });
const validated = (provider: string) => {
const value = row();
Object.assign(value.lease.metadata, { runnerTaskProjectAuthValidation: { configurationId: "configuration", provider, projectIds: [projectId] } });
return value;
};
const run = (harness: string, methods: string[]) => {
const workers = worker(); workers.getWorker.mockReturnValue({ supportedMethods: ["environmentTask", ...methods] });
const provider = harness === "codex" ? "openai" : harness;
return { workers, result: executeEnvironmentTask(database(validated(provider)).db, workers as never, { companyId: "company", leaseId,
operation: { ...submit, runner: { ...submit.runner, harness } } }) };
};
await expect(run("codex", [...login, "loginPtyReadCredential"]).result).resolves.toMatchObject({ kind: "accepted" });
await expect(run("copilot", ["environmentAcquireLease", "environmentReleaseLease"]).result).resolves.toMatchObject({ kind: "accepted" });
for (const [harness, methods] of [["grok", [...login, "loginPtyReadCredential"]], ["codex", login], ["copilot", []]] as const) {
const { workers, result } = run(harness, [...methods]);
await expect(result).rejects.toThrow("harness is unavailable");
expect(workers.call).not.toHaveBeenCalled();
}
});
it.each(["allowed", "denied", "wrong-configuration", "wrong-provider", "timeout"])("records only a matching successful project validation (%s)", async mode => {
const operation = { kind: "check_project_auth" as const, configurationId: "configuration", provider: "openai" as const, projectIds: [projectId] };
const result = { kind: "project_auth", taskId: "attempt-1", configurationId: mode === "wrong-configuration" ? "other" : "configuration",
@@ -683,6 +705,26 @@ describe("plugin-provided Runner execution", () => {
expect(JSON.stringify({ ...error, message: error.message })).not.toContain("never-leak-variable");
expect(error.cause).toBeUndefined();
});
it("resumes a warm task only while its saved harness is still supported", async () => {
const login = ["environmentAcquireLease", "environmentInspectLease", "environmentReleaseLease", "loginPtyOpen", "loginPtyInput", "loginPtyStop", "loginPtyClose", "loginPtyReadCredential"];
Object.assign(state.plugin.manifestJson.environmentDrivers[0], { supportsLoginPty: true, creationOperationVersion: 1, supportedAdapters: ["codex_local"] });
const identity = { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run", normalizedSessionId: "session", turnId: "turn", itemId: "item" };
const operation = { kind: "resume" as const, identity, bootstrapTicket: "transient-test-ticket" };
const result = { kind: "resume", taskId: "attempt-1", outcome: "resumed" };
const resume = (saved: Record<string, unknown>, methods = ["environmentTask", ...login]) => {
const value = row(); value.lease.status = "retained"; value.run!.status = "succeeded";
Object.assign(value.lease.metadata, saved);
const workers = worker(result); workers.getWorker.mockReturnValue({ supportedMethods: methods });
return { workers, result: executeEnvironmentTask(database(value).db, workers as never, { companyId: "company", leaseId, operation }) };
};
await expect(resume({ runnerTaskHarness: "codex" }).result).resolves.toEqual(result);
await expect(resume({}).result).resolves.toEqual(result);
for (const [saved, methods] of [[{ runnerTaskHarness: "grok" }, undefined], [{ runnerTaskHarness: "codex" }, ["environmentTask"]]] as const) {
const { workers, result: resumed } = resume(saved, methods ? [...methods] : undefined);
await expect(resumed).rejects.toThrow("harness is unavailable");
expect(workers.call).not.toHaveBeenCalled();
}
});
it("rejects wrong task receipts and sanitizes worker errors", async () => {
await expect(executeEnvironmentTask(database().db, worker({ kind: "accepted", taskId: "other" }) as never, { companyId: "company", leaseId, operation: submit })).rejects.toThrow("reconcile the same task");
const workers = worker(); workers.call.mockRejectedValue(new Error("private-credential"));
@@ -147,7 +147,7 @@ describe("createProductionLoginSessionRuntime lease-acquisition gate", () => {
runtime.acquireLoginLease({ ...acquireInput, sessionId: randomUUID() }),
).rejects.toThrow(DEVICE_LOGIN_PROVIDER_UNSUPPORTED);
// The runtime re-checked the current capability from the environment id.
expect(assertProviderSupportsLoginPty).toHaveBeenCalledWith("env-1");
expect(assertProviderSupportsLoginPty).toHaveBeenCalledWith("env-1", "codex_local");
// The gate failed before the provider lease, so no lease was acquired.
expect(acquireRunLease).not.toHaveBeenCalled();
});
@@ -183,7 +183,7 @@ describe("createProductionLoginSessionRuntime lease-acquisition gate", () => {
const acquired = await runtime.acquireLoginLease({ ...acquireInput, sessionId: randomUUID() });
expect(assertProviderSupportsLoginPty).toHaveBeenCalledWith("env-1");
expect(assertProviderSupportsLoginPty).toHaveBeenCalledWith("env-1", "codex_local");
// The gate passed, so the runtime acquired the provider lease after it.
expect(acquireRunLease).toHaveBeenCalledTimes(1);
expect(acquired.providerLeaseId).toBe("provider-lease-1");
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
import { listReadyPluginEnvironmentDrivers, pluginSupportsLoginPty } from "../services/plugin-environment-driver.js";
import { listReadyPluginEnvironmentDrivers, pluginDriverLoginAdapters, pluginDriverSupportedAdapters, pluginSupportsLoginPty } from "../services/plugin-environment-driver.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
const mockRegistry = vi.hoisted(() => ({
@@ -101,7 +101,7 @@ describe("live login capability admission and presentation", () => {
expect(pluginSupportsLoginPty({ supportsLoginPty: true }, hooks)).toBe(false);
expect(pluginSupportsLoginPty({ supportsLoginPty: true }, [...hooks, "loginPtyReadCredential"], true)).toBe(false);
});
it("requires the narrow credential hook only for Codex", () => {
it("requires the credential read hook only for sign-ins that save a file", () => {
expect(pluginSupportsLoginPty(driver, hooks)).toBe(true);
expect(pluginSupportsLoginPty(driver, hooks, true)).toBe(false);
expect(pluginSupportsLoginPty(driver, [...hooks, "loginPtyReadCredential"], true)).toBe(true);
@@ -119,7 +119,49 @@ describe("live login capability admission and presentation", () => {
const workerManager = { isRunning: () => true, getWorker: () => ({ supportedMethods: methods }) } as unknown as PluginWorkerManager;
const [projected] = await listReadyPluginEnvironmentDrivers({ db: {} as never, workerManager, kind: "environment_driver" });
expect(projected.supportsLoginPty).toBe(mode === "complete");
expect(projected.supportsCodexLogin).toBe(mode === "complete");
expect(projected.loginAdapters).toEqual(mode === "complete" ? ["claude_local", "codex_local"] : []);
expect(projected.supportedAdapters).toBeUndefined();
},
);
});
describe("declared adapter support", () => {
const login = ["environmentAcquireLease", "environmentInspectLease", "environmentReleaseLease", "loginPtyOpen", "loginPtyInput", "loginPtyStop", "loginPtyClose"];
const declaration = { supportsTasks: true, supportsLoginPty: true, creationOperationVersion: 1 as const,
supportedAdapters: ["claude_local", "codex_local", "grok_local", "copilot_runtime"] };
it("keeps every listed adapter when the worker implements its whole lifecycle", () => {
const methods = ["environmentTask", ...login, "loginPtyReadCredential"];
expect(pluginDriverSupportedAdapters(declaration, methods)).toEqual(declaration.supportedAdapters);
expect(pluginDriverLoginAdapters(declaration, methods)).toEqual(["claude_local", "codex_local", "grok_local"]);
});
it("removes an adapter whose sign-in the worker cannot finish, never only its sign-in", () => {
const methods = ["environmentTask", ...login];
expect(pluginDriverSupportedAdapters(declaration, methods)).toEqual(["claude_local", "copilot_runtime"]);
expect(pluginDriverLoginAdapters(declaration, methods)).toEqual(["claude_local"]);
expect(pluginDriverSupportedAdapters(declaration, [...login, "loginPtyReadCredential"])).toEqual([]);
});
it("removes every adapter when the worker cannot acquire or release a task lease", () => {
const methods = ["environmentTask", ...login, "loginPtyReadCredential"];
for (const missing of ["environmentAcquireLease", "environmentReleaseLease"]) {
expect(pluginDriverSupportedAdapters({ ...declaration, supportedAdapters: ["copilot_runtime"] },
methods.filter((method) => method !== missing))).toEqual([]);
}
});
it("keeps the earlier sign-ins for a driver without the list", () => {
const legacy = { supportsLoginPty: true, creationOperationVersion: 1 as const };
expect(pluginDriverSupportedAdapters(legacy, login)).toBeUndefined();
expect(pluginDriverLoginAdapters(legacy, login)).toEqual(["claude_local"]);
expect(pluginDriverLoginAdapters(legacy, [...login, "loginPtyReadCredential"])).toEqual(["claude_local", "codex_local"]);
});
it("publishes the verified list for a listed driver", async () => {
mockRegistry.list.mockResolvedValue([{
id: PLUGIN_ID, pluginKey: PLUGIN_KEY, status: "ready", manifestJson: {
...manifest, environmentDrivers: [{ ...manifest.environmentDrivers![0], ...declaration, kind: "environment_driver" }],
},
}]);
const workerManager = { isRunning: () => true, getWorker: () => ({ supportedMethods: ["environmentTask", ...login] }) } as unknown as PluginWorkerManager;
const [projected] = await listReadyPluginEnvironmentDrivers({ db: {} as never, workerManager, kind: "environment_driver" });
expect(projected.supportedAdapters).toEqual(["claude_local", "copilot_runtime"]);
expect(projected.loginAdapters).toEqual(["claude_local"]);
});
});
@@ -262,7 +262,7 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
const onDispatched = vi.fn(), checkpoint = vi.fn(async () => {}), close = vi.fn(async () => {});
ingress.connect.mockReturnValue({ ready: Promise.resolve(), close });
const owner = createPluginRunnerTaskOwner({ taskId: description.taskId, task: target.runnerTask, projectAuthCheckVersion: 1,
credentialIdentity: "revision", accountIdentity: "account", credential: { type: "codex-auth-json", authJson: '{"OPENAI_API_KEY":"synthetic-account-key"}' }, projectIds: target.runnerTaskProjectIds ?? [], harness: "codex",
credentialIdentity: "revision", accountIdentity: "account", credential: { type: "auth-file", provider: "codex", content: '{"OPENAI_API_KEY":"synthetic-account-key"}' }, projectIds: target.runnerTaskProjectIds ?? [], harness: "codex",
onSessionRetained: checkpoint, onDispatched, pollMs: 1 });
const identity = { runnerInstanceId: randomUUID(), environmentLeaseId: acquired.lease.id, runId,
normalizedSessionId: randomUUID(), turnId: "turn", itemId: "item" };
@@ -277,7 +277,7 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
}) });
await expect(runtime.task({ companyId, leaseId: acquired.lease.id, operation: {
kind: "submit", projectIds: [projectId], preparedLaunchId: prepared.configurationId, bootstrapTicket: "synthetic-ticket",
accountIdentity: "account", credential: { type: "codex-auth-json", authJson: '{"OPENAI_API_KEY":"never-transfer-stale-proof"}' },
accountIdentity: "account", credential: { type: "auth-file", provider: "codex", content: '{"OPENAI_API_KEY":"never-transfer-stale-proof"}' },
runner: { protocolMin: 1, protocolMax: 3, harness: "codex", runnerId: identity.runnerInstanceId,
leaseId: identity.environmentLeaseId, runId: identity.runId, sessionId: identity.normalizedSessionId,
turnId: identity.turnId, itemId: identity.itemId },
@@ -55,11 +55,11 @@ suite("durable plugin task credential handoff", () => {
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" });
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, provider: `plugin:${pluginId}:tasks`, providerLeaseId: "fixture-task", status: "active",
metadata: { driver: "plugin", pluginId, driverKey: "tasks", runnerTaskLease: true, runnerTaskDispatched: dispatched, runnerTaskExecutionStopped: false } });
await registerPluginTaskCredentialHandoff(db, { companyId, leaseId }, managed.sessionIdentity, managed.credentialWriteback!);
await registerPluginTaskCredentialHandoff(db, { companyId, leaseId }, managed.sessionIdentity, managed.credentialWriteback!, provider);
// Recovery must not depend on the original controller or its private home.
await rm(managed.home!, { recursive: true, force: true });
const calls: string[] = [];
let failExport = false, exported: string | null = auth("fixture-refreshed", 2021);
let failExport = false, exported: string | null = credential("fixture-refreshed", 2021), exportedProvider: string = provider;
const workers = { getWorker: () => ({ supportedMethods: ["environmentTask"] }),
call: async (_plugin: string, _method: string, params: any) => {
calls.push(params.operation.kind);
@@ -68,7 +68,7 @@ suite("durable plugin task credential handoff", () => {
if (params.operation.kind === "credentials") {
expect(params.operation.accountIdentity).toBe(managed.sessionIdentity);
if (failExport) throw new Error("fixture export unavailable");
return { kind: "credentials", taskId: "fixture-task", credential: exported === null ? null : { type: "codex-auth-json", authJson: exported } };
return { kind: "credentials", taskId: "fixture-task", credential: exported === null ? null : { type: "auth-file", provider: exportedProvider, content: exported } };
}
return { kind: "accepted", taskId: "fixture-task" };
} } as unknown as PluginWorkerManager;
@@ -79,7 +79,7 @@ suite("durable plugin task credential handoff", () => {
if (result.kind !== "credentials") throw new Error("Unexpected credential result");
return result.credential;
}),
exportCredential(value: string | null) { exported = value; },
exportCredential(value: string | null, from = provider as string) { exported = value; exportedProvider = from; },
failExport(value: boolean) { failExport = value; }, credential: () => service.credential(selection!),
settle: (executionStopObserved = false) => settleDispatchedEnvironmentTask(db, workers, { companyId, id: leaseId }, { executionStopObserved }) };
}
@@ -97,6 +97,15 @@ suite("durable plugin task credential handoff", () => {
expect(f.calls).toHaveLength(4);
});
it("writes a Grok task's refreshed sign-in file back to its account", async () => {
const f = await fixture(true, "grok");
await expect(f.synchronize()).resolves.toBe("rotated");
expect(await f.credential()).toBe(f.accountCredential("fixture-refreshed", 2021));
f.exportCredential(auth("fixture-other-provider", 2022), "codex");
await expect(f.synchronize()).rejects.toThrow("provider mismatch");
expect(await f.credential()).toBe(f.accountCredential("fixture-refreshed", 2021));
});
it.each(["codex", "grok"] as const)("writes managed %s refreshes without any plugin or invocation home", async provider => {
const f = await fixture(true, provider);
const read = vi.fn(async () => f.accountCredential("fixture-refreshed", 2021));
+1 -1
View File
@@ -1134,7 +1134,7 @@ export async function createApp(
api.use(
adapterRoutes({
db,
resolveRunnerTarget: (companyId, environmentId) => resolveAgentRunnerTargetForCompany(db, companyId, environmentId),
resolveRunnerTarget: (companyId, environmentId) => resolveAgentRunnerTargetForCompany(db, companyId, environmentId, undefined, workerManager),
getNativeRunnerEnabled: async () =>
(await instanceSettingsService(db).getExperimental())
.enableNativeRunner === true,
+3
View File
@@ -115,6 +115,7 @@ interface AdapterCapabilities {
interface AdapterInfo extends AgentRunnerAvailability {
candidateHarnesses?: Array<{ agent: "antigravity"; model: string }>;
supportedAdapters?: string[];
type: string;
label: string;
source: "builtin" | "external";
@@ -195,6 +196,8 @@ function buildAdapterInfo(adapter: ServerAdapterModule, externalRecord: AdapterP
disabled: disabledSet.has(adapter.type),
capabilities: buildAdapterCapabilities(adapter),
...agentRunnerAvailability(adapter.type, target, [...disabledSet]),
...(adapter.type === "paperclip_runner" && target?.runnerTasks && target.supportedAdapters
? { supportedAdapters: target.supportedAdapters } : {}),
...(adapter.acp ? { acp: adapter.acp } : {}),
overriddenBuiltin: externalRecord ? BUILTIN_ADAPTER_TYPES.has(adapter.type) : undefined,
overridePaused: BUILTIN_ADAPTER_TYPES.has(adapter.type) ? isOverridePaused(adapter.type) : undefined,
+33 -21
View File
@@ -15,8 +15,8 @@ import { connectionManagementService, continuingConnectionManagement } from "../
import { connectionManagementGuard, connectionRequestContext, connectionRequestUserId, aiLoginUserAction } from "./connection-management-authz.js";
import { cancellationRequestId } from "../services/native-runtime/native-cancellation-request.js";
import { NATIVE_CLEANUP_SETTLING_MESSAGE } from "../services/native-runtime/completed-turn-cleanup.js";
import { agentHarnessType, environmentLoginRequiresAgent, isEnvironmentDriverSupportedForAdapter, normalizeClaudeRunnerOptions, pluginEnvironmentLoginReadsCredential, type AgentConfigurationWarning, type AgentRunnerChoice } from "@paperclipai/shared";
import { resolveNewAgentRunnerForCompany } from "../services/agent-runner-selection.js";
import { agentHarnessType, environmentLoginRequiresAgent, isEnvironmentDriverSupportedForAdapter, normalizeClaudeRunnerOptions, type AgentConfigurationWarning, type AgentRunnerChoice } from "@paperclipai/shared";
import { assertRunnerTaskEnvironmentSupportsHarness, resolveNewAgentRunnerForCompany } from "../services/agent-runner-selection.js";
import { PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, pluginEnvironmentRunnerTaskDriver, pluginRunnerAiConnectionRequiredMessage, pluginRunnerAiConnectionRequiredTestResult } from "../services/plugin-runner-ai-connection.js";
import { agentEnvironmentTestService } from "../services/agent-environment-test.js";
import { qualifyAgentRunner } from "../services/agent-runner-qualification.js";
@@ -161,7 +161,7 @@ import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { environmentService } from "../services/environments.js";
import { environmentRuntimeService } from "../services/environment-runtime.js";
import { pluginSupportsLoginPty, resolvePluginEnvironmentDriver, resolvePluginSandboxProviderDriverByKey, sandboxProviderSupportsLoginPty } from "../services/plugin-environment-driver.js";
import { pluginDriverLoginAdapters, resolvePluginEnvironmentDriver, resolvePluginSandboxProviderDriverByKey, sandboxProviderSupportsLoginPty } from "../services/plugin-environment-driver.js";
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
import type {
AdapterEnvironmentCheck,
@@ -881,8 +881,8 @@ export function agentRoutes(
// earlier, so a managed reconciliation can rebind the environment to an
// unsupported provider between the gate and the acquire; this fails closed
// before the lease and the pseudo-terminal.
assertProviderSupportsLoginPty: (environmentId) =>
assertCodexLoginProviderCapability(environmentId),
assertProviderSupportsLoginPty: (environmentId, adapterType) =>
assertDeviceLoginProviderCapability(environmentId, adapterType),
// Wire the live Codex pseudo-terminal opener through the plugin worker
// manager route. The opener sets the sandbox `CODEX_HOME` to the same
// server-controlled session home the descriptor-bound credential read
@@ -1601,11 +1601,12 @@ export function agentRoutes(
* capability. It resolves the effective provider from the current environment
* config, then reads the static capability from the provider plugin manifest. It
* never checks the provider by name. A missing provider, a missing plugin, a
* non-plugin provider, and a provider without the flag all return false. Both
* login flows share this resolver, so both gates read the same current
* capability.
* non-plugin provider, and a provider without the flag all return false. A
* plugin environment driver must also host this adapter's sign-in on its
* running worker. Both login flows share this resolver, so both gates read the
* same current capability.
*/
async function resolveProviderSupportsLoginPty(environmentId: string, adapterType: "claude_local" | "codex_local"): Promise<boolean> {
async function resolveProviderSupportsLoginPty(environmentId: string, adapterType: string): Promise<boolean> {
const environment = await environmentsSvc.getById(environmentId);
const config =
environment?.config && typeof environment.config === "object"
@@ -1616,7 +1617,7 @@ export function agentRoutes(
try {
const resolved = await resolvePluginEnvironmentDriver({ db, workerManager: options.pluginWorkerManager, config: config as unknown as import("@paperclipai/shared").PluginEnvironmentConfig });
const methods = options.pluginWorkerManager.getWorker(resolved.plugin.id)?.supportedMethods ?? [];
return pluginSupportsLoginPty(resolved.driver, methods, pluginEnvironmentLoginReadsCredential(adapterType));
return pluginDriverLoginAdapters(resolved.driver, methods).includes(adapterType);
} catch { return false; }
}
const provider = typeof config.provider === "string" ? config.provider : "";
@@ -1641,15 +1642,15 @@ export function agentRoutes(
}
/**
* Fails closed when the environment provider does not advertise the login
* pseudo-terminal capability that the Codex device login needs. It reads the
* current provider capability. The Codex route runs it before any session or
* Fails closed when the environment provider does not host the device login
* for this adapter. It reads the current provider capability. The device
* login route runs it before any session or
* lease state, and the lease-acquisition path runs it again from current runtime
* state before the provider lease. It fails closed with the fixed, typed error,
* so no session row, lease, or pseudo-terminal starts.
*/
async function assertCodexLoginProviderCapability(environmentId: string): Promise<void> {
if (!(await resolveProviderSupportsLoginPty(environmentId, "codex_local"))) {
async function assertDeviceLoginProviderCapability(environmentId: string, adapterType: string): Promise<void> {
if (!(await resolveProviderSupportsLoginPty(environmentId, adapterType))) {
throw unprocessable(DEVICE_LOGIN_PROVIDER_UNSUPPORTED, {
code: DEVICE_LOGIN_PROVIDER_UNSUPPORTED_CODE,
});
@@ -3467,6 +3468,7 @@ export function agentRoutes(
adapterType: type, adapterConfig: adapterConfigForTest,
runner: testRunner,
defaultEnvironmentId: requestedEnvironmentId,
pluginWorkers: options.pluginWorkerManager,
});
type = selection.adapterType;
adapterConfigForTest = { ...selection.adapterConfig,
@@ -3823,7 +3825,7 @@ export function agentRoutes(
const targetAgentId = await resolveSandboxLoginTarget(companyId, data.environmentId, {
agentId: data.agentId, adapterType: data.adapterType, selectComputer: Boolean(data.aiConnection),
});
await assertCodexLoginProviderCapability(data.environmentId);
await assertDeviceLoginProviderCapability(data.environmentId, data.adapterType);
return targetAgentId;
},
});
@@ -4471,8 +4473,12 @@ export function agentRoutes(
);
}
const rollbackWarnings = await checkAgentProtectedEnvironmentKeys(db, rollbackAdapterConfig,
typeof rollbackConfig.defaultEnvironmentId === "string" ? rollbackConfig.defaultEnvironmentId : null);
const rollbackEnvironmentId = typeof rollbackConfig.defaultEnvironmentId === "string" ? rollbackConfig.defaultEnvironmentId : null;
await assertRunnerTaskEnvironmentSupportsHarness(db, existing.companyId, {
adapterType: rollbackAdapterType, adapterConfig: rollbackAdapterConfig,
defaultEnvironmentId: rollbackEnvironmentId, pluginWorkers: options.pluginWorkerManager,
});
const rollbackWarnings = await checkAgentProtectedEnvironmentKeys(db, rollbackAdapterConfig, rollbackEnvironmentId);
const actor = getActorInfo(req);
const updated = await svc.rollbackConfigRevision(id, revisionId, {
@@ -4666,7 +4672,7 @@ export function agentRoutes(
}
if (inheritRuntimeFrom === "caller" && hireRunner !== undefined) throw unprocessable("inheritRuntimeFrom=caller cannot be combined with runner");
let configurationWarnings: AgentConfigurationWarning[] = [];
Object.assign(hireInput, await resolveNewAgentRunnerForCompany(db, companyId, { ...hireInput, runner: hireRunner,
Object.assign(hireInput, await resolveNewAgentRunnerForCompany(db, companyId, { ...hireInput, runner: hireRunner, pluginWorkers: options.pluginWorkerManager,
onConfigurationWarnings: warnings => { configurationWarnings = warnings; } }));
hireInput.adapterType = await assertSelectableAdapterType(hireInput.adapterType, hireInput.adapterConfig, companyId);
const rawHireAdapterConfig = (hireInput.adapterConfig ?? {}) as Record<string, unknown>;
@@ -5017,7 +5023,7 @@ export function agentRoutes(
assertExternalInstructionsAdmin(req, { id: agentId, companyId, name: createInput.name, adapterConfig: requestedCreateConfig });
let configurationWarnings: AgentConfigurationWarning[] = [];
Object.assign(createInput, await resolveNewAgentRunnerForCompany(db, companyId, { ...createInput, runner: createRunner, setupOnly: Boolean(setupId),
onConfigurationWarnings: warnings => { configurationWarnings = warnings; } }));
pluginWorkers: options.pluginWorkerManager, onConfigurationWarnings: warnings => { configurationWarnings = warnings; } }));
createInput.adapterType = await assertSelectableAdapterType(createInput.adapterType, createInput.adapterConfig, companyId);
const rawCreateAdapterConfig = (createInput.adapterConfig ?? {}) as Record<string, unknown>;
assertProviderTraceSettingTransition(req, createInput.runtimeConfig);
@@ -5755,7 +5761,7 @@ export function agentRoutes(
Object.assign(patchData, await resolveNewAgentRunnerForCompany(db, existing.companyId, {
adapterType: convertingPi || convertingGrok ? existing.adapterType : typeof patchData.adapterType === "string" ? patchData.adapterType : existing.adapterType,
adapterConfig: config, runner: runner ?? "paperclip", setupOnly: existing.lifecycleHolds?.includes("setup"),
onConfigurationWarnings: warnings => { configurationWarnings = warnings; },
pluginWorkers: options.pluginWorkerManager, onConfigurationWarnings: warnings => { configurationWarnings = warnings; },
defaultEnvironmentId: hasOwn(patchData, "defaultEnvironmentId") ? patchData.defaultEnvironmentId as string | null : existing.defaultEnvironmentId,
}));
}
@@ -5961,6 +5967,12 @@ export function agentRoutes(
allowedSandboxProviders: allowedSandboxProvidersForAgent(requestedAdapterType),
},
);
await assertRunnerTaskEnvironmentSupportsHarness(db, existing.companyId, {
adapterType: requestedAdapterType,
adapterConfig: asRecord(patchData.adapterConfig ?? existing.adapterConfig) ?? {},
defaultEnvironmentId: nextDefaultEnvironmentId,
pluginWorkers: options.pluginWorkerManager,
});
const protectedKeyWarnings = await checkAgentProtectedEnvironmentKeys(db, patchData.adapterConfig ?? existing.adapterConfig, nextDefaultEnvironmentId);
configurationWarnings.push(...protectedKeyWarnings.filter(warning => !configurationWarnings.some(existing => existing.field === warning.field)));
}
+4 -1
View File
@@ -821,7 +821,10 @@ export function environmentRoutes(
},
);
res.json({ ...capabilities, loginPtyDrivers: Object.fromEntries(loginDrivers.map(driver => [
`${driver.pluginKey}:${driver.driverKey}`, { supportsLoginPty: driver.supportsLoginPty === true, supportsCodexLogin: driver.supportsCodexLogin === true },
`${driver.pluginKey}:${driver.driverKey}`, {
supportsLoginPty: driver.supportsLoginPty === true,
loginAdapters: driver.loginAdapters,
},
])) });
});
@@ -546,7 +546,8 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
}
const target = context.executionTarget;
if (managed.credentialWriteback && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId) {
await registerPluginTaskCredentialHandoff(db, { companyId: context.companyId, leaseId: target.leaseId }, managed.sessionIdentity, managed.credentialWriteback);
await registerPluginTaskCredentialHandoff(db, { companyId: context.companyId, leaseId: target.leaseId }, managed.sessionIdentity, managed.credentialWriteback,
binding.provider === "xai" ? "grok" : undefined);
}
const result = await probeManagedEnvironment(adapterType, context, binding, managed);
// A provider rejection invalidates the tested credential generation. A
@@ -18,7 +18,7 @@ vi.mock("./environment-config.js", async () => ({
}));
vi.mock("./plugin-registry.js", () => ({ pluginRegistryService: () => ({ getByKey: state.pluginByKey }) }));
vi.mock("@paperclipai/adapter-utils/ssh", () => ({ runSshCommand: state.ssh }));
import { AGENT_RUNNER_SSH_PLATFORM_COMMAND, agentRunnerAvailability, resolveAgentRunnerTaskDriverForCompany, resolveAgentRunnerTargetForCompany, resolveNewAgentRunner, resolveNewAgentRunnerForCompany } from "./agent-runner-selection.js";
import { AGENT_RUNNER_SSH_PLATFORM_COMMAND, agentRunnerAvailability, assertRunnerTaskEnvironmentSupportsHarness, resolveAgentRunnerTaskDriverForCompany, resolveAgentRunnerTargetForCompany, resolveNewAgentRunner, resolveNewAgentRunnerForCompany } from "./agent-runner-selection.js";
import { buildCodexAcpConfig, resolveCodexExecutionEngine } from "@paperclipai/adapter-codex-local/server";
import { secretService } from "./secrets.js";
import * as localPlatform from "../lib/agent-runner-platform.js";
@@ -771,6 +771,63 @@ describe("Runner-only plugin environments", () => {
.rejects.toThrow("The fake sandbox provider cannot execute runs.");
});
it("offers and saves only the adapters a listing driver supports", async () => {
state.pluginByKey.mockResolvedValue(plugin({ supportsTasks: true, supportsLoginPty: true, creationOperationVersion: 1,
supportedAdapters: ["claude_local", "copilot_runtime"] }));
const target = await resolveAgentRunnerTargetForCompany({} as never, "company", "computer");
expect(target).toEqual({ driver: "plugin", runnerTasks: true, supportedAdapters: ["claude_local", "copilot_runtime"] });
expect(agentRunnerAvailability("claude_local", target)).toEqual({ supportedRunners: ["paperclip"], defaultRunner: "paperclip" });
expect(agentRunnerAvailability("grok_local", target)).toEqual({ supportedRunners: [], defaultRunner: "legacy" });
expect(agentRunnerAvailability("paperclip_runner", { ...target, supportedAdapters: ["copilot_runtime"] }).supportedRunners).not.toEqual([]);
expect(agentRunnerAvailability("paperclip_runner", { ...target, supportedAdapters: [] })).toEqual({ supportedRunners: [], defaultRunner: "legacy" });
const copilot = { provider: "acpx", acpxAgent: "copilot", model: "gpt-5" };
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner", adapterConfig: copilot, defaultEnvironmentId: "computer" }))
.resolves.toMatchObject({ adapterType: "paperclip_runner" });
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner",
adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "grok-4.7" }, defaultEnvironmentId: "computer" }))
.rejects.toMatchObject({ status: 422, details: { code: "agent_runner_unavailable", harness: "grok_local" } });
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner", runner: "auto",
adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "grok-4.7" }, defaultEnvironmentId: "computer" }))
.rejects.toMatchObject({ status: 422, details: { code: "agent_runner_unavailable", harness: "grok_local" } });
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner", runner: "auto",
adapterConfig: copilot, defaultEnvironmentId: "computer" })).resolves.toMatchObject({ adapterType: "paperclip_runner" });
state.settings = { defaultEnvironmentId: "computer" };
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner", adapterConfig: { provider: "codex" } }))
.rejects.toMatchObject({ details: { harness: "codex_local" } });
});
it("offers and saves only the listed adapters that the running worker supports end to end", async () => {
state.pluginByKey.mockResolvedValue(plugin({ supportsTasks: true, supportsLoginPty: true, creationOperationVersion: 1,
supportedAdapters: ["claude_local", "codex_local"] }));
const login = ["environmentTask", "environmentAcquireLease", "environmentInspectLease", "environmentReleaseLease",
"loginPtyOpen", "loginPtyInput", "loginPtyStop", "loginPtyClose"];
const workers = { getWorker: vi.fn((pluginId: string) => pluginId === "plugin-id" ? { supportedMethods: login } : undefined) };
const target = await resolveAgentRunnerTargetForCompany({} as never, "company", "computer", undefined, workers);
expect(target).toEqual({ driver: "plugin", runnerTasks: true, supportedAdapters: ["claude_local"] });
expect(agentRunnerAvailability("codex_local", target)).toEqual({ supportedRunners: [], defaultRunner: "legacy" });
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner", adapterConfig: { provider: "codex" },
defaultEnvironmentId: "computer", pluginWorkers: workers })).rejects.toMatchObject({ status: 422, details: { harness: "codex_local" } });
workers.getWorker.mockReturnValue({ supportedMethods: [...login, "loginPtyReadCredential"] });
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner", adapterConfig: { provider: "codex" },
defaultEnvironmentId: "computer", pluginWorkers: workers })).resolves.toMatchObject({ adapterType: "paperclip_runner" });
workers.getWorker.mockReturnValue(undefined);
expect(await resolveAgentRunnerTargetForCompany({} as never, "company", "computer", undefined, workers))
.toMatchObject({ supportedAdapters: ["claude_local", "codex_local"] });
});
it("saves a Cursor Cloud agent whose inherited default environment lists other adapters", async () => {
state.pluginByKey.mockResolvedValue(plugin({ supportsTasks: true, supportsLoginPty: true, creationOperationVersion: 1,
supportedAdapters: ["claude_local"] }));
state.settings = { defaultEnvironmentId: "computer" };
await expect(assertRunnerTaskEnvironmentSupportsHarness({} as never, "company", { adapterType: "paperclip_runner",
adapterConfig: { provider: "cursor_cloud" }, defaultEnvironmentId: null })).resolves.toBeUndefined();
await expect(assertRunnerTaskEnvironmentSupportsHarness({} as never, "company", { adapterType: "paperclip_runner",
adapterConfig: { provider: "codex" }, defaultEnvironmentId: null })).rejects.toMatchObject({ details: { harness: "codex_local" } });
});
it("checks no harness against a driver that predates the list", async () => {
await expect(resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "paperclip_runner",
adapterConfig: { provider: "acpx", acpxAgent: "grok", model: "grok-4.7" }, defaultEnvironmentId: "computer" }))
.resolves.toMatchObject({ adapterType: "paperclip_runner" });
});
it("saves a Claude agent on the plugin environment as Paperclip Runner", async () => {
const saved = await resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "claude_local", defaultEnvironmentId: "computer" });
expect(saved).toMatchObject({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" } });
+57 -9
View File
@@ -1,6 +1,6 @@
import { assertProviderApiPlacementPolicy, managedCursorApiDefaultEnabled, resolveProviderApiPlacement } from "./native-runtime/provider-api-placement.js";
import type { Db } from "@paperclipai/db";
import { agentHarnessType, paperclipRunnerProfileForHarness, isEnvironmentDriverSupportedForAdapter, paperclipRunnerSupportsPlatform, type AgentRunnerChoice, type AgentRunnerAvailability } from "@paperclipai/shared";
import { agentHarnessName, agentHarnessType, paperclipRunnerProfileForHarness, isEnvironmentDriverSupportedForAdapter, paperclipRunnerSupportsPlatform, type AgentRunnerChoice, type AgentRunnerAvailability } from "@paperclipai/shared";
import { normalizeLegacyRunnerProvider, PAPERCLIP_RUNNER_DEFAULT_MODELS } from "@paperclipai/adapter-utils";
import { resolveClaudeModel } from "@paperclipai/adapter-claude-local";
import { DEFAULT_GROK_LOCAL_MODEL } from "@paperclipai/adapter-grok-local";
@@ -18,7 +18,7 @@ import { normalizeClaudeRunnerOptions, type AgentConfigurationWarning } from "@p
import { usesManagedCloudSandboxImage } from "./sandbox-snapshot-qualification.js";
import { environmentCustomImageTemplateMatchesBaseConfig } from "./environment-custom-image-runtime.js";
import type { ExecutionPolicy } from "./execution-allowlist.js";
import { pluginEnvironmentRunnerTaskDriver } from "./plugin-runner-ai-connection.js";
import { pluginEnvironmentRunnerTaskDriver, type PluginRunnerTaskWorkers } from "./plugin-runner-ai-connection.js";
export type RunnerTarget = {
driver: string; platform?: string; architecture?: string; libc?: "glibc" | "musl" | "unknown"; glibcVersion?: string;
@@ -26,6 +26,7 @@ export type RunnerTarget = {
runnerTasks?: boolean;
managedCloudImage?: boolean;
warmTaskVersion?: 1;
supportedAdapters?: string[];
executionMode?: ExecutionPolicy["executionMode"];
};
export const AGENT_RUNNER_SSH_PLATFORM_COMMAND = "uname -s; uname -m; if paperclip_glibc_version=$(getconf GNU_LIBC_VERSION 2>/dev/null) && [ -n \"$paperclip_glibc_version\" ]; then printf 'glibc\\n%s\\n' \"$paperclip_glibc_version\"; else case \"$(ldd --version 2>&1)\" in *musl*) printf 'musl\\n' ;; *) printf 'unknown\\n' ;; esac; fi";
@@ -65,6 +66,10 @@ export function agentRunnerAvailability(harness: string, target: RunnerTarget =
defaultRunner: legacy || !supported ? "legacy" : "paperclip" };
}
if (target.driver === "unavailable") return { supportedRunners: [], defaultRunner: "legacy" };
if (target.runnerTasks && target.supportedAdapters && (harness === "paperclip_runner"
? target.supportedAdapters.length === 0 : !target.supportedAdapters.includes(harness))) {
return { supportedRunners: [], defaultRunner: "legacy" };
}
if (target.runnerTasks || target.managedCloudImage) {
return runnerAdaptersAvailable(harness, target.driver, disabledTypes)
? { supportedRunners: target.runnerTasks ? ["paperclip"] : ["paperclip", "legacy"], defaultRunner: "paperclip" }
@@ -378,7 +383,30 @@ function resolveAgentRunner(input: AgentRunnerSelection): { adapterType: string;
return { adapterType: "paperclip_runner", adapterConfig: config };
}
export async function resolveNewAgentRunnerForCompany(db: Db, companyId: string, input: AgentRunnerSelection & { defaultEnvironmentId?: string | null }) {
export async function assertRunnerTaskEnvironmentSupportsHarness(db: Db, companyId: string, input: {
adapterType: string; adapterConfig?: Record<string, unknown>; defaultEnvironmentId?: string | null;
pluginWorkers?: PluginRunnerTaskWorkers;
}) {
if (input.adapterType !== "paperclip_runner") return;
const harness = agentHarnessName(input.adapterType, input.adapterConfig ?? {});
if (harness === "cursor_cloud") return;
const { instanceSettingsService } = await import("./instance-settings.js");
const { environmentService } = await import("./environments.js");
const settings = await instanceSettingsService(db).get();
if (settings.general?.executionMode === "kubernetes") return;
const environmentId = input.defaultEnvironmentId ?? settings.defaultEnvironmentId;
const environment = environmentId ? await environmentService(db).getById(environmentId) : null;
if (environment?.driver !== "plugin") return;
const driver = await pluginEnvironmentRunnerTaskDriver(db, environment, input.pluginWorkers);
if (driver?.supportedAdapters && !driver.supportedAdapters.includes(harness)) {
throw unsupportedHarness(harness);
}
}
export async function resolveNewAgentRunnerForCompany(db: Db, companyId: string, input: AgentRunnerSelection & {
defaultEnvironmentId?: string | null;
pluginWorkers?: PluginRunnerTaskWorkers;
}) {
const disabledTypes = await adapterSettingsService(db).getDisabledTypes();
input = { ...input, disabledTypes };
const cursor = agentHarnessType(input.adapterType ?? "process", input.adapterConfig) === "cursor_cloud";
@@ -407,20 +435,40 @@ export async function resolveNewAgentRunnerForCompany(db: Db, companyId: string,
}
}
if (!paperclipRunnerProfileForHarness(agentHarnessType(input.adapterType ?? "process", input.adapterConfig))
|| input.runner === "legacy" || (input.adapterType === "paperclip_runner" && (input.runner === undefined || input.runner === "paperclip"))) return resolveNewAgentRunner(input);
const target = await resolveAgentRunnerTargetForCompany(db, companyId, input.defaultEnvironmentId, input.disabledTypes);
return resolveNewAgentRunner({ ...input, target });
|| input.runner === "legacy" || (input.adapterType === "paperclip_runner" && (input.runner === undefined || input.runner === "paperclip"))) {
const selected = resolveNewAgentRunner(input);
await assertRunnerTaskEnvironmentSupportsHarness(db, companyId, { ...selected, defaultEnvironmentId: input.defaultEnvironmentId, pluginWorkers: input.pluginWorkers });
return selected;
}
const target = await resolveAgentRunnerTargetForCompany(db, companyId, input.defaultEnvironmentId, input.disabledTypes, input.pluginWorkers);
const selected = resolveNewAgentRunner({ ...input, target });
assertRunnerTargetSupportsHarness(target, selected);
return selected;
}
export async function resolveAgentRunnerTargetForCompany(db: Db, companyId: string, defaultEnvironmentId?: string | null, disabledTypes?: string[]): Promise<RunnerTarget> {
function assertRunnerTargetSupportsHarness(target: RunnerTarget, selected: { adapterType: string; adapterConfig: Record<string, unknown> }) {
if (selected.adapterType !== "paperclip_runner" || !target.runnerTasks || !target.supportedAdapters) return;
const harness = agentHarnessName(selected.adapterType, selected.adapterConfig);
if (!target.supportedAdapters.includes(harness)) throw unsupportedHarness(harness);
}
function unsupportedHarness(harness: string) {
return unprocessable("This environment does not support the selected harness. Choose a supported harness or environment.", {
code: "agent_runner_unavailable", harness,
});
}
export async function resolveAgentRunnerTargetForCompany(db: Db, companyId: string, defaultEnvironmentId?: string | null, disabledTypes?: string[],
pluginWorkers?: PluginRunnerTaskWorkers): Promise<RunnerTarget> {
await waitForExternalAdapters();
const { environment, driver, executionMode } = await resolveAgentRunnerEnvironmentForCompany(db, companyId, defaultEnvironmentId);
const withPolicy = (value: RunnerTarget): RunnerTarget => ({ ...value, ...(executionMode ? { executionMode } : {}) });
let target: RunnerTarget = driver === "local" ? localAgentRunnerTarget()
: { driver };
if (driver === "plugin" && environment) {
const taskDriver = await pluginEnvironmentRunnerTaskDriver(db, environment);
if (taskDriver) target = { driver, runnerTasks: true, ...(taskDriver.warmTaskVersion === 1 ? { warmTaskVersion: 1 as const } : {}) };
const taskDriver = await pluginEnvironmentRunnerTaskDriver(db, environment, pluginWorkers);
if (taskDriver) target = { driver, runnerTasks: true, ...(taskDriver.warmTaskVersion === 1 ? { warmTaskVersion: 1 as const } : {}),
...(taskDriver.supportedAdapters ? { supportedAdapters: taskDriver.supportedAdapters } : {}) };
}
if (driver === "sandbox" && environment) {
if (usesManagedCloudSandboxImage(environment, null)) {
+2 -2
View File
@@ -1638,7 +1638,7 @@ export interface ProductionLoginSessionRuntimeDeps {
* unsupported-provider error, so the runtime creates no lease and opens no
* pseudo-terminal for an unsupported provider.
*/
assertProviderSupportsLoginPty: (environmentId: string) => Promise<void>;
assertProviderSupportsLoginPty: (environmentId: string, adapterType: string) => Promise<void>;
/**
* Opens the live pseudo-terminal for the acquired lease. When a caller omits
* it, the runtime binds a fail-closed opener: the login run then fails and the
@@ -1674,7 +1674,7 @@ export function createProductionLoginSessionRuntime(
// capability, not the stale route decision. It throws the fixed
// unsupported-provider error, so the runtime acquires no lease and opens no
// pseudo-terminal for an unsupported provider.
await deps.assertProviderSupportsLoginPty(input.environmentId);
await deps.assertProviderSupportsLoginPty(input.environmentId, input.adapterType);
const record = await deps.environmentRuntime.acquireRunLease(
buildLoginLeaseAcquireArgs({
browserLogin: true,
@@ -4,7 +4,8 @@ import { attachSandboxCreation, environmentService } from "./environments.js";
import { createOwnedSandbox, queueSandboxCreationCleanup, recordSandboxCreationResource } from "./sandbox-creation-operations.js";
import { writeEnvironmentCleanup } from "./environment-cleanup-notifications.js";
import { releaseProviderRecoveryTransfers, stageProviderFreshWorkspace } from "./provider-fresh-workspace.js";
import { readWorkspaceProviderBinding } from "@paperclipai/shared";
import { agentHarnessName, readWorkspaceProviderBinding } from "@paperclipai/shared";
import { pluginDriverSupportedAdapters } from "./plugin-environment-driver.js";
import { canReadStoppedPluginTaskCredential, settlePluginTaskCredentialHandoff } from "./plugin-task-credential-writeback.js";
import { and, eq, inArray, sql } from "drizzle-orm";
import { environmentLeases, executionWorkspaces, environments, heartbeatRuns, issues, projects, type Db } from "@paperclipai/db";
@@ -410,13 +411,23 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
JSON.stringify([...proof.projectIds].sort()) !== JSON.stringify([...operation.projectIds].sort()))
throw new Error("Plugin Runner file scope unavailable");
}
const gatedHarness = operation.kind === "submit" ? operation.runner.harness
: operation.kind === "resume" ? [metadata.runnerTaskHarness, savedIdentity?.harness].find(value => typeof value === "string") as string | undefined
: undefined;
if (gatedHarness && driver.supportedAdapters) {
const adapter = agentHarnessName("paperclip_runner", ["codex", "opencode"].includes(gatedHarness)
? { provider: gatedHarness } : { provider: "acpx", acpxAgent: gatedHarness });
if (!pluginDriverSupportedAdapters(driver, worker.supportedMethods)?.includes(adapter)) {
throw new Error("Plugin Runner harness is unavailable on this environment");
}
}
if (operation.kind === "submit") {
const proof = metadata.runnerTaskProjectAuthValidation as { configurationId?: unknown; provider?: unknown; projectIds?: string[] } | undefined;
const provider = operation.runner.harness === "codex" ? "openai" : operation.runner.harness === "claude" ? "anthropic" : operation.runner.harness;
const projectAuthProvider = (harness: string) => harness === "codex" ? "openai" : harness === "claude" ? "anthropic" : harness;
const provider = projectAuthProvider(operation.runner.harness);
if (!provider || !operation.preparedLaunchId || proof?.configurationId !== operation.preparedLaunchId || proof.provider !== provider
|| (!Array.isArray(proof.projectIds) ? null : JSON.stringify([...proof.projectIds].sort())) !== JSON.stringify([...operation.projectIds].sort())
|| (operation.credential && (operation.credential.type === "codex-auth-json" ? "openai"
: operation.credential.type === "claude-env" ? "anthropic" : operation.credential.provider) !== provider)) {
|| (operation.credential && projectAuthProvider(operation.credential.type === "claude-env" ? "claude" : operation.credential.provider) !== provider)) {
throw new Error("Plugin Runner managed project authentication validation unavailable");
}
requiredProjectAuthProof = proof as Record<string, unknown>;
@@ -442,6 +453,7 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
runnerTaskExecutionStopped: false, runnerTaskSessionRetained: false,
...(operation.kind === "submit" ? {
runnerTaskIdentity: operation.runner,
runnerTaskHarness: operation.runner.harness,
runnerTaskResumeFrom: operation.resumeFrom ?? null,
runnerTaskAccountIdentity: operation.accountIdentity,
} : {}),
+11 -18
View File
@@ -9,23 +9,15 @@
// key routes the worker; it confers no command authority. A caller cannot pass a
// command, so the sandbox pseudo-terminal never runs an arbitrary process.
/**
* The closed set of login command identities. The host resolves the key from the
* trusted adapter type. The worker maps the key to a compile-time command. The
* union is exhaustive: a value outside it fails closed before the worker RPC.
*/
export type LoginCommandKey = "claude" | "codex" | "grok";
import { adapterLoginCommandKey, isAdapterLoginCommandKey, type AdapterLoginCommandKey } from "@paperclipai/shared";
/**
* The exhaustive map from the trusted adapter type to the login command key. The
* host reads only this map. It never reads the key from a request, a
* configuration, a plugin manifest, or the provider driver key.
* The closed set of login command identities. The host resolves the key from the
* trusted adapter type through the shared adapter sign-in map. The worker maps the
* key to a compile-time command. A value outside the set fails closed before the
* worker RPC.
*/
const ADAPTER_TYPE_TO_LOGIN_COMMAND_KEY: Readonly<Record<string, LoginCommandKey>> = {
claude_local: "claude",
codex_local: "codex",
grok_local: "grok",
};
export type LoginCommandKey = AdapterLoginCommandKey;
/** The fixed non-secret error an unsupported adapter type returns. */
export const LOGIN_COMMAND_UNSUPPORTED_ADAPTER = "LOGIN_PTY_UNSUPPORTED_ADAPTER";
@@ -34,12 +26,13 @@ export const LOGIN_SESSION_HOME_INVALID = "LOGIN_PTY_INVALID_SESSION_HOME";
/**
* Resolves the login command key from the trusted adapter type. It reads only the
* exhaustive first-party map. It throws the fixed non-secret error for an adapter
* shared first-party map, never a request, a configuration, a plugin manifest, or
* the provider driver key. It throws the fixed non-secret error for an adapter
* type that has no mapped key, so an unknown adapter fails closed before the
* worker RPC.
*/
export function resolveLoginCommandKey(adapterType: string): LoginCommandKey {
const key = ADAPTER_TYPE_TO_LOGIN_COMMAND_KEY[adapterType];
const key = adapterLoginCommandKey(adapterType);
if (!key) {
throw new Error(LOGIN_COMMAND_UNSUPPORTED_ADAPTER);
}
@@ -48,7 +41,7 @@ export function resolveLoginCommandKey(adapterType: string): LoginCommandKey {
/** Reports whether a value is a member of the closed login command key set. */
export function isLoginCommandKey(value: unknown): value is LoginCommandKey {
return value === "claude" || value === "codex" || value === "grok";
return isAdapterLoginCommandKey(value);
}
/**
@@ -58,7 +51,7 @@ export function isLoginCommandKey(value: unknown): value is LoginCommandKey {
* map later, so admission and command resolution stay consistent.
*/
export function isLoginCommandSupportedAdapterType(adapterType: string): boolean {
return ADAPTER_TYPE_TO_LOGIN_COMMAND_KEY[adapterType] !== undefined;
return adapterLoginCommandKey(adapterType) !== undefined;
}
/**
@@ -12,7 +12,8 @@ const db = { select: () => ({ from: () => ({ where: () => ({ limit: async () =>
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" }; });
describe("login environment transport target", () => {
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("rejects a provider without an existing-computer credential path", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent", adapterType: "grok_local" })).rejects.toMatchObject({ status: 400 }); });
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 }); });
it("requires a saved target for existing-computer login", async () => { await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment" })).rejects.toMatchObject({ status: 400 }); });
it("rejects a foreign company environment", async () => { fixtures.companies = ["another-company"]; await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).rejects.toMatchObject({ status: 403 }); });
it("does not expose a foreign or missing agent", async () => { fixtures.agent!.companyId = "another-company"; await expect(assertLoginEnvironmentTarget(db, { companyId: "company", environmentId: "environment", agentId: "agent" })).rejects.toMatchObject({ status: 404 }); });
+2 -2
View File
@@ -1,5 +1,5 @@
import { agents, environmentLeases, type Db } from "@paperclipai/db";
import { environmentLoginRequiresAgent, isPluginEnvironmentLoginAdapter } from "@paperclipai/shared";
import { adapterLoginCommandKey, environmentLoginRequiresAgent } from "@paperclipai/shared";
import { and, asc, eq, isNull, notExists, notInArray, or, sql } from "drizzle-orm";
import { badRequest, forbidden, notFound } from "../errors.js";
import { assertEnvironmentSelectionForCompany } from "./environment-selection.js";
@@ -29,7 +29,7 @@ export async function resolveLoginEnvironmentTarget(
if (input.agentId) throw badRequest("A temporary sandbox login does not take an agent computer target.");
return { environment, agentId: undefined };
}
if (input.adapterType && !isPluginEnvironmentLoginAdapter(input.adapterType)) throw badRequest("This provider login is not supported on agent computers.", { code: "login_adapter_unsupported" });
if (input.adapterType && !adapterLoginCommandKey(input.adapterType)) throw badRequest("This provider login is not supported on agent computers.", { code: "login_adapter_unsupported" });
if (!input.agentId) {
if (!input.selectComputer) throw badRequest("Select an agent computer for sign-in.", { code: "login_agent_required" });
const settings = await instanceSettingsService(db).get();
@@ -20704,7 +20704,7 @@ describe("runnerd provider runtime wiring", () => {
expect(task.mock.calls).toEqual([[{kind:"describe"}]]);
if (portable) expect(register).toHaveBeenCalledExactlyOnceWith(expect.anything(), {
companyId: current.binding.companyId, leaseId: "new-lease",
}, "account", binding);
}, "account", binding, "codex");
else expect(register).not.toHaveBeenCalled();
} finally {register.mockRestore(); owner.mockRestore();await rm(home,{recursive:true,force:true});}
});
@@ -17143,7 +17143,8 @@ async function createRunnerdBackendWithinSessionClaim(
if ((!adopting || input.remoteWarmRecovery?.portableSourceTaskId) && input.managedAiCredentialWriteback && credentials.accountIdentity) {
if (!remoteTarget.leaseId) throw new Error("Plugin Runner credential lease unavailable");
await registerPluginTaskCredentialHandoff(input.db, { companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId },
credentials.accountIdentity, input.managedAiCredentialWriteback);
credentials.accountIdentity, input.managedAiCredentialWriteback,
credentials.credential?.type === "auth-file" ? credentials.credential.provider : undefined);
}
const taskConfiguredEnvironment = pluginTaskConfiguredEnvironment(input.runnerEnvironment);
if (description.configuredEnvironmentVersion !== 1 && Object.keys(taskConfiguredEnvironment).length > 0) {
@@ -17159,7 +17160,7 @@ async function createRunnerdBackendWithinSessionClaim(
normalizedSessionId: nativeSessionKey(input.execution),
runnerInstanceId: adoptionIdentity?.runnerInstanceId ?? prior?.runnerInstanceId ?? effectiveRunnerInstanceId,
event,
synchronizeCredentials: event.payload.provider === "codex" ? () => syncPluginTaskCredentialHandoff(input.db, {
synchronizeCredentials: credentials.credential?.type === "auth-file" && event.payload.provider === credentials.credential.provider ? () => syncPluginTaskCredentialHandoff(input.db, {
companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId!, expectedTaskId: description.taskId,
}, async accountIdentity => {
const snapshot = environmentTaskResultSchema.parse(await pluginTask({ kind: "credentials", accountIdentity }, { expectedTaskId: description.taskId }));
@@ -18,16 +18,16 @@ describe("plugin Runner selected credentials", () => {
const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} });
expect(transfer.accountIdentity).toBe("account");
expect(transfer.needsWriteback).toBe(true);
expect(transfer.credential).toEqual({ type: "codex-auth-json", authJson: JSON.stringify(auth) });
expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify(auth) });
const refreshed = { ...auth, tokens: { ...auth.tokens, refresh_token: "fixture-rotated" }, last_refresh: "2021-01-01T00:00:00Z" };
await transfer.onCredentials!({ type: "codex-auth-json", authJson: JSON.stringify(refreshed) });
await transfer.onCredentials!({ type: "auth-file", provider: "codex", content: JSON.stringify(refreshed) });
expect(JSON.parse(await readFile(join(directory, "auth.json"), "utf8"))).toEqual(refreshed);
});
it("transfers a selected API key without requiring refresh authority", async () => {
const directory = await home({ OPENAI_API_KEY: "fixture-key" });
const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} });
expect(transfer.needsWriteback).toBe(false);
expect(transfer.credential).toEqual({ type: "codex-auth-json", authJson: JSON.stringify({ OPENAI_API_KEY: "fixture-key" }) });
expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify({ OPENAI_API_KEY: "fixture-key" }) });
});
it("transfers only the selected Claude authentication variable", async () => {
const transfer = await preparePluginRunnerCredentials({ provider: "claude", identity: "revision", environment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-oauth", HOME: "/controller/private", OTHER_SECRET: "fixture-unrelated" } });
@@ -140,9 +140,20 @@ describe("plugin Runner provider environment credentials", () => {
expect(transfer.githubBroker).toEqual({ url: "https://core.example.test", token: "runtime-capability" });
expect(transfer.credential).toEqual({ type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "fixture-xai" } });
});
it("refuses a Grok subscription, which needs an auth file with refresh and writeback", async () => {
await expect(preparePluginRunnerCredentials({ provider: "grok", identity: "revision", home: "/controller/private/provider",
environment: blanks })).rejects.toThrow("Grok subscription login is not supported");
it("sends a Grok subscription as its saved sign-in file and requires the managed writeback", async () => {
const grokAuth = { "https://auth.x.ai::00000000-0000-4000-8000-000000000000": { key: "fixture-key", refresh_token: "fixture-refresh" } };
const directory = await home(grokAuth);
const transfer = await preparePluginRunnerCredentials({ provider: "grok", identity: "revision", accountIdentity: "account",
home: directory, environment: blanks });
expect(transfer).toEqual({ accountIdentity: "account", needsWriteback: true,
credential: { type: "auth-file", provider: "grok", content: JSON.stringify(grokAuth) } });
});
it("refuses a Grok subscription without a usable sign-in file", async () => {
await expect(preparePluginRunnerCredentials({ provider: "grok", identity: "revision", environment: blanks }))
.rejects.toThrow("credential home unavailable");
const directory = await home({ "https://auth.x.ai::00000000-0000-4000-8000-000000000000": { key: "fixture-key" } });
await expect(preparePluginRunnerCredentials({ provider: "grok", identity: "revision", home: directory, environment: blanks }))
.rejects.toThrow("credential invalid");
});
it("refuses Grok provider routing that would redirect the key", async () => {
await expect(preparePluginRunnerCredentials({ provider: "grok", identity: "revision",
@@ -1,6 +1,7 @@
import { realpath } from "node:fs/promises";
import { join } from "node:path";
import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
import { hasUsableGrokAuthValue, parseGrokAuthPayload } from "@paperclipai/adapter-grok-local/server";
import {
ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS, environmentTaskCredentialSchema,
type PluginEnvironmentTaskCredential, type PluginEnvironmentTaskCredentialProvider,
@@ -38,14 +39,27 @@ export async function preparePluginRunnerCredentials(input: {
const authJson = await readLocalAiCredentialFile(hostAuthPath);
const parsed = JSON.parse(authJson);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Plugin Runner selected credential invalid");
const credential = environmentTaskCredentialSchema.parse({ type: "codex-auth-json", authJson });
const credential = environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "codex", content: authJson });
return { ...github, accountIdentity, credential, needsWriteback: !!parsed.tokens,
onCredentials: async (snapshot: PluginEnvironmentTaskCredential) => {
if (snapshot.type !== "codex-auth-json") throw new Error("Plugin Runner credential provider mismatch");
await copyBackCodexAuth({ hostAuthPath, readSandboxAuth: async () => Buffer.from(snapshot.authJson), log: () => {} });
if (snapshot.type !== "auth-file" || snapshot.provider !== "codex") throw new Error("Plugin Runner credential provider mismatch");
await copyBackCodexAuth({ hostAuthPath, readSandboxAuth: async () => Buffer.from(snapshot.content), log: () => {} });
},
};
}
if (input.provider === "grok" && !input.environment.XAI_API_KEY) {
if (input.environment.XAI_BASE_URL) throw new Error("Plugin Runner does not support the selected provider routing");
if (!input.home) throw new Error("Plugin Runner selected credential home unavailable");
const content = await readLocalAiCredentialFile(join(await realpath(input.home), "auth.json"));
let usable = false;
try {
const parsed = parseGrokAuthPayload(JSON.parse(content));
usable = parsed !== null && hasUsableGrokAuthValue(parsed.value);
} catch { /* Do not expose credential bytes through JSON parser errors. */ }
if (!usable) throw new Error("Plugin Runner selected credential invalid");
return { ...github, accountIdentity, needsWriteback: true,
credential: environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "grok", content }) };
}
if (input.provider === "claude") {
if (input.environment.ANTHROPIC_BASE_URL || input.environment.ANTHROPIC_AUTH_TOKEN) {
throw new Error("Plugin Runner does not support the selected provider routing");
@@ -58,7 +72,6 @@ export async function preparePluginRunnerCredentials(input: {
const provider: PluginEnvironmentTaskCredentialProvider = input.provider;
if (provider === "grok") {
if (input.environment.XAI_BASE_URL) throw new Error("Plugin Runner does not support the selected provider routing");
if (!input.environment.XAI_API_KEY) throw new Error("Plugin Runner supports Grok only with an xAI API key. Grok subscription login is not supported.");
}
if (provider === "antigravity") {
if (input.environment[ANTIGRAVITY_SIGN_IN_ENV]?.trim()) throw new Error("Plugin Runner selected credential unavailable");
@@ -156,7 +156,7 @@ describe("plugin Runner setup", () => {
return { kind: "project_auth", taskId: "task", provider: op.provider, configurationId: op.configurationId,
allowed: !/base_url|model_provider|api_key|env_key/.test(projectConfig) };
}
case "credentials": return { kind: "credentials", taskId: "task", credential: { type: "codex-auth-json", authJson: accountJson } };
case "credentials": return { kind: "credentials", taskId: "task", credential: { type: "auth-file", provider: "codex", content: accountJson } };
case "read_state": return { kind: "state", taskId: "task", state: JSON.parse(await readFile(join(resources.runner_state!, "runner-state.json"), "utf8")) };
case "archive_state": {
const path = join(resources.runner_state!, "runner-state.json");
@@ -300,7 +300,7 @@ describe("plugin Runner setup", () => {
expect(JSON.stringify(operations)).not.toContain("core-secret-not-transferred");
expect(result.status).toBe(mode === "managed-account" ? "pass" : "fail");
if (mode === "managed-account") expect(submission).toMatchObject({ credentialIdentity: "selected-revision", accountIdentity: "selected-account",
credential: { type: "codex-auth-json", authJson: accountJson } });
credential: { type: "auth-file", provider: "codex", content: accountJson } });
expect(operations.some(op => op.kind === "submit")).toBe(true);
expect(operations.some(op => op.kind === "stop")).toBe(true);
expect(stopped).toBe(true);
@@ -334,7 +334,7 @@ describe("plugin native Runner ownership", () => {
provider: mode === "wrong-provider" ? "anthropic" : op.provider } : perform(op));
const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness: "codex",
projectAuthCheckVersion: mode === "unsupported" ? undefined : 1,
credentialIdentity: "revision", accountIdentity: "account", credential: { type: "codex-auth-json", authJson: '{"OPENAI_API_KEY":"never-transfer"}' } });
credentialIdentity: "revision", accountIdentity: "account", credential: { type: "auth-file", provider: "codex", content: '{"OPENAI_API_KEY":"never-transfer"}' } });
await expect(prepare(owner)).rejects.toThrow(mode === "unsupported" ? "validation unavailable" : "conflicts");
expect(() => owner.launcher(launchSpec())).toThrow("requires preparation");
expect(JSON.stringify(task.mock.calls)).not.toContain("never-transfer");
@@ -349,7 +349,7 @@ describe("plugin native Runner ownership", () => {
it("collects refreshed credentials after process termination and before releasing task grants", async () => {
const { task } = provider();
const perform = task.getMockImplementation()!;
const credential = { type: "codex-auth-json" as const, authJson: '{"OPENAI_API_KEY":"fixture-key"}' };
const credential = { type: "auth-file" as const, provider: "codex" as const, content: '{"OPENAI_API_KEY":"fixture-key"}' };
let copied = false;
task.mockImplementation(async operation => {
if (operation.kind === "credentials") {
@@ -373,7 +373,7 @@ describe("plugin native Runner ownership", () => {
it("retains grants when the credential handoff fails", async () => {
const { task } = provider();
const perform = task.getMockImplementation()!;
task.mockImplementation(async op => op.kind === "credentials" ? { kind: "credentials", taskId: "task", credential: { type: "codex-auth-json", authJson: "{}" } } : perform(op));
task.mockImplementation(async op => op.kind === "credentials" ? { kind: "credentials", taskId: "task", credential: { type: "auth-file", provider: "codex", content: "{}" } } : perform(op));
ingress.connect.mockReturnValue({ ready: Promise.resolve(), close: async () => {} });
const owner = createPluginRunnerTaskOwner({ taskId: "task", projectAuthCheckVersion: 1, task, projectIds: [], harness: "codex", accountIdentity: "account", pollMs: 1,
onCredentials: async () => { throw new Error("credential handoff failed"); } });
@@ -23,6 +23,8 @@ import type {
PluginEnvironmentRealizeWorkspaceResult,
} from "@paperclipai/plugin-sdk";
import { unprocessable } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { ADAPTER_LOGIN_CREDENTIAL_SOURCE, adapterLoginCommandKey } from "@paperclipai/shared";
import {
collectSecretRefPaths,
parseSecretRefBindingObject,
@@ -147,6 +149,45 @@ export function pluginSupportsLoginPty(
].every(method => methods.includes(method));
}
const TASK_WORKER_METHODS = ["environmentTask", "environmentAcquireLease", "environmentReleaseLease"] as const;
type AdapterSupportDeclaration = Pick<PluginEnvironmentDriverDeclaration,
"supportedAdapters" | "supportsTasks" | "supportsLoginPty" | "creationOperationVersion">;
export function pluginDriverSupportedAdapters(driver: AdapterSupportDeclaration, methods: readonly string[]): string[] | undefined {
if (!driver.supportedAdapters) return undefined;
if (driver.supportsTasks !== true || !TASK_WORKER_METHODS.every((method) => methods.includes(method))) return [];
return driver.supportedAdapters.filter((adapter) => {
const key = adapterLoginCommandKey(adapter);
return !key || pluginSupportsLoginPty(driver, methods, ADAPTER_LOGIN_CREDENTIAL_SOURCE[key] === "file");
});
}
export function pluginDriverLoginAdapters(driver: AdapterSupportDeclaration, methods: readonly string[]): string[] {
const supported = pluginDriverSupportedAdapters(driver, methods);
if (supported) return supported.filter((adapter) => adapterLoginCommandKey(adapter) !== undefined);
if (!pluginSupportsLoginPty(driver, methods)) return [];
return ["claude_local", ...(pluginSupportsLoginPty(driver, methods, true) ? ["codex_local"] : [])];
}
function supportedAdapterFields(pluginKey: string, driver: AdapterSupportDeclaration & { driverKey: string; kind?: string }, methods: readonly string[]) {
if (driver.kind !== "environment_driver") return { loginAdapters: [] };
const supportedAdapters = pluginDriverSupportedAdapters(driver, methods);
if (supportedAdapters) reportUnsupportedAdapters(pluginKey, driver, supportedAdapters);
return { ...(supportedAdapters ? { supportedAdapters } : {}), loginAdapters: pluginDriverLoginAdapters(driver, methods) };
}
const reportedUnsupportedAdapters = new Set<string>();
function reportUnsupportedAdapters(pluginKey: string, driver: AdapterSupportDeclaration & { driverKey: string }, supported: readonly string[]) {
for (const adapter of driver.supportedAdapters ?? []) {
const key = `${pluginKey}:${driver.driverKey}:${adapter}`;
if (supported.includes(adapter) || reportedUnsupportedAdapters.has(key)) continue;
reportedUnsupportedAdapters.add(key);
logger.warn({ pluginKey, driverKey: driver.driverKey, adapter },
"Plugin environment driver lists an adapter its worker cannot fully support; the adapter is unavailable");
}
}
export function sandboxProviderSupportsLoginPty(driver: Pick<PluginEnvironmentDriverDeclaration, "supportsLoginPty">): boolean {
return driver.supportsLoginPty === true;
}
@@ -168,7 +209,8 @@ export interface ReadyPluginEnvironmentDriver {
* matches the acquisition guard, which also verifies the same methods live.
*/
reusableLeaseMethodsVerified: boolean;
supportsCodexLogin?: boolean;
supportedAdapters?: string[];
loginAdapters: string[];
supportsInteractiveSetup?: PluginEnvironmentDriverDeclaration["supportsInteractiveSetup"];
interactiveSetupConnectionTypes?: PluginEnvironmentDriverDeclaration["interactiveSetupConnectionTypes"];
supportsTemplateCapture?: PluginEnvironmentDriverDeclaration["supportsTemplateCapture"];
@@ -429,7 +471,7 @@ export async function listReadyPluginEnvironmentDrivers(input: {
templateConfigBinding: driver.templateConfigBinding,
supportsTemplateDelete: driver.supportsTemplateDelete,
supportsLoginPty: driver.kind === "environment_driver" ? pluginSupportsLoginPty(driver, [...workerMethods]) : sandboxProviderSupportsLoginPty(driver),
supportsCodexLogin: pluginSupportsLoginPty(driver, [...workerMethods], true),
...supportedAdapterFields(plugin.pluginKey, driver, [...workerMethods]),
})),
);
}
@@ -11,19 +11,29 @@ const call = vi.fn();
const loginMethods = ["environmentAcquireLease", "environmentInspectLease", "environmentReleaseLease", "loginPtyOpen", "loginPtyInput", "loginPtyStop", "loginPtyClose", "loginPtyReadCredential"];
const methods = [...loginMethods];
const workerManager = { call, getWorker: () => ({ supportedMethods: methods }) } as unknown as PluginWorkerManager;
beforeEach(() => { call.mockReset(); call.mockResolvedValue({ kind: "codex-auth-json", authJson: '{"fixture":true}' }); methods.splice(0, methods.length, ...loginMethods); getById.mockResolvedValue({ id: "plugin", status: "ready", manifestJson: { environmentDrivers: [{ driverKey: "computer", supportsLoginPty: true, creationOperationVersion: 1 }] } }); });
beforeEach(() => { call.mockReset(); call.mockResolvedValue({ kind: "auth-file", content: '{"fixture":true}' }); methods.splice(0, methods.length, ...loginMethods); getById.mockResolvedValue({ id: "plugin", status: "ready", manifestJson: { environmentDrivers: [{ driverKey: "computer", supportsLoginPty: true, creationOperationVersion: 1 }] } }); });
describe("plugin login fixed credential result", () => {
it("reads the exact bound lease through the optional RPC", async () => {
const bytes = await readPluginLoginCredential({ db: {} as Db, workerManager, environment, lease });
expect(bytes.toString()).toBe('{"fixture":true}');
expect(call).toHaveBeenCalledWith("plugin", "loginPtyReadCredential", { driverKey: "computer", companyId: "company", environmentId: "environment", providerLeaseId: "login", loginCommandKey: "codex" });
});
it("reads a Grok sign-in file with the allocation's own command key", async () => {
const grok = { ...lease, metadata: { ...lease.metadata, loginCommandKey: "grok" } } as unknown as EnvironmentLease;
await readPluginLoginCredential({ db: {} as Db, workerManager, environment, lease: grok });
expect(call).toHaveBeenCalledWith("plugin", "loginPtyReadCredential", expect.objectContaining({ loginCommandKey: "grok" }));
});
it("never reads back a sign-in that leaves its token in the terminal output", async () => {
const claude = { ...lease, metadata: { ...lease.metadata, loginCommandKey: "claude" } } as unknown as EnvironmentLease;
await expect(readPluginLoginCredential({ db: {} as Db, workerManager, environment, lease: claude })).rejects.toThrow("Login credential result unavailable");
expect(call).not.toHaveBeenCalled();
});
it("fails before calling a driver that does not meet the login PTY rule", async () => {
getById.mockResolvedValue({ id: "plugin", status: "ready", manifestJson: { environmentDrivers: [{ driverKey: "computer", supportsLoginPty: true }] } });
await expect(readPluginLoginCredential({ db: {} as Db, workerManager, environment, lease })).rejects.toThrow("Login credential result unavailable");
expect(call).not.toHaveBeenCalled();
});
it("fails before calling a worker that lacks the optional read", async () => { methods.splice(methods.indexOf("loginPtyReadCredential"), 1); await expect(readPluginLoginCredential({ db: {} as Db, workerManager, environment, lease })).rejects.toThrow("Login credential result unavailable"); expect(call).not.toHaveBeenCalled(); });
it.each([{ kind: "other", authJson: "private-provider-output" }, { kind: "codex-auth-json", authJson: "x".repeat(65537) }, { kind: "codex-auth-json", authJson: "" }])("rejects malformed or oversized private results", async result => { call.mockResolvedValue(result); await expect(readPluginLoginCredential({ db: {} as Db, workerManager, environment, lease })).rejects.toThrow(/^Login credential result unavailable$/); });
it.each([{ kind: "other", content: "private-provider-output" }, { kind: "auth-file", content: "x".repeat(65537) }, { kind: "auth-file", content: "" }])("rejects malformed or oversized private results", async result => { call.mockResolvedValue(result); await expect(readPluginLoginCredential({ db: {} as Db, workerManager, environment, lease })).rejects.toThrow(/^Login credential result unavailable$/); });
it("rejects a mismatched allocation scope before exporting", async () => { await expect(readPluginLoginCredential({ db: {} as Db, workerManager, environment: { ...environment, id: "other" }, lease })).rejects.toThrow(); expect(call).not.toHaveBeenCalled(); });
});
@@ -1,5 +1,5 @@
import type { Db } from "@paperclipai/db";
import type { Environment, EnvironmentLease } from "@paperclipai/shared";
import { ADAPTER_LOGIN_CREDENTIAL_SOURCE, isAdapterLoginCommandKey, type Environment, type EnvironmentLease } from "@paperclipai/shared";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { pluginRegistryService } from "./plugin-registry.js";
import { pluginSupportsLoginPty } from "./plugin-environment-driver.js";
@@ -11,7 +11,9 @@ export async function readPluginLoginCredential(input: {
}): Promise<Buffer> {
try {
const metadata = input.lease.metadata;
if (input.lease.environmentId !== input.environment.id || metadata?.purpose !== "login" || metadata.loginCommandKey !== "codex" ||
const loginCommandKey = metadata?.loginCommandKey;
if (input.lease.environmentId !== input.environment.id || metadata?.purpose !== "login" ||
!isAdapterLoginCommandKey(loginCommandKey) || ADAPTER_LOGIN_CREDENTIAL_SOURCE[loginCommandKey] !== "file" ||
!input.lease.providerLeaseId || typeof metadata.pluginId !== "string" || typeof metadata.driverKey !== "string") throw new Error();
const plugin = await pluginRegistryService(input.db).getById(metadata.pluginId);
const driver = plugin?.manifestJson.environmentDrivers?.find(candidate => candidate.driverKey === metadata.driverKey);
@@ -19,10 +21,10 @@ export async function readPluginLoginCredential(input: {
!pluginSupportsLoginPty(driver, input.workerManager.getWorker(plugin.id)?.supportedMethods ?? [], true)) throw new Error();
const result = await input.workerManager.call(plugin.id, "loginPtyReadCredential", {
driverKey: metadata.driverKey, companyId: input.lease.companyId, environmentId: input.environment.id,
providerLeaseId: input.lease.providerLeaseId, loginCommandKey: "codex",
providerLeaseId: input.lease.providerLeaseId, loginCommandKey,
});
if (result?.kind !== "codex-auth-json" || typeof result.authJson !== "string" || !result.authJson.length || Buffer.byteLength(result.authJson) > MAX_LOGIN_CREDENTIAL_BYTES) throw new Error();
return Buffer.from(result.authJson, "utf8");
if (result?.kind !== "auth-file" || typeof result.content !== "string" || !result.content.length || Buffer.byteLength(result.content) > MAX_LOGIN_CREDENTIAL_BYTES) throw new Error();
return Buffer.from(result.content, "utf8");
} catch {
throw new Error("Login credential result unavailable");
}
@@ -24,7 +24,9 @@ export function pluginRunnerAiConnectionRequiredMessage(preconfiguredHome: boole
// The plugin's manifest declaration decides whether its environment runs
// Runner tasks. Run admission separately verifies a ready plugin and a live
// worker, so a plugin that is down still selects the Runner and fails its run.
export async function pluginEnvironmentRunnerTaskDriver(db: Db, environment: Parameters<typeof parseEnvironmentDriverConfig>[0]) {
export type PluginRunnerTaskWorkers = { getWorker(pluginId: string): { supportedMethods: readonly string[] } | undefined };
export async function pluginEnvironmentRunnerTaskDriver(db: Db, environment: Parameters<typeof parseEnvironmentDriverConfig>[0], workers?: PluginRunnerTaskWorkers) {
let config: { pluginKey: string; driverKey: string };
try {
const parsed = parseEnvironmentDriverConfig(environment);
@@ -35,8 +37,12 @@ export async function pluginEnvironmentRunnerTaskDriver(db: Db, environment: Par
}
const { pluginRegistryService } = await import("./plugin-registry.js");
const plugin = await pluginRegistryService(db).getByKey(config.pluginKey);
return plugin?.manifestJson.capabilities.includes("environment.drivers.register")
const driver = plugin?.manifestJson.capabilities.includes("environment.drivers.register")
? plugin.manifestJson.environmentDrivers?.find(driver => driver.driverKey === config.driverKey && driver.supportsTasks === true) : undefined;
const methods = driver?.supportedAdapters && plugin ? workers?.getWorker(plugin.id)?.supportedMethods : undefined;
if (!driver || !methods) return driver;
const { pluginDriverSupportedAdapters } = await import("./plugin-environment-driver.js");
return { ...driver, supportedAdapters: pluginDriverSupportedAdapters(driver, methods) };
}
/** The setup probe result for a plugin Runner-task target without a managed AI connection. */
@@ -1,11 +1,12 @@
import { and, eq, sql } from "drizzle-orm";
import { environmentLeases, type Db } from "@paperclipai/db";
import { z, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk";
import { ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS, z, type PluginEnvironmentTaskAuthFileProvider, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk";
import { isDeepStrictEqual } from "node:util";
import { managedAiCredentialWritebackBindingSchema, syncManagedAiCredentials, syncManagedAntigravityCredential, type ManagedAiCredentialWritebackBinding } from "./managed-ai-credential-writeback.js";
const handoffSchema = z.object({
accountIdentity: z.string().min(1),
provider: z.enum(ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS).optional(),
binding: managedAiCredentialWritebackBindingSchema,
state: z.enum(["pending", "complete"]),
outcome: z.enum(["rotated", "unchanged", "binding_changed", "not_dispatched", "no_credentials", "account_refused"]).optional(),
@@ -25,8 +26,9 @@ export async function registerPluginTaskCredentialHandoff(
scope: Scope,
accountIdentity: string,
binding: ManagedAiCredentialWritebackBinding,
provider: PluginEnvironmentTaskAuthFileProvider = "codex",
) {
const handoff = handoffSchema.parse({ accountIdentity, binding, state: "pending" });
const handoff = handoffSchema.parse({ accountIdentity, binding, state: "pending", ...(provider === "codex" ? {} : { provider }) });
await db.transaction(async tx => {
const [lease] = await tx.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, scope.companyId), eq(environmentLeases.id, scope.leaseId),
@@ -38,7 +40,8 @@ export async function registerPluginTaskCredentialHandoff(
const saved = lease.metadata[key];
if (saved) {
const prior = handoffSchema.parse(saved);
if (prior.accountIdentity !== accountIdentity || !isDeepStrictEqual(prior.binding, handoff.binding)) {
if (prior.accountIdentity !== accountIdentity || !isDeepStrictEqual(prior.binding, handoff.binding) ||
(prior.provider ?? "codex") !== provider) {
throw new Error("Plugin task credential authority changed");
}
return;
@@ -81,11 +84,12 @@ async function writeBackCredentials(
if (!value) throw new Error("Plugin task credential provider mismatch");
return value;
});
return syncManagedAiCredentials(db, companyId, handoff.binding, "codex", async () => {
const provider = handoff.provider ?? "codex";
return syncManagedAiCredentials(db, companyId, handoff.binding, provider, async () => {
const credential = await fetchCredential(handoff.accountIdentity);
if (credential === null) return null;
if (credential.type !== "codex-auth-json") throw new Error("Plugin task credential provider mismatch");
return credential.authJson;
if (credential.type !== "auth-file" || credential.provider !== provider) throw new Error("Plugin task credential provider mismatch");
return credential.content;
});
}