mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 08:22:20 +02:00
<!-- Write all pull request text in Simplified Technical English (ASD-STE100). --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task descriptions, comments, continuation data, skills, and execution rules enter several agent adapters. > - The same source can be rendered by more than one automatic input carrier. > - Failed resumes can also rebuild input from stale or compact context. > - This pull request gives each Paperclip-owned source one delivery owner and preserves the required transport boundaries. > - It adds deterministic adapter, interaction, runner, and browser tests for these boundaries. > - The benefit is more predictable context delivery with explicit evidence for later live qualification. ## Linked Issues or Issue Description Related: #13144 removes a duplicate environment payload and bounds wake lists. Related: #11360 addresses Hermes resume behavior. This pull request preserves compatible active-session formats while repairing context ownership and stale question creation. **What happened?** Task descriptions and comments could enter more than one automatic context block. Native transports could wrap a complete model input in a second task envelope. Some legacy and gateway adapters could omit the owned assignment on ordinary tasks or rebuild a failed resume with stale compact context. A continuation could also request a question after newer human comments had arrived. **Expected behavior** Each task or comment source has one automatic model-facing owner. Distinct comment IDs and repeated wording remain distinct. Fresh fallback attempts rebuild the required full context. A question request is rejected when newer queued human direction makes it stale. Harness access policy remains owned by execution configuration. **Steps to reproduce** 1. Build a task with a description and current comments. 2. Capture the actual adapter or runner input. 3. Compare source ownership and task-envelope nesting. 4. Queue a human comment before a continuation requests a question. 5. Trigger a failed resume and inspect the fresh retry input. 6. Run the focused adapter, interaction, runner, and browser checks. ## What Changed - Add shared prompt-section selection at the provider-attempt boundary. - Deliver owned assignment context through native, legacy CLI, ACP, gateway, cloud, Pi, Kimi, Grok, Gemini, OpenCode, Cursor, OpenClaw, and Hermes paths. - Rebuild full or compact context after resume recovery changes the attempt. Add native and Claude ACP tests of actual recovery requests. - Preserve custom templates, loaded instruction files, execution policies, and older active-session formats. - Record continuation source metadata and reject stale question creation under the issue-row lock. - Add explicit Product E2E context-integrity profiles, prerequisite gates, credential-isolation checks, and report fixtures. - Bypass service-worker forwarding for same-origin Vite development modules. A real Chromium test fails with resource exhaustion before the repair and passes after it. Production asset caching keeps its existing policy. - Add browser diagnostics and service-worker module-loading regressions. - Add an explicit zero-retry eval option. The default retry behavior remains unchanged. Each campaign records its effective policy. - Remove the model-facing working-directory sentence from four prompt builders. Existing workspace, sandbox, permission, and custom-template configuration remains unchanged. - Align the everyday workflow assertion with the current 47-entry catalog. Compared with current upstream master, the branch carries the context-ownership implementation and its tests, the explicit context-integrity catalog and evidence harness, and the focused browser regression checks. ## Verification **Merge assessment:** focused regression evidence supports merge. This is not full completion of the original broad qualification matrix. The maintainer has authorized merge after fresh verification of the master integration. - Current head: `bbd52f82114eabf09bc7b1a7e97d54a5b43bbc00`. This integrates current master `2f585ef26a1814fa209715242d1ca791b63e4c4e`. All 14 conflicts are resolved. Cancellation checks, workspace finalization, native Grok support, and both sets of tests are retained. - Current-head Greptile: **5/5**, with no blocking findings. The review names this exact commit. All **59 reported checks are terminal: 55 successful, 4 skipped, zero pending or failing**. This includes the full root general and serialized suites, separate runner checks, typecheck, build, canary, browser E2E, Docker, and security checks. The successful legacy security status is included in that total. - After integration: workspace typecheck and full build passed. Separate runner checks passed: **2,160 TypeScript tests (10 skipped), 582 Rust tests, and 39 preparation checks**. Other passing checks include 621 Product E2E harness units, 376 focused shared/adapter tests, 160 real-database/API tests, 86 Hermes tests, 18 browser-support checks, and Product E2E typechecking. The complete root suite passed in CI. The duplicate local monolithic root run was stopped after that CI result; it is not counted as a completed local pass. - New native recovery coverage retains full assignment, completion contract, and explicit skill selection after safe replacement, for old and prepared input formats. Full native session test file: **136/136 passed**. - New Claude ACP coverage captures actual fresh, resumed, and missing-session fallback requests. It verifies one assignment copy, comment order, identical text under distinct comment IDs, and full fallback context. Full file: **33/33 passed**. Both affected TypeScript checks passed. - Existing deterministic tests cover source revisions, approval and trust boundaries, completion validation, custom templates, compatible sessions, standalone driver wrapping, and maintained adapter transport requests. - Provider-free browser support: **17/17 passed** after the master merge. Service-worker unit tests: **33/33 passed**. The module-overload regression failed before the repair and passed after it in real Chromium. ### Fresh live comparisons The new batch ran exactly four Product E2E attempts. **All four passed on the first attempt; no retries.** Each has six terminal matchers plus the existing browser lifecycle and invariant checks. | Exact case ID | Control | Candidate | |---|---|---| | `core-compatibility.runner-codex.local.plan-revise-accept` | Passed | Passed | | `local-session-integrity.runner-acpx-claude.local.structured-question-restart-resume` | Passed | Passed | The plan case checks a revised canonical plan and revision-bound approval before completion. The question case restarts the server before submitting the answer, then verifies the continuation completes. Control source is `dfa4e1bda8d50a1a01746603251a9128dbe9d0d6`. Candidate source is `79fcdb5dece501d28064ea9da306603881b46f0c`. They use identical frozen definitions and provider versions: Codex `0.156.0` with `gpt-5.6-sol`; ACPX `0.13.1` / Claude ACP `0.73.0` with `claude-sonnet-5`. The September 24 head added master browser recovery and test-only changes. The September 28 head also integrates newer master changes, including cancellation, workspace finalization, and native Grok. These are frozen-source live results, not exact-head live runs. The candidate received one description copy where the control initially received three. The submitted initial plan envelopes were 7,969 versus 19,097 characters. Question envelopes were 7,592 versus 18,919. These are structural measurements, not whole-provider token or dollar savings. ### Earlier evidence and failed attempts - The preceding fresh batch has four effective passing pairs: OpenCode comment continuation and assigned skill, native Codex comment continuation, and native Claude comment continuation. It retains **11 attempts: eight passed and three failed**. - Original failures remain recorded: missing local PostgreSQL library links before task creation; host-sleep cleanup after task/page checks passed; and a Claude **control** session-open rejection before a model turn. Setup was repaired identically on both worktrees. The permitted unchanged infrastructure retries passed. The underlying Claude provider startup error was not retained and remains unknown. - Older R2 retains **17 passes and one failure** across 18 attempts, including eight both-pass native/legacy Codex/Claude pairs. Its OpenCode blank-page failure led to the service-worker repair. R2 is historical evidence: master changed the native fixed prompt and removed duplicate wake environment data afterward. - The September 24 CI run initially failed one unrelated preview readiness test (`ECONNREFUSED` on its local fixture). Its test and production code match master. Isolated local verification passed **28 tests, 3 skipped**. One unchanged CI retry passed the full shard: **831 passed, 1 skipped**, including all **31 preview-exposure tests**. The aggregate CI gate passed afterward. The precise startup cause remains unknown; a port race is a hypothesis, not a proved cause. ### Limits The original wider profile/workflow matrix, repeated trials, and remote Daytona qualification are incomplete. These results support a focused merge recommendation, not statistical equivalence or universal harness qualification. Some usage receipts are missing in both variants, so no token or dollar savings are claimed. The $500 ceiling was preserved using conservative allowances; failed attempts and unknown charges remain in the ledger. Reproduce the focused additions with `pnpm exec vitest run packages/adapters/claude-local/src/server/acp.test.ts` and `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/native-session-runtime.test.ts`. Full checks use `pnpm -r typecheck`, `pnpm test:run`, `pnpm build`, and the separate runner checks. Paid evals require the frozen definitions, profiles, and credentials; do not use `--all` as a substitute for the selected cases. ## Risks - Context placement changes can affect model behavior. Deterministic checks cover the selected paths, but live qualification remains incomplete. - The stale-question guard can reject a request when queued human comments arrived during the run. This is intended. - New stored inputs and model envelopes retain compatibility readers for older active sessions. - Custom templates may intentionally repeat content. - Removing a model-facing working-directory sentence does not change filesystem, command, sandbox, or permission configuration. - The worker bypass applies only to same-origin development module paths. Cache-policy tests preserve private-response handling and production asset caching. Mounted HTTP fixture changes remain test-only. - This PR does not claim measured token savings or statistical equivalence across every harness. ## Model Used OpenAI Codex, exact model gpt-6-astra, with repository tools and code execution. Bounded supporting work used gpt-5.6-luna and gpt-6-luna. The serving context-window size is not exposed in this task. ## 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 described the issue in-PR using the required issue fields - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket id - [x] I have run the focused local checks and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect these changes - [x] I have considered and documented risks above - [x] All current-head Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups for the current head - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
650 lines
22 KiB
TypeScript
650 lines
22 KiB
TypeScript
import fs from "node:fs/promises";
|
|
import path from "node:path";
|
|
import {
|
|
Agent,
|
|
type AgentOptions,
|
|
type ModelSelection,
|
|
type Run,
|
|
type RunResult,
|
|
type SDKAgent,
|
|
type SDKMessage,
|
|
} from "@cursor/sdk";
|
|
import type { AdapterExecutionContext, AdapterExecutionResult, AdapterInvocationMeta } from "@paperclipai/adapter-utils";
|
|
import {
|
|
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
|
|
DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE,
|
|
asBoolean,
|
|
asString,
|
|
buildPaperclipEnv,
|
|
buildRuntimeToolsEnv,
|
|
joinPromptSections,
|
|
parseObject,
|
|
readPaperclipIssueWorkModeFromContext,
|
|
selectPaperclipPromptSections,
|
|
selectInitialCommunicationGuidance,
|
|
isPaperclipRecoveryWakePayload,
|
|
renderTemplate,
|
|
} from "@paperclipai/adapter-utils/server-utils";
|
|
|
|
type CursorCloudSession = {
|
|
cursorAgentId: string;
|
|
latestRunId?: string;
|
|
runtime: "cloud";
|
|
envType?: "cloud" | "pool" | "machine";
|
|
envName?: string;
|
|
repos: Array<{ url: string; startingRef?: string; prUrl?: string }>;
|
|
};
|
|
|
|
type CursorCloudEvent =
|
|
| { type: "cursor_cloud.init"; sessionId: string; agentId: string; runId?: string; model?: string }
|
|
| { type: "cursor_cloud.status"; status: string; message?: string }
|
|
| { type: "cursor_cloud.message"; message: SDKMessage }
|
|
| {
|
|
type: "cursor_cloud.result";
|
|
status: string;
|
|
result?: string;
|
|
model?: string;
|
|
durationMs?: number;
|
|
git?: unknown;
|
|
error?: string;
|
|
};
|
|
|
|
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
function asStringEnvMap(value: unknown): Record<string, string> {
|
|
const parsed = parseObject(value);
|
|
const env: Record<string, string> = {};
|
|
for (const [key, entry] of Object.entries(parsed)) {
|
|
if (typeof entry === "string") {
|
|
env[key] = entry;
|
|
} else if (typeof entry === "object" && entry !== null && !Array.isArray(entry)) {
|
|
const rec = entry as Record<string, unknown>;
|
|
if (rec.type === "plain" && typeof rec.value === "string") env[key] = rec.value;
|
|
}
|
|
}
|
|
return env;
|
|
}
|
|
|
|
function normalizeEnvType(raw: string): "cloud" | "pool" | "machine" {
|
|
const value = raw.trim().toLowerCase();
|
|
if (value === "pool" || value === "machine") return value;
|
|
return "cloud";
|
|
}
|
|
|
|
function trimNullable(value: unknown): string | null {
|
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
}
|
|
|
|
function firstNonEmptyLine(text: string): string {
|
|
return (
|
|
text
|
|
.split(/\r?\n/)
|
|
.map((line) => line.trim())
|
|
.find(Boolean) ?? ""
|
|
);
|
|
}
|
|
|
|
function toModelSelection(rawModel: string): ModelSelection | undefined {
|
|
const model = rawModel.trim();
|
|
return model ? { id: model } : undefined;
|
|
}
|
|
|
|
function toSummary(result: RunResult): string | null {
|
|
const direct = trimNullable(result.result);
|
|
if (direct) return firstNonEmptyLine(direct);
|
|
return null;
|
|
}
|
|
|
|
function formatRunError(err: unknown): string {
|
|
if (err instanceof Error && err.message.trim().length > 0) return err.message.trim();
|
|
return String(err);
|
|
}
|
|
|
|
function buildWakeEnv(ctx: AdapterExecutionContext, configEnv: Record<string, string>): Record<string, string> {
|
|
const { runId, agent, context, authToken } = ctx;
|
|
const env: Record<string, string> = {
|
|
...configEnv,
|
|
...buildPaperclipEnv(agent),
|
|
...buildRuntimeToolsEnv(ctx.runtimeTools),
|
|
PAPERCLIP_RUN_ID: runId,
|
|
};
|
|
// PAPERCLIP_API_KEY is never accepted from config — the harness-minted run
|
|
// token is the only source of Paperclip API identity.
|
|
delete env.PAPERCLIP_API_KEY;
|
|
// Wake context travels in the prompt; a configured copy can exceed spawn limits.
|
|
delete env.PAPERCLIP_WAKE_PAYLOAD_JSON;
|
|
|
|
const wakeTaskId = trimNullable(context.taskId) ?? trimNullable(context.issueId);
|
|
const wakeReason = trimNullable(context.wakeReason);
|
|
const wakeCommentId = trimNullable(context.wakeCommentId) ?? trimNullable(context.commentId);
|
|
const approvalId = trimNullable(context.approvalId);
|
|
const approvalStatus = trimNullable(context.approvalStatus);
|
|
const linkedIssueIds = Array.isArray(context.issueIds)
|
|
? context.issueIds.filter((value): value is string => typeof value === "string" && value.trim().length > 0)
|
|
: [];
|
|
const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
|
|
|
|
if (wakeTaskId) env.PAPERCLIP_TASK_ID = wakeTaskId;
|
|
if (wakeReason) env.PAPERCLIP_WAKE_REASON = wakeReason;
|
|
if (wakeCommentId) env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
|
|
if (approvalId) env.PAPERCLIP_APPROVAL_ID = approvalId;
|
|
if (approvalStatus) env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
|
|
if (linkedIssueIds.length > 0) env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
|
|
if (issueWorkMode) env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
|
|
if (authToken) {
|
|
env.PAPERCLIP_API_KEY = authToken;
|
|
}
|
|
|
|
// cursor_cloud runs remotely in Cursor's cloud and is intentionally not
|
|
// issued a Paperclip run JWT (registry: supportsLocalAgentJwt=false).
|
|
// buildPaperclipEnv always sets PAPERCLIP_API_URL, defaulting to the local
|
|
// runtime host — which a remote worker can neither reach nor authenticate
|
|
// against, so any agent-initiated Paperclip API call would fail with a 401
|
|
// (or be unreachable) and add noise. When there is no usable key, drop the
|
|
// callback wiring so cloud-side Paperclip tools degrade to a clean no-op.
|
|
// Run results are delivered server-side via the Cursor Agent SDK (getRun /
|
|
// wait), not through this callback, so nothing is lost.
|
|
if (!trimNullable(env.PAPERCLIP_API_KEY)) {
|
|
delete env.PAPERCLIP_API_URL;
|
|
delete env.PAPERCLIP_API_BRIDGE_MODE;
|
|
}
|
|
|
|
const workspace = parseObject(context.paperclipWorkspace);
|
|
const workspaceMappings: Array<[string, unknown]> = [
|
|
["PAPERCLIP_WORKSPACE_CWD", workspace.cwd],
|
|
["PAPERCLIP_WORKSPACE_SOURCE", workspace.source],
|
|
["PAPERCLIP_WORKSPACE_ID", workspace.workspaceId],
|
|
["PAPERCLIP_WORKSPACE_REPO_URL", workspace.repoUrl],
|
|
["PAPERCLIP_WORKSPACE_REPO_REF", workspace.repoRef],
|
|
["PAPERCLIP_WORKSPACE_BRANCH", workspace.branch],
|
|
["PAPERCLIP_WORKSPACE_WORKTREE_PATH", workspace.worktreePath],
|
|
["AGENT_HOME", workspace.agentHome],
|
|
];
|
|
for (const [key, value] of workspaceMappings) {
|
|
const normalized = trimNullable(value);
|
|
if (normalized) env[key] = normalized;
|
|
}
|
|
|
|
delete env.CURSOR_API_KEY;
|
|
// Cursor rejects the entire request when any envVars value is empty.
|
|
// Paperclip may use empty values to unset optional host credentials; remote
|
|
// workers do not inherit those host variables, so omit the empty entries.
|
|
return Object.fromEntries(Object.entries(env).filter(([, value]) => value.length > 0));
|
|
}
|
|
|
|
async function buildInstructionsPrefix(
|
|
config: Record<string, unknown>,
|
|
onLog: AdapterExecutionContext["onLog"],
|
|
): Promise<{ prefix: string; notes: string[]; chars: number }> {
|
|
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
|
if (!instructionsFilePath) {
|
|
return { prefix: "", notes: [], chars: 0 };
|
|
}
|
|
|
|
try {
|
|
const contents = await fs.readFile(instructionsFilePath, "utf8");
|
|
const instructionsDir = `${path.dirname(instructionsFilePath)}/`;
|
|
const prefix = `${contents.trim()}\n\nThe above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsDir}.\n`;
|
|
return {
|
|
prefix,
|
|
chars: prefix.length,
|
|
notes: [
|
|
`Loaded agent instructions from ${instructionsFilePath}`,
|
|
`Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).`,
|
|
],
|
|
};
|
|
} catch (err) {
|
|
const reason = err instanceof Error ? err.message : String(err);
|
|
await onLog(
|
|
"stderr",
|
|
`[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`,
|
|
);
|
|
return {
|
|
prefix: "",
|
|
chars: 0,
|
|
notes: [
|
|
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
|
|
],
|
|
};
|
|
}
|
|
}
|
|
|
|
function renderPaperclipEnvNote(env: Record<string, string>): string {
|
|
const keys = Object.keys(env)
|
|
.filter((key) => key.startsWith("PAPERCLIP_"))
|
|
.sort();
|
|
if (keys.length === 0) return "";
|
|
return [
|
|
"Paperclip runtime note:",
|
|
`The following PAPERCLIP_* environment variables are available in the cloud agent shell: ${keys.join(", ")}`,
|
|
"Use them directly instead of assuming they are absent.",
|
|
].join("\n");
|
|
}
|
|
|
|
function readSession(params: Record<string, unknown> | null): CursorCloudSession | null {
|
|
if (!params) return null;
|
|
const record = asRecord(params);
|
|
if (!record) return null;
|
|
const cursorAgentId =
|
|
trimNullable(record.cursorAgentId) ??
|
|
trimNullable(record.agentId) ??
|
|
trimNullable(record.sessionId);
|
|
if (!cursorAgentId) return null;
|
|
const latestRunId = trimNullable(record.latestRunId) ?? trimNullable(record.runId) ?? undefined;
|
|
const envType = trimNullable(record.envType);
|
|
const envName = trimNullable(record.envName);
|
|
const reposValue = Array.isArray(record.repos) ? record.repos : [];
|
|
const repos = reposValue
|
|
.map((entry) => asRecord(entry))
|
|
.filter((entry): entry is Record<string, unknown> => Boolean(entry))
|
|
.map((entry) => ({
|
|
url: asString(entry.url, "").trim(),
|
|
startingRef: trimNullable(entry.startingRef) ?? undefined,
|
|
prUrl: trimNullable(entry.prUrl) ?? undefined,
|
|
}))
|
|
.filter((entry) => entry.url.length > 0);
|
|
return {
|
|
cursorAgentId,
|
|
...(latestRunId ? { latestRunId } : {}),
|
|
runtime: "cloud",
|
|
...(envType ? { envType: normalizeEnvType(envType) } : {}),
|
|
...(envName ? { envName } : {}),
|
|
repos,
|
|
};
|
|
}
|
|
|
|
function sessionMatches(
|
|
session: CursorCloudSession | null,
|
|
envType: "cloud" | "pool" | "machine",
|
|
envName: string | null,
|
|
repos: Array<{ url: string; startingRef?: string; prUrl?: string }>,
|
|
): boolean {
|
|
if (!session) return false;
|
|
if ((session.envType ?? "cloud") !== envType) return false;
|
|
if ((session.envName ?? null) !== envName) return false;
|
|
if (session.repos.length !== repos.length) return false;
|
|
return session.repos.every((repo, index) => {
|
|
const next = repos[index];
|
|
return repo.url === next.url
|
|
&& (repo.startingRef ?? null) === (next.startingRef ?? null)
|
|
&& (repo.prUrl ?? null) === (next.prUrl ?? null);
|
|
});
|
|
}
|
|
|
|
function buildAgentOptions(input: {
|
|
apiKey: string;
|
|
name: string;
|
|
model?: ModelSelection;
|
|
envType: "cloud" | "pool" | "machine";
|
|
envName: string | null;
|
|
repos: Array<{ url: string; startingRef?: string; prUrl?: string }>;
|
|
workOnCurrentBranch: boolean;
|
|
autoCreatePR: boolean;
|
|
skipReviewerRequest: boolean;
|
|
envVars: Record<string, string>;
|
|
}): AgentOptions {
|
|
return {
|
|
apiKey: input.apiKey,
|
|
name: input.name,
|
|
...(input.model ? { model: input.model } : {}),
|
|
cloud: {
|
|
env: {
|
|
type: input.envType,
|
|
...(input.envName ? { name: input.envName } : {}),
|
|
},
|
|
repos: input.repos,
|
|
workOnCurrentBranch: input.workOnCurrentBranch,
|
|
autoCreatePR: input.autoCreatePR,
|
|
skipReviewerRequest: input.skipReviewerRequest,
|
|
envVars: input.envVars,
|
|
},
|
|
};
|
|
}
|
|
|
|
function eventLine(event: CursorCloudEvent): string {
|
|
return `${JSON.stringify(event)}\n`;
|
|
}
|
|
|
|
async function emitMessage(onLog: AdapterExecutionContext["onLog"], message: SDKMessage) {
|
|
await onLog("stdout", eventLine({ type: "cursor_cloud.message", message }));
|
|
}
|
|
|
|
async function emitStatus(onLog: AdapterExecutionContext["onLog"], status: string, message?: string) {
|
|
await onLog("stdout", eventLine({ type: "cursor_cloud.status", status, ...(message ? { message } : {}) }));
|
|
}
|
|
|
|
async function streamRun(run: Run, onLog: AdapterExecutionContext["onLog"]) {
|
|
if (!run.supports("stream")) return;
|
|
for await (const message of run.stream()) {
|
|
await emitMessage(onLog, message);
|
|
}
|
|
}
|
|
|
|
async function getAttachedRun(input: {
|
|
apiKey: string;
|
|
session: CursorCloudSession | null;
|
|
}): Promise<Run | null> {
|
|
const latestRunId = input.session?.latestRunId;
|
|
const cursorAgentId = input.session?.cursorAgentId;
|
|
if (!latestRunId || !cursorAgentId) return null;
|
|
try {
|
|
const run = await Agent.getRun(latestRunId, {
|
|
runtime: "cloud",
|
|
agentId: cursorAgentId,
|
|
apiKey: input.apiKey,
|
|
});
|
|
return run.status === "running" ? run : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult> {
|
|
const { runId, agent, runtime, config, context, onLog, onMeta, onDispatch } = ctx;
|
|
const envConfig = asStringEnvMap(config.env);
|
|
const apiKey = asString(envConfig.CURSOR_API_KEY, "").trim();
|
|
if (!apiKey) {
|
|
return {
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: "CURSOR_API_KEY is required for cursor_cloud.",
|
|
provider: "cursor",
|
|
biller: "cursor",
|
|
billingType: "api",
|
|
clearSession: false,
|
|
};
|
|
}
|
|
|
|
const workspace = parseObject(context.paperclipWorkspace);
|
|
const repoUrl =
|
|
asString(config.repoUrl, "").trim() ||
|
|
asString(workspace.repoUrl, "").trim();
|
|
if (!repoUrl) {
|
|
return {
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: "cursor_cloud requires repoUrl in adapterConfig or workspace context.",
|
|
provider: "cursor",
|
|
biller: "cursor",
|
|
billingType: "api",
|
|
clearSession: false,
|
|
};
|
|
}
|
|
|
|
const repoStartingRef =
|
|
trimNullable(config.repoStartingRef) ??
|
|
trimNullable(workspace.repoRef) ??
|
|
undefined;
|
|
const repoPullRequestUrl = trimNullable(config.repoPullRequestUrl) ?? undefined;
|
|
const envType = normalizeEnvType(asString(config.runtimeEnvType, "cloud"));
|
|
const envName = trimNullable(config.runtimeEnvName);
|
|
const workOnCurrentBranch = asBoolean(config.workOnCurrentBranch, false);
|
|
const autoCreatePR = asBoolean(config.autoCreatePR, false);
|
|
const skipReviewerRequest = asBoolean(config.skipReviewerRequest, false);
|
|
const model = toModelSelection(asString(config.model, ""));
|
|
const repos = [{
|
|
url: repoUrl,
|
|
...(repoStartingRef ? { startingRef: repoStartingRef } : {}),
|
|
...(repoPullRequestUrl ? { prUrl: repoPullRequestUrl } : {}),
|
|
}];
|
|
const remoteEnv = buildWakeEnv(ctx, envConfig);
|
|
const session = readSession(runtime.sessionParams) ?? (runtime.sessionId
|
|
? {
|
|
cursorAgentId: runtime.sessionId,
|
|
runtime: "cloud" as const,
|
|
repos,
|
|
}
|
|
: null);
|
|
const canReuseSession = sessionMatches(session, envType, envName, repos);
|
|
const promptTemplate = asString(config.promptTemplate, context.conversationMode === true
|
|
? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
|
|
: DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE);
|
|
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
|
const templateData = {
|
|
agentId: agent.id,
|
|
companyId: agent.companyId,
|
|
runId,
|
|
company: { id: agent.companyId },
|
|
agent,
|
|
run: { id: runId, source: "on_demand" },
|
|
context,
|
|
};
|
|
const instructions = await buildInstructionsPrefix(config, onLog);
|
|
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
|
|
resumedSession: canReuseSession,
|
|
includeCommunicationGuidance: false,
|
|
});
|
|
const renderedBootstrapPrompt =
|
|
!canReuseSession && bootstrapPromptTemplate.trim().length > 0
|
|
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
|
: "";
|
|
const renderedPrompt =
|
|
(canReuseSession && wakePrompt.length > 0) || isPaperclipRecoveryWakePayload(context.paperclipWake)
|
|
? ""
|
|
: renderTemplate(promptTemplate, templateData).trim();
|
|
const paperclipEnvNote = renderPaperclipEnvNote(remoteEnv);
|
|
const prompt = joinPromptSections([
|
|
selectInitialCommunicationGuidance(context, { resumedSession: canReuseSession }),
|
|
instructions.prefix,
|
|
renderedBootstrapPrompt,
|
|
wakePrompt,
|
|
taskContextNote,
|
|
paperclipEnvNote,
|
|
renderedPrompt,
|
|
]);
|
|
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
|
const finalPrompt = joinPromptSections([prompt, sessionHandoffNote]);
|
|
const promptMetrics = {
|
|
promptChars: finalPrompt.length,
|
|
instructionsChars: instructions.chars,
|
|
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
|
wakePromptChars: wakePrompt.length,
|
|
taskContextChars: taskContextNote.length,
|
|
heartbeatPromptChars: renderedPrompt.length,
|
|
};
|
|
|
|
const agentOptions = buildAgentOptions({
|
|
apiKey,
|
|
name: `Paperclip ${agent.name}`,
|
|
model,
|
|
envType,
|
|
envName,
|
|
repos,
|
|
workOnCurrentBranch,
|
|
autoCreatePR,
|
|
skipReviewerRequest,
|
|
envVars: remoteEnv,
|
|
});
|
|
|
|
const commandNotes = [
|
|
...instructions.notes,
|
|
canReuseSession
|
|
? `Reusing Cursor cloud agent session ${session?.cursorAgentId ?? "unknown"}`
|
|
: "Creating a new Cursor cloud agent session",
|
|
`Repository: ${repoUrl}${repoStartingRef ? ` @ ${repoStartingRef}` : ""}`,
|
|
`Runtime target: ${envType}${envName ? ` (${envName})` : ""}`,
|
|
];
|
|
|
|
if (onMeta) {
|
|
const meta: AdapterInvocationMeta = {
|
|
adapterType: "cursor_cloud",
|
|
command: "@cursor/sdk",
|
|
commandNotes,
|
|
prompt: finalPrompt,
|
|
promptMetrics,
|
|
context: {
|
|
cursorCloud: {
|
|
envType,
|
|
envName,
|
|
repoUrl,
|
|
repoStartingRef,
|
|
repoPullRequestUrl,
|
|
canReuseSession,
|
|
},
|
|
},
|
|
};
|
|
await onMeta(meta);
|
|
}
|
|
|
|
let sdkAgent: SDKAgent | null = null;
|
|
let run: Run | null = null;
|
|
let streamError: string | null = null;
|
|
try {
|
|
// This adapter has no local child process, so crossing into the first SDK
|
|
// request is its dispatch boundary. Report it before any potentially
|
|
// long-running remote reattach/create/send operation.
|
|
onDispatch?.();
|
|
const attachedRun = canReuseSession
|
|
? await getAttachedRun({ apiKey, session })
|
|
: null;
|
|
|
|
if (attachedRun) {
|
|
await emitStatus(onLog, "running", `Reattached to existing Cursor run ${attachedRun.id}.`);
|
|
await onLog("stdout", eventLine({
|
|
type: "cursor_cloud.init",
|
|
sessionId: attachedRun.agentId,
|
|
agentId: attachedRun.agentId,
|
|
runId: attachedRun.id,
|
|
...(model?.id ? { model: model.id } : {}),
|
|
}));
|
|
const priorStreamPromise = streamRun(attachedRun, onLog).catch((err) => {
|
|
streamError = formatRunError(err);
|
|
});
|
|
if (attachedRun.supports("wait")) await attachedRun.wait();
|
|
await priorStreamPromise;
|
|
streamError = null;
|
|
await emitStatus(
|
|
onLog,
|
|
"running",
|
|
`Prior Cursor run ${attachedRun.id} finished; sending heartbeat follow-up so this wake's context is not dropped.`,
|
|
);
|
|
}
|
|
|
|
sdkAgent = canReuseSession && session
|
|
? await Agent.resume(session.cursorAgentId, agentOptions)
|
|
: await Agent.create(agentOptions);
|
|
run = await sdkAgent.send(finalPrompt, {
|
|
...(model ? { model } : {}),
|
|
});
|
|
await onLog("stdout", eventLine({
|
|
type: "cursor_cloud.init",
|
|
sessionId: sdkAgent.agentId,
|
|
agentId: sdkAgent.agentId,
|
|
runId: run.id,
|
|
...(model?.id ? { model: model.id } : {}),
|
|
}));
|
|
await emitStatus(onLog, "running", `Started Cursor run ${run.id}.`);
|
|
|
|
const streamPromise = streamRun(run, onLog).catch((err) => {
|
|
streamError = formatRunError(err);
|
|
});
|
|
const result = run.supports("wait")
|
|
? await run.wait()
|
|
: {
|
|
id: run.id,
|
|
status: run.status === "running" ? "error" : run.status,
|
|
result: run.result,
|
|
model: run.model,
|
|
durationMs: run.durationMs,
|
|
git: run.git,
|
|
};
|
|
await streamPromise;
|
|
|
|
const modelId = result.model?.id ?? model?.id ?? null;
|
|
await onLog("stdout", eventLine({
|
|
type: "cursor_cloud.result",
|
|
status: result.status,
|
|
...(result.result ? { result: result.result } : {}),
|
|
...(modelId ? { model: modelId } : {}),
|
|
...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
|
|
...(result.git ? { git: result.git } : {}),
|
|
...(streamError ? { error: streamError } : {}),
|
|
}));
|
|
|
|
const nextSession: CursorCloudSession = {
|
|
cursorAgentId: run.agentId,
|
|
latestRunId: result.id,
|
|
runtime: "cloud",
|
|
envType,
|
|
...(envName ? { envName } : {}),
|
|
repos,
|
|
};
|
|
const isError = result.status !== "finished";
|
|
return {
|
|
exitCode: isError ? 1 : 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: isError ? (trimNullable(result.result) ?? streamError ?? `Cursor run ${result.status}`) : null,
|
|
sessionId: run.agentId,
|
|
sessionDisplayId: run.agentId,
|
|
sessionParams: nextSession,
|
|
provider: "cursor",
|
|
biller: "cursor",
|
|
billingType: "api",
|
|
model: modelId,
|
|
costUsd: null,
|
|
summary: toSummary(result),
|
|
resultJson: {
|
|
status: result.status,
|
|
cursorAgentId: run.agentId,
|
|
cursorRunId: result.id,
|
|
envType,
|
|
envName,
|
|
repos,
|
|
...(result.result ? { result: result.result } : {}),
|
|
...(result.git ? { git: result.git } : {}),
|
|
...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
|
|
...(streamError ? { streamError } : {}),
|
|
},
|
|
clearSession: false,
|
|
};
|
|
} catch (err) {
|
|
const error = formatRunError(err);
|
|
const reason = !model && error.includes("[invalid_model]")
|
|
? `${error} Cursor rejected its configured default model. Choose an available default at https://cursor.com/dashboard/cloud-agents or set this agent's model explicitly.`
|
|
: error.includes("Failed to determine repository default branch")
|
|
? `${error} Verify that Cursor's GitHub integration can access ${repoUrl} at https://cursor.com/dashboard/cloud-agents. If the repository has no default branch, configure a starting branch for this agent.`
|
|
: error;
|
|
if (run) {
|
|
await onLog("stdout", eventLine({
|
|
type: "cursor_cloud.result",
|
|
status: "error",
|
|
error: reason,
|
|
}));
|
|
}
|
|
return {
|
|
exitCode: 1,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: reason,
|
|
sessionId: session?.cursorAgentId ?? null,
|
|
sessionDisplayId: session?.cursorAgentId ?? null,
|
|
sessionParams: session,
|
|
provider: "cursor",
|
|
biller: "cursor",
|
|
billingType: "api",
|
|
costUsd: null,
|
|
clearSession: false,
|
|
resultJson: {
|
|
status: "error",
|
|
...(run ? { cursorRunId: run.id } : {}),
|
|
...(session?.cursorAgentId ? { cursorAgentId: session.cursorAgentId } : {}),
|
|
error: reason,
|
|
},
|
|
};
|
|
} finally {
|
|
if (sdkAgent) {
|
|
try {
|
|
await sdkAgent[Symbol.asyncDispose]();
|
|
} catch {
|
|
// Best effort only.
|
|
}
|
|
}
|
|
}
|
|
}
|