diff --git a/server/src/__tests__/agent-harness-verification-preflight.test.ts b/server/src/__tests__/agent-harness-verification-preflight.test.ts index 835cdf1061d..74b839f3acc 100644 --- a/server/src/__tests__/agent-harness-verification-preflight.test.ts +++ b/server/src/__tests__/agent-harness-verification-preflight.test.ts @@ -13,6 +13,10 @@ import { aiConnectionService } from "../services/ai-connections.js"; import { secretService } from "../services/secrets.js"; import { readAiConnectionConfigurationFailure } from "../services/ai-connection-configuration-failure.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; +import { + createCloudTrialInferenceController, + setDefaultCloudTrialInferenceController, +} from "../services/cloud-trial-inference.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -269,4 +273,43 @@ describePostgres("saved harness account preflight", () => { await expect(verify()).resolves.toBe("complete"); expect(allocate).toHaveBeenCalledTimes(2); }); + + it("verifies a Cloud starter-trial paperclip_runner agent on a plugin Runner environment without requiring a user aiConnection", async () => { + await useRunnerTaskEnvironment({ cloudTrialInference: true }); + [agent] = await db.update(agents) + .set({ adapterConfig: { provider: "opencode", model: "openrouter/openai/gpt-6-luna" } }) + .where(eq(agents.id, agent.id)) + .returning(); + + const trialController = createCloudTrialInferenceController({ + env: { + PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1", + PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-test-trial-key", + }, + fetchImpl: vi.fn(async () => new Response(JSON.stringify({ data: { limit: 1, usage: 0, limit_remaining: 1 } }), { status: 200 })), + }); + setDefaultCloudTrialInferenceController(trialController); + + try { + await expect(verify()).resolves.toBe("complete"); + expect(allocate).not.toHaveBeenCalled(); + expect(probe).not.toHaveBeenCalled(); + + // Permanent model mismatch must map to harness_model_unavailable (not generic retry). + [agent] = await db.update(agents) + .set({ adapterConfig: { provider: "opencode", model: "openrouter/anthropic/claude-opus-4" } }) + .where(eq(agents.id, agent.id)) + .returning(); + await expect(verify()).rejects.toMatchObject({ code: "harness_model_unavailable" }); + + // Preconfigured home on a plugin Runner environment must STILL be rejected. + [agent] = await db.update(agents) + .set({ adapterConfig: { provider: "opencode", model: "openrouter/openai/gpt-6-luna", homeMode: "preconfigured" } }) + .where(eq(agents.id, agent.id)) + .returning(); + await expect(verify()).rejects.toMatchObject({ code: "ai_connection_required" }); + } finally { + setDefaultCloudTrialInferenceController(createCloudTrialInferenceController()); + } + }); }); diff --git a/server/src/__tests__/heartbeat-plugin-environment.test.ts b/server/src/__tests__/heartbeat-plugin-environment.test.ts index 5122b683b32..67ea618659b 100644 --- a/server/src/__tests__/heartbeat-plugin-environment.test.ts +++ b/server/src/__tests__/heartbeat-plugin-environment.test.ts @@ -22,6 +22,10 @@ import { } from "./helpers/embedded-postgres.js"; import { heartbeatService } from "../services/heartbeat.ts"; import { instanceSettingsService } from "../services/instance-settings.ts"; +import { + createCloudTrialInferenceController, + setDefaultCloudTrialInferenceController, +} from "../services/cloud-trial-inference.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.ts"; const adapterExecute = vi.hoisted(() => vi.fn(async () => ({ @@ -139,6 +143,193 @@ describeEmbeddedPostgres("heartbeat plugin environments", () => { await expect(stat(pluginOnlyCwd)).rejects.toMatchObject({ code: "ENOENT" }); }, 20_000); + it("allows Cloud starter-trial agents through plugin Runner heartbeat admission with proxy settings while still refusing preconfigured home", async () => { + const companyId = randomUUID(); + const userId = randomUUID(); + const environmentId = randomUUID(); + const pluginId = randomUUID(); + const pluginKey = `acme.trial-tasks.${pluginId}`; + const trialAgentId = randomUUID(); + const preconfiguredAgentId = randomUUID(); + const issueId = randomUUID(); + const preconfiguredIssueId = randomUUID(); + const pluginOnlyCwd = path.join(os.tmpdir(), `paperclip-trial-plugin-only-${randomUUID()}`); + const now = new Date(); + await db.insert(authUsers).values({ + id: userId, + name: "Trial Owner", + email: `trial-${userId.slice(0, 8)}@example.com`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }); + await db.insert(companies).values({ + id: companyId, + name: "Trial tasks Co", + issuePrefix: `TT${companyId.slice(0, 4).toUpperCase()}`, + defaultResponsibleUserId: userId, + }); + await db.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: userId, + status: "active", + membershipRole: "owner", + }); + await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@acme/trial-tasks", version: "1.0.0", apiVersion: 1, + categories: ["automation"], status: "ready", manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", + displayName: "Trial Tasks", description: "Trial task fixture", author: "Paperclip", categories: ["automation"], + capabilities: ["environment.drivers.register", "workspaces.manage", "events.subscribe"], resourceLifecycle: ["project"], + workspaceProvider: { modes: ["shared_workspace", "isolated_workspace", "operator_branch"], strategies: ["project_primary", "git_worktree"] }, + entrypoints: { worker: "worker.js" }, + environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", supportsTasks: true, warmTaskVersion: 1, configSchema: { type: "object" } }] } }); + await db.insert(environments).values({ id: environmentId, name: "Trial Tasks Env", driver: "plugin", status: "active", + config: { pluginKey, driverKey: "tasks", driverConfig: {} } }); + await db.insert(agents).values([ + { + id: trialAgentId, + companyId, + name: "Trial Chief of Staff", + role: "ceo", + status: "idle", + adapterType: "paperclip_runner", + adapterConfig: { provider: "opencode", model: "openrouter/openai/gpt-6-luna", lifecycleMode: "warm" }, + runtimeConfig: { cloudTrialInference: true }, + defaultEnvironmentId: environmentId, + permissions: {}, + }, + { + id: preconfiguredAgentId, + companyId, + name: "Preconfigured Trial Agent", + role: "engineer", + status: "idle", + adapterType: "paperclip_runner", + adapterConfig: { provider: "opencode", model: "openrouter/openai/gpt-6-luna", homeMode: "preconfigured", lifecycleMode: "warm" }, + runtimeConfig: { cloudTrialInference: true }, + defaultEnvironmentId: environmentId, + permissions: {}, + }, + ]); + await db.insert(issues).values([ + { + id: issueId, + companyId, + title: "First chat", + status: "in_progress", + originKind: "onboarding_first_task", + assigneeAgentId: trialAgentId, + issueNumber: 1, + identifier: "TT-1", + }, + { + id: preconfiguredIssueId, + companyId, + title: "Preconfigured task", + status: "in_progress", + assigneeAgentId: preconfiguredAgentId, + issueNumber: 2, + identifier: "TT-2", + }, + ]); + + const trialController = createCloudTrialInferenceController({ + env: { + PAPERCLIP_ONBOARDING_VARIANT: "free_inference_1", + PAPERCLIP_CLOUD_TRIAL_OPENROUTER_API_KEY: "sk-or-v1-heartbeat-trial-key", + PAPERCLIP_API_URL: "http://127.0.0.1:3100", + }, + fetchImpl: vi.fn(async () => new Response(JSON.stringify({ data: { limit: 1, usage: 0, limit_remaining: 1 } }), { status: 200 })), + }); + const prepareSpy = vi.spyOn(trialController, "prepareCloudTrialRuntime"); + setDefaultCloudTrialInferenceController(trialController); + + try { + // 1. Eligible starter-trial agent passes plugin Runner admission and reaches execution with proxy env injected. + const callEligible = vi.fn(async (_id: string, method: string) => { + if (method === "workspaceOperation") return { workspacePath: pluginOnlyCwd }; + if (method === "environmentAcquireLease") return { providerLeaseId: "trial-lease-1", metadata: { remoteCwd: "/workspace/trial" } }; + if (method === "environmentReleaseLease") return undefined; + throw new Error(`Unexpected task provider call: ${method}`); + }); + const enteredEligible = vi.fn(() => { throw new Error("synthetic_native_boundary_reached"); }); + const workerManagerEligible = { + isRunning: () => true, + getWorker: () => ({ supportedMethods: ["workspaceOperation", "environmentTask", "environmentAcquireLease", "environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"] }), + call: callEligible, + } as unknown as PluginWorkerManager; + const heartbeatEligible = heartbeatService(db, { pluginWorkerManager: workerManagerEligible, nativeSessionBackendFactory: enteredEligible }); + heartbeats.push(heartbeatEligible); + + const eligibleRun = await heartbeatEligible.wakeup(trialAgentId, { + source: "on_demand", + triggerDetail: "manual", + requestedByActorType: "user", + requestedByActorId: userId, + contextSnapshot: { issueId, responsibleUserId: userId }, + }); + expect(eligibleRun).not.toBeNull(); + await vi.waitFor(async () => { + const current = await heartbeatEligible.getRun(eligibleRun!.id); + expect(current?.status).not.toBe("queued"); + expect(current?.status).not.toBe("running"); + }, { timeout: 10_000 }); + await heartbeatEligible.drainActiveRunExecutions(); + const finishedEligible = await heartbeatEligible.getRun(eligibleRun!.id); + // Must NOT fail with configuration_incomplete / ai_connection_required; reaches execution with proxy settings. + expect(finishedEligible?.errorCode).not.toBe("configuration_incomplete"); + expect(prepareSpy).toHaveBeenCalledOnce(); + const preparedRuntime = await prepareSpy.mock.results[0]!.value; + expect(preparedRuntime.env).toMatchObject({ + OPENROUTER_API_KEY: "", + PAPERCLIP_OPENROUTER_PROXY_URL: "http://127.0.0.1:3100/api/internal/cloud-inference/v1", + PAPERCLIP_OPENROUTER_PROXY_TOKEN: expect.stringMatching(/^pctrial_/), + }); + expect(enteredEligible).toHaveBeenCalled(); + + // 2. Preconfigured home on a plugin Runner environment STILL fails before any plugin call. + const callPreconfigured = vi.fn(async (_id: string, method: string) => { + throw new Error(`Unexpected task provider call: ${method}`); + }); + const enteredPreconfigured = vi.fn(() => { throw new Error("synthetic_native_boundary_reached"); }); + const workerManagerPreconfigured = { + isRunning: () => true, + getWorker: () => ({ supportedMethods: ["workspaceOperation", "environmentTask", "environmentAcquireLease", "environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"] }), + call: callPreconfigured, + } as unknown as PluginWorkerManager; + const heartbeatPreconfigured = heartbeatService(db, { pluginWorkerManager: workerManagerPreconfigured, nativeSessionBackendFactory: enteredPreconfigured }); + heartbeats.push(heartbeatPreconfigured); + + const preconfiguredRun = await heartbeatPreconfigured.wakeup(preconfiguredAgentId, { + source: "on_demand", + triggerDetail: "manual", + requestedByActorType: "user", + requestedByActorId: userId, + contextSnapshot: { issueId: preconfiguredIssueId, responsibleUserId: userId }, + }); + expect(preconfiguredRun).not.toBeNull(); + await vi.waitFor(async () => { + expect((await heartbeatPreconfigured.getRun(preconfiguredRun!.id))?.status).toBe("failed"); + }, { timeout: 10_000 }); + await heartbeatPreconfigured.drainActiveRunExecutions(); + const failedPreconfigured = await heartbeatPreconfigured.getRun(preconfiguredRun!.id); + expect(failedPreconfigured).toMatchObject({ + errorCode: "configuration_incomplete", + resultJson: { + configurationIncomplete: { + reason: "ai_connection_required", + homeMode: "preconfigured", + actionUrl: `/agents/${preconfiguredAgentId}/runtime`, + }, + }, + }); + expect(callPreconfigured).not.toHaveBeenCalled(); + expect(enteredPreconfigured).not.toHaveBeenCalled(); + } finally { + setDefaultCloudTrialInferenceController(createCloudTrialInferenceController()); + } + }, 25_000); + it("acquires plugin environment leases through the heartbeat execution path", async () => { const companyId = randomUUID(); const projectId = randomUUID(); diff --git a/server/src/services/agent-harness-verification.ts b/server/src/services/agent-harness-verification.ts index 6bdc924c2f5..58883d98f20 100644 --- a/server/src/services/agent-harness-verification.ts +++ b/server/src/services/agent-harness-verification.ts @@ -5,14 +5,27 @@ import { createHmac } from "node:crypto"; import { and, eq, inArray } from "drizzle-orm"; import { agents, companies, companySecrets, type Db } from "@paperclipai/db"; import type { AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils"; -import { ADAPTER_AUTH_MISSING_CHECK_CODE, aiRuntimeConnectionBindingSchema } from "@paperclipai/shared"; +import { + ADAPTER_AUTH_MISSING_CHECK_CODE, + CLOUD_TRIAL_EXHAUSTED_ERROR_CODE, + CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE, + aiRuntimeConnectionBindingSchema, + isAgentUsingCloudTrialInference, +} from "@paperclipai/shared"; +import { HttpError } from "../errors.js"; import { isForbiddenConfigEnvKey, parseObject } from "@paperclipai/adapter-utils/server-utils"; import { requireServerAdapter } from "../adapters/index.js"; import { agentEnvironmentTestService } from "./agent-environment-test.js"; import { aiConnectionRouterService } from "./ai-connection-router.js"; import { aiConnectionService } from "./ai-connections.js"; import { withManagedAiProbe, stripAiAuthBindings } from "./ai-connection-runtime.js"; -import { PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, pluginEnvironmentRunnerTaskDriver, pluginRunnerAiConnectionRequiredFailure } from "./plugin-runner-ai-connection.js"; +import { getDefaultCloudTrialInferenceController } from "./cloud-trial-inference.js"; +import { + PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, + pluginEnvironmentRunnerTaskDriver, + pluginRunnerAiConnectionRequiredFailure, + requiresPluginRunnerAiConnection, +} from "./plugin-runner-ai-connection.js"; import { environmentService } from "./environments.js"; import { secretService } from "./secrets.js"; import { instanceSettingsService } from "./instance-settings.js"; @@ -94,6 +107,7 @@ export function agentHarnessVerificationService(db: Db, manager: PluginWorkerMan const context = { consumerType: "agent" as const, consumerId: agent.id, actorType: "system" as const, actorId: "agent-lifecycle", responsibleUserId }; let binding = agent.runtimeConfig.aiConnection ? aiRuntimeConnectionBindingSchema.parse(agent.runtimeConfig.aiConnection) : undefined; + const usesCloudTrial = !binding && isAgentUsingCloudTrialInference(agent.runtimeConfig); let config = agent.adapterConfig; if (binding?.mode === "router") { const selected = await aiConnectionRouterService(db, manager).resolve({ companyId: agent.companyId, @@ -102,7 +116,7 @@ export function agentHarnessVerificationService(db: Db, manager: PluginWorkerMan binding = selected.binding; config = { ...config, ...selected.runtimeConfig }; } - if (binding) config = { ...config, env: stripAiAuthBindings(config.env) }; + if (binding || usesCloudTrial) config = { ...config, env: stripAiAuthBindings(config.env) }; config = (await secrets.resolveAdapterConfigForRuntime(agent.companyId, config, context, { adapterType: agent.adapterType })).config; let runner: Record | null = providerApi ? { kind: "provider_api" } : { kind: "local", version: serverVersion }; const environmentId = providerApi ? null : await tests.resolveAdapterTestEnvironmentId(agent.companyId, agent.defaultEnvironmentId, agent.adapterType === "paperclip_runner" && config.provider === "acpx" && config.acpxAgent === "copilot"); @@ -121,14 +135,63 @@ export function agentHarnessVerificationService(db: Db, manager: PluginWorkerMan } // Run admission refuses these agents before any lease, so verification must too. const preconfiguredHome = agent.adapterType === "paperclip_runner" && config.homeMode === "preconfigured"; - if (agent.adapterType === "paperclip_runner" && environment && (preconfiguredHome || !binding) - && await pluginEnvironmentRunnerTaskDriver(db, environment)) throw pluginRunnerAiConnectionRequiredFailure(preconfiguredHome); - const env = Object.fromEntries(Object.entries(binding ? stripAiAuthBindings(environment?.envVars) : parseObject(environment?.envVars)) + if (environment && requiresPluginRunnerAiConnection({ + adapterType: agent.adapterType, + preconfiguredHome, + hasAiBinding: Boolean(binding), + runtimeConfig: agent.runtimeConfig, + }) && await pluginEnvironmentRunnerTaskDriver(db, environment)) throw pluginRunnerAiConnectionRequiredFailure(preconfiguredHome); + const env = Object.fromEntries(Object.entries(binding || usesCloudTrial ? stripAiAuthBindings(environment?.envVars) : parseObject(environment?.envVars)) .filter(([key]) => !isForbiddenConfigEnvKey(key))); const resolved = await secrets.resolveEnvBindings(agent.companyId, env, { ...context, consumerType: "environment", consumerId: environmentId }); config = { ...config, env: { ...resolved.env, ...parseObject(config.env) } }; } + // Cloud starter-trial agents use Paperclip Cloud's server-proxied OpenRouter + // starter key instead of a user AI connection. Verify eligibility, active + // starter key availability, and model restriction without spending tokens or + // requiring a user-managed AI connection. + if (usesCloudTrial) { + let trialRuntime: Awaited< + ReturnType["prepareCloudTrialRuntime"]> + >; + try { + trialRuntime = await getDefaultCloudTrialInferenceController().prepareCloudTrialRuntime(db, { + companyId: agent.companyId, + agentId: agent.id, + runId: `verify:${agent.id}:${agent.lifecycleVersion}`, + model: typeof config.model === "string" ? config.model : undefined, + probeOnly: true, + }); + } catch (error) { + const detailCode = + error instanceof HttpError && error.details && typeof error.details === "object" + ? (error.details as { code?: unknown }).code + : undefined; + if (detailCode === "cloud_trial_model_not_allowed") { + throw Object.assign( + new Error(error instanceof Error ? error.message : "The selected model is unavailable."), + { code: "harness_model_unavailable", cause: error }, + ); + } + if ( + detailCode === "cloud_trial_disabled" || + detailCode === CLOUD_TRIAL_EXHAUSTED_ERROR_CODE || + detailCode === CLOUD_TRIAL_WORK_REQUIRES_MODEL_ERROR_CODE + ) { + throw Object.assign( + new Error(error instanceof Error ? error.message : "Connect a model provider to continue."), + { code: PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, cause: error }, + ); + } + throw error; + } + try { + return "complete"; + } finally { + await trialRuntime.cleanup(); + } + } const selectAccount = () => aiConnectionService(db).select({ companyId: agent.companyId, userId: responsibleUserId, agentId: agent.id, adapterType: agent.adapterType, model: config.model, runnerProvider: config.provider, diff --git a/server/src/services/cloud-trial-proxy.ts b/server/src/services/cloud-trial-proxy.ts index 6c257f6ebf8..16040b6c270 100644 --- a/server/src/services/cloud-trial-proxy.ts +++ b/server/src/services/cloud-trial-proxy.ts @@ -89,6 +89,7 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { agentId: string; runId: string; model?: string; + probeOnly?: boolean; }, ): Promise { const effective = await resolveEffectiveOnboardingConfig(db, keyStore); @@ -149,7 +150,9 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) { const serverOrigin = (env.PAPERCLIP_API_URL?.trim() || "http://127.0.0.1:3100").replace(/\/+$/, ""); const proxyUrl = `${serverOrigin}/api/internal/cloud-inference/v1`; const token = `${RUN_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`; - keyStore.recordRunPrepared(); + if (!input.probeOnly) { + keyStore.recordRunPrepared(); + } activeRunTokens.set(token, { token, diff --git a/server/src/services/heartbeat/execution-configuration.ts b/server/src/services/heartbeat/execution-configuration.ts index 53bb746ecc3..38a9f99be00 100644 --- a/server/src/services/heartbeat/execution-configuration.ts +++ b/server/src/services/heartbeat/execution-configuration.ts @@ -22,7 +22,12 @@ import { isAgentUsingCloudTrialInference } from "@paperclipai/shared"; import { managedAiSessionIdentityCompatible } from "../ai-connection-session.js"; import type { companySkillService } from "../company-skills.js"; import { connectionIntentService } from "../connection-intents.js"; -import { PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, pluginEnvironmentRunnerTaskDriver, pluginRunnerAiConnectionRequiredMessage } from "../plugin-runner-ai-connection.js"; +import { + PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, + pluginEnvironmentRunnerTaskDriver, + pluginRunnerAiConnectionRequiredMessage, + requiresPluginRunnerAiConnection, +} from "../plugin-runner-ai-connection.js"; import { prepareConnectionInstructionDelivery } from "../connection-instructions.js"; import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "../connector-runtime.js"; import { resolveManagedGitHubIdentitySelection } from "../git-credentials.js"; @@ -137,10 +142,15 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear configurationIncomplete: { reason: "skill_unavailable", actionUrl: `/agents/${agent.id}/runtime` }, }); } - // A plugin Runner-task environment runs only managed AI connections. Refuse a new - // admission before secrets, leases, or provider calls. Resumed native input keeps - // the contract it was admitted under. - if (agent.adapterType === "paperclip_runner" && (preconfiguredHome || !input.config.aiBinding) && !persistedNativeExecutionInput + // A plugin Runner-task environment runs only managed AI connections or Cloud + // starter-trial inference. Refuse a new admission before secrets, leases, or + // provider calls. Resumed native input keeps the contract it was admitted under. + if (requiresPluginRunnerAiConnection({ + adapterType: agent.adapterType, + preconfiguredHome, + hasAiBinding: Boolean(input.config.aiBinding), + runtimeConfig: agent.runtimeConfig, + }) && !persistedNativeExecutionInput && selectedEnvironmentForConfig && await pluginEnvironmentRunnerTaskDriver(db, selectedEnvironmentForConfig)) { throw new ConfigurationIncompleteFailure(pluginRunnerAiConnectionRequiredMessage(preconfiguredHome), { configurationIncomplete: { reason: PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, actionUrl: `/agents/${agent.id}/runtime`, diff --git a/server/src/services/plugin-runner-ai-connection.ts b/server/src/services/plugin-runner-ai-connection.ts index 7c001131f02..2212e1d8233 100644 --- a/server/src/services/plugin-runner-ai-connection.ts +++ b/server/src/services/plugin-runner-ai-connection.ts @@ -1,5 +1,6 @@ import type { AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils"; import type { Db } from "@paperclipai/db"; +import { isAgentUsingCloudTrialInference } from "@paperclipai/shared"; import { parseEnvironmentDriverConfig } from "./environment-config.js"; /** @@ -21,6 +22,23 @@ export function pluginRunnerAiConnectionRequiredMessage(preconfiguredHome: boole return preconfiguredHome ? PLUGIN_RUNNER_ISOLATED_HOME_REQUIRED_MESSAGE : PLUGIN_RUNNER_AI_CONNECTION_REQUIRED_MESSAGE; } +/** + * Shared admission/verification policy for plugin Runner-task environments: + * a preconfigured Runner home is always refused, and an isolated home requires + * either a managed AI connection or Cloud starter-trial inference. + */ +export function requiresPluginRunnerAiConnection(input: { + adapterType: string; + preconfiguredHome: boolean; + hasAiBinding: boolean; + runtimeConfig: unknown; +}): boolean { + if (input.adapterType !== "paperclip_runner") return false; + if (input.preconfiguredHome) return true; + if (input.hasAiBinding) return false; + return !isAgentUsingCloudTrialInference(input.runtimeConfig); +} + // 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.