mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
fix(cloud-trial): allow Cloud starter-trial agents through plugin Runner verification and admission (#23427)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Cloud onboarding supports a starter-inference variant
(`free_inference_1`) where the first agent uses Paperclip Cloud's
server-proxied OpenRouter starter key
(`runtimeConfig.cloudTrialInference: true`) before the user connects
their own model provider
> - On Cloud plugin Runner environments, both
`agentHarnessVerificationService` and heartbeat run admission
(`execution-configuration.ts`) rejected `paperclip_runner` agents with
`ai_connection_required` whenever `runtimeConfig.aiConnection` was
absent
> - Because verification failed, the hired first agent stayed stuck in
`status: "paused"` / `lifecycleState: "verifying"` and the first
free-inference chat never executed or replied
> - This pull request allows `cloudTrialInference` agents (with isolated
homes) through plugin Runner verification and run admission, verifying
starter-key eligibility and model restriction via
`prepareCloudTrialRuntime(..., { probeOnly: true })`
> - The benefit is that `free_inference_1` onboarding agents transition
immediately to `ready`/`idle` and execute their first chat turn on
starter inference without requiring a user-managed AI connection
## Linked Issues or Issue Description
Refs #23401
**What happened?**
When a user completes `free_inference_1` onboarding on a Cloud stack
with a plugin Runner environment, the first agent is hired with
`runtimeConfig.cloudTrialInference: true` and no
`runtimeConfig.aiConnection`. Agent harness verification fails with
`ai_connection_required`, leaving the agent stuck in `paused` (`"Agent
setup needs attention"`) so the first chat run sits in `queued` forever.
**What did you expect to happen?**
The starter-trial agent should pass harness verification using Paperclip
Cloud's starter-trial eligibility and key check, transition to `idle`,
and execute its first chat turn via the Cloud trial OpenRouter proxy.
**Steps to reproduce**
1. Enable `free_inference_1` on a Cloud stack backed by a plugin Runner
environment.
2. Complete onboarding and click "Start chatting".
3. Send a message in the first chat; observe the agent remains paused on
`"Agent setup needs attention"`.
## What Changed
- Updated `server/src/services/agent-harness-verification.ts` to
recognize `runtimeConfig.cloudTrialInference: true` on
`paperclip_runner` agents (while still refusing `homeMode:
"preconfigured"` on plugin Runner environments), strip host AI auth env
bindings, and verify starter-key eligibility + model restriction via
`prepareCloudTrialRuntime(..., { probeOnly: true })` + `cleanup()`.
- Updated `server/src/services/heartbeat/execution-configuration.ts` to
allow `cloudTrialInference` agents (when `homeMode` is not
`"preconfigured"`) past the plugin Runner `aiConnection` preflight check
so the first chat run reaches `prepareCloudTrialRuntime`.
- Added optional `probeOnly?: boolean` to `prepareCloudTrialRuntime` in
`server/src/services/cloud-trial-proxy.ts` so verification checks do not
increment `trialRunsCount` telemetry.
- Added a red-green regression test in
`server/src/__tests__/agent-harness-verification-preflight.test.ts`
covering both valid starter-trial verification on a plugin Runner
environment and continued rejection of `homeMode: "preconfigured"`.
## Verification
- Confirmed RED before the fix
(`agent-harness-verification-preflight.test.ts` rejected with
`ai_connection_required`).
- Confirmed GREEN after the fix:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/agent-harness-verification-preflight.test.ts
src/__tests__/cloud-trial-inference.test.ts` (22/22 passed)
- `pnpm --filter @paperclipai/server typecheck` (0 errors)
## Risks
- Low risk. Scope is restricted to agents with
`runtimeConfig.cloudTrialInference === true` and no `aiConnection`.
Non-trial agents and `homeMode: "preconfigured"` agents keep identical
fail-closed `ai_connection_required` enforcement.
## Model Used
- Google Gemini (Antigravity agentic harness with tool use and code
execution)
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
1 parent
0d3ed44550
commit
fcb8fc5deb
6 files changed
+339
-11
No files matched your search
@@ -13,6 +13,10 @@ import { aiConnectionService } from "../services/ai-connections.js";
|
|||||||
import { secretService } from "../services/secrets.js";
|
import { secretService } from "../services/secrets.js";
|
||||||
import { readAiConnectionConfigurationFailure } from "../services/ai-connection-configuration-failure.js";
|
import { readAiConnectionConfigurationFailure } from "../services/ai-connection-configuration-failure.js";
|
||||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.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";
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||||
|
|
||||||
const support = await getEmbeddedPostgresTestSupport();
|
const support = await getEmbeddedPostgresTestSupport();
|
||||||
@@ -269,4 +273,43 @@ describePostgres("saved harness account preflight", () => {
|
|||||||
await expect(verify()).resolves.toBe("complete");
|
await expect(verify()).resolves.toBe("complete");
|
||||||
expect(allocate).toHaveBeenCalledTimes(2);
|
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());
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -22,6 +22,10 @@ import {
|
|||||||
} from "./helpers/embedded-postgres.js";
|
} from "./helpers/embedded-postgres.js";
|
||||||
import { heartbeatService } from "../services/heartbeat.ts";
|
import { heartbeatService } from "../services/heartbeat.ts";
|
||||||
import { instanceSettingsService } from "../services/instance-settings.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";
|
import type { PluginWorkerManager } from "../services/plugin-worker-manager.ts";
|
||||||
|
|
||||||
const adapterExecute = vi.hoisted(() => vi.fn(async () => ({
|
const adapterExecute = vi.hoisted(() => vi.fn(async () => ({
|
||||||
@@ -139,6 +143,193 @@ describeEmbeddedPostgres("heartbeat plugin environments", () => {
|
|||||||
await expect(stat(pluginOnlyCwd)).rejects.toMatchObject({ code: "ENOENT" });
|
await expect(stat(pluginOnlyCwd)).rejects.toMatchObject({ code: "ENOENT" });
|
||||||
}, 20_000);
|
}, 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 () => {
|
it("acquires plugin environment leases through the heartbeat execution path", async () => {
|
||||||
const companyId = randomUUID();
|
const companyId = randomUUID();
|
||||||
const projectId = randomUUID();
|
const projectId = randomUUID();
|
||||||
|
|||||||
@@ -5,14 +5,27 @@ import { createHmac } from "node:crypto";
|
|||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq, inArray } from "drizzle-orm";
|
||||||
import { agents, companies, companySecrets, type Db } from "@paperclipai/db";
|
import { agents, companies, companySecrets, type Db } from "@paperclipai/db";
|
||||||
import type { AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
|
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 { isForbiddenConfigEnvKey, parseObject } from "@paperclipai/adapter-utils/server-utils";
|
||||||
import { requireServerAdapter } from "../adapters/index.js";
|
import { requireServerAdapter } from "../adapters/index.js";
|
||||||
import { agentEnvironmentTestService } from "./agent-environment-test.js";
|
import { agentEnvironmentTestService } from "./agent-environment-test.js";
|
||||||
import { aiConnectionRouterService } from "./ai-connection-router.js";
|
import { aiConnectionRouterService } from "./ai-connection-router.js";
|
||||||
import { aiConnectionService } from "./ai-connections.js";
|
import { aiConnectionService } from "./ai-connections.js";
|
||||||
import { withManagedAiProbe, stripAiAuthBindings } from "./ai-connection-runtime.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 { environmentService } from "./environments.js";
|
||||||
import { secretService } from "./secrets.js";
|
import { secretService } from "./secrets.js";
|
||||||
import { instanceSettingsService } from "./instance-settings.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,
|
const context = { consumerType: "agent" as const, consumerId: agent.id, actorType: "system" as const,
|
||||||
actorId: "agent-lifecycle", responsibleUserId };
|
actorId: "agent-lifecycle", responsibleUserId };
|
||||||
let binding = agent.runtimeConfig.aiConnection ? aiRuntimeConnectionBindingSchema.parse(agent.runtimeConfig.aiConnection) : undefined;
|
let binding = agent.runtimeConfig.aiConnection ? aiRuntimeConnectionBindingSchema.parse(agent.runtimeConfig.aiConnection) : undefined;
|
||||||
|
const usesCloudTrial = !binding && isAgentUsingCloudTrialInference(agent.runtimeConfig);
|
||||||
let config = agent.adapterConfig;
|
let config = agent.adapterConfig;
|
||||||
if (binding?.mode === "router") {
|
if (binding?.mode === "router") {
|
||||||
const selected = await aiConnectionRouterService(db, manager).resolve({ companyId: agent.companyId,
|
const selected = await aiConnectionRouterService(db, manager).resolve({ companyId: agent.companyId,
|
||||||
@@ -102,7 +116,7 @@ export function agentHarnessVerificationService(db: Db, manager: PluginWorkerMan
|
|||||||
binding = selected.binding;
|
binding = selected.binding;
|
||||||
config = { ...config, ...selected.runtimeConfig };
|
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;
|
config = (await secrets.resolveAdapterConfigForRuntime(agent.companyId, config, context, { adapterType: agent.adapterType })).config;
|
||||||
let runner: Record<string, unknown> | null = providerApi ? { kind: "provider_api" } : { kind: "local", version: serverVersion };
|
let runner: Record<string, unknown> | 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");
|
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.
|
// Run admission refuses these agents before any lease, so verification must too.
|
||||||
const preconfiguredHome = agent.adapterType === "paperclip_runner" && config.homeMode === "preconfigured";
|
const preconfiguredHome = agent.adapterType === "paperclip_runner" && config.homeMode === "preconfigured";
|
||||||
if (agent.adapterType === "paperclip_runner" && environment && (preconfiguredHome || !binding)
|
if (environment && requiresPluginRunnerAiConnection({
|
||||||
&& await pluginEnvironmentRunnerTaskDriver(db, environment)) throw pluginRunnerAiConnectionRequiredFailure(preconfiguredHome);
|
adapterType: agent.adapterType,
|
||||||
const env = Object.fromEntries(Object.entries(binding ? stripAiAuthBindings(environment?.envVars) : parseObject(environment?.envVars))
|
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)));
|
.filter(([key]) => !isForbiddenConfigEnvKey(key)));
|
||||||
const resolved = await secrets.resolveEnvBindings(agent.companyId, env,
|
const resolved = await secrets.resolveEnvBindings(agent.companyId, env,
|
||||||
{ ...context, consumerType: "environment", consumerId: environmentId });
|
{ ...context, consumerType: "environment", consumerId: environmentId });
|
||||||
config = { ...config, env: { ...resolved.env, ...parseObject(config.env) } };
|
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<ReturnType<typeof getDefaultCloudTrialInferenceController>["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({
|
const selectAccount = () => aiConnectionService(db).select({
|
||||||
companyId: agent.companyId, userId: responsibleUserId, agentId: agent.id,
|
companyId: agent.companyId, userId: responsibleUserId, agentId: agent.id,
|
||||||
adapterType: agent.adapterType, model: config.model, runnerProvider: config.provider,
|
adapterType: agent.adapterType, model: config.model, runnerProvider: config.provider,
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ export function createCloudTrialProxy(keyStore: CloudTrialKeyStore) {
|
|||||||
agentId: string;
|
agentId: string;
|
||||||
runId: string;
|
runId: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
|
probeOnly?: boolean;
|
||||||
},
|
},
|
||||||
): Promise<PreparedCloudTrialRuntime> {
|
): Promise<PreparedCloudTrialRuntime> {
|
||||||
const effective = await resolveEffectiveOnboardingConfig(db, keyStore);
|
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 serverOrigin = (env.PAPERCLIP_API_URL?.trim() || "http://127.0.0.1:3100").replace(/\/+$/, "");
|
||||||
const proxyUrl = `${serverOrigin}/api/internal/cloud-inference/v1`;
|
const proxyUrl = `${serverOrigin}/api/internal/cloud-inference/v1`;
|
||||||
const token = `${RUN_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
|
const token = `${RUN_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
|
||||||
|
if (!input.probeOnly) {
|
||||||
keyStore.recordRunPrepared();
|
keyStore.recordRunPrepared();
|
||||||
|
}
|
||||||
|
|
||||||
activeRunTokens.set(token, {
|
activeRunTokens.set(token, {
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -22,7 +22,12 @@ import { isAgentUsingCloudTrialInference } from "@paperclipai/shared";
|
|||||||
import { managedAiSessionIdentityCompatible } from "../ai-connection-session.js";
|
import { managedAiSessionIdentityCompatible } from "../ai-connection-session.js";
|
||||||
import type { companySkillService } from "../company-skills.js";
|
import type { companySkillService } from "../company-skills.js";
|
||||||
import { connectionIntentService } from "../connection-intents.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 { prepareConnectionInstructionDelivery } from "../connection-instructions.js";
|
||||||
import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "../connector-runtime.js";
|
import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "../connector-runtime.js";
|
||||||
import { resolveManagedGitHubIdentitySelection } from "../git-credentials.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` },
|
configurationIncomplete: { reason: "skill_unavailable", actionUrl: `/agents/${agent.id}/runtime` },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// A plugin Runner-task environment runs only managed AI connections. Refuse a new
|
// A plugin Runner-task environment runs only managed AI connections or Cloud
|
||||||
// admission before secrets, leases, or provider calls. Resumed native input keeps
|
// starter-trial inference. Refuse a new admission before secrets, leases, or
|
||||||
// the contract it was admitted under.
|
// provider calls. Resumed native input keeps the contract it was admitted under.
|
||||||
if (agent.adapterType === "paperclip_runner" && (preconfiguredHome || !input.config.aiBinding) && !persistedNativeExecutionInput
|
if (requiresPluginRunnerAiConnection({
|
||||||
|
adapterType: agent.adapterType,
|
||||||
|
preconfiguredHome,
|
||||||
|
hasAiBinding: Boolean(input.config.aiBinding),
|
||||||
|
runtimeConfig: agent.runtimeConfig,
|
||||||
|
}) && !persistedNativeExecutionInput
|
||||||
&& selectedEnvironmentForConfig && await pluginEnvironmentRunnerTaskDriver(db, selectedEnvironmentForConfig)) {
|
&& selectedEnvironmentForConfig && await pluginEnvironmentRunnerTaskDriver(db, selectedEnvironmentForConfig)) {
|
||||||
throw new ConfigurationIncompleteFailure(pluginRunnerAiConnectionRequiredMessage(preconfiguredHome), {
|
throw new ConfigurationIncompleteFailure(pluginRunnerAiConnectionRequiredMessage(preconfiguredHome), {
|
||||||
configurationIncomplete: { reason: PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, actionUrl: `/agents/${agent.id}/runtime`,
|
configurationIncomplete: { reason: PLUGIN_RUNNER_AI_CONNECTION_REQUIRED, actionUrl: `/agents/${agent.id}/runtime`,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
|
import type { AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
|
||||||
import type { Db } from "@paperclipai/db";
|
import type { Db } from "@paperclipai/db";
|
||||||
|
import { isAgentUsingCloudTrialInference } from "@paperclipai/shared";
|
||||||
import { parseEnvironmentDriverConfig } from "./environment-config.js";
|
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;
|
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
|
// The plugin's manifest declaration decides whether its environment runs
|
||||||
// Runner tasks. Run admission separately verifies a ready plugin and a live
|
// 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.
|
// worker, so a plugin that is down still selects the Runner and fails its run.
|
||||||
|
|||||||
Reference in new issue
Block a user