mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-27 11:20:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents run via per-adapter execute paths; the `cursor_cloud` adapter runs the agent in Cursor's cloud (remote), orchestrated server-side via the Cursor Agent SDK > - Local adapters receive a run-scoped Paperclip JWT (`supportsLocalAgentJwt=true`) injected as `PAPERCLIP_API_KEY` so the agent can call the Paperclip API; `cursor_cloud` is intentionally `supportsLocalAgentJwt=false` (no JWT minted for a remote worker) > - But `buildPaperclipEnv` always sets `PAPERCLIP_API_URL` (defaulting to the local runtime host), so the remote cloud worker is handed a callback URL it can neither reach nor authenticate against > - Any agent-initiated Paperclip API call from the cloud worker therefore fails with a 401 (or is unreachable), producing log noise and confusing failures > - This pull request drops the callback wiring when there is no usable key, so cloud-side Paperclip tools degrade to a clean no-op > - The benefit is no spurious 401s from remote cloud runs, with run results unaffected (delivered server-side via the Cursor Agent SDK) ## Linked Issues or Issue Description No existing public issue — describing the bug inline (per `.github/ISSUE_TEMPLATE/bug_report.yml`): **What happened** `cursor_cloud` runs emit 401s when the remote cloud agent attempts Paperclip API calls. Root cause: `buildPaperclipEnv` (`packages/adapter-utils/src/server-utils.ts`) always sets `PAPERCLIP_API_URL` (local runtime default), while `cursor_cloud` has `supportsLocalAgentJwt=false`, so no `PAPERCLIP_API_KEY` is minted — URL present, key absent → 401 / unreachable from `buildWakeEnv` in `packages/adapters/cursor-cloud/src/server/execute.ts`. **Expected behavior** A remote cloud worker that is not issued a run JWT should not attempt (and fail) Paperclip API callbacks. **Steps to reproduce** 1. Configure a `cursor_cloud` agent (runs in Cursor's cloud; `supportsLocalAgentJwt=false`). 2. Trigger a run that causes the cloud agent to make a Paperclip API call. 3. Observe a 401 (or unreachable) because `PAPERCLIP_API_URL` points at an unreachable local runtime and no key is present. **Paperclip version** Reproduced on current `master` (cutover base `e68188c43`). **Deployment mode** Self-hosted control plane, `cursor_cloud` adapter (remote execution in Cursor's cloud). **Related PRs (searched; none duplicate this fix):** - #8197 — `claude_local` opt-out of the sandbox *bridge* for direct-reachable remote SSH targets. Related family, but the opposite situation: that path keeps the callback because the remote is reachable **and** has a run token. `cursor_cloud` has neither, so here the callback is removed. - #8130, #4794, #8025 — `PAPERCLIP_API_URL`/loopback injection for **local** agents (distinct from the remote cloud worker case). - #401 — alternative agent-auth scheme (run-ID header when no bearer token); different approach, not overlapping with this targeted fix. ## What Changed - `packages/adapters/cursor-cloud/src/server/execute.ts`: in `buildWakeEnv`, when there is no usable `PAPERCLIP_API_KEY`, delete `PAPERCLIP_API_URL` and `PAPERCLIP_API_BRIDGE_MODE` so the remote worker performs no Paperclip API callbacks. Informational `PAPERCLIP_*` vars (run id, agent id, company id, task, wake reason) still flow. When a key *is* present (operator-provided), the URL is retained. - `packages/adapters/cursor-cloud/src/server/execute.test.ts`: new test asserting no callback vars are injected when no run JWT is present; positive assertion that the URL is retained when a key is present. ## Verification - `pnpm exec vitest run packages/adapters/cursor-cloud/src/server/execute.test.ts` → **5/5 pass**. - `pnpm --filter @paperclipai/adapter-cursor-cloud typecheck` → **green**. - Confirmed result delivery does not depend on this callback: `execute()` reads results server-side via `Agent.getRun()` and `run.wait()`. ## Risks - **Low risk.** Only affects the env handed to remote `cursor_cloud` workers. No schema/migration/behavioral change to result delivery (which is server-side). When an operator explicitly provides `PAPERCLIP_API_KEY`, the callback URL is retained, preserving intentional callback setups. ## Model Used - **Claude Opus 4.8** (Anthropic), extended/high reasoning mode, via the Cursor agent with tool use + code execution. Diagnosis grounded in the adapter/runtime code. ## 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 (none found) - [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 references) - [x] My branch name describes the change (`fix/cursor-cloud-skip-unreachable-callback`) 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 - [ ] I have updated relevant documentation to reflect my changes (N/A — no documented behavior changes) - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green (pending CI run) - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (pending review) - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Sebastian Heyneman <sebastian@joinnova.com> Co-authored-by: Cursor <cursoragent@cursor.com>
375 lines
11 KiB
TypeScript
375 lines
11 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
|
|
import { execute } from "./execute.js";
|
|
|
|
type MockRunOptions = {
|
|
id?: string;
|
|
agentId?: string;
|
|
status?: string;
|
|
waitResult?: Record<string, unknown>;
|
|
streamMessages?: unknown[];
|
|
streamError?: Error | null;
|
|
};
|
|
|
|
type MockAgentOptions = {
|
|
agentId?: string;
|
|
sendRun?: ReturnType<typeof createMockRun>;
|
|
};
|
|
|
|
const { createMock, resumeMock, getRunMock } = vi.hoisted(() => ({
|
|
createMock: vi.fn(),
|
|
resumeMock: vi.fn(),
|
|
getRunMock: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("@cursor/sdk", () => ({
|
|
Agent: {
|
|
create: createMock,
|
|
resume: resumeMock,
|
|
getRun: getRunMock,
|
|
},
|
|
}));
|
|
|
|
function createMockRun(options: MockRunOptions = {}) {
|
|
const runId = options.id ?? "run-123";
|
|
const agentId = options.agentId ?? "agent-123";
|
|
const status = options.status ?? "finished";
|
|
const waitResult = options.waitResult ?? {
|
|
id: runId,
|
|
status,
|
|
result: "Done\nWith detail",
|
|
model: { id: "gpt-5.4" },
|
|
durationMs: 1234,
|
|
};
|
|
const streamMessages = options.streamMessages ?? [];
|
|
const streamError = options.streamError ?? null;
|
|
|
|
return {
|
|
id: runId,
|
|
agentId,
|
|
status,
|
|
result: typeof waitResult.result === "string" ? waitResult.result : null,
|
|
model: waitResult.model ?? null,
|
|
durationMs: waitResult.durationMs ?? null,
|
|
git: waitResult.git ?? null,
|
|
supports(capability: string) {
|
|
return capability === "stream" || capability === "wait";
|
|
},
|
|
async *stream() {
|
|
for (const message of streamMessages) yield message;
|
|
if (streamError) throw streamError;
|
|
},
|
|
async wait() {
|
|
return waitResult;
|
|
},
|
|
};
|
|
}
|
|
|
|
function createMockSdkAgent(options: MockAgentOptions = {}) {
|
|
const sendRun = options.sendRun ?? createMockRun();
|
|
return {
|
|
agentId: options.agentId ?? sendRun.agentId,
|
|
send: vi.fn(async () => sendRun),
|
|
[Symbol.asyncDispose]: vi.fn(async () => {}),
|
|
};
|
|
}
|
|
|
|
function createContext(
|
|
overrides: Partial<AdapterExecutionContext> = {},
|
|
): AdapterExecutionContext & {
|
|
logs: Array<{ stream: "stdout" | "stderr"; chunk: string }>;
|
|
meta: Record<string, unknown>[];
|
|
} {
|
|
const logs: Array<{ stream: "stdout" | "stderr"; chunk: string }> = [];
|
|
const meta: Record<string, unknown>[] = [];
|
|
const agent = overrides.agent ?? {
|
|
id: "agent-1",
|
|
companyId: "company-1",
|
|
name: "Cursor Cloud Agent",
|
|
adapterType: "cursor_cloud",
|
|
adapterConfig: {},
|
|
};
|
|
const runtime = overrides.runtime ?? {
|
|
sessionId: null,
|
|
sessionParams: null,
|
|
sessionDisplayId: null,
|
|
taskKey: null,
|
|
};
|
|
const config = overrides.config ?? {
|
|
env: {
|
|
CURSOR_API_KEY: "cursor-secret",
|
|
EXTRA_FLAG: "1",
|
|
},
|
|
repoUrl: "https://github.com/paperclipai/paperclip.git",
|
|
repoStartingRef: "main",
|
|
runtimeEnvType: "cloud",
|
|
promptTemplate: "Do the work for {{agent.name}}",
|
|
model: "gpt-5.4",
|
|
};
|
|
const context = overrides.context ?? {
|
|
taskId: "issue-1",
|
|
issueId: "issue-1",
|
|
wakeReason: "issue_commented",
|
|
};
|
|
|
|
const base: AdapterExecutionContext = {
|
|
runId: "run-heartbeat-1",
|
|
agent,
|
|
runtime,
|
|
config,
|
|
context,
|
|
authToken: "paperclip-run-jwt",
|
|
onLog: async (stream, chunk) => {
|
|
logs.push({ stream, chunk });
|
|
},
|
|
onMeta: async (entry) => {
|
|
meta.push(entry as unknown as Record<string, unknown>);
|
|
},
|
|
};
|
|
|
|
return {
|
|
...base,
|
|
...overrides,
|
|
logs,
|
|
meta,
|
|
};
|
|
}
|
|
|
|
describe("cursor_cloud execute", () => {
|
|
beforeEach(() => {
|
|
createMock.mockReset();
|
|
resumeMock.mockReset();
|
|
getRunMock.mockReset();
|
|
});
|
|
|
|
it("creates a fresh Cursor agent and injects Paperclip env without CURSOR_API_KEY", async () => {
|
|
const run = createMockRun({
|
|
agentId: "agent-fresh",
|
|
streamMessages: [
|
|
{
|
|
type: "assistant",
|
|
message: {
|
|
content: [{ type: "text", text: "Working" }],
|
|
},
|
|
},
|
|
],
|
|
});
|
|
const sdkAgent = createMockSdkAgent({ agentId: "agent-fresh", sendRun: run });
|
|
createMock.mockResolvedValue(sdkAgent);
|
|
const ctx = createContext();
|
|
|
|
const result = await execute(ctx);
|
|
|
|
expect(createMock).toHaveBeenCalledTimes(1);
|
|
expect(resumeMock).not.toHaveBeenCalled();
|
|
expect(getRunMock).not.toHaveBeenCalled();
|
|
expect(createMock.mock.calls[0]?.[0]).toMatchObject({
|
|
apiKey: "cursor-secret",
|
|
name: "Paperclip Cursor Cloud Agent",
|
|
model: { id: "gpt-5.4" },
|
|
cloud: {
|
|
env: { type: "cloud" },
|
|
repos: [{ url: "https://github.com/paperclipai/paperclip.git", startingRef: "main" }],
|
|
},
|
|
});
|
|
expect(createMock.mock.calls[0]?.[0]?.cloud?.envVars).toMatchObject({
|
|
EXTRA_FLAG: "1",
|
|
PAPERCLIP_RUN_ID: "run-heartbeat-1",
|
|
PAPERCLIP_TASK_ID: "issue-1",
|
|
PAPERCLIP_WAKE_REASON: "issue_commented",
|
|
PAPERCLIP_API_KEY: "paperclip-run-jwt",
|
|
});
|
|
// When a run JWT is present the callback URL is retained so the worker can
|
|
// authenticate its Paperclip API calls.
|
|
expect(createMock.mock.calls[0]?.[0]?.cloud?.envVars).toHaveProperty("PAPERCLIP_API_URL");
|
|
expect(createMock.mock.calls[0]?.[0]?.cloud?.envVars).not.toHaveProperty("CURSOR_API_KEY");
|
|
|
|
expect(result).toMatchObject({
|
|
exitCode: 0,
|
|
errorMessage: null,
|
|
sessionId: "agent-fresh",
|
|
model: "gpt-5.4",
|
|
summary: "Done",
|
|
sessionParams: {
|
|
cursorAgentId: "agent-fresh",
|
|
latestRunId: "run-123",
|
|
runtime: "cloud",
|
|
envType: "cloud",
|
|
repos: [{ url: "https://github.com/paperclipai/paperclip.git", startingRef: "main" }],
|
|
},
|
|
});
|
|
expect(ctx.logs.map((entry) => entry.chunk)).toEqual(
|
|
expect.arrayContaining([
|
|
expect.stringContaining('"type":"cursor_cloud.init"'),
|
|
expect.stringContaining('"type":"cursor_cloud.message"'),
|
|
expect.stringContaining('"type":"cursor_cloud.result"'),
|
|
]),
|
|
);
|
|
});
|
|
|
|
it("omits the Paperclip API callback when no run JWT is issued (remote worker cannot call home)", async () => {
|
|
const run = createMockRun({ agentId: "agent-no-jwt" });
|
|
const sdkAgent = createMockSdkAgent({ agentId: "agent-no-jwt", sendRun: run });
|
|
createMock.mockResolvedValue(sdkAgent);
|
|
// cursor_cloud is registered with supportsLocalAgentJwt=false, so heartbeat
|
|
// passes no authToken. A remote cloud worker must not receive a callback URL
|
|
// it can neither reach nor authenticate against (the source of 401 noise).
|
|
const ctx = createContext({ authToken: undefined });
|
|
|
|
await execute(ctx);
|
|
|
|
const envVars = (createMock.mock.calls[0]?.[0]?.cloud?.envVars ?? {}) as Record<string, string>;
|
|
expect(envVars).not.toHaveProperty("PAPERCLIP_API_KEY");
|
|
expect(envVars).not.toHaveProperty("PAPERCLIP_API_URL");
|
|
expect(envVars).not.toHaveProperty("PAPERCLIP_API_BRIDGE_MODE");
|
|
// Informational Paperclip env (non-credential) still flows through.
|
|
expect(envVars).toMatchObject({
|
|
PAPERCLIP_RUN_ID: "run-heartbeat-1",
|
|
PAPERCLIP_AGENT_ID: "agent-1",
|
|
PAPERCLIP_COMPANY_ID: "company-1",
|
|
});
|
|
});
|
|
|
|
it("resumes a matching saved session when no active run can be reattached", async () => {
|
|
getRunMock.mockResolvedValue(createMockRun({ status: "finished" }));
|
|
const resumedRun = createMockRun({ id: "run-resumed", agentId: "agent-resumed" });
|
|
const sdkAgent = createMockSdkAgent({ agentId: "agent-resumed", sendRun: resumedRun });
|
|
resumeMock.mockResolvedValue(sdkAgent);
|
|
const ctx = createContext({
|
|
runtime: {
|
|
sessionId: null,
|
|
sessionDisplayId: "agent-previous",
|
|
taskKey: null,
|
|
sessionParams: {
|
|
cursorAgentId: "agent-previous",
|
|
latestRunId: "run-previous",
|
|
runtime: "cloud",
|
|
envType: "cloud",
|
|
repos: [{ url: "https://github.com/paperclipai/paperclip.git", startingRef: "main" }],
|
|
},
|
|
},
|
|
});
|
|
|
|
const result = await execute(ctx);
|
|
|
|
expect(getRunMock).toHaveBeenCalledWith("run-previous", {
|
|
runtime: "cloud",
|
|
agentId: "agent-previous",
|
|
apiKey: "cursor-secret",
|
|
});
|
|
expect(resumeMock).toHaveBeenCalledTimes(1);
|
|
expect(createMock).not.toHaveBeenCalled();
|
|
expect(sdkAgent.send).toHaveBeenCalledTimes(1);
|
|
expect(result.sessionId).toBe("agent-resumed");
|
|
});
|
|
|
|
it("reattaches to an active run, drains it, then sends the heartbeat as a follow-up", async () => {
|
|
const attachedRun = createMockRun({
|
|
id: "run-attached",
|
|
agentId: "agent-attached",
|
|
status: "running",
|
|
waitResult: {
|
|
id: "run-attached",
|
|
status: "finished",
|
|
result: "Prior result",
|
|
model: { id: "gpt-5.4" },
|
|
},
|
|
streamMessages: [
|
|
{
|
|
type: "status",
|
|
status: "running",
|
|
message: "Still working",
|
|
},
|
|
],
|
|
});
|
|
getRunMock.mockResolvedValue(attachedRun);
|
|
const followUpRun = createMockRun({
|
|
id: "run-followup",
|
|
agentId: "agent-attached",
|
|
waitResult: {
|
|
id: "run-followup",
|
|
status: "finished",
|
|
result: "Follow-up result",
|
|
model: { id: "gpt-5.4" },
|
|
},
|
|
});
|
|
const sdkAgent = createMockSdkAgent({ agentId: "agent-attached", sendRun: followUpRun });
|
|
resumeMock.mockResolvedValue(sdkAgent);
|
|
const ctx = createContext({
|
|
runtime: {
|
|
sessionId: null,
|
|
sessionDisplayId: "agent-attached",
|
|
taskKey: null,
|
|
sessionParams: {
|
|
cursorAgentId: "agent-attached",
|
|
latestRunId: "run-attached",
|
|
runtime: "cloud",
|
|
envType: "cloud",
|
|
repos: [{ url: "https://github.com/paperclipai/paperclip.git", startingRef: "main" }],
|
|
},
|
|
},
|
|
});
|
|
|
|
const result = await execute(ctx);
|
|
|
|
expect(getRunMock).toHaveBeenCalledTimes(1);
|
|
expect(createMock).not.toHaveBeenCalled();
|
|
expect(resumeMock).toHaveBeenCalledTimes(1);
|
|
expect(sdkAgent.send).toHaveBeenCalledTimes(1);
|
|
expect(result).toMatchObject({
|
|
exitCode: 0,
|
|
sessionId: "agent-attached",
|
|
summary: "Follow-up result",
|
|
resultJson: {
|
|
cursorRunId: "run-followup",
|
|
},
|
|
});
|
|
const logChunks = ctx.logs.map((entry) => entry.chunk);
|
|
expect(logChunks).toEqual(
|
|
expect.arrayContaining([
|
|
expect.stringContaining("Reattached to existing Cursor run run-attached."),
|
|
expect.stringContaining("Prior Cursor run run-attached finished"),
|
|
expect.stringContaining("Started Cursor run run-followup."),
|
|
expect.stringContaining('"runId":"run-attached"'),
|
|
expect.stringContaining('"runId":"run-followup"'),
|
|
]),
|
|
);
|
|
expect(ctx.meta[0]?.context).toMatchObject({
|
|
cursorCloud: {
|
|
canReuseSession: true,
|
|
repoUrl: "https://github.com/paperclipai/paperclip.git",
|
|
},
|
|
});
|
|
});
|
|
|
|
it("maps non-finished Cursor results to failing Paperclip runs", async () => {
|
|
const cancelledRun = createMockRun({
|
|
id: "run-cancelled",
|
|
agentId: "agent-cancelled",
|
|
status: "cancelled",
|
|
waitResult: {
|
|
id: "run-cancelled",
|
|
status: "cancelled",
|
|
result: "",
|
|
model: { id: "gpt-5.4" },
|
|
},
|
|
});
|
|
const sdkAgent = createMockSdkAgent({ agentId: "agent-cancelled", sendRun: cancelledRun });
|
|
createMock.mockResolvedValue(sdkAgent);
|
|
const ctx = createContext();
|
|
|
|
const result = await execute(ctx);
|
|
|
|
expect(result).toMatchObject({
|
|
exitCode: 1,
|
|
errorMessage: "Cursor run cancelled",
|
|
sessionId: "agent-cancelled",
|
|
resultJson: {
|
|
status: "cancelled",
|
|
cursorAgentId: "agent-cancelled",
|
|
cursorRunId: "run-cancelled",
|
|
},
|
|
});
|
|
});
|
|
});
|