From ab099dc3790c366b6db970f4742b3af9c6b08141 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Tue, 1 Dec 2026 08:13:39 -0800 Subject: [PATCH] feat(plugin-sdk): declare supported adapters per environment driver (#22827) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 Co-authored-by: Paperclip --- doc/connections/AI-CONNECTIONS.md | 3 +- doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md | 33 ++++++++-- docs/api/agents.md | 19 ++++++ packages/plugins/sdk/README.md | 27 +++++++- packages/plugins/sdk/src/environment-tasks.ts | 5 +- packages/plugins/sdk/src/index.ts | 4 +- packages/plugins/sdk/src/protocol.ts | 8 +-- .../environment-task-release-resume.test.ts | 6 +- .../plugins/sdk/tests/worker-rpc-host.test.ts | 4 +- packages/shared/src/adapter-login.ts | 27 ++++++++ .../shared/src/environment-support.test.ts | 18 +++-- packages/shared/src/environment-support.ts | 15 +---- packages/shared/src/index.ts | 11 +++- packages/shared/src/types/plugin.ts | 1 + packages/shared/src/validators/plugin.test.ts | 23 +++++++ packages/shared/src/validators/plugin.ts | 19 ++++++ server/src/__tests__/adapter-routes.test.ts | 10 +++ ...t-adapter-validation-runner-routes.test.ts | 26 ++++++++ ...y-plugin-task-credential-writeback.test.ts | 2 +- .../environment-task-runtime.test.ts | 44 ++++++++++++- .../__tests__/login-session-runtime.test.ts | 4 +- ...onment-driver-sandbox-capabilities.test.ts | 48 +++++++++++++- .../plugin-runner-task.integration.test.ts | 4 +- .../plugin-task-credential-writeback.test.ts | 17 +++-- server/src/app.ts | 2 +- server/src/routes/adapters.ts | 3 + server/src/routes/agents.ts | 54 +++++++++------ server/src/routes/environments.ts | 5 +- server/src/services/agent-environment-test.ts | 3 +- .../services/agent-runner-selection.test.ts | 59 ++++++++++++++++- server/src/services/agent-runner-selection.ts | 66 ++++++++++++++++--- server/src/services/device-login-service.ts | 4 +- .../src/services/environment-task-runtime.ts | 20 ++++-- server/src/services/login-command.ts | 29 ++++---- server/src/services/login-environment.test.ts | 3 +- server/src/services/login-environment.ts | 4 +- .../native-session-executor.test.ts | 2 +- .../native-runtime/native-session-executor.ts | 5 +- .../plugin-runner-credentials.test.ts | 23 +++++-- .../plugin-runner-credentials.ts | 21 ++++-- .../plugin-runner-probe.test.ts | 4 +- .../native-runtime/plugin-runner-task.test.ts | 6 +- .../src/services/plugin-environment-driver.ts | 46 ++++++++++++- .../services/plugin-login-credential.test.ts | 14 +++- .../src/services/plugin-login-credential.ts | 12 ++-- .../services/plugin-runner-ai-connection.ts | 10 ++- .../plugin-task-credential-writeback.ts | 16 +++-- .../runner-e2e/source-sdk-public-inputs.json | 19 +++--- ui/src/api/adapters.ts | 1 + .../AiConnectionCredentialStep.tsx | 8 ++- .../new-agent/AgentBasicsDialog.tsx | 7 +- 51 files changed, 655 insertions(+), 169 deletions(-) create mode 100644 packages/shared/src/adapter-login.ts diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md index 7e87a566189..d2ddf557869 100644 --- a/doc/connections/AI-CONNECTIONS.md +++ b/doc/connections/AI-CONNECTIONS.md @@ -4,7 +4,8 @@ AI accounts use the existing Apps/Connections substrate. Manage them at `/:company/apps`; select their use beside an agent's harness/model settings. Onboarding, new-agent setup, account creation/reconnect, and inline task requests reuse `AdapterLoginPanel`, its existing login controllers, and `AdapterLoginChrome`. -For Codex and Claude subscriptions on an agent computer, Connections selects an +For a subscription on an agent computer (Claude, Codex or Grok, when the +computer's driver supports that adapter), Connections selects an eligible computer in the chosen company and sign-in environment when the user starts sign-in. The session keeps that computer until it ends. Connection ownership and permissions still come from the account setup. diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index fa265db1d43..f8cee7970c0 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -75,10 +75,16 @@ The `credential` field has one of these types: | `type` | Contents | Harness | | --- | --- | --- | -| `codex-auth-json` | `authJson`: the selected Codex `auth.json` | `codex` | +| `auth-file` | `provider` and `content`: the provider's saved sign-in file, as written | `codex` or `grok` | | `claude-env` | `environment`: exactly one of `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` | `claude` | | `provider-env` | `provider` and `environment`: one complete variable set for that provider | `grok`, `copilot`, `opencode` or `antigravity` | +An `auth-file` credential is the `auth.json` that the provider's sign-in saved: +a Codex subscription or API-key account, or a Grok subscription. Install it as +written in the provider's home. When the provider refreshes it, the `credentials` +operation returns the refreshed copy in the same form, and Core saves it to the +account. `ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS` exports the provider list. + A `provider-env` credential contains exactly one of these variable sets and no other variable: @@ -108,8 +114,6 @@ The Runner refuses a Copilot token or a Gemini API key without a matching binding. For `antigravity`, the Runner also removes every other `GOOGLE_*` and `GEMINI_*` variable before it starts the provider, so a configured variable cannot redirect the key. -Core does not send a Grok subscription login. A Grok agent must use an xAI API -key in a plugin environment. For a Google Antigravity agent bound to a Google sign-in, the `antigravity` credential carries `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. @@ -618,6 +622,22 @@ before publishing it. Deliverables additionally verify the caller's expected size and digest. Providers without this operation fail closed; Core never falls back to reading remote paths on the server. Existing artifact uploads are unchanged. +## Supported adapters + +A task driver (`kind: "environment_driver"` with `supportsTasks: true`) lists +the adapters it runs in `supportedAdapters`. Support is all or nothing: a listed +adapter that has a Paperclip sign-in (Claude, Codex and Grok today) must also be +signed in on the driver, so the manifest must declare `supportsLoginPty` and +`creationOperationVersion: 1`. Core checks the running worker for every method +each listed adapter needs: `environmentTask`, `environmentAcquireLease` and +`environmentReleaseLease` for every adapter, the login methods for a sign-in, +and `loginPtyReadCredential` for a sign-in that saves a file. It removes an +adapter whose methods are missing and logs it. Core refuses to save an agent +whose harness the environment's driver does not list, and the adapter list shows +that harness as unavailable there. A driver without `supportedAdapters` keeps +the earlier behavior: every Runner harness, Claude sign-in, and Codex sign-in +when the worker reads credentials back. + ## Login allocations on an existing computer A login-capable environment driver can host authorization on a saved agent's @@ -643,7 +663,8 @@ Inspection by `creationOperation` must return that exact allocation as `creationLease`, with its provider ID matching the observation envelope, so a lost acquisition reply still reaches the existing cleanup path. -Claude uses the existing setup-token output parser. Codex uses the optional -`loginPtyReadCredential` hook to read its fixed auth artifact. Both retain the -existing owner-bound credential completion and durable cleanup. A restart +Claude uses the existing setup-token output parser. Codex and Grok save an +`auth.json`, which Core reads with `loginPtyReadCredential` using the +allocation's command key; the result is `{ kind: "auth-file", content }`. All +three retain the existing owner-bound credential completion and durable cleanup. A restart interrupts an unfinished login; it does not resume the terminal. diff --git a/docs/api/agents.md b/docs/api/agents.md index f9fc9e62160..8a4f7f99a0d 100644 --- a/docs/api/agents.md +++ b/docs/api/agents.md @@ -103,6 +103,25 @@ check `adapterConfig.env` against them: `protected_environment_variable`, a `field` such as `adapterConfig.env.KEY`, and a `message` that names those environments. +### Harnesses a Runner environment supports + +A plugin environment driver that runs Paperclip Runner tasks can declare +`supportedAdapters`: the harnesses its tasks can run. Create, hire, update and +configuration rollback check a `paperclip_runner` agent's harness against that +list, using the agent's environment (its `defaultEnvironmentId`, or the +instance default when it has none): + +- A harness outside the list fails with `422` and code + `agent_runner_unavailable`. The response details name the `harness`, such as + `codex_local` or `copilot_runtime`. +- A driver that declares no list accepts every harness. +- Cursor Cloud agents, and instances in Kubernetes execution mode, are not + checked: their runs do not use the agent's environment. + +`GET /api/adapters?companyId={companyId}&environmentId={environmentId}` +reports the list on the `paperclip_runner` entry as `supportedAdapters`, and +adapters outside it as having no supported runners. + ## Pause Agent ``` diff --git a/packages/plugins/sdk/README.md b/packages/plugins/sdk/README.md index cfc510726f1..972707c1945 100644 --- a/packages/plugins/sdk/README.md +++ b/packages/plugins/sdk/README.md @@ -1607,6 +1607,25 @@ existing permissions. This capability is for trusted execution infrastructure, not agent-facing tools or UI. Never expose or persist it. See [GitHub identity](../../../doc/execution-github-identity.md#project-authorization-for-background-repository-work). +## Supported adapters + +A Runner task driver (`kind: "environment_driver"` with `supportsTasks: true`) +declares the adapters it runs in `supportedAdapters`, for example +`["claude_local", "codex_local", "grok_local"]`. Support is all or nothing. +Listing an adapter means the driver runs it, with the `onEnvironmentTask`, +`onEnvironmentAcquireLease` and `onEnvironmentReleaseLease` hooks, and, when +Paperclip has a sign-in for that adapter, hosts the whole sign-in: the login PTY +hooks, plus `onLoginPtyReadCredential` when the sign-in saves a credential file +(Codex and Grok today). The manifest is rejected when it lists such an adapter +without `supportsLoginPty` and `creationOperationVersion: 1`. When the running +worker lacks a method an adapter needs, Core removes that adapter from the +driver and logs it; it never offers the adapter's runs without its sign-in. +Core refuses to save or run an unlisted adapter on the driver. + +A driver that omits `supportedAdapters` keeps the earlier behavior: any Runner +harness, Claude sign-in, and Codex sign-in when the worker reads credentials +back. + ## Login on an existing computer A driver can use the existing login PTY hooks for a login on a saved agent's @@ -1622,9 +1641,11 @@ A provider that retries delivery must retain the input identity and bytes, and reject reuse of the identity with different input. A failed input call ends the Core login; Core does not silently replay an unconfirmed write. -Providers can implement `onLoginPtyReadCredential` to export the fixed Codex -credential artifact for a bound login lease. The result is -`{ kind: "codex-auth-json", authJson }`; the request accepts no path or command. +Providers implement `onLoginPtyReadCredential` to export the credential file +that a completed sign-in saved in a bound login lease. Core calls it with the +lease's `loginCommandKey` for sign-ins that save a file. The result is +`{ kind: "auth-file", content }`, the provider's file as written; the request +accepts no path or command. The worker advertises this optional method only when the hook exists. The host must check that method before using this read path, enforce a size limit, and keep credential bytes out of logs and public session responses. Existing sandbox diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index ebdf0950379..d8ff7e00e98 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -76,9 +76,12 @@ const providerCredential = z.object({ } }); +export const ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS = ["codex", "grok"] as const; +export type PluginEnvironmentTaskAuthFileProvider = typeof ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS[number]; + /** Only provider authentication is transferred. Paths and executable settings remain provider-owned. */ export const environmentTaskCredentialSchema = z.discriminatedUnion("type", [ - z.object({ type: z.literal("codex-auth-json"), authJson: credentialValue }).strict(), + z.object({ type: z.literal("auth-file"), provider: z.enum(ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS), content: credentialValue }).strict(), z.object({ type: z.literal("claude-env"), environment: claudeCredentialEnvironment }).strict(), providerCredential, ]); diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.ts index 686c87d177f..3d57b26092e 100644 --- a/packages/plugins/sdk/src/index.ts +++ b/packages/plugins/sdk/src/index.ts @@ -498,8 +498,8 @@ export type { PluginEnvironmentTaskErrorDiagnostic } from "./environment-task-er export type { AiConnectionPool, AiConnectionPoolConfig, AiConnectionPoolMember, AiConnectionRouterRequest, AiConnectionRouterResult, AiConnectionRouterSelection } from "@paperclipai/shared"; -export { MAX_ENVIRONMENT_TASK_FILE_BYTES, ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS, environmentRunnerLaunchRequirementsSchema, environmentTaskOperationSchema, environmentTaskResultSchema, environmentTaskCredentialSchema, environmentTaskConfiguredEnvironmentSchema, MAX_CONFIGURED_ENVIRONMENT_KEYS, MAX_CONFIGURED_ENVIRONMENT_ENTRY_BYTES, MAX_CONFIGURED_ENVIRONMENT_BYTES, parseEnvironmentTaskResult } from "./environment-tasks.js"; -export type { PluginEnvironmentTaskOperation, PluginEnvironmentTaskParams, PluginEnvironmentTaskResult, PluginEnvironmentTaskCredential, PluginEnvironmentTaskCredentialProvider, PluginEnvironmentTaskConfiguredEnvironment, PluginEnvironmentTaskExecutionContext } from "./environment-tasks.js"; +export { MAX_ENVIRONMENT_TASK_FILE_BYTES, ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS, ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS, environmentRunnerLaunchRequirementsSchema, environmentTaskOperationSchema, environmentTaskResultSchema, environmentTaskCredentialSchema, environmentTaskConfiguredEnvironmentSchema, MAX_CONFIGURED_ENVIRONMENT_KEYS, MAX_CONFIGURED_ENVIRONMENT_ENTRY_BYTES, MAX_CONFIGURED_ENVIRONMENT_BYTES, parseEnvironmentTaskResult } from "./environment-tasks.js"; +export type { PluginEnvironmentTaskOperation, PluginEnvironmentTaskParams, PluginEnvironmentTaskResult, PluginEnvironmentTaskCredential, PluginEnvironmentTaskAuthFileProvider, PluginEnvironmentTaskCredentialProvider, PluginEnvironmentTaskConfiguredEnvironment, PluginEnvironmentTaskExecutionContext } from "./environment-tasks.js"; export type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared"; export type { PluginEnvironmentRunnerLaunchRequirements, PluginEnvironmentPreparedLaunch } from "./environment-tasks.js"; diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.ts index a540b56dee3..a61de4d6501 100644 --- a/packages/plugins/sdk/src/protocol.ts +++ b/packages/plugins/sdk/src/protocol.ts @@ -1164,18 +1164,18 @@ export interface PluginLoginPtyInputParams { data: string; } -/** Read the fixed Codex result of a bound login allocation; never an arbitrary path. */ +/** Read the fixed result of a bound login allocation; never an arbitrary path. */ export interface PluginLoginPtyReadCredentialParams { driverKey: string; companyId: string; environmentId: string; providerLeaseId: string; - loginCommandKey: "codex"; + loginCommandKey: PluginLoginCommandKey; } export interface PluginLoginPtyReadCredentialResult { - kind: "codex-auth-json"; - authJson: string; + kind: "auth-file"; + content: string; } /** The stop request. It carries the worker session identifier. */ diff --git a/packages/plugins/sdk/tests/environment-task-release-resume.test.ts b/packages/plugins/sdk/tests/environment-task-release-resume.test.ts index 5f8b4610b1b..7dd69989a40 100644 --- a/packages/plugins/sdk/tests/environment-task-release-resume.test.ts +++ b/packages/plugins/sdk/tests/environment-task-release-resume.test.ts @@ -27,15 +27,15 @@ const submit = { kind: "submit", projectIds: [], bootstrapTicket: "fixture-ticke const credentials: [string, unknown, boolean][] = [ ["a Claude OAuth token", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-oauth" } }, true], ["a Claude API key", { type: "claude-env", environment: { ANTHROPIC_API_KEY: "fixture-key" } }, true], - ["a Codex auth file", { type: "codex-auth-json", authJson: "{\"tokens\":{}}" }, true], + ["a Codex auth file", { type: "auth-file", provider: "codex", content: "{\"tokens\":{}}" }, true], ["two Claude credentials", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "a", ANTHROPIC_API_KEY: "b" } }, false], ["no Claude credential", { type: "claude-env", environment: {} }, false], ["an unsupported Claude variable", { type: "claude-env", environment: { ANTHROPIC_BASE_URL: "https://example.test" } }, false], ["an empty value", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "" } }, false], ["a NUL byte", { type: "claude-env", environment: { CLAUDE_CODE_OAUTH_TOKEN: "a\0b" } }, false], - ["an oversized value", { type: "codex-auth-json", authJson: "x".repeat(65_537) }, false], + ["an oversized value", { type: "auth-file", provider: "codex", content: "x".repeat(65_537) }, false], ["an unknown type", { type: "gemini-env", environment: { GEMINI_API_KEY: "fixture" } }, false], - ["an extra field", { type: "codex-auth-json", authJson: "{}", path: "/home/agent/.codex" }, false], + ["an extra field", { type: "auth-file", provider: "codex", content: "{}", path: "/home/agent/.codex" }, false], ["an xAI API key for Grok", { type: "provider-env", provider: "grok", environment: { XAI_API_KEY: "fixture-xai" } }, true], ["a Copilot token", { type: "provider-env", provider: "copilot", environment: { COPILOT_GITHUB_TOKEN: "fixture-copilot" } }, true], ["an OpenRouter key for OpenCode", { type: "provider-env", provider: "opencode", environment: { OPENROUTER_API_KEY: "fixture-openrouter" } }, true], diff --git a/packages/plugins/sdk/tests/worker-rpc-host.test.ts b/packages/plugins/sdk/tests/worker-rpc-host.test.ts index 77545c1159f..6be6b855239 100644 --- a/packages/plugins/sdk/tests/worker-rpc-host.test.ts +++ b/packages/plugins/sdk/tests/worker-rpc-host.test.ts @@ -409,13 +409,13 @@ describe("worker configChanged cross-tenant guard", () => { async setup() {}, ...(supported ? { async onLoginPtyReadCredential(input: typeof params) { expect(input).toEqual(params); - return { kind: "codex-auth-json" as const, authJson: '{"fixture":true}' }; + return { kind: "auth-file" as const, content: '{"fixture":true}' }; } } : {}), })); try { const initialized = await worker.initialize() as { supportedMethods: string[] }; expect(initialized.supportedMethods.includes("loginPtyReadCredential")).toBe(supported); - if (supported) expect(await worker.callWorker("loginPtyReadCredential", params)).toEqual({ kind: "codex-auth-json", authJson: '{"fixture":true}' }); + if (supported) expect(await worker.callWorker("loginPtyReadCredential", params)).toEqual({ kind: "auth-file", content: '{"fixture":true}' }); else await expect(worker.callWorker("loginPtyReadCredential", params)).rejects.toMatchObject({ code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED }); } finally { worker.stop(); } }); diff --git a/packages/shared/src/adapter-login.ts b/packages/shared/src/adapter-login.ts new file mode 100644 index 00000000000..312186ee1d5 --- /dev/null +++ b/packages/shared/src/adapter-login.ts @@ -0,0 +1,27 @@ +export type AdapterLoginCommandKey = "claude" | "codex" | "grok"; + +const LOGIN_COMMAND_KEY_BY_ADAPTER_TYPE: Readonly> = { + claude_local: "claude", + codex_local: "codex", + grok_local: "grok", +}; + +export const ADAPTER_LOGIN_CREDENTIAL_SOURCE: Readonly> = { + claude: "terminal", + codex: "file", + grok: "file", +}; + +export function adapterLoginCommandKey(adapterType: string): AdapterLoginCommandKey | undefined { + return Object.hasOwn(LOGIN_COMMAND_KEY_BY_ADAPTER_TYPE, adapterType) + ? LOGIN_COMMAND_KEY_BY_ADAPTER_TYPE[adapterType] + : undefined; +} + +export function isAdapterLoginCommandKey(value: unknown): value is AdapterLoginCommandKey { + return typeof value === "string" && Object.hasOwn(ADAPTER_LOGIN_CREDENTIAL_SOURCE, value); +} + +export function adapterLoginTypes(): string[] { + return Object.keys(LOGIN_COMMAND_KEY_BY_ADAPTER_TYPE).sort(); +} diff --git a/packages/shared/src/environment-support.test.ts b/packages/shared/src/environment-support.test.ts index d082845e808..91a7aacce30 100644 --- a/packages/shared/src/environment-support.test.ts +++ b/packages/shared/src/environment-support.test.ts @@ -103,15 +103,19 @@ describe("getEnvironmentCapabilities reusable leases default", () => { describe("environment login PTY support", () => { - it("uses the declared driver of the selected environment", async () => { + it("offers a plugin sign-in only for the adapters its running driver hosts", async () => { const { environmentSupportsLoginPty } = await import("./environment-support.js"); - const capabilities = { ...getEnvironmentCapabilities(["codex_local"]), loginPtyDrivers: { "fixture:computer": { supportsLoginPty: true } } }; - expect(environmentSupportsLoginPty({ driver: "plugin", config: { pluginKey: "fixture", driverKey: "computer" } }, capabilities)).toBe(true); + const computer = { driver: "plugin", config: { pluginKey: "fixture", driverKey: "computer" } }; + const capabilities = { ...getEnvironmentCapabilities(["codex_local"]), + loginPtyDrivers: { "fixture:computer": { supportsLoginPty: true, loginAdapters: ["claude_local", "grok_local"] } } }; + expect(environmentSupportsLoginPty(computer, capabilities)).toBe(true); expect(environmentSupportsLoginPty({ driver: "plugin", config: { pluginKey: "other", driverKey: "computer" } }, capabilities)).toBe(false); expect(environmentSupportsLoginPty({ driver: "local", config: {} }, capabilities)).toBe(false); - expect(environmentSupportsLoginPty({ driver: "plugin", config: { pluginKey: "fixture", driverKey: "computer" } }, capabilities, "grok_local")).toBe(false); - expect(environmentSupportsLoginPty({ driver: "plugin", config: { pluginKey: "fixture", driverKey: "computer" } }, capabilities, "codex_local")).toBe(false); - expect(environmentSupportsLoginPty({ driver: "plugin", config: { pluginKey: "fixture", driverKey: "computer" } }, { ...capabilities, loginPtyDrivers: { "fixture:computer": { supportsLoginPty: true, supportsCodexLogin: true } } }, "codex_local")).toBe(true); - expect(environmentSupportsLoginPty({ driver: "plugin", config: { pluginKey: "fixture", driverKey: "computer" } }, capabilities, "claude_local")).toBe(true); + expect(environmentSupportsLoginPty(computer, capabilities, "grok_local")).toBe(true); + expect(environmentSupportsLoginPty(computer, capabilities, "claude_local")).toBe(true); + expect(environmentSupportsLoginPty(computer, capabilities, "codex_local")).toBe(false); + const none = { ...capabilities, loginPtyDrivers: { "fixture:computer": { supportsLoginPty: true, loginAdapters: [] } } }; + expect(environmentSupportsLoginPty(computer, none)).toBe(false); + expect(environmentSupportsLoginPty(computer, none, "claude_local")).toBe(false); }); }); diff --git a/packages/shared/src/environment-support.ts b/packages/shared/src/environment-support.ts index a7658dfe116..261c02dccfb 100644 --- a/packages/shared/src/environment-support.ts +++ b/packages/shared/src/environment-support.ts @@ -60,7 +60,7 @@ export interface EnvironmentProviderCapability { export interface EnvironmentCapabilities { /** Namespaced plugin driver keys that can host a login on a saved agent. */ - loginPtyDrivers?: Record; + loginPtyDrivers?: Record; adapters: AdapterEnvironmentSupport[]; drivers: Record; sandboxProviders: Record; @@ -203,16 +203,6 @@ export function getEnvironmentCapabilities( }; } -export const PLUGIN_ENVIRONMENT_LOGIN_ADAPTER_TYPES = ["claude_local", "codex_local"] as const; - -export function isPluginEnvironmentLoginAdapter(adapterType: string): boolean { - return (PLUGIN_ENVIRONMENT_LOGIN_ADAPTER_TYPES as readonly string[]).includes(adapterType); -} - -export function pluginEnvironmentLoginReadsCredential(adapterType: string): boolean { - return adapterType === "codex_local"; -} - export function environmentLoginRequiresAgent(environment: { driver: string } | null | undefined): boolean { return environment?.driver === "plugin"; } @@ -224,8 +214,7 @@ export function environmentSupportsLoginPty(environment: { driver: string; confi if (environmentLoginRequiresAgent(environment)) { const driver = capabilities.loginPtyDrivers?.[`${environment.config.pluginKey}:${environment.config.driverKey}`]; return driver?.supportsLoginPty === true - && (adapterType === undefined || (isPluginEnvironmentLoginAdapter(adapterType) - && (!pluginEnvironmentLoginReadsCredential(adapterType) || driver.supportsCodexLogin === true))); + && (adapterType === undefined ? driver.loginAdapters.length > 0 : driver.loginAdapters.includes(adapterType)); } return false; } diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index dbdd64c5df8..98149289a57 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2856,9 +2856,6 @@ export { getEnvironmentCapabilities, environmentSupportsLoginPty, environmentLoginRequiresAgent, - isPluginEnvironmentLoginAdapter, - pluginEnvironmentLoginReadsCredential, - PLUGIN_ENVIRONMENT_LOGIN_ADAPTER_TYPES, getAdapterEnvironmentSupport, isEnvironmentDriverSupportedForAdapter, isSandboxProviderSupportedForAdapter, @@ -2867,6 +2864,14 @@ export { supportedSandboxProvidersForAdapter, } from "./environment-support.js"; +export { + ADAPTER_LOGIN_CREDENTIAL_SOURCE, + adapterLoginCommandKey, + adapterLoginTypes, + isAdapterLoginCommandKey, +} from "./adapter-login.js"; +export type { AdapterLoginCommandKey } from "./adapter-login.js"; + export type { AdapterEnvironmentSupport, EnvironmentCapabilities, diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts index af85e6aa845..99567f30af5 100644 --- a/packages/shared/src/types/plugin.ts +++ b/packages/shared/src/types/plugin.ts @@ -197,6 +197,7 @@ export interface PluginEnvironmentDriverDeclaration { requiresAgent?: boolean; /** Provides Runner execution, resource preparation, and PRP connections via environmentTask. */ supportsTasks?: boolean; + supportedAdapters?: string[]; freshWorkspaceVersion?: 1; creationOperationVersion?: 1; /** Codex task retention and authorized run attachment, version 1. */ diff --git a/packages/shared/src/validators/plugin.test.ts b/packages/shared/src/validators/plugin.test.ts index 467df457aa1..0a028e978f6 100644 --- a/packages/shared/src/validators/plugin.test.ts +++ b/packages/shared/src/validators/plugin.test.ts @@ -569,3 +569,26 @@ describe("agent environment slot requirements", () => { expect(pluginUiSlotDeclarationSchema.safeParse({ ...slot, ...patch }).success).toBe(false); }); }); + +describe("supported adapters", () => { + const taskDriver = { kind: "environment_driver", supportsTasks: true, supportsLoginPty: true, creationOperationVersion: 1 }; + it("accepts a task driver that hosts the sign-in of every listed adapter", () => { + const parsed = pluginManifestV1Schema.parse(buildSandboxProviderManifest({ ...taskDriver, + supportedAdapters: ["claude_local", "codex_local", "grok_local", "copilot_runtime", "opencode_local"] })); + expect(parsed.environmentDrivers?.[0]?.supportedAdapters).toEqual(["claude_local", "codex_local", "grok_local", "copilot_runtime", "opencode_local"]); + }); + it("rejects an adapter with a Paperclip sign-in on a driver that cannot host it", () => { + for (const driver of [{ ...taskDriver, supportsLoginPty: false }, { ...taskDriver, creationOperationVersion: undefined }]) { + expect(pluginManifestV1Schema.safeParse(buildSandboxProviderManifest({ ...driver, supportedAdapters: ["grok_local"] })).success).toBe(false); + } + expect(pluginManifestV1Schema.safeParse(buildSandboxProviderManifest({ ...taskDriver, supportsLoginPty: false, + supportedAdapters: ["copilot_runtime", "opencode_local"] })).success).toBe(true); + }); + it("rejects the list outside a Runner task environment driver, and duplicates", () => { + for (const kind of ["sandbox_provider", undefined]) { + expect(pluginManifestV1Schema.safeParse(buildSandboxProviderManifest({ ...taskDriver, kind, supportedAdapters: ["copilot_runtime"] })).success).toBe(false); + } + expect(pluginManifestV1Schema.safeParse(buildSandboxProviderManifest({ ...taskDriver, supportsTasks: false, supportedAdapters: ["copilot_runtime"] })).success).toBe(false); + expect(pluginManifestV1Schema.safeParse(buildSandboxProviderManifest({ ...taskDriver, supportedAdapters: ["claude_local", "claude_local"] })).success).toBe(false); + }); +}); diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.ts index baa064f9530..072f0e6e3b7 100644 --- a/packages/shared/src/validators/plugin.ts +++ b/packages/shared/src/validators/plugin.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { adapterLoginCommandKey } from "../adapter-login.js"; import { PLUGIN_STATUSES, PLUGIN_CATEGORIES, @@ -168,6 +169,7 @@ export const pluginEnvironmentDriverDeclarationSchema = z.object({ skillKeys: z.array(z.string().min(1).max(100)).max(100).optional(), requiresAgent: z.boolean().optional(), supportsTasks: z.boolean().optional(), + supportedAdapters: z.array(z.string().regex(/^[a-z0-9][a-z0-9_:-]{0,63}$/)).max(64).optional(), freshWorkspaceVersion: z.literal(1).optional(), creationOperationVersion: z.literal(1).optional(), warmTaskVersion: z.literal(1).optional(), @@ -200,6 +202,23 @@ export const pluginEnvironmentDriverDeclarationSchema = z.object({ supportsSetupTokenLogin: z.boolean().optional(), configSchema: jsonSchemaSchema, }).strict().superRefine((driver, ctx) => { + if (driver.supportedAdapters) { + const adapters = driver.supportedAdapters; + if (new Set(adapters).size !== adapters.length) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Supported adapters must be unique", path: ["supportedAdapters"] }); + } + if (driver.kind !== "environment_driver" || driver.supportsTasks !== true) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Only a Runner task environment driver declares supported adapters", path: ["supportedAdapters"] }); + } + const signIns = adapters.filter((adapter) => adapterLoginCommandKey(adapter) !== undefined); + if (signIns.length > 0 && ((driver.supportsLoginPty ?? driver.supportsSetupTokenLogin) !== true || driver.creationOperationVersion !== 1)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `Supported adapters with a Paperclip sign-in (${signIns.join(", ")}) require supportsLoginPty and creationOperationVersion 1`, + path: ["supportedAdapters"], + }); + } + } // Reject a manifest that carries both the alias and the canonical field with // different values. Matching values pass. A single field passes. if ( diff --git a/server/src/__tests__/adapter-routes.test.ts b/server/src/__tests__/adapter-routes.test.ts index f85b660e20e..5710f11e619 100644 --- a/server/src/__tests__/adapter-routes.test.ts +++ b/server/src/__tests__/adapter-routes.test.ts @@ -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"); }); diff --git a/server/src/__tests__/agent-adapter-validation-runner-routes.test.ts b/server/src/__tests__/agent-adapter-validation-runner-routes.test.ts index de85212c69a..c10a4ae429b 100644 --- a/server/src/__tests__/agent-adapter-validation-runner-routes.test.ts +++ b/server/src/__tests__/agent-adapter-validation-runner-routes.test.ts @@ -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), env: { DESKTOP_SESSION: { type: "plain", value: "mine" } } }; diff --git a/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts b/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts index 9c59b806358..32b9104bcb8 100644 --- a/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts +++ b/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts @@ -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) => { diff --git a/server/src/__tests__/environment-task-runtime.test.ts b/server/src/__tests__/environment-task-runtime.test.ts index 26234253815..7a2bc80550c 100644 --- a/server/src/__tests__/environment-task-runtime.test.ts +++ b/server/src/__tests__/environment-task-runtime.test.ts @@ -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, 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")); diff --git a/server/src/__tests__/login-session-runtime.test.ts b/server/src/__tests__/login-session-runtime.test.ts index c5069d1ba2d..a8c6a528928 100644 --- a/server/src/__tests__/login-session-runtime.test.ts +++ b/server/src/__tests__/login-session-runtime.test.ts @@ -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"); diff --git a/server/src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts b/server/src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts index 3d531f03c90..74adf3dc299 100644 --- a/server/src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts +++ b/server/src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts @@ -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"]); + }); +}); diff --git a/server/src/__tests__/plugin-runner-task.integration.test.ts b/server/src/__tests__/plugin-runner-task.integration.test.ts index 403eba17f2e..515af4b21d4 100644 --- a/server/src/__tests__/plugin-runner-task.integration.test.ts +++ b/server/src/__tests__/plugin-runner-task.integration.test.ts @@ -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 }, diff --git a/server/src/__tests__/plugin-task-credential-writeback.test.ts b/server/src/__tests__/plugin-task-credential-writeback.test.ts index 936ef101f31..32b2fda0de4 100644 --- a/server/src/__tests__/plugin-task-credential-writeback.test.ts +++ b/server/src/__tests__/plugin-task-credential-writeback.test.ts @@ -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)); diff --git a/server/src/app.ts b/server/src/app.ts index 722fc76fbde..65d75d45a99 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -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, diff --git a/server/src/routes/adapters.ts b/server/src/routes/adapters.ts index d5af45a560c..cb1936bc264 100644 --- a/server/src/routes/adapters.ts +++ b/server/src/routes/adapters.ts @@ -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, diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 59b34569f12..73b3981aae9 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -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 { + async function resolveProviderSupportsLoginPty(environmentId: string, adapterType: string): Promise { 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 { - if (!(await resolveProviderSupportsLoginPty(environmentId, "codex_local"))) { + async function assertDeviceLoginProviderCapability(environmentId: string, adapterType: string): Promise { + 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; @@ -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; 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))); } diff --git a/server/src/routes/environments.ts b/server/src/routes/environments.ts index b498e26d6a1..7f6239f5bba 100644 --- a/server/src/routes/environments.ts +++ b/server/src/routes/environments.ts @@ -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, + }, ])) }); }); diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.ts index 253d097401f..8ed39bdab9a 100644 --- a/server/src/services/agent-environment-test.ts +++ b/server/src/services/agent-environment-test.ts @@ -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 diff --git a/server/src/services/agent-runner-selection.test.ts b/server/src/services/agent-runner-selection.test.ts index 03b6a26ab03..603a93e453a 100644 --- a/server/src/services/agent-runner-selection.test.ts +++ b/server/src/services/agent-runner-selection.test.ts @@ -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" } }); diff --git a/server/src/services/agent-runner-selection.ts b/server/src/services/agent-runner-selection.ts index b9083160825..59e92167b41 100644 --- a/server/src/services/agent-runner-selection.ts +++ b/server/src/services/agent-runner-selection.ts @@ -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; 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 { +function assertRunnerTargetSupportsHarness(target: RunnerTarget, selected: { adapterType: string; adapterConfig: Record }) { + 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 { 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)) { diff --git a/server/src/services/device-login-service.ts b/server/src/services/device-login-service.ts index d0025f7bcce..401ca45af66 100644 --- a/server/src/services/device-login-service.ts +++ b/server/src/services/device-login-service.ts @@ -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; + assertProviderSupportsLoginPty: (environmentId: string, adapterType: string) => Promise; /** * 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, diff --git a/server/src/services/environment-task-runtime.ts b/server/src/services/environment-task-runtime.ts index 0d0616a13f4..825adbc1fba 100644 --- a/server/src/services/environment-task-runtime.ts +++ b/server/src/services/environment-task-runtime.ts @@ -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 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; @@ -442,6 +453,7 @@ export async function executeEnvironmentTask(db: Db, workers: Pick> = { - 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; } /** diff --git a/server/src/services/login-environment.test.ts b/server/src/services/login-environment.test.ts index b811e8f76df..a06b9642ca0 100644 --- a/server/src/services/login-environment.test.ts +++ b/server/src/services/login-environment.test.ts @@ -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 }); }); diff --git a/server/src/services/login-environment.ts b/server/src/services/login-environment.ts index 498e05cfaf7..adca2145812 100644 --- a/server/src/services/login-environment.ts +++ b/server/src/services/login-environment.ts @@ -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(); diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index d151823d415..6cfff3d624a 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -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});} }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 1d1b2aad0fd..0dd0ab70436 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -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 })); diff --git a/server/src/services/native-runtime/plugin-runner-credentials.test.ts b/server/src/services/native-runtime/plugin-runner-credentials.test.ts index 819229b7bd0..dccf6001724 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.test.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.test.ts @@ -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", diff --git a/server/src/services/native-runtime/plugin-runner-credentials.ts b/server/src/services/native-runtime/plugin-runner-credentials.ts index 13e5da840b7..d6b00a98085 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.ts @@ -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"); diff --git a/server/src/services/native-runtime/plugin-runner-probe.test.ts b/server/src/services/native-runtime/plugin-runner-probe.test.ts index 89551fa83bf..249553040a2 100644 --- a/server/src/services/native-runtime/plugin-runner-probe.test.ts +++ b/server/src/services/native-runtime/plugin-runner-probe.test.ts @@ -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); diff --git a/server/src/services/native-runtime/plugin-runner-task.test.ts b/server/src/services/native-runtime/plugin-runner-task.test.ts index 5102247bb69..ecca8fe3712 100644 --- a/server/src/services/native-runtime/plugin-runner-task.test.ts +++ b/server/src/services/native-runtime/plugin-runner-task.test.ts @@ -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"); } }); diff --git a/server/src/services/plugin-environment-driver.ts b/server/src/services/plugin-environment-driver.ts index 217235f09ad..644437bde3d 100644 --- a/server/src/services/plugin-environment-driver.ts +++ b/server/src/services/plugin-environment-driver.ts @@ -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; + +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(); +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): 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]), })), ); } diff --git a/server/src/services/plugin-login-credential.test.ts b/server/src/services/plugin-login-credential.test.ts index ca7d1057e12..38ff715f8eb 100644 --- a/server/src/services/plugin-login-credential.test.ts +++ b/server/src/services/plugin-login-credential.test.ts @@ -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(); }); }); diff --git a/server/src/services/plugin-login-credential.ts b/server/src/services/plugin-login-credential.ts index d47dbbcddea..258b94978b9 100644 --- a/server/src/services/plugin-login-credential.ts +++ b/server/src/services/plugin-login-credential.ts @@ -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 { 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"); } diff --git a/server/src/services/plugin-runner-ai-connection.ts b/server/src/services/plugin-runner-ai-connection.ts index 22202500dfb..7c001131f02 100644 --- a/server/src/services/plugin-runner-ai-connection.ts +++ b/server/src/services/plugin-runner-ai-connection.ts @@ -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[0]) { +export type PluginRunnerTaskWorkers = { getWorker(pluginId: string): { supportedMethods: readonly string[] } | undefined }; + +export async function pluginEnvironmentRunnerTaskDriver(db: Db, environment: Parameters[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. */ diff --git a/server/src/services/plugin-task-credential-writeback.ts b/server/src/services/plugin-task-credential-writeback.ts index 6cae4464f9d..941bafad4fd 100644 --- a/server/src/services/plugin-task-credential-writeback.ts +++ b/server/src/services/plugin-task-credential-writeback.ts @@ -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; }); } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index e0e3d9d5de1..7c0dc5a22fe 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -13,14 +13,14 @@ "packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb", "packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8", "packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4", - "packages/plugins/sdk/src/environment-tasks.ts": "ebdf0950379645dda416300acaa65718daf2795e", + "packages/plugins/sdk/src/environment-tasks.ts": "d8ff7e00e98c02e671fe60fb7f7eda887a34371b", "packages/plugins/sdk/src/host-client-factory.ts": "8f76d518b4b43a41436b516cb2929165611bd483", "packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a", "packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f", - "packages/plugins/sdk/src/index.ts": "686c87d177f180a05e4162dd762fd0447572956f", + "packages/plugins/sdk/src/index.ts": "3d57b26092ec8877d51c10a42764b582231af1eb", "packages/plugins/sdk/src/invocation-tracer.ts": "b28ac4aa4bc3e82658abac4a8081ed4508008696", "packages/plugins/sdk/src/protocol.duplex-channel.test.ts": "18255eb3d63038dc459240c111cbcb29fcba25cc", - "packages/plugins/sdk/src/protocol.ts": "a540b56dee310bfacc0d9100a795d12dfbc9396a", + "packages/plugins/sdk/src/protocol.ts": "a61de4d6501dcac9d3ecaae2d2ccabcafc899f09", "packages/plugins/sdk/src/testing.ts": "d40b4c1cada40a3a371085612774b64aa1b984a0", "packages/plugins/sdk/src/types.ts": "1391d1599de9da2c0a3e7c9cacaf1448cedf6dac", "packages/plugins/sdk/src/ui/clipboard.ts": "1f42069c97d731e636a6ad5481dad22d20c0ed63", @@ -42,6 +42,7 @@ "packages/shared/src/adapter-auth-check-code.test.ts": "5f466b2887051ce24ca92f2505ebf5d7cea3cd6c", "packages/shared/src/adapter-auth-check-code.ts": "a8995b2d4875834ece1a9d71af04ca2a2c7c742c", "packages/shared/src/adapter-auth-session.ts": "1bde62818a6e2a127ceb6e947882ded311798892", + "packages/shared/src/adapter-login.ts": "312186ee1d541d54dac23d14d10f0ab97d102041", "packages/shared/src/adapter-type.ts": "5af29dfc580ef18d53404b679cbe32a53587098e", "packages/shared/src/adapter-types.test.ts": "49646cb8f85f86cb45d9dd0efda6b84ed0599341", "packages/shared/src/agent-appearance.test.ts": "709173240aad4df58d5d6fb0f4d94bef36ac3911", @@ -252,8 +253,8 @@ "packages/shared/src/env-file.ts": "ee15f8dfa6610d3fd1eea3ca0846cc2c583f9070", "packages/shared/src/environment-custom-images.test.ts": "80d00f3581f13a782480700296b1295d8159ddae", "packages/shared/src/environment-custom-images.ts": "a81814b7f99e5c8871f50ffcf9dd93dc435dee27", - "packages/shared/src/environment-support.test.ts": "d082845e80881308f1bc0261566b4cb2f99c3986", - "packages/shared/src/environment-support.ts": "a7658dfe11625cb826dfe400697a1f70c3b10f4e", + "packages/shared/src/environment-support.test.ts": "91a7aacce30fb6fcf6782045a5a5e1281448cdf4", + "packages/shared/src/environment-support.ts": "261c02dccfb7d8396687739ccc1b03bb59067a6b", "packages/shared/src/execution-workspace-guards.ts": "5428546ab16ef5cb4d23edd914d0a15a83a94668", "packages/shared/src/external-agent-guidance.ts": "d815fc60b170717f0fdcff61bc30c8a1289f7fcc", "packages/shared/src/external-objects-server.ts": "f323ba3e5e0b1a2ad415bdb5e0ca99bf9d449821", @@ -289,7 +290,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "dbdd64c5df8ba7011e2a14fa17a77f8c330ecd43", + "packages/shared/src/index.ts": "98149289a57cc0fd6738bbb3c12e06eb00c86988", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -464,7 +465,7 @@ "packages/shared/src/types/issue.ts": "84699de7b12622743914b66ce6d6d2c91220a64a", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", - "packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949", + "packages/shared/src/types/plugin.ts": "99567f30af5165880d67519c1d9e71855600d4f9", "packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c", "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", @@ -550,8 +551,8 @@ "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830", "packages/shared/src/validators/onboarding-seed.ts": "de302a8400d4199053f379d9ed853522a3ac6d32", "packages/shared/src/validators/partial.ts": "fa60ec7481fc14175365e9e500c814b159f1ab53", - "packages/shared/src/validators/plugin.test.ts": "467df457aa12a29d42f0e2c90f0debfc39da2c83", - "packages/shared/src/validators/plugin.ts": "baa064f95301c2420682981550f384db23581401", + "packages/shared/src/validators/plugin.test.ts": "0a028e978f6706b3b23039e30ea04d7d8bccb1e2", + "packages/shared/src/validators/plugin.ts": "072f0e6e3b7618b1d3a7c85dc1cc5074c86bd2b0", "packages/shared/src/validators/project.ts": "6ea168f5faf3161e6004ea47274f60634c77b219", "packages/shared/src/validators/provider-trace.ts": "b38b6200a2e51513f5dca0f8b008f2fe68175e82", "packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd", diff --git a/ui/src/api/adapters.ts b/ui/src/api/adapters.ts index fd609ba1496..a562db01567 100644 --- a/ui/src/api/adapters.ts +++ b/ui/src/api/adapters.ts @@ -37,6 +37,7 @@ export interface AdapterInfo { /** Exact operator-authorized candidates for the requested company and target. */ candidateHarnesses?: Array<{ agent: "antigravity"; model: string }>; supportedRunners?: import("@paperclipai/shared").AgentRunner[]; + supportedAdapters?: string[]; defaultRunner?: import("@paperclipai/shared").AgentRunner; type: string; label: string; diff --git a/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx b/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx index 99bebaa2acf..49eb39188a5 100644 --- a/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx +++ b/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx @@ -1,4 +1,4 @@ -import { environmentLoginRequiresAgent, environmentSupportsLoginPty } from "@paperclipai/shared"; +import { AI_CONNECTION_CAPABILITIES, adapterLoginCommandKey, environmentLoginRequiresAgent, environmentSupportsLoginPty } from "@paperclipai/shared"; import { useState, type ReactNode } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { type AiProvider, type AiAuthMethod, type AiConnectionLoginIntent } from "@paperclipai/shared"; @@ -81,8 +81,10 @@ function SubscriptionConnectionStep({ defaultAccountDialog, onOtherModels, advan } catch (error) { if (!hostedGoogleSignIn) environmentError = describeError(error).body; } + const subscriptionAdapter = AI_CONNECTION_CAPABILITIES[provider].methods.subscription?.adapters[0]; + const loginAdapter = subscriptionAdapter && adapterLoginCommandKey(subscriptionAdapter) ? subscriptionAdapter : undefined; const loginEnvironments = (envs.data ?? []).filter((env) => - env.status === "active" && (env.driver === "local" || (provider !== "google" && environmentSupportsLoginPty(env, caps.data, provider === "openai" ? "codex_local" : provider === "anthropic" ? "claude_local" : "unsupported"))), + env.status === "active" && (env.driver === "local" || (loginAdapter !== undefined && environmentSupportsLoginPty(env, caps.data, loginAdapter))), ); // Signing in may use a different environment from later agent execution. // Prefer a supported login environment without changing any agent routing. @@ -91,7 +93,7 @@ function SubscriptionConnectionStep({ defaultAccountDialog, onOtherModels, advan environmentId = loginEnvironments[0]?.id ?? null; } const environment = envs.data?.find((env) => env.id === environmentId); - const canLogin = environmentSupportsLoginPty(environment, caps.data, provider === "openai" ? "codex_local" : provider === "anthropic" ? "claude_local" : "unsupported"); + const canLogin = loginAdapter !== undefined && environmentSupportsLoginPty(environment, caps.data, loginAdapter); const loading = [envs, caps, settings, experimental, general].some((query) => query.isPending) || (provider === "google" && health.isPending) || views.some((view) => view.kind === "reconnecting"); const loadError = views.find((view) => view.kind === "error"); const intent: AiConnectionLoginIntent = { provider: provider as AiConnectionLoginIntent["provider"], method: "subscription", name, ownership, agentIds, allAgents, connectionId }; diff --git a/ui/src/components/new-agent/AgentBasicsDialog.tsx b/ui/src/components/new-agent/AgentBasicsDialog.tsx index 02d0875c5fe..67e418fa3f1 100644 --- a/ui/src/components/new-agent/AgentBasicsDialog.tsx +++ b/ui/src/components/new-agent/AgentBasicsDialog.tsx @@ -88,12 +88,13 @@ export function AgentBasicsDialog({ const adaptersView = useQueryView(adaptersQuery); const adapters = adaptersView.data; const nativeRunner = adapters?.find(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled && adapter.supportedRunners?.length !== 0); - const copilotAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("copilot")) && Boolean(nativeRunner) && PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "copilot" && profile.qualified); - const kimiAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("kimi")) && Boolean(nativeRunner) && experimental.data?.enableNativeRunner === true + const wrapperSupports = (harness: string) => Boolean(nativeRunner) && (!nativeRunner?.supportedAdapters || nativeRunner.supportedAdapters.includes(harness)); + const copilotAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("copilot")) && wrapperSupports("copilot_runtime") && PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "copilot" && profile.qualified); + const kimiAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("kimi")) && wrapperSupports("kimi_local") && experimental.data?.enableNativeRunner === true && PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "kimi" && profile.qualified); const antigravityQualified = PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "antigravity" && profile.qualified); const antigravityCandidate = nativeRunner?.candidateHarnesses?.some(candidate => candidate.agent === "antigravity"); - const antigravityAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("antigravity")) && Boolean(nativeRunner); + const antigravityAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("antigravity")) && wrapperSupports("antigravity_runtime"); const choices = [...(adapters ?? []).filter( (adapter) => adapter.loaded &&