mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-04 11:01:16 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Runner gives each provider durable execution, tool, and completion contracts. > - Cursor Cloud currently has a direct adapter outside that native contract. > - Cloud work needs exact ownership across HTTP, SSE, Stop, and recovery. > - This PR adds a qualified Cloud API driver and verified proxy to Runner. > - Product setup and hosted placement remain separate dependent changes. ## Linked Issues or Issue Description Refs #5664, #11803, #17299, and #17471. Product integration is #18069. Managed-only API placement is #18310. The related direct-adapter model/transcript work is not replaced. No duplicate native Cursor Cloud integration was found. ## What Changed - Add native `cursor_cloud` / `cursor_cloud_api` with explicit model/repository validation, bounded HTTP/SSE, durable per-turn checkpoints and a qualified Node proxy launched through the Rust facade. - Commit terminal custody before publication/release; coalesce consumers, preserve ambiguous create/Stop/recovery fences, reject late tools, and distinguish definitely-unsent oversized requests from ambiguous responses. - Support scoped cold attachment, current authority, reconnect and verified artifact staging. Keep unsupported warm/external and Windows paths closed. - Preserve early source cursors and verify immutable legacy prefixes before suffix replay, including supported compaction/masking. Optional proof publication failure falls back to complete cold verification. - Preserve canonical records at the durable native producer with JSON-safe privacy and the existing 8MiB bound; drain admitted successor flushes. Reconcile upstream semantic/pack/schema/lifecycle changes and retain S3 and legacy CLI checks. ## Verification Core head `37c442ec8dd4`: all 66 check contexts are terminal successful/neutral/skipped, including required `ci / verify` and `ci / e2e`; fresh exact-head Greptile is 5/5 with zero unresolved threads. Dependent Product `81e828d20a77` and Top `dd2959689627` include the later client handoff correction and are running their own fresh gates. Core: 47/47 Rust, 4/4 compiled-native retirement, 19/19 settlement and normal Runner build passed. Runtime Top `9af1a5de42a2`: build and recursive typecheck passed. Earlier source-scoped evidence includes 398 focused tests, five relay tests and token/type gates. The 251-assertion, 7/8-suite run failed physical PostgreSQL teardown; the unchanged stable WSP suite passed 128 through the documented wrapper. The downstream fixture corrections passed 7/7 browser and 121/121 startup tests without timeout/oracle relaxation; a broken-unsubscribe control fails. Hosted runtime `9af1a5de42a2` has a passing normal build and recursive typecheck. Latest dependent heads additionally contain a pure client fix for stale live/history overlap, with 48 focused tests, UI typecheck and token gates passing. Its new client is not deployed in the frozen hosted image; server/native/API/provider source is unchanged by these four downstream files. Fresh hosted Linux admission on `9af1a5de42a2` retired its owned runner/proxy/socket with zero prompts. The saved configuration survived reopening, and Test authenticated the bound key/catalog/selected model without a prompt. Artifact with `claude-sonnet-4-5` completed, downloaded the exact 27 bytes, matched 121 canonical identities against complete logs and independently reached FINISHED. The active Stop retry was clicked within its immutable boundary, produced one canonical interrupted turn and acknowledged run-only cancellation, retained a valid 35.076s quiet window (maximum gap 4.584s), and independently remained CANCELLED/artifact-absent beyond the original 180-second command deadline. All provider-observer credential callbacks, DB clients and loaders closed; accounting is settled and explicitly unpriced. The first fresh Stop retains its failed 10.373s sampling gap and every sample. On the upgraded9af server, the historical F226 artifact was reopened and downloaded with its exact original hash after its provider agent had been deleted/GET404 earlier today. Historical F226 full Artifact/Stop cleanup, Question, corrected Plan and reconnect retain their original identities. Deleting the three newly created disposable provider agents and the new-case post-delete grade remain blocked on explicit user approval after automatic review rejected expanding the two original approved IDs. No new-case cleanup or complete fresh matrix pass is claimed; this is separate from the directly observed task/Stop behavior and retained exact cleanup proof. Retained failures: stale fixture 132/133; E8 48/135 with 87 reset-hook failures; Mac 17 SQL failures/skips; earlier startup-title, title-save, custody/Stop and deletion failures with unknown causes and bounded recoveries. `dea023` Artifact passed 17 checks but Stop failed its false warning and 50 duplicate log identities. Pre-repair ACK failure and original Core CI failure remain recorded; retry alone establishes no cause or full local-suite pass. Provider dollar cost stays UNKNOWN. ## Risks Experimental: Cursor independently acknowledges neither the effective model nor instruction digest before the first prompt. The caller’s explicit values are submitted and behavior checked live. Unpriced provider dollar cost stays UNKNOWN. Only qualified per-turn controllers are admitted. Uncertain work and incomplete cleanup stay fenced. Existing damaged/duplicate archives remain failed evidence. Prefix proof adds bounded object-store I/O; the 8MiB producer bound does not guarantee future providers’ output fits. ## Model Used OpenAI Codex, GPT-6 family, assisted with reasoning, repository tools, code execution, browser verification, and delegated code review. The serving model’s exact API ID and context window are not exposed. No value is inferred from the model catalog. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used and the limits of available model metadata - [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 linked public issues or described the issue in this PR - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch describes the change and contains no internal ticket ID - [x] I have run the scoped local tests reported above; pending gates are stated separately - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented the risks - [x] All required CI gates pass on the current head - [x] Fresh Greptile is 5/5 with no unresolved findings on the current head - [x] I will address all reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
115 lines
6.2 KiB
TypeScript
115 lines
6.2 KiB
TypeScript
import { execFileSync, spawn } from "node:child_process";
|
|
import { closeSync, openSync } from "node:fs";
|
|
import { chmod, copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
import { randomUUID } from "node:crypto";
|
|
import { tmpdir } from "node:os";
|
|
import { join, resolve } from "node:path";
|
|
import { createInterface } from "node:readline";
|
|
|
|
import { expect, it } from "vitest";
|
|
|
|
// runnerd rejects any provider stdout line above CODEX_APP_SERVER_MAX_FRAME_BYTES.
|
|
const RUNNERD_MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
const MODEL = "openrouter/deepseek/deepseek-v4-flash-0731";
|
|
|
|
type RpcFrame = { id?: string | number; method?: string; result?: unknown; error?: unknown };
|
|
|
|
async function startProxy(root: string, proxy: string, executable: string, runtime: string) {
|
|
const launchRoot = join(root, `.paperclip-verified-executable-${randomUUID().replaceAll("-", "")}`);
|
|
await mkdir(launchRoot, { mode: 0o700 });
|
|
await chmod(launchRoot, 0o700);
|
|
const snapshot = join(launchRoot, "launch");
|
|
await copyFile(executable, snapshot);
|
|
await chmod(snapshot, 0o500);
|
|
expect(await readFile(snapshot)).toEqual(await readFile(executable));
|
|
const fd = process.platform === "linux" ? openSync(snapshot, "r") : undefined;
|
|
const child = spawn(process.execPath, [proxy, "--paperclip-trusted-opencode-executable", fd === undefined ? snapshot : "/proc/self/fd/3"], {
|
|
// Keep an enclosing Paperclip run's launch bindings out of this fixture.
|
|
env: { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("PAPERCLIP_"))),
|
|
PAPERCLIP_OPENCODE_RUNTIME_DIR: runtime, OPENROUTER_API_KEY: "fixture-key",
|
|
PAPERCLIP_RUN_ID: "resume-frame-run", PAPERCLIP_NORMALIZED_SESSION_ID: "resume-frame-session" },
|
|
stdio: fd === undefined ? ["pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe", fd],
|
|
detached: process.platform !== "win32",
|
|
cwd: root,
|
|
});
|
|
if (fd !== undefined) closeSync(fd);
|
|
const lineBytes: number[] = [];
|
|
const frames: RpcFrame[] = [];
|
|
const input = createInterface({ input: child.stdout! });
|
|
input.on("line", line => {
|
|
lineBytes.push(Buffer.byteLength(line));
|
|
frames.push(JSON.parse(line) as RpcFrame);
|
|
});
|
|
child.stderr!.resume();
|
|
let exited = false;
|
|
const exit = new Promise<void>(done => child.once("exit", () => { exited = true; done(); }));
|
|
const send = (message: unknown) => child.stdin!.write(`${JSON.stringify(message)}\n`);
|
|
const response = async (id: number) => {
|
|
await expect.poll(() => frames.find(frame => frame.id === id), { timeout: 10_000 }).toBeDefined();
|
|
const frame = frames.find(entry => entry.id === id)!;
|
|
expect(frame.error).toBeUndefined();
|
|
return frame.result as Record<string, unknown>;
|
|
};
|
|
const stop = async () => {
|
|
child.stdin!.end();
|
|
await Promise.race([exit, new Promise(done => setTimeout(done, 5_000))]);
|
|
if (!exited && child.pid) process.kill(process.platform === "win32" ? child.pid : -child.pid, "SIGKILL");
|
|
await exit;
|
|
input.close();
|
|
};
|
|
return { send, response, stop, lineBytes };
|
|
}
|
|
|
|
it("resumes a session whose OpenCode message history exceeds runnerd's frame limit", async () => {
|
|
const root = await mkdtemp(join(tmpdir(), "opencode-proxy-thread-read-"));
|
|
const executable = join(root, "fixture-launch");
|
|
const fixture = resolve("test/fixtures/fake-opencode-server.mjs");
|
|
execFileSync("cc", ["-x", "c", "-o", executable, "-"], { input: `#include <unistd.h>\n#include <stdlib.h>\nint main(int argc, char **argv) { char **args = calloc(argc + 2, sizeof(char *)); args[0] = ${JSON.stringify(process.execPath)}; args[1] = ${JSON.stringify(fixture)}; for (int i = 1; i < argc; i++) args[i + 1] = argv[i]; execv(args[0], args); return 127; }` });
|
|
if (process.platform === "darwin") {
|
|
execFileSync("codesign", ["--force", "--sign", "-", executable]);
|
|
execFileSync("codesign", ["--verify", "--strict", executable]);
|
|
}
|
|
await chmod(executable, 0o500);
|
|
const proxy = join(root, "proxy.cjs");
|
|
await writeFile(proxy, execFileSync(process.execPath, ["--input-type=module", "-e", `import { bundleVerifiedProviderEntrypoints } from "./scripts/build-verified-provider-entrypoints.mjs"; const entries = await bundleVerifiedProviderEntrypoints({ write: false }); process.stdout.write(entries.find(({ entrypoint }) => entrypoint.name === "opencode-app-server-proxy").verifiedResult.outputFiles[0].contents);`], { maxBuffer: 16 * 1024 * 1024 }));
|
|
const runtime = join(root, "runtime");
|
|
const workspace = join(root, "workspace");
|
|
await mkdir(workspace);
|
|
try {
|
|
const first = await startProxy(root, proxy, executable, runtime);
|
|
let threadId: string;
|
|
try {
|
|
first.send({ id: 1, method: "initialize", params: {} });
|
|
await first.response(1);
|
|
first.send({ id: 2, method: "thread/start", params: { cwd: workspace, model: MODEL } });
|
|
threadId = ((await first.response(2)).thread as { id: string }).id;
|
|
} finally {
|
|
await first.stop();
|
|
}
|
|
|
|
// The persisted OpenCode session has accumulated more retained message
|
|
// content than one runnerd stdout frame may carry.
|
|
const sessions = (await readdir(runtime, { withFileTypes: true })).filter(entry => entry.isDirectory());
|
|
expect(sessions).toHaveLength(1);
|
|
await writeFile(join(runtime, sessions[0]!.name, "data", "fake-message-history-bytes"), String(RUNNERD_MAX_FRAME_BYTES + 1024 * 1024));
|
|
|
|
// Mirror runnerd's restore sequence: thread/resume, then thread/read to
|
|
// discover whether a provider turn is still active.
|
|
const resumed = await startProxy(root, proxy, executable, runtime);
|
|
try {
|
|
resumed.send({ id: 1, method: "initialize", params: {} });
|
|
await resumed.response(1);
|
|
resumed.send({ id: 2, method: "thread/resume", params: { threadId, cwd: workspace, model: MODEL } });
|
|
expect(((await resumed.response(2)).thread as { id: string }).id).toBe(threadId);
|
|
resumed.send({ id: 3, method: "thread/read", params: { threadId, includeTurns: true } });
|
|
const read = await resumed.response(3);
|
|
expect(read.thread).toMatchObject({ id: threadId, turns: [] });
|
|
expect(Math.max(...resumed.lineBytes)).toBeLessThan(RUNNERD_MAX_FRAME_BYTES);
|
|
} finally {
|
|
await resumed.stop();
|
|
}
|
|
} finally {
|
|
await rm(root, { recursive: true, force: true });
|
|
}
|
|
}, 60_000);
|