mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 20:12:20 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The scaling effort uses a real-agent ramp harness (`scripts/scale-agents-ramp.ts`, added in #21695) to load a hosted test instance through the product API > - Its first real run held a 20-minute step with 10 tasks, 10 queued runs and 0 started runs, and reported only "concurrency_reached failed (observed 0)" > - The cause was in the harness: it bound the agents to a plugin Runner-task environment, which runs only agents with a managed AI connection. Each agent stayed in setup (status `paused`, setup state `verifying`) with that reason, so each run stayed queued. The product did what it is designed to do > - The harness did not wait for agent setup, did not read the setup error, and held the full step with nothing running. Its fake API created agents ready at once, so its tests could not catch this > - This pull request makes the harness wait for agent setup, gate the ramp on one started run, and stop within minutes with Paperclip's own reason > - The benefit is that a wrong environment or any other start blocker costs about one minute and prints the cause, not a 20-minute step with no explanation ## Linked Issues or Issue Description Refs #21695 **What happened?** A ramp of 10 then 50 agents on a hosted test stack created 10 agents, 10 tasks and 10 runs. In 20 minutes no run started. The result said only "concurrency_reached failed (observed 0)". Cleanup found every agent already paused and cancelled 10 queued runs. The tasks never left `todo` (status version 1, no checkout run). The agents were bound to the "Paperclip Sandbox (Daytona)" plugin environment, whose `daytona-tasks` driver declares `supportsTasks: true`. For such an environment, lifecycle verification refuses a `paperclip_runner` agent that has no `runtimeConfig.aiConnection` (`ai_connection_required`, see `server/src/services/agent-harness-verification.ts` and its test "refuses a plugin Runner-task agent without a managed AI connection before allocating a target"). The failure pauses automatic verification, so the agents never become ready. **Expected behavior** The harness must not create a full step of work before agents can run. When agents cannot finish setup, or when no run starts, it must stop soon, print the task, run and agent state with Paperclip's reason, and clean up. **Steps to reproduce** 1. Run `node --test scripts/scale-ramp/scale-ramp.test.ts` with the new fake (agents start in setup; `agentSetupError` keeps them there) and the old `ramp.ts`, `setup.ts` and `config.ts`. 2. The new test "stops within minutes with Paperclip's reason when the agents never finish setup" fails with `concurrency_reached`, the same result as the real run. 3. With this change, it stops with `agents_ready` and the setup reason in under 5 virtual minutes. **Paperclip version or commit** Instance on `2026.1106.0+2555.git.819f61f1f` (master at 11:34Z on 2026-11-15); harness from #21695. ## What Changed - `setup.ts`: add `waitForAgentsReady`, `agentReady` and `describeAgent`. The harness reads the company agent list until each agent has setup state `ready` and is not paused. It stops when an agent reports a setup error for 60 s, or after `--agent-ready-minutes` (default 10), and prints the agent's status, setup state, holds and Paperclip's reason. - `ramp.ts`: before the first step, a preflight creates one agent and one task and creates the rest only after that task's run starts. A new check stops the ramp when no run has started within `--start-timeout-minutes` (default 5) of the first task. The stop reason names the task status, any execution blocker, the run status, error code, error and liveness, and the agent's setup state. New stop criteria: `agents_ready` and `run_started`. Run records keep `error`, `errorCode` and `livenessReason`. - `config.ts`: add `--start-timeout-minutes` and `--agent-ready-minutes`. - `fake-paperclip.ts`: agents start as the real product creates them (status `paused`, setup state `preparing`) and become `ready` after `agentReadyDelayMs`, or stay in `verifying` with `agentSetupError`. Issue creation queues a run even for an agent in setup, as the real product does. Runs start only for a ready agent. - `scale-ramp.test.ts`: three tests. Agents that never finish setup stop the run with `agents_ready` and the reason, with one agent and no task created. A first task that never starts stops the run at the preflight with `run_started`, the task, run and agent state, and one cancelled run. The rest of a step is created only after the preflight task starts. - `doc/plans/2026-11-13-thousand-concurrent-agents.md`: the Phase 3 runbook describes the start checks, the first run's cause, and which environments the harness can use. ## Verification - `node --test scripts/scale-ramp/scale-ramp.test.ts`: 43 of 43 pass. - Red check: with the new fake and tests but the `origin/master` `ramp.ts`, `setup.ts` and `config.ts`, 3 tests fail. The setup test fails with `concurrency_reached` (the real run's result) where `agents_ready` is expected. - `tsc -p scripts/scale-ramp/tsconfig.json` (same options): no errors. - Read-only inspection of the hosted instance (GET only): task rows (`todo`, status version 1, no checkout run), activity (agent created, no pause, 10 `heartbeat.cancelled` at cleanup), the plugin manifest (`daytona-tasks` `supportsTasks: true`), and the company AI connections (no OpenRouter connection). The run and agent rows were deleted with the agents at cleanup, so their setup error was inferred from the code path and the cleanup counts, not read. - Not run: a new real ramp (needs the owner's go-ahead). ## Risks - Low risk. The change touches only the scale-ramp harness, its fake and its tests, and one runbook section. No product code changes. - A real ramp now spends up to one preflight start (seconds to minutes) before the first step. The preflight task is part of step 1 and the preflight running samples are dropped, so step metrics keep their meaning. - An agent whose setup error clears within 60 s does not stop the run. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, read-only HTTP GETs to the test instance). ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
230 lines
9.9 KiB
TypeScript
230 lines
9.9 KiB
TypeScript
import { ApiError, type Clock, type PaperclipClient } from "./client.ts";
|
|
import type { AgentProfile, Options } from "./config.ts";
|
|
import { agentName, companyName, mapLimit, projectName, secretPrefix, type RunState, type StateStore } from "./state.ts";
|
|
|
|
type Json = Record<string, any>;
|
|
|
|
export class SetupError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = "SetupError";
|
|
}
|
|
}
|
|
|
|
export async function resolveCompany(api: PaperclipClient, options: Pick<Options, "companyId" | "label">, state: RunState, store: StateStore): Promise<void> {
|
|
if (options.companyId) {
|
|
const me = await api.get<{ companyIds?: string[] }>("/api/cli-auth/me");
|
|
if (!(me.companyIds ?? []).includes(options.companyId)) throw new SetupError(`The signed-in board user is not a member of company ${options.companyId}`);
|
|
state.companyId = options.companyId;
|
|
await store.save(state);
|
|
return;
|
|
}
|
|
try {
|
|
const company = await api.post<{ id: string }>("/api/companies", {
|
|
name: companyName(options.label),
|
|
description: `Scale ramp ${options.label}. Created and archived by scripts/scale-agents-ramp.ts.`,
|
|
});
|
|
state.companyId = String(company.id);
|
|
state.companyCreated = true;
|
|
await store.save(state);
|
|
} catch (error) {
|
|
if (error instanceof ApiError && error.status === 403) {
|
|
throw new SetupError(`This instance does not let the harness create a company (${error.code ?? "forbidden"}); pass --company <id> or PAPERCLIP_SCALE_COMPANY_ID`);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function pickEnvironment(api: PaperclipClient, companyId: string, requested: string | null, allowLocal: boolean): Promise<string> {
|
|
const environments = await api.get<Json[]>(`/api/companies/${companyId}/environments`);
|
|
if (requested) {
|
|
if (!environments.some(environment => environment.id === requested)) throw new SetupError(`Environment ${requested} is not in the company`);
|
|
return requested;
|
|
}
|
|
const active = environments.filter(environment => environment.status !== "archived" && (allowLocal || environment.driver !== "local"));
|
|
const sandboxes = active.filter(environment => environment.driver === "sandbox");
|
|
const candidates = sandboxes.length ? sandboxes : active;
|
|
if (candidates.length !== 1) {
|
|
throw new SetupError(`The company has ${candidates.length} usable environments; pass --environment <id>`);
|
|
}
|
|
return String(candidates[0]!.id);
|
|
}
|
|
|
|
export const AGENT_INSTRUCTIONS = [
|
|
"You are a load-test worker for a Paperclip scale ramp.",
|
|
"Follow the assigned task literally and in order. Keep every reply short.",
|
|
"Use only the runtime's real tool-call channel for tools. Never print tool-call markup as text.",
|
|
"Never print, store or expose credential values. Never create other tasks, documents or agents.",
|
|
].join("\n");
|
|
|
|
export function agentPayload(input: { label: string; index: number; environmentId: string; profile: AgentProfile; secretId: string | null }): Json {
|
|
const { profile } = input;
|
|
const env = profile.credentialKey && input.secretId
|
|
? { [profile.credentialKey]: { type: "secret_ref", secretId: input.secretId, version: "latest" } }
|
|
: {};
|
|
return {
|
|
name: agentName(input.label, input.index),
|
|
role: "qa",
|
|
title: "Scale ramp worker",
|
|
capabilities: "Runs one small deterministic task at a time for a load test.",
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: {
|
|
provider: profile.provider,
|
|
model: profile.model,
|
|
lifecycleMode: "warm",
|
|
idleTimeoutMs: 300_000,
|
|
...(profile.provider === "opencode" ? { opencodePermissionMode: "allow" } : {}),
|
|
env,
|
|
...profile.adapterOverrides,
|
|
},
|
|
defaultEnvironmentId: input.environmentId,
|
|
budgetMonthlyCents: 0,
|
|
runtimeConfig: { heartbeat: { enabled: false, maxConcurrentRuns: 1 } },
|
|
instructionsBundle: { entryFile: "AGENTS.md", files: { "AGENTS.md": AGENT_INSTRUCTIONS } },
|
|
};
|
|
}
|
|
|
|
export async function prepareCompany(input: {
|
|
api: PaperclipClient;
|
|
options: Options;
|
|
state: RunState;
|
|
store: StateStore;
|
|
credential: string | null;
|
|
log: (line: string) => void;
|
|
}): Promise<void> {
|
|
const { api, options, state, store } = input;
|
|
await resolveCompany(api, options, state, store);
|
|
const companyId = state.companyId!;
|
|
state.environmentId = await pickEnvironment(api, companyId, options.environmentId, options.target.kind === "local");
|
|
await store.save(state);
|
|
const profile = options.profile;
|
|
if (profile.credentialKey && !profile.providerSecretId) {
|
|
if (!input.credential) throw new SetupError(`Set ${profile.credentialKey} in the environment, or PAPERCLIP_SCALE_PROVIDER_SECRET_ID to reuse a stored secret`);
|
|
const secret = await api.post<{ id: string }>(`/api/companies/${companyId}/secrets`, {
|
|
name: `${secretPrefix(options.label)}${profile.credentialKey}`,
|
|
value: input.credential,
|
|
description: `Scale ramp ${options.label}; deleted at cleanup`,
|
|
});
|
|
state.secretId = String(secret.id);
|
|
await store.save(state);
|
|
}
|
|
const project = await api.post<{ id: string }>(`/api/companies/${companyId}/projects`, {
|
|
name: projectName(options.label),
|
|
description: `Scale ramp ${options.label}. Created and archived by scripts/scale-agents-ramp.ts.`,
|
|
});
|
|
state.projectId = String(project.id);
|
|
await store.save(state);
|
|
input.log(`Prepared company ${companyId}: environment ${state.environmentId}, project ${state.projectId}`);
|
|
}
|
|
|
|
export async function ensureAgents(input: {
|
|
api: PaperclipClient;
|
|
options: Options;
|
|
state: RunState;
|
|
store: StateStore;
|
|
count: number;
|
|
}): Promise<void> {
|
|
const { api, options, state, store } = input;
|
|
const secretId = options.profile.providerSecretId ?? state.secretId;
|
|
const start = state.agentIds.length;
|
|
const indices = Array.from({ length: Math.max(0, input.count - start) }, (_, offset) => start + offset);
|
|
await mapLimit(indices, AGENT_CREATE_PARALLELISM, async index => {
|
|
const created = await api.post<{ id: string }>(`/api/companies/${state.companyId}/agents`, agentPayload({
|
|
label: options.label, index, environmentId: state.environmentId!, profile: options.profile, secretId,
|
|
}));
|
|
state.agentIds.push(String(created.id));
|
|
await store.save(state);
|
|
});
|
|
}
|
|
|
|
export const AGENT_CREATE_PARALLELISM = 8;
|
|
export const LIFECYCLE_ERROR_GRACE_MS = 60_000;
|
|
export const AGENT_LIST_FAILURE_LIMIT = 5;
|
|
|
|
export class AgentsNotReady extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = "AgentsNotReady";
|
|
}
|
|
}
|
|
|
|
const NOT_INVOKABLE = new Set(["paused", "terminated", "pending_approval"]);
|
|
|
|
export function agentReady(agent: Json): boolean {
|
|
if (agent.lifecycleState === "ready") return !NOT_INVOKABLE.has(String(agent.status));
|
|
return agent.lifecycleState == null && ["idle", "active", "running", "error"].includes(String(agent.status));
|
|
}
|
|
|
|
export function describeAgent(agent: Json): string {
|
|
const parts = [`agent ${agent.name ?? agent.id} is ${agent.status ?? "missing"}`];
|
|
if (agent.lifecycleState) parts.push(`setup state ${agent.lifecycleState}`);
|
|
if (agent.pauseReason) parts.push(`pause reason ${agent.pauseReason}`);
|
|
if (Array.isArray(agent.lifecycleHolds) && agent.lifecycleHolds.length) parts.push(`holds ${agent.lifecycleHolds.join(", ")}`);
|
|
const reason = agent.lifecycleError ?? agent.errorReason;
|
|
return `${parts.join(", ")}; ${reason ? `Paperclip says: ${String(reason).slice(0, 400)}` : "Paperclip gave no reason"}`;
|
|
}
|
|
|
|
export async function waitForAgentsReady(input: {
|
|
api: PaperclipClient;
|
|
clock: Clock;
|
|
companyId: string;
|
|
agentIds: readonly string[];
|
|
timeoutMs: number;
|
|
pollMs: number;
|
|
shouldStop: () => boolean;
|
|
log: (line: string) => void;
|
|
tick?: () => Promise<boolean>;
|
|
}): Promise<boolean> {
|
|
const { api, clock } = input;
|
|
const started = clock.now();
|
|
const erroredSince = new Map<string, number>();
|
|
let logged = false;
|
|
let readFailures = 0;
|
|
for (;;) {
|
|
if (input.shouldStop()) return false;
|
|
let listed: Json[];
|
|
try {
|
|
listed = await api.get<Json[]>(`/api/companies/${input.companyId}/agents`);
|
|
readFailures = 0;
|
|
} catch (error) {
|
|
readFailures += 1;
|
|
if (input.shouldStop()) return false;
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
if (readFailures >= AGENT_LIST_FAILURE_LIMIT) {
|
|
throw new AgentsNotReady(`the agent list could not be read ${readFailures} times in a row while waiting for agent setup: ${message.slice(0, 300)}`);
|
|
}
|
|
if (clock.now() - started >= input.timeoutMs) {
|
|
throw new AgentsNotReady(`agent setup could not be checked within ${Math.round(input.timeoutMs / 60_000)} min: ${message.slice(0, 300)}`);
|
|
}
|
|
await clock.sleep(input.pollMs);
|
|
continue;
|
|
}
|
|
const byId = new Map(listed.map(agent => [String(agent.id), agent]));
|
|
const waiting = input.agentIds.map(id => byId.get(id) ?? { id, status: null }).filter(agent => !agentReady(agent));
|
|
if (!waiting.length) {
|
|
if (logged) input.log(`All ${input.agentIds.length} agents finished setup after ${Math.round((clock.now() - started) / 1_000)} s`);
|
|
return true;
|
|
}
|
|
if (input.shouldStop() || await input.tick?.()) return false;
|
|
const now = clock.now();
|
|
for (const agent of waiting) {
|
|
const id = String(agent.id);
|
|
if (agent.lifecycleError) {
|
|
if (!erroredSince.has(id)) erroredSince.set(id, now);
|
|
} else erroredSince.delete(id);
|
|
}
|
|
const stuck = waiting.find(agent => now - (erroredSince.get(String(agent.id)) ?? now) >= LIFECYCLE_ERROR_GRACE_MS);
|
|
if (stuck) {
|
|
throw new AgentsNotReady(`${waiting.length} of ${input.agentIds.length} agents cannot finish setup: ${describeAgent(stuck)}`);
|
|
}
|
|
if (now - started >= input.timeoutMs) {
|
|
throw new AgentsNotReady(`${waiting.length} of ${input.agentIds.length} agents did not finish setup within ${Math.round(input.timeoutMs / 60_000)} min: ${describeAgent(waiting[0]!)}`);
|
|
}
|
|
if (!logged) {
|
|
input.log(`Waiting for ${waiting.length} agents to finish setup (${describeAgent(waiting[0]!)})`);
|
|
logged = true;
|
|
}
|
|
await clock.sleep(input.pollMs);
|
|
}
|
|
}
|